text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.variations.firstrun;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.ContextUtils;
import org.chromium.base.ThreadUtils;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.metrics.test.ShadowRecordHistogram;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.components.variations.VariationsSeedOuterClass.VariationsSeed;
import org.chromium.components.variations.VariationsSwitches;
import org.chromium.components.variations.firstrun.VariationsSeedFetcher.DateTime;
import org.chromium.components.variations.firstrun.VariationsSeedFetcher.SeedFetchInfo;
import org.chromium.components.variations.firstrun.VariationsSeedFetcher.SeedInfo;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.Date;

/**
 * Tests for VariationsSeedFetcher
 */
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE, shadows = {ShadowRecordHistogram.class})
public class VariationsSeedFetcherTest {
    private HttpURLConnection mConnection;
    private VariationsSeedFetcher mFetcher;
    private SharedPreferences mPrefs;
    private Looper mOrigLooper;

    private static final String sRestrict = "restricted";
    private static final String sMilestone = "64";
    private static final String sChannel = "dev";

    @Rule
    public TestRule mCommandLineFlagsRule = CommandLineFlags.getTestRule();

    @Before
    public void setUp() throws IOException {
        // Pretend we are not on the UI thread, since the class we are testing is supposed to run
        // only on a background thread.
        Handler handler = ThreadUtils.getUiThreadHandler();
        if (handler != null) mOrigLooper = handler.getLooper();
        ThreadUtils.setUiThread(null);
        ThreadUtils.setWillOverrideUiThread(true);
        ThreadUtils.setUiThread(mock(Looper.class));
        mFetcher = spy(VariationsSeedFetcher.get());
        mConnection = mock(HttpURLConnection.class);
        doReturn(mConnection)
                .when(mFetcher)
                .getServerConnection(VariationsSeedFetcher.VariationsPlatform.ANDROID, sRestrict,
                        sMilestone, sChannel);
        mPrefs = ContextUtils.getAppSharedPreferences();
        ShadowRecordHistogram.reset();
    }

    @After
    public void tearDown() {
        ThreadUtils.setUiThread(null);
        if (mOrigLooper != null) {
            ThreadUtils.setUiThread(mOrigLooper);
            mOrigLooper = null;
        }
        ThreadUtils.setWillOverrideUiThread(false);
    }

    /**
     * Test method for {@link VariationsSeedFetcher#fetchSeed()}.
     *
     * @throws IOException
     */
    @Test
    public void testFetchSeed() throws IOException {
        // Pretend we are on a background thread; set the UI thread looper to something other than
        // the current thread.

        when(mConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
        when(mConnection.getHeaderField("X-Seed-Signature")).thenReturn("signature");
        when(mConnection.getHeaderField("X-Country")).thenReturn("Nowhere Land");
        when(mConnection.getHeaderField("IM")).thenReturn("gzip");
        when(mConnection.getInputStream())
                .thenReturn(new ByteArrayInputStream(ApiCompatibilityUtils.getBytesUtf8("1234")));

        long startTime = new Date().getTime();
        mFetcher.fetchSeed(sRestrict, sMilestone, sChannel);
        long endTime = new Date().getTime();

        assertThat(mPrefs.getString(VariationsSeedBridge.VARIATIONS_FIRST_RUN_SEED_SIGNATURE, ""),
                equalTo("signature"));
        assertThat(mPrefs.getString(VariationsSeedBridge.VARIATIONS_FIRST_RUN_SEED_COUNTRY, ""),
                equalTo("Nowhere Land"));
        long seedDate = mPrefs.getLong(VariationsSeedBridge.VARIATIONS_FIRST_RUN_SEED_DATE, 0);
        // We use *OrEqualTo comparisons here to account for when both points in time fall into the
        // same tick of the clock.
        assertThat("Seed date should be after the test start time", seedDate,
                greaterThanOrEqualTo(startTime));
        assertThat("Seed date should be before the test end time", seedDate,
                lessThanOrEqualTo(endTime));
        assertTrue(mPrefs.getBoolean(
                VariationsSeedBridge.VARIATIONS_FIRST_RUN_SEED_IS_GZIP_COMPRESSED, false));
        assertThat(mPrefs.getString(VariationsSeedBridge.VARIATIONS_FIRST_RUN_SEED_BASE64, ""),
                equalTo(Base64.encodeToString(
                        ApiCompatibilityUtils.getBytesUtf8("1234"), Base64.NO_WRAP)));
        assertEquals("Should be logged as HTTP code", 1,
                RecordHistogram.getHistogramValueCountForTesting(
                        VariationsSeedFetcher.SEED_FETCH_RESULT_HISTOGRAM,
                        HttpURLConnection.HTTP_OK));
        assertEquals("Should only log Variations.FirstRun.SeedFetchResult once", 1,
                RecordHistogram.getHistogramTotalCountForTesting(
                        VariationsSeedFetcher.SEED_FETCH_RESULT_HISTOGRAM));
    }

    /**
     * Test method for {@link VariationsSeedFetcher#downloadContent()} when no fetch is needed as
     * If-None-Match header matches.
     *
     * @throws IOException
     */
    @Test
    public void downloadContentNotModified() throws IOException {
        // Pretend we are on a background thread; set the UI thread looper to something other than
        // the current thread.
        when(mConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_NOT_MODIFIED);

        SeedInfo curSeedInfo = new SeedInfo();
        curSeedInfo.signature = "";
        curSeedInfo.country = "US";
        curSeedInfo.isGzipCompressed = false;
        Date lastSeedDate = new Date();
        lastSeedDate.setTime(12345L);
        curSeedInfo.date = lastSeedDate.getTime();

        final Date date = mock(Date.class);
        when(date.getTime()).thenReturn(67890L);
        final DateTime dt = mock(DateTime.class);
        when(dt.newDate()).thenReturn(date);
        mFetcher.setDateTime(dt);

        VariationsSeed seed = VariationsSeed.newBuilder()
                                      .setVersion("V")
                                      .setSerialNumber("savedSerialNumber")
                                      .build();
        curSeedInfo.seedData = seed.toByteArray();

        SeedFetchInfo seedFetchInfo =
                mFetcher.downloadContent(VariationsSeedFetcher.VariationsPlatform.ANDROID,
                        sRestrict, sMilestone, sChannel, curSeedInfo);

        assertEquals(seedFetchInfo.seedFetchResult, HttpURLConnection.HTTP_NOT_MODIFIED);

        SeedInfo updatedSeedInfo = seedFetchInfo.seedInfo;
        assertEquals(curSeedInfo.signature, updatedSeedInfo.signature);
        assertEquals(curSeedInfo.country, updatedSeedInfo.country);
        assertEquals(curSeedInfo.isGzipCompressed, updatedSeedInfo.isGzipCompressed);
        assertEquals(67890L, updatedSeedInfo.date);
        Arrays.equals(curSeedInfo.seedData, updatedSeedInfo.seedData);

        assertEquals(curSeedInfo.getParsedVariationsSeed().getSerialNumber(), "savedSerialNumber");
    }

    /**
     * Test method for {@link VariationsSeedFetcher#fetchSeed()} when no fetch is needed
     */
    @Test
    public void testFetchSeed_noFetchNeeded() throws IOException {
        mPrefs.edit().putBoolean(VariationsSeedFetcher.VARIATIONS_INITIALIZED_PREF, true).apply();

        mFetcher.fetchSeed(sRestrict, sMilestone, sChannel);

        verify(mConnection, never()).connect();
        assertEquals("Should not log Variations.FirstRun.SeedFetchResult if no fetch needed", 0,
                RecordHistogram.getHistogramTotalCountForTesting(
                        VariationsSeedFetcher.SEED_FETCH_RESULT_HISTOGRAM));
    }

    /**
     * Test method for {@link VariationsSeedFetcher#fetchSeed()} with a bad response
     */
    @Test
    public void testFetchSeed_badResponse() throws IOException {
        when(mConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND);

        mFetcher.fetchSeed(sRestrict, sMilestone, sChannel);

        assertTrue(mPrefs.getBoolean(VariationsSeedFetcher.VARIATIONS_INITIALIZED_PREF, false));
        assertFalse(VariationsSeedBridge.hasJavaPref());
        assertEquals("Should be logged as HTTP code", 1,
                RecordHistogram.getHistogramValueCountForTesting(
                        VariationsSeedFetcher.SEED_FETCH_RESULT_HISTOGRAM,
                        HttpURLConnection.HTTP_NOT_FOUND));
        assertEquals("Should only log Variations.FirstRun.SeedFetchResult once", 1,
                RecordHistogram.getHistogramTotalCountForTesting(
                        VariationsSeedFetcher.SEED_FETCH_RESULT_HISTOGRAM));
    }

    /**
     * Test method for {@link VariationsSeedFetcher#fetchSeed()} with an exception when connecting
     */
    @Test
    public void testFetchSeed_IOException() throws IOException {
        doThrow(new IOException()).when(mConnection).connect();

        mFetcher.fetchSeed(sRestrict, sMilestone, sChannel);

        assertTrue(mPrefs.getBoolean(VariationsSeedFetcher.VARIATIONS_INITIALIZED_PREF, false));
        assertFalse(VariationsSeedBridge.hasJavaPref());
        assertEquals("Should be logged as IOException", 1,
                RecordHistogram.getHistogramValueCountForTesting(
                        VariationsSeedFetcher.SEED_FETCH_RESULT_HISTOGRAM,
                        VariationsSeedFetcher.SEED_FETCH_RESULT_IOEXCEPTION));
        assertEquals("Should only log Variations.FirstRun.SeedFetchResult once", 1,
                RecordHistogram.getHistogramTotalCountForTesting(
                        VariationsSeedFetcher.SEED_FETCH_RESULT_HISTOGRAM));
    }

    /**
     * Test method for {@link VariationsSeedFetcher#getConnectionString()} has URl params.
     */
    @Test
    public void testGetConnectionString_HasParams() {
        String urlString = mFetcher.getConnectionString(
                VariationsSeedFetcher.VariationsPlatform.ANDROID, sRestrict, sMilestone, sChannel);

        // Has the params.
        assertTrue(urlString, urlString.contains("restrict"));
        assertTrue(urlString, urlString.contains("osname"));
        assertTrue(urlString, urlString.contains("milestone"));
        assertTrue(urlString, urlString.contains("channel"));

        // Has the param values.
        assertTrue(urlString, urlString.contains(sRestrict));
        assertTrue(urlString, urlString.contains(sMilestone));
        assertTrue(urlString, urlString.contains(sChannel));

        urlString = mFetcher.getConnectionString(
                VariationsSeedFetcher.VariationsPlatform.ANDROID, "", sMilestone, sChannel);
        assertFalse(urlString.contains("restrict"));
        assertTrue(urlString.contains("osname"));
        assertTrue(urlString.contains("milestone"));
        assertTrue(urlString.contains("channel"));

        urlString = mFetcher.getConnectionString(
                VariationsSeedFetcher.VariationsPlatform.ANDROID, sRestrict, "", sChannel);
        assertTrue(urlString.contains("restrict"));
        assertTrue(urlString.contains("osname"));
        assertFalse(urlString.contains("milestone"));
        assertTrue(urlString.contains("channel"));

        urlString = mFetcher.getConnectionString(
                VariationsSeedFetcher.VariationsPlatform.ANDROID, sRestrict, sMilestone, "");
        assertTrue(urlString.contains("restrict"));
        assertTrue(urlString.contains("osname"));
        assertTrue(urlString.contains("milestone"));
        assertFalse(urlString.contains("channel"));
    }

    /**
     * Test method to make sure {@link VariationsSeedFetcher#getConnectionString()} honors the
     * "--fake-variations-channel" switch.
     */
    @Test
    @CommandLineFlags.Add(VariationsSwitches.FAKE_VARIATIONS_CHANNEL + "=stable")
    public void testGetConnectionString_HonorsChannelCommandlineSwitch() {
        String urlString = mFetcher.getConnectionString(
                VariationsSeedFetcher.VariationsPlatform.ANDROID, sRestrict, sMilestone, sChannel);

        // The URL should have a channel param.
        assertTrue(urlString, urlString.contains("channel"));

        // The channel param should be overridden by commandline.
        assertTrue(urlString, urlString.contains("stable"));
    }
}


text:
<?php
	_deprecated_file( __FILE__, '3.10', 'Tribe__Events__Pro__APM_Filters__Recur_Filter' );

