text:
package org.artifactory.factory;

import com.thoughtworks.xstream.XStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.artifactory.checksum.ChecksumsInfo;
import org.artifactory.fs.*;
import org.artifactory.md.MutableMetadataInfo;
import org.artifactory.md.MutablePropertiesInfo;
import org.artifactory.md.PropertiesInfo;
import org.artifactory.repo.RepoPath;
import org.artifactory.resource.MutableRepoResourceInfo;
import org.artifactory.resource.RepoResourceInfo;
import org.artifactory.security.*;
import org.artifactory.util.Tree;

import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;

/**
 * Date: 8/1/11
 * Time: 8:46 PM
 *
 * @author Fred Simon
 */
public interface InfoFactory {
    RepoPath createRepoPathFromId(String repoPathId);

    RepoPath createRepoPath(String repoKey, String path);

    RepoPath createRepoPath(RepoPath parent, String relPath);

    MutableRepoResourceInfo copyRepoResource(RepoResourceInfo repoResourceInfo);

    MutableItemInfo copyItemInfo(ItemInfo itemInfo);

    MutableFileInfo createFileInfo(RepoPath repoPath);

    MutableFileInfo copyFileInfo(FileInfo fileInfo);

    MutableFolderInfo createFolderInfo(RepoPath repoPath);

    MutableFolderInfo copyFolderInfo(FolderInfo folderInfo);

    MutablePropertiesInfo createProperties();

    MutablePermissionTargetInfo createPermissionTarget();

    MutablePropertiesInfo copyProperties(PropertiesInfo copy);

    MutablePermissionTargetInfo copyPermissionTarget(PermissionTargetInfo copy);

    MutableUserInfo createUser();

    MutableUserInfo copyUser(UserInfo copy);

    MutableGroupInfo createGroup();

    MutableGroupInfo copyGroup(GroupInfo copy);

    MutableAclInfo createAcl();

    MutableAclInfo copyAcl(AclInfo copy);

    MutableAceInfo createAce();

    MutableAceInfo copyAce(AceInfo copy);

    UserGroupInfo createUserGroup(String groupName);

    Set<UserGroupInfo> createGroups(Set<String> names);

    UserGroupInfo createUserGroup(String groupName, String realm);

    SecurityInfo createSecurityInfo(List<UserInfo> users, List<GroupInfo> groups, List<AclInfo> acls);

    XStream getSecurityXStream();

    MutablePermissionTargetInfo createPermissionTarget(String permName, List<String> repoKeys);

    MutableAceInfo createAce(String principal, boolean group, int mask);

    MutableGroupInfo createGroup(String groupName);

    MutableUserInfo createUser(String userName);

    MutableAclInfo createAcl(PermissionTargetInfo permissionTarget);

    /**
     * Return an immutable ACL
     * @param permissionTarget
     * @param aces
     * @param updatedBy
     * @return
     */
    AclInfo createAcl(PermissionTargetInfo permissionTarget, Set<AceInfo> aces, String updatedBy);

    Tree<ZipEntryInfo> createZipEntriesTree();

    ZipEntryInfo createZipEntry(ZipEntry... zipEntry);

    ZipEntryInfo createArchiveEntry(ArchiveEntry... archiveEntries);

    ZipEntryResourceInfo createZipEntryResource(FileInfo info, ZipEntryInfo zipEntryInfo, Long first,
            ChecksumsInfo checksumsInfo);

    MutableMetadataInfo createMetadata(RepoPath repoPath);

    XStream getFileSystemXStream();

    MutableStatsInfo createStats();

    MutableStatsInfo copyStats(StatsInfo copy);

    MutableWatchersInfo createWatchers();

    MutableWatcherInfo createWatcher(String watcherUsername, long watchCreationDate);

    MetadataEntryInfo createMetadataEntry(String metadataName, String xmlContent);

    MutableWatchersInfo copyWatchers(WatchersInfo copy);

    MutableMetadataInfo createMetadata(RepoPath repoPath, String metadataName);

    RepoPath createRepoPath(String repoKey, String path, boolean folder);
}


text:
<?php

namespace FieldNation;

abstract class Result implements ResultInterface
{
    protected $message;
    protected $workOrderId;
    protected $success;

    /**
     * Set if request successful?
     *
     * @param $success
     * @return self
     */
    public function setSuccessful($success)
    {
        $this->success = (boolean) $success;
    }

    /**
     * Was the request successful?
     *
     * @return boolean
     */
    abstract public function wasSuccessful();

    /**
     * A message that explains the success or failure.
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Set the message.
     *
     * @param $message
     * @return self
     */
    public function setMessage($message)
    {
        $this->message = $message;
        return $this;
    }

    /**
     * Get to work order id, if applicable.
     *
     * @return integer|NULL
     */
    public function getWorkOrderId()
    {
        return $this->workOrderId;
    }

    /**
     * Set the work order id.
     *
     * @param integer $id
     * @return self
     */
    public function setWorkOrderId($id)
    {
        $this->workOrderId = $id;
        return $this;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-root',
  template: `

Hello {{ title }}!

    {{ href }}
  `,
  styles: [
    `
      div {
        font-weight: bold;
      }
    `,
  ],
})
export class AppComponent {
  title = 'world';
  href: string;

  constructor(@Inject(DOCUMENT) doc: Document) {
    this.href = doc.location.href;
  }
}


text:
import { SchemaCallback } from "../@types";
/**
 * The property that exists on the source scheme as a FK reference
 * to the external schema/entity.
 */
export declare type SourceProperty = string;
export declare class Schema<T = any> {
    schemaId: string;
    private _schemas;
    private _relationships;
    constructor(schemaId: string, mockFn?: SchemaCallback);
    /**
     * Add a mocking function to be used to generate the schema in mock DB
     */
    mock(cb: SchemaCallback): this;
    /**
     * There are times where it's appropriate to have multiple schemas for
     * the same entity/model, in this case you'll want to state what model
     * your schema is emulating. If you don't state this property it assumes
     * the schema name IS the model name
     */
    modelName(value: string): this;
    /** prefixes a static path to the beginning of the  */
    pathPrefix(prefix: string): this;
    /**
     * The default pluralizer is quite simple so if you find that
     * it is pluralizing incorrectly then you can manually state
     * the plural name.
     */
    pluralName(plural: string): this;
    /**
     * Configures a "belongsTo" relationship with another schema/entity
     */
    belongsTo(target: string, sourceProperty?: SourceProperty): this;
    /**
     * Configures a "hasMany" relationship with another schema/entity
     */
    hasMany(target: string, sourceProperty?: SourceProperty): this;
    /** Add another schema */
    addSchema<D>(schema: string, mock?: SchemaCallback): Schema<D>;
}


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

<title>SOM.LearningType (Java Machine Learning Library 0.1.7)</title>
<meta name="date" content="2012-07-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

net.sf.javaml.clustering

Enum SOM.LearningType

java.lang.Object

java.lang.Enum<SOM.LearningType>

net.sf.javaml.clustering.SOM.LearningType

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<SOM.LearningType>

Enclosing class:

SOM

public static enum SOM.LearningType
extends java.lang.Enum<SOM.LearningType>

Enum Constant Summary

Enum Constants

Enum Constant and Description

EXPONENTIAL

INVERSE

LINEAR

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
toString()

