text:
package labels

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func mustNewMatcher(t *testing.T, mType MatchType, value string) *Matcher {
	m, err := NewMatcher(mType, "", value)
	require.NoError(t, err)
	return m
}

func TestMatcher(t *testing.T) {
	tests := []struct {
		matcher *Matcher
		value   string
		match   bool
	}{
		{
			matcher: mustNewMatcher(t, MatchEqual, "bar"),
			value:   "bar",
			match:   true,
		},
		{
			matcher: mustNewMatcher(t, MatchEqual, "bar"),
			value:   "foo-bar",
			match:   false,
		},
		{
			matcher: mustNewMatcher(t, MatchNotEqual, "bar"),
			value:   "bar",
			match:   false,
		},
		{
			matcher: mustNewMatcher(t, MatchNotEqual, "bar"),
			value:   "foo-bar",
			match:   true,
		},
		{
			matcher: mustNewMatcher(t, MatchRegexp, "bar"),
			value:   "bar",
			match:   true,
		},
		{
			matcher: mustNewMatcher(t, MatchRegexp, "bar"),
			value:   "foo-bar",
			match:   false,
		},
		{
			matcher: mustNewMatcher(t, MatchRegexp, ".*bar"),
			value:   "foo-bar",
			match:   true,
		},
		{
			matcher: mustNewMatcher(t, MatchNotRegexp, "bar"),
			value:   "bar",
			match:   false,
		},
		{
			matcher: mustNewMatcher(t, MatchNotRegexp, "bar"),
			value:   "foo-bar",
			match:   true,
		},
		{
			matcher: mustNewMatcher(t, MatchNotRegexp, ".*bar"),
			value:   "foo-bar",
			match:   false,
		},
	}

	for _, test := range tests {
		require.Equal(t, test.matcher.Matches(test.value), test.match)
	}
}

func TestInverse(t *testing.T) {
	tests := []struct {
		matcher  *Matcher
		expected *Matcher
	}{
		{
			matcher:  &Matcher{Type: MatchEqual, Name: "name1", Value: "value1"},
			expected: &Matcher{Type: MatchNotEqual, Name: "name1", Value: "value1"},
		},
		{
			matcher:  &Matcher{Type: MatchNotEqual, Name: "name2", Value: "value2"},
			expected: &Matcher{Type: MatchEqual, Name: "name2", Value: "value2"},
		},
		{
			matcher:  &Matcher{Type: MatchRegexp, Name: "name3", Value: "value3"},
			expected: &Matcher{Type: MatchNotRegexp, Name: "name3", Value: "value3"},
		},
		{
			matcher:  &Matcher{Type: MatchNotRegexp, Name: "name4", Value: "value4"},
			expected: &Matcher{Type: MatchRegexp, Name: "name4", Value: "value4"},
		},
	}

	for _, test := range tests {
		result, err := test.matcher.Inverse()
		require.NoError(t, err)
		require.Equal(t, test.expected.Type, result.Type)
	}
}

func BenchmarkMatchType_String(b *testing.B) {
	for i := 0; i <= b.N; i++ {
		_ = MatchType(i % int(MatchNotRegexp+1)).String()
	}
}


text:
package com.github.kolorobot.basic;

import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class SamePasswordsValidatorTest {

    private SamePasswordsValidator validator;

    @Before
    public void setup() {
        validator = new SamePasswordsValidator();
    }

    @Test
    public void isValidWhenPasswordsMatch() {
        // arrange
        Register register = Register.builder()
                .withPassword("x")
                .withConfirmedPassword("x")
                .build();

        // act & assert
        assertThat(validator.isValid(register)).isTrue();
    }

    @Test
    public void notValidWhenPasswordsDoNotMatch() {
        // arrange
        Register register = Register.builder()
                .withPassword("x")
                .withConfirmedPassword("y")
                .build();

        // act & assert
        assertThat(validator.isValid(register)).isFalse();
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* global Storage */
const port = chrome.runtime.connectNative('com.nicktomlin.kino')

const tabQuery = {
  active: true,
  windowType: chrome.tabs.WindowType.NORMAL,
  lastFocusedWindow: true
}

function pageAction (action, message) {
  chrome.tabs.query(tabQuery, async (tabs) => {
    if (!tabs.length) { console.info('No tabs found; you may be using a non active window'); return }
    if (chrome.runtime.lastError) {
      console.log('Error querying tabs', tabs, chrome.runtime.lastError.message)
    }

    const hostname = new URL(tabs[0].url).hostname
    const mappings = await Storage.getMappingsWithDefaults()

    const code = (mappings[hostname] && mappings[hostname][action]) || mappings[Storage.ALL_HOSTS][action]
    if (code) {
      console.info(`Dispatching to ${hostname} with ${code}`)
      chrome.tabs.executeScript(tabs[0].id, { code })
    }
  })
}

port.onMessage.addListener((rawMessage) => {
  let message = {}
  try { message = JSON.parse(rawMessage) } catch (e) {}
  console.info('Received native message', message)

  if (message.action) {
    pageAction(message.action, message)
  }
})

port.onDisconnect.addListener(() => {
  console.log('Disconnected from  native port:', chrome.runtime.lastError.message)
})


text:
layout: base
title:  'Statistics of Polarity in UD_Latin-LLCT'
udver: '2'
---

## Treebank Statistics: UD_Latin-LLCT: Features: `Polarity`

This feature is universal.
It occurs with 1 different values: `Neg`.

730 tokens (0%) have a non-empty value of `Polarity`.
16 types (0%) occur at least once with a non-empty value of `Polarity`.
7 lemmas (0%) occur at least once with a non-empty value of `Polarity`.
The feature is used with 5 part-of-speech tags: <tt>PART</tt> (659; 0% instances), <tt>DET</tt> (43; 0% instances), <tt>PRON</tt> (15; 0% instances), <tt>ADV</tt> (12; 0% instances), <tt>CCONJ</tt> (1; 0% instances).

### `PART`

659 <tt>PART</tt> tokens (78% of all `PART` tokens) have a non-empty value of `Polarity`.

`PART` tokens may have the following values of `Polarity`:

* `Neg` (659; 100% of non-empty `Polarity`): non, ne
* `EMPTY` (187): nam, quidem, autem, enim

### `DET`

43 <tt>DET</tt> tokens (0% of all `DET` tokens) have a non-empty value of `Polarity`.

The most frequent other feature values with which `DET` and `Polarity` co-occurred: <tt>Number[psor]</tt><tt>=EMPTY</tt> (43; 100%), <tt>Person[psor]</tt><tt>=EMPTY</tt> (43; 100%), <tt>Poss</tt><tt>=EMPTY</tt> (43; 100%), <tt>PronType</tt><tt>=Ind</tt> (43; 100%), <tt>Number</tt><tt>=Sing</tt> (36; 84%), <tt>Gender</tt><tt>=Masc</tt> (22; 51%).

`DET` tokens may have the following values of `Polarity`:

* `Neg` (43; 100% of non-empty `Polarity`): nulla, nulli, nullum, nullo, nullus, nonnulli, nullam, nonnullis
* `EMPTY` (19970): ipsa, qui, mea, suprascripta, nostro, ipsius, tuis, omnia, hanc, meis

### `PRON`

15 <tt>PRON</tt> tokens (0% of all `PRON` tokens) have a non-empty value of `Polarity`.

The most frequent other feature values with which `PRON` and `Polarity` co-occurred: <tt>Case</tt><tt>=Acc</tt> (15; 100%), <tt>Gender</tt><tt>=Neut</tt> (15; 100%), <tt>Number</tt><tt>=Sing</tt> (15; 100%), <tt>Person</tt><tt>=EMPTY</tt> (15; 100%), <tt>PronType</tt><tt>=Ind</tt> (15; 100%).

`PRON` tokens may have the following values of `Polarity`:

* `Neg` (15; 100% of non-empty `Polarity`): nihil, nihel
* `EMPTY` (18295): ego, me, nos, tibi, qui, eius, mihi, vobis, quas, id

### `ADV`

12 <tt>ADV</tt> tokens (0% of all `ADV` tokens) have a non-empty value of `Polarity`.

The most frequent other feature values with which `ADV` and `Polarity` co-occurred: <tt>AdvType</tt><tt>=EMPTY</tt> (12; 100%).

`ADV` tokens may have the following values of `Polarity`:

* `Neg` (12; 100% of non-empty `Polarity`): nihil, numquam, numqua, nunquam
* `EMPTY` (8187): supra, una, exinde, ubi, taliter, tantum, sic, unde, superius, ibi

### `CCONJ`

1 <tt>CCONJ</tt> tokens (0% of all `CCONJ` tokens) have a non-empty value of `Polarity`.

`CCONJ` tokens may have the following values of `Polarity`:

* `Neg` (1; 100% of non-empty `Polarity`): necnon
* `EMPTY` (14000): et, vel, aut, seo, adque, seu, nisi, que, sive, ac

## Relations with Agreement in `Polarity`

The 10 most frequent relations where parent and child node agree in `Polarity`:
<tt>PART --[<tt>fixed</tt>]--> PART</tt> (7; 100%).


text:
setupExec(SETUP_CALLBACK_INIT).then(function () {
    setupExec(SETUP_CALLBACK_TERM);
});

});


text:
package goryachev.common.util;

public interface HasDump
{
	public String getDump();
}


text:
using System;

// ReSharper disable CommentTypo
namespace SampSharp.GameMode.Definitions;

/// Contains all map icons.
public enum MapIcon
{
    /// Can be used in any color. Used for Single Player objectives.
    ColoredSquareTriangleDynamic = 0,

    /// 2 times bigger than ID 0 and without the border.
    [Obsolete("This element will cause your game to crash if you have map legends enabled while viewing the map", false)]
    WhiteSquare = 1,

    /// Will be used on the mini-map by default.
    [Obsolete("This element will cause your game to crash if you have map legends enabled while viewing the map", false)]
    PlayerPosition = 2,

    /// Your position when on the large map.
    PlayerMenuMap = 3,

    /// Always appears on the radar toward the north.
    [Obsolete("This element will cause your game to crash if you have map legends enabled while viewing the map", false)]
    North = 4,

    /// Air Yard
    AirYard = 5,

    /// Ammunation
    Ammunation = 6,

    /// Barber
    Barber = 7,

    /// Big Smoke
    BigSmoke = 8,

    /// Boat Yard
    BoatYard = 9,

    /// Burger Shot
    BurgerShot = 10,

    /// Quarry
    Quarry = 11,

    /// Catalina
    Catalina = 12,

    /// Cesar
    Cesar = 13,

    /// Cluckin' Bell
    CluckinBell = 14,

    /// Carl Johnson
    CarlJohnson = 15,

    /// C.R.A.S.H
    Crash = 16,

    /// Diner
    Diner = 17,

    /// Emmet
    Emmet = 18,

    /// Enemy Attack
    EnemyAttack = 19,

    /// Fire
    Fire = 20,

    /// Girlfriend
    Girlfriend = 21,

    /// Hospital
    Hospital = 22,

    /// Loco
    Loco = 23,

    /// Madd Dogg
    MaddDogg = 24,

    /// Caligulas
    Caligulas = 25,

    /// MC Loc
    McLoc = 26,

    /// Mod garage
    ModGarage = 27,

    /// OG Loc
    OgLoc = 28,

    /// Well Stacked Pizza Co
    WellStackedPizzaCo = 29,

    /// Police
    Police = 30,

    /// A property you're free to purchase.
    FreeProperty = 31,

    /// A property that isn't available for purchase.
    Property = 32,

    /// Race
    Race = 33,

    /// Ryder
    Ryder = 34,

    /// Used for safehouses where you save the game in singleplayer.
    SaveGame = 35,

    /// School
    School = 36,

    /// Unknown
    Unknown = 37,