	class Tribe_Recur_Filter extends Tribe__Events__Pro__APM_Filters__Recur_Filter {

	}

redpajama_set_name: RedPajamaGithub


text:
Resource http://ci.emse.fr/rdfp/example demonstrates RDF Presentation Negotiation, and the use of the `rdfp-jersey-server` implementation.

The resource exposes and consumes RDF Graphs that are described by https://w3id.org/rdfp/example/graph (negotiate its representation with the server, or directly access the [turtle](https://w3id.org/rdfp/example/description.ttl), or a [RDF/XML](https://w3id.org/rdfp/example/description.rdf) document).

This graph description explicitly mentions two presentations (in addition to the well known turtle and RDF/XML presentations:

- one for media type `application/xml`;
- one for media type `application/json`.

Also, two other RDF Presentations can be played with:

- another for media type `application/xml`;
- one for media type `text/plain`.

## Testing POST operation

In order to test the POST operation, examples of inputs can be found at URL https://w3id.org/rdfp/example/input. Negotiate its representation with the server, or directly access:

-  https://w3id.org/rdfp/example/input.txt
-  https://w3id.org/rdfp/example/input.json
-  https://w3id.org/rdfp/example/input.xml
-  https://w3id.org/rdfp/example/input.ttl

Examples of the requests you can test include:

_note: POST at https://w3id.org/rdfp/example does not work, use http://ci.emse.fr/rdfp/example_

```
POST /rdfp/example (--> POST http://ci.emse.fr/rdfp/example)
Content-Type: text/turtle

-- the content of https://w3id.org/rdfp/example/input.ttl in the body --

POST /rdfp/example (--> POST http://ci.emse.fr/rdfp/example)
Content-Type: application/xml

-- the content of https://w3id.org/rdfp/example/input.xml in the body --

POST /rdfp/example
Content-Type: application/json

-- the content of https://w3id.org/rdfp/example/input.json in the body --

POST /rdfp/example
Content-Type: text/plain
Content-Presentation: https://w3id.org/rdfp/presentation3

-- the content of https://w3id.org/rdfp/example/input.txt in the body --
```

Examples of requests that trigger errors include:

```
POST /rdfp/example
Content-Type: foo/bar

-- any content in the body  --

POST/rdfp/example
Accept: text/plain
Accept-Presentation: https://w3id.org/rdfp/presentation2

-- any content in the body --
```

## Testing GET operation

Examples of the requests you can test include:

_note: both GET https://w3id.org/rdfp/example and get http://ci.emse.fr/rdfp/example will work_

```

GET /rdfp/example
Accept: text/turtle

GET /rdfp/example
Accept: application/rdf+xml

GET /rdfp/example
Accept: application/json

GET /rdfp/example
Accept: application/xml

GET /rdfp/example
Accept: application/xml
Accept-Presentation: https://w3id.org/rdfp/presentation2
```

Examples of requests that trigger errors include:

```
GET /rdfp/example
Accept: foo/bar

GET /rdfp/example
Accept: text/plain
Accept-Presentation: https://w3id.org/rdfp/presentation2

GET /rdfp/example
Accept: text/plain
Accept-Presentation: https://w3id.org/rdfp/presentation3
```


text:
#ifndef __INC_ENTROPYMV_H
#define __INC_ENTROPYMV_H

#include "treecoder.h"

enum
{
    mv_max  = 1023,              /* max absolute value of a MV component */
    MVvals = (2 * mv_max) + 1,   /* # possible values "" */

    mvlong_width = 10,       /* Large MVs have 9 bit magnitudes */
    mvnum_short = 8,         /* magnitudes 0 through 7 */

    /* probability offsets for coding each MV component */

    mvpis_short = 0,         /* short (<= 7) vs long (>= 8) */
    MVPsign,                /* sign for non-zero */
    MVPshort,               /* 8 short values = 7-position tree */

    MVPbits = MVPshort + mvnum_short - 1, /* mvlong_width long value bits */
    MVPcount = MVPbits + mvlong_width    /* (with independent probabilities) */
};

typedef struct mv_context
{
    vp8_prob prob[MVPcount];  /* often come in row, col pairs */
} MV_CONTEXT;

extern const MV_CONTEXT vp8_mv_update_probs[2], vp8_default_mv_context[2];

#endif


text:
<?php
use Phalcon\Forms\Form,
	Phalcon\Forms\FileUpload,
	Phalcon\Forms\TextEditor,
    Phalcon\Forms\Element\Text,
    Phalcon\Forms\Element\Textarea,
    Phalcon\Forms\Element\Select,
	Phalcon\Forms\Element\Password;

use Phalcon\Validation\Validator\PresenceOf,
	Phalcon\Validation\Validator\Email,
	Phalcon\Validation\Validator\StringLength;

class MgmtMailController extends ControllerBase
{
	protected $entity;
	private $status = array('status' => 'false','messages' => array());
	private $post;
	private $get;
	private $session;

    public function initialize()
    {
        $this->view->setTemplateAfter('email');
        Phalcon\Tag::setTitle('MgmtMails');
        parent::initialize();
		$this->post = $this->request->getPost();
		$this->get =  $this->request->getQuery();
		$this->session = $this->session->get('auth');
		$this->entity = 'MgmtMail';
	}

	public function indexAction()
    {
		$this->setaction($this->entity);
		$this->setcolumns($this->entity);
		$MgmtMails = $this->search2(array('columns' => array_keys(MgmtMail::columnMap()),'entity' => $this->entity));
		if(count($MgmtMails) > 0){ $this->view->setVar("MgmtMails", $MgmtMails); }
	}

	public function cleanAction()
	{
		$this->view->disable();
		$post = $this->request->getPost();
		$this->setaction($this->entity);
		$this->setcolumns($this->entity);

		if(isset($post['field']) && isset($post['value']))
		{
			$acl = Acl::find('entityid = "'.$post['value'].'" ');
			$cc=0;$str = '';
			foreach($acl as $rule)
			{
				if($cc>0){$str .= ' OR '; }
				$str .= ' id = "'.$rule->userid.'" ';
				$cc++;
			}
			$args = $str;
		}
		$MgmtMails = $this->search($columns,'MgmtMail',$args);
		if(count($MgmtMails) > 0)
		{
			$this->view->setVar("MgmtMails", $MgmtMails);
		}
		$this->view->partial("MgmtMail/clean");
	}

	public function sortAction()
	{
		$this->view->disable();
		if($this->request->isPost())
		{
			$post = $this->post;

			$this->setaction($this->entity);
			$this->setcolumns($this->entity);

			$args = $this->getargs($post);
			$args['entity'] = 'MgmtMail';
			$args['columns'] = array_keys(MgmtMail::columnMap());

			$MgmtMails = $this->search2($args);
			if(count($MgmtMails) > 0)
			{
				$this->view->setVar("MgmtMails", $MgmtMails);
			}

			$this->view->setvar("post", $post);
			$this->view->partial("mgmtmail/clean");
		}
	}

	public function editAction()
	{
		$form = new Form();
		$post = $this->post;
		$entityid = $this->uuid();
		$id = $this->request->getQuery('id');

		$MgmtMail = MgmtMail::findFirst('id = "'.$id.'"');
		//files
		$files = $this->getfiles('MgmtMail',$MgmtMail->id);
		$this->view->setVar("files", $files);

		$cm = $MgmtMail->columnMap();
		foreach($cm as $column)
		{ $form->add(new Text($column, array('value' => $MgmtMail->$column,'id' => $column,'class' => 'form-control'))); }
		//TODO add special fields

		$form->add(new TextEditor("message", array("id" => "message","value" => $MgmtMail->message,"class" => "form-control")));

		$this->view->setVar("MgmtMail", $MgmtMail);
		$this->view->setVar("entityid", $entityid);
		$this->view->setVar("form", $form);
		$this->view->pick("mgmtmail/new");
	}

	public function newAction()
	{
		$form = new Form();
		$session = $this->session;
		$post = $this->post;
		$entityid = $this->uuid();

		$MgmtMail = MgmtMail::findFirst();
		if(!isset($MgmtMail->id))
		{
			$MgmtMail = new MgmtMail();
			$MgmtMail->userid = $this->uuid();
		}

		$cm = $MgmtMail->columnMap();
		foreach($cm as $column)
		{ $form->add(new Text($column, array('id' => $column,'class' => 'form-control'))); }

		$form->add(new TextEditor("message", array("id" => "message","value" => $MgmtMail->message,"class" => "form-control")));
		$form->add(new FileUpload('file',array('id'=>'file','class'=>'form-control','x' => 200,'y' => 200)));

		$this->view->setVar("entityid", $entityid);
		$this->view->setVar("form", $form);
	}

	public function addAction()
	{
		$this->view->disable();
		$status = $this->status;
		if ($this->request->isPost())
		{
			$post = $this->post;

			$validation = new Phalcon\Validation();
			$validation = $this->striptagsfilter($validation,array("id","subject","message","from","to","lastedit"));

					$validation->add('subject', new PresenceOf(array(

						'field' => 'subject',
						'message' => 'Het veld subject is verplicht.'
					)));

					$validation->add('subject', new StringLength(array(
						'messageMinimum' => 'Vul een subject in van tenminste 2 characters.',
						'min' => 2
					)));

					$validation->add('message', new PresenceOf(array(

						'field' => 'message',
						'message' => 'Het veld message is verplicht.'
					)));

					$validation->add('message', new StringLength(array(
						'messageMinimum' => 'Vul een message in van tenminste 2 characters.',
						'min' => 2
					)));

					$validation->add('from', new PresenceOf(array(

						'field' => 'from',
						'message' => 'Het veld from is verplicht.'
					)));

					$validation->add('from', new StringLength(array(
						'messageMinimum' => 'Vul een from in van tenminste 2 characters.',
						'min' => 2
					)));

					$validation->add('to', new PresenceOf(array(

						'field' => 'to',
						'message' => 'Het veld to is verplicht.'
					)));

					$validation->add('to', new StringLength(array(
						'messageMinimum' => 'Vul een to in van tenminste 2 characters.',
						'min' => 2
					)));

			$messages = $validation->validate($post);
			if (count($messages))
			{
				$status['messages'] = $this->getmessages($messages);
			}
			else
			{
				$entity = $this->getEntity('mgmtmail',$post);

				//save standard columns
				foreach ($entity as $key => $value)
				{
					if(isset($post[$key]) && $key != 'id' && $key != 'fileid' && strlen($post[$key]) > 0)
					{
						$entity->$key = $post[$key];
					}
				}

				//if(isset($post['files'])){ $user->fileid = $post['files'][0]; }

				if(!isset($post['id']) || strlen($post['id']) < 10)
				{
					$status['messages'] = $this->getmessages($entity->validation());
				}

				if(count($status['messages'])==0 && $entity->save())
				{
					$status['status'] = 'ok';
				}
				else
				{
					foreach ($entity->getMessages() as $message)
					{
							echo 'mgmtmail:'.$message;
					}
				}
			}
		}
		echo json_encode($status);
	}

	public function deleteAction()
	{
		$this->view->disable();
		$status = $this->status;
		if ($this->request->isPost())
		{
			$post = $this->request->getPost();
			$MgmtMail = MgmtMail::findFirst('id = "'.$post['id'].'"');
			if($MgmtMail->delete())
			{
				$status['status'] = 'ok';
			}
		}
		echo json_encode($status);
	}

	public function viewAction()
	{
		$form = new Form();
		$post = $this->post;
		$id = $this->get['id'];

		$user = User::findFirst('id = "'.$id.'"');
		$this->view->setVar("user", $user);
		$this->view->setVar("entityid", $user->id);

		$acl = Acl::findFirst();
		$this->view->setVar("acl", $acl);

		$cm = $acl->columnMap();
		foreach($cm as $column)
		{ $form->add(new Text($column, array('value' => $acl->$column,'id' => $column,'class' => 'form-control'))); }

		$this->view->setVar("entityid", $entityid);
		$this->view->setVar("form", $form);
	}
}
?>


text:
package org.apache.causeway.viewer.restfulobjects.applib;

import java.io.IOException;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.fail;

import static org.apache.causeway.viewer.restfulobjects.applib.JsonFixture.readJson;

class JsonRepresentationTest_getNull_isNull {

    private JsonRepresentation jsonRepresentation;

    @BeforeEach
    public void setUp() throws Exception {
        jsonRepresentation = new JsonRepresentation(readJson("map.json"));
    }

    @Test
    public void forNullValue() throws IOException {
        final JsonRepresentation nullValue = jsonRepresentation.getNull("aNull");
        assertThat(nullValue, is(not(nullValue())));
        assertThat(nullValue.isNull(), is(true));

        final Boolean isNull = jsonRepresentation.isNull("aNull");
        assertThat(isNull, is(true));
    }

    @Test
    public void isNull_forArray() throws IOException {
        final Boolean isNull = jsonRepresentation.isNull("anEmptyArray");
        assertThat(isNull, is(false));
    }

    @Test
    public void getNull_forArray() {
        try {
            jsonRepresentation.getNull("anEmptyArray");
            fail();
        } catch (final IllegalArgumentException e) {
            assertThat(e.getMessage(), is("'anEmptyArray' is not the null value"));
        }
    }

    @Test
    public void isNull_forNonExistent() {
        final Boolean isNull = jsonRepresentation.isNull("nonExistent");
        assertThat(isNull, is(nullValue())); // ie don't know whether is null
    }

    @Test
    public void getNull_forNonExistent() {
        assertThat(jsonRepresentation.getArray("doesNotExist"), is(nullValue()));
    }

    @Test
    public void isNull_forMap() throws IOException {
        final Boolean isNull = jsonRepresentation.isNull("aSubMap");
        assertThat(isNull, is(false));
    }

    @Test
    public void forMap() {
        try {
            jsonRepresentation.getNull("aSubMap");
            fail();
        } catch (final IllegalArgumentException e) {
            assertThat(e.getMessage(), is("'aSubMap' is not the null value"));
        }
    }

}


text:
package org.fiteagle.adapters.ACSclient.Exceptions;

public class BadConfigureRequest extends RuntimeException{

  public BadConfigureRequest(String message){
    super(message);
  }

}


text:
function result = is_orthogonal_matrix(P)
%
% Orthogonal Matrices
%
% is_orthogonal_matrix(P) determines if the matrix P is an orthogonal
% matrix. An error is returned if a matrix that is not square is attempted
% to be determined for orthogonality.
%
%  Function written by Anthony Russo, downloaded from MatlabCentral.
%

matrix_size = size(P);

m = matrix_size(1,1);
n = matrix_size(1,2);

tolerance = 10^-10;

if m ~= n
    error('Only square matrices can be orthogonal.');
else
    count = 0;

    identity_matrix = P*P';

    if det(P) ~= 0
        for i = 1:m
            if abs(identity_matrix(i,i) - 1) <= tolerance
                count = count + 1;
            else
                break
            end
        end
    end

    if count == m
        result = 1;
    else
        result = 0;
    end
end


text:
<?php namespace Codesleeve\Sprockets\Directives;

class RequireSelf extends BaseDirective
{
	public function process($param = null)
	{
		return array($this->manifestFile);
	}

}


text:
import React, { Component } from 'react';
import {
	View,
	Text,
	ScrollView,
	TouchableOpacity,
	RefreshControl
} from 'react-native';
import { Card } from 'react-native-elements';
import { Actions } from 'react-native-router-flux';

import styles from './style';
import getLocalhost from '../../../server';

class Active extends Component {
	constructor(props) {
		super(props);
		this.state = {
			inProgress: [],
			refreshing: false
		};
	}

	componentDidMount() {
		this._onRefresh();
	}

	_onRefresh() {
		const localhost = getLocalhost();
		this.setState({ refreshing: true });

		fetch(`${localhost}/orders`, {
			method: 'GET',
			'Content-Type': 'application/json'
		})
			.then(res => res.json())
			.then(data => {
				const inProgress = [];

				for (let i = 0; i < data.length; i++) {
					if (data[i].status === 'in progress') {
						inProgress.push(data[i]);
					}
				}

				this.setState({
          inProgress: inProgress,
          refreshing: false
				});
			})
			.catch(err => console.log(err));
	}

	render() {
		return (
			<View style={styles.container}>
				<ScrollView
					refreshControl={
						<RefreshControl
							refreshing={this.state.refreshing}
							onRefresh={this._onRefresh.bind(this)}
						/>
					}
				>
					<View style={styles.cardContainer}>
						{this.state.inProgress.map((item, index) => {
							return (
								<TouchableOpacity
									onPress={() => Actions.detail({ data: item })}
									key={index}
								>
									<Card>
										<View
											style={{
												flexDirection: 'row',
												justifyContent: 'space-between'
											}}
										>
											<Text>{item.status}</Text>
											<Text>{item.timeWork}</Text>
										</View>
										<Text>
											{'_______________________________________________'}
										</Text>
										<Text style={styles.textDescription}>{item.address}</Text>
									</Card>
								</TouchableOpacity>
							);
						})}
					</View>
				</ScrollView>
			</View>
		);
	}
}

export default Active;


text:
package com.twitter.finagle.memcached.unit.partitioning

import com.twitter.conversions.time._
import com.twitter.finagle.loadbalancer.LoadBalancerFactory
import com.twitter.finagle.memcached.partitioning.PartitioningService
import com.twitter.finagle.stats.InMemoryStatsReceiver
import com.twitter.finagle.{Address, _}
import com.twitter.util._
import java.net.InetSocketAddress
import java.util.concurrent.ConcurrentHashMap

class PartitioningServiceTest extends PartitioningServiceTestBase {

  import PartitioningServiceTestBase._

  override def getPartitioningServiceModule: Stackable[ServiceFactory[String, String]] = {
    SimplePartitioningService.module
  }

  test("partitioning service makes the non-batched requests stick to the matching port") {
    val sr = new InMemoryStatsReceiver
    val numServers = 21
    servers = createServers(numServers)
    client = createClient(sr)

    assert(servers.length == numServers)
    assert(sr.counters(Seq("client", "loadbalancer", "adds")) == numServers)

    // using multiple iterations to test repeatability
    0 until 5 foreach { i =>
      // send the client requests concurrently. One request per client.
      val resFutures: Seq[Future[String]] = servers.map(s => client(s._3.toString))

      // wait for all three to finish
      awaitResult(Future.join(resFutures))

      servers zip resFutures foreach {
        case (s, resFuture) =>
          val res = awaitResult(resFuture)
          assert(res == s"${s._3}${EchoDelimiter}server#${s._4}", s"i=$i $s res=$res")
      }
      assert(sr.counters(Seq("client", "loadbalancer", "adds")) == numServers, s"i=$i")
    }
  }

  test("partitioning service makes the batched requests stick to the matching port") {
    // for this test, a batched request is a delimiter separated string of multiple sub requests
    val sr = new InMemoryStatsReceiver
    val numServers = 11
    servers = createServers(numServers)
    client = createClient(sr)

    assert(servers.length == numServers)
    assert(sr.counters(Seq("client", "loadbalancer", "adds")) == numServers)

    // using multiple iterations to test repeatability
    0 until 5 foreach { i =>
      val batchedRequest: String = servers.map(_._3.toString()).mkString(RequestDelimiter)
      val batchedResponse = awaitResult(client(batchedRequest))
      val responses = batchedResponse.split(ResponseDelimiter)
      assert(responses.length == numServers)

      val responseMap: Map[String, String] = responses.map { response =>
        val portAndName = response.split(EchoDelimiter)
        assert(portAndName.length == 2)
        val port = portAndName(0)
        val name = portAndName(1)
        port -> name
      }.toMap
      assert(responseMap.size == numServers)

      servers foreach { s =>
        val respondedByShard = responseMap.getOrElse(s._3.toString, fail())
        assert(respondedByShard == s"server#${s._4}")
      }
      assert(sr.counters(Seq("client", "loadbalancer", "adds")) == numServers, s"i=$i")
    }
  }

  test("batched request with failing hosts") {
    val sr = new InMemoryStatsReceiver
    val numServers = 5
    servers = createServers(numServers)
    client = createClient(sr)
    failingHosts.add("server#3")

    assert(servers.length == numServers)
    assert(sr.counters(Seq("client", "loadbalancer", "adds")) == numServers)

    val batchedRequest: String = servers.map(_._3).mkString(RequestDelimiter)
    intercept[ChannelClosedException] {
      awaitResult(client(batchedRequest))
    }
  }

  test("batched request with slow hosts") {
    val sr = new InMemoryStatsReceiver
    val numServers = 5
    servers = createServers(numServers)
    client = createClient(sr)
    slowHosts.add("server#2")

    assert(servers.length == numServers)
    assert(sr.counters(Seq("client", "loadbalancer", "adds")) == numServers)

    Time.withCurrentTimeFrozen { timeControl =>
      val batchedRequest: String = servers.map(_._3).mkString(RequestDelimiter)
      intercept[IndividualRequestTimeoutException] {
        val future = client(batchedRequest)
        timeControl.advance(3.seconds)
        timer.tick()
        Await.result(future, 10.seconds)
      }
    }
  }
}

/**
 * This partitioning service uses a simple string based matching ("request -> server port) to pin
 * requests with the specific partitions. To send a given request to a specific named
 * partition, caller needs to set the request to that name.
 */
private[this] object SimplePartitioningService {

  def module: Stackable[ServiceFactory[String, String]] = {
    new Stack.Module[ServiceFactory[String, String]] {
      val role = Stack.Role("SimplePartitioning")
      val description = "Maintains host stickiness based on name"

      override def parameters: Seq[Stack.Param[_]] = Seq.empty

      def make(
        params: Stack.Params,
        next: Stack[ServiceFactory[String, String]]
      ): Stack[ServiceFactory[String, String]] = {
        val LoadBalancerFactory.Dest(dest: Var[Addr]) = params[LoadBalancerFactory.Dest]
        val service = new SimplePartitioningService(next, params, dest)
        Stack.Leaf(role, ServiceFactory.const(service))
      }
    }
  }
}

/**
 * This service makes the request stick to the partition using the port that matches the request.
 * So requests can choose the partition they intend to use.
 *
 * BatchedRequests: multiple sub-requests delimited by RequestDelimiter. The responses are
 * concatenated using ResponseDelimiter.
 *
 * This example is just for testing and proof of concept. In a real use case the batched requests
 * will contain multiple keys and the responses will be key-value maps. The merged response
 * will combine the smaller maps into a single key-value map before returning the response to the
 * caller.
 */
private[this] class SimplePartitioningService(
  underlying: Stack[ServiceFactory[String, String]],
  params: Stack.Params,
  dest: Var[Addr]
) extends PartitioningService[String, String] {

  import PartitioningServiceTestBase._

  val unresolvedPartition: Future[Service[String, String]] = {
    val modifiedParams = params + LoadBalancerFactory.Dest(Var.value(Addr.Neg))
    val next: ServiceFactory[String, String] = underlying.make(modifiedParams)
    next()
  }

  // map port numbers to the services representing downstream partitions
  private[this] val serviceMap = new ConcurrentHashMap[String, Future[Service[String, String]]]()

  {
    // initialize the map of port -> service representing a shard
    val serviceMapVar = dest.map {
      case Addr.Bound(addresses: Set[Address], _) =>
        addresses.map {
          case addr @ Address.Inet(ia: InetSocketAddress, _) =>
            val service = mkService(addr)
            serviceMap.put(ia.getPort.toString, service)
            (ia.getPort.toString, service)
          case _ =>
            throw new IllegalStateException
        }.toMap
      case _ =>
        Map.empty
    }
    serviceMapVar.changes.register(Witness({ _: Map[_ <: String, Future[Service[String, String]]] =>
      }))
  }

  private[this] def mkService(addr: Address.Inet): Future[Service[String, String]] = {
    val modifiedParams = params + LoadBalancerFactory.Dest(Var.value(Addr.Bound(addr)))
    val next = underlying.make(modifiedParams)
    next().map { svc =>
      new ServiceProxy(svc) {
        override def close(deadline: Time): Future[Unit] = {
          Future.join(Seq(next.close(deadline), super.close(deadline)))
        }
      }
    }
  }

  override protected def getPartitionFor(request: String): Future[Service[String, String]] = {
    serviceMap.get(request) match {
      case service: Future[Service[String, String]] =>
        service
      case null =>
        unresolvedPartition
    }
  }

  override protected def partitionRequest(batchedRequest: String): Seq[String] = {
    // assuming all sub-requests are unique (one request per partition). If not the following code
    // will need to group requests by partition by using getPartitionFor method
    batchedRequest.split(RequestDelimiter).map(_.trim).toSeq
  }

  override protected def mergeResponses(responses: Seq[String]): String = {
    // responses contain the request keys. So just concatenate. In a real implementation this will
    // typically be a key-value map.
    responses.mkString(ResponseDelimiter)
  }

  protected def isSinglePartition(request: String): Boolean = false
}


text:
/*-------------------------------------------------------------------------
 *
 * cdbmirroredbufferpool.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <signal.h>

#include "access/xlogmm.h"
#include "cdb/cdbmirroredbufferpool.h"
#include "cdb/cdbpersistenttablespace.h"
#include "cdb/cdbpersistentstore.h"
#include "cdb/cdbvars.h"
#include "cdb/cdbutil.h"
#include "storage/bufmgr.h"
#include "storage/fd.h"
#include "storage/smgr.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/palloc.h"
#include "cdb/cdbpersistentfilesysobj.h"
#include "cdb/cdbpersistentrelfile.h"

static int32 writeBufLen = 0;
static char	*writeBuf = NULL;

/*
 * Open a relation for mirrored write.
 */
static void MirroredBufferPool_DoOpen(
	MirroredBufferPoolOpen 		*open,
				/* The resulting open struct. */

	RelFileNode 				*relFileNode,
				/* The tablespace, database, and relation OIDs for the open. */

	uint32						segmentFileNum,
				/* Which segment file. */

	char						*relationName,
				/* For tracing only.  Can be NULL in some execution paths. */
	bool						create,

	int 						*primaryError)
{
	int		fileFlags = O_RDWR | PG_BINARY;
	int		fileMode = 0600;
						/*
						 * File mode is S_IRUSR 00400 user has read permission
						 *               + S_IWUSR 00200 user has write permission
						 */

	char *filespaceLocation = NULL;

	Assert(open != NULL);

	*primaryError = 0;

	if (create)
		fileFlags = O_CREAT | O_RDWR | PG_BINARY;

	PersistentTablespace_GetFilespacePath(
										relFileNode->spcNode,
										FALSE,
										&filespaceLocation);

	if (Debug_persistent_print && create)
	{
		SUPPRESS_ERRCONTEXT_DECLARE;

		SUPPRESS_ERRCONTEXT_PUSH();

		elog(Persistent_DebugPrintLevel(),
			 "MirroredBufferPool_DoOpen: Special open %u/%u/%u --> create %s, "
			 "primary filespace location %s ",
			 relFileNode->spcNode,
			 relFileNode->dbNode,
			 relFileNode->relNode,
			 (create ? "true" : "false"),
			 (filespaceLocation == NULL) ? "<null>" : filespaceLocation);

		SUPPRESS_ERRCONTEXT_POP();
	}

	MemSet(open, 0, sizeof(MirroredBufferPoolOpen));
	open->primaryFile = -1;

	open->relFileNode = *relFileNode;
	open->segmentFileNum = segmentFileNum;

	open->create = create;
	if (true)
	{
		char *dbPath;
		char *path;

		dbPath = (char*)palloc(MAXPGPATH + 1);
		path = (char*)palloc(MAXPGPATH + 1);

		/*
		 * Do the primary work first so we don't leave files on the mirror or have an
		 * open to clean up.
		 */

		FormDatabasePath(
					dbPath,
					filespaceLocation,
					relFileNode->spcNode,
					relFileNode->dbNode);

		if (segmentFileNum == 0)
			sprintf(path, "%s/%u", dbPath, relFileNode->relNode);
		else
			sprintf(path, "%s/%u.%u", dbPath, relFileNode->relNode, segmentFileNum);

		errno = 0;

		open->primaryFile = PathNameOpenFile(path, fileFlags, fileMode);

		if (open->primaryFile < 0)
		{
			*primaryError = errno;
		}

		pfree(dbPath);
		pfree(path);
	}

	if (*primaryError != 0)
	{
		open->isActive = false;
	}
	else
	{
		open->isActive = true;
	}

	if (filespaceLocation != NULL)
		pfree(filespaceLocation);
}

void MirroredBufferPool_Open(
	MirroredBufferPoolOpen *open,
				/* The resulting open struct. */

	RelFileNode 	*relFileNode,
				/* The tablespace, database, and relation OIDs for the open. */

	uint32			segmentFileNum,
				/* Which segment file. */

	char			*relationName,
				/* For tracing only.  Can be NULL in some execution paths. */

	int 			*primaryError)

{
	MIRROREDLOCK_BUFMGR_DECLARE;

	// -------- MirroredLock ----------
	MIRROREDLOCK_BUFMGR_LOCK;

	MirroredBufferPool_DoOpen(
							open,
							relFileNode,
							segmentFileNum,
							relationName,
							/* create */ false,
							primaryError);

	MIRROREDLOCK_BUFMGR_UNLOCK;
	// -------- MirroredLock ----------
}

void MirroredBufferPool_Create(
	MirroredBufferPoolOpen 		*open,
				/* The resulting open struct. */

	RelFileNode 				*relFileNode,
				/* The tablespace, database, and relation OIDs for the open. */

	uint32						segmentFileNum,
				/* Which segment file. */

	char						*relationName,
				/* For tracing only.  Can be NULL in some execution paths. */

	int 						*primaryError)

{
	MIRROREDLOCK_BUFMGR_DECLARE;

	*primaryError = 0;

	// -------- MirroredLock ----------
	MIRROREDLOCK_BUFMGR_LOCK;

	MirroredBufferPool_DoOpen(
					open,
					relFileNode,
					segmentFileNum,
					relationName,
					/* create */ true,
					primaryError);

	MIRROREDLOCK_BUFMGR_UNLOCK;
	// -------- MirroredLock ----------
}

bool MirroredBufferPool_IsActive(
	MirroredBufferPoolOpen *open)
				/* The open struct. */
{
	return open->isActive;
}

/*
 * Flush a flat file.
 *
 */
bool MirroredBufferPool_Flush(
	MirroredBufferPoolOpen *open)
				/* The open struct. */
{
	int ioError;

	Assert(open != NULL);
	Assert(open->isActive);

	ioError = 0;

	errno = 0;

	if (FileSync(open->primaryFile) < 0)
		ioError = errno;

	errno = ioError;
	return (errno == 0);

}

/*
 * Close a bulk relation file.
 *
 */
void MirroredBufferPool_Close(
	MirroredBufferPoolOpen *open)
{
	Assert(open != NULL);
	Assert(open->isActive);
	errno = 0;

	FileClose(open->primaryFile);
	open->primaryFile = -1;
	open->isActive = false;
}

/*
 * Write a mirrored flat file.
 */
bool MirroredBufferPool_Write(
	MirroredBufferPoolOpen *open,
				/* The open struct. */

	int32		position,
				/* The position to write the data. */

	void		*buffer,
				/* Pointer to the buffer. */

	int32		bufferLen)
				/* Byte length of buffer. */

{
	int64	seekResult;
	int	primaryError;

	Assert(open != NULL);
	Assert(buffer != NULL);
	Assert(open->isActive);

	primaryError = 0;

	if (bufferLen > writeBufLen)
	{
		if (writeBuf != NULL)
		{
			pfree(writeBuf);
			writeBuf = NULL;
			writeBufLen = 0;
		}
	}

	if (writeBuf == NULL)
	{
		writeBufLen = bufferLen;

		writeBuf = MemoryContextAlloc(TopMemoryContext, writeBufLen);
		if (writeBuf == NULL)
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 (errmsg("could not allocate memory for mirrored alligned buffer"))));
	}