static SOM.LearningType
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static SOM.LearningType[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

EXPONENTIAL

public static final SOM.LearningType EXPONENTIAL

INVERSE

public static final SOM.LearningType INVERSE

LINEAR

public static final SOM.LearningType LINEAR

Method Detail

values

public static SOM.LearningType[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (SOM.LearningType c : SOM.LearningType.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in
the order they are declared

valueOf

public static SOM.LearningType valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Enum<SOM.LearningType>

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

			Copyright © 2006-2012 - Thomas Abeel - All Rights Reserved.


text:
/*DATOS GENERALES*/
*{font-family: arial;}

/*Div*/
div{float: left;
	margin: 33px; padding: 0;
	width: 180px; height: 300px;
	border: 6px solid #F00;}

/*Div por id*/
#div1{text-transform: uppercase; letter-spacing: 0.05em;}
	#div1 p::first-letter{font-size: 250%;}

#div2{text-transform: lowercase; letter-spacing: 0.1em;}
	#div2 span{background-color: #FFC; word-wrap: break-word;}

#div3{text-transform: capitalize; word-spacing: 0.1em;}
	#div3 span{background-color: #FFC; word-wrap: normal;}


text:
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <sstream>
#include <vector>
#include <algorithm>
#include <spdlog/spdlog.h>

#include "Synth.hpp"

#define IS_NEGATED(l) ((l & 1) == 1)
#define STRIP_LIT(lit) (lit & ~1)
#define NEGATED(lit) (lit ^ 1)

#define L_INF(message) {spdlog::get("console")->info() << message;}

#define hmap unordered_map
typedef unsigned uint;
typedef vector<uint> VecUint;
typedef unordered_set<uint> SetUint;

/*
class Grapher {
public:
    Grapher() {}

    hmap<uint, SetUint> deps;  // aiger_uint_lit -> set of aiger_uint_lit // for latches -- use latch.next
    hmap<uint, uint> freq_map;

    SetUint
    _get_deps(uint lit, aiger *spec) {
        auto stripped_lit = STRIP_LIT(lit);

        if (deps.find(stripped_lit) == deps.end()) {
            auto and_ = aiger_is_and(spec, stripped_lit);                       MASSERT(and_, "impossible");
            auto rhs0_deps = _get_deps(and_->rhs0, spec);
            auto rhs1_deps = _get_deps(and_->rhs1, spec);

            SetUint a_deps;
            a_deps.insert(rhs0_deps.begin(), rhs0_deps.end());
            a_deps.insert(rhs1_deps.begin(), rhs1_deps.end());

            deps[stripped_lit] = a_deps;
        }

        return deps[stripped_lit];
    }

    void compute_deps(aiger* spec) {
        deps.clear();
        freq_map.clear();

        deps[0] = SetUint();  // value 'false' (need to insert this value, since we later call 'find')

        for (uint i=0; i < spec->num_latches; ++i)
            deps[spec->latches[i].lit].insert(spec->latches[i].lit);

        for (uint i=0; i < spec->num_inputs; ++i)
            deps[spec->inputs[i].lit].insert(spec->inputs[i].lit);

        // above we initialized values for latches and inputs ('real' variables)
        // now we calculate dependencies between them

        for (uint i=0; i < spec->num_ands; ++i)
            deps[spec->ands[i].lhs] = _get_deps(spec->ands[i].lhs, spec);

        // at this point deps of all 'real' vars are computed:
        // - input vars do not have deps,
        // - latches vars are computed because dependencies of their next literals are computed
        _compute_freq_map(spec);
    }

    void _compute_freq_map(aiger *spec) {
        for (uint i=0; i < spec->num_latches; ++i) {
            auto latch_deps = deps[STRIP_LIT(spec->latches[i].next)];
            for (auto const & elem : latch_deps)
                ++freq_map[elem];
        }

        auto output_deps = deps[STRIP_LIT(spec->outputs[0].lit)];
        for (auto const & elem : output_deps)
            ++freq_map[elem];
    }

    // TODO:
//    uint is_referenced_only_once(uint and_lit) { }
//
//     TODO:
//    void distance(uint lit1, uint lit2) { }
//
    void dump_dot(aiger* spec) {
        cout << "digraph latch_graph { rankdir=BT;" << endl;

        for (uint i=0; i < spec->num_inputs; i++)
            cout << spec->inputs[i].lit << "[shape=triangle];" << endl;
        for (uint i=0; i < spec->num_latches; i++)
            cout << spec->latches[i].lit << "[shape=diamond, color=magenta];" << endl;
        cout << STRIP_LIT(spec->outputs[0].lit) << "[shape=triangle, color=blue];" << endl;

        for (uint i=0; i < spec->num_latches; i++)
            for (auto const & src : deps[STRIP_LIT(spec->latches[i].next)])
                cout << src << "->" << spec->latches[i].lit << ";" << endl;

        for (auto const & src : deps[STRIP_LIT(spec->outputs[0].lit)])
            cout << src << "->" << STRIP_LIT(spec->outputs[0].lit) << ";" << endl;

        cout << "}" << endl;
    }
};
 */

BDD Synth::get_bdd_for_sign_lit(uint lit) {
    /* lit is an AIGER variable index with a 'sign' */

    if (bdd_by_aiger_unlit.find(STRIP_LIT(lit)) != bdd_by_aiger_unlit.end()) {
        BDD res = bdd_by_aiger_unlit[STRIP_LIT(lit)];
        if (IS_NEGATED(lit))
            return ~res;
    }

    uint stripped_lit = STRIP_LIT(lit);
    BDD res;

    if (stripped_lit == 0) {
        res = cudd.bddZero();
    }
    else if (aiger_is_input(aiger_spec, stripped_lit) ||
             aiger_is_latch(aiger_spec, stripped_lit)) {
        res = cudd.ReadVars(cudd_by_aiger[stripped_lit]);
//        MASSERT(res.NodeReadIndex() == stripped_lit/2, "that bug again: impossible: " << res.NodeReadIndex() << " vs " << stripped_lit/2 );
    }
    else { // aiger_and
        aiger_and *and_ = aiger_is_and(aiger_spec, stripped_lit);
        res = get_bdd_for_sign_lit(and_->rhs0) & get_bdd_for_sign_lit(and_->rhs1);
    }

    bdd_by_aiger_unlit[stripped_lit] = res;

    return IS_NEGATED(lit) ? (~res):res;
}

vector<BDD> Synth::get_bdd_vars(bool(*filter_func)(char *)) {
    vector<BDD> result;
    for (uint i = 0; i < aiger_spec->num_inputs; ++i) {
        aiger_symbol symbol = aiger_spec->inputs[i];
        if ((*filter_func)(symbol.name)) {
            BDD out_var_bdd = get_bdd_for_sign_lit(symbol.lit);
            result.push_back(out_var_bdd);
        }
    }

    return result;
}

bool starts_with_controllable(char *name) { return 0 == string(name).find("controllable"); }

bool not_starts_with_controllable(char *name) { return string::npos == string(name).find("controllable"); }

vector<BDD> Synth::get_controllable_vars_bdds() {
    return get_bdd_vars(starts_with_controllable);
}

vector<BDD> Synth::get_uncontrollable_vars_bdds() {
    return get_bdd_vars(not_starts_with_controllable);
}

void Synth::introduce_error_bdd() {
    error = get_bdd_for_sign_lit(aiger_spec->outputs[0].lit);
}

void Synth::compose_init_state_bdd() { // Initial state is 'all latches are zero'
    L_INF("compose_init_state_bdd..");

    init = cudd.bddOne();

    for (uint i = 0; i < aiger_spec->num_latches; i++) {
        BDD latch_var = get_bdd_for_sign_lit(aiger_spec->latches[i].lit);
        init = init & ~latch_var;
    }
}

void Synth::compose_transition_vector() {
    L_INF("compose_transition_vector..");

    for (uint i = 0; i < aiger_spec->num_latches; ++i)
        transition_func[aiger_spec->latches[i].lit] = get_bdd_for_sign_lit(aiger_spec->latches[i].next);
}

vector<BDD> Synth::get_substitution() {
    vector<BDD> substitution;

    for (uint i = 0; i < (uint)cudd.ReadSize(); ++i) {
        if (aiger_is_latch(aiger_spec, aiger_by_cudd[i]))
            substitution.push_back(transition_func.find(aiger_by_cudd[i])->second);
        else
            substitution.push_back(cudd.ReadVars(i));
    }

    return substitution;
}

vector<string> &split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

/*
void print_aiger_like_order(const Cudd& cudd) {
    string best_order = cudd.OrderString();
    auto str_vars = split(best_order, ' ');                                 MASSERT(str_vars.size() == (uint) cudd.ReadSize(), "");
    for (auto const & str_v : str_vars)
        cout << stoi(str_v.substr(1))*2 << " ";
    cout << endl;
}
 */

/*
void reorder_opt(Cudd& cudd) {                                              L_INF("reorder_opt, original size: " << cudd.ReadNodeCount());
    int count = 0;                                                          Timer timer;
    while (count != cudd.ReadNodeCount()) {
        count = (int) cudd.ReadNodeCount();
        cudd.ReduceHeap(CUDD_REORDER_SIFT_CONVERGE, 0);                     L_INF("REORDERING: SIFT_CONV: SIZE: " << cudd.ReadNodeCount());
    }                                                                       L_INF("first reordering while took (sec): " << timer.sec_restart());

    // now add annealing
    count = 0;
    while (count != cudd.ReadNodeCount()) {
        count = (int) cudd.ReadNodeCount();
        cudd.ReduceHeap(CUDD_REORDER_ANNEALING, 0);                           L_INF("REORDERING: ANNLNG: SIZE: " << cudd.ReadNodeCount());
        cudd.ReduceHeap(CUDD_REORDER_SIFT_CONVERGE, 0);                       L_INF("REORDERING: SIFT_CONV: SIZE: " << cudd.ReadNodeCount());
    }                                                                         L_INF("second reordering while took (sec): " << timer.sec_restart());
}

*/
VecUint get_order(Cudd &cudd) {
    string order_str = cudd.OrderString();
    auto str_vars = split(order_str, ' ');                                MASSERT(str_vars.size() == (uint) cudd.ReadSize(), "");
    VecUint order;
    for (auto const & str_v : str_vars) {
        order.push_back((uint) stoi(str_v.substr(1)));
    }
    return order;
}

//string string_vector(const VecUint& v) {
//    stringstream ss;
//    for(size_t i = 0; i < v.size(); ++i)
//    {
//        if(i != 0)
//            ss << ",";
//        ss << v[i];
//    }
//    return ss.str();
//}
//
string string_set(const SetUint& v) {
    stringstream ss;
    for(auto const el : v)
        ss << el << ",";
    return ss.str();
}

template<typename Container>
struct container_hash {
    std::size_t operator()(Container const & v) const {
        size_t hash = 0;
        for (auto const el: v)
            hash ^= el;
        return hash;
    }
};

bool do_intersect(const SetUint& s1, const SetUint& s2) {
    for (auto el1 : s1)
        if (s2.find(el1) != s2.end())
            return true;
    return false;
}

//SetUint union_sets(const SetUint& s1, const SetUint& s2) {
//    SetUint merged(s1.begin(), s1.end());
//    merged.insert(s2.begin(), s2.end());
//    return merged;
//}

vector<SetUint>
get_group_candidates(const vector<VecUint >& orders,
                     uint window_size)
{
    hmap<SetUint, uint, container_hash<SetUint>>
            group_freq;

    for (auto const & order : orders) {
        for (uint idx=0; idx < order.size() - window_size; ++idx) {
            SetUint sub_group(order.begin() + idx,
                              order.begin() + idx + window_size);
            ++group_freq[sub_group];
        }
    }

    vector<SetUint> candidates;
    for (auto const & it: group_freq) {
        if (((float)it.second/orders.size()) >= 0.8)  // appears 'often'
            candidates.push_back(it.first);
    }
    return candidates;
}

void remove_intersecting(SetUint group,
                         vector<SetUint> &groups)
{
    vector<SetUint >::iterator it = groups.begin();
    while (it != groups.end()) {
        if (do_intersect(group, *it))
            it = groups.erase(it);
        else
            ++it;
    }
}

uint get_var_of_min_order_position(Cudd& cudd, const SetUint& group)
{
    uint min_var = *group.begin();
    uint min_pos = (uint)cudd.ReadPerm(min_var);
    for (auto const var : group)
        if ((uint )cudd.ReadPerm(var) < min_pos) {
            min_var = var;
            min_pos = (uint)cudd.ReadPerm(var);
        }
    return min_var;
}

void introduce_group_into_cudd(Cudd &cudd, const SetUint& group)
{
    L_INF("adding variable group to cudd: " << string_set(group));
    auto first_var_pos = get_var_of_min_order_position(cudd, group);
    cudd.MakeTreeNode(first_var_pos, (uint) group.size(), MTR_FIXED);
}

void _do_grouping(Cudd &cudd,
                  hmap<uint, vector<SetUint>> &groups_by_length,  // we modify its values
                  uint cur_group_length,
                  const VecUint& cur_order)
{
    L_INF("fixing groups of size " << cur_group_length << ". The number of groups = " << groups_by_length[cur_group_length].size());

    auto cur_groups = groups_by_length[cur_group_length];

    for (uint i = 0; i+cur_group_length < cur_order.size(); ++i) {
        SetUint candidate;
        for (uint j = 0; j < cur_group_length; ++j)
            candidate.insert(cur_order[i+j]);

        if (find(cur_groups.begin(), cur_groups.end(), candidate) != cur_groups.end()) {
            for (uint l = 2; l < cur_group_length; ++l) {
//                cout << "rm intersections " << string_set(candidate) << endl;
//                cout << "before: " << endl;
//                for (auto const v : groups_by_length[l])
//                    cout << string_set(v) << endl;
                remove_intersecting(candidate, groups_by_length[l]);  //remove from smaller groups
//                cout << "after: " << endl;
//                for (auto const v : groups_by_length[l])
//                    cout << string_set(v) << endl;
            }
            introduce_group_into_cudd(cudd, candidate);
        }
    }
}

void do_grouping(Cudd& cudd,
                 const vector<VecUint>& orders)
{
    L_INF("trying to group vars..");

    if (orders[0].size() < 5)  // window size is too big
        return;

    hmap<uint, vector<SetUint>> groups_by_length;
    groups_by_length[2] = get_group_candidates(orders, 2);
    groups_by_length[3] = get_group_candidates(orders, 3);
    groups_by_length[4] = get_group_candidates(orders, 4);
    groups_by_length[5] = get_group_candidates(orders, 5);

    L_INF("# of group candidates: of size 2 -- " << groups_by_length[2].size());
    for (auto const& g : groups_by_length[2]) {
        L_INF(string_set(g));
    }
    L_INF("# of group candidates: of size 3 -- " << groups_by_length[3].size());
    for (auto const& g : groups_by_length[3]) {
        L_INF(string_set(g));
    }
    L_INF("# of group candidates: of size 4 -- " << groups_by_length[4].size());
    L_INF("# of group candidates: of size 5 -- " << groups_by_length[5].size());

    auto cur_order = orders.back();    // we fix only groups present in the current order (because that is easier to implement)

    for (uint i = 5; i>=2; --i)  // decreasing order!
        if (!groups_by_length[i].empty())
            _do_grouping(cudd, groups_by_length, i, cur_order);
}

void update_order_if(Cudd& cudd, vector<VecUint >& orders)
{
    static uint last_nof_orderings = 0;

    if (last_nof_orderings != cudd.ReadReorderings())
        orders.push_back(get_order(cudd));

    last_nof_orderings = cudd.ReadReorderings();
}

BDD Synth::pre_sys(BDD dst) {
    /**
    Calculate predecessor states of given states.

        ∀u ∃c ∃t': tau(t,u,c,t') & dst(t') & ~error(t,u,c)

    We use the direct substitution optimization (since t' <-> BDD(t,u,c)), thus:

        ∀u ∃c: (!error(t,u,c)  &  (dst(t)[t <- bdd_next_t(t,u,c)]))

    or for Moore machines:

        ∃c ∀u: (!error(t,u,c)  &  (dst(t)[t <- bdd_next_t(t,u,c)]))

    Note that we do not replace t variables in the error bdd.

    :return: BDD of the predecessor states
    **/

    // NOTE: I tried considering two special cases: error(t,u,c) and error(t),
    //       and move error(t) outside of quantification ∀u ∃c.
    //       It slowed down..
    // TODO: try again: on the driver example

    static vector<VecUint> orders;
    static bool did_grouping = false;

    if (!did_grouping && timer.sec_from_origin() > time_limit_sec/4) { // at 0.25*time_limit we fix the order
        do_grouping(cudd, orders);
        did_grouping = true;
    }

    dst = dst.VectorCompose(get_substitution());                                update_order_if(cudd, orders);

    if (is_moore) {
        BDD result = dst.And(~error);

        vector<BDD> uncontrollable = get_uncontrollable_vars_bdds();
        if (!uncontrollable.empty()) {
            BDD uncontrollable_cube = cudd.bddComputeCube(uncontrollable.data(),
                                                          NULL,
                                                          (int)uncontrollable.size());
            result = result.UnivAbstract(uncontrollable_cube);                  update_order_if(cudd, orders);
        }

        // ∃c ∀u  (...)
        vector<BDD> controllable = get_controllable_vars_bdds();
        BDD controllable_cube = cudd.bddComputeCube(controllable.data(),
                                                    NULL,
                                                    (int)controllable.size());
        result = result.ExistAbstract(controllable_cube);                       update_order_if(cudd, orders);
        return result;
    }

    // the case of Mealy machines
    vector<BDD> controllable = get_controllable_vars_bdds();
    BDD controllable_cube = cudd.bddComputeCube(controllable.data(),
                                                NULL,
                                                (int)controllable.size());
    BDD result = dst.AndAbstract(~error, controllable_cube);                   update_order_if(cudd, orders);

    vector<BDD> uncontrollable = get_uncontrollable_vars_bdds();
    if (!uncontrollable.empty()) {
        // ∀u ∃c (...)
        BDD uncontrollable_cube = cudd.bddComputeCube(uncontrollable.data(),
                                                      NULL,
                                                      (int)uncontrollable.size());
        result = result.UnivAbstract(uncontrollable_cube);                    update_order_if(cudd, orders);
    }
    return result;
}

//int post_order_hook(DdManager* cudd, const char*, void*)
//{
//    L_INF("cudd initiated reordering: ");
//    return 1;
//}

BDD Synth::calc_win_region() {
    /** Calculate a winning region for the safety game: win = greatest_fix_point.X [not_error & pre_sys(X)]
        :return: BDD representing the winning region
    **/

    BDD new_ = cudd.bddOne();
    for (uint i = 1; ; ++i) {                                             L_INF("calc_win_region: iteration " << i << ": node count " << cudd.ReadNodeCount());
        BDD curr = new_;

        new_ = pre_sys(curr);

        if ((init & new_) == cudd.bddZero())
            return cudd.bddZero();

        if (new_ == curr)
            return new_;
    }
}

BDD Synth::get_nondet_strategy() {
    /**
    Get non-deterministic strategy from the winning region.
    If the system outputs controllable values that satisfy this non-deterministic strategy,
    then the system wins.
    I.e., a non-deterministic strategy describes for each state all possible plausible output values
    (below is assuming W excludes error states)

        strategy(t,u,c) = ∃t' W(t) & T(t,i,c,t') & W(t')

    But since t' <-> bdd(t,i,o), (and since we use error=error(t,u,c)), we use:

        strategy(t,u,c) = ~error(t,u,c) & W(t) & W(t)[t <- bdd_next_t(t,u,c)]

    :return: non-deterministic strategy bdd
    :note: The strategy is non-deterministic -- determinization is done later.
    **/

    L_INF("get_nondet_strategy..");

    // TODO: do we need win_region?
    return ~error & win_region & win_region.VectorCompose(get_substitution());
}

hmap<uint,BDD> Synth::extract_output_funcs() {
    /** The result vector respects the order of the controllable variables **/

    L_INF("extract_output_funcs..");

    cudd.FreeTree();    // ordering that worked for win region computation might not work here

    hmap<uint,BDD> model_by_cuddidx;

    vector<BDD> controls = get_controllable_vars_bdds();

    while (!controls.empty()) {
        BDD c = controls.back(); controls.pop_back();

        aiger_symbol *aiger_input = aiger_is_input(aiger_spec, aiger_by_cudd[c.NodeReadIndex()]);
        L_INF("getting output function for " << aiger_input->name);

        BDD c_arena;
        if (controls.size() > 0) {
            BDD cube = cudd.bddComputeCube(controls.data(), NULL, (int)controls.size());
            c_arena = non_det_strategy.ExistAbstract(cube);
        }
        else { //no other signals left
            c_arena = non_det_strategy;
        }
        // Now we have: c_arena(t,u,c) = ∃c_others: nondet(t,u,c)
        // (i.e., c_arena talks about this particular c, about t and u)

        BDD c_can_be_true = c_arena.Cofactor(c);
        BDD c_can_be_false = c_arena.Cofactor(~c);

        BDD c_must_be_true = ~c_can_be_false & c_can_be_true;
        BDD c_must_be_false = c_can_be_false & ~c_can_be_true;
        // Note that we cannot use `c_must_be_true = ~c_can_be_false`,
        // since the negation can cause including tuples (t,i,o) that violate non_det_strategy.

        auto support_indices = cudd.SupportIndices(vector<BDD>({c_must_be_false, c_must_be_true}));
        for (auto const var_cudd_idx : support_indices) {
            auto v = cudd.ReadVars(var_cudd_idx);
            auto new_c_must_be_false = c_must_be_false.ExistAbstract(v);
            auto new_c_must_be_true = c_must_be_true.ExistAbstract(v);

            if ((new_c_must_be_false & new_c_must_be_true) == cudd.bddZero()) {
                c_must_be_false = new_c_must_be_false;
                c_must_be_true = new_c_must_be_true;
            }
        }

        // We use 'restrict' operation, but we could also just do:
        //     c_model = care_set -> must_be_true
        // but this is (presumably) less efficient (in time? in size?).
        // (intuitively, because we always set c_model to 1 if !care_set, but we could set it to 0)
        //
        // The result of restrict operation satisfies:
        //     on c_care_set: c_must_be_true <-> must_be_true.Restrict(c_care_set)

        BDD c_model = c_must_be_true.Restrict(c_must_be_true | c_must_be_false);

        model_by_cuddidx[c.NodeReadIndex()] = c_model;

        //killing node refs
        c_must_be_false = c_must_be_true = c_can_be_false = c_can_be_true = c_arena = cudd.bddZero();

        //TODO: ak: strange -- the python version for the example amba_02_9n produces a smaller circuit (~5-10 times)!
        non_det_strategy = non_det_strategy.Compose(c_model, c.NodeReadIndex());
        //non_det_strategy = non_det_strategy & ((c & c_model) | (~c & ~c_model));
    }

    return model_by_cuddidx;
}

uint Synth::next_lit() {
    /* return: next possible to add to the spec literal */
    return (aiger_spec->maxvar + 1) * 2;
}

uint Synth::get_optimized_and_lit(uint a_lit, uint b_lit) {
    if (a_lit == 0 || b_lit == 0)
        return 0;

    if (a_lit == 1 && b_lit == 1)
        return 1;

    if (a_lit == 1)
        return b_lit;

    if (b_lit == 1)
        return a_lit;

    if (a_lit > 1 && b_lit > 1) {
        uint a_b_lit = next_lit();
        aiger_add_and(aiger_spec, a_b_lit, a_lit, b_lit);
        return a_b_lit;
    }

    MASSERT(0, "impossible");
}

uint Synth::walk(DdNode *a_dd) {
    /**
    Walk given DdNode node (recursively).
    If a given node requires intermediate AND gates for its representation, the function adds them.
        Literal representing given input node is `not` added to the spec.

    :returns: literal representing input node
    **/

    // caching
    static hmap<DdNode*, uint> cache;
    {
        auto cached_lit = cache.find(Cudd_Regular(a_dd));
        if (cached_lit != cache.end())
            return Cudd_IsComplement(a_dd) ? NEGATED(cached_lit->second) : cached_lit->second;
    }
    // end of caching

    if (Cudd_IsConstant(a_dd))
        return (uint) (a_dd == cudd.bddOne().getNode());  // in aiger: 0 is False and 1 is True

    // get an index of the variable
    uint a_lit = aiger_by_cudd[Cudd_NodeReadIndex(a_dd)];

    DdNode *t_bdd = Cudd_T(a_dd);
    DdNode *e_bdd = Cudd_E(a_dd);

    uint t_lit = walk(t_bdd);
    uint e_lit = walk(e_bdd);

    // ite(a_bdd, then_bdd, else_bdd)
    // = a*then + !a*else
    // = !(!(a*then) * !(!a*else))
    // -> in general case we need 3 more ANDs

    uint a_t_lit = get_optimized_and_lit(a_lit, t_lit);

    uint na_e_lit = get_optimized_and_lit(NEGATED(a_lit), e_lit);

    uint n_a_t_lit = NEGATED(a_t_lit);
    uint n_na_e_lit = NEGATED(na_e_lit);

    uint and_lit = get_optimized_and_lit(n_a_t_lit, n_na_e_lit);

    uint res = NEGATED(and_lit);

    cache[Cudd_Regular(a_dd)] = res;

    if (Cudd_IsComplement(a_dd))
        res = NEGATED(res);

    return res;
}

void Synth::model_to_aiger(const BDD &c_signal, const BDD &func) {
    /// Update AIGER spec with a definition of `c_signal`

    uint c_lit = aiger_by_cudd[c_signal.NodeReadIndex()];
    string output_name = string(aiger_is_input(aiger_spec, c_lit)->name);  // save the name before it is freed

    uint func_as_aiger_lit = walk(func.getNode());

    aiger_redefine_input_as_and(aiger_spec, c_lit, func_as_aiger_lit, func_as_aiger_lit);

    if (print_full_model)
        aiger_add_output(aiger_spec, c_lit, output_name.c_str());
}

//bool first_cmp (pair<uint, uint> a, pair<uint, uint> b) { return (a.first > b.first); /* > means often-first */ }

/*
void print_order_frequencies(Grapher& grapher, Cudd& cudd, aiger* aiger_spec) {
    string best_order = cudd.OrderString();
    auto str_vars = split(best_order, ' ');                             MASSERT(str_vars.size() == (uint) cudd.ReadSize(), "");
    vector<int> int_vars;
    for (auto const & str_v : str_vars)
        int_vars.push_back(stoi(str_v.substr(1)));
    cout << endl;
    cout << "frequencies of best order:" << endl;
    for (auto int_v : int_vars) {
        cout << grapher.freq_map[int_v * 2];
        auto s = aiger_is_input(aiger_spec, (uint) (int_v * 2));
        if (s) {
            cout << "\t*";
            if (string(s->name).find("controllable") != string::npos)
                cout << "*";
        }
        cout << endl;
    }
    cout << endl;
}
*/

/*
vector<int> compute_permutation(Grapher& grapher, Cudd& cudd, aiger* aiger_spec) {
    // Assumes the variables are already created.

    vector<pair<uint, uint>> freq_lit_vector;
    for (uint i = 0; i < aiger_spec->num_inputs; ++i) {
        auto lit = aiger_spec->inputs[i].lit;
        freq_lit_vector.push_back(make_pair(grapher.freq_map[lit], lit));
    }
    for (uint i = 0; i < aiger_spec->num_latches; ++i) {
        auto lit = aiger_spec->latches[i].lit;
        freq_lit_vector.push_back(make_pair(grapher.freq_map[lit], lit));
    }

    sort(freq_lit_vector.begin(), freq_lit_vector.end(), first_cmp);

    MASSERT(((uint)cudd.ReadSize()) == aiger_spec->num_inputs + aiger_spec->num_latches+1, "should not happen");

    SetUint all_var_indices;
    for (uint i = 0; i < (uint)cudd.ReadSize(); ++i)
        all_var_indices.insert(i);

    vector<int> permutation;
    for (uint i = 0; i < (uint)cudd.ReadSize(); ++i) {
        if (i < (aiger_spec->num_inputs+aiger_spec->num_latches)) {
            permutation.push_back(freq_lit_vector[i].second/2);
            all_var_indices.erase(freq_lit_vector[i].second/2);
//                cout << "perm level " << i << " lit freq " << freq_lit_vector[i].first << " setting var(lit/2) " << freq_lit_vector[i].second/2 << endl;
        }
        else {
            auto some_random_var = *all_var_indices.begin();                         L_INF("ALERT!!! who did create this var? " << some_random_var);
            all_var_indices.erase(all_var_indices.begin());
            permutation.push_back(some_random_var);
        }
    }
    MASSERT(all_var_indices.empty(), "should be empty");

    return permutation;
}

void print_set(SetUint& s, aiger* spec) {
    for (auto const e: s) {
        cout << e;
        auto latch = aiger_is_latch(spec, e);
        if (latch) {
            cout << "(" << latch->next << ")";
        }
        cout << endl;

    }
    cout << endl;
}
*/

class Cleaner {
public:
    aiger* spec;
    Cleaner(aiger* spec): spec(spec) { }
    ~Cleaner() { aiger_reset(spec); }
};

void init_cudd(Cudd& cudd)
{
//    cudd.Srandom(827464282);  // for reproducibility (?)
    cudd.AutodynEnable(CUDD_REORDER_SIFT);
//    cudd.EnableReorderingReporting();
}

/* something does not work here
BDD compute_reachable(aiger* spec, BDD init_orig, hmap<unsigned,BDD>& transition_func_orig, BDD error_orig,
                      Cudd& cudd_orig)
{

#define AIG_2_PRIM_IDX(aiger_lit)  (aiger_lit/2 + spec->num_latches)
#define AIG_2_CUR_IDX(aiger_lit)  (aiger_lit/2)
#define PRIM_IDX_2_AIG_LIT(aiger_lit)  (aiger_lit/2 + spec->num_inputs + spec->num_latches)
#define CUR_IDX_2_AIG(aiger_lit)  (aiger_lit/2)

    L_INF("compute_reachable...");
    Cudd cudd2;
    init_cudd(cudd2);

    vector<BDD> _tmp;
    for (uint i=0; i < spec->num_inputs + 2*spec->num_latches + 1; ++i)
        _tmp.push_back(cudd2.bddVar(i));

    VecUint permutation;
    permutation.push_back(0);

    for (uint i=0; i < spec->num_latches; ++i) {
        permutation.push_back(AIG_2_CUR_IDX(spec->latches[i].lit));
        permutation.push_back(AIG_2_PRIM_IDX(spec->latches[i].lit));
    }

    for (uint i=0; i < spec->num_inputs; ++i)
        permutation.push_back(AIG_2_CUR_IDX(spec->inputs[i].lit));

    for (auto c : permutation)
        cout << c << endl;
    cudd2.ShuffleHeap((int*)permutation.data());

    for (uint i=1; i < spec->num_latches + 1; ++i)
        cudd2.MakeTreeNode(i*2-1, 2, MTR_FIXED);

    auto init = init_orig.Transfer(cudd2);

    cout << "transferring error.." << endl;
    auto error = error_orig.Transfer(cudd2);

    cout << "computing trans rel .. " << endl;
    auto trans_rel = cudd2.bddOne();
    for (auto const& it : transition_func_orig) {
        cout << "adding & for var" << it.first << endl;
        auto newBdd = it.second.Transfer(cudd2);
        trans_rel &= ~(cudd2.ReadVars(AIG_2_PRIM_IDX(it.first)).Xor(newBdd));  //aka: l' <-> bdd
    }

    vector<BDD> all_inputs;
    for (uint i = 0; i < spec->num_inputs; ++i) {
        auto aig_inp = spec->inputs[i];
        all_inputs.push_back(cudd2.ReadVars(AIG_2_CUR_IDX(aig_inp.lit)));
    }
    auto all_inputs_cube = cudd2.bddComputeCube(all_inputs.data(), NULL, (int) all_inputs.size());

    vector<BDD> all_cur_latches;
    vector<BDD> all_prim_latches;
    for (uint i = 0; i < spec->num_latches; ++i) {
        auto aig_l = spec->latches[i];
        all_cur_latches.push_back(cudd2.ReadVars(AIG_2_CUR_IDX(aig_l.lit)));
        all_prim_latches.push_back(cudd2.ReadVars(AIG_2_PRIM_IDX(aig_l.lit)));  //i.e., normal idx multiplied by 2
    }
    auto all_cur_latches_cube = cudd2.bddComputeCube(all_cur_latches.data(), NULL, (int) all_cur_latches.size());

    auto trans_not_err = trans_rel & ~error;
    BDD curr;
    BDD new_ = init;
    do {
        curr = new_;
        cout << "another iteration.. is curr 1?" << (new_==cudd2.bddOne()) << endl;
        // new_(l') = \exists u,c,l: curr(l) & trans(l,u,c,l') & ~error(l,u,c)
        // new_(l') = \exists l: (curr(l) & (\exists u,c: (trans(l,u,c,l') & ~error(l,u,c))) )
//        new_ = curr.AndAbstract(trans_rel.AndAbstract(~error, all_inputs_cube),
//                                all_cur_latches_cube)
//               .SwapVariables(all_prim_latches, all_cur_latches);
        new_ = trans_not_err.AndAbstract(curr, all_cur_latches_cube & all_inputs_cube);
        new_ = new_.SwapVariables(all_prim_latches, all_cur_latches);

//        new_ = curr.AndAbstract(trans_rel.ExistAbstract(all_inputs_cube),
//                                all_cur_latches_cube)
//               .SwapVariables(all_prim_latches, all_cur_latches);
    } while (new_ != curr);

    L_INF("finished computing reachable states");
    cout << (new_==cudd2.bddOne()) << ", size: " << new_.nodeCount() << endl;
    L_INF("transferring it back..");
    auto res = new_.Transfer(cudd_orig);
    L_INF("finished transferring back!");
    return res;
}
 */

bool Synth::run() {
    init_cudd(cudd);

    aiger_spec = aiger_init();
    const char *err = aiger_open_and_read_from_file(aiger_spec, aiger_file_name.c_str());
    MASSERT(err == NULL, err);
    Cleaner cleaner(aiger_spec);

    // main part
    L_INF("synthesize.. number of vars = " << aiger_spec->num_inputs + aiger_spec->num_latches);
//    grapher = new Grapher();                                        timer.sec_restart();
//    grapher->compute_deps(aiger_spec);                              L_INF("calculating deps graph took (sec): " << timer.sec_restart());

    //grapher.dump_dot();
    //print_set(grapher.deps[STRIP_LIT(aiger_spec->outputs[0].lit)], aiger_spec);

    // Create all variables. _tmp ensures that BDD have positive refs.
    vector<BDD> _tmp;
    for (uint i = 0; i < aiger_spec->num_inputs + aiger_spec->num_latches; ++i)
        _tmp.push_back(cudd.bddVar(i));

    for (uint i = 0; i < aiger_spec->num_inputs; ++i) {
        auto aiger_strip_lit = aiger_spec->inputs[i].lit;
        cudd_by_aiger[aiger_strip_lit] = i;
        aiger_by_cudd[i] = aiger_strip_lit;
    }
    for (uint i = 0; i < aiger_spec->num_latches; ++i) {
        auto aiger_strip_lit = aiger_spec->latches[i].lit;
        auto cudd_idx = i + aiger_spec->num_inputs;
        cudd_by_aiger[aiger_strip_lit] = cudd_idx;
        aiger_by_cudd[cudd_idx] = aiger_strip_lit;
    }

//    vector<int> permutation = compute_permutation(grapher, cudd, aiger_spec);
//    MASSERT(permutation.size() == (uint) cudd.ReadSize(), "");

    /*
    L_INF("frequencies of latches");
    for (uint i = 0; i < aiger_spec->num_latches; ++i) {
        auto lit = aiger_spec->latches[i].lit;
        cout << "latch lit " << lit << " : " << grapher.freq_map[lit] << endl;
    }
    L_INF("frequencies of inputs");
    for (uint i = 0; i < aiger_spec->num_inputs; ++i) {
        auto lit = aiger_spec->inputs[i].lit;
        cout << "input lit " << lit << " : " << grapher.freq_map[lit] << endl;
    }
    */

    /*
    vector<BDD> nodes;
    nodes.push_back(error);
    vector<string> names;
    vector<const char*> names_;

    names.push_back(string("weird0"));
    names_.push_back(names[0].data());

    for (uint i = 1; i < aiger_spec->num_latches + aiger_spec->num_inputs+1; ++i) {
        names.push_back(to_string(i));
        if (aiger_is_input(aiger_spec, i*2)) {
            auto s = aiger_is_input(aiger_spec, i*2);
            if (s->name)
                names.push_back(string(s->name));
            else
                names.push_back(to_string(i*2));
        }
        if (aiger_is_latch(aiger_spec, i*2)) {
            auto s = aiger_is_latch(aiger_spec, i*2);
            if (s->name)
                names.push_back(string(s->name));
            else
                names.push_back(to_string(i*2));
        }

        names_.push_back(names[i].data());

    }
    cudd.DumpDot(nodes, names_.data(), NULL);
    cout << cudd.OrderString() << endl;
    exit(0);
    */

    compose_init_state_bdd();
    timer.sec_restart();
    compose_transition_vector();
    L_INF("calc_trans_rel took (sec): " << timer.sec_restart());
    introduce_error_bdd();
    L_INF("introduce_error_bdd took (sec): " << timer.sec_restart());

//    cout << "before comput: nof_vars = " << cudd.ReadSize() << endl;
//    reachable = compute_reachable(aiger_spec, init, transition_func, error, cudd);
//    cout << "after comput: nof_vars = " << cudd.ReadSize() << endl;

    // no need for cache
    bdd_by_aiger_unlit.clear();

//                                               reorder_opt(cudd);
//                                               print_aiger_like_order(cudd);

    timer.sec_restart();
    win_region = calc_win_region();
    L_INF("calc_win_region took (sec): " << timer.sec_restart());

//                                               print_aiger_like_order(cudd);
//                                               Cudd_MakeTreeNode(cudd.getManager(), 5, 8, MTR_FIXED);

//                                               reorder_opt(cudd);
//                                               cout << "optimal order after calc_win_region" << endl;
//                                               print_aiger_like_order(cudd);
//                                                 cout << cudd.ReadNodeCount() << endl;

    if (win_region.IsZero()) {
        cout << "UNREALIZABLE" << endl;
        return 0;
    }

    cout << "REALIZABLE" << endl;

    non_det_strategy = get_nondet_strategy();

    //cleaning non-used bdds
    win_region = cudd.bddZero();
    transition_func.clear();
    init = cudd.bddZero();
    error = cudd.bddZero();
    //

    // TODO: set time limit on reordering? or even disable it if no time?
    hmap<uint, BDD> model_by_cuddidx = extract_output_funcs();                   L_INF("extract_output_funcs took (sec): " << timer.sec_restart());

    //cleaning non-used bdds
    non_det_strategy = cudd.bddZero();
    //

    auto elapsed_sec = time_limit_sec - timer.sec_from_origin();
    if (elapsed_sec > 100) {    // leave 100sec just in case
        auto spare_time_sec = elapsed_sec - 100;
        cudd.ResetStartTime();
        cudd.IncreaseTimeLimit((unsigned long) (spare_time_sec * 1000));
        cudd.ReduceHeap(CUDD_REORDER_SIFT_CONVERGE);
        cudd.UnsetTimeLimit();
        cudd.AutodynDisable();  // just in case -- cudd hangs on timeout
    }

    for (auto const it : model_by_cuddidx)
        model_to_aiger(cudd.ReadVars((int)it.first), it.second);
                                                                   L_INF("model_to_aiger took (sec): " << timer.sec_restart());
                                                                   L_INF("circuit size: " << (aiger_spec->num_ands + aiger_spec->num_latches));

    int res = 1;
    if (output_file_name == "stdout")
        res = aiger_write_to_file(aiger_spec, aiger_ascii_mode, stdout);
    else if (!output_file_name.empty()) {                                       L_INF("writing a model to " << output_file_name);
        res = aiger_open_and_write_to_file(aiger_spec, output_file_name.c_str());
    }

    MASSERT(res, "Could not write result file");

    return 1;
}

Synth::~Synth() {
//    if (grapher)
//        delete(grapher);
//    grapher = NULL;
}


text:
package greycat.ml.neuralnet;

import greycat.Type;
import greycat.ml.neuralnet.layer.Layer;
import greycat.ml.neuralnet.layer.Layers;
import greycat.ml.neuralnet.loss.Loss;
import greycat.ml.neuralnet.loss.Losses;
import greycat.ml.neuralnet.optimiser.Optimiser;
import greycat.ml.neuralnet.optimiser.Optimisers;
import greycat.ml.neuralnet.process.ExMatrix;
import greycat.ml.neuralnet.process.ProcessGraph;
import greycat.struct.DMatrix;
import greycat.struct.EStruct;
import greycat.struct.EStructArray;
import greycat.struct.matrix.MatrixOps;
import greycat.struct.matrix.RandomInterface;
import greycat.struct.matrix.VolatileDMatrix;

public class NeuralNetWrapper {

    private static final String TRAIN_LOSS = "train_loss";
    private static final String TEST_LOSS = "test_loss";
    private static final String LEARNER = "optimiser";

    private RandomInterface random = null;
    private EStructArray backend;
    private EStruct root;
    private Layer[] layers;
    private Loss tarinLoss;
    private Loss testLoss;
    private Optimiser learner;

    public NeuralNetWrapper(EStructArray p_backend) {
        backend = p_backend;
        int nb = backend.size() - 1;

        if (nb < 0) {
            //create configuration node
            root = p_backend.newEStruct();
            p_backend.setRoot(root);
            nb = 0;
        } else {
            root = p_backend.root();
        }

        //Load config with everything in default

        tarinLoss = Losses.getUnit(root.getWithDefault(TRAIN_LOSS, Losses.DEFAULT), null);
        testLoss = Losses.getUnit(root.getWithDefault(TEST_LOSS, Losses.DEFAULT), null);
        learner = Optimisers.getUnit(root.getWithDefault(LEARNER, Optimisers.DEFAULT), backend.root());

        if (nb > 0) {
            //load all layers
            layers = new Layer[nb];
            for (int i = 0; i < layers.length; i++) {
                layers[i] = Layers.loadLayer(backend.estruct(i + 1));
            }
        } else {
            layers = new Layer[0];
        }
    }

    public void setRandom(RandomInterface random) {
        this.random = random;
    }

    public void setTrainLoss(int trainLoss, double[] weights) {
        this.tarinLoss = Losses.getUnit(trainLoss, weights);
        root.set(TRAIN_LOSS, Type.INT, trainLoss);
    }

    public void setTestLoss(int testLoss, double[] weights) {
        this.testLoss = Losses.getUnit(testLoss, weights);
        root.set(TEST_LOSS, Type.INT, testLoss);
    }

    public void setOptimizer(int optimizer, double[] learnerParams, int frequency) {
        this.learner = Optimisers.getUnit(optimizer, root);
        if (learnerParams != null) {
            this.learner.setParams(learnerParams);
        }
        this.learner.setFrequency(frequency);
    }

    public void initAllLayers(int weightInitType, RandomInterface random, double std) {
        for (int i = 0; i < layers.length; i++) {
            layers[i].init(weightInitType, random, std);
        }
    }

    public void initSelectedLayer(int layerNumber, int weightInitType, RandomInterface random, double std) {
        if (layerNumber < layers.length) {
            layers[layerNumber].init(weightInitType, random, std);
        } else {
            throw new RuntimeException("Layer not found");
        }
    }

    public NeuralNetWrapper addLayer(int layerType, int inputs, int outputs, int activationUnit, double[] activationParams) {
        if (layers.length > 0) {
            if (layers[layers.length - 1].outputDimensions() != inputs) {
                throw new RuntimeException("Layers last output size is different that current layer input");
            }
        }
        Layer ff = Layers.createLayer(backend.newEStruct(), layerType);
        ff.create(inputs, outputs, activationUnit, activationParams);
        internal_add(ff);
        return this;
    }

    public DMatrix[] learn(double[] inputs, double[] outputs, boolean reportLoss) {
        ProcessGraph cg = new ProcessGraph(random, true);
        ExMatrix input = ExMatrix.createFromW(VolatileDMatrix.wrap(inputs, inputs.length, 1));
        ExMatrix targetOutput = ExMatrix.createFromW(VolatileDMatrix.wrap(outputs, outputs.length, 1));
        ExMatrix actualOutput = internalForward(cg, input, 0, layers.length);
        DMatrix error = cg.applyLoss(tarinLoss, actualOutput, targetOutput, reportLoss);
        cg.backpropagate();
        learner.stepUpdate(layers);
        return new DMatrix[]{actualOutput, error};
    }

    public DMatrix[] learnVec(DMatrix inputs, DMatrix outputs, boolean reportLoss) {
        ProcessGraph cg = new ProcessGraph(random, true);
        ExMatrix input = ExMatrix.createFromW(inputs);
        ExMatrix targetOutput = ExMatrix.createFromW(outputs);
        ExMatrix actualOutput = internalForward(cg, input, 0, layers.length);
        DMatrix error = cg.applyLoss(tarinLoss, actualOutput, targetOutput, reportLoss);
        cg.backpropagate();
        learner.setBatchSize(inputs.columns());
        learner.stepUpdate(layers);
        return new DMatrix[]{actualOutput, error};
    }

    public DMatrix[] test(double[] inputs, double[] outputs) {
        ProcessGraph cg = new ProcessGraph(random, false);
        ExMatrix input = ExMatrix.createFromW(VolatileDMatrix.wrap(inputs, inputs.length, 1));
        ExMatrix targetOutput = ExMatrix.createFromW(VolatileDMatrix.wrap(outputs, outputs.length, 1));
        ExMatrix actualOutput = internalForward(cg, input, 0, layers.length);
        return new DMatrix[]{actualOutput, cg.applyLoss(testLoss, actualOutput, targetOutput, true)};
    }

    public DMatrix[] testVec(DMatrix inputs, DMatrix outputs) {
        ProcessGraph cg = new ProcessGraph(random, false);
        ExMatrix input = ExMatrix.createFromW(inputs);
        ExMatrix targetOutput = ExMatrix.createFromW(outputs);
        ExMatrix actualOutput = internalForward(cg, input, 0, layers.length);
        return new DMatrix[]{actualOutput, cg.applyLoss(testLoss, actualOutput, targetOutput, true)};
    }

    public DMatrix predictVec(DMatrix inputs) {
        ProcessGraph cg = new ProcessGraph(random, false);
        ExMatrix input = ExMatrix.createFromW(inputs);
        ExMatrix actualOutput = internalForward(cg, input, 0, layers.length);
        return actualOutput.getW();
    }

    public final void finalLearn() {
        learner.finalUpdate(layers);
    }

    public void resetState() {
        for (int i = 0; i < layers.length; i++) {
            layers[i].resetState();
        }
    }

    public double[] predict(double[] inputs) {
        ProcessGraph cg = new ProcessGraph(random, false);
        ExMatrix input = ExMatrix.createFromW(VolatileDMatrix.wrap(inputs, inputs.length, 1));
        ExMatrix actualOutput = internalForward(cg, input, 0, layers.length);
        return actualOutput.data();
    }

    public double[] forward(double[] inputs, int offset, int numOfLayers) {
        ProcessGraph cg = new ProcessGraph(random, false);
        ExMatrix input = ExMatrix.createFromW(VolatileDMatrix.wrap(inputs, inputs.length, 1));
        ExMatrix actualOutput = internalForward(cg, input, offset, numOfLayers);
        return actualOutput.data();
    }

    public DMatrix forwardVec(DMatrix inputs, int offset, int numOfLayers) {
        ProcessGraph cg = new ProcessGraph(random, false);
        ExMatrix input = ExMatrix.createFromW(inputs);
        ExMatrix actualOutput = internalForward(cg, input, offset, numOfLayers);
        return actualOutput.getW();
    }

    private ExMatrix internalForward(ProcessGraph cg, ExMatrix input, int offset, int numOfLayers) {
        ExMatrix nextInput = input;
        for (int i = offset; i < offset + numOfLayers; i++) {
            nextInput = layers[i].forward(nextInput, cg);
        }
        return nextInput;
    }

    private void internal_add(Layer layer) {
        Layer[] temp = new Layer[layers.length + 1];
        System.arraycopy(layers, 0, temp, 0, layers.length);
        temp[layers.length] = layer;
        layers = temp;
    }

    public Layer[] getLayers() {
        return this.layers;
    }

    public void printNN(boolean details) {
        for (Layer l : layers) {
            l.print(details);
        }
    }
}


text:
using System.Linq;
using GammaJul.ReSharper.EnhancedTooltip.Presentation;
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Lookup;
using JetBrains.ReSharper.Feature.Services.ParameterInfo;
using JetBrains.ReSharper.Psi;
using JetBrains.UI.RichText;
using JetBrains.Util;

namespace GammaJul.ReSharper.EnhancedTooltip.ParameterInfo {

	/// <summary>
	/// Wraps an existing <see cref="ParameterInfoCandidate"/>
	/// and override its <see cref="ICandidate.GetSignature"/> method to provide colored parameter info.
	/// </summary>
	public class EnhancedParameterInfoCandidate : EnhancedCandidate<ParameterInfoCandidate> {

		private readonly ColorizerPresenter _colorizerPresenter;

		protected override PresenterOptions GetPresenterOptions(IContextBoundSettingsStore settings, AnnotationsDisplayKind showAnnotations)
			=> PresenterOptions.ForParameterInfo(settings, showAnnotations.ToAttributesDisplayKind());

		protected override RichText? TryGetSignatureCore(
			PresenterOptions options,
			HighlighterIdProvider highlighterIdProvider,
			out TextRange[] parameterRanges,
			out int[] mapToOriginalOrder,
			out ExtensionMethodInfo extensionMethodInfo) {

			parameterRanges = EmptyArray<TextRange>.Instance;
			mapToOriginalOrder = EmptyArray<int>.Instance;
			extensionMethodInfo = ExtensionMethodInfo.NoExtension;

			var (declaredElement, substitution) = UnderlyingCandidate.InvocationCandidate;
			var elementInstance = new DeclaredElementInstance(declaredElement, substitution);
			RichText? richText = _colorizerPresenter.TryPresent(elementInstance, options, UnderlyingCandidate.Language, highlighterIdProvider, null, out PresentedInfo presentedInfo);
			if (richText is null)
				return null;

			if (presentedInfo.Parameters.Count > 0) {
				if (presentedInfo.IsExtensionMethod && UnderlyingCandidate.InvocationCandidate.IsExtensionMethodInvocation) {
					parameterRanges = presentedInfo.Parameters.Skip(1).ToArray();
					mapToOriginalOrder = CreateIdentityMap(presentedInfo.Parameters.Count - 1);
					extensionMethodInfo = new ExtensionMethodInfo(presentedInfo.Parameters[0], TextRange.InvalidRange);
				}
				else {
					parameterRanges = presentedInfo.Parameters.ToArray();
					mapToOriginalOrder = CreateIdentityMap(presentedInfo.Parameters.Count);
				}
			}

			return richText;
		}

		private static int[] CreateIdentityMap(int length) {
			var map = new int[length];
			for (int i = 0; i < length; ++i)
				map[i] = i;
			return map;
		}

		public EnhancedParameterInfoCandidate(
			ParameterInfoCandidate underlyingCandidate,
			IContextBoundSettingsStore settings,
			HighlighterIdProviderFactory highlighterIdProviderFactory,
			ColorizerPresenter colorizerPresenter)
			: base(underlyingCandidate, settings, highlighterIdProviderFactory) {
			_colorizerPresenter = colorizerPresenter;
		}

	}

}


text:
#ifndef __UART_H__
#define __UART_H__

#define UART_BASE 0x09000000

/**
 * @brief Put a character on uart data buffer
 *
 * @param c byte to be sent out
 */
void uputc(char c);

/**
 * @brief Get a character from uart data buffer
 *
 * @return int byte read from the uart data register
 */
int ugetc(void);

/**
 * @brief Init the uart, set baud etc
 *
 */
void uart_init(void);

#endif


text:
(function() {
    'use strict';

    angular
        .module('icms.stage.resource')
        .factory('Song', Song);

    Song.$inject = ['$resource'];
    function Song($resource) {
        return $resource('http://localhost:8001/songs/:songId/', {songId:'@id'}, {
            update: {method:'PUT'}
        }, {stripTrailingSlashes: false});
    }

})();


text:
{-
HAAP: Haskell Automated Assessment Platform

This module provides functions for injecting basic PHP authentication into HTML files.

TODO: generalize login database format.
-}

{-# LANGUAGE OverloadedStrings #-}

module HAAP.Web.PHP.Login where

import HAAP.Utils

import Hakyll

import System.FilePath

phpRoute :: Routes
phpRoute = customRoute $ \iden -> case takeExtension (toFilePath iden) of
    ".html" -> replaceExtension (toFilePath iden) "php"
    otherwise -> toFilePath iden

phpFunRoute :: FilePath -> FilePath
phpFunRoute = \iden -> case takeExtension iden of
    ".html" -> replaceExtension iden "php"
    otherwise -> iden

addPHPLogin :: FilePath -> Item String -> Compiler (Item String)
addPHPLogin logindb a = do
    Just dest <- getUnderlying >>= getRoute
    let phpCtx = constField "code" (itemBody a)
               `mappend` constField "logindb" (fileToRoot dest </> logindb)
    loadAndApplyTemplate "templates/login.php" phpCtx a


text:
![TEST](images/install-step-1.png "TEST")

This is the first step of the install / edition process of the Entity Manager. You may define:

 * The **source directory**: the directory here your classes are located, as defined in your composer.json file
 * **Entities Namespace:** the Namespace of your entities (Model Classes)
 * **Proxy Namespace:** the Namespace of the Proxies (mainly used for implementing Lazy loading)
 * **DAO Namespace:** the Namespace for you the DAOs (partly generated)

> **Note:** this package was built for PSR compliant projects. The DAO Namespace value will be used to generate DAO classes (see [Generated DAO classes](daos.md))

Next Step : [Schema Update](schema.md)


text:
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, Directive } from '@angular/core';
import { DayHoverEvent, DayViewModel } from '../../models/index';

@Component({
  selector: '[bsDatepickerDayDecorator]',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.disabled]': 'day.isDisabled',
    '[class.is-highlighted]': 'day.isHovered',
    '[class.is-other-month]': 'day.isOtherMonth',
    '[class.in-range]': 'day.isInRange',
    '[class.select-start]': 'day.isSelectionStart',
    '[class.select-end]': 'day.isSelectionEnd',
    '[class.selected]': 'day.isSelected'
  },
  template: `{{ day.label }}`
})
export class BsDatepickerDayDecoratorComponent {
  @Input() day: DayViewModel;
}


text:
package org.openprovenance.elmo;
import java.util.Set;
import org.openprovenance.rdf.Account;
import org.openprovenance.rdf.Node;

import javax.xml.namespace.QName;
import org.openrdf.elmo.ElmoManager;
import org.openprovenance.model.Annotable;
import org.openrdf.model.Statement;
import org.openrdf.elmo.sesame.SesameManager;

import org.openprovenance.model.CommonURIs;

public class RdfLabel extends org.openprovenance.model.Label implements CompactAnnotation, CommonURIs {

    ElmoManager manager;
    String prefix;
    QName qname;

    static int count=0;

    public RdfLabel(ElmoManager manager, String prefix) {
        this.manager=manager;
        this.prefix=prefix;
    }

    public void toRdf(Annotable entity) throws org.openrdf.repository.RepositoryException {
        org.openprovenance.rdf.Annotable subject=(org.openprovenance.rdf.Annotable)((HasFacade)entity).findMyFacade();
        subject.getLabels().add(getValue());
    }

    public void toRdf_DELETE(Annotable entity) throws org.openrdf.repository.RepositoryException {
        QName subject=((HasFacade)entity).getQName();
        Statement stmnt=new org.openrdf.model.impl.StatementImpl(new org.openrdf.model.impl.URIImpl(subject.getNamespaceURI()+subject.getLocalPart()),
                                                                 new org.openrdf.model.impl.URIImpl(NEW_LABEL_PROPERTY),
                                                                 new org.openrdf.model.impl.LiteralImpl(getValue()));

        ((SesameManager)manager).getConnection().add(stmnt);

    }

}


text:
module Ruby
  class Node
    module Traversal
      def select(*args, &block)
        result = []
        result << self if matches?(args.dup, &block)

        children = (prolog.try(:elements).to_a || []) + nodes
        children.flatten.compact.inject(result) do |result, node|
          result + node.select(*args, &block)
        end
      end

      def matches?(args, &block)
        conditions = args.last.is_a?(::Hash) ? args.pop : {}
        conditions[:is_a] = args unless args.empty?

        conditions.inject(!conditions.empty?) do |result, (type, value)|
          result && case type
          when :is_a
            has_type?(value)
          when :class
            is_instance_of?(value)
          when :token
            has_token?(value)
          when :value
            has_value?(value)
          when :pos, :position
            position?(value)
          when :right_of
            right_of?(value)
          when :left_of
            left_of?(value)
          end
        end && (!block_given? || block.call(self))
      end

      def has_type?(klass)
        case klass
        when ::Array
          klass.each { |klass| return true if has_type?(klass) } and false
        else
          is_a?(klass) # allow to pass a symbol or string, too
        end
      end

      def is_instance_of?(klass)
        case klass
        when ::Array
          klass.each { |klass| return true if has_type?(klass) } and false
        else
          instance_of?(klass) # allow to pass a symbol or string, too
        end
      end

      def has_token?(token)
        case token
        when ::Array
          type.each { |type| return true if has_token?(token) } and false
        else
          self.token == token
        end if respond_to?(:token)
      end

      def has_value?(value)
        self.value == value if respond_to?(:value)
      end

      def position?(pos)
        position == pos
      end

      def left_of?(right)
        right.nil? || self.position < right.position
      end

      def right_of?(left)
        left.nil? || left.position < self.position
      end
    end
  end
end


text:
<?php

namespace bouquins\BackBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DashboardController extends Controller
{
    public function indexAction()
    {
        return $this->render('bouquinsBackBundle:Dashboard:dashboard.html.twig');
    }
}


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

Lista de productos/servicios

                <form class="modal-form-search">
                    <input type="hidden" name="search-data-model" value="products"/>

                                Buscar
                                <input id="search-data" class="form-control search-data" type="text" name="search-data-value" aria-describedby="span-search-data">

                                    <input type="radio" name="search-data-column" value="product_name" checked> Nombre

                                    <input type="radio" name="search-data-column" value="product_reference"> Referencia

                </form>

                        No existen productos registrados.


text:
package multipoint

import (
	"context"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
	framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
)

// CommunicatingPlugin is an example of a plugin that implements two
// extension points. It communicates through state with another function.
type CommunicatingPlugin struct{}

var _ framework.ReservePlugin = CommunicatingPlugin{}
var _ framework.PreBindPlugin = CommunicatingPlugin{}

// Name is the name of the plugin used in Registry and configurations.
const Name = "multipoint-communicating-plugin"

// Name returns name of the plugin. It is used in logs, etc.
func (mc CommunicatingPlugin) Name() string {
	return Name
}

type stateData struct {
	data string
}

func (s *stateData) Clone() framework.StateData {
	copy := &stateData{
		data: s.data,
	}
	return copy
}

// Reserve is the function invoked by the framework at "reserve" extension point.
func (mc CommunicatingPlugin) Reserve(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status {
	if pod == nil {
		return framework.NewStatus(framework.Error, "pod cannot be nil")
	}
	if pod.Name == "my-test-pod" {
		state.Lock()
		state.Write(framework.StateKey(pod.Name), &stateData{data: "never bind"})
		state.Unlock()
	}
	return nil
}

// Unreserve is the function invoked by the framework when any error happens
// during "reserve" extension point or later.
func (mc CommunicatingPlugin) Unreserve(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) {
	if pod.Name == "my-test-pod" {
		state.Lock()
		// The pod is at the end of its lifecycle -- let's clean up the allocated
		// resources. In this case, our clean up is simply deleting the key written
		// in the Reserve operation.
		state.Delete(framework.StateKey(pod.Name))
		state.Unlock()
	}
}

// PreBind is the function invoked by the framework at "prebind" extension point.
func (mc CommunicatingPlugin) PreBind(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status {
	if pod == nil {
		return framework.NewStatus(framework.Error, "pod cannot be nil")
	}
	state.RLock()
	defer state.RUnlock()
	if v, e := state.Read(framework.StateKey(pod.Name)); e == nil {
		if value, ok := v.(*stateData); ok && value.data == "never bind" {
			return framework.NewStatus(framework.Unschedulable, "pod is not permitted")
		}
	}
	return nil
}

// New initializes a new plugin and returns it.
func New(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
	return &CommunicatingPlugin{}, nil
}


text:
{{extend 'item/item_layout.html'}}

      {{=T('META changelog')}} {{=item.headline}}

        {{=T('''
        Current item metadata version by %(first_name)s %(last_name)s on %(date_time)s
        ''') % dict(
          first_name=db.auth_user(item.modified_by).first_name,
          last_name=db.auth_user(item.modified_by).last_name,
          date_time=item.modified_on
        )}}

  {{if changes.rows:}}
    {{=changes}}
  {{pass}}

    {{if application.getContentChangesURL(item.unique_id):}}

            {{=T('Content changes')}}

    {{pass}}


text:
package com.unicorn.utilities;

import java.util.HashMap;

import com.unicorn.project.Constant;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class AuthAgent {
	public static final AuthAgent mAuthAgent = new AuthAgent();

	public AuthAgent() {
	}

	public static AuthAgent getInstance() {
		return mAuthAgent;
	}

	public static String AUTH_UUID = "UUID";
	public static String AUTH_RegistrationID = "RegistrationID";
	public static String AUTH_loginedUserID = "loginedUserID";
	public static String AUTH_loginedUserName = "loginedUserName";
	public static String AUTH_loginedUserFirstName = "loginedUserFirstName";
	public static String AUTH_loginedUserLastName = "loginedUserLastName";
	public static String AUTH_loginedUserProfileImageURL = "loginedUserProfileImageURL";
	public static String AUTH_userID = "userID";
	public static String AUTH_IDSearchedAllow = "IDSearchedAllow";
	public static String AUTH_Telephone = "telephone";
	public static String AUTH_CountryCode = "countryCode";
	public static String AUTH_Mailaddress = "mailaddress";
	public static String AUTH_Birthday = "auth_birthday";
	public static String AUTH_Gender = "auth_gender";
	public static String AUTH_New = "new";

	private static String[] removeType = { "RegistrationID", "loginedUserID", "loginedUserName",
			"loginedUserFirstName", "loginedUserLastName", "loginedUserProfileImageURL", "userID",
			"IDSearchedAllow", "telephone", "countryCode", "mailaddress", "auth_birthday",
			"auth_gender", "new" };

	// tokenの一時保管場所・・
	private String AUTH_Token = null;

	private SharedPreferences mPref = null;
	private SharedPreferences.Editor mEditor;
	private HashMap<String, String> mUserData = new HashMap<String, String>();

	/**
	 * ユーザデータを取得する
	 *
	 * @param context
	 *            コンテキスト
	 * @param type
	 *            取得したいデータのタイプを設定すること。AuthAgent.AUTH_・・のうち、どれかを選択すること
	 * @return 指定したデータをStringで返す。値がない場合はnullを返す
	 */
	public String getData(Context context, String type) {

		if (null == mUserData.get(type)) {
			if (null == mPref) {
				mPref = context.getSharedPreferences(Constant.SHAREPREF_KEY, Activity.MODE_PRIVATE);
			}
			mUserData.put(type, mPref.getString(type, ""));
		}

		if (mUserData.get(type).equals("")) {
			return null;
		} else {
			return mUserData.get(type);
		}
	}

	/**
	 * ユーザデータを設定する
	 *
	 * @param context
	 *            コンテキスト
	 * @param type
	 *            設定したいデータのタイプを設定すること。AuthAgent.AUTH_・・のうち、どれかを選択すること
	 * @param arg
	 *            設定したい値
	 */
	public void setData(Context context, String type, String arg) {
		if (null == type) {
			// nullだったら何もせずにreturn
			return;
		}

		if (null == mPref) {
			mPref = context.getSharedPreferences(Constant.SHAREPREF_KEY, Activity.MODE_PRIVATE);
		}
		if (null != arg) {
			mUserData.put(type, arg);
		} else {
			if (mUserData.containsKey(type)) {
				mUserData.remove(type);
			}
		}

		mEditor = mPref.edit();
		if (null != arg) {
			mEditor.putString(type, arg);
		} else {
			mEditor.remove(type);
		}
		mEditor.commit();

	}

	public void removeAllData(Context context) {
		if (null == mPref) {
			mPref = context.getSharedPreferences(Constant.SHAREPREF_KEY, Activity.MODE_PRIVATE);
		}

		for (String type : removeType) {
			if (mUserData.containsKey(type)) {
				mUserData.remove(type);
			}

			mEditor = mPref.edit();
			mEditor.remove(type);
			mEditor.commit();
		}
	}

	public void setToken(String token) {
		AUTH_Token = token;
	}

	public String getToken() {
		return AUTH_Token;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.web.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/web-project/3">
            <name>FramesLinks</name>
            <minimum-ant-version>1.6.5</minimum-ant-version>
            <web-module-libraries/>
            <web-module-additional-libraries/>
            <source-roots>
                <root id="src.dir" name="Source Packages"/>
            </source-roots>
            <test-roots>
                <root id="test.src.dir" name="Test Packages"/>
            </test-roots>
        </data>
    </configuration>
</project>


text:
<!DOCTYPE html>
<title>Canvas tests - 2d.pattern.image.*</title>
<link rel="stylesheet" href="../frame.css">

[index]

2d.pattern.image.*

(iframe fallback)(iframe fallback)(iframe fallback)(iframe fallback)(iframe fallback)


text:
package org.elasticsearch.search.aggregations;

import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.memory.MemoryIndex;
import org.apache.lucene.search.Scorer;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.MockBigArrays;
import org.elasticsearch.common.util.MockPageCacheRecycler;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.same;
import static org.mockito.Mockito.verifyNoMoreInteractions;

public class MultiBucketAggregatorWrapperTests extends ESTestCase {

    public void testNoNullScorerIsDelegated() throws Exception {
        LeafReaderContext leafReaderContext = MemoryIndex.fromDocument(Collections.emptyList(), new MockAnalyzer(random()))
                .createSearcher().getIndexReader().leaves().get(0);
        BigArrays bigArrays = new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), new NoneCircuitBreakerService());
        SearchContext searchContext = mock(SearchContext.class);
        when(searchContext.bigArrays()).thenReturn(bigArrays);

        Aggregator aggregator = mock(Aggregator.class);
        AggregatorFactory aggregatorFactory = new TestAggregatorFactory(searchContext, aggregator);
        LeafBucketCollector wrappedCollector = mock(LeafBucketCollector.class);
        when(aggregator.getLeafCollector(leafReaderContext)).thenReturn(wrappedCollector);
        Aggregator wrapper = AggregatorFactory.asMultiBucketAggregator(aggregatorFactory, searchContext, null);

        LeafBucketCollector collector = wrapper.getLeafCollector(leafReaderContext);

        collector.collect(0, 0);
        // setScorer should not be invoked as it has not been set
        // Only collect should be invoked:
        verify(wrappedCollector).collect(0, 0);
        verifyNoMoreInteractions(wrappedCollector);

        reset(wrappedCollector);
        Scorer scorer = mock(Scorer.class);
        collector.setScorer(scorer);
        collector.collect(0, 1);
        verify(wrappedCollector).setScorer(same(scorer));
        verify(wrappedCollector).collect(0, 0);
        verifyNoMoreInteractions(wrappedCollector);
        wrapper.close();
    }

    static class TestAggregatorFactory extends AggregatorFactory {

        private final Aggregator aggregator;

        TestAggregatorFactory(SearchContext context, Aggregator aggregator) throws IOException {
            super("_name", context, null, new AggregatorFactories.Builder(), Collections.emptyMap());
            this.aggregator = aggregator;
        }

        @Override
        protected Aggregator createInternal(Aggregator parent, boolean collectsFromSingleBucket, List list,
                                            Map metaData) throws IOException {
            return aggregator;
        }
    }

}


text:
package org.wso2.carbon.apimgt.rest.api.store.v1.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.wso2.carbon.apimgt.rest.api.store.v1.dto.SettingsIdentityProviderDTO;
import javax.validation.constraints.*;

import io.swagger.annotations.*;
import java.util.Objects;

import javax.xml.bind.annotation.*;
import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope;
import com.fasterxml.jackson.annotation.JsonCreator;

import javax.validation.Valid;

public class SettingsDTO   {

    private List<String> grantTypes = new ArrayList<String>();
    private List<String> scopes = new ArrayList<String>();
    private Boolean applicationSharingEnabled = false;
    private Boolean mapExistingAuthApps = false;
    private String apiGatewayEndpoint = null;
    private Boolean monetizationEnabled = false;
    private Boolean recommendationEnabled = false;
    private Boolean isUnlimitedTierPaid = false;
    private SettingsIdentityProviderDTO identityProvider = null;
    private Boolean isAnonymousModeEnabled = true;
    private Boolean isPasswordChangeEnabled = true;
    private String userStorePasswordPattern = null;
    private String passwordPolicyPattern = null;
    private Integer passwordPolicyMinLength = null;
    private Integer passwordPolicyMaxLength = null;

  /**
   **/
  public SettingsDTO grantTypes(List<String> grantTypes) {
    this.grantTypes = grantTypes;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("grantTypes")
  public List<String> getGrantTypes() {
    return grantTypes;
  }
  public void setGrantTypes(List<String> grantTypes) {
    this.grantTypes = grantTypes;
  }

  /**
   **/
  public SettingsDTO scopes(List<String> scopes) {
    this.scopes = scopes;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("scopes")
  public List<String> getScopes() {
    return scopes;
  }
  public void setScopes(List<String> scopes) {
    this.scopes = scopes;
  }

  /**
   **/
  public SettingsDTO applicationSharingEnabled(Boolean applicationSharingEnabled) {
    this.applicationSharingEnabled = applicationSharingEnabled;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("applicationSharingEnabled")
  public Boolean isApplicationSharingEnabled() {
    return applicationSharingEnabled;
  }
  public void setApplicationSharingEnabled(Boolean applicationSharingEnabled) {
    this.applicationSharingEnabled = applicationSharingEnabled;
  }

  /**
   **/
  public SettingsDTO mapExistingAuthApps(Boolean mapExistingAuthApps) {
    this.mapExistingAuthApps = mapExistingAuthApps;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("mapExistingAuthApps")
  public Boolean isMapExistingAuthApps() {
    return mapExistingAuthApps;
  }
  public void setMapExistingAuthApps(Boolean mapExistingAuthApps) {
    this.mapExistingAuthApps = mapExistingAuthApps;
  }

  /**
   **/
  public SettingsDTO apiGatewayEndpoint(String apiGatewayEndpoint) {
    this.apiGatewayEndpoint = apiGatewayEndpoint;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("apiGatewayEndpoint")
  public String getApiGatewayEndpoint() {
    return apiGatewayEndpoint;
  }
  public void setApiGatewayEndpoint(String apiGatewayEndpoint) {
    this.apiGatewayEndpoint = apiGatewayEndpoint;
  }

  /**
   **/
  public SettingsDTO monetizationEnabled(Boolean monetizationEnabled) {
    this.monetizationEnabled = monetizationEnabled;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("monetizationEnabled")
  public Boolean isMonetizationEnabled() {
    return monetizationEnabled;
  }
  public void setMonetizationEnabled(Boolean monetizationEnabled) {
    this.monetizationEnabled = monetizationEnabled;
  }

  /**
   **/
  public SettingsDTO recommendationEnabled(Boolean recommendationEnabled) {
    this.recommendationEnabled = recommendationEnabled;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("recommendationEnabled")
  public Boolean isRecommendationEnabled() {
    return recommendationEnabled;
  }
  public void setRecommendationEnabled(Boolean recommendationEnabled) {
    this.recommendationEnabled = recommendationEnabled;
  }

  /**
   **/
  public SettingsDTO isUnlimitedTierPaid(Boolean isUnlimitedTierPaid) {
    this.isUnlimitedTierPaid = isUnlimitedTierPaid;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("IsUnlimitedTierPaid")
  public Boolean isIsUnlimitedTierPaid() {
    return isUnlimitedTierPaid;
  }
  public void setIsUnlimitedTierPaid(Boolean isUnlimitedTierPaid) {
    this.isUnlimitedTierPaid = isUnlimitedTierPaid;
  }

  /**
   **/
  public SettingsDTO identityProvider(SettingsIdentityProviderDTO identityProvider) {
    this.identityProvider = identityProvider;
    return this;
  }

  @ApiModelProperty(value = "")
      @Valid
  @JsonProperty("identityProvider")
  public SettingsIdentityProviderDTO getIdentityProvider() {
    return identityProvider;
  }
  public void setIdentityProvider(SettingsIdentityProviderDTO identityProvider) {
    this.identityProvider = identityProvider;
  }

  /**
   **/
  public SettingsDTO isAnonymousModeEnabled(Boolean isAnonymousModeEnabled) {
    this.isAnonymousModeEnabled = isAnonymousModeEnabled;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("IsAnonymousModeEnabled")
  public Boolean isIsAnonymousModeEnabled() {
    return isAnonymousModeEnabled;
  }
  public void setIsAnonymousModeEnabled(Boolean isAnonymousModeEnabled) {
    this.isAnonymousModeEnabled = isAnonymousModeEnabled;
  }

  /**
   **/
  public SettingsDTO isPasswordChangeEnabled(Boolean isPasswordChangeEnabled) {
    this.isPasswordChangeEnabled = isPasswordChangeEnabled;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("IsPasswordChangeEnabled")
  public Boolean isIsPasswordChangeEnabled() {
    return isPasswordChangeEnabled;
  }
  public void setIsPasswordChangeEnabled(Boolean isPasswordChangeEnabled) {
    this.isPasswordChangeEnabled = isPasswordChangeEnabled;
  }

  /**
   * The 'PasswordJavaRegEx' cofigured in the UserStoreManager
   **/
  public SettingsDTO userStorePasswordPattern(String userStorePasswordPattern) {
    this.userStorePasswordPattern = userStorePasswordPattern;
    return this;
  }

  @ApiModelProperty(value = "The 'PasswordJavaRegEx' cofigured in the UserStoreManager")
  @JsonProperty("userStorePasswordPattern")
  public String getUserStorePasswordPattern() {
    return userStorePasswordPattern;
  }
  public void setUserStorePasswordPattern(String userStorePasswordPattern) {
    this.userStorePasswordPattern = userStorePasswordPattern;
  }

  /**
   * The regex configured in the Password Policy property 'passwordPolicy.pattern'
   **/
  public SettingsDTO passwordPolicyPattern(String passwordPolicyPattern) {
    this.passwordPolicyPattern = passwordPolicyPattern;
    return this;
  }

  @ApiModelProperty(value = "The regex configured in the Password Policy property 'passwordPolicy.pattern'")
  @JsonProperty("passwordPolicyPattern")
  public String getPasswordPolicyPattern() {
    return passwordPolicyPattern;
  }
  public void setPasswordPolicyPattern(String passwordPolicyPattern) {
    this.passwordPolicyPattern = passwordPolicyPattern;
  }

  /**
   * If Password Policy Feature is enabled, the property 'passwordPolicy.min.length' is returned as the 'passwordPolicyMinLength'. If password policy is not enabled, default value -1 will be returned. And it should be noted that the regex pattern(s) returned in 'passwordPolicyPattern' and 'userStorePasswordPattern' properties too will affect the minimum password length allowed and an intersection of all conditions will be considered finally to validate the password.
   **/
  public SettingsDTO passwordPolicyMinLength(Integer passwordPolicyMinLength) {
    this.passwordPolicyMinLength = passwordPolicyMinLength;
    return this;
  }

  @ApiModelProperty(value = "If Password Policy Feature is enabled, the property 'passwordPolicy.min.length' is returned as the 'passwordPolicyMinLength'. If password policy is not enabled, default value -1 will be returned. And it should be noted that the regex pattern(s) returned in 'passwordPolicyPattern' and 'userStorePasswordPattern' properties too will affect the minimum password length allowed and an intersection of all conditions will be considered finally to validate the password.")
  @JsonProperty("passwordPolicyMinLength")
  public Integer getPasswordPolicyMinLength() {
    return passwordPolicyMinLength;
  }
  public void setPasswordPolicyMinLength(Integer passwordPolicyMinLength) {
    this.passwordPolicyMinLength = passwordPolicyMinLength;
  }

  /**
   * If Password Policy Feature is enabled, the property 'passwordPolicy.max.length' is returned as the 'passwordPolicyMaxLength'. If password policy is not enabled, default value -1 will be returned. And it should be noted that the regex pattern(s) returned in 'passwordPolicyPattern' and 'userStorePasswordPattern' properties too will affect the maximum password length allowed and an intersection of all conditions will be considered finally to validate the password.
   **/
  public SettingsDTO passwordPolicyMaxLength(Integer passwordPolicyMaxLength) {
    this.passwordPolicyMaxLength = passwordPolicyMaxLength;
    return this;
  }

  @ApiModelProperty(value = "If Password Policy Feature is enabled, the property 'passwordPolicy.max.length' is returned as the 'passwordPolicyMaxLength'. If password policy is not enabled, default value -1 will be returned. And it should be noted that the regex pattern(s) returned in 'passwordPolicyPattern' and 'userStorePasswordPattern' properties too will affect the maximum password length allowed and an intersection of all conditions will be considered finally to validate the password.")
  @JsonProperty("passwordPolicyMaxLength")
  public Integer getPasswordPolicyMaxLength() {
    return passwordPolicyMaxLength;
  }
  public void setPasswordPolicyMaxLength(Integer passwordPolicyMaxLength) {
    this.passwordPolicyMaxLength = passwordPolicyMaxLength;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    SettingsDTO settings = (SettingsDTO) o;
    return Objects.equals(grantTypes, settings.grantTypes) &&
        Objects.equals(scopes, settings.scopes) &&
        Objects.equals(applicationSharingEnabled, settings.applicationSharingEnabled) &&
        Objects.equals(mapExistingAuthApps, settings.mapExistingAuthApps) &&
        Objects.equals(apiGatewayEndpoint, settings.apiGatewayEndpoint) &&
        Objects.equals(monetizationEnabled, settings.monetizationEnabled) &&
        Objects.equals(recommendationEnabled, settings.recommendationEnabled) &&
        Objects.equals(isUnlimitedTierPaid, settings.isUnlimitedTierPaid) &&
        Objects.equals(identityProvider, settings.identityProvider) &&
        Objects.equals(isAnonymousModeEnabled, settings.isAnonymousModeEnabled) &&
        Objects.equals(isPasswordChangeEnabled, settings.isPasswordChangeEnabled) &&
        Objects.equals(userStorePasswordPattern, settings.userStorePasswordPattern) &&
        Objects.equals(passwordPolicyPattern, settings.passwordPolicyPattern) &&
        Objects.equals(passwordPolicyMinLength, settings.passwordPolicyMinLength) &&
        Objects.equals(passwordPolicyMaxLength, settings.passwordPolicyMaxLength);
  }

  @Override
  public int hashCode() {
    return Objects.hash(grantTypes, scopes, applicationSharingEnabled, mapExistingAuthApps, apiGatewayEndpoint, monetizationEnabled, recommendationEnabled, isUnlimitedTierPaid, identityProvider, isAnonymousModeEnabled, isPasswordChangeEnabled, userStorePasswordPattern, passwordPolicyPattern, passwordPolicyMinLength, passwordPolicyMaxLength);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class SettingsDTO {\n");

    sb.append("    grantTypes: ").append(toIndentedString(grantTypes)).append("\n");
    sb.append("    scopes: ").append(toIndentedString(scopes)).append("\n");
    sb.append("    applicationSharingEnabled: ").append(toIndentedString(applicationSharingEnabled)).append("\n");
    sb.append("    mapExistingAuthApps: ").append(toIndentedString(mapExistingAuthApps)).append("\n");
    sb.append("    apiGatewayEndpoint: ").append(toIndentedString(apiGatewayEndpoint)).append("\n");
    sb.append("    monetizationEnabled: ").append(toIndentedString(monetizationEnabled)).append("\n");
    sb.append("    recommendationEnabled: ").append(toIndentedString(recommendationEnabled)).append("\n");
    sb.append("    isUnlimitedTierPaid: ").append(toIndentedString(isUnlimitedTierPaid)).append("\n");
    sb.append("    identityProvider: ").append(toIndentedString(identityProvider)).append("\n");
    sb.append("    isAnonymousModeEnabled: ").append(toIndentedString(isAnonymousModeEnabled)).append("\n");
    sb.append("    isPasswordChangeEnabled: ").append(toIndentedString(isPasswordChangeEnabled)).append("\n");
    sb.append("    userStorePasswordPattern: ").append(toIndentedString(userStorePasswordPattern)).append("\n");
    sb.append("    passwordPolicyPattern: ").append(toIndentedString(passwordPolicyPattern)).append("\n");
    sb.append("    passwordPolicyMinLength: ").append(toIndentedString(passwordPolicyMinLength)).append("\n");
    sb.append("    passwordPolicyMaxLength: ").append(toIndentedString(passwordPolicyMaxLength)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}