text:
<!doctype html>

<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="alternate" type="application/atom+xml" href="/news/feed.xml" title="Ruma" />

<meta http-equiv="Content-Security-Policy" content="
    default-src 'self';
    script-src 'none';
    style-src 'self' 'unsafe-inline';
    frame-src 'none'">

<title>This Week in Ruma | Ruma</title>

<link rel="stylesheet" href="/normalize.css">
<link rel="stylesheet" href="/site.css">

Home

News

Projects using Ruma

Donate on Liberapay

Documentation

            This Week in Ruma

        › published on
        <time datetime="2019-06-23" itemprop="datePublished">2019-06-23</time>
        by
        Jimmy Cuadra

From the editor

This week was spent working on a big revamp of ruma-events, the library that defines Rust types for the "events" used in Matrix.
The previous week, I did a pass through the entire library to bring it up to date with version r0.5.0 of the Matrix specification.

After some discussion in #ruma:matrix.org, I decided to make a move towards treating ruma-events as a higher-level library.
Previously, ruma-events has more or less offered Rust types that are exact representations of the JSON structures used by Matrix.
However, by representing events this way, it would be possible for users to easily create values that, while valid JSON, would be invalid events according to the specification.

The way we're approaching this problem is by separating serialization/deserialization of JSON from validation of events.
Rather than directly implementing serde::Deserialize, event types will be converted from a string of JSON data using std::str::FromStr.
This implementation will deserialize the data internally and then validate it, returning either a valid event, or a raw serde_json::Value along with an error message about why the event was invalid.
The latter form is necessary because invalid events will always be present in the Matrix system, created via bugs or other problems in homeserver implementations.
Once an event is in the event graph, other servers will receive these invalid events over federation, and must still persist them and deal with them as they are.

Similar to the new interface around deserialization, the serialized form of an event created by ruma-events may not directly match the structure of the Rust type.
ruma-events will instead expose variants of each event to ensure they can only be created in valid states.

To reduce the boilerplate that this approach necessarily causes (because for many events there will now be two structures: the public one and the private one used for converting to and from JSON), I started a new procedural macro, ruma-events-macros, to make the most common cases require minimal code in ruma-events.
It's been a lot of work, and there's still probably another week or more to go to finish implementing ruma-events using the new approach.
But when it's done, the result will be a Rust library for Matrix events that leaves less room for users to accidentally do the wrong thing, while also supporting interoperation with other Matrix software that isn't so strict.


text: docker build -t simple-nuget-server .

redpajama_set_name: RedPajamaGithub


text:
import { QualifiedName } from "node-opcua-data-model";
import { KeyValuePair } from "node-opcua-types";
import { DataType, Variant } from "node-opcua-variant";

describe("bug KeyValuePair", () => {
    it("KVP1: should create a KeyValuePair Variant", () => {
        const v = new Variant({
            dataType: DataType.ExtensionObject,
            value: new KeyValuePair({ key: "A", value: { dataType: DataType.String, value: "B" } })
        });

        v.value.key.name.should.eql("A");
        v.value.value.dataType.should.eql(DataType.String);
        v.value.value.value.should.eql("B");
    });
    it("KVP2: should create a KeyValue Pair", () => {
        const kv = new KeyValuePair({ key: "A", value: { dataType: DataType.String, value: "B" } });
        kv.key.should.be.instanceOf(QualifiedName);
        kv.key.name.should.eql("A");
        kv.value.dataType.should.eql(DataType.String);
        kv.value.value.should.eql("B");
    });
});


text:
<!DOCTYPE html>

 <title>CSS Reftest Reference</title>
 <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">


text:
package io.github.data4all.activity;

import static org.junit.Assert.assertNotNull;

import java.io.File;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import android.content.Intent;

@RunWith(RobolectricTestRunner.class)
@Config(emulateSdk = 18)
public class ShowPictureActivityTest {
    ShowPictureActivity activity;

    @Before
    public void setup() {
        this.activity = Robolectric.buildActivity(ShowPictureActivity.class)
                .get();
        Intent intent = new Intent();
        File test = new File("@drawable/android3");
        intent.putExtra("file_path", test);
        activity.setIntent(intent);
    }

    @Test
    public void shouldNotNull() throws Exception {
        assertNotNull(activity);
    }

    @Test
    public void getIntentFile() throws Exception {

    }

}


text:
const mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    crypto = require('crypto');

var User = new Schema({
    email: {
        type: String,
        unique: true
    },
    local: {
        username: {
            type: String,
            unique: true
        },
        password: String
    },
    google: {
        id: String,
        tokens: {
            access_token: { type: String },
            id_token: { type: String },
            refresh_token: { type: String },
            token_type: { type: String },
            expiry_date: { type: String }
        }
    },
    facebook: {
        id: String,
        token: String
    },
    root: String,
    unsorted: String,
    date: {
        type: Date,
        default: Date.now
    }
});

User.methods.validPassword = function(password) {
    return this.local.password === this.generateHash(password);
};

User.methods.generateHash = function(password) {
    return crypto.createHash('md5').update(password).digest('hex');
};

User.pre('save', function(next) {
    /* let pass = this.password;
    this.password = this.generateHash(pass);
    // console.log(crypto.createHash('md5').update('this.password').digest('hex')); */
    next();
});

module.exports = mongoose.model('User', User);


text:
function toggleUserSidebar (id) {
	$.post('/users/' + id + '/toggle_sidebar', function (data) {
		if (data) {
			console.log('Sidebar setting was toggled');
		} else {
			console.log('Could not toggle sidebar');
		}
	});
}