	/*
	 * memcpy() is required since buffer is still changing, however filerep
	 * requires identical data to be written to primary and its mirror
	 */
	memcpy(writeBuf, buffer, bufferLen);

	if (true)
	{
		errno = 0;

		seekResult = FileSeek(open->primaryFile, position, SEEK_SET);
		if (seekResult != position)
		{
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not seek in file to position %d in file '%s', segment file %d : %m",
							position,
							relpath(open->relFileNode),
							open->segmentFileNum)));
		}

		errno = 0;
		if ((int) FileWrite(open->primaryFile, writeBuf, bufferLen) != bufferLen)
		{
			/* if write didn't set errno, assume problem is no disk space */
			if (errno == 0)
				errno = ENOSPC;
			primaryError = errno;
		}
	}

	errno = primaryError;
	return (primaryError == 0);

}

/*
 * Read a mirrored buffer pool page.
 */
int MirroredBufferPool_Read(
	MirroredBufferPoolOpen *open,
				/* The open struct. */

	int32		position,
				/* The position to write the data. */

	void		*buffer,
				/* Pointer to the buffer. */

	int32		bufferLen)
				/* Byte length of buffer. */

{
	int64 seekResult;

	Assert(open != NULL);
	Assert(buffer != NULL);
	Assert(open->isActive);

	errno = 0;
	seekResult = FileSeek(open->primaryFile, position, SEEK_SET);
	if (seekResult != position)
	{
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not seek in file to position %d in file '%s', segment file %d: %m",
				        position,
				        relpath(open->relFileNode), open->segmentFileNum)));
	}

	return FileRead(open->primaryFile, buffer, bufferLen);
}