    /// Sweet
    Sweet = 38,

    /// Tattoo
    Tattoo = 39,

    /// The Truth
    TheTruth = 40,

    /// Can be placed by players on the pause menu map by right-clicking
    Waypoint = 41,

    /// Toreno
    Toreno = 42,

    /// Triads
    Triads = 43,

    /// Triads Casino
    TriadsCasino = 44,

    /// Clothes
    Clothes = 45,

    /// Woozie
    Woozie = 46,

    /// Zero
    Zero = 47,

    /// Club
    Club = 48,

    /// Bar
    Bar = 49,

    /// Restaurant
    Restaurant = 50,

    /// Truck
    Truck = 51,

    /// Frequently used for banks.
    Robbery = 52,

    /// Race
    RaceFlag = 53,

    /// Gym
    Gym = 54,

    /// Car
    Car = 55,

    /// Light
    [Obsolete("This element will cause your game to crash if you have map legends enabled while viewing the map", false)]
    Light = 56,

    /// Closest airport
    ClosestAirport = 57,

    /// Varrios Los Aztecas
    VarriosLosAztecas = 58,

    /// Ballas
    Ballas = 59,

    /// Los Santos Vagos
    LosSantosVagos = 60,

    /// San Fierro Rifa
    SanFierroRifa = 61,

    /// Grove street
    GroveStreet = 62,

    /// Pay 'n' Spray
    PayNSpray = 63
}


text:
@interface UIViewController (MZTargetViewController)

- (UIViewController *)mz_parentTargetViewController;
- (UIViewController *)mz_childTargetViewControllerForStatusBarStyle;
- (UIViewController *)mz_childTargetViewControllerForStatusBarHidden;

@end


text:
module Foreign.Marshal.Utils.CompatSpec (main, spec) where

import Test.Hspec

import Foreign.Marshal.Alloc
import Foreign.Marshal.Utils.Compat
import Foreign.Ptr
import Foreign.Storable

main :: IO ()
main = hspec spec

spec :: Spec
spec = do
  describe "fillBytes" $
    it "fills a given number of bytes in memory area with a byte value" $ do
      alloca $ \ptr -> do
        let _ = ptr :: Ptr Int
        fillBytes ptr 0 $ sizeOf ptr
        peek ptr `shouldReturn` 0


text:
date:         2011-04-29
title:        Invalid form validation
description:  Whining about overly restrictive web form validation.
author:       Jonas Westerlund
tags:         html, javascript, regular-expressions, unicode
---