$(document).ready( function() {
  $('.file-input input[type="file"]').change( function() {
    var filename = $(this).val().replace(/\\/g, '/').replace(/.*\//, '');
    $('.filename').html( filename );
  });
});


text:
/*
 *  Chrono::Ingot
 *      Mass-based rigid body creation for Chrono::Engine
 *
 *  ingot_test.cpp
 */

#include <chrono_ingot/make_body.hpp>

using namespace chrono;
using namespace chrono::ingot;

namespace {
static const double eps = 1.e-10;
}

void ensure_mass(const std::shared_ptr<ChBody> body, const ChMass& mass) {
	assert(abs(body->GetMass() - mass.get_mass()) < eps);
}

void ensure_dens(const std::shared_ptr<ChBody> body, const ChDensity& dens) {
	assert(abs(body->GetDensity() - dens.get_density()) < eps);
}

int main(int , char* []) {
	const ChDensity dens(1000.);
	const ChMass mass(0.5);

	{
		const ChDimensions<ChBodyEasyBox> dim(0.5, 0.5, 0.5);
		ensure_mass(make_body(dim, mass), mass);
		ensure_dens(make_body(dim, dens), dens);
	}

	{
		const ChDimensions<ChBodyEasyCylinder> dim(0.5, 0.5);
		ensure_mass(make_body(dim, mass), mass);
		ensure_dens(make_body(dim, dens), dens);
	}

	{
		const ChDimensions<ChBodyEasySphere> dim(0.5);
		ensure_mass(make_body(dim, mass), mass);
		ensure_dens(make_body(dim, dens), dens);
	}

	{
		const ChDimensions<ChBodyEasyConvexHull> dim({ VNULL, ChVector<>(.5, 0., 0.), ChVector<>(0., .5, 0.), ChVector<>(0., 0., .5) });
		ensure_mass(make_body(dim, mass), mass);
		ensure_dens(make_body(dim, dens), dens);
	}

	{
		const ChDimensions<ChBodyEasyConvexHullAuxRef> dim({ VNULL, ChVector<>(.5, 0., 0.), ChVector<>(0., .5, 0.), ChVector<>(0., 0., .5) });
		ensure_mass(make_body(dim, mass), mass);
		ensure_dens(make_body(dim, dens), dens);
	}

	{
		const ChDimensions<ChBodyEasyClusterOfSpheres> dim({ VNULL, ChVector<>(.5, 0., 0.), ChVector<>(0., .5, 0.), ChVector<>(0., 0., .5) }, {.1, .2, .3, .4});
		ensure_mass(make_body(dim, mass), mass);
		ensure_dens(make_body(dim, dens), dens);
	}

	std::cout << "All assertions succeeded\n";
	return 0;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    package="fr.neamar.kiss"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionCode="48"
    android:versionName="2.6.4">

    <!-- Self explanatory -->
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <!-- To call a phone number directly without displaying the dialer -->
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <!-- To enable / disable cellular data -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <!-- To enable / disable wifi -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <!-- To enable / disable bluetooth -->
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <!-- Incoming SMS sender history -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <uses-feature
        android:name="android.hardware.telephony"
        android:required="false"/>
    <uses-feature
        android:name="android.hardware.bluetooth"
        android:required="false"/>
    <uses-feature
        android:name="android.hardware.wifi"
        android:required="false"/>

    <application
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <!--
        clearTaskOnLaunch: when viewing kiss settings, display the main activity when pressing home https://github.com/Neamar/KISS/issues/117
        launchMode=singleTop: call onNewIntent() when pressing home again while already viewing main activity, also redisplay main activity when viewing full-screen contact from picture
        windowSoftInputMode: hide keyboard by default
        stateNotNeeded: rebuild the whole UI each time onResume() is called
        -->
        <activity
            android:name=".MainActivity"
            android:clearTaskOnLaunch="true"
            android:excludeFromRecents="true"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:stateNotNeeded="true"
            android:windowSoftInputMode="stateAlwaysHidden|adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
                <category android:name="android.intent.category.HOME"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
        <activity
            android:name="fr.neamar.kiss.SettingsActivity"
            android:label="@string/activity_setting"
            android:theme="@style/SettingTheme">
        </activity>

        <!-- On new app installed, refresh the list -->
        <receiver android:name=".broadcast.NewAppInstalledHandler">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED"/>
                <action android:name="android.intent.action.PACKAGE_REMOVED"/>

                <data android:scheme="package"/>
            </intent-filter>
        </receiver>

        <!-- On incoming messages, add user to history -->
        <receiver android:name=".broadcast.IncomingSmsHandler">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>


text:
// Copyright ©2005, 2006 Freescale Semiconductor, Inc.
// Please see the License for the specific language governing rights and
// limitations under the License.

#ifndef _H_LGAColorSwatch
	#define _H_LGAColorSwatch
	#pragma once

#if defined (__CFM68K__) && !defined (__USING_STATIC_LIBS__)
	#pragma import on
#endif

// ¥ POWERPLANT HEADERS
#include <LPane.h>

//====================================================================================
//	OBJECT
//====================================================================================

class LGAColorSwatch : public LPane
{

	//====<< ¥ CLASS ID ¥ >>===========================================================

public:

	enum	{ class_ID = 'gswt' };

	//====<< ¥ FIELDS ¥ >>=============================================================

protected:

	RGBColor		mSwatchColor;		//	The color being displayed by the swatch

	//====<< ¥ METHODS ¥ >>============================================================

	//----<< ¥ INITIALIZATION & DISPOSAL ¥ >>------------------------------------------

public:

				LGAColorSwatch 		();						//	¥ Default Constructor
				LGAColorSwatch 		(	const LGAColorSwatch &inOriginal );
																		//	¥ Copy Constructor
				LGAColorSwatch 		(	LStream*	inStream );
																		//	¥ Stream	Constructor
				LGAColorSwatch			(	const SPaneInfo	&inPaneInfo,
												RGBColor				&inSwatchColor );
																		//	¥ Parameterized Constructor
	virtual	~LGAColorSwatch 		();						//	¥ Destructor

	//----<< ¥ ACCESSORS ¥ >>----------------------------------------------------------

	//	¥ GETTERS

	virtual	RGBColor		GetSwatchColor		()
										{	return mSwatchColor;	};

	//	¥ SETTERS

	virtual	void			SetSwatchColor		(	RGBColor		&inSwatchColor )
										{	mSwatchColor = inSwatchColor;	};

	//----<< ¥ ENABLING ¥ >>-----------------------------------------------------------

	virtual	void			EnableSelf			();									// ¥ OVERRIDE
	virtual	void			DisableSelf			();									// ¥ OVERRIDE

	//----<< ¥ ACTIVATION ¥ >>---------------------------------------------------------

	virtual 	void			ActivateSelf		();									// ¥ OVERRIDE
	virtual 	void			DeactivateSelf		();									// ¥ OVERRIDE

	//----<< ¥ DRAWING ¥ >>------------------------------------------------------------

	virtual	void			DrawSelf				();									// ¥ OVERRIDE

	//----<< ¥ CLICK HANDLING ¥ >>-----------------------------------------------------

	virtual	void		ClickSelf				( const SMouseDownEvent&	inMouseDown );
																								// ¥ OVERRIDE

};	// LGAColorSwatch

#if defined (__CFM68K__) && !defined (__USING_STATIC_LIBS__)
	#pragma import reset
#endif

#endif


text:
#include <QObject>

#include <pocas/gui/backend/qt.h>

class QEvent;

class Bqt_EventFilter : public QObject
{
    Q_OBJECT

public:
    struct FilterArgs
    {
        QEvent *event;
        bool filter;
    };

    Bqt_EventFilter();

signals:
    void eventOccured(Bqt_EventFilter::FilterArgs *args);

protected:
    virtual bool eventFilter(QObject *obj, QEvent *event);
};

#endif


text:
FROM nvidia/cuda:8.0-cudnn5-devel
MAINTAINER "Álvaro Barbero Jiménez, https://github.com/albarji"

# Install system dependencies
RUN set -ex && \
	apt-get update && apt-get install --no-install-recommends --no-install-suggests -y \
	ca-certificates \
	sudo \
	libprotobuf-dev \
	protobuf-compiler \
	wget \
	git \
	&& apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Install torch
RUN git clone https://github.com/torch/distro.git /root/torch --recursive && cd /root/torch && \
    bash install-deps
RUN cd /root/torch && ./install.sh
RUN ln -s /root/torch/install/bin/* /usr/local/bin

# Install additional necessary torch dependencies
RUN luarocks install loadcaffe && \
    luarocks install autograd

# Install Python miniconda3 + requirements
ENV MINICONDA_HOME="/opt/miniconda"
ENV PATH="${MINICONDA_HOME}/bin:${PATH}"
RUN curl -o Miniconda3-latest-Linux-x86_64.sh https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh \
  && chmod +x Miniconda3-latest-Linux-x86_64.sh \
  && ./Miniconda3-latest-Linux-x86_64.sh -b -p "${MINICONDA_HOME}" \
&& rm Miniconda3-latest-Linux-x86_64.sh
COPY conda.txt conda.txt
RUN conda install -y --file=conda.txt && \
    conda clean -y -i -l -p -t && \
    rm -f conda.txt
COPY pip.txt pip.txt
RUN pip install -r pip.txt && \
    rm -f pip.txt

# Clone neural-style app
WORKDIR /app
RUN set -ex && \
	wget --no-check-certificate https://github.com/jcjohnson/neural-style/archive/master.tar.gz && \
	tar -xvzf master.tar.gz && \
    mv neural-style-master neural-style && \
	rm master.tar.gz

# Download precomputed VGG network weights
WORKDIR /app/neural-style
RUN bash models/download_models.sh

# Add neural-style to path
ENV PATH /app/neural-style:$PATH

# Clone style-swap app
WORKDIR /app
RUN set -ex && \
	wget --no-check-certificate https://github.com/rtqichen/style-swap/archive/master.tar.gz && \
	tar -xvzf master.tar.gz && \
    mv style-swap-master style-swap && \
	rm master.tar.gz
# Link precomputed VGG network weights
RUN rm -rf /app/style-swap/models
RUN ln -s /app/neural-style/models /app/style-swap/models
# Add precomputed inverse network model
ADD models/dec-tconv-sigmoid.t7 /app/style-swap/models/dec-tconv-sigmoid.t7

# Copy wrapper scripts and config files
COPY ["entrypoint.py" ,"/app/entrypoint/"]
COPY ["/neuralstyle/*.py", "/app/entrypoint/neuralstyle/"]
COPY ["gpuconfig.json", "/app/entrypoint/"]

WORKDIR /app/entrypoint
ENTRYPOINT ["python", "/app/entrypoint/entrypoint.py"]


text:
import ctypes
from rpython.rtyper.lltypesystem import rffi
from rpython.rtyper.lltypesystem import lltype
from rpython.rlib.unroll import unrolling_iterable
from rpython.translator.tool.cbuild import ExternalCompilationInfo

import py

#rffi.UINT = rffi.INT # XXX
#rffi.UCHAR = lltype.Char # XXX

# XXX any automatic stuff here?
_TYPE_MAPPING = {
    ctypes.c_ubyte     : rffi.UCHAR,
    ctypes.c_byte      : rffi.CHAR,
    ctypes.c_char      : rffi.CHAR,
    ctypes.c_int8      : rffi.CHAR,
    ctypes.c_ushort    : rffi.USHORT,
    ctypes.c_short     : rffi.SHORT,
    ctypes.c_uint16    : rffi.USHORT,
    ctypes.c_int16     : rffi.SHORT,
    ctypes.c_int       : rffi.INT,
    ctypes.c_uint      : rffi.UINT,
    ctypes.c_int32     : rffi.INT,
    ctypes.c_uint32    : rffi.UINT,
    #ctypes.c_long      : rffi.LONG, # same as c_int..
    #ctypes.c_ulong     : rffi.ULONG,
    ctypes.c_longlong  : rffi.LONGLONG,
    ctypes.c_ulonglong : rffi.ULONGLONG,
    ctypes.c_int64     : rffi.LONGLONG,
    ctypes.c_uint64    : rffi.ULONGLONG,
    ctypes.c_voidp     : rffi.VOIDP,
    None               : rffi.lltype.Void, # XXX make a type in rffi
    ctypes.c_char_p    : rffi.CCHARP,
    ctypes.c_double    : rffi.lltype.Float, # XXX make a type in rffi
}

class RffiBuilder(object):
    def __init__(self, ns=None, includes=[], libraries=[], include_dirs=[]):
        if ns is None:
            # map name -> lltype object
            self.ns = {}
        else:
            self.ns = ns
        self.include_dirs = include_dirs

        CConfig = type('CConfig', (object,), {})
        CConfig._compilation_info_ = ExternalCompilationInfo(
            includes = list(includes),
            include_dirs = list(include_dirs),
            libraries = list(libraries),
        )

        self.CConfig = CConfig

    def proc_struct(self, tp):
        name = tp.__name__
        struct = self.ns.get(name)
        if struct is None:
            fields = []
            if not hasattr(tp, '_fields_'):
                raise NotImplementedError("no _fields")
            for field in tp._fields_:
                if len(field) != 2:
                    raise NotImplementedError("field length")
                name_, field_tp = field
                fields.append((name_, self.proc_tp(field_tp)))
            struct = lltype.Struct(name, *fields, **{'hints':{'external':'C', 'c_name':name}})
            self.ns[name] = struct
        return struct

    def proc_tp(self, tp):
        try:
            return _TYPE_MAPPING[tp]
        except KeyError:
            pass
        if issubclass(tp, ctypes._Pointer):
            if issubclass(tp._type_, ctypes._SimpleCData):
                x = self.proc_tp(tp._type_)
                ll_tp = lltype.Ptr(lltype.Array(x, hints={'nolength': True}))
            else:
                ll_tp = lltype.Ptr(self.proc_tp(tp._type_))
        elif issubclass(tp, ctypes.Structure):
            ll_tp = self.proc_struct(tp)
        else:
            raise NotImplementedError("Not implemented mapping for %s" % tp)
        _TYPE_MAPPING[tp] = ll_tp
        return ll_tp

    def proc_func(self, func):
        name = func.__name__
        arg_tps = [self.proc_tp(arg) for arg in func.argtypes]
        ll_item = rffi.llexternal(
            name, arg_tps,
            self.proc_tp(func.restype),
            compilation_info=self.CConfig._compilation_info_)
        self.ns[name] = ll_item
        return ll_item

    def proc_namespace(self, ns):
        exempt = set(id(value) for value in ctypes.__dict__.values())
        for key, value in ns.items():
            if id(value) in exempt:
                continue
            if isinstance(value, ctypes._CFuncPtr):
                try:
                    self.proc_func(value)
                except NotImplementedError, e:
                    print "genrffi: skipped:", key, value, e
                except TypeError, e:
                    print "genrffi: skipped:", key, value, e


text:
from functools import partial

import numpy as np

from pygsp import utils
# prevent circular import in Python < 3.5
from . import approximations
from ..graphs import Graph

_logger = utils.build_logger(__name__)

class Filter(object):
    r"""
    The base Filter class.

    * Provide a common interface (and implementation) to filter objects.
    * Can be instantiated to construct custom filters from functions.
    * Initialize attributes for derived classes.

    Parameters
    ----------
    G : graph
        The graph to which the filter bank is tailored.
    kernels : function or list of functions
        A (list of) function(s) defining the filter bank in the Fourier domain.
        One function per filter.

    Attributes
    ----------
    G : Graph
        The graph to which the filter bank was tailored. It is a reference to
        the graph passed when instantiating the class.
    n_features_in : int
        Number of signals or features the filter bank takes in.
    n_features_out : int
        Number of signals or features the filter bank gives out.
    n_filters : int
        Number of filters in the filter bank.

    Examples
    --------
    >>> G = graphs.Logo()
    >>> my_filter = filters.Filter(G, lambda x: x / (1. + x))
    >>>
    >>> # Signal: Kronecker delta.
    >>> signal = np.zeros(G.N)
    >>> signal[42] = 1
    >>>
    >>> filtered_signal = my_filter.filter(signal)

    """

    def __init__(self, G, kernels):

        self.G = G

        try:
            iter(kernels)
        except TypeError:
            kernels = [kernels]
        self._kernels = kernels

        # Only used by subclasses to instantiate a single filterbank.
        self.n_features_in, self.n_features_out = (1, len(kernels))
        self.shape = (self.n_features_out, self.n_features_in)
        self.n_filters = self.n_features_in * self.n_features_out
        self.Nf = self.n_filters  # TODO: kept for backward compatibility only.

    def _get_extra_repr(self):
        """To be overloaded by children."""
        return dict()

    def __repr__(self):
        attrs = {'in': self.n_features_in, 'out': self.n_features_out}
        attrs.update(self._get_extra_repr())
        s = ''
        for key, value in attrs.items():
            s += '{}={}, '.format(key, value)
        return '{}({})'.format(self.__class__.__name__, s[:-2])

    def __len__(self):
        # Numpy returns shape[0].
        return self.n_filters

    def __getitem__(self, key):
        return Filter(self.G, self._kernels[key])

    def __add__(self, other):
        """Concatenation of filterbanks."""
        if not isinstance(other, Filter):
            return NotImplemented
        return Filter(self.G, self._kernels + other._kernels)

    def __call__(self, x):
        if isinstance(x, Graph):
            return Filter(x, self._kernels)
        else:
            return self.evaluate(x)

    def __matmul__(self, other):
        return self.filter(other)

    def toarray(self):
        r"""Return an array representation of the filter bank.

        See :meth:`compute_frame`.
        """
        return self.compute_frame()

    def evaluate(self, x):
        r"""Evaluate the kernels at given frequencies.

        Parameters
        ----------
        x : array_like
            Graph frequencies at which to evaluate the filter.

        Returns
        -------
        y : ndarray
            Frequency response of the filters. Shape ``(g.Nf, len(x))``.

        Examples
        --------
        Frequency response of a low-pass filter:

        >>> import matplotlib.pyplot as plt
        >>> G = graphs.Logo()
        >>> G.compute_fourier_basis()
        >>> f = filters.Expwin(G)
        >>> G.compute_fourier_basis()
        >>> y = f.evaluate(G.e)
        >>> plt.plot(G.e, y[0])  # doctest: +ELLIPSIS
        [<matplotlib.lines.Line2D object at ...>]

        """
        x = np.asanyarray(x)
        # Avoid to copy data as with np.array([g(x) for g in self._kernels]).
        y = np.empty([self.Nf] + list(x.shape))
        for i, kernel in enumerate(self._kernels):
            y[i] = kernel(x)
        return y

    def filter(self, s, method='chebyshev', order=30):
        r"""Filter signals (analysis or synthesis).

        A signal is defined as a rank-3 tensor of shape ``(N_NODES, N_SIGNALS,
        N_FEATURES)``, where ``N_NODES`` is the number of nodes in the graph,
        ``N_SIGNALS`` is the number of independent signals, and ``N_FEATURES``
        is the number of features which compose a graph signal, or the
        dimensionality of a graph signal. For example if you filter a signal
        with a filter bank of 8 filters, you're extracting 8 features and
        decomposing your signal into 8 parts. That is called analysis. Your are
        thus transforming your signal tensor from ``(G.N, 1, 1)`` to ``(G.N, 1,
        8)``. Now you may want to combine back the features to form an unique
        signal. For this you apply again 8 filters, one filter per feature, and
        sum the result up. As such you're transforming your ``(G.N, 1, 8)``
        tensor signal back to ``(G.N, 1, 1)``. That is known as synthesis. More
        generally, you may want to map a set of features to another, though
        that is not implemented yet.

        The method computes the transform coefficients of a signal :math:`s`,
        where the atoms of the transform dictionary are generalized
        translations of each graph spectral filter to each vertex on the graph:

        .. math:: c = D^* s,

        where the columns of :math:`D` are :math:`g_{i,m} = T_i g_m` and
        :math:`T_i` is a generalized translation operator applied to each
        filter :math:`\hat{g}_m(\cdot)`. Each column of :math:`c` is the
        response of the signal to one filter.

        In other words, this function is applying the analysis operator
        :math:`D^*`, respectively the synthesis operator :math:`D`, associated
        with the frame defined by the filter bank to the signals.

        Parameters
        ----------
        s : array_like
            Graph signals, a tensor of shape ``(N_NODES, N_SIGNALS,
            N_FEATURES)``, where ``N_NODES`` is the number of nodes in the
            graph, ``N_SIGNALS`` the number of independent signals you want to
            filter, and ``N_FEATURES`` is either 1 (analysis) or the number of
            filters in the filter bank (synthesis).
        method : {'exact', 'chebyshev'}
            Whether to use the exact method (via the graph Fourier transform)
            or the Chebyshev polynomial approximation. A Lanczos
            approximation is coming.
        order : int
            Degree of the Chebyshev polynomials.

        Returns
        -------
        s : ndarray
            Graph signals, a tensor of shape ``(N_NODES, N_SIGNALS,
            N_FEATURES)``, where ``N_NODES`` and ``N_SIGNALS`` are the number
            of nodes and signals of the signal tensor that pas passed in, and
            ``N_FEATURES`` is either 1 (synthesis) or the number of filters in
            the filter bank (analysis).

        References
        ----------
        See :cite:`hammond2011wavelets` for details on filtering graph signals.

        Examples
        --------

        Create a bunch of smooth signals by low-pass filtering white noise:

        >>> import matplotlib.pyplot as plt
        >>> G = graphs.Ring(N=60)
        >>> G.estimate_lmax()
        >>> s = np.random.default_rng(42).uniform(size=(G.N, 10))
        >>> taus = [1, 10, 100]
        >>> s = filters.Heat(G, taus).filter(s)
        >>> s.shape
        (60, 10, 3)

        Plot the 3 smoothed versions of the 10th signal:

        >>> fig, ax = plt.subplots()
        >>> G.set_coordinates('line1D')  # To visualize multiple signals in 1D.
        >>> _ = G.plot(s[:, 9, :], ax=ax)
        >>> legend = [r'$\tau={}$'.format(t) for t in taus]
        >>> ax.legend(legend)  # doctest: +ELLIPSIS
        <matplotlib.legend.Legend object at ...>

        Low-pass filter a delta to create a localized smooth signal:

        >>> G = graphs.Sensor(30, seed=42)
        >>> G.compute_fourier_basis()  # Reproducible computation of lmax.
        >>> s1 = np.zeros(G.N)
        >>> s1[13] = 1
        >>> s1 = filters.Heat(G, 3).filter(s1)
        >>> s1.shape
        (30,)

        Filter and reconstruct our signal:

        >>> g = filters.MexicanHat(G, Nf=4)
        >>> s2 = g.analyze(s1)
        >>> s2.shape
        (30, 4)
        >>> s2 = g.synthesize(s2)
        >>> s2.shape
        (30,)

        Look how well we were able to reconstruct:

        >>> fig, axes = plt.subplots(1, 2)
        >>> _ = G.plot(s1, ax=axes[0])
        >>> _ = G.plot(s2, ax=axes[1])
        >>> print('{:.5f}'.format(np.linalg.norm(s1 - s2)))
        0.27649

        Perfect reconstruction with Itersine, a tight frame:

        >>> g = filters.Itersine(G)
        >>> s2 = g.analyze(s1, method='exact')
        >>> s2 = g.synthesize(s2, method='exact')
        >>> np.linalg.norm(s1 - s2) < 1e-10
        True

        """
        s = self.G._check_signal(s)

        # TODO: not in self.Nin (Nf = Nin x Nout).
        if s.ndim == 1 or s.shape[-1] not in [1, self.Nf]:
            if s.ndim == 3:
                raise ValueError('Third dimension (#features) should be '
                                 'either 1 or the number of filters Nf = {}, '
                                 'got {}.'.format(self.Nf, s.shape))
            s = np.expand_dims(s, -1)
        n_features_in = s.shape[-1]

        if s.ndim < 3:
            s = np.expand_dims(s, 1)
        n_signals = s.shape[1]

        if s.ndim > 3:
            raise ValueError('At most 3 dimensions: '
                             '#nodes x #signals x #features.')
        assert s.ndim == 3

        # TODO: generalize to 2D (m --> n) filter banks.
        # Only 1 --> Nf (analysis) and Nf --> 1 (synthesis) for now.
        n_features_out = self.Nf if n_features_in == 1 else 1

        if method == 'exact':

            # TODO: will be handled by g.adjoint().
            axis = 1 if n_features_in == 1 else 2
            f = self.evaluate(self.G.e)
            f = np.expand_dims(f.T, axis)
            assert f.shape == (self.G.N, n_features_in, n_features_out)

            s = self.G.gft(s)
            s = np.matmul(s, f)
            s = self.G.igft(s)

        elif method == 'chebyshev':

            # TODO: update Chebyshev implementation (after 2D filter banks).
            c = approximations.compute_cheby_coeff(self, m=order)

            if n_features_in == 1:  # Analysis.
                s = s.squeeze(axis=2)
                s = approximations.cheby_op(self.G, c, s)
                s = s.reshape((self.G.N, n_features_out, n_signals), order='F')
                s = s.swapaxes(1, 2)

            elif n_features_in == self.Nf:  # Synthesis.
                s = s.swapaxes(1, 2)
                s_in = s.reshape(
                    (self.G.N * n_features_in, n_signals), order='F')
                s = np.zeros((self.G.N, n_signals))
                tmpN = np.arange(self.G.N, dtype=int)
                for i in range(n_features_in):
                    s += approximations.cheby_op(self.G,
                                                 c[i],
                                                 s_in[i * self.G.N + tmpN])
                s = np.expand_dims(s, 2)

        else:
            raise ValueError('Unknown method {}.'.format(method))

        # Return a 1D signal if e.g. a 1D signal was filtered by one filter.
        return s.squeeze()

    def analyze(self, s, method='chebyshev', order=30):
        r"""Convenience alias to :meth:`filter`."""
        if s.ndim == 3 and s.shape[-1] != 1:
            raise ValueError('Last dimension (#features) should be '
                             '1, got {}.'.format(s.shape))
        return self.filter(s, method, order)

    def synthesize(self, s, method='chebyshev', order=30):
        r"""Convenience wrapper around :meth:`filter`.

        Will be an alias to `adjoint().filter()` in the future.
        """
        if s.shape[-1] != self.Nf:
            raise ValueError('Last dimension (#features) should be the number '
                             'of filters Nf = {}, got {}.'.format(self.Nf,
                                                                  s.shape))
        return self.filter(s, method, order)

    def localize(self, i, **kwargs):
        r"""Localize the kernels at a node (to visualize them).

        That is particularly useful to visualize a filter in the vertex domain.

        A kernel is localized on vertex :math:`v_i` by filtering a Kronecker
        delta :math:`\delta_i` as

        .. math:: (g(L) \delta_i)(j) = g(L)(i,j),
                  \text{ where } \delta_i(j) =
                  \begin{cases} 0 \text{ if } i \neq j, \\
                                1 \text{ if } i = j.    \end{cases}

        Parameters
        ----------
        i : int
            Index of the node where to localize the kernel.
        kwargs: dict
            Parameters to be passed to the :meth:`analyze` method.

        Returns
        -------
        s : ndarray
            Kernel localized at vertex i.

        Examples
        --------
        Visualize heat diffusion on a grid by localizing the heat kernel.

        >>> import matplotlib
        >>> N = 20
        >>> DELTA = N//2 * (N+1)
        >>> G = graphs.Grid2d(N)
        >>> G.estimate_lmax()
        >>> g = filters.Heat(G, 100)
        >>> s = g.localize(DELTA)
        >>> _ = G.plot(s, highlight=DELTA)

        """
        s = np.zeros(self.G.N)
        s[i] = 1
        return np.sqrt(self.G.N) * self.filter(s, **kwargs)

    def estimate_frame_bounds(self, x=None):
        r"""Estimate lower and upper frame bounds.

        A filter bank forms a frame if there are positive real numbers
        :math:`A` and :math:`B`, :math:`0 < A \leq B < \infty`, that satisfy
        the *frame condition*

        .. math:: A \|x\|^2 \leq \| g(L) x \|^2 \leq B \|x\|^2

        for all signals :math:`x \in \mathbb{R}^N`, where :math:`g(L)` is the
        analysis operator of the filter bank.

        As :math:`g(L) = U g(\Lambda) U^\top` is diagonalized by the Fourier
        basis :math:`U` with eigenvalues :math:`\Lambda`, :math:`\| g(L) x \|^2
        = \| g(\Lambda) U^\top x \|^2`, and :math:`A = \min g^2(\Lambda)`,
        :math:`B = \max g^2(\Lambda)`.

        Parameters
        ----------
        x : array_like
            Graph frequencies at which to evaluate the filter bank `g(x)`.
            The default is ``x = np.linspace(0, G.lmax, 1000)``.
            The exact bounds are given by evaluating the filter bank at the
            eigenvalues of the graph Laplacian, i.e., ``x = G.e``.

        Returns
        -------
        A : float
            Lower frame bound of the filter bank.
        B : float
            Upper frame bound of the filter bank.

        See Also
        --------
        compute_frame: compute the frame
        complement: complement a filter bank to become a tight frame

        Examples
        --------

        >>> from matplotlib import pyplot as plt
        >>> fig, axes = plt.subplots(2, 2, figsize=(10, 6))
        >>> G = graphs.Sensor(64, seed=42)
        >>> G.compute_fourier_basis()
        >>> g = filters.Abspline(G, 7)

        Estimation quality vs speed (loose & fast -> exact & slow):

        >>> A, B = g.estimate_frame_bounds(np.linspace(0, G.lmax, 5))
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=1.883, B=2.288
        >>> A, B = g.estimate_frame_bounds()
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=1.708, B=2.359
        >>> A, B = g.estimate_frame_bounds(G.e)
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=1.875, B=2.359

        The frame bounds can be seen in the plot of the filter bank as the
        minimum and maximum of their squared sum (the black curve):

        >>> def plot(g, ax):
        ...     g.plot(ax=ax, labels=False, title='')
        ...     ax.hlines(B, 0, G.lmax, colors='r', zorder=3,
        ...               label='upper bound $B={:.2f}$'.format(B))
        ...     ax.hlines(A, 0, G.lmax, colors='b', zorder=3,
        ...               label='lower bound $A={:.2f}$'.format(A))
        ...     ax.legend(loc='center right')
        >>> plot(g, axes[0, 0])

        The heat kernel has a null-space and doesn't define a frame (the lower
        bound should be greater than 0 to have a frame):

        >>> g = filters.Heat(G)
        >>> A, B = g.estimate_frame_bounds()
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=0.000, B=1.000
        >>> plot(g, axes[0, 1])

        Without a null-space, the heat kernel forms a frame:

        >>> g = filters.Heat(G, scale=[1, 10])
        >>> A, B = g.estimate_frame_bounds()
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=0.135, B=2.000
        >>> plot(g, axes[1, 0])

        A kernel and its dual form a tight frame (A=B):

        >>> g = filters.Regular(G)
        >>> A, B = g.estimate_frame_bounds()
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=1.000, B=1.000
        >>> plot(g, axes[1, 1])
        >>> fig.tight_layout()

        The Itersine filter bank forms a tight frame (A=B):

        >>> g = filters.Itersine(G)
        >>> A, B = g.estimate_frame_bounds()
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=1.000, B=1.000

        """
        if x is None:
            x = np.linspace(0, self.G.lmax, 1000)
        else:
            x = np.asanyarray(x)

        sum_filters = np.sum(self.evaluate(x)**2, axis=0)

        return sum_filters.min(), sum_filters.max()

    def compute_frame(self, **kwargs):
        r"""Compute the associated frame.

        A filter bank defines a frame, which is a generalization of a basis to
        sets of vectors that may be linearly dependent. See
        `Wikipedia <https://en.wikipedia.org/wiki/Frame_(linear_algebra)>`_.

        The frame of a filter bank is the union of the frames of its
        constituent filters. The vectors forming the frame are the rows of the
        *analysis operator*

        .. math::
            g(L) = \begin{pmatrix} g_1(L) \\ \vdots \\ g_F(L) \end{pmatrix}
                   \in \mathbb{R}^{NF \times N}, \quad
            g_i(L) = U g_i(\Lambda) U^\top,

        where :math:`g_i` are the filter kernels, :math:`N` is the number of
        nodes, :math:`F` is the number of filters, :math:`L` is the graph
        Laplacian, :math:`\Lambda` is a diagonal matrix of the Laplacian's
        eigenvalues, and :math:`U` is the Fourier basis, i.e., its columns are
        the eigenvectors of the Laplacian.

        The matrix :math:`g(L)` represents the *analysis operator* of the
        frame. Its adjoint :math:`g(L)^\top` represents the *synthesis
        operator*. A signal :math:`x` is thus analyzed with the frame by
        :math:`y = g(L) x`, and synthesized from its frame coefficients by
        :math:`z = g(L)^\top y`. Computing this matrix is however a rather
        inefficient way of doing those operations.

        If :math:`F > 1`, the frame is said to be over-complete and the
        representation :math:`g(L) x` of the signal :math:`x` is said to be
        redundant.

        If the frame is tight, the *frame operator* :math:`g(L)^\top g(L)` is
        diagonal, with entries equal to the frame bound :math:`A = B`.

        Parameters
        ----------
        kwargs: dict
            Parameters to be passed to the :meth:`analyze` method.

        Returns
        -------
        frame : ndarray
            Array of size (#nodes x #filters) x #nodes.

        See Also
        --------
        estimate_frame_bounds: estimate the frame bounds
        filter: more efficient way to filter signals

        Examples
        --------

        >>> G = graphs.Sensor(100, seed=42)
        >>> G.compute_fourier_basis()

        Filtering as a multiplication with the matrix representation of the
        frame analysis operator:

        >>> g = filters.MexicanHat(G, Nf=6)
        >>> s = np.random.default_rng().uniform(size=G.N)
        >>>
        >>> gL = g.compute_frame()
        >>> gL.shape
        (600, 100)
        >>> s1 = gL.dot(s)
        >>> s1 = s1.reshape(G.N, -1, order='F')
        >>>
        >>> s2 = g.filter(s)
        >>> np.all(np.abs(s1 - s2) < 1e-10)
        True

        The frame operator of a tight frame is the identity matrix times the
        frame bound:

        >>> g = filters.Itersine(G)
        >>> A, B = g.estimate_frame_bounds()
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=1.000, B=1.000
        >>> gL = g.compute_frame(method='exact')
        >>> gL.shape
        (600, 100)
        >>> np.all(gL.T.dot(gL) - np.identity(G.N) < 1e-10)
        True

        """
        if self.G.N > 2000:
            _logger.warning('Creating a big matrix. '
                            'You should prefer the filter method.')

        # Filter one delta per vertex.
        s = np.identity(self.G.N)
        return self.filter(s, **kwargs).T.reshape(-1, self.G.N)

    def complement(self, frame_bound=None):
        r"""Return the filter that makes the frame tight.

        The complementary filter is designed such that the union of a filter
        bank and its complementary filter forms a tight frame.

        Parameters
        ----------
        frame_bound : float or None
            The desired frame bound :math:`A = B` of the resulting tight frame.
            The chosen bound should be larger than the sum of squared
            evaluations of all filters in the filter bank. If None (the
            default), the method chooses the smallest feasible bound.

        Returns
        -------
        complement: Filter
            The complementary filter.

        See Also
        --------
        estimate_frame_bounds: estimate the frame bounds

        Examples
        --------
        >>> from matplotlib import pyplot as plt
        >>> G = graphs.Sensor(100, seed=42)
        >>> G.estimate_lmax()
        >>> g = filters.Abspline(G, 4)
        >>> A, B = g.estimate_frame_bounds()
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=0.200, B=1.971
        >>> fig, axes = plt.subplots(1, 2)
        >>> fig, ax = g.plot(ax=axes[0])
        >>> g += g.complement()
        >>> A, B = g.estimate_frame_bounds()
        >>> print('A={:.3f}, B={:.3f}'.format(A, B))
        A=1.971, B=1.971
        >>> fig, ax = g.plot(ax=axes[1])

        """

        def kernel(x, *args, **kwargs):

            y = self.evaluate(x)
            np.power(y, 2, out=y)
            y = np.sum(y, axis=0)

            if frame_bound is None:
                bound = y.max()
            elif y.max() > frame_bound:
                raise ValueError('The chosen bound is not feasible. '
                                 'Choose at least {}.'.format(y.max()))
            else:
                bound = frame_bound

            return np.sqrt(bound - y)

        return Filter(self.G, kernel)

    def inverse(self):
        r"""Return the pseudo-inverse filter bank.

        The pseudo-inverse of the *analysis filter bank* :math:`g` is the
        *synthesis filter bank* :math:`g^+` such that

        .. math:: g(L)^+ g(L) = I,

        where :math:`I` is the identity matrix, and the *synthesis operator*

        .. math:: g(L)^+ = (g(L)\top g(L))^{-1} g(L)^\top
                         = (g_1(L)^+, \dots, g_F(L)^+)
                           \in \mathbb{R}^{N \times NF}

        is the left pseudo-inverse of the analysis operator :math:`g(L)`. Note
        that :math:`g_i(L)^+` is the pseudo-inverse of :math:`g_i(L)`,
        :math:`N` is the number of vertices, and :math:`F` is the number of
        filters in the bank.

        The above relation holds, and the reconstruction is exact, if and only
        if :math:`g(L)` is a frame. To be a frame, the rows of :math:`g(L)`
        must span the whole space (i.e., :math:`g(L)` must have full row rank).
        That is the case if the lower frame bound :math:`A > 0`. If
        :math:`g(L)` is not a frame, the reconstruction :math:`g(L)^+ g(L) x`
        will be the closest to :math:`x` in the least square sense.

        While there exists infinitely many inverses of the analysis operator of
        a frame, the pseudo-inverse is unique and corresponds to the *canonical
        dual* of the filter kernel.

        The *frame operator* of :math:`g^+` is :math:`g(L)^+ (g(L)^+)^\top =
        (g(L)\top g(L))^{-1}`, the inverse of the frame operator of :math:`g`.
        Similarly, its *frame bounds* are :math:`A^{-1}` and :math:`B^{-1}`,
        where :math:`A` and :math:`B` are the frame bounds of :math:`g`.

        If :math:`g` is tight (i.e., :math:`A=B`), the canonical dual is given
        by :math:`g^+ = g / A` (i.e., :math:`g^+_i = g_i / A \ \forall i`).

        Returns
        -------
        inverse : :class:`pygsp.filters.Filter`
            The pseudo-inverse filter bank, which synthesizes (or reconstructs)
            a signal from its coefficients using the canonical dual frame.

        See Also
        --------
        estimate_frame_bounds: estimate the frame bounds

        Examples
        --------
        >>> from matplotlib import pyplot as plt
        >>> G = graphs.Sensor(100, seed=42)
        >>> G.compute_fourier_basis()
        >>> # Create a filter and its inverse.
        >>> g = filters.Abspline(G, 5)
        >>> h = g.inverse()
        >>> # Plot them.
        >>> fig, axes = plt.subplots(1, 2)
        >>> _ = g.plot(ax=axes[0], title='original filter bank')
        >>> _ = h.plot(ax=axes[1], title='inverse filter bank')
        >>> # Filtering with the inverse reconstructs the original signal.
        >>> x = np.random.default_rng(42).normal(size=G.N)
        >>> y = g.filter(x, method='exact')
        >>> z = h.filter(y, method='exact')
        >>> np.linalg.norm(x - z) < 1e-10
        True
        >>> # Indeed, they cancel each others' effect.
        >>> Ag, Bg = g.estimate_frame_bounds()
        >>> Ah, Bh = h.estimate_frame_bounds()
        >>> print('A(g)*B(h) = {:.3f} * {:.3f} = {:.3f}'.format(Ag, Bh, Ag*Bh))
        A(g)*B(h) = 0.687 * 1.457 = 1.000
        >>> print('B(g)*A(h) = {:.3f} * {:.3f} = {:.3f}'.format(Bg, Ah, Bg*Ah))
        B(g)*A(h) = 1.994 * 0.501 = 1.000

        """

        A, _ = self.estimate_frame_bounds()
        if A == 0:
            _logger.warning('The filter bank is not invertible as it is not '
                            'a frame (lower frame bound A=0).')

        def kernel(g, i, x):
            y = g.evaluate(x).T
            z = np.linalg.pinv(np.expand_dims(y, axis=-1)).squeeze(axis=-2)
            return z[:, i]  # Return one filter.

        kernels = [partial(kernel, self, i) for i in range(self.n_filters)]

        return Filter(self.G, kernels)

    def plot(self, n=500, eigenvalues=None, sum=None, labels=None, title=None,
             ax=None, **kwargs):
        r"""Docstring overloaded at import time."""
        from pygsp.plotting import _plot_filter
        return _plot_filter(self, n=n, eigenvalues=eigenvalues, sum=sum,
                            labels=labels, title=title, ax=ax, **kwargs)


text:
package model;

import exception.*;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * Created by cosmin on 02/11/16.
 */
public class ReadFileStmt implements IStmt {
    private Exp exp;
    private String var;

    public ReadFileStmt(Exp exp, String var) {
        this.exp = exp;
        this.var = var;
    }

    @Override
    public PrgState execute(PrgState state) throws IOException, FileAlreadyOpenedException, FileNotOpenedException, UnknownVariableException, DivideByZeroException, UnknownComparisonExpression {
        int fd = this.exp.eval(state.getSymTable(), state.getHeap());
        Tuple<String, BufferedReader> br = state.getFileTable().get(fd);
        if (br == null)
            throw new FileNotOpenedException("FileNotOpenedException at: " + this.toString() + "\nNo such file descriptor: " + String.valueOf(fd));
        String line = br.getSecond().readLine();
        int val = 0;
        if(line != null)
            val = Integer.valueOf(line);
        state.getSymTable().put(this.var, val);
        return null;
    }

    @Override
    public String toString() {
        return "readFileStmt(" + this.exp.toString() + ", " + this.var + ")";
    }
}


text:
export * from './pseudo-checkbox/pseudo-checkbox';
export * from './pseudo-checkbox/pseudo-checkbox-module';


text:
'use strict';

var mongoose = require('mongoose'),
  Schema = mongoose.Schema,
  timestamps = require('mongoose-timestamp');

var ContactSchema = new Schema({
  firstname: {
    type: String,
    required: 'Le prénom est requis'
  },
  lastname: {
    type: String,
    required: 'Le nom de famille est requis'
  },
  poste: {
    type: Schema.ObjectId,
    ref: 'poste'
  },
  email: {
    type: String
  },
  etablissements: [{
    type: Schema.ObjectId,
    ref: 'etablissement'
  }]
});

ContactSchema.plugin(timestamps);

ContactSchema.methods.toString = function() {
  return this.firstname + ' ' + this.lastname;
};

ContactSchema.methods.getEmail = function() {
  return this.email;
};

module.exports = mongoose.model('contact', ContactSchema);


text:
namespace {

// Compares each pixel in the 1x representation of two images for testing.
// TODO(pkotwicz): Compare pixels of all bitmaps contained within image.
bool CompareTwoImages(const gfx::ImageSkia& image_a,
                      const gfx::ImageSkia& image_b,
                      int log_level) {
  CHECK(!image_a.isNull());
  CHECK(!image_b.isNull());

  gfx::ImageSkiaRep image_rep_a =
      image_a.GetRepresentation(ui::SCALE_FACTOR_100P);
  CHECK_EQ(ui::SCALE_FACTOR_100P, image_rep_a.scale_factor());
  gfx::ImageSkiaRep image_rep_b =
      image_b.GetRepresentation(ui::SCALE_FACTOR_100P);
  CHECK_EQ(ui::SCALE_FACTOR_100P, image_rep_b.scale_factor());

  SkBitmap a = image_rep_a.sk_bitmap();
  SkBitmap b = image_rep_b.sk_bitmap();

  CHECK(!a.empty());
  CHECK(!b.empty());
  if (a.getSize() != b.getSize()) {
    VLOG(log_level) << "Mistmatched size: "
                    << a.getSize() << " != " << b.getSize();
    return false;
  }
  size_t bytes = a.getSize();
  SkAutoLockPixels locka(a);
  SkAutoLockPixels lockb(b);
  const char* pixa = static_cast<const char*>(a.getPixels());
  const char* pixb = static_cast<const char*>(b.getPixels());
  if (!pixa || !pixb) {
    if (!pixa)
      VLOG(log_level) << "getPixels() returned NULL for LHS";
    if (!pixb)
      VLOG(log_level) << "getPixels() returned NULL for RHS";
    return false;
  }
  size_t width = a.width();
  size_t height = a.height();
  size_t bpp = a.bytesPerPixel();
  if (width * height * bpp != bytes) {
    VLOG(log_level) << "Width: " << width << " x Height: " << height
                    << " x bpp: " << bpp << " != Size: " << bytes;
    return false;
  }
  for (int y=0; y<a.height(); ++y) {
    for (int x=0; x<a.width(); ++x) {
      for (size_t i = 0; i<bpp; ++i) {
        if (*pixa++ != *pixb++) {
          VLOG(log_level) << "Icon: " << width << "x" << height << "x" << bpp
                          << ", Mismatch at: " << x << "," << y << ":" << i;
          return false;
        }
      }
    }
  }
  return true;
}

} // namespace

namespace chromeos {

class NetworkMenuIconTest : public testing::Test {
 protected:
  NetworkMenuIconTest() : rb_(ResourceBundle::GetSharedInstance()) {}

  // testing::Test implementation.
  virtual void SetUp() OVERRIDE {
    cros_ = CrosLibrary::Get()->GetNetworkLibrary();
    // Ethernet connected = WIRED icon, no badges.
    ethernet_connected_image_ = NetworkMenuIcon::GenerateImageFromComponents(
        *rb_.GetImageSkiaNamed(IDR_STATUSBAR_WIRED),
        NULL, NULL, NULL, NULL);
    // Wifi connected, strength = 100% = ARCS4 icon, no badges.
    wifi_connected_100_image_ = NetworkMenuIcon::GenerateImageFromComponents(
        NetworkMenuIcon::GetImage(
            NetworkMenuIcon::ARCS,
            NetworkMenuIcon::NumImages(NetworkMenuIcon::ARCS) - 1,
            NetworkMenuIcon::COLOR_DARK),
        NULL, NULL, NULL, NULL);
    // Wifi connected, strength = 50%, encrypted = ARCS2 icon + SECURE badge.
    wifi_encrypted_50_image_ = NetworkMenuIcon::GenerateImageFromComponents(
        NetworkMenuIcon::GetImage(NetworkMenuIcon::ARCS, 3,
                                  NetworkMenuIcon::COLOR_DARK),
        NULL, NULL, NULL,
        rb_.GetImageSkiaNamed(IDR_STATUSBAR_NETWORK_SECURE_DARK));
    // Wifi connecting = IDR_STATUSBAR_NETWORK_ARCS1 (faded).
    wifi_connecting_image_ = NetworkMenuIcon::GenerateConnectingImage(
        NetworkMenuIcon::GetImage(NetworkMenuIcon::ARCS, 1,
                                  NetworkMenuIcon::COLOR_DARK));
    // 4G connected, strength = 50% = BARS4 icon + 4G badge.
    wimax_connected_50_image_ =
        NetworkMenuIcon::GenerateImageFromComponents(
            NetworkMenuIcon::GetImage(
                NetworkMenuIcon::BARS, 3,
                NetworkMenuIcon::COLOR_DARK),
        rb_.GetImageSkiaNamed(IDR_STATUSBAR_NETWORK_4G_DARK), NULL, NULL, NULL);
    // 3G connected, strength = 100% = BARS4 icon + 3G badge.
    cellular_connected_100_image_ =
        NetworkMenuIcon::GenerateImageFromComponents(
            NetworkMenuIcon::GetImage(
                NetworkMenuIcon::BARS,
                NetworkMenuIcon::NumImages(NetworkMenuIcon::BARS) - 1,
                NetworkMenuIcon::COLOR_DARK),
        rb_.GetImageSkiaNamed(IDR_STATUSBAR_NETWORK_3G_DARK), NULL, NULL, NULL);
    // 3G connected, strength = 50%, roaming = BARS2 icon + roaming & 3G badges.
    cellular_roaming_50_image_ = NetworkMenuIcon::GenerateImageFromComponents(
        NetworkMenuIcon::GetImage(NetworkMenuIcon::BARS, 3,
                                  NetworkMenuIcon::COLOR_DARK),
        rb_.GetImageSkiaNamed(IDR_STATUSBAR_NETWORK_3G_DARK), NULL, NULL,
        rb_.GetImageSkiaNamed(IDR_STATUSBAR_NETWORK_ROAMING_DARK));
    // 3G connecting = IDR_STATUSBAR_NETWORK_BARS1 (faded).
    cellular_connecting_image_ = NetworkMenuIcon::GenerateConnectingImage(
        NetworkMenuIcon::GetImage(NetworkMenuIcon::BARS, 1,
                                  NetworkMenuIcon::COLOR_DARK));
    // Disconnected = ARCS0 icon.
    disconnected_image_ = NetworkMenuIcon::GenerateImageFromComponents(
        NetworkMenuIcon::GetImage(NetworkMenuIcon::ARCS, 0,
                                  NetworkMenuIcon::COLOR_DARK),
        NULL, NULL, NULL, NULL);
  }

  virtual void TearDown() OVERRIDE {
  }

 protected:
  void SetConnected(Network* network) {
    Network::TestApi test_network(network);
    test_network.SetConnected();
  }

  void SetConnecting(Network* network) {
    Network::TestApi test_network(network);
    test_network.SetConnecting();
  }

  void SetDisconnected(Network* network) {
    Network::TestApi test_network(network);
    test_network.SetDisconnected();
  }

  void SetActive(Network* network, bool active) {
    if (active) {
      cros_->SetActiveNetwork(network->type(), network->service_path());
    } else {
      cros_->SetActiveNetwork(network->type(), "");
    }
  }

  void SetStrength(WirelessNetwork* network, int strength) {
    WirelessNetwork::TestApi test_network(network);
    test_network.SetStrength(strength);
  }

  void SetEncryption(WifiNetwork* network, ConnectionSecurity encryption) {
    WifiNetwork::TestApi test_network(network);
    test_network.SetEncryption(encryption);
  }

  void SetRoamingState(CellularNetwork* network, NetworkRoamingState roaming) {
    CellularNetwork::TestApi test_network(network);
    test_network.SetRoamingState(roaming);
  }

  bool CompareImages(const gfx::ImageSkia& icon, const gfx::ImageSkia& base) {
    if (CompareTwoImages(icon, base, 1))
      return true;
    EXPECT_FALSE(CompareTwoImages(icon, ethernet_connected_image_, 2));
    EXPECT_FALSE(CompareTwoImages(icon, wifi_connected_100_image_, 2));
    EXPECT_FALSE(CompareTwoImages(icon, wifi_encrypted_50_image_, 2));
    EXPECT_FALSE(CompareTwoImages(icon, wifi_connecting_image_, 2));
    EXPECT_FALSE(CompareTwoImages(icon, cellular_connected_100_image_, 2));
    EXPECT_FALSE(CompareTwoImages(icon, cellular_roaming_50_image_, 2));
    EXPECT_FALSE(CompareTwoImages(icon, cellular_connecting_image_, 2));
    EXPECT_FALSE(CompareTwoImages(icon, disconnected_image_, 2));
    return false;
  }

 protected:
  ScopedStubCrosEnabler cros_stub_;
  NetworkLibrary* cros_;
  ResourceBundle& rb_;
  gfx::ImageSkia ethernet_connected_image_;
  gfx::ImageSkia wifi_connected_100_image_;
  gfx::ImageSkia wifi_encrypted_50_image_;
  gfx::ImageSkia wifi_connecting_image_;
  gfx::ImageSkia wimax_connected_50_image_;
  gfx::ImageSkia cellular_connected_100_image_;
  gfx::ImageSkia cellular_roaming_50_image_;
  gfx::ImageSkia cellular_connecting_image_;
  gfx::ImageSkia disconnected_image_;
};

// Compare icon cache results against expected results fron SetUp().
TEST_F(NetworkMenuIconTest, EthernetIcon) {
  Network* network = cros_->FindNetworkByPath("eth1");
  ASSERT_NE(static_cast<const Network*>(NULL), network);
  SetConnected(network);
  gfx::ImageSkia icon = NetworkMenuIcon::GetImage(network,
                                                  NetworkMenuIcon::COLOR_DARK);
  EXPECT_TRUE(CompareImages(icon, ethernet_connected_image_));
}

TEST_F(NetworkMenuIconTest, WifiIcon) {
  WifiNetwork* network = cros_->FindWifiNetworkByPath("wifi1");
  ASSERT_NE(static_cast<const Network*>(NULL), network);
  gfx::ImageSkia icon = NetworkMenuIcon::GetImage(network,
                                                  NetworkMenuIcon::COLOR_DARK);
  EXPECT_TRUE(CompareImages(icon, wifi_connected_100_image_));

  SetStrength(network, 50);
  SetEncryption(network, SECURITY_RSN);
  icon = NetworkMenuIcon::GetImage(network,
                                   NetworkMenuIcon::COLOR_DARK);
  EXPECT_TRUE(CompareImages(icon, wifi_encrypted_50_image_));
}

TEST_F(NetworkMenuIconTest, CellularIcon) {
  CellularNetwork* network = cros_->FindCellularNetworkByPath("cellular1");
  ASSERT_NE(static_cast<const Network*>(NULL), network);
  SetConnected(network);
  SetStrength(network, 100);
  SetRoamingState(network, ROAMING_STATE_HOME);
  gfx::ImageSkia icon = NetworkMenuIcon::GetImage(network,
                                                  NetworkMenuIcon::COLOR_DARK);
  EXPECT_TRUE(CompareImages(icon, cellular_connected_100_image_));

  SetStrength(network, 50);
  SetRoamingState(network, ROAMING_STATE_ROAMING);
  icon = NetworkMenuIcon::GetImage(network,
                                   NetworkMenuIcon::COLOR_DARK);
  EXPECT_TRUE(CompareImages(icon, cellular_roaming_50_image_));
}

namespace {

class TestNetworkMenuIcon : public NetworkMenuIcon {
 public:
  explicit TestNetworkMenuIcon(Mode mode)
      : NetworkMenuIcon(&delegate_, mode),
        animation_(0.0) {
  }
  virtual ~TestNetworkMenuIcon() {}

  // NetworkMenuIcon override.
  virtual double GetAnimation() OVERRIDE { return animation_; }

  void set_animation(double animation) { animation_ = animation; }

 private:
  class Delegate : public NetworkMenuIcon::Delegate {
   public:
    Delegate() : changed_(0) {}
    virtual void NetworkMenuIconChanged() OVERRIDE {
      ++changed_;
    }
    int changed() const { return changed_; }
   private:
    int changed_;
  };
  Delegate delegate_;
  double animation_;
};

}  // namespace

// Test Network Menu status icon logic.

// Default relevent stub state:
//  eth1: connected (active ethernet)
//  wifi1: connected (active wifi)
//  cellular1: connected  (active cellular)
//  wimax2: connected  (active wimax)
// See network_library_unit_test.cc for more info.

TEST_F(NetworkMenuIconTest, StatusIconMenuMode) {
  TestNetworkMenuIcon menu_icon(NetworkMenuIcon::MENU_MODE);
  gfx::ImageSkia icon;

  // Set cellular1 to connecting.
  CellularNetwork* cellular1 = cros_->FindCellularNetworkByPath("cellular1");
  ASSERT_NE(static_cast<const Network*>(NULL), cellular1);
  SetRoamingState(cellular1, ROAMING_STATE_HOME);  // Clear romaing state
  SetConnecting(cellular1);

  // For MENU_MODE, we always display the connecting icon (cellular1).
  icon = menu_icon.GetIconAndText(NULL);
  EXPECT_TRUE(CompareImages(icon, cellular_connecting_image_));

  // Set cellular1 to connected; ethernet icon should be shown.
  SetConnected(cellular1);
  icon = menu_icon.GetIconAndText(NULL);
  EXPECT_TRUE(CompareImages(icon, ethernet_connected_image_));

  // Set ethernet to inactive/disconnected; wifi icon should be shown.
  Network* eth1 = cros_->FindNetworkByPath("eth1");
  ASSERT_NE(static_cast<const Network*>(NULL), eth1);
  SetActive(eth1, false);
  SetDisconnected(eth1);
  icon = menu_icon.GetIconAndText(NULL);
  EXPECT_TRUE(CompareImages(icon, wifi_connected_100_image_));

  // Set all networks to disconnected; disconnected icon should be shown.
  SetActive(cellular1, false);
  SetDisconnected(cellular1);
  WifiNetwork* wifi1 = cros_->FindWifiNetworkByPath("wifi1");
  SetActive(wifi1, false);
  SetDisconnected(wifi1);
  WimaxNetwork* wimax2 = cros_->FindWimaxNetworkByPath("wimax2");
  SetActive(wimax2, false);
  SetDisconnected(wimax2);
  icon = menu_icon.GetIconAndText(NULL);
  EXPECT_TRUE(CompareImages(icon, disconnected_image_));
}

TEST_F(NetworkMenuIconTest, StatusIconDropdownMode) {
  TestNetworkMenuIcon menu_icon(NetworkMenuIcon::DROPDOWN_MODE);
  gfx::ImageSkia icon;

  // Set wifi1 to connecting.
  WifiNetwork* wifi1 = cros_->FindWifiNetworkByPath("wifi1");
  ASSERT_NE(static_cast<const Network*>(NULL), wifi1);
  SetConnecting(wifi1);

  // For DROPDOWN_MODE, we prioritize the connected network (ethernet).
  icon = menu_icon.GetIconAndText(NULL);
  EXPECT_TRUE(CompareImages(icon, ethernet_connected_image_));

  // Set ethernet to inactive/disconnected.
  Network* ethernet = cros_->FindNetworkByPath("eth1");
  ASSERT_NE(static_cast<const Network*>(NULL), ethernet);
  SetActive(ethernet, false);
  SetDisconnected(ethernet);

  // Icon should now be cellular connected icon.
  icon = menu_icon.GetIconAndText(NULL);
  EXPECT_TRUE(CompareImages(icon, cellular_connected_100_image_));

  // Set cellular1 to disconnected; Icon should now be wimax icon.
  CellularNetwork* cellular1 = cros_->FindCellularNetworkByPath("cellular1");
  ASSERT_NE(static_cast<const Network*>(NULL), cellular1);
  SetDisconnected(cellular1);
  icon = menu_icon.GetIconAndText(NULL);
  EXPECT_TRUE(CompareImages(icon, wimax_connected_50_image_));

  // Set wifi1 to connected. Icon should now be wifi connected icon.
  SetConnected(wifi1);
  icon = menu_icon.GetIconAndText(NULL);
  EXPECT_TRUE(CompareImages(icon, wifi_connected_100_image_));
}

}  // namespace chromeos


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

<title>com.felina.android.api</title>
<meta name="date" content="2014-05-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.felina.android.api

Classes

R

R.drawable

R.style


text:
package models

import (
	"database/sql"
	"errors"

	"github.com/eirka/eirka-libs/db"
	e "github.com/eirka/eirka-libs/errors"
)

// DeleteImageTagModel holds request input
type DeleteImageTagModel struct {
	Image uint
	Tag   uint
	Name  string
	Ib    uint
}

// IsValid will check struct validity
func (m *DeleteImageTagModel) IsValid() bool {

	if m.Image == 0 {
		return false
	}

	if m.Tag == 0 {
		return false
	}

	if m.Name == "" {
		return false
	}

	if m.Ib == 0 {
		return false
	}

	return true

}

// Status will return info
func (m *DeleteImageTagModel) Status() (err error) {

	// Get Database handle
	dbase, err := db.GetDb()
	if err != nil {
		return
	}

	// Check if the tag is there
	err = dbase.QueryRow("SELECT tag_name FROM tags WHERE tag_id = ? AND ib_id = ? LIMIT 1", m.Tag, m.Ib).Scan(&m.Name)
	if err == sql.ErrNoRows {
		return e.ErrNotFound
	} else if err != nil {
		return
	}

	return

}

// Delete will remove the entry
func (m *DeleteImageTagModel) Delete() (err error) {

	// check model validity
	if !m.IsValid() {
		return errors.New("DeleteImageTagModel is not valid")
	}

	// Get Database handle
	dbase, err := db.GetDb()
	if err != nil {
		return
	}

	ps1, err := dbase.Prepare(`DELETE tm FROM tagmap AS tm
    INNER JOIN tags ON tm.tag_id = tags.tag_id
    WHERE image_id = ? AND tm.tag_id = ? AND ib_id = ?`)
	if err != nil {
		return
	}
	defer ps1.Close()

	_, err = ps1.Exec(m.Image, m.Tag, m.Ib)
	if err != nil {
		return
	}

	return

}


text:
package com.pkware.truth.android.content;

import android.content.SharedPreferences;

import com.google.common.truth.FailureMetadata;
import com.google.common.truth.MapSubject;
import com.google.common.truth.Subject;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public abstract class AbstractSharedPreferencesSubject<T extends SharedPreferences> extends Subject {

  @Nullable
  private final T actual;

  protected AbstractSharedPreferencesSubject(@Nonnull FailureMetadata failureMetadata, @Nullable T actual) {
    super(failureMetadata, actual);
    this.actual = actual;
  }

  public void hasKey(@Nonnull String key) {
    check("contains(key)")
        .withMessage("Expected key <%s> to be present but it was not.", key)
        .that(actual.contains(key))
        .isTrue();
  }

  public void doesNotHaveKey(@Nonnull String key) {
    check("contains(key)")
        .withMessage("Expected key <%s> not to be present but it was.", key)
        .that(actual.contains(key))
        .isFalse();
  }

  public MapSubject asMap() {
    return check("getAll()").that(actual.getAll());
  }
}


text:
/**
 * Min-Max Find Heap
 * Author: Kendal Harland (kendalharland@ku.edu)
 *
 * My understanding of this data structure is taken from a paper found online. For
 * safekeeping I've uploaded that same paper to this location:
 * https://mega.co.nz/#!nIdnkIwS!NB0vLMuJA_BUo4x_oBgywdxLH9ntCOqkK8f_MlIXn3g
 */


text:
#include <radiobutton.hpp>

RadioButton *RadioButton::groupSelect[512];
int RadioButton::defaultGroup=0;
static bool init=false;

void RadioButton::select() {
	if (!init) {
		memset(groupSelect,0,sizeof(RadioButton *)*512);
		init=true;
	}
	groupSelect[group]=this;
}

void RadioButton::unSelect() {
	if (!init) {
		memset(groupSelect,0,sizeof(RadioButton *)*512);
		init=true;
	}
	groupSelect[group]=NULL;
}

void RadioButton::unSelectGroup(int group) {
	groupSelect[group]=NULL;
}

void RadioButton::render() {
	Button::render();
	if ( groupSelect[group] == this ) {
		con->setChar(x,y,'>');
	}
}

void RadioButton::onButtonClick() {
	select();
	Button::onButtonClick();
}


text:
To compile on a Cray XE6 with the default environment:

$ which cc
/opt/cray/xt-asyncpe/5.22/bin/cc

$ make CC=cc


text:
// Copyright (C) 2001-2003 Douglas Gregor

// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// For more information, see http://www.boost.org/

#include <boost/function.hpp>
#include <iostream>
#include <functional>

struct X {
  int foo(int);
};
int X::foo(int x) { return -x; }

int main()
{
      boost::function<int (int)> f;
  X x;
  f = std::bind1st(
        std::mem_fun(&X::foo), &x);
  f(5); // Call x.foo(5)

    return 0;
}


text:
package org.slf4j.spi;

import org.slf4j.ILoggerFactory;
import org.slf4j.IMarkerFactory;

public interface SLF4JServiceProvider {

    /**
     * Return the instance of {@link ILoggerFactory} that
     * {@link org.slf4j.LoggerFactory} class should bind to.
     *
     * @return the instance of {@link ILoggerFactory} that
     * {@link org.slf4j.LoggerFactory} class should bind to.
     */
    public ILoggerFactory getLoggerFactory();

    /**
     * Return the instance of {@link IMarkerFactory} that
     * {@link org.slf4j.MarkerFactory} class should bind to.
     *
     * @return the instance of {@link IMarkerFactory} that
     * {@link org.slf4j.MarkerFactory} class should bind to.
     */
    public IMarkerFactory getMarkerFactory();

    public MDCAdapter getMDCAdapter();

    public String getRequesteApiVersion();

    public void initialize();
}


text:
package org.ehcache.impl.internal.store.heap.holders;

import org.ehcache.impl.copy.IdentityCopier;
import org.ehcache.impl.copy.ReadWriteCopier;
import org.junit.Test;

import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;

/**
 * Created by alsu on 20/08/15.
 */
public class CopiedOnHeapValueHolderTest {

  @Test
  public void testValueByValue() throws Exception {
    Person person = new Person("foo", 24);
    PersonCopier copier = new PersonCopier();
    CopiedOnHeapValueHolder<Person> valueHolder = new CopiedOnHeapValueHolder<>(person, -1, false, copier);
    person.age = 25;

    assertNotSame(person, valueHolder.get());
  }

  @Test
  public void testValueByRef() throws Exception {
    Person person = new Person("foo", 24);
    CopiedOnHeapValueHolder<Person> valueHolder = new CopiedOnHeapValueHolder<>(person, -1, false, new IdentityCopier<>());
    person.age = 25;

    assertSame(person, valueHolder.get());
  }

  private static class Person {
    String name;
    int age;

    Person(Person other) {
      this.name = other.name;
      this.age = other.age;
    }

    Person(String name, int age) {
      this.name = name;
      this.age = age;
    }

    @Override
    public boolean equals(final Object other) {
      if(this == other) return true;
      if(other == null || this.getClass() != other.getClass()) return false;

      Person that = (Person)other;
      if(name != that.name || age != that.age) return false;

      return true;
    }

    @Override
    public int hashCode() {
      int result = 1;
      result = 31 * result + age;
      result = 31 * result + name.hashCode();
      return result;
    }
  }

  public static class PersonCopier extends ReadWriteCopier<Person> {

    @Override
    public Person copy(final Person obj) {
      return new Person(obj);
    }
  }
}


text:
<resources>
    <string name="app_name">Bootstrap</string>
    <string name="popular">Popular</string>
    <string name="editors">Editors</string>
    <string name="upcoming">Upcoming</string>
    <string name="fresh">Fresh</string>
</resources>


text:
<?php

namespace Sonata\CoreBundle\Model\Adapter;

class AdapterChain implements AdapterInterface
{
    protected $adapters = array();

    /**
     * @param AdapterInterface $adapter
     */
    public function addAdapter(AdapterInterface $adapter)
    {
        $this->adapters[] = $adapter;
    }

    /**
     * {@inheritdoc}
     */
    public function getNormalizedIdentifier($model)
    {
        foreach ($this->adapters as $adapter) {
            $identifier = $adapter->getNormalizedIdentifier($model);

            if ($identifier) {
                return $identifier;
            }
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function getUrlsafeIdentifier($model)
    {
        foreach ($this->adapters as $adapter) {
            $safeIdentifier = $adapter->getUrlsafeIdentifier($model);

            if ($safeIdentifier) {
                return $safeIdentifier;
            }
        }

        return null;
    }
}


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

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis
{
    /// <summary>
    /// Resolves references to source files specified in source code.
    /// </summary>
    public class SourceFileResolver : SourceReferenceResolver
    {
        public static SourceFileResolver Default { get; } = new SourceFileResolver(ImmutableArray<string>.Empty, baseDirectory: null);

        private readonly string _baseDirectory;
        private readonly ImmutableArray<string> _searchPaths;

        public SourceFileResolver(IEnumerable<string> searchPaths, string baseDirectory)
            : this(searchPaths.AsImmutableOrNull(), baseDirectory)
        {
        }

        public SourceFileResolver(ImmutableArray<string> searchPaths, string baseDirectory)
        {
            if (searchPaths.IsDefault)
            {
                throw new ArgumentNullException(nameof(searchPaths));
            }

            if (baseDirectory != null && PathUtilities.GetPathKind(baseDirectory) != PathKind.Absolute)
            {
                throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(baseDirectory));
            }

            _baseDirectory = baseDirectory;
            _searchPaths = searchPaths;
        }

        public string BaseDirectory
        {
            get { return _baseDirectory; }
        }

        public ImmutableArray<string> SearchPaths
        {
            get { return _searchPaths; }
        }

        public override string NormalizePath(string path, string baseFilePath)
        {
            return FileUtilities.NormalizeRelativePath(path, baseFilePath, _baseDirectory);
        }

        public override string ResolveReference(string path, string baseFilePath)
        {
            string resolvedPath = FileUtilities.ResolveRelativePath(path, baseFilePath, _baseDirectory, _searchPaths, FileExists);

            if (!FileExists(resolvedPath))
            {
                return null;
            }

            return FileUtilities.TryNormalizeAbsolutePath(resolvedPath);
        }

        public override Stream OpenRead(string resolvedPath)
        {
            CompilerPathUtilities.RequireAbsolutePath(resolvedPath, nameof(resolvedPath));
            return FileUtilities.OpenRead(resolvedPath);
        }

        protected virtual bool FileExists(string resolvedPath)
        {
            return PortableShim.File.Exists(resolvedPath);
        }

        public override bool Equals(object obj)
        {
            // Explicitly check that we're not comparing against a derived type
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }

            var other = (SourceFileResolver)obj;
            return string.Equals(_baseDirectory, other._baseDirectory, StringComparison.Ordinal) &&
                _searchPaths.SequenceEqual(other._searchPaths, StringComparer.Ordinal);
        }

        public override int GetHashCode()
        {
            return Hash.Combine(_baseDirectory != null ? StringComparer.Ordinal.GetHashCode(_baseDirectory) : 0,
                   Hash.CombineValues(_searchPaths, StringComparer.Ordinal));
        }
    }
}


text:
  <title>The Shopping List app</title>

Welcome to Meteor!

  {{> country}}

  {{> hello}}

<template name="hello">
  <button>Click Me</button>

You've pressed the button {{counter}} times.

</template>

<template name="country">

Hello from United States It is now {{currentTime}}

</template>


text:
  Saint-Martin-de-Fugères est
       un village
       localisé dans le département de Haute-Loire en Auvergne. Elle comptait 243 habitants en 2008.

La ville offre quelques  équipements sportifs, elle propose entre autres un terrain de sport et une boucle de randonnée.

À coté de Saint-Martin-de-Fugères sont positionnées géographiquement les villes de
Le Brignon à 5 km, 572 habitants,
Vielprat localisée à 5 km, 64 habitants,
Saint-Arcons-de-Barges située à 7 km, 124 habitants,
Le Monastier-sur-Gazeille à 6 km, 1 738 habitants,
Alleyrac à 4 km, 121 habitants,
Goudet située à 2 km, 62 habitants,
 entre autres. De plus, Saint-Martin-de-Fugères est située à seulement 15 km de Le Puy-en-Velay.

Le nombre de logements, à Saint-Martin-de-Fugères, était réparti en 2011 en un appartements et 251 maisons soit
 un marché relativement équilibré.

Si vous pensez emmenager à Saint-Martin-de-Fugères, vous pourrez aisément trouver une maison à acheter.


text:
<?php

namespace SendGrid\Mail;

/**
 * This class is used to construct a Section object for the /mail/send API call
 *
 * An object of key/value pairs that define block sections of code to be used
 * as substitutions
 *
 * @package SendGrid\Mail
 */
class Section implements \JsonSerializable
{
    /** @var $key string Section key */
    private $key;
    /** @var $value string Section value */
    private $value;

    /**
     * Optional constructor
     *
     * @param string|null $key Section key
     * @param string|null $value Section value
     */
    public function __construct($key = null, $value = null)
    {
        if (isset($key)) {
            $this->setKey($key);
        }
        if (isset($value)) {
            $this->setValue($value);
        }
    }

    /**
     * Add the key on a Section object
     *
     * @param string $key Section key
     *
     * @throws TypeException
     */
    public function setKey($key)
    {
        if (!is_string($key)) {
            throw new TypeException('$key must be of type string.');
        }
        $this->key = $key;
    }

    /**
     * Retrieve the key from a Section object
     *
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * Add the value on a Section object
     *
     * @param string $value Section value
     *
     * @throws TypeException
     */
    public function setValue($value)
    {
        if (!is_string($value)) {
            throw new TypeException('$value must be of type string.');
        }
        $this->value = $value;
    }

    /**
     * Retrieve the value from a Section object
     *
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Return an array representing a Section object for the SendGrid API
     *
     * @return null|array
     */
    public function jsonSerialize()
    {
        return array_filter(
            [
                'key' => $this->getKey(),
                'value' => $this->getValue()
            ],
            function ($value) {
                return $value !== null;
            }
        ) ?: null;
    }
}


text:
@extends('main')
@section('content')

@if (count($errors) > 0)

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

@endif

  <form method="POST" action="/auth/register">
      {!! csrf_field() !!}

          Name
          <input class="form-control" type="text" name="name" value="{{ old('name') }}">

          Email
          <input class="form-control" type="email" name="email" value="{{ old('email') }}">

          Password
          <input class="form-control" type="password" name="password">

          Confirm Password
          <input class="form-control" type="password" name="password_confirmation">

          <button class="btn btn-default" type="submit">Register</button>

  </form>

@endsection


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <link rel="stylesheet" type="text/css" href="__CSS__/172/css/snower.css" media="all" />
<link rel="stylesheet" type="text/css" href="__CSS__/172/css/weimob-ui-1-1.css" media="all" />
<link rel="stylesheet" type="text/css" href="__CSS__/172/css/common.css" media="all" />
<link rel="stylesheet" type="text/css" href="__CSS__/172/css/home-2.css" media="all" />

<title>{gr-$tpl.wxname}</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
		<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">

            <meta content="application/xhtml+xml;charset=UTF-8" http-equiv="Content-Type">
            <meta content="no-cache,must-revalidate" http-equiv="Cache-Control">
            <meta content="no-cache" http-equiv="pragma">
            <meta content="0" http-equiv="expires">
            <meta content="telephone=no, address=no" name="format-detection">
            <meta content="width=device-width, initial-scale=1.0" name="viewport">
            <meta name="apple-mobile-web-app-capable" content="yes" />
            <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

    {gr-$zhidacode}

    <if condition="$homeInfo['musicurl'] neq false"><include file="Index:music"/></if>
<link rel="stylesheet" type="text/css" href="__CSS__/172/css/font-awesome.css?v=2014051116" media="all" />

<volist name="flash" id="so">

</volist>

<volist name="flash" id="so"><li <if condition="$i eq 1">class="on"</if>
</volist>

                											<volist name="info" id="vo"><a href="<if condition="$vo['url'] eq ''">{gr-:U('Wap/Index/lists',array('classid'=>$vo['id'],'token'=>$vo['token']))}<else/>{gr-$vo.url|htmlspecialchars_decode}</if>" class="weimob-list-item">

{gr-$vo.name}

{gr-$vo.info}

                    </volist>

<if condition="$iscopyright eq 1">{gr-$homeInfo.copyright}<else/>{gr-$siteCopyright}</if>

<include file="Index:styleInclude"/>


text:
<?php

namespace Kanboard\ServiceProvider;

use LogicException;
use RuntimeException;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use PicoDb\Database;

/**
 * Class DatabaseProvider
 *
 * @package Kanboard\ServiceProvider
 * @author  Frederic Guillot
 */
class DatabaseProvider implements ServiceProviderInterface
{
    /**
     * Register provider
     *
     * @access public
     * @param  Container $container
     * @return Container
     */
    public function register(Container $container)
    {
        $container['db'] = $this->getInstance();

        if (DB_RUN_MIGRATIONS) {
            self::runMigrations($container['db']);
        }

        if (DEBUG) {
            $container['db']->getStatementHandler()
                ->withLogging()
                ->withStopWatch()
            ;
        }

        return $container;
    }

    /**
     * Setup the database driver
     *
     * @access public
     * @return \PicoDb\Database
     */
    public function getInstance()
    {
        switch (DB_DRIVER) {
            case 'sqlite':
                $db = $this->getSqliteInstance();
                break;
            case 'mysql':
                $db = $this->getMysqlInstance();
                break;
            case 'postgres':
                $db = $this->getPostgresInstance();
                break;
            default:
                throw new LogicException('Database driver not supported');
        }

        return $db;
    }

    /**
     * Get current database version
     *
     * @static
     * @access public
     * @param  Database $db
     * @return int
     */
    public static function getSchemaVersion(Database $db)
    {
        return $db->getDriver()->getSchemaVersion();
    }

    /**
     * Execute database migrations
     *
     * @static
     * @access public
     * @throws RuntimeException
     * @param  Database $db
     * @return bool
     */
    public static function runMigrations(Database $db)
    {
        if (! $db->schema()->check(\Schema\VERSION)) {
            $messages = $db->getLogMessages();
            throw new RuntimeException('Unable to run SQL migrations: '.implode(', ', $messages).' (You may have to fix it manually)');
        }

        return true;
    }

    /**
     * Setup the Sqlite database driver
     *
     * @access private
     * @return \PicoDb\Database
     */
    private function getSqliteInstance()
    {
        require_once __DIR__.'/../Schema/Sqlite.php';

        return new Database(array(
            'driver' => 'sqlite',
            'filename' => DB_FILENAME,
        ));
    }

    /**
     * Setup the Mysql database driver
     *
     * @access private
     * @return \PicoDb\Database
     */
    private function getMysqlInstance()
    {
        require_once __DIR__.'/../Schema/Mysql.php';

        return new Database(array(
            'driver'   => 'mysql',
            'hostname' => DB_HOSTNAME,
            'username' => DB_USERNAME,
            'password' => DB_PASSWORD,
            'database' => DB_NAME,
            'charset'  => 'utf8',
            'port'     => DB_PORT,
            'ssl_key'  => DB_SSL_KEY,
            'ssl_ca'   => DB_SSL_CA,
            'ssl_cert' => DB_SSL_CERT,
            'verify_server_cert' => DB_VERIFY_SERVER_CERT,
            'timeout'  => DB_TIMEOUT,
        ));
    }

    /**
     * Setup the Postgres database driver
     *
     * @access private
     * @return \PicoDb\Database
     */
    private function getPostgresInstance()
    {
        require_once __DIR__.'/../Schema/Postgres.php';

        return new Database(array(
            'driver'   => 'postgres',
            'hostname' => DB_HOSTNAME,
            'username' => DB_USERNAME,
            'password' => DB_PASSWORD,
            'database' => DB_NAME,
            'port'     => DB_PORT,
            'timeout'  => DB_TIMEOUT,
        ));
    }
}


text:
<?php

/*
 *
 *  ____            _        _   __  __ _                  __  __ ____
 * |  _ \ ___   ___| | _____| |_|  \/  (_)_ __   ___      |  \/  |  _ \
 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
 * |  __/ (_) | (__|   <  __/ |_| |  | | | | | |  __/_____| |  | |  __/
 * |_|   \___/ \___|_|\_\___|\__|_|  |_|_|_| |_|\___|     |_|  |_|_|
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * @author PocketMine Team
 * @link http://www.pocketmine.net/
 *
 *
*/

namespace pocketmine\plugin;

use LogLevel;
use pocketmine\Server;

class PluginLogger implements \AttachableLogger{

	private $pluginName;

	/** @var \LoggerAttachment[] */
	private $attachments = [];

	public function addAttachment(\LoggerAttachment $attachment){
		$this->attachments[spl_object_hash($attachment)] = $attachment;
	}

	public function removeAttachment(\LoggerAttachment $attachment){
		unset($this->attachments[spl_object_hash($attachment)]);
	}

	public function removeAttachments(){
		$this->attachments = [];
	}

	public function getAttachments(){
		return $this->attachments;
	}

	/**
	 * @param Plugin $context
	 */
	public function __construct(Plugin $context){
		$prefix = $context->getDescription()->getPrefix();
		$this->pluginName = $prefix != null ? "[$prefix] " : "[" . $context->getDescription()->getName() . "] ";
	}

	public function emergency($message){
		$this->log(LogLevel::EMERGENCY, $message);
	}

	public function alert($message){
		$this->log(LogLevel::ALERT, $message);
	}

	public function critical($message){
		$this->log(LogLevel::CRITICAL, $message);
	}

	public function error($message){
		$this->log(LogLevel::ERROR, $message);
	}

	public function warning($message){
		$this->log(LogLevel::WARNING, $message);
	}

	public function notice($message){
		$this->log(LogLevel::NOTICE, $message);
	}

	public function info($message){
		$this->log(LogLevel::INFO, $message);
	}

	public function debug($message){
		$this->log(LogLevel::DEBUG, $message);
	}

	public function logException(\Throwable $e, $trace = null){
		Server::getInstance()->getLogger()->logException($e, $trace);
	}

	public function log($level, $message){
		Server::getInstance()->getLogger()->log($level, $this->pluginName . $message);
		foreach($this->attachments as $attachment){
			$attachment->log($level, $message);
		}
	}
}


text:
namespace Algolia.Search.Models.Recommend
{
    /// <summary>
    /// Recommendation request configured to use the "bought-together" model, passed in a <see cref="RecommendRequests"/>
    /// </summary>
    public class BoughtTogetherRequest : RecommendRequest

    {
        /// <summary>
        /// The recommendation model to use: "bought-together"
        /// </summary>
        public new string Model { get; } = "bought-together";
    }
}