int64 MirroredBufferPool_SeekSet(
	MirroredBufferPoolOpen *open,
				/* The open struct. */

	int32		position)
{
	Assert(open != NULL);
	Assert(open->isActive);

	errno = 0;
	return FileSeek(open->primaryFile, position, SEEK_SET);
}

int64 MirroredBufferPool_SeekEnd(
	MirroredBufferPoolOpen *open)
				/* The open struct. */
{
	Assert(open != NULL);
	Assert(open->isActive);

	errno = 0;
	return FileSeek(open->primaryFile, 0L, SEEK_END);
}

/*
 * Mirrored drop.
 */
static void MirroredBufferPool_DoDrop(
	RelFileNode 				*relFileNode,
				/* The tablespace, database, and relation OIDs for the open. */

	uint32						segmentFileNum,
				/* Which segment file. */

	char						*relationName,
				/* For tracing only.  Can be NULL in some execution paths. */

	int 						*primaryError)
{
	char *filespaceLocation = NULL;

	*primaryError = 0;

	PersistentTablespace_GetFilespacePath(
												   relFileNode->spcNode,
												   FALSE,
												   &filespaceLocation);

	if (true)
	{
		char *dbPath;
		char *path;

		dbPath = (char*)palloc(MAXPGPATH + 1);
		path = (char*)palloc(MAXPGPATH + 1);

		FormDatabasePath(
						 dbPath,
						 filespaceLocation,
						 relFileNode->spcNode,
						 relFileNode->dbNode);

		if (segmentFileNum == 0)
			sprintf(path, "%s/%u", dbPath, relFileNode->relNode);
		else
			sprintf(path, "%s/%u.%u", dbPath, relFileNode->relNode, segmentFileNum);

		errno = 0;

		if (RemovePath(path, 0) < 0)
		{
			*primaryError = errno;
		}

		pfree(dbPath);
		pfree(path);
	}

	if (filespaceLocation != NULL)
		pfree(filespaceLocation);
}