Every now and then I end up on a website that, for no good reason, rejects something I enter into a form.
Usually, bad [regular expression](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions) validation is causing this.
It is somewhat difficult to write [Unicode](http://en.wikipedia.org/wiki/Unicode)-aware regular expressions in JavaScript, so these expressions often consider a letter to be A to Z and nothing else.
So if you live in Umeå, or your name is José, you may be out of luck.
Why, then, is it hard to write good regular expressions? Often, developers just don't think about these issues, and if they do, they may be hindered by JavaScript's lack of Unicode features.

## Unicode in JavaScript

The [ECMAScript](http://en.wikipedia.org/wiki/ECMAScript) specification defines a string as a sequence of [UTF-16](http://en.wikipedia.org/wiki/UTF-16) code units. This implementation detail is fully exposed to programmers, which means they must sometimes deal with these code units directly.

If you are unfamiliar with UTF-16, it is one of several encodings for Unicode.
It is a variable-length encoding, so a single code point can be represented by one or two 16-bit code units.
Since strings are defined in terms of code units, this means that the value of their `length` property will not necessarily reflect the number of characters in the string, since a single character may be represented by two code units.
It also means that use of methods like `substring` can break characters, since they also operate on the code unit level.

In practice, this is rarely a problem, since the characters for most modern languages are assigned to the [basic multilingual plane](http://en.wikipedia.org/wiki/Basic_Multilingual_Plane#Basic_Multilingual_Plane), and can be represented by a single code unit.

## Unicode in regular expressions

A more problematic area is JavaScript regular expressions.

Unicode characters are organized into categories. There are categories for letters, numbers, punctuation and so on.
Some regular expression engines support these categories, so that you can easily match anything that belongs to a certain category.

JavaScript regular expressions currently do not support them.
They do support some [character classes](http://www.regular-expressions.info/charclass.html), but these are not Unicode-aware. This means that the [word character](http://www.regular-expressions.info/charclass.html#shorthand) class, for example, will only match the characters A to Z (and their lowercase counterparts), 0 to 9, and the underscore character.

## Form validation with regular expressions

Regular expressions are often used to perform client-side form validation.
HTML5 even introduced a new attribute for input elements, [`pattern`](http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#the-pattern-attribute), which contains a JavaScript regular expression that will be used to validate the input's value.

Since it is a bit difficult to write Unicode-friendly regular expressions in JavaScript, most developers don't.

A way to sidestep this issue is to simply be very permissive when validating form input.
A quick Google search for "javascript name validation regular expression" will find code like `var fnameRegxp = /^([a-zA-Z]+)$/`{.javascript}.
This will obviously not work very well, as it excludes a lot of letters and accents.
Instead, you could simply consider it valid if the user has entered anything at all, and not try to check if it contains letters only.

Another solution, if you really need it, is to use a library that adds these missing features. [XRegExp](http://xregexp.com/) is such a library, it provides a more usable implementation of regular expressions, with support for Unicode categories (through a [plugin](http://xregexp.com/plugins/)), named capture, and more.
With this library, you could instead write `XRegExp("^\\p{L}+$")`{.javascript} and it would at least match any letter, not just A to Z.

But still, don't be too restrictive with your validation scripts, you will more than likely reject valid input.
As an example, [this regular expression](http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html) is what would be required to validate that an email address conforms to [RFC 822](http://www.ietf.org/rfc/rfc0822.txt). And if you google for one, you will [find](http://javascript.about.com/library/blre.htm) [plenty](http://www.marketingtechblog.com/javascript-regex-emailaddress/) of [expressions](http://www.devx.com/tips/Tip/35130) that reject valid addresses.
You can see how difficult it is to write a correct one, and how easy it is to write an incorrect one, when you try to be restrictive.

If you must validate something at all, and absolutely want to use a regular expression to do it, make it as permissive as possible.


text:
#ifndef QQUICKANIMATEDSPRITE_P_H
#define QQUICKANIMATEDSPRITE_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <private/qtquickglobal_p.h>

QT_REQUIRE_CONFIG(quick_sprite);

#include <QtQuick/QQuickItem>
#include <private/qquicksprite_p.h>
#include <QtCore/qelapsedtimer.h>

QT_BEGIN_NAMESPACE

class QSGContext;
class QQuickSprite;
class QQuickSpriteEngine;
class QSGGeometryNode;
class QQuickAnimatedSpriteMaterial;
class QQuickAnimatedSpritePrivate;
class QSGSpriteNode;
class Q_AUTOTEST_EXPORT QQuickAnimatedSprite : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(bool running READ running WRITE setRunning NOTIFY runningChanged)
    Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate NOTIFY interpolateChanged)
    //###try to share similar spriteEngines for less overhead?
    //These properties come out of QQuickSprite, since an AnimatedSprite is a renderer for a single sprite
    Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
    Q_PROPERTY(bool reverse READ reverse WRITE setReverse NOTIFY reverseChanged)
    Q_PROPERTY(bool frameSync READ frameSync WRITE setFrameSync NOTIFY frameSyncChanged)
    Q_PROPERTY(int frameCount READ frameCount WRITE setFrameCount NOTIFY frameCountChanged)
    //If frame height or width is not specified, it is assumed to be a single long row of square frames.
    //Otherwise, it can be multiple contiguous rows, when one row runs out the next will be used.
    Q_PROPERTY(int frameHeight READ frameHeight WRITE setFrameHeight NOTIFY frameHeightChanged)
    Q_PROPERTY(int frameWidth READ frameWidth WRITE setFrameWidth NOTIFY frameWidthChanged)
    Q_PROPERTY(int frameX READ frameX WRITE setFrameX NOTIFY frameXChanged)
    Q_PROPERTY(int frameY READ frameY WRITE setFrameY NOTIFY frameYChanged)
    //Precedence order: frameRate, frameDuration
    Q_PROPERTY(qreal frameRate READ frameRate WRITE setFrameRate NOTIFY frameRateChanged RESET resetFrameRate)
    Q_PROPERTY(int frameDuration READ frameDuration WRITE setFrameDuration NOTIFY frameDurationChanged RESET resetFrameDuration)
    //Extra Simple Sprite Stuff
    Q_PROPERTY(int loops READ loops WRITE setLoops NOTIFY loopsChanged)
    Q_PROPERTY(bool paused READ paused WRITE setPaused NOTIFY pausedChanged)
    Q_PROPERTY(int currentFrame READ currentFrame WRITE setCurrentFrame NOTIFY currentFrameChanged)

public:
    explicit QQuickAnimatedSprite(QQuickItem *parent = 0);
    enum LoopParameters {
        Infinite = -1
    };
    Q_ENUM(LoopParameters)

    bool running() const;
    bool interpolate() const;
    QUrl source() const;
    bool reverse() const;
    bool frameSync() const;
    int frameCount() const;
    int frameHeight() const;
    int frameWidth() const;
    int frameX() const;
    int frameY() const;
    qreal frameRate() const;
    int frameDuration() const;
    int loops() const;
    bool paused() const;
    int currentFrame() const;

Q_SIGNALS:

    void pausedChanged(bool arg);
    void runningChanged(bool arg);
    void interpolateChanged(bool arg);

    void sourceChanged(QUrl arg);
    void reverseChanged(bool arg);
    void frameSyncChanged(bool arg);
    void frameCountChanged(int arg);
    void frameHeightChanged(int arg);
    void frameWidthChanged(int arg);
    void frameXChanged(int arg);
    void frameYChanged(int arg);
    void frameRateChanged(qreal arg);
    void frameDurationChanged(int arg);
    void loopsChanged(int arg);
    void currentFrameChanged(int arg);

public Q_SLOTS:
    void start();
    void stop();
    void restart() {stop(); start();}
    void advance(int frames=1);
    void pause();
    void resume();

    void setRunning(bool arg);
    void setPaused(bool arg);
    void setInterpolate(bool arg);
    void setSource(QUrl arg);
    void setReverse(bool arg);
    void setFrameSync(bool arg);
    void setFrameCount(int arg);
    void setFrameHeight(int arg);
    void setFrameWidth(int arg);
    void setFrameX(int arg);
    void setFrameY(int arg);
    void setFrameRate(qreal arg);
    void setFrameDuration(int arg);
    void resetFrameRate();
    void resetFrameDuration();
    void setLoops(int arg);
    void setCurrentFrame(int arg);

private Q_SLOTS:
    void createEngine();

protected Q_SLOTS:
    void reset();

protected:
    void componentComplete() Q_DECL_OVERRIDE;
    QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *) Q_DECL_OVERRIDE;
private:
    void maybeUpdate();
    bool isCurrentFrameChangedConnected();
    void prepareNextFrame(QSGSpriteNode *node);
    void reloadImage();
    QSGSpriteNode* initNode();

private:
    Q_DISABLE_COPY(QQuickAnimatedSprite)
    Q_DECLARE_PRIVATE(QQuickAnimatedSprite)
};

QT_END_NAMESPACE

#endif // QQUICKANIMATEDSPRITE_P_H


text:
package org.napile.idea.plugin.projectView;

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

import org.napile.compiler.lang.psi.NapileClassBody;
import org.napile.compiler.lang.psi.NapileClass;
import org.napile.compiler.lang.psi.NapileClassLike;
import org.napile.compiler.lang.psi.NapileDeclaration;
import org.napile.compiler.lang.psi.NapileFile;
import org.napile.idea.plugin.util.FileRootUtil;
import com.intellij.ide.projectView.SelectableTreeStructureProvider;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;

/**
 * User: Alefas
 * Date: 15.02.12
 */
public class NapileProjectViewProvider implements SelectableTreeStructureProvider, DumbAware
{
	private final Project myProject;

	public NapileProjectViewProvider(Project project)
	{
		myProject = project;
	}

	@Override
	public Collection<AbstractTreeNode> modify(AbstractTreeNode parent, Collection<AbstractTreeNode> children, ViewSettings settings)
	{
		List<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>(children.size());

		for(AbstractTreeNode child : children)
		{
			Object childValue = child.getValue();

			if(childValue instanceof NapileFile)
			{
				NapileFile file = (NapileFile) childValue;

				NapileClass mainClass = NapileProjectViewUtil.getClassIfHeSingle(file);
				if(mainClass != null)
					result.add(new NapileClassTreeNode(file.getProject(), mainClass, settings));
				else
					result.add(new NapileFileTreeNode(file.getProject(), file, settings));
			}
			else
			{
				result.add(child);
			}
		}

		return result;
	}

	@Override
	public Object getData(Collection<AbstractTreeNode> selected, String dataName)
	{
		return null;
	}

	@Override
	public PsiElement getTopLevelElement(PsiElement element)
	{
		PsiFile file = element.getContainingFile();
		if(file == null || !(file instanceof NapileFile))
			return null;

		VirtualFile virtualFile = file.getVirtualFile();
		assert virtualFile != null;

		if(!FileRootUtil.isNapileSourceFile(myProject, virtualFile))
			return file;

		PsiElement current = element;
		while(current != null)
		{
			if(isSelectable(current))
				break;
			current = current.getParent();
		}

		if(current instanceof NapileFile)
		{
			NapileClass[] declarations = ((NapileFile) current).getDeclarations();
			String nameWithoutExtension = virtualFile != null ? virtualFile.getNameWithoutExtension() : file.getName();
			if(declarations.length == 1 && declarations[0] != null &&
					nameWithoutExtension.equals(declarations[0].getName()))
				current = declarations[0];
		}

		return current != null ? current : file;
	}

	private static boolean isSelectable(PsiElement element)
	{
		if(element instanceof NapileFile)
			return true;
		if(element instanceof NapileDeclaration)
		{
			PsiElement parent = element.getParent();
			if(parent instanceof NapileFile)
			{
				return true;
			}
			else if(parent instanceof NapileClassBody)
			{
				parent = parent.getParent();
				if(parent instanceof NapileClassLike)
				{
					return isSelectable(parent);
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
}


text:
// The MIT License (MIT)
// Copyright © 2015 AppsLandia. All rights reserved.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package com.appslandia.plum.base;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.appslandia.common.utils.AssertUtils;

/**
 *
 * @author Loc Ha
 *
 */
public abstract class ActionParser {

	public abstract ControllerDescProvider getControllerDescProvider();

	public abstract AppConfig getAppConfig();

	public abstract LanguageProvider getLanguageProvider();

	public abstract String getActionExtension();

	public boolean parseActionContext(List<String> pathItems, ActionContext actionContext, Map<String, String> pathParamMap) {
		ControllerDesc controllerDesc;
		ActionDesc actionDesc;

		if (pathItems.size() == 0) {

			// {language}.{extension}
			controllerDesc = this.getControllerDescProvider().getDefault();
			actionDesc = controllerDesc.getActionDesc(ServletUtils.ACTION_INDEX);

		} else if (pathItems.size() == 1) {
			// /{controller}.{extension}
			String controller = pathItems.get(0);

			if (controller.equals(ServletUtils.ACTION_INDEX)) {
				controllerDesc = this.getControllerDescProvider().getDefault();
			} else {
				controllerDesc = this.getControllerDescProvider().getControllerDesc(controller);
				if (controllerDesc == null) {
					return false;
				}
			}

			actionDesc = controllerDesc.getActionDesc(ServletUtils.ACTION_INDEX);
			if ((actionDesc == null) || actionDesc.isChildAction()) {
				return false;
			}
			if (actionDesc.getPathParams().length > 0) {
				return false;
			}
		} else {
			// /{controller}(/{parameter})+.{extension} -> index action
			// /{controller}/{action}(/{parameter})+.{extension}
			String controller = pathItems.get(0);
			String action = pathItems.get(1);

			controllerDesc = this.getControllerDescProvider().getControllerDesc(controller);
			if (controllerDesc == null) {
				return false;
			}
			actionDesc = controllerDesc.getActionDesc(action);
			boolean actionFound = (actionDesc != null) && (actionDesc.isChildAction() == false);

			if (actionFound == false) {
				action = ServletUtils.ACTION_INDEX;
				actionDesc = controllerDesc.getActionDesc(action);

				if ((actionDesc == null) || actionDesc.isChildAction()) {
					return false;
				}
			}

			// Remove controller/action parameters
			pathItems.remove(0);
			if (actionFound) {
				pathItems.remove(0);
			}
			PathParam[] pathParams = actionDesc.getPathParams();
			if (pathItems.size() != pathParams.length) {
				return false;
			}

			// pathParamMap
			for (int i = 0; i < pathParams.length; i++) {
				PathParam pathParm = pathParams[i];
				if (pathParm.getParamName() != null) {
					String paramVal = pathItems.get(i).trim();
					if (paramVal.isEmpty()) {
						return false;
					}
					pathParamMap.put(pathParm.getParamName(), paramVal);
				} else {
					if (ActionPathUtils.parsePathParams(pathItems.get(i), pathParm.getPathParams(), pathParamMap) == false) {
						return false;
					}
				}
			}
		}

		actionContext.setControllerDesc(controllerDesc);
		actionContext.setActionDesc(actionDesc);
		return true;
	}

	public String toActionUrl(HttpServletRequest request, String language, String controller, String action, Map<String, Object> parameterMap) throws IllegalArgumentException {
		// controllerDesc
		ControllerDesc controllerDesc = this.getControllerDescProvider().getControllerDesc(controller);
		if (controllerDesc == null) {
			throw new IllegalArgumentException("Controller is not found (controller=" + controller + ")");
		}
		// actionDesc
		ActionDesc actionDesc = controllerDesc.getActionDesc(action);
		if ((actionDesc == null) || actionDesc.isChildAction()) {
			throw new IllegalArgumentException("Action is not found (controller=" + controller + ", action=" + action + ")");
		}

		// actionContext
		ActionContext actionContext = (ActionContext) request.getAttribute(ServletUtils.REQUEST_ATTRIBUTE_ACTION_CONTEXT);

		// URL
		StringBuilder url = new StringBuilder();

		// Scheme|Server|Port
		if (actionContext.getActionDesc().isEnableHttps() || request.isSecure()) {
			url.append("https://").append(request.getServerName());
			if (this.getAppConfig().getHttpsPort() != 443) {
				url.append(':').append(this.getAppConfig().getHttpsPort());
			}
		} else {
			url.append("http://").append(request.getServerName());
			if (this.getAppConfig().getHttpPort() != 80) {
				url.append(':').append(this.getAppConfig().getHttpPort());
			}
		}

		// Context path
		url.append(request.getServletContext().getContextPath());

		// Language
		if (language == null) {
			language = actionContext.getLanguageId();
			if (language != null) {
				url.append('/').append(language);
			}
		} else {
			if (this.getLanguageProvider().getLanguage(language) == null) {
				throw new IllegalArgumentException("Language is not supported (language=" + language + ")");
			}
			url.append('/').append(language);
		}
		// Controller
		url.append('/').append(controller);

		// Action
		boolean hasPathParams = (actionDesc.getPathParams().length > 0);
		if ((ServletUtils.ACTION_INDEX.equals(action) == false) || (hasPathParams == false)) {
			url.append('/').append(action);
		}

		// Path parameters
		if (parameterMap != null) {
			ActionPathUtils.addPathParams(url, parameterMap, actionDesc.getPathParams());
		} else {
			AssertUtils.assertFalse(hasPathParams, "Path parameters are required.");
		}

		// Extension
		url.append(this.getActionExtension());

		// Query String
		if ((parameterMap != null) && (parameterMap.isEmpty() == false)) {
			url.append('?');
			ActionPathUtils.addQueryParams(url, parameterMap, actionDesc.getPathParams());
		}
		return url.toString();
	}
}


text:
<?php

final class PonderAnswerEditController extends PonderController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();
    $id = $request->getURIData('id');

    $answer = id(new PonderAnswerQuery())
      ->setViewer($viewer)
      ->withIDs(array($id))
      ->requireCapabilities(
        array(
          PhabricatorPolicyCapability::CAN_VIEW,
          PhabricatorPolicyCapability::CAN_EDIT,
        ))
      ->executeOne();
    if (!$answer) {
      return new Aphront404Response();
    }

    $v_content = $answer->getContent();
    $v_status = $answer->getStatus();
    $e_content = true;

    $question = $answer->getQuestion();
    $qid = $question->getID();

    $answer_uri = $answer->getURI();

    $errors = array();
    if ($request->isFormPost()) {
      $v_content = $request->getStr('content');
      $v_status = $request->getStr('status');

      if (!strlen($v_content)) {
        $errors[] = pht('You must provide some substance in your answer.');
        $e_content = pht('Required');
      }

      if (!$errors) {
        $xactions = array();
        $xactions[] = id(new PonderAnswerTransaction())
          ->setTransactionType(PonderAnswerTransaction::TYPE_CONTENT)
          ->setNewValue($v_content);

        $xactions[] = id(new PonderAnswerTransaction())
          ->setTransactionType(PonderAnswerTransaction::TYPE_STATUS)
          ->setNewValue($v_status);

        $editor = id(new PonderAnswerEditor())
          ->setActor($viewer)
          ->setContentSourceFromRequest($request)
          ->setContinueOnNoEffect(true);

        $editor->applyTransactions($answer, $xactions);

        return id(new AphrontRedirectResponse())
          ->setURI($answer_uri);
      }
    }

    $answer_content_id = celerity_generate_unique_node_id();

    $form = id(new AphrontFormView())
      ->setUser($viewer)
      ->appendChild(
        id(new AphrontFormStaticControl())
          ->setLabel(pht('Question'))
          ->setValue($question->getTitle()))
      ->appendChild(
          id(new AphrontFormSelectControl())
            ->setLabel(pht('Status'))
            ->setName('status')
            ->setValue($v_status)
            ->setOptions(PonderAnswerStatus::getAnswerStatusMap()))
      ->appendChild(
        id(new PhabricatorRemarkupControl())
          ->setUser($viewer)
          ->setLabel(pht('Answer'))
          ->setName('content')
          ->setID($answer_content_id)
          ->setValue($v_content)
          ->setError($e_content))
      ->appendChild(
        id(new AphrontFormSubmitControl())
          ->setValue(pht('Submit'))
          ->addCancelButton($answer_uri));

    $crumbs = $this->buildApplicationCrumbs();
    $crumbs->addTextCrumb("Q{$qid}", $answer_uri);
    $crumbs->addTextCrumb(pht('Edit Answer'));

    $form_box = id(new PHUIObjectBoxView())
      ->setHeaderText(pht('Edit Answer'))
      ->setFormErrors($errors)
      ->setForm($form);

    $preview = id(new PHUIRemarkupPreviewPanel())
      ->setHeader(pht('Answer Preview'))
      ->setControlID($answer_content_id)
      ->setPreviewURI($this->getApplicationURI('preview/'));

    return $this->buildApplicationPage(
      array(
        $crumbs,
        $form_box,
        $preview,
      ),
      array(
        'title' => pht('Edit Answer'),
      ));

  }
}


text:
=head1 LICENSE

# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2022] EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=cut

=head1 NAME

Bio::EnsEMBL::Analysis::RunnableDB::RepeatMasker -

=head1 SYNOPSIS

  my $repeat_masker = Bio::EnsEMBL::Analysis::RunnableDB::RepeatMasker->
  new(
      -input_id => 'contig::AL805961.22.1.166258:1:166258:1',
      -db => $db,
      -analysis => $analysis,
     );
  $repeat_masker->fetch_input;
  $repeat_masker->run;
  $repeat_masker->write_output;

=head1 DESCRIPTION

This module provides an interface between the ensembl database and
the Runnable RepeatMasker which wraps the program RepeatMasker

This module can fetch appropriate input from the database
pass it to the runnable then write the results back to the database
in the repeat_feature and repeat_consensus tables

=head1 METHODS

=cut

package Bio::EnsEMBL::Analysis::RunnableDB::RepeatMasker;

use strict;
use warnings;

use Bio::EnsEMBL::Analysis::RunnableDB;
use Bio::EnsEMBL::Analysis::Runnable::RepeatMasker;

use vars qw(@ISA);

@ISA = qw(Bio::EnsEMBL::Analysis::RunnableDB);

=head2 fetch_input

  Arg [1]   : Bio::EnsEMBL::Analysis::RunnableDB::RepeatMasker
  Function  : fetch data out of database and create runnable
  Returntype: 1
  Exceptions: none
  Example   :

=cut

sub fetch_input{
  my ($self) = @_;
  my $slice = $self->fetch_sequence;
  $self->query($slice);
  my %parameters;
  if($self->parameters_hash){
    %parameters = %{$self->parameters_hash};
  }
  my $runnable = Bio::EnsEMBL::Analysis::Runnable::RepeatMasker->new
    (
     -query => $self->query,
     -program => $self->analysis->program_file,
     -analysis => $self->analysis,
     %parameters,
    );
  $self->runnable($runnable);
  return 1;
}

=head2 get_adaptor

  Arg [1]   : Bio::EnsEMBL::Analysis::RunnableDB::RepeatMasker
  Function  : get repeatfeature adaptor
  Returntype: Bio::EnsEMBL::DBSQL::RepeatFeatureAdaptor
  Exceptions: none
  Example   :

=cut

sub get_adaptor{
  my ($self) = @_;
  return $self->db->get_RepeatFeatureAdaptor;
}

1;


text:
<?php

namespace TMPHP\RestApiGenerators\Compilers\Controllers;

use Doctrine\DBAL\Schema\Column;
use Illuminate\Database\Eloquent\Model;
use TMPHP\RestApiGenerators\AbstractEntities\StubCompilerAbstract;
use TMPHP\RestApiGenerators\Compilers\Core\RulesArrayCompiler;
use TMPHP\RestApiGenerators\Support\SchemaManager;

/**
 * Class CrudControllerCompiler
 * @package TMPHP\RestApiGenerators\Compilers
 */
class CrudControllerCompiler extends StubCompilerAbstract
{
    /** @var string $controllersNamespace */
    private $controllersNamespace;

    /** @var string $modelsNamespace */
    private $modelsNamespace;

    /** @var string $transformersNamespace */
    private $transformersNamespace;

    /** @var  string */
    private $tableName;

    /** @var  Model */
    private $model;

    /** @var Column[] */
    private $columns;

    /**
     * @var SchemaManager
     */
    private $schema;

    /**
     * CrudControllerCompiler constructor.
     *
     * @param null $saveToPath
     * @param null $saveFileName
     * @param null $stub
     */
    public function __construct($saveToPath = null, $saveFileName = null, $stub = null)
    {
        $saveToPath = base_path(config('rest-api-generator.paths.controllers'));
        $saveFileName = '';

        $this->schema = new SchemaManager();
        $this->controllersNamespace = config('rest-api-generator.namespaces.controllers');
        $this->modelsNamespace = config('rest-api-generator.namespaces.models');
        $this->transformersNamespace = config('rest-api-generator.namespaces.transformers');

        parent::__construct($saveToPath, $saveFileName, $stub);
    }

    /**
     * Run compile process
     *
     * @param array $params
     *
     * @return bool|mixed|string
     */
    public function compile(array $params): string
    {
        //
        $this->replaceInStub([
            '{{Model}}' => ucfirst($params['modelNameCamelcase']),
            '{{controllersNamespace}}' => $this->controllersNamespace,
            '{{modelsNamespace}}' => $this->modelsNamespace,
            '{{transformersNamespace}}' => $this->transformersNamespace,
        ]);

        $this->saveFileName = ucfirst($params['modelNameCamelcase']) . 'Controller.php';
        $modelClassWithNamespace = $this->modelsNamespace. '\\'. ucfirst($params['modelNameCamelcase']);
        $this->model = new $modelClassWithNamespace();
        $this->tableName = $this->model->getTable();
        $this->columns = $this->schema->listTableColumns($this->tableName);

        //{{RulesArray}}
        $this->compileRulesArray($this->columns, $this->tableName);

        $this->saveStub();

        return $this->stub;
    }

    /**
     * @param array $columns
     * @param string $tableName
     */
    private function compileRulesArray(array $columns, string $tableName)
    {
        $rulesArrayCompiler = new RulesArrayCompiler();
        $rulesArrayCompiled = $rulesArrayCompiler->compile([
            'columns' => $columns,
            'tableName' => $tableName,
        ]);

        //{{rulesArray}}
        $this->replaceInStub(['{{rulesArray}}' => $rulesArrayCompiled]);
    }
}


text:
<?php

namespace Guy\Bundle\CnetBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AboutController extends Controller
{
    public function indexAction()
    {
        return $this->render('GuyCnetBundle:Default:about.html.twig');
    }

}


text:
<?php

namespace PHPExiftool\Driver\Tag\Sony;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class LateralChromaticAberration extends AbstractTag
{

    protected $Id = 8210;

    protected $Name = 'LateralChromaticAberration';

    protected $FullName = 'Sony::Main';

    protected $GroupName = 'Sony';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'Sony';

    protected $g2 = 'Camera';

    protected $Type = 'int32u';

    protected $Writable = true;

    protected $Description = 'Lateral Chromatic Aberration';

    protected $flag_Permanent = true;

    protected $Values = array(
        0 => array(
            'Id' => 0,
            'Label' => 'Off',
        ),
        2 => array(
            'Id' => 2,
            'Label' => 'Auto',
        ),
        '4294967295' => array(
            'Id' => '4294967295',
            'Label' => 'n/a',
        ),
    );

}


text:
/* Generated By:JJTree: Do not edit this line. OModifier.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.orientechnologies.orient.core.sql.parser;

import java.util.Map;

public class OModifier extends SimpleNode {

  boolean                    squareBrackets = false;
  OArrayRangeSelector        arrayRange;
  OOrBlock                   condition;
  OArraySingleValuesSelector arraySingleValues;
  OMethodCall                methodCall;
  OSuffixIdentifier          suffix;

  OModifier                  next;

  public OModifier(int id) {
    super(id);
  }

  public OModifier(OrientSql p, int id) {
    super(p, id);
  }

  /** Accept the visitor. **/
  public Object jjtAccept(OrientSqlVisitor visitor, Object data) {
    return visitor.visit(this, data);
  }

  @Override
  public String toString() {
    StringBuilder result = new StringBuilder();
    if (squareBrackets) {
      result.append("[");

      if (arrayRange != null) {
        result.append(arrayRange.toString());
      } else if (condition != null) {
        result.append(condition.toString());
      } else if (arraySingleValues != null) {
        result.append(arraySingleValues.toString());
      }

      result.append("]");
    } else if (methodCall != null) {
      result.append(methodCall.toString());
    } else if (suffix != null) {
      result.append(".");
      result.append(suffix.toString());
    }
    if (next != null) {
      result.append(next.toString());
    }
    return result.toString();
  }

  public void replaceParameters(Map<Object, Object> params) {
    if (arrayRange != null) {
      arrayRange.replaceParameters(params);
    }
    if (condition != null) {
      condition.replaceParameters(params);
    }
    if (arraySingleValues != null) {
      arraySingleValues.replaceParameters(params);
    }
    if (methodCall != null) {
      methodCall.replaceParameters(params);
    }
    if (next != null) {
      next.replaceParameters(params);
    }
  }
}
/* JavaCC - OriginalChecksum=39c21495d02f9b5007b4a2d6915496e1 (do not edit this line) */


text:
Edit Project

            Oops! You've got some things to fix.
            {{ form.errors|default:"" }}

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            Changes to your project were saved.

        <form id="form" class="form-horizontal" role="form" method='POST' onsubmit="return validateProjectForm()" autocomplete="off">{% csrf_token %}
          <input type="hidden" name="submenu" value="project_profile">
          <input type="hidden" name="id" value="{{ form.id.value|default:"" }}">

            Project Name (*)

              <input type="text" id="project-name" name="name" class="form-control" value="{{ form.name.value|default:"" }}">

            Client

              <input type="text" id="project-client" name="client" class="form-control" value="{{ form.client.value|default:"" }}">

            Type of Project (*)

              <select id="project-type" name="type" class="form-control" >
                  <option value=""></option>
                  <option value="Android" {% if form.type.value == "Android" %}selected{% endif %}>Android</option>
                  <option value="Backend/WS" {% if form.type.value == "Backend/WS" %}selected{% endif %}>Backend/WS</option>
                  <option value="Blackberry" {% if form.type.value == "Blackberry" %}selected{% endif %}>Blackberry</option>
                  <option value="Flash" {% if form.type.value == "Flash" %}selected{% endif %}>Flash</option>
                  <option value="iPad" {% if form.type.value == "iPad" %}selected{% endif %}>iPad</option>
                  <option value="iPhone" {% if form.type.value == "iPhone" %}selected{% endif %}>iPhone</option>
                  <option value="iPhone/iPad" {% if form.type.value == "iPhone/iPad" %}selected{% endif %}>iPhone/iPad</option>
                  <option value=".Net" {% if form.type.value == ".Net" %}selected{% endif %}>.Net</option>
                  <option value="Web" {% if form.type.value == "Web" %}selected{% endif %}>Web</option>
                  <option value="Other" {% if form.type.value == "Other" %}selected{% endif %}>Other</option>
               </select>

            Estimated Hours

              <input type="text" id="estimated-hours" name="estimated_hours" class="form-control" value="{{ form.estimated_hours.value|default:"" }}">

                    <input type="submit" id="edit-project" class="btn btn-success" value="Save"/>
                    Cancel

        </form>


text:
from tastypie.test import ResourceTestCase

from django.utils.unittest import skip

class UsersResourceTest(ResourceTestCase):

    fixtures = [
        'users_api_users.json'
    ]

    DETAIL_URL = '/users/%s/'
    LIST_URL = '/users/'

    USER_ID = 1
    USERNAME = 'admin'
    PASSWORD = 'admin'

    ADMIN_RESPONSE = {
        u'username': u'admin',
        u'resourceUri': u'/users/1/',
        u'firstName': u'',
        u'lastName': u'',
        u'isSuperuser': True,
        u'isStaff': True,
        u'email': u'admin@admin.com',
        u'isActive': True
    }

    @property
    def detail_uri(self):
        return self.DETAIL_URL % self.USER_ID

    @property
    def list_uri(self):
        return self.LIST_URL

    def login(self):
        self.api_client.client.login(username=self.USERNAME,
                                     password=self.PASSWORD)

    def logout(self):
        self.api_client.client.logout()

    ###########################################################################
    # NOT ALLOWED
    ###########################################################################
    def test_delete_list_not_allowed(self):
        self.login()
        response = self.api_client.delete(self.list_uri)
        self.assertHttpMethodNotAllowed(response)

    def test_put_list_not_allowed(self):
        self.login()
        response = self.api_client.put(self.list_uri)
        self.assertHttpMethodNotAllowed(response)

    def test_post_detail_not_allowed(self):
        self.login()

        data = {
            'username': 'newusers',
            'password': 'newpass'
        }

        response = self.api_client.post(self.detail_uri, data=data)
        self.assertHttpMethodNotAllowed(response)

    ###########################################################################
    # UNAUTHENTICATED
    ###########################################################################
    def test_get_list_unauthenticated(self):
        response = self.api_client.get(self.list_uri)
        self.assertHttpUnauthorized(response)

    def test_get_detail_unauthenticated(self):
        response = self.api_client.get(self.detail_uri)
        self.assertHttpUnauthorized(response)

    def test_post_list_unauthenticated(self):
        data = {
            'username': 'newusers',
            'password': 'newpass'
        }
        response = self.api_client.post(self.list_uri, data=data)
        self.assertHttpUnauthorized(response)

    def test_put_detail_unauthenticated(self):
        data = {
            'username': 'newusers',
            'password': 'newpass'
        }
        response = self.api_client.put(self.detail_uri, data=data)
        self.assertHttpUnauthorized(response)

    def test_delete_detail_unauthenticated(self):
        response = self.api_client.delete(self.detail_uri)
        self.assertHttpUnauthorized(response)

    ###########################################################################
    # UNAUTHORIZED
    ###########################################################################
    def test_post_list_unauthorized(self):
        self.USERNAME = 'user1'
        self.PASSWORD = 'user1'
        self.login()

        data = {
            'username': 'newusers',
            'password': 'newpass'
        }

        response = self.api_client.post(self.list_uri, data=data)
        self.assertHttpUnauthorized(response)

    def test_put_detail_unauthorized(self):
        self.USERNAME = 'user1'
        self.PASSWORD = 'user1'
        self.login()

        data = {
            'username': 'newusers',
            'password': 'newpass'
        }

        response = self.api_client.put(self.detail_uri, data=data)
        self.assertHttpUnauthorized(response)

    def test_delete_detail_unauthorized(self):
        self.USERNAME = 'user1'
        self.PASSWORD = 'user1'
        self.login()

        response = self.api_client.delete(self.detail_uri)
        self.assertHttpUnauthorized(response)

    ###########################################################################
    # GET
    ###########################################################################
    def test_get_list_superuser(self):
        self.login()

        response = self.api_client.get(self.list_uri)
        self.assertHttpOK(response)
        self.assertValidJSONResponse(response)

        res = self.deserialize(response)
        self.assertEqual(res['meta']['totalCount'], 2)
        self.assertDictContainsSubset(self.ADMIN_RESPONSE, res['objects'][0])

    def test_get_detail_superuser(self):
        self.login()

        response = self.api_client.get(self.detail_uri)
        self.assertHttpOK(response)
        self.assertValidJSONResponse(response)

        res = self.deserialize(response)
        self.assertDictContainsSubset(self.ADMIN_RESPONSE, res)

    def test_get_list_normal_user(self):
        self.USERNAME = 'user1'
        self.PASSWORD = 'user1'
        self.login()

        response = self.api_client.get(self.list_uri)
        self.assertHttpOK(response)

        res = self.deserialize(response)
        self.assertEqual(res['meta']['totalCount'], 2)

    def test_get_detail_normal_user(self):
        self.USERNAME = 'user1'
        self.PASSWORD = 'user1'
        self.login()

        response = self.api_client.get(self.detail_uri)
        self.assertHttpOK(response)

        res = self.deserialize(response)
        self.assertDictContainsSubset(self.ADMIN_RESPONSE, res)

    ###########################################################################
    # POST
    ###########################################################################
    def test_post_list(self):
        self.login()

        data = {
            'username': 'user2',
            'password': 'user2',
            'email': 'user2@admin.com'
        }

        response = self.api_client.post(self.list_uri, data=data)
        self.assertHttpCreated(response)

        res = self.deserialize(response)
        self.assertNotIn('password', res)

        resource_uri = res['resourceUri']
        response = self.api_client.get(resource_uri)
        self.assertDictContainsSubset({
            u'username': u'user2',
            u'resourceUri': resource_uri,
            u'firstName': u'',
            u'lastName': u'',
            u'isSuperuser': False,
            u'isStaff': False,
            u'email': u'user2@admin.com',
            u'isActive': True
        }, self.deserialize(response))

    def test_post_list_invalid(self):
        self.login()

        data = {}
        response = self.api_client.post(self.list_uri, data=data)
        self.assertHttpBadRequest(response)

        data = {'username': 'user2'}
        response = self.api_client.post(self.list_uri, data=data)
        self.assertHttpBadRequest(response)

        data = {'password': 'user2'}
        response = self.api_client.post(self.list_uri, data=data)
        self.assertHttpBadRequest(response)

        data = {
            'username': 'user2',
            'password': 'user2',
            'email': 'INVALID_EMAIL'
        }
        response = self.api_client.post(self.list_uri, data=data)
        self.assertHttpBadRequest(response)

    ###########################################################################
    # PUT
    ###########################################################################
    def test_put_detail(self):
        self.login()

        data = {
            'firstName': 'Admin',
            'lastName': 'Admin Last'
        }
        response = self.api_client.put(self.detail_uri, data=data)
        self.assertHttpOK(response)

        self.assertDictContainsSubset(data, self.deserialize(response))

        # Another user
        data = {
            'firstName': 'User 1',
            'lastName': '1 User'
        }
        self.USER_ID = 2
        response = self.api_client.put(self.detail_uri, data=data)
        self.assertHttpOK(response)

        self.assertDictContainsSubset(data, self.deserialize(response))

    def test_put_detail_superuser_change_password(self):
        self.login()

        self.USER_ID = 2
        data = {
            'password': 'new password'
        }
        response = self.api_client.put(self.detail_uri, data=data)
        self.assertHttpOK(response)

        self.logout()

        self.USERNAME = 'user1'
        self.PASSWORD = data['password']
        self.login()
        response = self.api_client.get(self.list_uri)
        self.assertHttpOK(response)

    @skip('Required with different authorization')
    def test_put_detail_owner_change_password(self):
        self.USERNAME = 'user1'
        self.PASSWORD = 'user1'
        self.USER_ID = 2
        self.login()

        data = {
            'password': 'new password'
        }
        response = self.api_client.put(self.detail_uri, data=data)
        self.assertHttpOK(response)

        self.logout()

        # Try to use old password, and fail!
        self.login()
        response = self.api_client.get(self.list_uri)
        self.assertHttpUnauthorized(response)

    def test_put_detail_invalid(self):
        self.login()

        data = {
            'email': 'INVALID_EMAIL'
        }
        response = self.api_client.put(self.detail_uri, data=data)
        self.assertHttpBadRequest(response)

    def test_put_detail_not_found(self):
        self.login()

        data = {
            'email': 'INVALID_EMAIL'
        }
        self.USER_ID = 100
        response = self.api_client.put(self.detail_uri, data=data)
        self.assertHttpBadRequest(response)

    ###########################################################################
    # DELETE
    ###########################################################################
    def test_delete_detail(self):
        self.login()

        self.USER_ID = 2

        response = self.api_client.delete(self.detail_uri)
        self.assertHttpAccepted(response)

    def test_delete_detail_not_found(self):
        self.login()

        self.USER_ID = 200

        response = self.api_client.delete(self.detail_uri)
        self.assertHttpNotFound(response)


text:
package com.visionarts.powerjambda.models;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;

import com.visionarts.powerjambda.AwsProxyRequest;
import com.visionarts.powerjambda.http.HttpMethod;

/**
 * The request to populate an action.
 *
 * @param <T> The type of body in an action request
 *
 */
public class ActionRequest<T> {

    private AwsProxyRequest request;
    private T body;

    public ActionRequest() {
        this(null);
    }

    public ActionRequest(AwsProxyRequest request) {
        this.request = request;
    }

    public AwsProxyRequest getOriginalRequest() {
        return request;
    }

    /**
     * Returns HTTP method.
     *
     * @return HTTP method
     */
    public HttpMethod getMethod() {
        return HttpMethod.valueOf(request.getHttpMethod());
    }

    /**
     * Returns the name of deployment stage on API Gateway.
     *
     * @return The name of stage
     */
    public String getStage() {
        return request.getRequestContext().getStage();
    }

    /**
     * Returns the stage variables defined for the stage in API Gateway.
     *
     * @return The stage variables
     */
    public Map<String, String> getStageVariables() {
        return request.getStageVariables();
    }

    /**
     * Returns the stage variable defined for the stage in API Gateway.
     *
     * @param key The key
     * @return The stage variable
     */
    public String getStageVariable(String key) {
        return request.getStageVariables().get(key);
    }

    public String getPath() {
        return request.getPath();
    }

    public Map<String, String> getHeaders() {
        return request.getHeaders();
    }

    public String getHeader(String key) {
        return request.getHeaders().get(key);
    }

    public Map<String, String> getPathParameters() {
        return Optional.ofNullable(request.getPathParameters())
                .orElse(Collections.emptyMap());
    }

    public String getPathParameter(String key) {
        return getPathParameters().get(key);
    }

    public Map<String, String> getQueryParameters() {
        return Optional.ofNullable(request.getQueryStringParameters())
                .orElse(Collections.emptyMap());
    }

    public String getQueryParameter(String key) {
        return getQueryParameters().get(key);
    }

    public T getBody() {
        return body;
    }

    public void setBody(T body) {
        this.body = body;
    }

    public String getBodyAsString() {
        return request.getBody();
    }
}


text:
namespace formulate.app.Configuration
{
    /// <summary>
    /// A configuration section for Formulate submissions.
    /// </summary>
    public sealed class SubmissionsConfig
    {
        #region Properties

        /// <summary>
        /// Gets or sets a value indicating whether to enable server side validation for submissions.
        /// </summary>
        public bool EnableServerSideValidation { get; set; }

        #endregion
    }
}


text:
FROM ubuntu:20.04
LABEL author="Adam Ewing <adam.ewing@gmail.com>"

ENV PATH=$PATH:$HOME/bin
ARG DEBIAN_FRONTEND=noninteractive

# Install dependencies
RUN apt-get update && apt-get upgrade -y && apt-get install -y \
    python3 \
    python3-pip \
    git \
    wget \
    build-essential \
    libz-dev \
    libglib2.0-dev \
    libbz2-dev \
    liblzma-dev \
    default-jre \
    autoconf \
    samtools \
    bwa

RUN mkdir $HOME/bin

RUN wget https://github.com/dzerbino/velvet/archive/refs/tags/v1.2.10.tar.gz && tar -xvzf v1.2.10.tar.gz
RUN make -C velvet-1.2.10
RUN cp velvet-1.2.10/velvetg $HOME/bin && cp velvet-1.2.10/velveth $HOME/bin

RUN git clone https://github.com/adamewing/exonerate.git
RUN cd exonerate && autoreconf -fi  && ./configure && make && make install

RUN wget https://github.com/broadinstitute/picard/releases/download/2.27.3/picard.jar
RUN chmod +x picard.jar
RUN export BAMSURGEON_PICARD_JAR=$HOME/picard.jar

RUN pip install pysam

RUN git clone https://github.com/adamewing/bamsurgeon.git
RUN export PATH=$PATH:$HOME/bin && cd bamsurgeon


text:
public class Contato {
	private String registro;
	private String tipo;
	private String operadora;

	public Contato(String registro, String tipo, String operadora) {
		this.registro = registro;
		this.tipo = tipo;
		this.operadora = operadora;
	}
	public Contato(){
		this.registro="";
		this.tipo="";
		this.operadora="";
	}

	public String getRegistro() {
		return registro;
	}

	public void setRegistro(String registro) {
		this.registro = registro;
	}

	public String getTipo() {
		return tipo;
	}

	public void setTipo(String tipo) {
		this.tipo = tipo;
	}

	public String getOperadora() {
		return operadora;
	}

	public void setOperadora(String operadora) {
		this.operadora = operadora;
	}

	public String retornaContato(){
		return this.tipo + " " +this.operadora+ " "+this.registro;
	}

}


text:
@interface ARArtworkContainerCoverDataSource : NSObject

/// File path for thumbnail of Grid View Item
- (NSString *)gridThumbnailPath:(NSString *)size container:(NSObject<ARArtworkContainer> *)object;

/// External URL for thumbnail of Grid View Item
- (NSURL *)gridThumbnailURL:(NSString *)size container:(NSObject<ARArtworkContainer> *)object;

/// Aspect ratio for the grid view item
- (float)aspectRatioForContainer:(NSObject<ARArtworkContainer> *)object;

@end


text:
The struct function allows you to manage data collections.
# Functions
## struct
Sample:
```
var Person = struct(["firstname", "lastname"]);
var peter = Person("Peter", "Doe");
//Doe
peter.lastname;
```
Parameter 1: String array with property names of the generated data collections. Return: A function that accepts as many parameters
as the array has items (2 in this sample). The returned function creates an array with the given properties.

# Location
* CoaLang in Java: [ccl/std/struct.cl2](https://github.com/coalang-soft/coastandardlib/blob/master/ccl/std/struct.cl2)


text:
#include "ble_gap_evt_app.h"
#include <string.h>
#include "ble_serialization.h"
#include "app_util.h"

#define PASSKEY_LEN sizeof (p_event->evt.gap_evt.params.passkey_display.passkey)

uint32_t ble_gap_evt_passkey_display_dec(uint8_t const * const p_buf,
                                         uint32_t              packet_len,
                                         ble_evt_t * const     p_event,
                                         uint32_t * const      p_event_len)
{
    uint32_t index = 0;
    uint32_t event_len;

    SER_ASSERT_NOT_NULL(p_buf);
    SER_ASSERT_NOT_NULL(p_event_len);

    event_len = offsetof(ble_gap_evt_t, params.passkey_display) + sizeof (ble_gap_evt_passkey_display_t);

    if (p_event == NULL)
    {
        *p_event_len = event_len;
        return NRF_SUCCESS;
    }

    SER_ASSERT(event_len <= *p_event_len, NRF_ERROR_DATA_SIZE);

    p_event->header.evt_id  = BLE_GAP_EVT_PASSKEY_DISPLAY;
    p_event->header.evt_len = event_len;

    uint32_t err_code = uint16_t_dec(p_buf, packet_len, &index, &p_event->evt.gap_evt.conn_handle);
    SER_ASSERT(err_code == NRF_SUCCESS, err_code);

    memcpy(p_event->evt.gap_evt.params.passkey_display.passkey, &p_buf[index], PASSKEY_LEN);
    index += PASSKEY_LEN;
    uint8_t match_req;

    err_code = uint8_t_dec(p_buf, packet_len, &index, &match_req);
    SER_ASSERT(err_code == NRF_SUCCESS, err_code);

    p_event->evt.gap_evt.params.passkey_display.match_request = (match_req & 0x01);

    SER_ASSERT_LENGTH_EQ(index, packet_len);

    *p_event_len = event_len;

    return NRF_SUCCESS;
}


text:
package local

import (
	"context"
	"net"
	"strings"

	"github.com/coredns/coredns/plugin"
	clog "github.com/coredns/coredns/plugin/pkg/log"
	"github.com/coredns/coredns/request"

	"github.com/miekg/dns"
)

var log = clog.NewWithPlugin("local")

// Local is a plugin that returns standard replies for local queries.
type Local struct {
	Next plugin.Handler
}

var zones = []string{"localhost.", "0.in-addr.arpa.", "127.in-addr.arpa.", "255.in-addr.arpa."}

func soaFromOrigin(origin string) []dns.RR {
	hdr := dns.RR_Header{Name: origin, Ttl: ttl, Class: dns.ClassINET, Rrtype: dns.TypeSOA}
	return []dns.RR{&dns.SOA{Hdr: hdr, Ns: "localhost.", Mbox: "root.localhost.", Serial: 1, Refresh: 0, Retry: 0, Expire: 0, Minttl: ttl}}
}

func nsFromOrigin(origin string) []dns.RR {
	hdr := dns.RR_Header{Name: origin, Ttl: ttl, Class: dns.ClassINET, Rrtype: dns.TypeNS}
	return []dns.RR{&dns.NS{Hdr: hdr, Ns: "localhost."}}
}

// ServeDNS implements the plugin.Handler interface.
func (l Local) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}
	qname := state.QName()

	lc := len("localhost.")
	if len(state.Name()) > lc && strings.HasPrefix(state.Name(), "localhost.") {
		// we have multiple labels, but the first one is localhost, intercept this and return 127.0.0.1 or ::1
		log.Debugf("Intercepting localhost query for %q %s, from %s", state.Name(), state.Type(), state.IP())
		LocalhostCount.Inc()
		reply := doLocalhost(state)
		w.WriteMsg(reply)
		return 0, nil
	}

	zone := plugin.Zones(zones).Matches(qname)
	if zone == "" {
		return plugin.NextOrFailure(l.Name(), l.Next, ctx, w, r)
	}

	m := new(dns.Msg)
	m.SetReply(r)
	zone = qname[len(qname)-len(zone):]

	switch q := state.Name(); q {
	case "localhost.", "0.in-addr.arpa.", "127.in-addr.arpa.", "255.in-addr.arpa.":
		switch state.QType() {
		case dns.TypeA:
			if q != "localhost." {
				// nodata
				m.Ns = soaFromOrigin(qname)
				break
			}

			hdr := dns.RR_Header{Name: qname, Ttl: ttl, Class: dns.ClassINET, Rrtype: dns.TypeA}
			m.Answer = []dns.RR{&dns.A{Hdr: hdr, A: net.ParseIP("127.0.0.1").To4()}}
		case dns.TypeAAAA:
			if q != "localhost." {
				// nodata
				m.Ns = soaFromOrigin(qname)
				break
			}

			hdr := dns.RR_Header{Name: qname, Ttl: ttl, Class: dns.ClassINET, Rrtype: dns.TypeAAAA}
			m.Answer = []dns.RR{&dns.AAAA{Hdr: hdr, AAAA: net.ParseIP("::1")}}
		case dns.TypeSOA:
			m.Answer = soaFromOrigin(qname)
		case dns.TypeNS:
			m.Answer = nsFromOrigin(qname)
		default:
			// nodata
			m.Ns = soaFromOrigin(qname)
		}
	case "1.0.0.127.in-addr.arpa.":
		switch state.QType() {
		case dns.TypePTR:
			hdr := dns.RR_Header{Name: qname, Ttl: ttl, Class: dns.ClassINET, Rrtype: dns.TypePTR}
			m.Answer = []dns.RR{&dns.PTR{Hdr: hdr, Ptr: "localhost."}}
		default:
			// nodata
			m.Ns = soaFromOrigin(zone)
		}
	}

	if len(m.Answer) == 0 && len(m.Ns) == 0 {
		m.Ns = soaFromOrigin(zone)
		m.Rcode = dns.RcodeNameError
	}

	w.WriteMsg(m)
	return 0, nil
}

// Name implements the plugin.Handler interface.
func (l Local) Name() string { return "local" }

func doLocalhost(state request.Request) *dns.Msg {
	m := new(dns.Msg)
	m.SetReply(state.Req)
	switch state.QType() {
	case dns.TypeA:
		hdr := dns.RR_Header{Name: state.QName(), Ttl: ttl, Class: dns.ClassINET, Rrtype: dns.TypeA}
		m.Answer = []dns.RR{&dns.A{Hdr: hdr, A: net.ParseIP("127.0.0.1").To4()}}
	case dns.TypeAAAA:
		hdr := dns.RR_Header{Name: state.QName(), Ttl: ttl, Class: dns.ClassINET, Rrtype: dns.TypeAAAA}
		m.Answer = []dns.RR{&dns.AAAA{Hdr: hdr, AAAA: net.ParseIP("::1")}}
	default:
		// nodata
		m.Ns = soaFromOrigin(state.QName())
	}
	return m
}

const ttl = 604800


text:
<?php
/**
 * A cryptographic random generator class used for generating secret keys
 *
 * This is based in part on Drupal code as well as what we used in our own code
 * prior to introduction of this class.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @author Daniel Friesen
 * @file
 */

class MWCryptRand {
	/**
	 * Minimum number of iterations we want to make in our drift calculations.
	 */
	const MIN_ITERATIONS = 1000;

	/**
	 * Number of milliseconds we want to spend generating each separate byte
	 * of the final generated bytes.
	 * This is used in combination with the hash length to determine the duration
	 * we should spend doing drift calculations.
	 */
	const MSEC_PER_BYTE = 0.5;

	/**
	 * Singleton instance for public use
	 */
	protected static $singleton = null;

	/**
	 * The hash algorithm being used
	 */
	protected $algo = null;

	/**
	 * The number of bytes outputted by the hash algorithm
	 */
	protected $hashLength = null;

	/**
	 * A boolean indicating whether the previous random generation was done using
	 * cryptographically strong random number generator or not.
	 */
	protected $strong = null;

	/**
	 * Initialize an initial random state based off of whatever we can find
	 * @return string
	 */
	protected function initialRandomState() {
		// $_SERVER contains a variety of unstable user and system specific information
		// It'll vary a little with each page, and vary even more with separate users
		// It'll also vary slightly across different machines
		$state = serialize( $_SERVER );

		// To try vary the system information of the state a bit more
		// by including the system's hostname into the state
		$state .= wfHostname();

		// Try to gather a little entropy from the different php rand sources
		$state .= rand() . uniqid( mt_rand(), true );

		// Include some information about the filesystem's current state in the random state
		$files = array();

		// We know this file is here so grab some info about ourselves
		$files[] = __FILE__;

		// We must also have a parent folder, and with the usual file structure, a grandparent
		$files[] = __DIR__;
		$files[] = dirname( __DIR__ );

		// The config file is likely the most often edited file we know should
		// be around so include its stat info into the state.
		// The constant with its location will almost always be defined, as
		// WebStart.php defines MW_CONFIG_FILE to $IP/LocalSettings.php unless
		// being configured with MW_CONFIG_CALLBACK (e.g. the installer).
		if ( defined( 'MW_CONFIG_FILE' ) ) {
			$files[] = MW_CONFIG_FILE;
		}

		foreach ( $files as $file ) {
			MediaWiki\suppressWarnings();
			$stat = stat( $file );
			MediaWiki\restoreWarnings();
			if ( $stat ) {
				// stat() duplicates data into numeric and string keys so kill off all the numeric ones
				foreach ( $stat as $k => $v ) {
					if ( is_numeric( $k ) ) {
						unset( $k );
					}
				}
				// The absolute filename itself will differ from install to install so don't leave it out
				if ( ( $path = realpath( $file ) ) !== false ) {
					$state .= $path;
				} else {
					$state .= $file;
				}
				$state .= implode( '', $stat );
			} else {
				// The fact that the file isn't there is worth at least a
				// minuscule amount of entropy.
				$state .= '0';
			}
		}

		// Try and make this a little more unstable by including the varying process
		// id of the php process we are running inside of if we are able to access it
		if ( function_exists( 'getmypid' ) ) {
			$state .= getmypid();
		}

		// If available try to increase the instability of the data by throwing in
		// the precise amount of memory that we happen to be using at the moment.
		if ( function_exists( 'memory_get_usage' ) ) {
			$state .= memory_get_usage( true );
		}

		// It's mostly worthless but throw the wiki's id into the data for a little more variance
		$state .= wfWikiID();

		// If we have a secret key set then throw it into the state as well
		global $wgSecretKey;
		if ( $wgSecretKey ) {
			$state .= $wgSecretKey;
		}

		return $state;
	}

	/**
	 * Randomly hash data while mixing in clock drift data for randomness
	 *
	 * @param string $data The data to randomly hash.
	 * @return string The hashed bytes
	 * @author Tim Starling
	 */
	protected function driftHash( $data ) {
		// Minimum number of iterations (to avoid slow operations causing the
		// loop to gather little entropy)
		$minIterations = self::MIN_ITERATIONS;
		// Duration of time to spend doing calculations (in seconds)
		$duration = ( self::MSEC_PER_BYTE / 1000 ) * $this->hashLength();
		// Create a buffer to use to trigger memory operations
		$bufLength = 10000000;
		$buffer = str_repeat( ' ', $bufLength );
		$bufPos = 0;

		// Iterate for $duration seconds or at least $minIterations number of iterations
		$iterations = 0;
		$startTime = microtime( true );
		$currentTime = $startTime;
		while ( $iterations < $minIterations || $currentTime - $startTime < $duration ) {
			// Trigger some memory writing to trigger some bus activity
			// This may create variance in the time between iterations
			$bufPos = ( $bufPos + 13 ) % $bufLength;
			$buffer[$bufPos] = ' ';
			// Add the drift between this iteration and the last in as entropy
			$nextTime = microtime( true );
			$delta = (int)( ( $nextTime - $currentTime ) * 1000000 );
			$data .= $delta;
			// Every 100 iterations hash the data and entropy
			if ( $iterations % 100 === 0 ) {
				$data = sha1( $data );
			}
			$currentTime = $nextTime;
			$iterations++;
		}
		$timeTaken = $currentTime - $startTime;
		$data = $this->hash( $data );

		wfDebug( __METHOD__ . ": Clock drift calculation " .
			"(time-taken=" . ( $timeTaken * 1000 ) . "ms, " .
			"iterations=$iterations, " .
			"time-per-iteration=" . ( $timeTaken / $iterations * 1e6 ) . "us)\n" );

		return $data;
	}

	/**
	 * Return a rolling random state initially build using data from unstable sources
	 * @return string A new weak random state
	 */
	protected function randomState() {
		static $state = null;
		if ( is_null( $state ) ) {
			// Initialize the state with whatever unstable data we can find
			// It's important that this data is hashed right afterwards to prevent
			// it from being leaked into the output stream
			$state = $this->hash( $this->initialRandomState() );
		}
		// Generate a new random state based on the initial random state or previous
		// random state by combining it with clock drift
		$state = $this->driftHash( $state );

		return $state;
	}

	/**
	 * Decide on the best acceptable hash algorithm we have available for hash()
	 * @throws MWException
	 * @return string A hash algorithm
	 */
	protected function hashAlgo() {
		if ( !is_null( $this->algo ) ) {
			return $this->algo;
		}

		$algos = hash_algos();
		$preference = array( 'whirlpool', 'sha256', 'sha1', 'md5' );

		foreach ( $preference as $algorithm ) {
			if ( in_array( $algorithm, $algos ) ) {
				$this->algo = $algorithm;
				wfDebug( __METHOD__ . ": Using the {$this->algo} hash algorithm.\n" );

				return $this->algo;
			}
		}

		// We only reach here if no acceptable hash is found in the list, this should
		// be a technical impossibility since most of php's hash list is fixed and
		// some of the ones we list are available as their own native functions
		// But since we already require at least 5.2 and hash() was default in
		// 5.1.2 we don't bother falling back to methods like sha1 and md5.
		throw new MWException( "Could not find an acceptable hashing function in hash_algos()" );
	}

	/**
	 * Return the byte-length output of the hash algorithm we are
	 * using in self::hash and self::hmac.
	 *
	 * @return int Number of bytes the hash outputs
	 */
	protected function hashLength() {
		if ( is_null( $this->hashLength ) ) {
			$this->hashLength = strlen( $this->hash( '' ) );
		}

		return $this->hashLength;
	}

	/**
	 * Generate an acceptably unstable one-way-hash of some text
	 * making use of the best hash algorithm that we have available.
	 *
	 * @param string $data
	 * @return string A raw hash of the data
	 */
	protected function hash( $data ) {
		return hash( $this->hashAlgo(), $data, true );
	}

	/**
	 * Generate an acceptably unstable one-way-hmac of some text
	 * making use of the best hash algorithm that we have available.
	 *
	 * @param string $data
	 * @param string $key
	 * @return string A raw hash of the data
	 */
	protected function hmac( $data, $key ) {
		return hash_hmac( $this->hashAlgo(), $data, $key, true );
	}

	/**
	 * @see self::wasStrong()
	 */
	public function realWasStrong() {
		if ( is_null( $this->strong ) ) {
			throw new MWException( __METHOD__ . ' called before generation of random data' );
		}

		return $this->strong;
	}

	/**
	 * @see self::generate()
	 */
	public function realGenerate( $bytes, $forceStrong = false ) {

		wfDebug( __METHOD__ . ": Generating cryptographic random bytes for " .
			wfGetAllCallers( 5 ) . "\n" );

		$bytes = floor( $bytes );
		static $buffer = '';
		if ( is_null( $this->strong ) ) {
			// Set strength to false initially until we know what source data is coming from
			$this->strong = true;
		}

		if ( strlen( $buffer ) < $bytes ) {
			// If available make use of mcrypt_create_iv URANDOM source to generate randomness
			// On unix-like systems this reads from /dev/urandom but does it without any buffering
			// and bypasses openbasedir restrictions, so it's preferable to reading directly
			// On Windows starting in PHP 5.3.0 Windows' native CryptGenRandom is used to generate
			// entropy so this is also preferable to just trying to read urandom because it may work
			// on Windows systems as well.
			if ( function_exists( 'mcrypt_create_iv' ) ) {
				$rem = $bytes - strlen( $buffer );
				$iv = mcrypt_create_iv( $rem, MCRYPT_DEV_URANDOM );
				if ( $iv === false ) {
					wfDebug( __METHOD__ . ": mcrypt_create_iv returned false.\n" );
				} else {
					$buffer .= $iv;
					wfDebug( __METHOD__ . ": mcrypt_create_iv generated " . strlen( $iv ) .
						" bytes of randomness.\n" );
				}
			}
		}

		if ( strlen( $buffer ) < $bytes ) {
			// If available make use of openssl's random_pseudo_bytes method to
			// attempt to generate randomness. However don't do this on Windows
			// with PHP < 5.3.4 due to a bug:
			// http://stackoverflow.com/questions/1940168/openssl-random-pseudo-bytes-is-slow-php
			// http://git.php.net/?p=php-src.git;a=commitdiff;h=cd62a70863c261b07f6dadedad9464f7e213cad5
			if ( function_exists( 'openssl_random_pseudo_bytes' )
				&& ( !wfIsWindows() || version_compare( PHP_VERSION, '5.3.4', '>=' ) )
			) {
				$rem = $bytes - strlen( $buffer );
				$openssl_bytes = openssl_random_pseudo_bytes( $rem, $openssl_strong );
				if ( $openssl_bytes === false ) {
					wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes returned false.\n" );
				} else {
					$buffer .= $openssl_bytes;
					wfDebug( __METHOD__ . ": openssl_random_pseudo_bytes generated " .
						strlen( $openssl_bytes ) . " bytes of " .
						( $openssl_strong ? "strong" : "weak" ) . " randomness.\n" );
				}
				if ( strlen( $buffer ) >= $bytes ) {
					// openssl tells us if the random source was strong, if some of our data was generated
					// using it use it's say on whether the randomness is strong
					$this->strong = !!$openssl_strong;
				}
			}
		}

		// Only read from urandom if we can control the buffer size or were passed forceStrong
		if ( strlen( $buffer ) < $bytes &&
			( function_exists( 'stream_set_read_buffer' ) || $forceStrong )
		) {
			$rem = $bytes - strlen( $buffer );
			if ( !function_exists( 'stream_set_read_buffer' ) && $forceStrong ) {
				wfDebug( __METHOD__ . ": Was forced to read from /dev/urandom " .
					"without control over the buffer size.\n" );
			}
			// /dev/urandom is generally considered the best possible commonly
			// available random source, and is available on most *nix systems.
			MediaWiki\suppressWarnings();
			$urandom = fopen( "/dev/urandom", "rb" );
			MediaWiki\restoreWarnings();

			// Attempt to read all our random data from urandom
			// php's fread always does buffered reads based on the stream's chunk_size
			// so in reality it will usually read more than the amount of data we're
			// asked for and not storing that risks depleting the system's random pool.
			// If stream_set_read_buffer is available set the chunk_size to the amount
			// of data we need. Otherwise read 8k, php's default chunk_size.
			if ( $urandom ) {
				// php's default chunk_size is 8k
				$chunk_size = 1024 * 8;
				if ( function_exists( 'stream_set_read_buffer' ) ) {
					// If possible set the chunk_size to the amount of data we need
					stream_set_read_buffer( $urandom, $rem );
					$chunk_size = $rem;
				}
				$random_bytes = fread( $urandom, max( $chunk_size, $rem ) );
				$buffer .= $random_bytes;
				fclose( $urandom );
				wfDebug( __METHOD__ . ": /dev/urandom generated " . strlen( $random_bytes ) .
					" bytes of randomness.\n" );

				if ( strlen( $buffer ) >= $bytes ) {
					// urandom is always strong, set to true if all our data was generated using it
					$this->strong = true;
				}
			} else {
				wfDebug( __METHOD__ . ": /dev/urandom could not be opened.\n" );
			}
		}

		// If we cannot use or generate enough data from a secure source
		// use this loop to generate a good set of pseudo random data.
		// This works by initializing a random state using a pile of unstable data
		// and continually shoving it through a hash along with a variable salt.
		// We hash the random state with more salt to avoid the state from leaking
		// out and being used to predict the /randomness/ that follows.
		if ( strlen( $buffer ) < $bytes ) {
			wfDebug( __METHOD__ .
				": Falling back to using a pseudo random state to generate randomness.\n" );
		}
		while ( strlen( $buffer ) < $bytes ) {
			$buffer .= $this->hmac( $this->randomState(), mt_rand() );
			// This code is never really cryptographically strong, if we use it
			// at all, then set strong to false.
			$this->strong = false;
		}

		// Once the buffer has been filled up with enough random data to fulfill
		// the request shift off enough data to handle the request and leave the
		// unused portion left inside the buffer for the next request for random data
		$generated = substr( $buffer, 0, $bytes );
		$buffer = substr( $buffer, $bytes );

		wfDebug( __METHOD__ . ": " . strlen( $buffer ) .
			" bytes of randomness leftover in the buffer.\n" );

		return $generated;
	}

	/**
	 * @see self::generateHex()
	 */
	public function realGenerateHex( $chars, $forceStrong = false ) {
		// hex strings are 2x the length of raw binary so we divide the length in half
		// odd numbers will result in a .5 that leads the generate() being 1 character
		// short, so we use ceil() to ensure that we always have enough bytes
		$bytes = ceil( $chars / 2 );
		// Generate the data and then convert it to a hex string
		$hex = bin2hex( $this->generate( $bytes, $forceStrong ) );

		// A bit of paranoia here, the caller asked for a specific length of string
		// here, and it's possible (eg when given an odd number) that we may actually
		// have at least 1 char more than they asked for. Just in case they made this
		// call intending to insert it into a database that does truncation we don't
		// want to give them too much and end up with their database and their live
		// code having two different values because part of what we gave them is truncated
		// hence, we strip out any run of characters longer than what we were asked for.
		return substr( $hex, 0, $chars );
	}

	/** Publicly exposed static methods **/

	/**
	 * Return a singleton instance of MWCryptRand
	 * @return MWCryptRand
	 */
	protected static function singleton() {
		if ( is_null( self::$singleton ) ) {
			self::$singleton = new self;
		}

		return self::$singleton;
	}

	/**
	 * Return a boolean indicating whether or not the source used for cryptographic
	 * random bytes generation in the previously run generate* call
	 * was cryptographically strong.
	 *
	 * @return bool Returns true if the source was strong, false if not.
	 */
	public static function wasStrong() {
		return self::singleton()->realWasStrong();
	}

	/**
	 * Generate a run of (ideally) cryptographically random data and return
	 * it in raw binary form.
	 * You can use MWCryptRand::wasStrong() if you wish to know if the source used
	 * was cryptographically strong.
	 *
	 * @param int $bytes The number of bytes of random data to generate
	 * @param bool $forceStrong Pass true if you want generate to prefer cryptographically
	 *                          strong sources of entropy even if reading from them may steal
	 *                          more entropy from the system than optimal.
	 * @return string Raw binary random data
	 */
	public static function generate( $bytes, $forceStrong = false ) {
		return self::singleton()->realGenerate( $bytes, $forceStrong );
	}

	/**
	 * Generate a run of (ideally) cryptographically random data and return
	 * it in hexadecimal string format.
	 * You can use MWCryptRand::wasStrong() if you wish to know if the source used
	 * was cryptographically strong.
	 *
	 * @param int $chars The number of hex chars of random data to generate
	 * @param bool $forceStrong Pass true if you want generate to prefer cryptographically
	 *                          strong sources of entropy even if reading from them may steal
	 *                          more entropy from the system than optimal.
	 * @return string Hexadecimal random data
	 */
	public static function generateHex( $chars, $forceStrong = false ) {
		return self::singleton()->realGenerateHex( $chars, $forceStrong );
	}
}


text:
module MethodChainable
  VERSION = "1.0.1"
end


text:
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions, URLSearchParams} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/catch';
import "rxjs/add/observable/interval";
import 'rxjs/add/operator/startWith';

import { GlobalService } from './global.service';

import { WalletCreation } from '../classes/wallet-creation';
import { WalletRecovery } from '../classes/wallet-recovery';
import { WalletLoad } from '../classes/wallet-load';
import { WalletInfo } from '../classes/wallet-info';
import { Mnemonic } from '../classes/mnemonic';
import { FeeEstimation } from '../classes/fee-estimation';
import { TransactionBuilding } from '../classes/transaction-building';
import { TransactionSending } from '../classes/transaction-sending';

/**
 * For information on the API specification have a look at our swagger files located at http://localhost:5000/swagger/ when running the daemon
 */
@Injectable()
export class ApiService {
    constructor(private http: Http, private globalService: GlobalService) {};

    private headers = new Headers({'Content-Type': 'application/json'});
    private pollingInterval = 3000;
    private bitcoinApiUrl = 'http://localhost:37220/api';
    private stratisApiUrl = 'http://localhost:37221/api';
    private currentApiUrl = 'http://localhost:37220/api';

    private getCurrentCoin() {
      let currentCoin = this.globalService.getCoinName();
      if (currentCoin === "Bitcoin" || currentCoin === "TestBitcoin") {
        this.currentApiUrl = this.bitcoinApiUrl;
      } else if (currentCoin === "Stratis" || currentCoin === "TestStratis") {
        this.currentApiUrl = this.stratisApiUrl;
      }
    }

    /**
     * Gets available wallets at the default path
     */
     getWalletFiles(): Observable<any> {
      return this.http
        .get(this.bitcoinApiUrl + '/wallet/files')
        .map((response: Response) => response);
     }

     /**
     * Gets available wallets at the default path
     */
    getStratisWalletFiles(): Observable<any> {
      return this.http
        .get(this.stratisApiUrl + '/wallet/files')
        .map((response: Response) => response);
     }

     /**
      * Get a new mnemonic
      */
    getNewMnemonic(): Observable<any> {
      let params: URLSearchParams = new URLSearchParams();
      params.set('language', 'English');
      params.set('wordCount', '12');

      return this.http
        .get(this.bitcoinApiUrl + '/wallet/mnemonic', new RequestOptions({headers: this.headers, search: params}))
        .map((response: Response) => response);
    }

    /**
     * Create a new Bitcoin wallet.
     */
    createBitcoinWallet(data: WalletCreation): Observable<any> {
      return this.http
        .post(this.bitcoinApiUrl + '/wallet/create/', JSON.stringify(data), {headers: this.headers})
        .map((response: Response) => response);
    }

    /**
     * Create a new Stratis wallet.
     */
    createStratisWallet(data: WalletCreation): Observable<any> {
      return this.http
        .post(this.stratisApiUrl + '/wallet/create/', JSON.stringify(data), {headers: this.headers})
        .map((response: Response) => response);
    }

    /**
     * Recover a Bitcoin wallet.
     */
    recoverBitcoinWallet(data: WalletRecovery): Observable<any> {
      return this.http
        .post(this.bitcoinApiUrl + '/wallet/recover/', JSON.stringify(data), {headers: this.headers})
        .map((response: Response) => response);
    }

    /**
     * Recover a Stratis wallet.
     */
    recoverStratisWallet(data: WalletRecovery): Observable<any> {
      return this.http
        .post(this.stratisApiUrl + '/wallet/recover/', JSON.stringify(data), {headers: this.headers})
        .map((response: Response) => response);
    }

    /**
     * Load a Bitcoin wallet
     */
    loadBitcoinWallet(data: WalletLoad): Observable<any> {
      return this.http
        .post(this.bitcoinApiUrl + '/wallet/load/', JSON.stringify(data), {headers: this.headers})
        .map((response: Response) => response);
    }

    /**
     * Load a Stratis wallet
     */
    loadStratisWallet(data: WalletLoad): Observable<any> {
      return this.http
        .post(this.stratisApiUrl + '/wallet/load/', JSON.stringify(data), {headers: this.headers})
        .map((response: Response) => response);
    }

    /**
     * Get wallet status info from the API.
     */
    getWalletStatus(): Observable<any> {
      this.getCurrentCoin();

      return this.http
        .get(this.currentApiUrl + '/wallet/status')
        .map((response: Response) => response);
    }

    /**
     * Get general wallet info from the API once.
     */
    getGeneralInfoOnce(data: WalletInfo): Observable<any> {
      let params: URLSearchParams = new URLSearchParams();
      params.set('Name', data.walletName);

      return this.http
        .get(this.bitcoinApiUrl + '/wallet/general-info', new RequestOptions({headers: this.headers, search: params}))
        .map((response: Response) => response);
    }

    /**
     * Get general wallet info from the API.
     */
    getGeneralInfo(data: WalletInfo): Observable<any> {
      this.getCurrentCoin();

      let params: URLSearchParams = new URLSearchParams();
      params.set('Name', data.walletName);

      return Observable
        .interval(this.pollingInterval)
        .startWith(0)
        .switchMap(() => this.http.get(this.currentApiUrl + '/wallet/general-info', new RequestOptions({headers: this.headers, search: params})))
        .map((response: Response) => response);
    }

    /**
     * Get wallet balance info from the API.
     */
    getWalletBalance(data: WalletInfo): Observable<any> {
      this.getCurrentCoin();

      let params: URLSearchParams = new URLSearchParams();
      params.set('walletName', data.walletName);

      return Observable
        .interval(this.pollingInterval)
        .startWith(0)
        .switchMap(() => this.http.get(this.currentApiUrl + '/wallet/balance', new RequestOptions({headers: this.headers, search: params})))
        .map((response: Response) => response);
    }

    /**
     * Get the maximum sendable amount for a given fee from the API
     */
    getMaximumBalance(data): Observable<any> {
      this.getCurrentCoin();

      let params: URLSearchParams = new URLSearchParams();
      params.set('walletName', data.walletName);
      params.set('accountName', "account 0");
      params.set('feeType', data.feeType);
      params.set('allowUnconfirmed', "true");

      return this.http
        .get(this.currentApiUrl + '/wallet/maxbalance', new RequestOptions({headers: this.headers, search: params}))
        .map((response: Response) => response);
    }

    /**
     * Get a wallets transaction history info from the API.
     */
    getWalletHistory(data: WalletInfo): Observable<any> {
      this.getCurrentCoin();

      let params: URLSearchParams = new URLSearchParams();
      params.set('walletName', data.walletName);

      return Observable
        .interval(this.pollingInterval)
        .startWith(0)
        .switchMap(() => this.http.get(this.currentApiUrl + '/wallet/history', new RequestOptions({headers: this.headers, search: params})))
        .map((response: Response) => response);
    }

    /**
     * Get an unused receive address for a certain wallet from the API.
     */
    getUnusedReceiveAddress(data: WalletInfo): Observable<any> {
      this.getCurrentCoin();

      let params: URLSearchParams = new URLSearchParams();
      params.set('walletName', data.walletName);
      params.set('accountName', "account 0"); //temporary
      return this.http
        .get(this.currentApiUrl + '/wallet/unusedaddress', new RequestOptions({headers: this.headers, search: params}))
        .map((response: Response) => response);
    }

    /**
     * Get multiple unused receive addresses for a certain wallet from the API.
     */
    getUnusedReceiveAddresses(data: WalletInfo, count: string): Observable<any> {
      this.getCurrentCoin();

      let params: URLSearchParams = new URLSearchParams();
      params.set('walletName', data.walletName);
      params.set('accountName', "account 0"); //temporary
      params.set('count', count);
      return this.http
        .get(this.currentApiUrl + '/wallet/unusedaddresses', new RequestOptions({headers: this.headers, search: params}))
        .map((response: Response) => response);
    }

    /**
     * Get get all receive addresses for an account of a wallet from the API.
     */
    getAllReceiveAddresses(data: WalletInfo): Observable<any> {
      this.getCurrentCoin();

      let params: URLSearchParams = new URLSearchParams();
      params.set('walletName', data.walletName);
      params.set('accountName', "account 0"); //temporary
      return this.http
        .get(this.currentApiUrl + '/wallet/addresses', new RequestOptions({headers: this.headers, search: params}))
        .map((response: Response) => response);
    }

    /**
     * Estimate the fee of a transaction
     */
    estimateFee(data: FeeEstimation): Observable<any> {
      this.getCurrentCoin();

      let params: URLSearchParams = new URLSearchParams();
      params.set('walletName', data.walletName);
      params.set('accountName', data.accountName);
      params.set('destinationAddress', data.destinationAddress);
      params.set('amount', data.amount);
      params.set('feeType', data.feeType);
      params.set('allowUnconfirmed', "true");

      return this.http
        .get(this.currentApiUrl + '/wallet/estimate-txfee', new RequestOptions({headers: this.headers, search: params}))
        .map((response: Response) => response);
    }

    /**
     * Build a transaction
     */
    buildTransaction(data: TransactionBuilding): Observable<any> {
      this.getCurrentCoin();

      return this.http
        .post(this.currentApiUrl + '/wallet/build-transaction', JSON.stringify(data), {headers: this.headers})
        .map((response: Response) => response);
    }

    /**
     * Send transaction
     */
    sendTransaction(data: TransactionSending): Observable<any> {
      this.getCurrentCoin();

      return this.http
        .post(this.currentApiUrl + '/wallet/send-transaction', JSON.stringify(data), {headers: this.headers})
        .map((response: Response) => response);
    }

    /**
     * Send shutdown signal to the daemon
     */
    shutdownNode(): Observable<any> {
      this.getCurrentCoin();

      return this.http
        .post(this.currentApiUrl + '/node/shutdown', '')
        .map((response: Response) => response);
    }
}