text:
# Migrating from JSS (optional)

This guide explains how to migrate from JSS to Emotion when updating from Material UI v4 to v5.

## Material UI v5 migration

1. [Getting started](/material-ui/migration/migration-v4/)
2. [Breaking changes part one: style and theme](/material-ui/migration/v5-style-changes/)
3. [Breaking changes part two: components](/material-ui/migration/v5-component-changes/)
4. Migrating from JSS 👈 _you are here_
5. [Troubleshooting](/material-ui/migration/troubleshooting/)

## Migrating from JSS to Emotion

One of the biggest changes in v5 is the replacement of JSS for [Emotion](https://emotion.sh/docs/introduction) (or [styled-components](https://styled-components.com/) as an alternative) as a default styling solution .

Note that you may continue to use JSS for adding overrides for the components (e.g. `makeStyles`, `withStyles`) even after migrating to v5.
Then, if at any point you want to move over to the new styling engine, you can refactor your components progressively.

This document reviews all the steps necessary to migrate away from JSS.

While you can use either of the following two options, the first is considered preferable:

### 1. Use styled or sx API

#### Codemod

We provide [a codemod](https://github.com/mui/material-ui/blob/master/packages/mui-codemod/README.md#jss-to-styled) to help migrate JSS styles to `styled` API, but this approach increases the CSS specificity.

:::info
Normally you wouldn't write styles like this.
But this is the best transformation that we could create with a codemod.

If you want to refine them later, you can refer to the examples shown in the sections below.
:::

```sh
npx @mui/codemod v5.0.0/jss-to-styled <path>
```

Example transformation:

```diff
 import Typography from '@mui/material/Typography';
-import makeStyles from '@mui/styles/makeStyles';
+import { styled } from '@mui/material/styles';

-const useStyles = makeStyles((theme) => ({
-  root: {
-    display: 'flex',
-    alignItems: 'center',
-    backgroundColor: theme.palette.primary.main
-  },
-  cta: {
-    borderRadius: theme.shape.radius
-  },
-  content: {
-    color: theme.palette.common.white,
-    fontSize: 16,
-    lineHeight: 1.7
-  },
-}))
+const PREFIX = 'MyCard';
+const classes = {
+  root: `${PREFIX}-root`,
+  cta: `${PREFIX}-cta`,
+  content: `${PREFIX}-content`,
+}
+const Root = styled('div')(({ theme }) => ({
+  [`&.${classes.root}`]: {
+    display: 'flex',
+    alignItems: 'center',
+    backgroundColor: theme.palette.primary.main
+  },
+  [`& .${classes.cta}`]: {
+    borderRadius: theme.shape.radius
+  },
+  [`& .${classes.content}`]: {
+    color: theme.palette.common.white,
+    fontSize: 16,
+    lineHeight: 1.7
+  },
+}))

 export const MyCard = () => {
-  const classes = useStyles();
   return (
-    <div className={classes.root}>
+    <Root className={classes.root}>
       {/* The benefit of this approach is that the code inside Root stays the same. */}
       <Typography className={classes.content}>...</Typography>
       <Button className={classes.cta}>Go</Button>
-    </div>
+    </Root>
   )
 }
```

:::warning
You should run this codemod on a small chunk of files and then check the changes before continuing, because in some cases you might need to adjust the code after the transformation—this codemod won't cover all cases.
:::

#### Manual

We recommend `sx` API over `styled` for creating responsive styles or overriding minor CSS.
[Read more about `sx` here](/system/the-sx-prop/).

```diff
 import Chip from '@mui/material/Chip';
-import makeStyles from '@mui/styles/makeStyles';
+import Box from '@mui/material/Box';
+import { styled } from '@mui/material/styles';

-const useStyles = makeStyles((theme) => ({
-  wrapper: {
-    display: 'flex',
-  },
-  chip: {
-    padding: theme.spacing(1, 1.5),
-    boxShadow: theme.shadows[1],
-  }
-}));

 function App() {
-  const classes = useStyles();
   return (
-    <div>
-      <Chip className={classes.chip} label="Chip" />
-    </div>
+    <Box sx={{ display: 'flex' }}>
+      <Chip label="Chip" sx={{ py: 1, px: 1.5, boxShadow: 1 }} />
+    </Box>
   );
 }
```

In some cases, you might want to create multiple styled components in a file instead of increasing CSS specificity.

For example:

```diff
-import makeStyles from '@mui/styles/makeStyles';
+import { styled } from '@mui/material/styles';

-const useStyles = makeStyles((theme) => ({
-  root: {
-    display: 'flex',
-    alignItems: 'center',
-    borderRadius: 20,
-    background: theme.palette.grey[50],
-  },
-  label: {
-    color: theme.palette.primary.main,
-  }
-}))
+const Root = styled('div')(({ theme }) => ({
+  display: 'flex',
+  alignItems: 'center',
+  borderRadius: 20,
+  background: theme.palette.grey[50],
+}))

+const Label = styled('span')(({ theme }) => ({
+  color: theme.palette.primary.main,
+}))

 function Status({ label }) {
-  const classes = useStyles();
   return (
-    <div className={classes.root}>
-      {icon}
-      <span className={classes.label}>{label}</span>
-    </div>
+    <Root>
+      {icon}
+      <Label>{label}</Label>
+    </Root>
   )
 }
```

:::warning
[This jss-to-styled tool](https://siriwatk.dev/tool/jss-to-styled) helps convert JSS to multiple styled components without increasing CSS specificity.

This tool is _not_ maintained by MUI.
:::

### 2. Use [tss-react](https://github.com/garronej/tss-react)

:::error
This API will not work if you are [using `styled-components` as the underlying styling engine in place of `@emotion`](/material-ui/guides/interoperability/#styled-components).
:::

The API is similar to JSS `makeStyles`, but under the hood, it uses `@emotion/react`.
It also features much better TypeScript support than v4's `makeStyles`.

In order to use it, you'll need to add it to your project's dependencies:

With npm:

```sh
npm install tss-react
```

With yarn:

```sh
yarn add tss-react
```

You will also need to edit your providers:

```diff
 import { render } from 'react-dom';
-import { StylesProvider } from '@material-ui/core/styles';
+import createCache from '@emotion/cache';
+import { CacheProvider } from "@emotion/react";

+export const muiCache = createCache({
+  'key': 'mui',
+  'prepend': true,
+});

 render(
-  <StylesProvider injectFirst>
+  <CacheProvider value={muiCache}>
     <Root />
-  </StylesProvider>,
+  </CacheProvider>,
   document.getElementById('root')
 );
```

#### Codemod

We provide [a codemod](https://github.com/mui/material-ui/blob/master/packages/mui-codemod/README.md#jss-to-tss-react) to help migrate JSS styles to the `tss-react` API.

```sh
npx @mui/codemod v5.0.0/jss-to-tss-react <path>
```

Example transformation:

```diff
 import React from 'react';
-import makeStyles from '@material-ui/styles/makeStyles';
+import { makeStyles } from 'tss-react/mui';
 import Button from '@mui/material/Button';
 import Link from '@mui/material/Link';

-const useStyles = makeStyles((theme) => {
+const useStyles = makeStyles()((theme) => {
   return {
     root: {
       color: theme.palette.primary.main,
     },
     apply: {
       marginRight: theme.spacing(2),
     },
   };
 });

 function Apply() {
-  const classes = useStyles();
+  const { classes } = useStyles();

   return (
     <div className={classes.root}>
       <Button component={Link} to="https://support.mui.com" className={classes.apply}>
         Apply now
       </Button>
     </div>
   );
 }

 export default Apply;
```

If you were using the `$` syntax and `clsx` to combine multiple CSS classes,
the transformation would look like this:

```diff
 import * as React from 'react';
-import { makeStyles } from '@material-ui/core/styles';
-import clsx from 'clsx';
+import { makeStyles } from 'tss-react/mui';

-const useStyles = makeStyles((theme) => ({
+const useStyles = makeStyles<void, 'child' | 'small'>()((theme, _params, classes) => ({
   parent: {
     padding: 30,
-    '&:hover $child': {
+    [`&:hover .${classes.child}`]: {
       backgroundColor: 'red',
     },
   },
   small: {},
   child: {
     backgroundColor: 'blue',
     height: 50,
-    '&$small': {
+    [`&.${classes.small}`]: {
       backgroundColor: 'lightblue',
       height: 30
     }
   },
 }));

 function App() {
-  const classes = useStyles();
+  const { classes, cx } = useStyles();
   return (
     <div className={classes.parent}>
       <div className={classes.child}>
         Background turns red when the mouse hovers over the parent.
       </div>
-      <div className={clsx(classes.child, classes.small)}>
+      <div className={cx(classes.child, classes.small)}>
         Background turns red when the mouse hovers over the parent.
         I am smaller than the other child.
       </div>
     </div>
   );
 }

 export default App;
```

:::warning
When using JavaScript (rather than TypeScript), remove `<void, 'child' | 'small'>`.
:::

The following is a comprehensive example using the `$` syntax, `useStyles()` parameters, merging in classes from a `classes` prop ([see doc](https://docs.tss-react.dev/your-own-classes-prop)) and [an explicit name for the stylesheet](https://docs.tss-react.dev/page-1/makestyles-usestyles#naming-the-stylesheets-useful-for-debugging-and-theme-style-overrides).

```diff
-import clsx from 'clsx';
-import { makeStyles, createStyles } from '@material-ui/core/styles';
+import { makeStyles } from 'tss-react/mui';

-const useStyles = makeStyles((theme) => createStyles<
-  'root' | 'small' | 'child', {color: 'primary' | 'secondary', padding: number}
->
-({
-  root: ({color, padding}) => ({
+const useStyles = makeStyles<{color: 'primary' | 'secondary', padding: number}, 'child' | 'small'>({name: 'App'})((theme, { color, padding }, classes) => ({
+  root: {
     padding: padding,
-    '&:hover $child': {
+    [`&:hover .${classes.child}`]: {
       backgroundColor: theme.palette[color].main,
     }
-  }),
+  },
   small: {},
   child: {
     border: '1px solid black',
     height: 50,
-    '&$small': {
+    [`&.${classes.small}`]: {
       height: 30
     }
   }
-}), {name: 'App'});
+}));

 function App({classes: classesProp}: {classes?: any}) {
-  const classes = useStyles({color: 'primary', padding: 30, classes: classesProp});
+  const { classes, cx } = useStyles({
+    color: 'primary',
+    padding: 30
+  }, {
+    props: {
+      classes: classesProp
+    }
+  });

   return (
     <div className={classes.root}>
       <div className={classes.child}>
         The Background take the primary theme color when the mouse hovers the parent.
       </div>
-      <div className={clsx(classes.child, classes.small)}>
+      <div className={cx(classes.child, classes.small)}>
         The Background take the primary theme color when the mouse hovers the parent.
         I am smaller than the other child.
       </div>
    </div>
  );
}

export default App;
```

After running the codemod, search your code for "TODO jss-to-tss-react codemod" to find cases that the codemod could not handle reliably.

There may be other cases beyond those with TODO comments that are not handled fully by the codemod—particularly if parts of the styles are returned by functions.

If the styles buried within a function use the `$` syntax or `useStyles` params, then those styles won't be migrated appropriately.

:::error
You should drop [`clsx`](https://www.npmjs.com/package/clsx) in favor of [`cx`](https://emotion.sh/docs/@emotion/css#cx).

The key advantage of `cx` is that it detects Emotion-generated class names to ensure that styles are overwritten in the correct order.

The default precedence of styles from multiple CSS classes is different between JSS and tss-react and some manual re-ordering of `cx` parameters
may be necessary—see [this issue comment](https://github.com/mui/material-ui/pull/31802#issuecomment-1093478971) for more details.
:::

To ensure that your class names always includes the actual name of your components, you can provide the `name` as an implicitly named key (`name: { App }`).

See [this tss-react doc](https://docs.tss-react.dev/page-1/makestyles-usestyles#naming-the-stylesheets-useful-for-debugging-and-theme-style-overrides) for details.

You may end up with eslint warnings [like this one](https://user-images.githubusercontent.com/6702424/148657837-eae48942-fb86-4516-abe4-5dc10f44f0be.png) if you deconstruct more than one item.

Don't hesitate to disable `eslint(prefer-const)`, [like this](https://github.com/thieryw/gitlanding/blob/b2b0c71d95cfd353979c86dfcfa1646ef1665043/.eslintrc.js#L17) in a regular project, or [like this](https://github.com/InseeFrLab/onyxia-web/blob/a264ec6a6a7110cb1a17b2e22cc0605901db6793/package.json#L133) in a CRA.

#### withStyles()

`tss-react` also features a [type-safe implementation](https://docs.tss-react.dev/page-1/withstyles) of [v4's `withStyles()`](https://v4.mui.com/styles/api/#withstyles-styles-options-higher-order-component).

:::info
The equivalent of the `$` syntax is also supported in tss's `withStyles()`.
[See doc](https://docs.tss-react.dev/nested-selectors#withstyles).
:::

```diff
-import Button from '@material-ui/core/Button';
+import Button from '@mui/material/Button';
-import withStyles from '@material-ui/styles/withStyles';
+import { withStyles } from 'tss-react/mui';

 const MyCustomButton = withStyles(
+  Button,
   (theme) => ({
     root: {
       minHeight: '30px',
     },
     textPrimary: {
       color: theme.palette.text.primary,
     },
     '@media (min-width: 960px)': {
       textPrimary: {
         fontWeight: 'bold',
       },
     },
   }),
-)(Button);
+);

 export default MyCustomButton;
```

#### Theme style overrides

[Global theme overrides](https://v4.mui.com/customization/components/#global-theme-override) are supported out of the box by TSS.

Follow the instructions in the relevant section of the [Breaking changes](/material-ui/migration/v5-style-changes/#restructure-component-definitions) doc, and [provide a `name` to `makeStyles`](https://docs.tss-react.dev/page-1/makestyles-usestyles/#naming-the-stylesheets-useful-for-debugging-and-theme-style-overrides).

In Material UI v5, [style overrides also accept callbacks](https://mui.com/material-ui/customization/theme-components/).

By default, TSS is only able to provide the theme.
If you want to provide the props and the `ownerState`, [please refer to this documentation](https://docs.tss-react.dev/mui-theme-styleoverrides).

:::warning
tss-react is _not_ maintained by MUI.

If you have any question about how to setup SSR (Next.js), or if you are wondering
how to customize the `theme` object, please refer to the tss-react documentation—particularly the [MUI integration section](https://github.com/garronej/tss-react#mui-integration).

You can also [submit an issue](https://github.com/garronej/tss-react/issues/new) for any bug or feature request, and [start a discussion](https://github.com/garronej/tss-react/discussions) if you need help.
:::

## Complete the migration

Once you migrate all of the styling, remove unnecessary `@mui/styles` by uninstalling the package.

With npm:

```sh
npm uninstall @mui/styles
```

With yarn:

```sh
yarn remove @mui/styles
```

:::warning
`@emotion/styled` is a peer dependency of `@mui/material`.
You must keep it in your dependencies even if you never explicitly use it.
:::


text:
package org.finos.waltz.model.allocation;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;

@Value.Immutable
@JsonSerialize(as = ImmutableMeasurablePercentage.class)
@JsonDeserialize(as = ImmutableMeasurablePercentage.class)
public abstract class MeasurablePercentage {

    public abstract int percentage();
    public abstract long measurableId();

    public static MeasurablePercentage mkMeasurablePercentage(long measurableId, int percentage) {
        return ImmutableMeasurablePercentage
                .builder()
                .percentage(percentage)
                .measurableId(measurableId)
                .build();
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace g{namespace Android{namespace android{namespace graphics{struct Color;}}}}

namespace g{
namespace Android{
namespace android{
namespace graphics{

// public sealed extern class Color :4713
// {
::g::Android::java::lang::Object_type* Color_typeof();
void Color___Init2_fn();
void Color__argb_fn(int* arg0, int* arg1, int* arg2, int* arg3, int* __retval);
void Color__argb_IMPL_6680_fn(int* arg0_, int* arg1_, int* arg2_, int* arg3_, int* __retval);

struct Color : ::g::Android::java::lang::Object
{
    static jclass _javaClass2_;
    static jclass& _javaClass2() { return _javaClass2_; }
    static jmethodID argb_6680_ID_;
    static jmethodID& argb_6680_ID() { return argb_6680_ID_; }

    static void _Init2();
    static int argb(int arg0, int arg1, int arg2, int arg3);
    static int argb_IMPL_6680(int arg0_, int arg1_, int arg2_, int arg3_);
};
// }

}}}} // ::g::Android::android::graphics


text:
require "spec_helper"

describe Draisine::IpChecker do
  subject { described_class.new(%w[127.0.0.1 192.168.0.1/24]) }

  describe "#check" do
    it "returns true if any of the ranges match input" do
      expect(subject.check('127.0.0.1')).to be_truthy
      expect(subject.check('192.168.0.24')).to be_truthy
      expect(subject.check('192.168.0.191')).to be_truthy
    end

    it "returns false if none of the ranges match input" do
      expect(subject.check('129.0.0.1')).to be_falsey
      expect(subject.check('192.169.0.24')).to be_falsey
      expect(subject.check('192.168.1.191')).to be_falsey
    end
  end
end


text:
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;

module.exports.translate = function (load) {
  if (load.source.indexOf('moduleId') != -1) return load;

  var url = document.createElement('a');
  url.href = load.address;

  var basePathParts = url.pathname.split('/');

  basePathParts.pop();
  var basePath = basePathParts.join('/');

  var baseHref = document.createElement('a');
  baseHref.href = this.baseURL;
  baseHref = baseHref.pathname;

  if (!baseHref.startsWith('/base/')) { // it is not karma
    basePath = basePath.replace(baseHref, '');
  }

  load.source = load.source
    .replace(templateUrlRegex, function (match, quote, url) {
      var resolvedUrl = url;

      if (url.startsWith('.')) {
        resolvedUrl = basePath + url.substr(1);
      }

      return 'templateUrl: "' + resolvedUrl + '"';
    })
    .replace(stylesRegex, function (match, relativeUrls) {
      var urls = [];

      while ((match = stringRegex.exec(relativeUrls)) !== null) {
        if (match[2].startsWith('.')) {
          urls.push('"' + basePath + match[2].substr(1) + '"');
        } else {
          urls.push('"' + match[2] + '"');
        }
      }

      return "styleUrls: [" + urls.join(', ') + "]";
    });

  return load;
};


text:
<?php

namespace VacStatus\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

use VacStatus\Steam\Steam;

use Carbon;

class UserList extends Model
{
	use SoftDeletes;

	protected $table = 'user_list';
	protected $dates = ['deleted_at'];
    protected $casts = [
    	// users.*
        'site_admin' => 'integer',
        'donation' => 'integer',
        'beta' => 'integer',
        // total added
        'total' => 'integer',
    ];

	public function UserListProfile()
	{
		return $this->hasMany('VacStatus\Models\UserListProfile');
	}

	public function User()
	{
		return $this->belongsTo('VacStatus\Models\User', 'user_id', 'id');
	}

	public function canSubscribe($user_id)
	{
		return $this->user_id == $user_id || $this->privacy != 3;
	}

	public function scopeCheckExistingUser($query, $profileId)
	{
		return $query->join('user_list_profile', function($join) use ($profileId)
		{
			$join->on('user_list_profile.user_list_id', '=', 'user_list.id')
				->where('user_list_profile.profile_id', '=', $profileId)
				->whereNull('user_list_profile.deleted_at');
		});
	}

	public function scopeGetListProfiles($query, $listId)
	{
		return $query->where('user_list.id', $listId)
			->leftJoin('user_list_profile as ulp_1', function($join)
			{
				$join->on('ulp_1.user_list_id', '=', 'user_list.id')
					->whereNull('ulp_1.deleted_at');
			})
			->leftjoin('profile', 'ulp_1.profile_id', '=', 'profile.id')
			->leftjoin('profile_ban', 'profile.id', '=', 'profile_ban.profile_id')
			->leftjoin('users', 'profile.small_id', '=', 'users.small_id')
			->leftJoin('user_list_profile as ulp_2', function($join)
			{
				$join->on('ulp_2.profile_id', '=', 'ulp_1.profile_id')
					->whereNull('ulp_2.deleted_at');
			})
			->leftJoin('subscription', function($join)
			{
				$join->on('subscription.user_list_id', '=', 'user_list.id')
					->whereNull('subscription.deleted_at');
			})
			->whereNotNull('profile.id')
			->groupBy('profile.id')
			->orderBy('ulp_1.id', 'desc')
			->get([
		      	'ulp_1.profile_name',
		      	'ulp_1.profile_description',
		      	'ulp_1.created_at as added_at',

				'profile.id',
				'profile.display_name',
				'profile.avatar_thumb',
				'profile.small_id',

				'profile_ban.vac_bans',
				'profile_ban.game_bans',
				'profile_ban.last_ban_date',
				'profile_ban.community',
				'profile_ban.trade',

				'users.site_admin',
				'users.donation',
				'users.beta',

				\DB::raw('max(ulp_1.created_at) as last_added_at'),
				\DB::raw('count(distinct ulp_2.user_list_id) as total'),
				\DB::raw('count(distinct subscription.id) as sub_count'),
			]);
	}

	public function toArray()
	{
		$array = parent::toArray();

		if($this->steam_64_bit) $array['steam_64_bit'] = $this->steam_64_bit;

		return $array;
	}

	public function getSteam64BitAttribute()
	{
		return $this->small_id ? Steam::to64Bit($this->small_id) : null;
	}

	public function getLastBanDateAttribute($lastBanDate)
	{
		return (new Carbon($lastBanDate))->format("M j Y");
	}

	public function getAddedAtAttribute($addedAt)
	{
		return (new Carbon($addedAt))->format("M j Y");
	}

	public function getCreatedAtAttribute($createdAt)
	{
		return (new Carbon($createdAt))->format("M j Y");
	}
}


text:
package org.springframework.boot.actuate.autoconfigure;

import org.junit.Test;

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

/**
 * Tests for {@link ManagementServerPropertiesAutoConfiguration}.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 */
public class ManagementServerPropertiesAutoConfigurationTests {

	@Test
	public void defaultManagementServerProperties() {
		ManagementServerProperties properties = new ManagementServerProperties();
		assertThat(properties.getPort()).isNull();
		assertThat(properties.getContextPath()).isEqualTo("");
	}

	@Test
	public void definedManagementServerProperties() {
		ManagementServerProperties properties = new ManagementServerProperties();
		properties.setPort(123);
		properties.setContextPath("/foo");
		assertThat(properties.getPort()).isEqualTo(123);
		assertThat(properties.getContextPath()).isEqualTo("/foo");
	}

	@Test
	public void trailingSlashOfContextPathIsRemoved() {
		ManagementServerProperties properties = new ManagementServerProperties();
		properties.setContextPath("/foo/");
		assertThat(properties.getContextPath()).isEqualTo("/foo");
	}

	@Test
	public void slashOfContextPathIsDefaultValue() {
		ManagementServerProperties properties = new ManagementServerProperties();
		properties.setContextPath("/");
		assertThat(properties.getContextPath()).isEqualTo("");
	}

}


text:
DROP TABLE IF EXISTS items;
DROP TABLE IF EXISTS locations;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS unit;
DROP TABLE IF EXISTS images;

-- //

CREATE TABLE IF NOT EXISTS locations (
	id serial primary key,
	parent_id integer,
	name text,
	notes text
);

CREATE TABLE IF NOT EXISTS items (
	id serial primary key,
	location_id integer,
	price integer,
	quantity integer,
	unit_id integer,
	name text
);

CREATE TABLE IF NOT EXISTS orders (
	items_id integer,
	user_id integer,
	store text,
	url text,
	sn text,
	price integer, -- CONVERTED TO SEK?
	quantity integer
);

CREATE TABLE IF NOT EXISTS unit (
	id serial primary key,
	name TEXT
);

CREATE TABLE IF NOT EXISTS images (
	items_id integer,
	user_id integer,
	url text
);

CREATE OR REPLACE FUNCTION get_location(child_id integer)
	RETURNS TEXT
	LANGUAGE plpgsql
	AS $$
DECLARE
	ret TEXT;
BEGIN
	WITH RECURSIVE search_graph(id, link, data, depth) AS (
		SELECT g.id, g.parent_id, g.name, 1
		FROM locations g WHERE id = child_id
      		UNION ALL
        	SELECT g.id, g.parent_id, g.name, sg.depth + 1
        	FROM locations g, search_graph sg
        	WHERE g.id = sg.link
	)
	SELECT json_agg(data  ORDER BY depth DESC) FROM search_graph LIMIT 10 INTO ret;

	RETURN ret;
END;
$$;

INSERT INTO locations (parent_id, name) VALUES (null, 'Hackerspace');
INSERT INTO locations (parent_id, name) VALUES (1, 'Rack 1');
INSERT INTO locations (parent_id, name) VALUES (2, 'Box 1');

INSERT INTO locations (parent_id, name) VALUES (1, 'Rack 2');
INSERT INTO locations (parent_id, name) VALUES (4, 'Box 2');

INSERT INTO items (location_id, price, quantity, name) VALUES (3, 10, 10, 'Item 1');
INSERT INTO items (location_id, price, quantity, name) VALUES (3, 10, 10, 'Item 2');
INSERT INTO items (location_id, price, quantity, name) VALUES (5, 10, 10, 'Item somewherelese');

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public  TO xilventory;


text:
<?php
trait RessourceLoader {

	function RessourceLoader() {
	}
	function loadFromRessourcesByClass($ontologyClass) {
		$iex = new Extraction();

		$wiki_search_url = "https://www.wikidata.org/w/api.php?action=wbsearchentities&search=" . $this->name . "&language=en&format=json";
		$wiki_search_ressource = $iex->getRessource($wiki_search_url);
		$wiki_search_json_object = json_decode($wiki_search_ressource->content);

		$entityID = $wiki_search_json_object->search[0]->id;

		$wiki_entity_url = "https://www.wikidata.org/w/api.php?action=wbgetentities&ids=" . $entityID . "&props=claims&format=json&languages=en";
		$wiki_entity_ressource = $iex->getRessource($wiki_entity_url);
		$wiki_entity_json_object = json_decode($wiki_entity_ressource->content);

		$information_wiki  = $iex->extractInformationFromWikiDataJsonObject($wiki_entity_json_object, $ontologyClass, array("ISIN" => "P946"));

		if ($information_wiki) {
			foreach($information_wiki as $key => $value) {
				$sl_key = strtolower($key);

				$this->$sl_key = $value;
			}
		}

		$merger = new Merger();
		$relsOCOC = $ontologyClass->getRelationOntologyClassOntologyClasses();
		foreach($relsOCOC as $relOCOC) {
			if ($relOCOC->OntologyRelationType->name === "hasOne") {
				$ressource = $relOCOC->IncomingOntologyClass->getRessource();

				if (isset($ressource)) {
					$fieldName = $relOCOC->IncomingOntologyClass->name;

					$subclass_information = $iex->extractInformationFromRessourceURL($ressource->url, $ontologyClass, array("symbol", "startDate"), array($this->symbol, "2016-01-20"), $relOCOC->IncomingOntologyClass, $ressource->schemaDefinition);

					$this->$fieldName = $subclass_information;
				}
			}
		}
	}
}
?>


text:
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.

namespace SharpDX.Direct3D9
{
    /// <summary>
    /// Internal class used to initialize this assembly.
    /// </summary>
    class ModuleInit
    {
        /// <summary>
        /// Initializes this assembly.
        /// </summary>
        /// <remarks>
        /// This method is called when the assembly is loaded.
        /// </remarks>
        [Tag("SharpDX.ModuleInit")]
        internal static void Setup()
        {
            // Register automatically Result code
            ResultDescriptor.RegisterProvider(typeof(ResultCode));
        }
    }
}


text:
from typing import Optional

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class InitialSolution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        while head and head.val == val:
            head = head.next

        if not head:
            return None

        prev, curr = head, head.next
        while curr:
            if curr.val == val:
                prev.next = curr.next
            else:
                prev = prev.next
            curr = curr.next

        return head

class DummyNodeSolution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        dummy = ListNode(val=-1, next=head)

        curr = dummy
        while curr.next:
            if curr.next.val == val:
                curr.next = curr.next.next
            else:
                curr = curr.next
        return dummy.next


text:
```html
#{include ../parts/header.html}
```

Shorter syntax with "in":

```html
#{in parts/footer.txt}
```

## Inserting variables

Simple variable insertion:

```html
<p> Name: #{name} </p>
<p> Age:  #{age} </p>
<p> Can be used for JSON-path syntax:  #{users[0].address.zipcode} </p>
```

## FOR loops

For a cycle of elements of a JSON array:

```html
#{for item : list}
	#{item.email}
#{end}
```

The use of a colon is optional:

```html
#{for item list}
	<tr>
		<td> #{item.id} </td>
		<td> #{item.name} </td>
		<td> #{item.description} </td>
	</tr>
#{end}
```

There may be multiple levels of the cycle:

```html
#{for row : rows}
	#{for cell : row}
		#{cell.email}
	#{end}
#{end}
```

## Conditional blocks

Paste if there is a JSON parameter:

```html
#{exists email}
	<!-- appears if the "email" parameter exists -->
	Send mail to: {#email}
#{end}
```

Shorter syntax with "ex":

```html
#{ex email}
	Send mail to: {#email}
#{end}
```

Paste if NO value exists:

```html
#{!exists email}
	<!-- appears only when the parameter is missing -->
	No email address provided!
#{end}
```

Shorter syntax with "!ex":

```html
#{!ex email}
	No email address provided!
#{end}
```

Paste if the value of the parameter is the same:

```html
#{equals email admin@foo.com}
	<!-- appears when the "email" parameter is "admin@foo.com" -->
	An administrator email address is provided.
#{end}
```

Shorter syntax with "eq":

```html
#{eq email admin@foo.com}
	An administrator email address is provided.
#{end}
```

Paste if NOT the same value as the given value:

```html
#{!equals email admin@foo.com}
	<!-- appears when the "email" parameter is NOT "admin@foo.com" -->
	The administrator email address is not specified.
#{end}
```

Shorter syntax with "!eq":

```html
#{!eq email admin@foo.com}
	The administrator email address is not specified.
#{end}
```

## User-defined functions

Invoke user-defined renderer / function:

```html
#{function formatEmail email}
```

Create the "formatEmail" function:

```java
engine.addFunction("formatEmail", (out, data) -> {
  if (data != null) {
    out.append(data.asString().replace("@", "[at]");
  }
});
```

Shorter syntax with "fn", parameter is optional:

```html
#{fn time}
```

Create the "time" function:

```java
engine.addFunction("time", (out, data) -> {
  out.append(new Date());
});
```


text:
package com.roncoo.jui.common.mapper;

import com.roncoo.jui.common.entity.SysMenuRole;
import com.roncoo.jui.common.entity.SysMenuRoleExample;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface SysMenuRoleMapper {
    int countByExample(SysMenuRoleExample example);

    int deleteByExample(SysMenuRoleExample example);

    int deleteByPrimaryKey(Long id);

    int insert(SysMenuRole record);

    int insertSelective(SysMenuRole record);

    List<SysMenuRole> selectByExample(SysMenuRoleExample example);

    SysMenuRole selectByPrimaryKey(Long id);

    int updateByExampleSelective(@Param("record") SysMenuRole record, @Param("example") SysMenuRoleExample example);

    int updateByExample(@Param("record") SysMenuRole record, @Param("example") SysMenuRoleExample example);

    int updateByPrimaryKeySelective(SysMenuRole record);

    int updateByPrimaryKey(SysMenuRole record);
}


text:
// Copyright 2016 Cricket Technology
// www.crickettechnology.com

#import <Foundation/Foundation.h>
#import "ck/effecttype.h"

/** Objective-C interface for CkEffect.
  See ck/effect.h for method documentation. */
@interface CkoEffect : NSObject

@property(nonatomic, assign) BOOL bypassed;
@property(nonatomic, assign) float wetDryRatio;

- (void) setParam:(int)paramId value:(float)value;

- (void) reset;

+ (nullable CkoEffect*) newEffect:(CkEffectType)type;
+ (nullable CkoEffect*) newCustomEffect:(int)id;

@end


text:
"""
Tools for different procedure estimations
"""

__author__ = "Luc Anselin luc.anselin@asu.edu, \
        Pedro V. Amaral pedro.amaral@asu.edu, \
        David C. Folch david.folch@asu.edu, \
        Daniel Arribas-Bel darribas@asu.edu,\
        Levi Wolf levi.john.wolf@gmail.com"

import numpy as np
from scipy import sparse as SP
from scipy.sparse import linalg as SPla
import scipy.optimize as op
import numpy.linalg as la
from pysal import lag_spatial
from sputils import *
import copy

class RegressionPropsY(object):

    """
    Helper class that adds common regression properties to any regression
    class that inherits it.  It takes no parameters.  See BaseOLS for example
    usage.

    Parameters
    ----------

    Attributes
    ----------
    mean_y  : float
              Mean of the dependent variable
    std_y   : float
              Standard deviation of the dependent variable

    """

    @property
    def mean_y(self):
        try:
            return self._cache['mean_y']
        except AttributeError:
            self._cache = {}
            self._cache['mean_y'] = np.mean(self.y)
        except KeyError:
            self._cache['mean_y'] = np.mean(self.y)
        return self._cache['mean_y']

    @mean_y.setter
    def mean_y(self, val):
        try:
            self._cache['mean_y'] = val
        except AttributeError:
            self._cache = {}
            self._cache['mean_y'] = val
        except KeyError:
            self._cache['mean_y'] = val

    @property
    def std_y(self):
        try:
            return self._cache['std_y']
        except AttributeError:
            self._cache = {}
            self._cache['std_y'] = np.std(self.y, ddof=1)
        except KeyError:
            self._cache['std_y'] = np.std(self.y, ddof=1)
        return self._cache['std_y']

    @std_y.setter
    def std_y(self, val):
        try:
            self._cache['std_y'] = val
        except AttributeError:
            self._cache = {}
            self._cache['std_y'] = val
        except KeyError:
            self._cache['std_y'] = val

class RegressionPropsVM(object):

    """
    Helper class that adds common regression properties to any regression
    class that inherits it.  It takes no parameters.  See BaseOLS for example
    usage.

    Parameters
    ----------

    Attributes
    ----------
    utu     : float
              Sum of the squared residuals
    sig2n    : float
              Sigma squared with n in the denominator
    sig2n_k : float
              Sigma squared with n-k in the denominator
    vm      : array
              Variance-covariance matrix (kxk)

    """

    @property
    def utu(self):
        try:
            return self._cache['utu']
        except AttributeError:
            self._cache = {}
            self._cache['utu'] = np.sum(self.u ** 2)
        except KeyError:
            self._cache['utu'] = np.sum(self.u ** 2)
        return self._cache['utu']

    @utu.setter
    def utu(self, val):
        try:
            self._cache['utu'] = val
        except AttributeError:
            self._cache = {}
            self._cache['utu'] = val
        except KeyError:
            self._cache['utu'] = val

    @property
    def sig2n(self):
        try:
            return self._cache['sig2n']
        except AttributeError:
            self._cache = {}
            self._cache['sig2n'] = self.utu / self.n
        except KeyError:
            self._cache['sig2n'] = self.utu / self.n
        return self._cache['sig2n']

    @sig2n.setter
    def sig2n(self, val):
        try:
            self._cache['sig2n'] = val
        except AttributeError:
            self._cache = {}
            self._cache['sig2n'] = val
        except KeyError:
            self._cache['sig2n'] = val

    @property
    def sig2n_k(self):
        try:
            return self._cache['sig2n_k']
        except AttributeError:
            self._cache = {}
            self._cache['sig2n_k'] = self.utu / (self.n - self.k)
        except KeyError:
            self._cache['sig2n_k'] = self.utu / (self.n - self.k)
        return self._cache['sig2n_k']

    @sig2n_k.setter
    def sig2n_k(self, val):
        try:
            self._cache['sig2n_k'] = val
        except AttributeError:
            self._cache = {}
            self._cache['sig2n_k'] = val
        except KeyError:
            self._cache['sig2n_k'] = val

    @property
    def vm(self):
        try:
            return self._cache['vm']
        except AttributeError:
            self._cache = {}
            self._cache['vm'] = np.dot(self.sig2, self.xtxi)
        except KeyError:
            self._cache['vm'] = np.dot(self.sig2, self.xtxi)
        finally:
            return self._cache['vm']

    @vm.setter
    def vm(self, val):
        try:
            self._cache['vm'] = val
        except AttributeError:
            self._cache = {}
            self._cache['vm'] = val
        except KeyError:
            self._cache['vm'] = val

def get_A1_het(S):
    """
    Builds A1 as in Arraiz et al [Arraiz2010]_

    .. math::

        A_1 = W' W - diag(w'_{.i} w_{.i})

    ...

    Parameters
    ----------

    S               : csr_matrix
                      PySAL W object converted into Scipy sparse matrix

    Returns
    -------

    Implicit        : csr_matrix
                      A1 matrix in scipy sparse format

    """
    StS = S.T * S
    d = SP.spdiags([StS.diagonal()], [0], S.get_shape()[0], S.get_shape()[1])
    d = d.asformat('csr')
    return StS - d

def get_A1_hom(s, scalarKP=False):
    """
    Builds A1 for the spatial error GM estimation with homoscedasticity as in
    Drukker et al. [Drukker2011]_ (p. 9).

    .. math::

        A_1 = \{1 + [n^{-1} tr(W'W)]^2\}^{-1} \[W'W - n^{-1} tr(W'W) I\]

    ...

    Parameters
    ----------

    s               : csr_matrix
                      PySAL W object converted into Scipy sparse matrix
    scalarKP        : boolean
                      Flag to include scalar corresponding to the first moment
                      condition as in Drukker et al. [1]_ (Defaults to False)

    Returns
    -------

    Implicit        : csr_matrix
                      A1 matrix in scipy sparse format
    """
    n = float(s.shape[0])
    wpw = s.T * s
    twpw = np.sum(wpw.diagonal())
    e = SP.eye(n, n, format='csr')
    e.data = np.ones(n) * (twpw / n)
    num = wpw - e
    if not scalarKP:
        return num
    else:
        den = 1. + (twpw / n) ** 2.
        return num / den

def get_A2_hom(s):
    """
    Builds A2 for the spatial error GM estimation with homoscedasticity as in
    Anselin (2011) [Anselin2011]_

    .. math::

        A_2 = \dfrac{(W + W')}{2}

    ...

    Parameters
    ----------
    s               : csr_matrix
                      PySAL W object converted into Scipy sparse matrix
    Returns
    -------
    Implicit        : csr_matrix
                      A2 matrix in scipy sparse format
    """
    return (s + s.T) / 2.

def _moments2eqs(A1, s, u):
    '''
    Helper to compute G and g in a system of two equations as in
    the heteroskedastic error models from Drukker et al. [Drukker2011]_
    ...

    Parameters
    ----------

    A1          : scipy.sparse.csr
                  A1 matrix as in the paper, different deppending on whether
                  it's homocedastic or heteroskedastic model

    s           : W.sparse
                  Sparse representation of spatial weights instance

    u           : array
                  Residuals. nx1 array assumed to be aligned with w

    Attributes
    ----------

    moments     : list
                  List of two arrays corresponding to the matrices 'G' and
                  'g', respectively.

    '''
    n = float(s.shape[0])
    A1u = A1 * u
    wu = s * u
    g1 = np.dot(u.T, A1u)
    g2 = np.dot(u.T, wu)
    g = np.array([[g1][0][0], [g2][0][0]]) / n

    G11 = np.dot(u.T, ((A1 + A1.T) * wu))
    G12 = -np.dot((wu.T * A1), wu)
    G21 = np.dot(u.T, ((s + s.T) * wu))
    G22 = -np.dot(wu.T, (s * wu))
    G = np.array([[G11[0][0], G12[0][0]], [G21[0][0], G22[0][0]]]) / n
    return [G, g]

def optim_moments(moments_in, vcX=np.array([0])):
    """
    Optimization of moments
    ...

    Parameters
    ----------

    moments     : Moments
                  Instance of gmm_utils.moments_het with G and g
    vcX         : array
                  Optional. 2x2 array with the Variance-Covariance matrix to be used as
                  weights in the optimization (applies Cholesky
                  decomposition). Set empty by default.

    Returns
    -------
    x, f, d     : tuple
                  x -- position of the minimum
                  f -- value of func at the minimum
                  d -- dictionary of information from routine
                        d['warnflag'] is
                            0 if converged
                            1 if too many function evaluations
                            2 if stopped for another reason, given in d['task']
                        d['grad'] is the gradient at the minimum (should be 0 ish)
                        d['funcalls'] is the number of function calls made
    """
    moments = copy.deepcopy(moments_in)
    if vcX.any():
        Ec = np.transpose(la.cholesky(la.inv(vcX)))
        moments[0] = np.dot(Ec, moments_in[0])
        moments[1] = np.dot(Ec, moments_in[1])
    scale = np.min([[np.min(moments[0]), np.min(moments[1])]])
    moments[0], moments[1] = moments[0] / scale, moments[1] / scale
    if moments[0].shape[0] == 2:
        optim_par = lambda par: foptim_par(
            np.array([[float(par[0]), float(par[0]) ** 2.]]).T, moments)
        start = [0.0]
        bounds = [(-1.0, 1.0)]
    if moments[0].shape[0] == 3:
        optim_par = lambda par: foptim_par(
            np.array([[float(par[0]), float(par[0]) ** 2., float(par[1])]]).T, moments)
        start = [0.0, 0.0]
        bounds = [(-1.0, 1.0), (0.0, None)]
    lambdaX = op.fmin_l_bfgs_b(
        optim_par, start, approx_grad=True, bounds=bounds)
    return lambdaX[0][0]

def foptim_par(par, moments):
    """
    Preparation of the function of moments for minimization
    ...

    Parameters
    ----------

    lambdapar       : float
                      Spatial autoregressive parameter
    moments         : list
                      List of Moments with G (moments[0]) and g (moments[1])

    Returns
    -------

    minimum         : float
                      sum of square residuals (e) of the equation system
                      moments.g - moments.G * lambdapar = e
    """
    vv = np.dot(moments[0], par)
    vv2 = moments[1] - vv
    return sum(vv2 ** 2)

def get_spFilter(w, lamb, sf):
    '''
    Compute the spatially filtered variables

    Parameters
    ----------
    w       : weight
              PySAL weights instance
    lamb    : double
              spatial autoregressive parameter
    sf      : array
              the variable needed to compute the filter
    Returns
    --------
    rs      : array
              spatially filtered variable

    Examples
    --------

    >>> import numpy as np
    >>> import pysal
    >>> db = pysal.open(pysal.examples.get_path('columbus.dbf'),'r')
    >>> y = np.array(db.by_col("CRIME"))
    >>> y = np.reshape(y, (49,1))
    >>> w=pysal.open(pysal.examples.get_path("columbus.gal")).read()
    >>> solu = get_spFilter(w,0.5,y)
    >>> print solu[0:5]
    [[  -8.9882875]
     [ -20.5685065]
     [ -28.196721 ]
     [ -36.9051915]
     [-111.1298   ]]

    '''
    try:
        result = sf - lamb * (w.sparse * sf)
    except:
        result = sf - lamb * (w * sf)
    return result

def get_lags(w, x, w_lags):
    '''
    Calculates a given order of spatial lags and all the smaller orders

    Parameters
    ----------
    w       : weight
              PySAL weights instance
    x       : array
              nxk arrays with the variables to be lagged
    w_lags  : integer
              Maximum order of spatial lag

    Returns
    --------
    rs      : array
              nxk*(w_lags+1) array with original and spatially lagged variables

    '''
    lag = lag_spatial(w, x)
    spat_lags = lag
    for i in range(w_lags - 1):
        lag = lag_spatial(w, lag)
        spat_lags = sphstack(spat_lags, lag)
    return spat_lags

def inverse_prod(w, data, scalar, post_multiply=False, inv_method="power_exp", threshold=0.0000000001, max_iterations=None):
    """

    Parameters
    ----------

    w               : Pysal W object
                      nxn Pysal spatial weights object

    data            : Numpy array
                      nx1 vector of data

    scalar          : float
                      Scalar value (typically rho or lambda)

    post_multiply   : boolean
                      If True then post-multiplies the data vector by the
                      inverse of the spatial filter, if false then
                      pre-multiplies.
    inv_method      : string
                      If "true_inv" uses the true inverse of W (slow);
                      If "power_exp" uses the power expansion method (default)

    threshold       : float
                      Test value to stop the iterations. Test is against
                      sqrt(increment' * increment), where increment is a
                      vector representing the contribution from each
                      iteration.

    max_iterations  : integer
                      Maximum number of iterations for the expansion.

    Examples
    --------

    >>> import numpy, pysal
    >>> import numpy.linalg as la
    >>> np.random.seed(10)
    >>> w = pysal.lat2W(5, 5)
    >>> w.transform = 'r'
    >>> data = np.random.randn(w.n)
    >>> data.shape = (w.n, 1)
    >>> rho = 0.4
    >>> inv_pow = inverse_prod(w, data, rho, inv_method="power_exp")
    >>> # true matrix inverse
    >>> inv_reg = inverse_prod(w, data, rho, inv_method="true_inv")
    >>> np.allclose(inv_pow, inv_reg, atol=0.0001)
    True
    >>> # test the transpose version
    >>> inv_pow = inverse_prod(w, data, rho, inv_method="power_exp", post_multiply=True)
    >>> inv_reg = inverse_prod(w, data, rho, inv_method="true_inv", post_multiply=True)
    >>> np.allclose(inv_pow, inv_reg, atol=0.0001)
    True

    """
    if inv_method == "power_exp":
        inv_prod = power_expansion(
            w, data, scalar, post_multiply=post_multiply,
            threshold=threshold, max_iterations=max_iterations)
    elif inv_method == "true_inv":
        try:
            matrix = la.inv(np.eye(w.n) - (scalar * w.full()[0]))
        except:
            matrix = la.inv(np.eye(w.shape[0]) - (scalar * w))
        if post_multiply:
            inv_prod = spdot(data.T, matrix)
        else:
            inv_prod = spdot(matrix, data)
    else:
        raise Exception, "Invalid method selected for inversion."
    return inv_prod

def power_expansion(w, data, scalar, post_multiply=False, threshold=0.0000000001, max_iterations=None):
    """
    Compute the inverse of a matrix using the power expansion (Leontief
    expansion).  General form is:

        .. math::
            x &= (I - \rho W)^{-1}v = [I + \rho W + \rho^2 WW + \dots]v \\
              &= v + \rho Wv + \rho^2 WWv + \dots

    Examples
    --------
    Tests for this function are in inverse_prod()

    """
    try:
        ws = w.sparse
    except:
        ws = w
    if post_multiply:
        data = data.T
    running_total = copy.copy(data)
    increment = copy.copy(data)
    count = 1
    test = 10000000
    if max_iterations == None:
        max_iterations = 10000000
    while test > threshold and count <= max_iterations:
        if post_multiply:
            increment = increment * ws * scalar
        else:
            increment = ws * increment * scalar
        running_total += increment
        test_old = test
        test = la.norm(increment)
        if test > test_old:
            raise Exception, "power expansion will not converge, check model specification and that weight are less than 1"
        count += 1
    return running_total

def set_endog(y, x, w, yend, q, w_lags, lag_q):
    # Create spatial lag of y
    yl = lag_spatial(w, y)
    # spatial and non-spatial instruments
    if issubclass(type(yend), np.ndarray):
        if lag_q:
            lag_vars = sphstack(x, q)
        else:
            lag_vars = x
        spatial_inst = get_lags(w, lag_vars, w_lags)
        q = sphstack(q, spatial_inst)
        yend = sphstack(yend, yl)
    elif yend == None:  # spatial instruments only
        q = get_lags(w, x, w_lags)
        yend = yl
    else:
        raise Exception, "invalid value passed to yend"
    return yend, q

    lag = lag_spatial(w, x)
    spat_lags = lag
    for i in range(w_lags - 1):
        lag = lag_spatial(w, lag)
        spat_lags = sphstack(spat_lags, lag)
    return spat_lags

def set_endog_sparse(y, x, w, yend, q, w_lags, lag_q):
    """
    Same as set_endog, but with a sparse object passed as weights instead of W object.
    """
    yl = w * y
    # spatial and non-spatial instruments
    if issubclass(type(yend), np.ndarray):
        if lag_q:
            lag_vars = sphstack(x, q)
        else:
            lag_vars = x
        spatial_inst = w * lag_vars
        for i in range(w_lags - 1):
            spatial_inst = sphstack(spatial_inst, w * spatial_inst)
        q = sphstack(q, spatial_inst)
        yend = sphstack(yend, yl)
    elif yend == None:  # spatial instruments only
        q = w * x
        for i in range(w_lags - 1):
            q = sphstack(q, w * q)
        yend = yl
    else:
        raise Exception, "invalid value passed to yend"
    return yend, q

def iter_msg(iteration, max_iter):
    if iteration == max_iter:
        iter_stop = "Maximum number of iterations reached."
    else:
        iter_stop = "Convergence threshold (epsilon) reached."
    return iter_stop

def sp_att(w, y, predy, w_y, rho):
    xb = predy - rho * w_y
    if np.abs(rho) < 1:
        predy_sp = inverse_prod(w, xb, rho)
        warn = None
        # Note 1: Here if omitting pseudo-R2; If not, see Note 2.
        resid_sp = y - predy_sp
    else:
        #warn = "Warning: Estimate for rho is outside the boundary (-1, 1). Computation of true inverse of W was required (slow)."
        #predy_sp = inverse_prod(w, xb, rho, inv_method="true_inv")
        warn = "*** WARNING: Estimate for spatial lag coefficient is outside the boundary (-1, 1). ***"
        predy_sp = np.zeros(y.shape, float)
        resid_sp = np.zeros(y.shape, float)
    # resid_sp = y - predy_sp #Note 2: Here if computing true inverse; If not,
    # see Note 1.
    return predy_sp, resid_sp, warn

def set_warn(reg, warn):
    ''' Groups warning messages for printout. '''
    if warn:
        try:
            reg.warning += "Warning: " + warn + "\n"
        except:
            reg.warning = "Warning: " + warn + "\n"
    else:
        pass

def RegressionProps_basic(reg, betas=None, predy=None, u=None, sig2=None, sig2n_k=None, vm=None):
    ''' Set props based on arguments passed. '''
    if betas is not None:
        reg.betas = betas
    if predy is not None:
        reg.predy = predy
    else:
        try:
            reg.predy = spdot(reg.z, reg.betas)
        except:
            reg.predy = spdot(reg.x, reg.betas)
    if u is not None:
        reg.u = u
    else:
        reg.u = reg.y - reg.predy
    if sig2 is not None:
        reg.sig2 = sig2
    elif sig2n_k:
        reg.sig2 = np.sum(reg.u ** 2) / (reg.n - reg.k)
    else:
        reg.sig2 = np.sum(reg.u ** 2) / reg.n
    if vm is not None:
        reg.vm = vm

def _test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    _test()


text:
\hypertarget{_computer_evaluator_8h}{}\section{Mastermind\+C\+P\+P\+D\+L\+L/\+Computer\+Evaluator.h File Reference}
\label{_computer_evaluator_8h}\index{Mastermind\+C\+P\+P\+D\+L\+L/\+Computer\+Evaluator.\+h@{Mastermind\+C\+P\+P\+D\+L\+L/\+Computer\+Evaluator.\+h}}
{\ttfamily \#include \char`\"{}A\+P\+I.\+h\char`\"{}}\newline
{\ttfamily \#include \char`\"{}Mastermind.\+h\char`\"{}}\newline
{\ttfamily \#include \char`\"{}I\+Evaluator.\+h\char`\"{}}\newline
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{classmastermind_1_1logic_1_1_computer_evaluator}{mastermind\+::logic\+::\+Computer\+Evaluator}
\begin{DoxyCompactList}\small\item\em Evaluator which automatically evaluates the \hyperlink{classmastermind_1_1logic_1_1_color_code}{Color\+Code} given to a solution. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Namespaces}
\begin{DoxyCompactItemize}
\item
 \hyperlink{namespacemastermind}{mastermind}
\item
 \hyperlink{namespacemastermind_1_1logic}{mastermind\+::logic}
\end{DoxyCompactItemize}


text:
package com.zlu.leetcode.linkedlistproblem;

public class RemoveLinkedListElements {
	public ListNode removeElements(ListNode head, int val) {
		   if(head == null) return head;
		   ListNode top = new ListNode(0);
		   top.next = head;
		    ListNode front = top;
	        ListNode current = head;
	        while(current != null){
	        	if(current.val == val)
	        		front.next = current.next;
	        	else front = front.next;
	        	current = current.next;
	        }
	        return top.next;
	    }
}


text:
Image viewer widget for Appcelerator Titanium

With this image viewer it's possible to show a single - zoomable, scrollable and pinchable - local image on iOS and Android (on iOS also remote images).

It uses module org.iotashan.TiTouchImageView (on Android), and installation of this module is necessary if you mean to use the widget on Android.

![image](docs/screenshot1.png?raw=true)

## Installation

Add in your *config.json*, under `dependencies`:

```
"dependencies": {
    "it.apra.tiimageviewer": "*"
}
```

## Usage
```javascript
widget = Alloy.createWidget('it.apra.tiimageviewer', {
	'image' : filepath,
	'title' : filename,
	'subtitle' : des
});
```

## Usage with Alloy
```xml
		<Widget src="it.apra.tiimageviewer" id="myiview" image="..." lowerGradientHidden="true" lowerInfoHidden="true"/>
```

**Args**
* **image**: image filepath
* **title**: optional image title (showed in lower panel)
* **subtitle**: optional image subtitle (showed in lower panel)
* **lowerInfoHidden**: if true hides lower info panel
* **lowerGradientHidden**: if true hides lower info panel gradient
* **backgroundColor**: backgroundColor (default is 'black')

**Functions**
* **removeEventListeners**: removes all listeners on controls
* **reloadImage**: reloads the image
* **showLowerInfo**: showes lower info
* **hideLowerInfo**: hides lower info

##Notes
* Could be useful a compatibility on Android without the native module too (using a webview?)
* The pinch-to-zoom and scroll on iOS are based on the widget https://github.com/CaffeinaLab/Ti.TiltImageView.


text:
<?php

/**
 * @file
 * Definition of Drupal\views\Tests\Plugin\StyleUnformattedTest.
 */

namespace Drupal\views\Tests\Plugin;

use Drupal\views\Views;

/**
 * Tests unformatted style functionality.
 *
 * @group views
 */
class StyleUnformattedTest extends StyleTestBase {

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = array('test_view');

  /**
   * Make sure that the default css classes works as expected.
   */
  function testDefaultRowClasses() {
    $view = Views::getView('test_view');
    $view->setDisplay();
    $output = $view->preview();
    $this->storeViewPreview(drupal_render($output));

    $rows = $this->elements->body->div->div->div;
    $count = 0;
    $count_result = count($view->result);
    foreach ($rows as $row) {
      $count++;
      $attributes = $row->attributes();
      $class = (string) $attributes['class'][0];
      $this->assertTrue(strpos($class, 'views-row') !== FALSE, 'Make sure that the views row class is set right.');
    }
  }

}


text:
FROM ubuntu:12.04

MAINTAINER Dave Simons

RUN apt-get update

# at time of writing this installed version 1.4.18 of haproxy
RUN apt-get install -y haproxy

ADD haproxy.sh /usr/local/bin/haproxy.sh
RUN chown root.root /usr/local/bin/haproxy.sh

#
# https://launchpad.net/ubuntu/precise/+package/socat is a key tool
# for managing haproxy once it's up and running - see one of the articles
# below for an intro to the technique
#
# reference
# -- http://serverfault.com/questions/249316/how-can-i-remove-balanced-node-from-haproxy-via-c
#
apt-get install -y socat


text:
<project name="FantasyFootballCustomScoringHelper" basedir="." default="jar">

	<description>
		Program for testing various custom fantasy football scoring rules
	</description>

	<!-- Set global properties for this build -->
	<property name="srcdir" location="${basedir}/src"/>
	<property name="mainjavadir" location="${srcdir}/main/java"/>
	<property name="libdir" location="${basedir}/lib"/>
	<property name="builddir" location="${basedir}/build"/>
	<property name="classdir" location="${builddir}/classes"/>
	<property name="distdir" location="${basedir}/dist"/>
	<property name="resultsdir" location="${basedir}/results"/>
	<property name="main-class" value="football.FantasyFootballCustomScoringHelper"/>
	<property name="jar-name" value="${distdir}/${ant.project.name}.jar"/>

	<path id="build-classpath">
		<fileset dir="${libdir}" includes="*.jar"/>
	</path>

	<manifestclasspath property="jar-classpath" jarfile="${jar-name}">
		<classpath refid="build-classpath"/>
	</manifestclasspath>

	<target name="init">
		<!-- Create the time stamp -->
		<tstamp/>
		<!-- Create the build directory structure used by compile, jar, and run -->
		<mkdir dir="${classdir}"/>
		<mkdir dir="${distdir}"/>
		<mkdir dir="${resultsdir}"/>
	</target>

	<target name="compile" depends="init" description="Compile source files" >
		<!-- Compile the java code from ${src} into ${build} -->
		<javac debug="true" srcdir="${mainjavadir}" destdir="${classdir}"
			classpathref="build-classpath" includeantruntime="false">
			<compilerarg value="-Xlint"/>
			<!--<exclude name="**/ValidateUtils.java"/>-->
		</javac>
	</target>

	<target name="jar" depends="compile" description="Create jar file">
		<jar basedir="${classdir}" destfile="${jar-name}">
			<manifest>
				<attribute name="Main-Class" value="${main-class}"/>
				<attribute name="Class-Path" value="${jar-classpath}"/>
			</manifest>
		</jar>
	</target>

	<target name="run" depends="jar,cmdlineargs" description="Run the program">
		<java jar="${jar-name}" fork="true">
			<arg value="${mode}"/>
			<arg line="${rules}"/>
		</java>
	</target>

	<!--
	<target name="run" depends="compile,cmdlineargs" description="Run the program">
		<java classname="${main-class}">
			<arg value="${mode}"/>
			<arg line="${rules}"/>
		</java>
	</target>
	-->

	<target name="cmdlineargs" unless="mode,rules" description="Prompts for command line arguments">
		<input addProperty="mode" message="Enter the player mode:"/>
		<input addProperty="rules" message="Enter custom scoring rules:"/>
	</target>

	<target name="clean" description="Delete all build artifacts" >
		<!-- Delete the ${build} directory -->
		<delete dir="${builddir}"/>
		<delete dir="${distdir}"/>
	</target>

	<target name="all" depends="clean,jar" description="Clean build dir, and then compile sources"/>

</project>


text:
package aha.poc.batch.api;

public enum TaskStatus {
	Prepared, Running, Canceled, Failed, Done

}


text:
Automating tasks is cool. It saves time and minimizes errors, at least manual errors. To save us (.NET developers) some time, I created this small script - inspired by @robertbird - for [Boxstarter](http://boxstarter.org/), so we can focus on more important things than manually downloading and installing our needed tools.

### Prerequisites ###
- Windows 10
- [Chocolatey](https://chocolatey.org)
- [Boxstarter](http://boxstarter.org/)

In order to get started with the script, you need to install Chocolatey first. Open a PowerShell console in administrator mode and run the following two lines:
```powershell
Set-ExecutionPolicy Unrestricted
(iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')))>$null 2>&1
```
After that it's time to install Boxstarter. Simply run the following script from your PowerShell:

```
choco install boxstarter -y
```

### Running the script ###
This is as easy as installing the prerequisites. Follow these simple steps.

1. Open the Boxstarter Shell or Powershell with elevated privileges
2. Run the following command
3. Grab a tea and relax! ;-)
```powershell
Install-BoxstarterPackage https://raw.githubusercontent.com/timmes/timmes.Boxstarter/master/BoxstarterDevFull.ps1
```

If you do not want to run the script *as is* but make your own changes, you should clone the repository or create a [Gist](https://gist.github.com/). Afterwards replace the `url?` with the new URL where your script is hosted.

----------

## Disclaimer ##
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND.**

## Contributing ##
If you want to contribute to this project, simply clone the repository and send a pull request with your changes.

## License ##
See the [LICENSE](LICENSE.md) file for license rights and limitations (MIT).


text:
package de.graeuler.garden.uplink;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.json.Json;
import javax.json.JsonObjectBuilder;
import javax.json.JsonValue;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import de.graeuler.garden.config.ConfigurationKeys;
import de.graeuler.garden.data.DataCollector;
import de.graeuler.garden.data.DataProcessor;
import de.graeuler.garden.data.DataRecord;
import de.graeuler.garden.data.JsonDataConverter;
import de.graeuler.garden.monitor.service.MonitorService;
import de.graeuler.garden.testhelpers.TestConfig;

public class DataCollectionMonitorTest {

	private static final int BLOCK_SIZE = 10;
	private TestConfig config = new TestConfig();
	@SuppressWarnings("unchecked")
	private DataCollector<DataRecord> dataCollector = (DataCollector<DataRecord>) mock(DataCollector.class);
	private JsonDataConverter dataConverter = mock(JsonDataConverter.class);
	private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
	private JsonUplink uplink = mock(HttpUplinkService.class);
	private List<DataRecord> sample = new ArrayList<>();
	private MonitorService dataCollectionMonitor;
	private JsonValue jsonValue1234;

	@Before
	public void setUp() throws Exception {
		config.set(ConfigurationKeys.COLLECT_TIME_RATE, 1);
		config.set(ConfigurationKeys.COLLECT_TIME_UNIT, TimeUnit.SECONDS);
		config.set(ConfigurationKeys.COLLECT_BLOCK_SIZE, BLOCK_SIZE);
		sample.add(new DataRecord("key", "1234"));
		dataCollectionMonitor = new DataCollectionMonitor(this.config, this.dataCollector, this.dataConverter,
				this.uplink, this.scheduler);
		JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
		jsonValue1234 = jsonBuilder.add("v", 1234).build();
	}

	@After
	public void tearDown() {
		dataCollectionMonitor.shutdown();
	}

	@Test
	public final void testEmptyDataCollector() {
		dataCollectionMonitor.monitor();
		wait(2, TimeUnit.SECONDS); // should not interact with converter or when no data was collected.
		verifyNoInteractions(dataConverter);
		verify(uplink).getConnectionState();
	}

	@Test
	public final void testUploadIsCalled() {
		when(dataConverter.convert(sample)).thenReturn(jsonValue1234);
		when(uplink.pushData(jsonValue1234)).thenReturn(true);
		when(uplink.getConnectionState()).thenReturn(UplinkConnectionState.ONLINE);
		doAnswer(new Answer<Void>() {

			@SuppressWarnings("unchecked")
			@Override
			public Void answer(InvocationOnMock invocation) throws Throwable {
				Object[] arguments = invocation.getArguments();
				if (arguments.length > 0 && arguments[0] instanceof DataProcessor) {
					assertTrue(((DataProcessor<DataRecord>) arguments[0]).apply(sample));
				}
				return null;
			}

		}).when(dataCollector).processCollectedRecords(Mockito.any(), Mockito.anyLong());
		dataCollectionMonitor.monitor();
		wait(2, TimeUnit.SECONDS);
		verify(dataConverter, atLeastOnce()).convert(sample);
		verify(uplink, atLeastOnce()).pushData(jsonValue1234);
	}

	@Test
	public final void testUploadFails() {
		new DataCollectionMonitor(this.config, this.dataCollector, this.dataConverter, this.uplink, this.scheduler);
		when(dataConverter.convert(sample)).thenReturn(jsonValue1234);
		when(uplink.pushData(jsonValue1234)).thenReturn(false);
		dataCollectionMonitor.monitor();
		wait(1, TimeUnit.SECONDS);
		verify(dataCollector, never()).removeDataset(sample);
	}

	private void wait(int timeout, TimeUnit timeUnit) {
		try {
			timeUnit.sleep(timeout);
		} catch (InterruptedException e) {
			fail("Interrupted Testrun!");
		}
	}

}


text:
if [ -z "$1" ]; then
	echo "Usage: ./haveibeenpwned.sh <email list>"
  exit 0
fi

echo "Checking haveibeenpwned.com using v2 of API:"
echo ""

while read email; do

  encodedEmail=${email//@/%40}
  url="https://haveibeenpwned.com/api/v2/breachedaccount/$encodedEmail?truncateResponse=true"
  response=$(curl --write-out %\{http_code\} --silent --output /dev/null $url)

  sleep 1

  echo -n "Checking if $email has been pwned: "
  if [ "$response" == "200" ]; then
    detail=$(curl --silent $url)
    echo "YES - $detail"
  else
    echo "NO"
  fi

done < $1


text:
<?php

use App\Basket\CustomerIntelligence\CustomerIntelligenceService;
use App\Basket\Installation;
use App\Basket\Location;
use App\Http\Controllers\Api\PreApprovalController;
use App\User;
use Illuminate\Support\Facades\Artisan;
use PayBreak\Sdk\Gateways\CustomerIntelligenceGateway;
use PayBreak\Sdk\Gateways\DictionaryGateway;

/**
 * Pre Approval Cest
 *
 * @author GK
 */
class PreApprovalCest
{
    /**
     * @author GK
     */
    public function _after()
    {
        Mockery::close();
    }

    /**
     * @author GK
     * @param FunctionalTester $I
     */
    public function testPreApprovalWithoutParameters(FunctionalTester $I)
    {
        $installationId = 1;
        $expectedResponse = ['service response'];

        $mockCustomerIntelligenceService = Mockery::mock(CustomerIntelligenceService::class);
        $mockCustomerIntelligenceService->shouldReceive('listPreApprovals')->with(
            Mockery::on(function (Installation $installation) use ($installationId) {
                return $installation instanceof Installation;
            }),
            PreApprovalController::DEFAULT_PAGE_LIMIT,
            PreApprovalController::DEFAULT_PAGE
        )->andReturn($expectedResponse);

        $I->getApplication()->instance(CustomerIntelligenceService::class, $mockCustomerIntelligenceService);

        $I->disableMiddleware();

        $I->haveHttpHeader('X-Requested-With', 'XMLHttpRequest');

        $I->sendGET(
            'api/installations/' . $installationId . '/customer-intelligence/pre-approvals'
        );

        $I->canSeeResponseCodeIs(200);
        $I->canSeeResponseIsJson();
        $I->canSeeResponseEquals('["service response"]', $I->grabResponse());
    }

    /**
     * @author GK
     * @param FunctionalTester $I
     */
    public function testPreApprovalWithPerPageAndPageParametersProvided(FunctionalTester $I)
    {
        $installationId = 1;
        $perPage = 20;
        $page = 2;
        $expectedResponse = ['service response'];

        $mockCustomerIntelligenceService = Mockery::mock(CustomerIntelligenceService::class);
        $mockCustomerIntelligenceService->shouldReceive('listPreApprovals')->with(
            Mockery::on(function (Installation $installation) use ($installationId) {
                return $installation instanceof Installation;
            }),
            $perPage,
            $page
        )->andReturn($expectedResponse);

        $I->getApplication()->instance(CustomerIntelligenceService::class, $mockCustomerIntelligenceService);

        $I->disableMiddleware();

        $I->haveHttpHeader('X-Requested-With', 'XMLHttpRequest');

        $I->sendGET(
            'api/installations/' . $installationId . '/customer-intelligence/pre-approvals' .
            '?per_page=' . $perPage .
            '&page=' . $page
        );

        $I->canSeeResponseCodeIs(200);
        $I->canSeeResponseIsJson();
        $I->canSeeResponseEquals('["service response"]', $I->grabResponse());
    }

    /**
     * @author GK
     * @param FunctionalTester $I
     */
    public function testPerformPreApprovalWhenRequiredPropertiesAreMissing(FunctionalTester $I)
    {
        $installationId = 1;

        $I->disableMiddleware();

        $I->haveHttpHeader('X-Requested-With', 'XMLHttpRequest');

        $I->sendPOST(
            'api/installations/' . $installationId . '/customer-intelligence/perform-pre-approval',
            [
                'email' => 'asdf@test.com',
            ]
        );

        $I->canSeeResponseCodeIs(422);
        $I->canSeeResponseIsJson();
    }

    /**
     * @author GK
     * @param FunctionalTester $I
     */
    public function testPerformPreApproval(FunctionalTester $I)
    {
        Artisan::call('migrate:refresh');
        Artisan::call('db:seed', ['--class' => 'DevSeeder']);

        $user = User::find(1);
        $installationId = 1;
        $installation = Installation::find($installationId);

        $request = [
            'email' => 'test@email.com',
            'title' => 'Mr',
            'first_name' => 'TIM',
            'last_name' => 'TIMINGSON',
            'date_of_birth' => '1978-05-27',
            'dependents' => 1,
            'marital_status' => 2,
            'employment_status' => 3,
            'employment_start_date' => '2008-04-20',
            'income' => 10000,
            'debt' => 15,
            'consent'=> '1',
            'marketing'=> '1',
            'addresses' => [
                [
                    'building_number' => '11',
                    'street' => 'SUNNY STREET',
                    'town' => 'TEST TOWN',
                    'postcode' => 'X9 9AA',
                    'moved_in' => '1995-02-01',
                    'residential_status' => '4',
                ],
            ],
        ];

        $apiResponse = ['id' => 1, 'advice' => 'Brush your teeth before going to sleep'];

        $I->haveHttpHeader('Authorization', 'Bearer ' . $user->api_token);
        $I->haveHttpHeader('X-Requested-With', 'XMLHttpRequest');

        $mockCustomerIntelligenceGateway = Mockery::mock(CustomerIntelligenceGateway::class);
        $mockCustomerIntelligenceGateway->shouldReceive('performPreApproval')
            ->with(
                $installation->ext_id,
                Mockery::on(function ($param) use ($request) {
                    return $param['email'] === $request['email'] &&
                        $param['title'] === $request['title'] &&
                        $param['first_name'] === $request['first_name'] &&
                        $param['last_name'] === $request['last_name'] &&
                        $param['date_of_birth'] === $request['date_of_birth'] &&
                        $param['dependents'] === $request['dependents'] &&
                        $param['marital_status'] === $request['marital_status'] &&
                        $param['employment_status'] === $request['employment_status'] &&
                        $param['employment_start_date'] === $request['employment_start_date'] &&
                        $param['income'] === $request['income'] &&
                        $param['debt'] === $request['debt'] &&
                        $param['marketing'] === true &&
                        $param['addresses'][0]['building_number'] === $request['addresses'][0]['building_number'] &&
                        $param['addresses'][0]['street'] === $request['addresses'][0]['street'] &&
                        $param['addresses'][0]['town'] === $request['addresses'][0]['town'] &&
                        $param['addresses'][0]['postcode'] === $request['addresses'][0]['postcode'] &&
                        $param['addresses'][0]['moved_in'] === $request['addresses'][0]['moved_in'] &&
                        $param['addresses'][0]['residential_status'] === 4
                        ;
                }),
                $installation->merchant->token
            )->andReturn($apiResponse);

        $I->getApplication()->instance(CustomerIntelligenceGateway::class, $mockCustomerIntelligenceGateway);

        $I->sendPOST(
            'api/installations/' . $installationId . '/customer-intelligence/perform-pre-approval',
            $request
        );

        $I->canSeeResponseCodeIs(200);
        $I->canSeeResponseIsJson();
        $I->canSeeResponseEquals(json_encode($apiResponse));
    }

    /**
     * @author GK
     * @param FunctionalTester $I
     */
    public function testPreApprovalShowHappyPath(FunctionalTester $I)
    {
        Artisan::call('migrate:refresh');
        Artisan::call('db:seed', ['--class' => 'DevSeeder']);

        $user = User::find(1);
        $installationId = 1;
        $installation = Installation::find($installationId);

        $preApprovalId = 42;

        $mockDictionary = Mockery::mock(DictionaryGateway::class);
        $mockDictionary->shouldReceive('getMaritalStatuses')->with($installation->merchant->token)
            ->andReturn(
                [
                    [
                        'id' => 1,
                        'description' => 'It\'s complicated',
                    ],
                ]
            );
        $mockDictionary->shouldReceive('getEmploymentStatuses')->with($installation->merchant->token)
            ->andReturn(
                [
                    [
                        'id' => 2,
                        'description' => 'Unemployed',
                    ]
                ]
            );

        $mockIntelligenceGateway = Mockery::mock(CustomerIntelligenceGateway::class);
        $mockIntelligenceGateway->shouldReceive('getPreApproval')->andReturn([
            'id' => 1,
            'lead_score_id' => 2,
            'advice' => 'green',
            'email' => 'test@email.com',
            'title' => 'Mr',
            'first_name' => 'TIM',
            'last_name' => 'TIMINGSON',
            'date_of_birth' => '1978-05-31',
            'dependents' => 0,
            'marital_status' => 1,
            'employment_status' => 2,
            'employment_start_date' => '2004-08-01',
            'tel_employer' => '01438847020',
            'income' => 10000,
            'debt' => 500,
            'bank_sort_code' => '404783',
            'bank_account_number' => '21039547',
            'bank_account_opened_date' => '1970-01-01',
            'consent' => '2018-09-12T11:51:25+00:00',
            'marketing' => false,
            'addresses' => [
                [
                    'building_number' => '11',
                    'street' => 'SUNNY STREET',
                    'town' => 'TEST TOWN',
                    'postcode' => 'X9 9AA',
                ],
            ],
            'products' => [
                [
                    'product' => [
                        'id' => 'IFC-06',
                        'product_group' => 'IFC',
                        'name' => 'Interest Free Credit 6 months',
                    ],
                    'advice' => 'red',
                    'credit_limit' => null,
                ],
                [
                    'product' => [
                        'id' => 'IFC-06',
                        'product_group' => 'IFC',
                        'name' => 'Interest Free Credit 12 months',
                    ],
                    'advice' => 'blue',
                    'credit_limit' => null,
                ],
                [
                    'product' => [
                        'id' => 'IFC-06',
                        'product_group' => 'IFC',
                        'name' => 'Interest Free Credit 18 months',
                    ],

                    'advice' => 'amber',
                    'credit_limit' => null,
                ],
                [
                    'product' => [
                        'id' => 'IFC-06',
                        'product_group' => 'IFC',
                        'name' => 'Interest Free Credit 24 months',
                    ],
                    'advice' => 'green',
                    'credit_limit' => 1660,
                ],
            ],
        ]);

        $I->getApplication()->instance(DictionaryGateway::class, $mockDictionary);
        $I->getApplication()->instance(CustomerIntelligenceGateway::class, $mockIntelligenceGateway);

        $I->amLoggedAs($user);

        $I->sendGet(
            'installations/' . $installationId . '/customer-intelligence/pre-approvals/' . $preApprovalId
        );

        $I->see('Agreement in Principle');
        $I->see('Customer');
        $I->see('Address');
        $I->see('Products');

        $I->see('It\'s complicated');
        $I->see('Unemployed');
    }
}


text:
![Barebon](img/logo.png)

**Barebon** is a minimal, easy to use boilerplate for fast front-end prototyping using [Bourbon](http://bourbon.io/) and [Neat](http://neat.bourbon.io/).

Barebon provides a Grunt-powered, **Sass + CoffeeScript** configuration that aims to speed up all the small steps you have to take when starting a new prototype website.

## Usage

In order to use Barebon effectively, you should have installed `grunt-cli` and `node` on your computer. If you don't, visit [nodejs.org](http://nodejs.org/) and [gruntjs.com](http://gruntjs.com/).

1. Clone or fork this repo
2. Get in the project folder and run `$ npm install`
4. Spawn the grunt watcher with `$ grunt watch`
5. Start prototyping!

## Features
* Blazing fast setup
* The power of Bourbon and Neat in a simple framework
* Grunt automation and Livereload save you a lot of precious time

## Documentation

### Project structure

```
.
├── components
│   ├── bourbon
│   ├── jquery
│   └── neat
├── css
│   ├── main.css
│   ├── normalize.css
│   └── sass
│       ├── _base.sass
│       ├── _config.sass
│       ├── _mixins.sass
│       ├── _mobile.sass
│       ├── _vars.sass
│       └── main.sass
├── img
├── js
│   ├── main.js
│   └── coffee
│       └── app.coffee
└── index.html
```

### Workflow

Barebone aims to be as easy as possible, in order to speed up prototype development.

##### Sass
`main.sass` contains all the imports and it's compiled into `main.css`. A simple workflow could consist in creating new files as you develop the project, and then import them in `main.sass`.

Ideally you should keep things as modular as you can, but the project structure allows you to achieve good maintainability and clean code in multiple ways. Do what you like!

##### Coffeescript
Any `.coffee` file in the `js/coffee` folder will be compiled and concatenated into `main.js`.

### CSS classes
Barebon comes with a few utility classes already packed in.

*Work in progress*

## To do
Lots of things! Feel free to fork and contribute!


text:
namespace crashpad {
namespace internal {

IOSIntermediateDumpList::IOSIntermediateDumpList() : list_() {}

IOSIntermediateDumpList::~IOSIntermediateDumpList() {}

IOSIntermediateDumpObject::Type IOSIntermediateDumpList::GetType() const {
  return Type::kList;
}

}  // namespace internal
}  // namespace crashpad


text:
<?php

namespace backend\controllers;

use Yii;
use backend\models\Post;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\UploadedFile;
use yii\helpers\Html;
use yii\helpers\FileHelper;

class AboutController extends Controller
{
	public function behaviors()
	{
		return [
		'access' => [
		'class' => AccessControl::className(),
		'rules' => [
		[
        'actions' => ['login', 'error'],//actions without loggin
        'allow' => true,
        ],
        [
        'actions' => ['logout','index','view','create','update','delete'],//action with login
        'allow' => true,
        'roles' => ['@'],
        ],
        ]
        ],
        'verbs' => [
        'class' => VerbFilter::className(),
        'actions' => [
        'delete' => ['POST'],
        ],
        ],
        ];
    }

    public function actions()
    {
    	return [
    	'error' => [
    	'class' => 'yii\web\ErrorAction',
    	],
    	];
    }

    public function actionIndex()
    {
    	$model = Post::find()
    	->where(['type'=>'about'])
    	->orWhere(['type'=>'privacy'])
    	->orWhere(['type'=>'ama'])->all();

    	return $this->render('index', [
    		'model' => $model,
    		]);
    }

    public function actionView($id)
    {
    	return $this->render('view', [
    		'model' => $this->findModel($id),
    		]);
    }

    public function actionCreate()
    {
    	$model = new Post();

    	if ($model->load(Yii::$app->request->post()) ) {
    		$imageName = time();
    		$model->file = UploadedFile::getInstance($model, 'file');
    		$path = Yii::getAlias('@web/uploads/meta/');
    		if(!empty($model->file)){
    			$model->file->saveAS('uploads/meta/'.$imageName.'.'.$model->file->extension);
    			$model->img = $path.$imageName.'.'.$model->file->extension;
    		}
    		$model->created_at = time();
    		$model->save(false);
    		return $this->redirect(['view', 'id' => $model->id]);
    	} else {
    		return $this->render('create', [
    			'model' => $model,
    			]);
    	}
    }

    public function actionUpdate($id)
    {
    	$model = $this->findModel($id);
    	$model->tags = Post::getTags($id);
    	$model->categories = Post::getCategories($id);

    	if ($model->load(Yii::$app->request->post()) ) {
    		$imageName = time();
    		$model->file = UploadedFile::getInstance($model, 'file');
    		$path = Yii::getAlias('@web/uploads/meta/');
    		if(!empty($model->file)){
    			$model->file->saveAS('uploads/meta/'.$imageName.'.'.$model->file->extension);
    			$model->img = $path.$imageName.'.'.$model->file->extension;
    		}

    		$model->save(false);
    		return $this->redirect(['view', 'id' => $model->id]);

    	} else {
    		return $this->render('update', [
    			'model' => $model,
    			]);
    	}
    }

    public function actionDelete($id)
    {
    	$this->findModel($id)->delete();

    	return $this->redirect(['index']);
    }

    protected function findModel($id)
    {
    	if (($model = Post::findOne($id)) !== null) {
    		return $model;
    	} else {
    		throw new NotFoundHttpException('The requested page does not exist.');
    	}
    }
}


text:
 This is an API that accepts a unix timestamp or a natural date and returns both.
 If neither are found, returns null. Hooks into an express app. A FreeCodeCamp
 project.

### Known Issues
 * currently functional on most cases, however edge cases like " 2016" or
   "De, 2016" pass.