void MirroredBufferPool_Drop(
	RelFileNode					*relFileNode,

	int32						segmentFileNum,

	char						*relationName,
					/* For tracing only.  Can be NULL in some execution paths. */

	bool						isRedo,

	int							*primaryError)
{
	MirroredBufferPool_DoDrop(
						relFileNode,
						segmentFileNum,
						relationName,
						primaryError);
}

bool MirroredBufferPool_Truncate(
	MirroredBufferPoolOpen *open,
				/* The open struct. */

	int64		position)
				/* The position to cutoff the data. */
{
	int ioError = 0;

	errno = 0;
	if (FileTruncate(open->primaryFile, position) < 0)
		ioError = errno;

	errno = ioError;
	return (ioError == 0);

}


text:
package com.bitdubai.fermat_csh_api.layer.csh_cash_money_transaction.send_cash_delivery.interfaces;

import com.bitdubai.fermat_csh_api.layer.csh_cash_money_transaction.send_cash_delivery.exceptions.CantCreateSendCashDeliveryException;
import com.bitdubai.fermat_csh_api.layer.csh_cash_money_transaction.send_cash_delivery.exceptions.CantGetSendCashDeliveryException;
import com.bitdubai.fermat_csh_api.layer.csh_cash_money_transaction.send_cash_delivery.exceptions.CantUpdateStatusSendCashDeliveryException;

import java.util.List;
import java.util.UUID;

/**
 * Created by Yordin Alayn on 25.09.15.
 */
public interface SendCashDeliveryManager {
    List<SendCashDelivery> getAllSendCashDeliveryFromCurrentDeviceUser() throws CantGetSendCashDeliveryException;

    SendCashDelivery createSendCashDelivery(
             final String publicKeyCustomer
            ,final String publicKeyBroker
            ,final String balanceType
            ,final String transactionType
            ,final float amount
            ,final String cashCurrencyType
            ,final String cashReference
            ,final String infoDelivery
    ) throws CantCreateSendCashDeliveryException;

    void updateStatusSendCashDelivery(final UUID cashTransactionId) throws CantUpdateStatusSendCashDeliveryException;
}


text:
package org.dita.dost.platform;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * List transtypes integration action.
 *
 * @since 1.5.4
 * @author Jarno Elovirta
 */
final class ListTranstypeAction extends ImportAction {

    /**
     * Get result.
     * @return result
     */
    @Override
    public void getResult(final ContentHandler buf) throws SAXException {
        final String separator = paramTable.containsKey("separator") ? paramTable.get("separator") : "|";
        final List<String> v = new ArrayList<>(valueSet);
        Collections.sort(v);
        final StringBuilder retBuf = new StringBuilder();
        for (final Iterator<String> i = v.iterator(); i.hasNext(); ) {
            retBuf.append(i.next());
            if (i.hasNext()) {
                retBuf.append(separator);
            }
        }
        final char[] ret = retBuf.toString().toCharArray();
        buf.characters(ret, 0, ret.length);
    }

    @Override
    public String getResult() {
        throw new UnsupportedOperationException();
    }

}


text:
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from articles.models import ArticleTranslation

def article(request, language, article_slug):
  if request.user.is_staff:
    article_translation = get_object_or_404(ArticleTranslation, language=language, slug=article_slug)
  else:
    article_translation = get_object_or_404(ArticleTranslation, language=language, slug=article_slug, published=True)
  return render_to_response('articles/article.html', locals(), context_instance=RequestContext(request))


text:
import { blobDisplayPath } from '../../../helpers/blob-display-path';
import { module, test } from 'qunit';

module('Unit | Helper | blob display path');

// Replace this with your real tests.
test('it works', function (assert) {
    var result = blobDisplayPath(['mydir/myblob.png', 'mydir/']);
    assert.ok(result === 'myblob.png');
});


text:
<?php

namespace Bootcamp\JobeetBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormError;

class JobFilterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', 'filter_number_range')
            ->add('companyName', 'filter_text')
            ->add('type', 'filter_number_range')
            ->add('logo', 'filter_text')
            ->add('url', 'filter_text')
            ->add('position', 'filter_text')
            ->add('location', 'filter_text')
            ->add('description', 'filter_text')
            ->add('howToApply', 'filter_number_range')
            ->add('email', 'filter_text')
        ;

        $listener = function(FormEvent $event)
        {
            // Is data empty?
            foreach ($event->getData() as $data) {
                if(is_array($data)) {
                    foreach ($data as $subData) {
                        if(!empty($subData)) return;
                    }
                }
                else {
                    if(!empty($data)) return;
                }
            }

            $event->getForm()->addError(new FormError('Filter empty'));
        };
        $builder->addEventListener(FormEvents::POST_BIND, $listener);
    }

    public function getName()
    {
        return 'bootcamp_jobeetbundle_jobfiltertype';
    }
}


text:
namespace Jasily.ComponentModel.Editable.Converters
{
    public abstract class ToStringConverter<T> : Converter<T, string>
    {
        #region Overrides of Converter<T,string>

        public override bool CanConvert(T value) => true;

        public override bool CanConvertBack(string value) => true;

        public override string Convert(T value) => value?.ToString();

        #endregion
    }
}


text:
using Api.ApplicationServices;
using Api.Data;
using Api.Models;
using Api.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;

namespace tests.Unit
{
    [TestClass]
    public class ProductHistoryTests
    {
        [TestMethod]
        public void Given_One_Product_With_One_History_When_Calculanting_Min_And_Max_Price_Then_Calculate_It()
        {
            var product = new Product("Teste", 2);
            var sut = new ProductHistory(product);

            Assert.AreEqual(2, sut.ExpensiverPrice);
            Assert.AreEqual(2, sut.CheaperPrice);
        }

        [TestMethod]
        public void Given_One_Product_With_Two_Histories_When_Calculanting_Min_And_Max_Price_Then_Calculate_It()
        {
            var product1 = new Product("Teste", 2);
            var product2 = new Product("Teste", 3);
            var sut = new ProductHistory(product1);

            sut.AddToProductsOfThePast(product2);

            Assert.AreEqual(3, sut.ExpensiverPrice);
            Assert.AreEqual(2, sut.CheaperPrice);
        }

        [TestMethod]
        public void Given_One_Product_With_4_Histories_When_Calculanting_Min_And_Max_Price_Then_Calculate_It()
        {
            var product1 = new Product("Teste", 2);
            var product2 = new Product("Teste", 3);
            var product3 = new Product("Teste", 1.3f);
            var product4 = new Product("Teste", 3.75f);
            var sut = new ProductHistory(product1);

            sut.AddToProductsOfThePast(product2);
            sut.AddToProductsOfThePast(product3);
            sut.AddToProductsOfThePast(product4);

            Assert.AreEqual(3.75f, sut.ExpensiverPrice);
            Assert.AreEqual(1.3f, sut.CheaperPrice);
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Image gallery</title>
<?php include("gallery/include/upper.php") ?>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>

<body>
 <?php include("gallery/index.php") ?>
 <?php include("gallery/include/footer.php") ?>
</body>
</html>


text:
"""Advanced language features covered in the official Python 3 tutorial."""

# Import an entire package.
import sys

# Import a submodule from a package.
from os import path ## Preferred Pythonic approach.
import os.path
from os import *

# Import a specific function or variable from a submodule.
from os.path import isdir ## Function
from os.path import curdir ## Variable

def demo_concat(*arguments, sep='/'):
    """Demo a variadic argument with an optional keyword argument."""

    return sep.join(arguments)

def another_fn(demo_decorator_fn):
    """Decorator function that accompanies demo_decorator()."""

    def new_f():
        print('Inside @another_fn and inside', demo_decorator_fn.__name__, '.')

        # Calling demo_decorator() here results in an infinite loop.

        print('Calling demo_decorator:')
        demo_decorator_fn()
        print('Finished calling demo_decorator and exiting.')

    # Returning the nested function runs the code defined here.
    return new_f

@another_fn
def demo_decorator():
    """Demo Python decorator syntax.

    In order to work, the decorator function must come before the
    decorated function.
    """
    print('Inside demo_decorator.')

def demo_default_values(num=3, person='Sam', optional='Surprise!'):
    """Demo default and keyword argument values."""

    if optional != 'Surprise!':
        print('Optional Value: ', optional)
    elif num == 3 and person == 'Sam':
        print('Default Value: ', num, 'Default Person: ', person)
    else:
        print('Value: ', num, 'Person: ', person)

def demo_lambda(n):
    """Demo a lambda expression."""

    return lambda x: x + n

def demo_modules():
    """Demonstrate basic module functions."""

    # The dir() function defines which names a module defines.
    names = dir() ## Names currently defined.
    print('dir():', names)
    names = dir(os.path) ## Names defined in this package.
    print('dir(os.path):', names)

    # Importing a function or variable directly places it in the local
    # symbol table.

    print('curdir: ', curdir)
    print('isdir: ', isdir('.'))

def demo_set():
    """ Demo the set data type."""

    # A set can be created using the set() function or curly braces.

    s1 = set() ## This is the only way to create an empty set.
    s2 = {'ant', 'bird', 'cat', 'dog', 'alligator'}

    # Sets support mathematic operations.

    s1.add('alligator')
    s1.add('dog')
    s1.add('brontosaurus')

    print(s2 - s1) ## Elements in s2 but not s1.
    print(s2 | s1) ## Elements in s2 or s1.
    print(s2 & s1) ## Elements in s2 and s1.
    print(s2 ^ s1) ## Elements in s2 or s1 but not both.

def main():
    # Function names can be assigned to and referenced using a variable.

    print('<--- Default Values --->')
    dv = demo_default_values

    # Functions can have default argument values.

    dv()
    dv(5, 'Samantha')

    # Keyword arguments are supplied directly, in any order, as long as
    # they come after any required positional arguments.

    dv(optional='Soda Popinski!')

    # Variadic arguments are denoted with a single asterisk. They scoop
    # up all remaining arguments after any positional arguments that
    # come before it and make these available as a tuple. Function
    # parameters listed after a variadic argument are only accessible
    # when called as a keyword argument. Arguments with 2 asterisks,
    # (**d for example), take a dictionary object.

    print('\n<--- Variadic Arguments --->')
    print(demo_concat('flour', 'sugar', 'blueberries', 'syrup', 'butter'))
    print(demo_concat('flour', 'sugar', 'blueberries', 'syrup', 'butter', sep=','))

    # In addition to small, anonymous functions, lambda expressions can
    # also be returned from a function.

    print('\n<--- Lambda Expressions --->')
    val = demo_lambda(42) ## Returns a lambda expression seeded with 42.
    print(val(3)) ## Prints 45.

    # Sets are unordered, unique data types that support mathematical
    # functions and membership testing.

    print('\n<--- Sets --->')
    demo_set()

    # When looping through an iterable, the enumerate function can
    # extract the index value and the actual value.

    print('\n<--- Enumerate --->')
    li = ['a', 'b', 'c', 'd']
    for i, v in enumerate(li):
        print(i, v)

    # Decorators are a shortcut notation for producing a "function
    # within a function". They can apply to functions and classes. The
    # result is identical to doing this:
    #
    # def foo(): pass
    # foo = some_static_method(foo)

    print('\n<--- Decorators --->')
    demo_decorator()

    # Modules (*.py files) can be imported in a variety of ways. When
    # building a package containing multiple modules, the project
    # directory structure dictates where Python finds the needed files.
    # __init__.py contains package initialization code. __all__ is a
    # list variable that defines which modules import * will import.

    print('\n<--- Modules --->')
    demo_modules()

    # String formatting can also be done with dictionary objects using
    # the format() function.

    print('\n<--- Strings --->')
    d = {'Jim': 'captain', 'McCoy': 'doctor', 'Spock': 'science officer'}
    print('Ask if {0[Jim]} and {0[McCoy]} should tell {0[Spock]}.'.format(d)) ## Standard format.
    print('Ask if {Jim} and {McCoy} should tell {Spock}.'.format(**d)) ## Unpacking the dictionary.

if __name__ == '__main__':
    main()


text:
<!doctype html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title></title>

		<link rel="apple-touch-startup-image" href="images/ios-startup-image-landscape.png" media="(orientation:landscape)" />
		<link rel="apple-touch-startup-image" href="images/ios-startup-image-portrait.png" media="(orientation:portrait)" />
		<link rel="apple-touch-icon" href="images/icon.png"/>

		<meta name="description" content="">
		<meta name="viewport" content="width=device-width">

		<link rel="stylesheet" href="views/styles/durandal.css" type="text/css">

		<link rel="stylesheet" href="views/styles/app.css">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black" />
		<meta name="format-detection" content="telephone=no"/>

		<meta name="viewport" content="width=device-width" />


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Trollbridge.Core.Results
{
    public class NonQueryResults
    {
        public int ExecuteResult { get; set; } // Number of rows affected by the ExecuteNonQuery command
        public int SpReturnValue { get; set; } // Stored procedure return value (if stored procedure called)

        public NonQueryResults()
        {
        }
    }
}


text:
@interface NewsListViewController ()<UITableViewDelegate, UITableViewDataSource>
//UI
@property (nonatomic, strong) UITableView *tableNode;
//Data
@property (nonatomic, strong) NewsListViewModel *listViewModel;
@end

@implementation NewsListViewController

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initParams];
    [self addTableNode];
    [self loadData];
}

#pragma mark - init

- (void)initParams
{
    _sourceType = 1;
}

- (void)addTableNode
{
    [self.view addSubview:self.tableNode];
    //使用masonry刷新横竖屏切换布局
    [_tableNode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)loadData
{
    [[self.listViewModel.fetchNewsListCommand execute:_topicID] subscribeNext:^(id x) {
        [_tableNode reloadData];
    } error:^(NSError *error) {

    }];
}

#pragma mark - tableView dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listViewModel.listModels.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsListInfoModel *listInfoModel = self.listViewModel.listModels[indexPath.row];
    if (_sourceType == 0) {
        NewsImageTitleCellNode *cellNode = [NewsImageTitleCellNode cellWithTableView:tableView];
        [cellNode setupListInfoModel:listInfoModel];
        return cellNode;
    }else{
        switch (listInfoModel.showType) {
            case 2:
            {
                NewsTitleImageCellNode *cellNode = [NewsTitleImageCellNode cellWithTableView:tableView];
                [cellNode setupListInfoModel:listInfoModel];
                return cellNode;
            }
                break;

            default:
            {
                NewsNormalCellNode *cellNode = [NewsNormalCellNode cellWithTableView:tableView];
                [cellNode setupListInfoModel:listInfoModel];
                return cellNode;
            }
                break;
        }
    }
}

#pragma mark - tableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsListInfoModel *listInfoModel = self.listViewModel.listModels[indexPath.row];
    NewsDetailViewController *detailViewController = [[NewsDetailViewController alloc] init];
    detailViewController.newsID = listInfoModel.docid;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

#pragma mark - setter / getter
- (UITableView *)tableNode
{
    if (!_tableNode) {
        UITableView *tableNode = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableNode.backgroundColor = [UIColor whiteColor];
        tableNode.delegate = self;
        tableNode.dataSource = self;
        tableNode.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableNode.rowHeight = UITableViewAutomaticDimension;
        tableNode.estimatedRowHeight = 100;
        _tableNode = tableNode;

    }
    return _tableNode;
}

- (NewsListViewModel *)listViewModel
{
    if (!_listViewModel) {
        NewsListViewModel *listViewModel = [[NewsListViewModel alloc] init];
        _listViewModel = listViewModel;
    }
    return _listViewModel;
}

#pragma mark - other
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
class PluginStoreRow < ActiveRecord::Base
end

# == Schema Information
#
# Table name: plugin_store_rows
#
#  id          :integer          not null, primary key
#  plugin_name :string           not null
#  key         :string           not null
#  type_name   :string           not null
#  value       :text
#
# Indexes
#
#  index_plugin_store_rows_on_plugin_name_and_key  (plugin_name,key) UNIQUE
#


text:
def extractSkinnarviksbergetWordpressCom(item):
	'''
	Parser for 'skinnarviksberget.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	if item['tags'] == ['未分类']:
		titlemap = [
			('Sinister Ex-Girlfriend',      'Sinister Ex-Girlfriend',          'translated'),
			('Tensei Shoujo no Rirekisho',  'Tensei Shoujo no Rirekisho',      'translated'),
			('Master of Dungeon',           'Master of Dungeon',               'oel'),
			('Handsome Friend',             'Handsome Friend',                 'translated'),
			('Strategy to Capture Men',     'Strategy to Capture Men',         'translated'),
			('before the divorce',          'before the divorce',              'translated'),
		]

		for titlecomponent, name, tl_type in titlemap:
			if titlecomponent.lower() in item['title'].lower():
				return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	tagmap = [
		('handsome friend',          'handsome friend',                         'translated'),
		('before the divorce',       'before the divorce',                      'translated'),
		('stcm',                     'Strategy to Capture Men',                 'translated'),
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


text:
<?xml version="1.0" encoding="UTF-8"?>
<settings
    xsi:schemaLocation = "http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd"
    xmlns = "http://maven.apache.org/SETTINGS/1.1.0"
    xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance">
    <profiles>
     <profile>
		<repositories>
		  <repository>
			<snapshots>
			  <enabled>false</enabled>
			</snapshots>
			<id>central</id>
			<name>gist-virtual-release</name>
			<url>http://artifactory.dev.cba/artifactory/gist-maven/</url>
		  </repository>
		  <repository>
			<snapshots />
			<id>snapshots</id>
			<name>gist-virtual-dev</name>
			<url>http://artifactory.dev.cba/artifactory/gist-maven/</url>
		  </repository>
		   <repository>
			<snapshots />
			<id>snapshots</id>
			<name>dna-virtual-dev</name>
			<url>http://artifactory.dev.cba/artifactory/dna-docker-dev-local/</url>
		  </repository>
		   <repository>
			<snapshots />
			<id>snapshots</id>
			<name>cep</name>
			<url>http://artifactory.dev.cba/artifactory/cep/</url>
		  </repository>
		</repositories>
		<pluginRepositories>
		  <pluginRepository>
			<snapshots>
			  <enabled>false</enabled>
			</snapshots>
			<id>central</id>
			<name>gist-virtual-release</name>
			<url>http://artifactory.dev.cba/artifactory/gist-maven/</url>
		  </pluginRepository>
		  <pluginRepository>
			<snapshots />
			<id>snapshots</id>
			<name>gist-virtual-dev</name>
			<url>http://artifactory.dev.cba/artifactory/gist-maven/</url>
		  </pluginRepository>
		  <pluginRepository>
			<snapshots />
			<id>snapshots</id>
			<name>dna-virtual-dev</name>
			<url>http://artifactory.dev.cba/artifactory/dna-docker-dev-local/</url>
		  </pluginRepository>
		</pluginRepositories>
      <id>ameventprocessor-dev</id>
    </profile>
    </profiles>
</settings>


text:
MyGi - health tracking App for iOS and Android built with React Native. Coming soon to an app store near you

![App Screens](/docs/MyGi-App-ScreenCast.gif?raw=true "App Screens")

## Notable Dependencies

| Module | Version         | Comment           | Resource Links  |
| ------ | --------------- | ----------------- | --------------- |
| react-native | 0.42.0 | React Native build for iOS and Android with an entirely shared code-base across the two platforms | [React Native](https://facebook.github.io/react-native/) |
| react-navigation | 1.0.0.-beta.6  | It does the job quite well, and the API is a pleasure to work with - however the keen eye can still tell the navigation is JS based rather than native e.g. the header transitions can be juddery. I also had to put a hack in to stop 'double tap' of certain items adding the target nav screen to the stack twice | [React  Navigation](https://github.com/react-community/react-navigation) |
| react-native-vector-icons | 4.0.0 | For the in app icons - currently utilises the Ionicons icon set - see the [Beyond JS](#beyond-js) section below for more info | [React Native Vector Icons](https://github.com/oblador/react-native-vector-icons) [Ionicons](http://ionicframework.com/docs/v2/ionicons/) |
| styled-components | 1.4.3 | Used in most places throughout the app - tho there are still some legacy inline stylesheet based components that could do with refactoring to styled-components. Provides a nice separation in our components between style and function. I also applied a particular 'DisplayName_' convention in each styled-component file which made finding and debugging CSS rules via the React Native Debugger (see [below](#useful-tools)) a breeze | [Styled Components](https://github.com/styled-components/styled-components) |
| redux | 3.6.0 | For state management along with its cousins react-redux (v5.0.1) and redux-thunk (v2.1.0) | [redux](https://github.com/reactjs/redux) [react-redux](https://github.com/reactjs/react-redux) [redux-thunk](https://github.com/gaearon/redux-thunk) |
| redux-persist | 4.4.2 | For persisting the state in the native app storage (AsyncStorage). Applied as redux middleware | [redux-persist](https://github.com/rt2zz/redux-persist) |
| moment | 2.17.1 | A must have for any/all date based logic in the app | [Moment JS](http://momentjs.com/) |

### Useful Tools

[React Native Debugger](https://github.com/jhen0409/react-native-debugger) - really useful Chrome app that provides React / Redux / Dev Tools. And enables tweaking of

## Install

Ensure you have the React Native local environ dependencies installed (e.g. XCode and Android Studio - [see getting started](https://facebook.github.io/react-native/docs/getting-started.html)) then run:

```
$ yarn install
or
$ npm install
```

### Run on iOS Emulator

No need to open XCode, just run:

```
$ react-native run-ios
```

### Run on Android Emulator

Open android virtual device manager

```
$ android avd
```

Start a simulator from the device manager, then run the below in a new terminal window

```
$ react-native run-android
```

## Release

See the [docs](https://facebook.github.io/react-native/docs/running-on-device.html#building-your-app-for-production) for how to release on iOS and Android. (Note: for this project you can cherry pick the last commit on the `release-properties` branch to apply the relevant release properties to the project)

### iOS

For iOS it involves updating the 'Scheme' for the app in XCode from 'Develop' to 'Release'

### Android

For Android it involves using a signed SDK, see [these docs](https://facebook.github.io/react-native/docs/signed-apk-android.html) (Note: the keystore passwords are not included in this repository)

Once this set up is done, the following can be run to generate a standalone release build for Android

```
$ cd android && ./gradlew assembleRelease
```

This will generate a release apk file that can be found at:

- android > app > build > outputs > apk

### Beyond JS

Below is a list of some of the tasks that were required in the build of this app that went beyond just writing React JS code:

| Task          | Description           | Resource Links  |
| ------------- | --------------------- | ---- |
| Icons         | The app uses react-native-vector-icons which required some manual adjustments in order to add the Icon font files as assets to the respective iOS and Android ecosystems. Running `$ react-native link` seemed to do the trick however it added multiple icon files and as we are currently only using the Ionicon fonts, the unused fonts were then manually removed. | [React Native Vector Icons](https://github.com/oblador/react-native-vector-icons) |
| App Icon | These was generated using a fantastic Yeoman based CLI tool which is a subset of  [generator-rn-toolbox](https://github.com/bamlab/generator-rn-toolbox) and requires 'imagemagick' to be installed locally in order to generate the icons with `$ yo rn-toolbox:assets --icon src/config/img/my-gi-icon.png` | [Generate Icons](https://github.com/bamlab/generator-rn-toolbox/blob/master/generators/assets/README.md) |
| Splash Screen | Used the same CLI tool as the App Icon but with command `$ yo rn-toolbox:assets --splash src/config/img/my-gi-splash.png`. Note to make it take effect I seemingly had to open XCode and in General settings clear the Launch Screen File, select Use Asset Catalog then Import after which you can select LaunchImage | [Generate Splash Screens](https://github.com/bamlab/generator-rn-toolbox/blob/master/generators/assets/README.md) |


text:
package org.apache.velocity.context;

import org.apache.velocity.context.Context;
import java.io.Writer;

public class AbstractContext implements Context {
    public Object put(String key, Object value) {
        return null;
    }

    public Object internalPut(String key, Object value) {
        return null;
    }
}


text:
// --------------------------------------------------------------------------
// Copyright (c) 2004, Drew Davidson and Luke Blanshard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Drew Davidson nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// --------------------------------------------------------------------------
package org.ognl.test;

import junit.framework.TestSuite;
import ognl.ExpressionSyntaxException;

import java.util.Arrays;

public class ConstantTest extends OgnlTestCase
{

    private static Object[][] TESTS = {
            { "12345", new Integer(12345) },
            { "0x100", new Integer(256) },
            { "0xfE", new Integer(254) },
            { "01000", new Integer(512) },
            { "1234L", new Integer(1234) },
            { "12.34", new Double(12.34) },
            { ".1234", new Double(.12340000000000) },
            { "12.34f", Double.valueOf(12.34) },
            { "12.", new Double(12) },
            { "12e+1d", new Double(120) },
            { "'x'", new Character('x') },
            { "'\\n'", new Character('\n') },
            { "'\\u048c'", new Character('\u048c')},
            { "'\\47'", new Character('\47') },
            { "'\\367'", new Character('\367') },
            { "'\\367", ExpressionSyntaxException.class },
            { "'\\x'", ExpressionSyntaxException.class },
            { "\"hello world\"", "hello world" },
            { "\"\\u00a0\\u0068ell\\'o\\\\\\n\\r\\f\\t\\b\\\"\\167orld\\\"\"", "\u00a0hell'o\\\n\r\f\t\b\"world\"" },
            { "\"hello world", ExpressionSyntaxException.class },
            { "\"hello\\x world\"", ExpressionSyntaxException.class },
            { "null", null },
            { "true", Boolean.TRUE },
            { "false", Boolean.FALSE },
            { "{ false, true, null, 0, 1. }",
              Arrays.asList(new Object[] { Boolean.FALSE, Boolean.TRUE, null, new Integer(0), new Double(1) }) },
            { "'HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"'",
              "HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"" },
    };

    /*
     * =================================================================== Public static methods
     * ===================================================================
     */
    public static TestSuite suite()
    {
        TestSuite result = new TestSuite();

        for(int i = 0; i < TESTS.length; i++) {
            result.addTest(new ConstantTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null,
                                            (String) TESTS[i][0], TESTS[i][1]));
        }
        return result;
    }

    /*
     * =================================================================== Constructors
     * ===================================================================
     */
    public ConstantTest()
    {
        super();
    }

    public ConstantTest(String name)
    {
        super(name);
    }

    public ConstantTest(String name, Object root, String expressionString, Object expectedResult, Object setValue,
                        Object expectedAfterSetResult)
    {
        super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult);
    }

    public ConstantTest(String name, Object root, String expressionString, Object expectedResult, Object setValue)
    {
        super(name, root, expressionString, expectedResult, setValue);
    }

    public ConstantTest(String name, Object root, String expressionString, Object expectedResult)
    {
        super(name, root, expressionString, expectedResult);
    }
}


text:
import { Schema } from "mongoose";

export const foodItemTemplateSchema = new Schema({
  categoryIds: [{
    ref: "FoodItemCategory",
    type: Schema.Types.ObjectId
  }],
  created: {
    required: true,
    type: Number
  },
  lastModified: {
    required: true,
    type: Number
  },
  name: {
    required: true,
    type: String
  },
  unitId: {
    ref: "FoodItemUnit",
    type: Schema.Types.ObjectId
  }
});


text:
struct A {
    typedef std::set<A> Set;
    int data;
    Set m;
    Set::iterator it;
    Set::const_iterator cit;
};

inline bool operator==(A const& L, A const& R) { return &L == &R; }
inline bool operator<(A const& L, A const& R)  { return L.data < R.data; }
int main(int, char**) {
    A a;

  return 0;
}


text:
package org.apache.jena.reasoner.rulesys.builtins;

import org.apache.jena.graph.* ;
import org.apache.jena.reasoner.rulesys.* ;

/**
 * Tests if the first argument is less than the second.
 */
public class LessThan extends BaseBuiltin {

    /**
     * Return a name for this builtin, normally this will be the name of the
     * functor that will be used to invoke it.
     */
    @Override
    public String getName() {
        return "lessThan";
    }

    /**
     * Return the expected number of arguments for this functor or 0 if the number is flexible.
     */
    @Override
    public int getArgLength() {
        return 2;
    }

    /**
     * This method is invoked when the builtin is called in a rule body.
     * @param args the array of argument values for the builtin, this is an array
     * of Nodes, some of which may be Node_RuleVariables.
     * @param context an execution context giving access to other relevant data
     * @return return true if the buildin predicate is deemed to have succeeded in
     * the current environment
     */
    @Override
    public boolean bodyCall(Node[] args, int length, RuleContext context) {
        checkArgs(length, context);
        Node n1 = getArg(0, args, context);
        Node n2 = getArg(1, args, context);
        if (Util.comparable(n1, n2)) {
            return Util.compareTypedLiterals(n1, n2) < 0;
        } else {
            return false;
        }
    }

}


text:
 Policy Simulator is a collection of endpoints for creating, running, and viewing a Replay. A `Replay` is a type of simulation that lets you see how your members' access to resources might change if you changed your IAM policy. During a `Replay`, Policy Simulator re-evaluates, or replays, past access attempts under both the current policy and your proposed policy, and compares those results to determine how your members' access might change under the proposed policy.

This page contains information about getting started with the Policy Simulator API
using the Google API Client Library for Java. In addition, you may be interested
in the following documentation:

* Browse the [Javadoc reference for the Policy Simulator API][javadoc]
* Read the [Developer's Guide for the Google API Client Library for Java][google-api-client].
* Interact with this API in your browser using the [APIs Explorer for the Policy Simulator API][api-explorer]

## Installation

### Maven

Add the following lines to your `pom.xml` file:

```xml
<project>
  <dependencies>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-policysimulator</artifactId>
      <version>v1beta1-rev20220429-1.32.1</version>
    </dependency>
  </dependencies>
</project>
```

### Gradle

```gradle
repositories {
  mavenCentral()
}
dependencies {
  implementation 'com.google.apis:google-api-services-policysimulator:v1beta1-rev20220429-1.32.1'
}
```

[javadoc]: https://googleapis.dev/java/google-api-services-policysimulator/latest/index.html
[google-api-client]: https://github.com/googleapis/google-api-java-client/
[api-explorer]: https://developers.google.com/apis-explorer/#p/policysimulator/v1/


text:
using System;
using System.Windows.Forms;
using EnvDTE80;

namespace Knowledge.KIF.Converter.gui {

    public partial class ConvForm : Form {

        private string _filePath = null;
        private DTE2 _environment;
        public ConvForm(string filePath, DTE2 environment) {
            InitializeComponent();
            _filePath = filePath;
            _environment = environment;
        }

        public DTE2 Environment {
            get { return _environment; }
        }

        private void outputFormatBox_SelectedIndexChanged(object sender, EventArgs e) {

        }
    }
}


text:
export function createEditorContainer(container, translation = {}, data = {}) {
    let editor = document.createElement('div');

    editor.setAttribute('class', 'bg-overlay edit-marker');
    editor.innerHTML = `

╳

${translation.editMarker}

                    ${translation.address}
                    <input type="text" id="address" name="address" placeholder="${translation.address}" class="add-marker-form__address" value="${data.address}" />

                    <input type="checkbox" id="display-window" name="displayWindow" ${data.displayWindow ? ' checked="checked"' : ''} />
                    ${translation.displayInfo}

                    ${translation.content}
                    <textarea name="content" id="content" rows="5" placeholder="${translation.content}">${data.content}</textarea>

                    <button name="delete" class="button delete">${translation.delete}</button>
                    <button name="save" class="button save">${translation.save}</button>

    `;

    container.append(editor);

    editor.querySelector('*[data-action="close"]').addEventListener('click', () => editor.parentNode.removeChild(editor));

    return editor;
}


text:
        {{ this.display_name }}:

    <input class="form-file" type="file" id="attribute_{{id}}" name="attribute[{{this.id}}]" {{#if required}}required{{/if}}>
    {{#if original_name}}
        {{{lang 'products.file_option_set' url=file_url name=original_name}}}
        {{lang 'cart.remove_file'}}<input type="checkbox" name="{{file_remove}}">
    {{/if}}

{{#if file_size}}{{lang 'products.max_filesize'}} {{file_size}}, {{/if}}{{#if file_types}}{{lang 'products.filetypes'}} {{file_types}}{{/if}}


text:
module BabyKeepsakesHelper
end


text:
<?php

namespace Oro\Bundle\CronBundle\Command;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\ORM\EntityManager;

use JMS\JobQueueBundle\Entity\Job;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

use Oro\Component\Log\OutputLogger;

class CleanupCommand extends ContainerAwareCommand implements CronCommandInterface
{
    const COMMAND_NAME = 'oro:cron:cleanup';
    const BATCH_SIZE   = 40;
    const DAYS         = 1; // cleanup entries older than ...

    const EXITCODE_SUCCESS = 0;
    const EXITCODE_FAILED = 1;

    /**
     * {@inheritdoc}
     */
    public function getDefaultDefinition()
    {
        return '0 1 * * *'; // every day
    }

    /**
     * {@inheritdoc}
     */
    public function configure()
    {
        $this
            ->setName(static::COMMAND_NAME)
            ->addOption(
                'dry-run',
                'd',
                InputOption::VALUE_NONE,
                'If option exists items won\'t be deleted, items count that match cleanup criteria will be shown'
            )
            ->setDescription('Clear cron-related log-alike tables: queue, etc');
    }

    /**
     * {@inheritdoc}
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $logger = new OutputLogger($output);
        $em     = $this->getContainer()->get('doctrine.orm.entity_manager');
        $con    = $em->getConnection();

        if ($input->getOption('dry-run')) {
            $stm = $this->getConditionStatement($con, true);
            $stm->execute();
            $result = $stm->fetchColumn();

            $message = 'Will be removed %d rows';
        } else {
            $em->beginTransaction();
            $result = 0;
            try {
                $stm = $this->getConditionStatement($con);
                $stm->execute();

                $buf = [];
                while ($id = $stm->fetchColumn()) {
                    $buf[] = $id;
                    $result++;

                    $buf = $this->processBuff($em, $buf);
                }

                $this->processBuff($em, $buf, 0);

                $em->commit();
            } catch (\Exception $e) {
                $em->rollback();
                $logger->critical($e->getMessage(), ['exception' => $e]);

                return self::EXITCODE_FAILED;
            }

            $message = 'Removed %d rows';
        }

        $logger->notice(sprintf($message, $result));
        $logger->notice('Completed');

        return self::EXITCODE_SUCCESS;
    }

    /**
     * @param EntityManager $em
     * @param array         $buf
     * @param int           $size
     *
     * @return array
     */
    protected function processBuff(EntityManager $em, $buf, $size = self::BATCH_SIZE)
    {
        if (count($buf) > $size) {
            $this->flushBatch($em->getConnection(), $buf);

            $em->commit();
            $em->beginTransaction();
            $buf = [];
        }

        return $buf;
    }

    /**
     * Get statement with bound values
     *
     * @param Connection $connection
     * @param bool       $isCount
     *
     * @return Statement
     */
    protected function getConditionStatement(Connection $connection, $isCount = false)
    {
        $sql = "SELECT %s FROM jms_jobs j
                 LEFT JOIN jms_job_dependencies d ON d.source_job_id=j.id
                 WHERE j.closedAt < ? AND j.state = ?
                 AND d.dest_job_id IS NULL";
        $sql = sprintf($sql, $isCount ? 'COUNT(j.id)' : 'j.id');

        $date = new \DateTime(sprintf('%d days ago', self::DAYS), new \DateTimeZone('UTC'));
        $date = $date->format('Y-m-d H:i:s');

        $stm = $connection->prepare($sql);
        $stm->bindValue(1, $date);
        $stm->bindValue(2, Job::STATE_FINISHED, \PDO::PARAM_INT);

        return $stm;
    }

    /**
     * Flush batch
     *
     * @param Connection $con
     * @param array      $ids
     */
    protected function flushBatch(Connection $con, array $ids)
    {
        $con->executeUpdate(
            "DELETE FROM jms_job_statistics WHERE job_id IN (?)",
            [$ids],
            [Connection::PARAM_INT_ARRAY]
        );

        $con->executeUpdate(
            "DELETE FROM jms_job_dependencies WHERE dest_job_id IN (?)",
            [$ids],
            [Connection::PARAM_INT_ARRAY]
        );

        $con->executeUpdate(
            "DELETE FROM jms_job_related_entities WHERE job_id IN (?)",
            [$ids],
            [Connection::PARAM_INT_ARRAY]
        );

        $con->executeUpdate(
            "DELETE FROM jms_jobs WHERE id IN (?)",
            [$ids],
            [Connection::PARAM_INT_ARRAY]
        );
    }
}


text:
module RequestLogAnalyzer::FileFormat

  # The RailsDevelopment FileFormat is an extention to the default Rails file format. It includes
  # all lines of the normal Rails file format, but parses SQL queries and partial rendering lines
  # as well.
  class RailsDevelopment < Rails
    def self.create
      # puts 'DEPRECATED: use --rails-format development instead!'
      super('development')
    end
  end
end


text:
``tornado.ioloop`` --- Main event loop
======================================

.. automodule:: tornado.ioloop

   IOLoop objects
   --------------

   .. autoclass:: IOLoop

   Running an IOLoop
   ^^^^^^^^^^^^^^^^^

   .. automethod:: IOLoop.current
   .. automethod:: IOLoop.make_current
   .. automethod:: IOLoop.clear_current
   .. automethod:: IOLoop.start
   .. automethod:: IOLoop.stop
   .. automethod:: IOLoop.run_sync
   .. automethod:: IOLoop.close
   .. automethod:: IOLoop.instance
   .. automethod:: IOLoop.install
   .. automethod:: IOLoop.clear_instance

   I/O events
   ^^^^^^^^^^

   .. automethod:: IOLoop.add_handler
   .. automethod:: IOLoop.update_handler
   .. automethod:: IOLoop.remove_handler

   Callbacks and timeouts
   ^^^^^^^^^^^^^^^^^^^^^^

   .. automethod:: IOLoop.add_callback
   .. automethod:: IOLoop.add_callback_from_signal
   .. automethod:: IOLoop.add_future
   .. automethod:: IOLoop.add_timeout
   .. automethod:: IOLoop.call_at
   .. automethod:: IOLoop.call_later
   .. automethod:: IOLoop.remove_timeout
   .. automethod:: IOLoop.spawn_callback
   .. automethod:: IOLoop.run_in_executor
   .. automethod:: IOLoop.set_default_executor
   .. automethod:: IOLoop.time
   .. autoclass:: PeriodicCallback
      :members: