text:
<?php

namespace ZendTest\Http\Client;

use PHPUnit\Framework\TestCase;
use stdClass;
use Zend\Config\Config;
use Zend\Http\Client as HTTPClient;
use Zend\Http\Client\Adapter\Exception as ClientAdapterException;
use Zend\Http\Client\Adapter\Test;
use Zend\Http\Client\Exception as ClientException;
use Zend\Http\Exception\InvalidArgumentException;
use Zend\Http\Exception\RuntimeException;
use Zend\Http\Header\SetCookie;
use Zend\Uri\Http as UriHttp;
use ZendTest\Http\Client\TestAsset\MockAdapter;
use ZendTest\Http\Client\TestAsset\MockClient;

/**
 * This Testsuite includes all Zend_Http_Client tests that do not rely
 * on performing actual requests to an HTTP server. These tests can be
 * executed once, and do not need to be tested with different servers /
 * client setups.
 *
 * @group      Zend_Http
 * @group      Zend_Http_Client
 */
class StaticTest extends TestCase
{
    // @codingStandardsIgnoreStart
    /**
     * Common HTTP client
     *
     * @var HTTPClient
     */
    protected $_client;
    // @codingStandardsIgnoreEnd

    /**
     * Set up the test suite before each test
     */
    public function setUp()
    {
        $this->_client = new MockClient('http://www.example.com');
    }

    /**
     * Clean up after running a test
     */
    public function tearDown()
    {
        $this->_client = null;
    }

    /**
     * URI Tests
     */

    /**
     * Test we can SET and GET a URI as string
     */
    public function testSetGetUriString()
    {
        $uristr = 'http://www.zend.com:80/';

        $this->_client->setUri($uristr);

        $uri = $this->_client->getUri();
        $this->assertInstanceOf(UriHttp::class, $uri, 'Returned value is not a Uri object as expected');
        $this->assertEquals($uri->__toString(), $uristr, 'Returned Uri object does not hold the expected URI');

        $uri = $this->_client->getUri()->toString();
        $this->assertInternalType(
            'string',
            $uri,
            'Returned value expected to be a string, ' . gettype($uri) . ' returned'
        );
        $this->assertEquals($uri, $uristr, 'Returned string is not the expected URI');
    }

    /**
     * Test we can SET and GET a URI as object
     */
    public function testSetGetUriObject()
    {
        $uriobj = new UriHttp('http://www.zend.com:80/');

        $this->_client->setUri($uriobj);

        $uri = $this->_client->getUri();
        $this->assertInstanceOf(UriHttp::class, $uri, 'Returned value is not a Uri object as expected');
        $this->assertEquals($uri, $uriobj, 'Returned object is not the excepted Uri object');
    }

    /**
     * Test that setting the same parameter twice in the query string does not
     * get reduced to a single value only.
     */
    public function testDoubleGetParameter()
    {
        $qstr = 'foo=bar&foo=baz';

        $this->_client->setUri('http://example.com/test/?' . $qstr);
        $this->_client->setAdapter(Test::class);
        $this->_client->setMethod('GET');
        $this->_client->send();

        $this->assertContains(
            $qstr,
            $this->_client->getLastRawRequest(),
            'Request is expected to contain the entire query string'
        );
    }

    /**
     * Header Tests
     */

    /**
     * Test we can get already set headers
     */
    public function testGetHeader()
    {
        $this->_client->setHeaders([
            'Accept-encoding' => 'gzip,deflate',
            'Accept-language' => 'en,de,*',
        ]);

        $this->assertEquals(
            $this->_client->getHeader('Accept-encoding'),
            'gzip, deflate',
            'Returned value of header is not as expected'
        );
        $this->assertEquals(
            $this->_client->getHeader('X-Fake-Header'),
            null,
            'Non-existing header should not return a value'
        );
    }

    /**
     * Authentication tests
     */

    /**
     * Test setAuth (dynamic method) fails when trying to use an unsupported
     * authentication scheme
     */
    public function testExceptUnsupportedAuthDynamic()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid or not supported authentication type: \'SuperStrongAlgo\'');

        $this->_client->setAuth('shahar', '1234', 'SuperStrongAlgo');
    }

    /**
     * Cookie and Cookie Jar tests
     */

    /**
     * Test we can properly set a new cookies
     */
    public function testSetNewCookies()
    {
        $this->_client->addCookie('cookie', 'value');
        $this->_client->addCookie('chocolate', 'chips');
        $cookies = $this->_client->getCookies();

        // Check we got the right cookiejar
        $this->assertInternalType('array', $cookies);
        $this->assertContainsOnlyInstancesOf(SetCookie::class, $cookies);
        $this->assertCount(2, $cookies);
    }

    /**
     * Test we can unset a cookie jar
     */
    public function testUnsetCookies()
    {
        // Set the cookie jar just like in testSetNewCookieJar
        $this->_client->addCookie('cookie', 'value');
        $this->_client->addCookie('chocolate', 'chips');
        $cookies = $this->_client->getCookies();

        // Try unsetting the cookies
        $this->_client->clearCookies();
        $cookies = $this->_client->getCookies();

        $this->assertEquals([], $cookies, 'Cookies are expected to be an empty array but it is not');
    }

    /**
     * Make sure using an invalid cookie jar object throws an exception
     */
    public function testSetInvalidCookies()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid parameter type passed as Cookie');

        $this->_client->addCookie('cookie');
    }

    /**
     * Configuration Handling
     */

    /**
     * Test that we can set a valid configuration array with some options
     */
    public function testConfigSetAsArray()
    {
        $config = [
            'timeout'    => 500,
            'someoption' => 'hasvalue',
        ];

        $this->_client->setOptions($config);

        $hasConfig = $this->_client->config;

        foreach ($config as $k => $v) {
            $this->assertEquals($v, $hasConfig[$k]);
        }
    }

    /**
     * Test that a Zend_Config object can be used to set configuration
     *
     * @link http://framework.zend.com/issues/browse/ZF-5577
     */
    public function testConfigSetAsZendConfig()
    {
        $config = new Config([
            'timeout'  => 400,
            'nested'   => [
                'item' => 'value',
            ],
        ]);

        $this->_client->setOptions($config);

        $hasConfig = $this->_client->config;
        $this->assertEquals($config->timeout, $hasConfig['timeout']);
        $this->assertEquals($config->nested->item, $hasConfig['nested']['item']);
    }

    /**
     * Test that passing invalid variables to setConfig() causes an exception
     *
     * @dataProvider invalidConfigProvider
     *
     * @param mixed $config
     */
    public function testConfigSetInvalid($config)
    {
        $this->expectException(ClientException\InvalidArgumentException::class);
        $this->expectExceptionMessage('Config parameter is not valid');

        $this->_client->setOptions($config);
    }

    /**
     * Test that configuration options are passed to the adapter after the
     * adapter is instantiated
     *
     * @group ZF-4557
     */
    public function testConfigPassToAdapterZF4557()
    {
        $adapter = new MockAdapter();

        // test that config passes when we set the adapter
        $this->_client->setOptions(['param' => 'value1']);
        $this->_client->setAdapter($adapter);
        $adapterCfg = $adapter->config;
        $this->assertEquals('value1', $adapterCfg['param']);

        // test that adapter config value changes when we set client config
        $this->_client->setOptions(['param' => 'value2']);
        $adapterCfg = $adapter->config;
        $this->assertEquals('value2', $adapterCfg['param']);
    }

    /**
     * Other Tests
     */

    /**
     * Test the getLastRawResponse() method actually returns the last response
     */
    public function testGetLastRawResponse()
    {
        // First, make sure we get null before the request
        $this->assertEquals(
            null,
            $this->_client->getLastRawResponse(),
            'getLastRawResponse() is still expected to return null'
        );

        // Now, test we get a proper response after the request
        $this->_client->setUri('http://example.com/foo/bar');
        $this->_client->setAdapter(Test::class);

        $response = $this->_client->send();
        $this->assertSame(
            $response,
            $this->_client->getResponse(),
            'Response is expected to be identical to the result of getResponse()'
        );
    }

    /**
     * Test that getLastRawResponse returns null when not storing
     */
    public function testGetLastRawResponseWhenNotStoring()
    {
        // Now, test we get a proper response after the request
        $this->_client->setUri('http://example.com/foo/bar');
        $this->_client->setAdapter(Test::class);
        $this->_client->setOptions(['storeresponse' => false]);

        $this->_client->send();

        $this->assertNull(
            $this->_client->getLastRawResponse(),
            'getLastRawResponse is expected to be null when not storing'
        );
    }

    /**
     * Check we get an exception when trying to send a POST request with an
     * invalid content-type header
     */
    public function testInvalidPostContentType()
    {
        if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
            $this->markTestSkipped(sprintf(
                '%s online tests are not enabled',
                HTTPClient::class
            ));
        }
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Cannot handle content type \'x-foo/something-fake\' automatically');

        $this->_client->setEncType('x-foo/something-fake');
        $this->_client->setParameterPost(['parameter' => 'value']);
        $this->_client->setMethod('POST');
        // This should throw an exception
        $this->_client->send();
    }

    /**
     * Check we get an exception if there's an error in the socket
     */
    public function testSocketErrorException()
    {
        if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
            $this->markTestSkipped(sprintf(
                '%s online tests are not enabled',
                HTTPClient::class
            ));
        }
        $this->expectException(ClientAdapterException\RuntimeException::class);
        $this->expectExceptionMessage('Unable to connect to 255.255.255.255:80');

        // Try to connect to an invalid host
        $this->_client->setUri('http://255.255.255.255');

        // Reduce timeout to 3 seconds to avoid waiting
        $this->_client->setOptions(['timeout' => 3]);

        // This call should cause an exception
        $this->_client->send();
    }

    /**
     * Check that an exception is thrown if non-word characters are used in
     * the request method.
     *
     * @dataProvider invalidMethodProvider
     *
     * @param string $method
     */
    public function testSettingInvalidMethodThrowsException($method)
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid HTTP method passed');

        $this->_client->setMethod($method);
    }

    /**
     * Test that POST data with multi-dimentional array is properly encoded as
     * multipart/form-data
     */
    public function testFormDataEncodingWithMultiArrayZF7038()
    {
        if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
            $this->markTestSkipped(sprintf(
                '%s online tests are not enabled',
                HTTPClient::class
            ));
        }
        $this->_client->setAdapter(Test::class);
        $this->_client->setUri('http://example.com');
        $this->_client->setEncType(HTTPClient::ENC_FORMDATA);

        $this->_client->setParameterPost([
            'test' => [
                'v0.1',
                'v0.2',
                'k1' => 'v1.0',
                'k2' => [
                    'v2.1',
                    'k2.1' => 'v2.1.0',
                ],
            ],
        ]);

        $this->_client->setMethod('POST');
        $this->_client->send();

        $expectedLines = file(__DIR__ . '/_files/ZF7038-multipartarrayrequest.txt');

        $gotLines = explode("\n", $this->_client->getLastRawRequest());

        $this->assertEquals(count($expectedLines), count($gotLines));

        while (($expected = array_shift($expectedLines))
            && ($got = array_shift($gotLines))
        ) {
            $expected = trim($expected);
            $got = trim($got);
            $this->assertRegExp(sprintf('/^%s$/', $expected), $got);
        }
    }

    /**
     * Test that we properly calculate the content-length of multibyte-encoded
     * request body
     *
     * This may file in case that mbstring overloads the substr and strlen
     * functions, and the mbstring internal encoding is a multibyte encoding.
     *
     * @link http://framework.zend.com/issues/browse/ZF-2098
     */
    public function testMultibyteRawPostDataZF2098()
    {
        if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
            $this->markTestSkipped(sprintf(
                '%s online tests are not enabled',
                HTTPClient::class
            ));
        }
        $this->_client->setAdapter(Test::class);
        $this->_client->setUri('http://example.com');

        $bodyFile = __DIR__ . '/_files/ZF2098-multibytepostdata.txt';

        $this->_client->setRawBody(file_get_contents($bodyFile));
        $this->_client->setEncType('text/plain');
        $this->_client->setMethod('POST');
        $this->_client->send();
        $request = $this->_client->getLastRawRequest();

        if (! preg_match('/^content-length:\s+(\d+)/mi', $request, $match)) {
            $this->fail('Unable to find content-length header in request');
        }

        $this->assertEquals(filesize($bodyFile), (int) $match[1]);
    }

    /**
     * Testing if the connection isn't closed
     *
     * @group ZF-9685
     */
    public function testOpenTempStreamWithValidFileDoesntThrowsException()
    {
        if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
            $this->markTestSkipped(sprintf(
                '%s online tests are not enabled',
                HTTPClient::class
            ));
        }
        $url = 'http://www.example.com/';
        $config = [
            'outputstream' => realpath(__DIR__ . '/_files/zend_http_client_stream.file'),
        ];
        $client = new HTTPClient($url, $config);

        $result = $client->send();

        // we can safely return until we can verify link is still active
        // @todo verify link is still active
    }

    /**
     * Test if a downloaded file can be deleted
     *
     * @group ZF-9685
     */
    public function testDownloadedFileCanBeDeleted()
    {
        if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
            $this->markTestSkipped('Zend\Http\Client online tests are not enabled');
        }
        $url = 'http://www.example.com/';
        $outputFile = @tempnam(@sys_get_temp_dir(), 'zht');
        if (! is_file($outputFile)) {
            $this->markTestSkipped('Failed to create a temporary file');
        }
        $config = [
            'outputstream' => $outputFile,
        ];
        $client = new HTTPClient($url, $config);

        $result = $client->send();

        $this->assertInstanceOf('Zend\Http\Response\Stream', $result);
        if (DIRECTORY_SEPARATOR === '\\') {
            $this->assertFalse(@unlink($outputFile), 'Deleting an open file should fail on Windows');
        }
        fclose($result->getStream());
        $this->assertTrue(@unlink($outputFile), 'Failed to delete downloaded file');
    }

    /**
     * Testing if the connection can be closed
     *
     * @group ZF-9685
     */
    public function testOpenTempStreamWithBogusFileClosesTheConnection()
    {
        if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
            $this->markTestSkipped(sprintf(
                '%s online tests are not enabled',
                HTTPClient::class
            ));
        }

        $url = 'http://www.example.com';
        $config = [
            'outputstream' => '/path/to/bogus/file.ext',
        ];
        $client = new HTTPClient($url, $config);
        $client->setMethod('GET');

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Could not open temp file /path/to/bogus/file.ext');
        $client->send();
    }

    /**
     * Test sending cookie with encoded value
     *
     * @group fix-double-encoding-problem-about-cookie-value
     */
    public function testEncodedCookiesInRequestHeaders()
    {
        if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
            $this->markTestSkipped(sprintf(
                '%s online tests are not enabled',
                HTTPClient::class
            ));
        }
        $this->_client->addCookie('foo', 'bar=baz');
        $this->_client->send();
        $cookieValue = 'Cookie: foo=' . urlencode('bar=baz');
        $this->assertContains(
            $cookieValue,
            $this->_client->getLastRawRequest(),
            'Request is expected to contain the entire cookie "keyname=encoded_value"'
        );
    }

    /**
     * Test sending cookie header with raw value
     *
     * @group fix-double-encoding-problem-about-cookie-value
     */
    public function testRawCookiesInRequestHeaders()
    {
        if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
            $this->markTestSkipped(sprintf(
                '%s online tests are not enabled',
                HTTPClient::class
            ));
        }
        $this->_client->setOptions(['encodecookies' => false]);
        $this->_client->addCookie('foo', 'bar=baz');
        $this->_client->send();
        $cookieValue = 'Cookie: foo=bar=baz';
        $this->assertContains(
            $cookieValue,
            $this->_client->getLastRawRequest(),
            'Request is expected to contain the entire cookie "keyname=raw_value"'
        );
    }

    /**
     * Data providers
     */

    /**
     * Data provider of valid non-standard HTTP methods
     *
     * @return array
     */
    public static function validMethodProvider()
    {
        return [
            ['OPTIONS'],
            ['POST'],
            ['DOSOMETHING'],
            ['PROPFIND'],
            ['Some_Characters'],
            ['X-MS-ENUMATTS'],
        ];
    }

    /**
     * Data provider of invalid HTTP methods
     *
     * @return array
     */
    public static function invalidMethodProvider()
    {
        return [
            ['N@5TYM3T#0D'],
            ['TWO WORDS'],
            ['GET http://foo.com/?'],
            ['Injected' . "\n" . 'newline'],
        ];
    }

    /**
     * Data provider for invalid configuration containers
     *
     * @return array
     */
    public static function invalidConfigProvider()
    {
        return [
            [false],
            ['foobar'],
            ['foo' => 'bar'],
            [null],
            [new stdClass()],
            [55],
        ];
    }
}


text:
using System.Diagnostics;
using System.Web.Mvc;
using Twilio.Mvc;
using Twilio.TwiML.Mvc;

public class MessageStatusController : Controller
{
    [HttpPost]
    public ActionResult Index(SmsRequest request)
    {
        // Log the message id and status
        var logMessage = "\"" + request.SmsSid + "\", " +
                         "\"" + request.MessageStatus + "\"";
        Trace.WriteLine(logMessage);
        return Content("Handled");
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Falcor.Router.Extensions;
using Falcor.Router.Tests.Model;
using NUnit.Framework;

namespace Falcor.Router.Tests
{
    [TestFixture]
    public class IntegrationTest
    {
        [Test]
        public async Task Single_properties_per_route()
        {
            var routes = new List<Route>();
            routes.MapRoute()
                .PathItem(Keys.For("Events"))
                .PathItem("index", Integers.Any())
                .To(ctx =>
                {
                    var indexItem = ctx.Item<Integers>("index");
                    var index = indexItem.Values.First();
                    var reference = new Ref(
                        new Keys("EventById"),
                        new Keys("980" + index));

                    return Task.FromResult(
                        new PathValue(reference, new Keys("Events"), Integers.For(index))
                                .AsEnumerable());
                });

            routes.MapRoute()
                .PathItem(Keys.For("EventById"))
                .PathItem("key", Keys.Any())
                .PathItem(Keys.For("Name"))
                .To(ctx =>
                {
                    var pathValue = new PathValue("name1", ctx.Path.Items.ToArray());
                    return Task.FromResult(pathValue.AsEnumerable());
                });

            var routeResolver = new RouteResolver(routes);
            var pathCollapser = new PathCollapser();
            var responseBuilder = new ResponseBuilder();

            var target = new Router(routeResolver, pathCollapser, responseBuilder);

            var path1 = new Path(
                new Keys("Events"),
                new Integers(0),
                new Keys("Name"));

            var path2 = new Path(
                new Keys("Events"),
                new Integers(1),
                new Keys("Name"));

            var result = await target.Execute(path1, path2);
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Data);

            var events = result.Data["Events"] as IDictionary<string, object>;
            Assert.IsNotNull(events);
            var eventById = result.Data["EventById"] as IDictionary<string, object>;
            Assert.IsNotNull(eventById);

            var event0 = events["0"] as Ref;
            var event1 = events["1"] as Ref;
            Assert.IsNotNull(event0);
            Assert.IsNotNull(event1);
            Assert.AreEqual("EventById", event0.Path.Items[0].Value);
            Assert.AreEqual("9800", event0.Path.Items[1].Value);
            Assert.AreEqual("EventById", event1.Path.Items[0].Value);
            Assert.AreEqual("9801", event1.Path.Items[1].Value);

            var eventById1 = (IDictionary<string,object>)eventById["9800"];
            var eventById2 = (IDictionary<string, object>)eventById["9801"];
            Assert.IsNotNull(eventById1);
            Assert.IsNotNull(eventById2);
            Assert.AreEqual("name1", eventById1["Name"]);
            Assert.AreEqual("name1", eventById2["Name"]);

            // TODO: thinkg about path meaning and how to reconstruct it
//            Assert.AreEqual(2, result.Paths.Count);
//            Assert.AreEqual(new object[] { "Events", 0, "Name"}, result.Paths[0]);
//            Assert.AreEqual(new object[] { "Events", 1, "Name" }, result.Paths[1]);

            /*
response = {
    jsong : {
        "events": {
            "0": $ref(["eventsById","99801"]),
            "1": $ref(["eventsById","99802"])
        },
        "eventById": {
            "99801": { name: "name1" },
            "99802": { name: "name2" }
        }
    },
    // we don't need to worry about this for get/set, it's important only for call
    // paths : [
    //     ["events", 0, "name"],
    //     ["events", 1, "name"],
    // ]
       }*/

        }

        [Test]
        public async Task Multiple_properties_per_route()
        {
            var routes = new List<Route>();
            routes.MapRoute()
                .PathItem(Keys.For("Events"))
                .PathItem("index", Integers.Any())
                .To(ctx =>
                {
                    var indexItem = ctx.Item<Integers>("index");
                    var index = indexItem.Values.First() + 1;
                    var reference = new Ref(
                        new Keys("EventById"),
                        new Keys("980" + index));

                    return Task.FromResult(new PathValue(reference, new Keys("Events"), ctx.Path.Items[1]).AsEnumerable());
                });

            routes.MapRoute(
                Keys.For("EventById"),
                Keys.Any(),
                Keys.For("Name", "Number"),
                (ctx, eventById, keys, properties) =>
                {
                    var list = new List<PathValue>();
                    foreach (var key in keys.Values)
                    {
                        if (properties.HasKey("Name"))
                        {
                            list.Add(new PathValue("name1", eventById, Keys.For(key), Keys.For("Name")));
                        }
                        if (properties.HasKey("Number"))
                        {
                            list.Add(new PathValue(1, eventById, Keys.For(key), Keys.For("Number")));
                        }
                    }

                    return Task.FromResult(list.AsEnumerable());
                });

            var routeResolver = new RouteResolver(routes);
            var pathCollapser = new PathCollapser();
            var responseBuilder = new ResponseBuilder();

            var target = new Router(routeResolver, pathCollapser, responseBuilder);

            var path1 = new Path(
                new Keys("Events"),
                new Integers(0),
                new Keys("Name"));

            var path2 = new Path(
                new Keys("Events"),
                new Integers(0),
                new Keys("Number"));

            var result = await target.Execute(path1, path2);
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Data);

            var events = result.Data["Events"] as IDictionary<string, object>;
            Assert.IsNotNull(events);
            var eventByIdResult = result.Data["EventById"] as IDictionary<string, object>;
            Assert.IsNotNull(eventByIdResult);

            var event0 = events["0"] as Ref;
            Assert.IsNotNull(event0);
            Assert.AreEqual("EventById", event0.Path.Items[0].Value);
            Assert.AreEqual("9801", event0.Path.Items[1].Value);

            var eventById1 = (IDictionary<string, object>)eventByIdResult["9801"];
            Assert.IsNotNull(eventById1);
            Assert.AreEqual("name1", eventById1["Name"]);
            Assert.AreEqual(1, eventById1["Number"]);
        }
    }
}


text:
module ContactForm {
    export function init() {
        // Get project
        var project = Project.getInstance();

        // Set version in contact form
        $("#contact-version").attr("placeholder", Main.getVersion());

        // Set validation on focusout
        $("#contact-form > .form-group").each( (i, item) => {
            $(item).on( "focusout", () => {
                verifyFormGroup($(item));
            });
        });

        $("#contact-send").on("click", () => {
            var url = "mailer.php";

            if(!verifyForm()) {
                return false;
            }

            $.ajax({
                type: "POST",
                url: url,
                data: {subject: $("#contact-subject").val(),
                       email: $("#contact-email").val(),
                       text: $("#contact-text").val(),
                       name: $("#contact-name").val(),
                       project: ($('#contact-isAttached').is(':checked')) ? project.toJSON() : "",
                       version: Main.getVersion()},
                success: function(data)
                {
                    if(data == "true") {
                        showSuccess();
                    } else {
                        showError();
                    }
                },
                error: function(data)
                {
                    showError();
                }
            });

            return false; // avoid to execute the actual submit of the form.
        });
    }

    function verifyFormGroup(element) {
        var control = element.find(".form-control");
        var result = true;

        var test = control.attr('id')

        if(control.attr('id') == "contact-email") {
            result = validateEmail(control.val());
        } else {
            result = (control.val() == "") ? false : true;
        }

        if(result) {
            element.removeClass("has-error");
        } else {
            element.removeClass("has-error").addClass("has-error");
        }

        return result;
    }

    function verifyForm() {
        var result = true;

        $("#contact-form > .form-group").each( (i, item) => {
            var test = $(item).attr('class');
            result = (verifyFormGroup($(item))) ? result : false;
        });

        return result;
    }

    function validateEmail(email) {
        var re = /\S+@\S+/;
        return re.test(email);
    }

    function showSuccess() {
        $("#contactModal").modal("hide");
        Main.showNotification("Thank you!", 2000);
    }

    function showError() {
        $("#contactModal").modal("hide");
        Main.showNotification("An error occurred, please try again", 2000);
    }
}


text:
require 'httparty'
require 'ipaddress'

module Apility
  module GeoIp
    def geolocate_ip(ipaddress=nil)
      base_url = 'https://api.apility.net/ip/'
      if ipaddress
          return "IP Address doesn't seem to be valid." if !(IPAddress.valid? ipaddress)
          response = HTTParty.get(base_url + ipaddress)
          response.success? ? response.parsed_response : "Sorry No data was found."
        else
          response = HTTParty.get(base_url)
          response.success? ? response.parsed_response : "Sorry No data was found."
      end
    end
  end
end


text:
#include "stc311x_gasgauge.h"
#include <stdio.h>
#include "stc311x_BatteryInfo.h"

static void GasGauge_DefaultInit(GasGauge_DataTypeDef * GG_struct);
static int GasGaugeTimerFinished(void);
static void Delay_ms(unsigned int value);

#define TIMER_LIMIT 0x5000 //arbitrary value to modify, and to wait 5s in normal use case
#define SYSTEM_TIMER_AVAILABLE

int main(void)
{
	GasGauge_DataTypeDef STC3117_GG_struct;
	int Voltage;
	int Soc;
	int Current;
	int status;
	int CounterValue;
	int i;
	int BatteryMonitoringEnabled = 1; //true

	//Optional: HardwareShutDown set to 1 when the user power down the hardware, and no need to monitor the battery.
	//But not the recommanded case, as it is better to have the gas gauge always running for better accuracy, even if the rest of the system is powered down
	volatile char HardwareShutDown = 0;

GasGauge_Restart:

	printf("STC3117 fuel gauge driver init ...\n");

	//----------------------------------------------------------------------
	//Check I2C is working and Fuel gauge device connected
	status = STC31xx_CheckI2cDeviceId();
	if (status != 0) //error
	{
		if(status == -1)
		{
			printf("STC3117: I2C error\n");
#ifdef DEBUG
			//wait to simulate the whole application restart
			while( GasGaugeTimerFinished() != 1);
			goto GasGauge_Restart;
#endif
		}
		else if(status == -2)
			printf("STC3117: Wrong device detected\n");
		else
			printf("STC3117: Unknown Hardware error\n");

		return -1; //return on error
	}

	//----------------------------------------------------------------------
	// Check Gasgauge is powered up & ready,
	// and wait first battery measurement (V, I) is done (i.e. wait CounterValue is 3 or more)

#ifdef SYSTEM_TIMER_AVAILABLE //wait implementation with timeout

	for(i=0; i<20; i++)  //check for 20*100ms = 2s
	{
		CounterValue = STC31xx_GetRunningCounter();
		if(CounterValue >= 3) //ok, device ready
		{
			break; //exit loop
		}
		else if(CounterValue < 0) //communication Error
		{
			printf("STC3117: Error at power up.\n");
			goto GasGauge_Restart;
		}
		else
		{
			//wait for battery measurement
			Delay_ms(100);
		}
	}

	if(CounterValue < 3) //timeout, the devise has not started
	{
		printf("STC3117 timeout: Error at power up.\n");
		goto GasGauge_Restart;
	}

#else //simple implementation but without timeout checked (can be stucked)

	CounterValue = 0;
	while(CounterValue < 3) //wait till device ready
	{
		CounterValue = STC31xx_GetRunningCounter();

		if(CounterValue < 0) //communication Error
		{
			printf("STC3117: Error at power up.\n");
			goto GasGauge_Restart;
		}
	}
#endif

	//----------------------------------------------------------------------
	//Call STC3117 driver init&start function

	//Config init
	GasGauge_DefaultInit(&STC3117_GG_struct);

	//Call STC311x driver START initialization function
	status = GasGauge_Start(&STC3117_GG_struct);

	if(status!=0 && status!=-2)
	{
		printf("Error in GasGauge_Start\n");
		return -1; //return on error
	}

	while(BatteryMonitoringEnabled) //main infinite loop
	{
		if(HardwareShutDown == 1) //var modified from IRQ routine
		{
			HardwareShutDown = 0; //clear

			status = GasGauge_Stop();
			if(status != 0) printf("Error in GasGauge_Stop\n");

			BatteryMonitoringEnabled = 0; //end of monitoring
		}
		else //normal case
		{
			if(GasGaugeTimerFinished() == 1) //Process task every 5s (or every 1s to 30s)
			{
				//Call task function
				status = GasGauge_Task(&STC3117_GG_struct);  /* process gas gauge algorithm, returns results */

				if (status > 0) //OK, new data available
				{
					/* results available */
					Soc = STC3117_GG_struct.SOC;
					Voltage = STC3117_GG_struct.Voltage;
					Current = STC3117_GG_struct.Current;

					printf("Vbat: %i mV, I=%i mA SoC=%i, C=%i \r\n",
						STC3117_GG_struct.Voltage,
						STC3117_GG_struct.Current,
						STC3117_GG_struct.SOC,
						STC3117_GG_struct.ChargeValue);
				}
				else if(status == 0) //only previous SOC, OCV and voltage are valid
				{
					printf("Previous_SoC=%i, OCV=%i \r\n",
						STC3117_GG_struct.SOC,
						STC3117_GG_struct.OCV);
				}
				else if(status == -1) //error occurred
				{
					/* results available */
					//Soc = (STC3117_GG_struct.SOC+5)/10;
					//Voltage = STC3117_GG_struct.Voltage;
				}
			}
			else
			{
				//Do other Tasks here ...

				//printf("Waiting next battery measurement...\r\n");
			}
		}
	}

	return 0;
}

static void GasGauge_DefaultInit(GasGauge_DataTypeDef * GG_struct)
{
	int Rint;

	//structure initialisation

	GG_struct->Cnom = BATT_CAPACITY;        /* nominal Battery capacity in mAh */  //Warning: Battery dependant. Put the corresponding used value.

	GG_struct->Vmode = MONITORING_MODE;       /* 1=Voltage mode, 0=mixed mode */

	Rint = BATT_RINT;
	if (Rint == 0)  Rint = 200; //force default

	GG_struct->VM_cnf = (int) ((Rint * BATT_CAPACITY) / 977.78);       /* nominal VM cnf */

	if (MONITORING_MODE == MIXED_MODE)
	{
		GG_struct->CC_cnf = (int)((RSENSE * BATT_CAPACITY) / 49.556);     /* nominal CC_cnf, for CC mode only */
	}

	GG_struct->SoctabValue[0] = 0;        /* SOC curve adjustment = 0%*/
	GG_struct->SoctabValue[1] = 3 * 2;    /* SOC curve adjustment = 3%*/
	GG_struct->SoctabValue[2] = 6 * 2;    /* SOC curve adjustment = 6%*/
	GG_struct->SoctabValue[3] = 10 * 2;    /* SOC curve adjustment = 10%*/
	GG_struct->SoctabValue[4] = 15 * 2;    /* SOC curve adjustment = 15%*/
	GG_struct->SoctabValue[5] = 20 * 2;    /* SOC curve adjustment = 20%*/
	GG_struct->SoctabValue[6] = 25 * 2;    /* SOC curve adjustment = 25%*/
	GG_struct->SoctabValue[7] = 30 * 2;    /* SOC curve adjustment = 30%*/
	GG_struct->SoctabValue[8] = 40 * 2;    /* SOC curve adjustment = 40%*/
	GG_struct->SoctabValue[9] = 50 * 2;    /* SOC curve adjustment = 50%*/
	GG_struct->SoctabValue[10] = 60 * 2;    /* SOC curve adjustment = 60%*/
	GG_struct->SoctabValue[11] = 65 * 2;    /* SOC curve adjustment = 65%*/
	GG_struct->SoctabValue[12] = 70 * 2;    /* SOC curve adjustment = 70%*/
	GG_struct->SoctabValue[13] = 80 * 2;    /* SOC curve adjustment = 80%*/
	GG_struct->SoctabValue[14] = 90 * 2;    /* SOC curve adjustment = 90%*/
	GG_struct->SoctabValue[15] = 100 * 2;    /* SOC curve adjustment = 100%*/

#ifdef	DEFAULT_BATTERY_4V20_MAX      //Default OCV curve for a 4.20V max battery
	GG_struct->OcvValue[0] = 0x1770;    /* OCV curve value at 0%*/
	GG_struct->OcvValue[1] = 0x1926;    /* OCV curve value at 3%*/
	GG_struct->OcvValue[2] = 0x19B2;    /* OCV curve value at 6%*/
	GG_struct->OcvValue[3] = 0x19FB;    /* OCV curve value at 10%*/
	GG_struct->OcvValue[4] = 0x1A3E;    /* OCV curve value at 15%*/
	GG_struct->OcvValue[5] = 0x1A6D;    /* OCV curve value at 20%*/
	GG_struct->OcvValue[6] = 0x1A9D;    /* OCV curve value at 25%*/
	GG_struct->OcvValue[7] = 0x1AB6;    /* OCV curve value at 30%*/
	GG_struct->OcvValue[8] = 0x1AD5;    /* OCV curve value at 40%*/
	GG_struct->OcvValue[9] = 0x1B01;    /* OCV curve value at 50%*/
	GG_struct->OcvValue[10] = 0x1B70;    /* OCV curve value at 60%*/
	GG_struct->OcvValue[11] = 0x1BB1;    /* OCV curve value at 65%*/
	GG_struct->OcvValue[12] = 0x1BE8;    /* OCV curve value at 70%*/
	GG_struct->OcvValue[13] = 0x1C58;    /* OCV curve value at 80%*/
	GG_struct->OcvValue[14] = 0x1CF3;    /* OCV curve value at 90%*/
	GG_struct->OcvValue[15] = 0x1DA9;    /* OCV curve value at 100%*/
#endif

#ifdef	DEFAULT_BATTERY_4V35_MAX      //Default OCV curve for a 4.35V max battery
	GG_struct->OcvValue[0] = 0x1770;    /* OCV curve value at 0%*/
	GG_struct->OcvValue[1] = 0x195D;    /* OCV curve value at 3%*/
	GG_struct->OcvValue[2] = 0x19EE;    /* OCV curve value at 6%*/
	GG_struct->OcvValue[3] = 0x1A1A;    /* OCV curve value at 10%*/
	GG_struct->OcvValue[4] = 0x1A59;    /* OCV curve value at 15%*/
	GG_struct->OcvValue[5] = 0x1A95;    /* OCV curve value at 20%*/
	GG_struct->OcvValue[6] = 0x1AB6;    /* OCV curve value at 25%*/
	GG_struct->OcvValue[7] = 0x1AC7;    /* OCV curve value at 30%*/
	GG_struct->OcvValue[8] = 0x1AEB;    /* OCV curve value at 40%*/
	GG_struct->OcvValue[9] = 0x1B2B;    /* OCV curve value at 50%*/
	GG_struct->OcvValue[10] = 0x1BCC;    /* OCV curve value at 60%*/
	GG_struct->OcvValue[11] = 0x1C13;    /* OCV curve value at 65%*/
	GG_struct->OcvValue[12] = 0x1C57;    /* OCV curve value at 70%*/
	GG_struct->OcvValue[13] = 0x1D09;    /* OCV curve value at 80%*/
	GG_struct->OcvValue[14] = 0x1DCF;    /* OCV curve value at 90%*/
	GG_struct->OcvValue[15] = 0x1EA2;    /* OCV curve value at 100%*/
#endif

#ifdef	CUSTOM_BATTERY_OCV   //fill custom battery data
	GG_struct->OcvValue[0] = ...;
	GG_struct->OcvValue[1] = ...;
	//...
	//...
#endif

	GG_struct->CapDerating[6]=0;   /* capacity derating in 0.1%, for temp = -20 °C */
	GG_struct->CapDerating[5]=0;   /* capacity derating in 0.1%, for temp = -10 °C */
	GG_struct->CapDerating[4]=0;   /* capacity derating in 0.1%, for temp = 0   °C */
	GG_struct->CapDerating[3]=0;   /* capacity derating in 0.1%, for temp = 10  °C */
	GG_struct->CapDerating[2]=0;   /* capacity derating in 0.1%, for temp = 25  °C */
	GG_struct->CapDerating[1]=0;   /* capacity derating in 0.1%, for temp = 40  °C */
	GG_struct->CapDerating[0]=0;   /* capacity derating in 0.1%, for temp = 60  °C */

	GG_struct->Alm_SOC = 10;     /* SOC alm level % */
	GG_struct->Alm_Vbat = 3600;    /* Vbat alm level mV */

	GG_struct->Rsense = RSENSE;      /* sense resistor mOhms */   //Warning: Hardware dependant. Put the corresponding used value
	GG_struct->RelaxCurrent = GG_struct->Cnom/20;  /* current for relaxation (< C/20) mA */

	GG_struct->ForceExternalTemperature = 0; //0: do not force Temperature but Gas gauge measures it

}

static int GasGaugeTimerFinished(void)
{
	static unsigned int i = 1;

	i--;
	if( i == 0)
	{
		i = TIMER_LIMIT;
		return 1;
	}
	else
	{
		return 0;
	}
}

#ifdef SYSTEM_TIMER_AVAILABLE

static void Delay_ms(unsigned int value)
{
	//quick and dirty delay function implementation. Use a real timer instead.

	unsigned int i,j;
	volatile int dummy = 0;

	for(i=0; i<value; i++)
	{
		for(j=0; j<2000; j++) //pseudo 1ms delay
		{
			// waste function, volatile makes sure it is not being optimized out by compiler
			dummy++;
		}
	}
}

#endif


text:
using LinFx.Extensions.Auditing;
using LinFx.Extensions.Data;
using LinFx.Extensions.EntityFrameworkCore.Uow;
using LinFx.Extensions.EventBus;
using LinFx.Extensions.Modularity;
using LinFx.Extensions.MultiTenancy;
using LinFx.Extensions.Threading;
using LinFx.Extensions.Uow;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace LinFx.Extensions.EntityFrameworkCore;

[DependsOn(
    typeof(AuditingModule),
    typeof(DataModule),
    typeof(EventBusModule),
    //typeof(AbpGuidsModule),
    typeof(MultiTenancyModule),
    typeof(ThreadingModule),
    //typeof(AbpTimingModule),
    typeof(UnitOfWorkModule)
    //typeof(AbpObjectMappingModule),
    //typeof(AbpExceptionHandlingModule),
    //typeof(AbpSpecificationsModule)
)]
public class EntityFrameworkCoreModule : Module
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        // 调用 DbContextOptions 的预配置方法,为了解决下面的问题。
        // https://stackoverflow.com/questions/55369146/eager-loading-include-with-using-uselazyloadingproxies
        Configure<EfDbContextOptions>(options =>
        {
            options.PreConfigure(dbContextConfigurationContext =>
            {
                dbContextConfigurationContext.DbContextOptions.ConfigureWarnings(warnings =>
                {
                    warnings.Ignore(CoreEventId.LazyLoadOnDisposedContextWarning);
                });
            });
        });

        // 注册 IDbContextProvider 组件。
        context.Services.TryAddTransient(typeof(IDbContextProvider<>), typeof(UnitOfWorkDbContextProvider<>));
    }
}


text:
This script produces the sample csv dataset used in the Alba Tutorial.

The raw data is obtained at the following url:
http://web.stanford.edu/class/cs341/downloads.html

It's processed in R in order to obtain a CSV with the following fields:

id, isin, author, title, publisher, year, price

PLEASE KEEP IN MIND THAT THE PRICE IS CALCULATED AS A RANDOM VALUE.


text:
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace CleanProject
{
    internal static class NativeMethods
    {
        ///
        ///     Retrieves a handle to the top-level window whose class name and window name match the specified strings. This
        ///     function does not search child windows. This function does not perform a case-sensitive search.
        ///     <para>
        ///         PInvode map to the
        ///
        ///             FindWindow
        ///
        ///         function
        ///     </para>
        ///
        /// <param name="sClassName">
        ///     <para>
        ///         The class name or a class atom created by a previous call to the
        ///
        ///             RegisterClass
        ///
        ///         or
        ///
        ///             RegisterClassEx
        ///
        ///         function. The atom must be in the low-order word of lpClassName; the high-order word must be zero.
        ///     </para>
        ///     <para>
        ///         If lpClassName points to a string, it specifies the window class name. The class name can be any name
        ///         registered with RegisterClass or RegisterClassEx, or any of the predefined control-class names.
        ///     </para>
        ///     <para>If lpClassName is NULL, it finds any window whose title matches the lpWindowName parameter.</para>
        /// </param>
        /// <param name="sAppName">
        ///     The window name (the window's title). If this parameter is NULL, all window names match.
        /// </param>
        /// <returns>
        ///     <para>
        ///         If the function succeeds, the return value is a handle to the window that has the specified class name and
        ///         window name.
        ///     </para>
        ///     <para>
        ///         If the function fails, the return value is NULL. To get extended error information, call
        ///
        ///             GetLastError
        ///
        ///         .
        ///     </para>
        /// </returns>
        /// <remarks>
        ///     If the lpWindowName parameter is not NULL, FindWindow calls the
        ///
        ///         GetWindowText
        ///
        ///     function to retrieve the window name for comparison.
        ///     <para>For a description of a potential problem that can arise, see the Remarks for GetWindowText.</para>
        /// </remarks>
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(string sClassName, string sAppName);

        ///
        ///     Converts the specified path to its long form.
        ///     <para>
        ///         PInvode map to the
        ///
        ///             GetLongPathName
        ///
        ///         function
        ///     </para>
        ///
        /// <param name="path">
        ///     The path to be converted.
        /// </param>
        /// <param name="pszPath">
        ///     A pointer to the buffer to receive the long path.
        /// </param>
        /// <param name="cchPath">
        ///     The size of the buffer lpszLongPath points to, in TCHARs.
        /// </param>
        /// <returns>
        ///     If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpszLongPath, not
        ///     including the terminating null character.
        ///     <para>
        ///         If the lpBuffer buffer is too small to contain the path, the return value is the size, in TCHARs, of the
        ///         buffer that is required to hold the path and the terminating null character.
        ///     </para>
        /// </returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        public static extern int GetLongPathName(string path, StringBuilder pszPath, int cchPath);

        /// Shows a Window
        /// <remarks>
        ///     <para>
        ///         To perform certain special effects when showing or hiding a
        ///         window, use AnimateWindow.
        ///     </para>
        ///     <para>
        ///         The first time an application calls ShowWindow, it should use
        ///         the WinMain function's nCmdShow parameter as its nCmdShow parameter.
        ///         Subsequent calls to ShowWindow must use one of the values in the
        ///         given list, instead of the one specified by the WinMain function's
        ///         nCmdShow parameter.
        ///     </para>
        ///     <para>
        ///         As noted in the discussion of the nCmdShow parameter, the
        ///         nCmdShow value is ignored in the first call to ShowWindow if the
        ///         program that launched the application specifies startup information
        ///         in the structure. In this case, ShowWindow uses the information
        ///         specified in the STARTUPINFO structure to show the window. On
        ///         subsequent calls, the application must call ShowWindow with nCmdShow
        ///         set to SW_SHOWDEFAULT to use the startup information provided by the
        ///         program that launched the application. This behavior is designed for
        ///         the following situations:
        ///     </para>
        ///     <list type="">
        ///         <item>
        ///             Applications create their main window by calling CreateWindow
        ///             with the WS_VISIBLE flag set.
        ///         </item>
        ///         <item>
        ///             Applications create their main window by calling CreateWindow
        ///             with the WS_VISIBLE flag cleared, and later call ShowWindow with the
        ///             SW_SHOW flag set to make it visible.
        ///         </item>
        ///     </list>
        /// </remarks>
        /// <param name="hWnd">Handle to the window.</param>
        /// <param name="nCmdShow">
        ///     Specifies how the window is to be shown.
        ///     This parameter is ignored the first time an application calls
        ///     ShowWindow, if the program that launched the application provides a
        ///     STARTUPINFO structure. Otherwise, the first time ShowWindow is called,
        ///     the value should be the value obtained by the WinMain function in its
        ///     nCmdShow parameter. In subsequent calls, this parameter can be one of
        ///     the WindowShowStyle members.
        /// </param>
        /// <returns>
        ///     If the window was previously visible, the return value is nonzero.
        ///     If the window was previously hidden, the return value is zero.
        /// </returns>
        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    }
}


text:
// Module dependencies.
var util = require('util');
var crypto = require('crypto');

var azureutil = require('../../util/util');
var ServiceClient = require('../core/serviceclient');
var StorageServiceClient = require('../core/storageserviceclient');
var WebResource = require('../../http/webresource');
var Constants = require('../../util/constants');
var HttpConstants = Constants.HttpConstants;
var HeaderConstants = Constants.HeaderConstants;

// Expose 'BatchServiceClient'.
exports = module.exports = BatchServiceClient;

// Module constants.
BatchServiceClient.BATCH_CODE = -1;

/**
* Creates a new BatchServiceClient.
*
* Implements a batch service client able to produce OData batch requests from an array of operations.
* For more information about OData batch processing refer to http://www.odata.org/developers/protocols/batch.
*
* @constructor
*/
function BatchServiceClient(host, storageAccount, storageAccessKey, authenticationProvider) {
  BatchServiceClient.super_.call(this, host, storageAccount, storageAccessKey, authenticationProvider);

  this.operations = null;
}

util.inherits(BatchServiceClient, StorageServiceClient);

/**
* Begins a new batch scope.
*
* @return {undefined}
*/
BatchServiceClient.prototype.beginBatch = function () {
  this.operations = [];
};

/**
* Determines if there is a current batch.
*
* @return {boolean} Boolean value indicating if service is in a batch context or not.
*/
BatchServiceClient.prototype.isInBatch = function () {
  return this.operations !== null;
};

/**
* Terminates the current batch scope by clearing current operations.
*
* @return {undefined}
*/
BatchServiceClient.prototype.rollback = function () {
  this.operations = null;
};

/**
* Returns a boolean value indicating weather there are operations queued up for execution in a batch or not.
*
* @return {Boolean} True if there are operations queued up; false otherwise.
*/
BatchServiceClient.prototype.hasOperations = function () {
  return this.isInBatch() &&
         this.operations.length > 0;
};

/**
* Adds an operation to the batch.
*
* @param {object}  webResource The request parameters.
* @param {object}  outputData  The body for the operation.
* @return {undefined}
*/
BatchServiceClient.prototype.addOperation = function (webResource, outputData) {
  if (azureutil.objectIsNull(outputData)) {
    outputData = '';
  }

  if (webResource.httpVerb !== ServiceClient.HTTP_VERB_GET) {
    webResource.headers[HeaderConstants.CONTENT_ID] = this.operations.length + 1;

    if (webResource.httpVerb !== ServiceClient.HTTP_VERB_DELETE) {
      webResource.headers[HeaderConstants.CONTENT_TYPE] = 'application/atom+xml;type=entry';
    }

    webResource.headers[HeaderConstants.CONTENT_LENGTH] = outputData.length;
  }

  this._setRequestUrl(webResource);
  var operation = {
    webResource: webResource
  };

  operation.content = webResource.httpVerb + ' ' + webResource.requestUrl + ' HTTP/1.1\n';

  for (var header in webResource.headers) {
    operation.content += header + ': ' + webResource.headers[header] + '\n';
  }

  operation.content += '\n';
  operation.content += outputData;

  this.operations.push(operation);
};

/**
* Commits the operations within the batch scope.
*
* @param {object}      [options]                        The request options.
* @param {int}         [options.timeoutIntervalInMs]    The timeout interval, in milliseconds, to use for the request.
* @param {function}    callback                         The response callback function.
* @return {undefined}
*/
BatchServiceClient.prototype.commitBatch = function (optionsOrCallback, callback) {
  var options = null;
  if (typeof optionsOrCallback === 'function' && !callback) {
    callback = optionsOrCallback;
  }
  else {
    options = optionsOrCallback;
  }

  if (!this.operations ||
    this.operations.length <= 0) {
    throw new Error('Nothing to commit');
  }

  var batchBoundary = 'batch_' + crypto.createHash('md5').update("" + (new Date()).getTime()).digest("hex");
  var changesetBoundary = 'changeset_' + crypto.createHash('md5').update("" + (new Date()).getTime()).digest("hex");

  var body = '--' + batchBoundary + '\n';
  body += HeaderConstants.CONTENT_TYPE + ': multipart/mixed; boundary=' + changesetBoundary + '\n\n';

  for (var operation in this.operations) {
    body += '--' + changesetBoundary + '\n';
    body += HeaderConstants.CONTENT_TYPE + ': application/http\n';
    body += HeaderConstants.CONTENT_TRANSFER_ENCODING_HEADER + ': binary\n\n';
    body += this.operations[operation].content + '\n';
  }

  body += '--' + changesetBoundary + '--\n';
  body += '--' + batchBoundary + '--';

  var webResource = WebResource.post('$batch')
    .withOkCode(HttpConstants.HttpResponseCodes.ACCEPTED_CODE)
    .withRawResponse(true);

  webResource.addOptionalHeader(HeaderConstants.CONTENT_TYPE, 'multipart/mixed; boundary=' + batchBoundary);
  webResource.addOptionalHeader(HeaderConstants.DATA_SERVICE_VERSION, '1.0;NetFx');
  webResource.addOptionalHeader(HeaderConstants.MAX_DATA_SERVICE_VERSION, '2.0;NetFx');
  webResource.addOptionalHeader(HeaderConstants.CONTENT_LENGTH, body.length);

  var self = this;

  // Store current operations to process response
  // and clear batch operation to end isInBatch state after commiting
  var requestOperations = this.operations;
  this.operations = null;

  var processResponseCallback = function (responseObject, next) {
    var responseObjects = self.processResponse(responseObject, requestOperations);
    responseObject.operationResponses = responseObjects;

    var finalCallback = function (returnObject) {
      // perform final callback
      callback(returnObject.error, returnObject.operationResponses, returnObject.response);
    };

    next(responseObject, finalCallback);
  };

  this.performRequest(webResource, body, options, processResponseCallback);
};

/**
* Processes a batch response.
*
* @param {object} responseObject The response object for the batch request.
* @return {array} An array with the processed / parsed responses.
*/
BatchServiceClient.prototype.processResponse = function (responseObject, requestOperations) {
  var responses = null;
  if (responseObject && responseObject.response && responseObject.response.body) {
    responses = [];
    var rawResponses = responseObject.response.body.split(Constants.CHANGESET_DELIMITER);

    var validResponse = 0;
    for (var i in rawResponses) {
      // Find HTTP/1.1 CODE line
      var httpLocation = rawResponses[i].indexOf('HTTP/');
      if (httpLocation !== -1) {
        var rawResponse = rawResponses[i].substring(httpLocation);
        // valid response
        var response = this.processOperation(requestOperations[validResponse++].webResource, rawResponse);
        responses.push(response);
      }
    }
  }

  return responses;
};

/**
* Processes a partial response.
*
* @param {WebResource} webResource The web resource for the response.
* @param {string}      rawResponse The raw, unparsed, http response from the server for the batch response.
* @return {object} A response object.
*/
BatchServiceClient.prototype.processOperation = function (webResource, rawResponse) {
  var responseObject = {
    error: null,
    response: { }
  };

  // Retrieve response code
  var firstSpace = rawResponse.indexOf(' ');
  responseObject.response.statusCode = parseInt(rawResponse.substring(firstSpace + 1, rawResponse.indexOf(' ', firstSpace + 2)), 10);
  responseObject.response.isSuccessful = webResource.validResponse(responseObject.response.statusCode);

  // Skip that line
  rawResponse = rawResponse.substring(rawResponse.indexOf('\n'));

  // Split into multiple lines and process them
  var responseLines = rawResponse.split('\r\n');

  // Populate headers
  responseObject.response.headers = { };
  responseObject.response.body = '';

  var isBody = false;
  for (var i in responseLines) {
    var line = responseLines[i];

    if (line === '' && !isBody) {
      isBody = true;
    } else if (isBody) {
      responseObject.response.body += line;
    } else {
      var headerSplit = line.indexOf(':');
      if (headerSplit !== -1) {
        responseObject.response.headers[line.substring(0, headerSplit).trim()] = line.substring(headerSplit + 1).trim();
      }
    }
  }

  this._parseResponse(responseObject.response);
  if (!responseObject.response.isSuccessful) {
    responseObject.error = this._normalizeError(responseObject.response.body);
  }

  return responseObject;
};


text:
package echo

import (
	"fmt"
	"github.com/dlsniper/cortana/plugins"
	"regexp"
)

var (
	canonicalCommand = "echo"
	command          = `(?:E|e)cho(?:\s)?(.*)`
	compiledCmd      = regexp.MustCompile(command)
	aliases          map[string]*regexp.Regexp
)

func isAlias(cmd string) *regexp.Regexp {
	for _, alias := range aliases {
		if alias.MatchString(cmd) {
			return alias
		}
	}

	return nil
}

func canHandle(cmd string) *regexp.Regexp {
	if compiledCmd.MatchString(cmd) {
		return compiledCmd
	}

	return isAlias(cmd)
}

func Initialize(pins plugins.PluginManager) {
	aliases = map[string]*regexp.Regexp{}

	pins.Register(
		canonicalCommand,
		command,
		Echo,
		Help,
		aliases,
	)
}

func Help(cmd string) (string, error) {
	return `Echo command help

Echo is a more advanced command.
Echo will always reply back everything what's after 'echo', making this a good mirror service.

Usage example:
echo Demo
echo Hello World
`, nil
}

func Echo(cmd string) (string, error) {
	regex := canHandle(cmd)
	if regex == nil {
		return "", fmt.Errorf("Can't handle command %s", cmd)
	}

	result := regex.FindStringSubmatch(cmd)

	return result[1], nil
}


text:
package com.github.andr83.parsek.spark.sink

import java.util.UUID

import com.github.andr83.parsek._
import com.github.andr83.parsek.formatter.FieldFormatter
import com.github.andr83.parsek.serde.{SerDe, Serializer, StringSerializer}
import com.github.andr83.parsek.spark.util.RDDUtils.{DefaultPartitioner, FieldsPartitioner}
import com.github.andr83.parsek.spark.util.{HadoopUtils, RDDUtils}
import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import org.apache.hadoop.io.NullWritable
import org.apache.hadoop.io.compress.CompressionCodec
import org.apache.hadoop.mapred.lib.MultipleTextOutputFormat
import org.apache.spark.rdd.RDD

import scala.collection.JavaConversions._

/**
  * Save RDD as a compressed text file
  *
  * @param path       path to directory where to save
  * @param codec      compression codec class
  * @param serializer factory function which return Serializer instance
  * @param partitions
  * @param numPartitions
  * @param fileNamePattern
  * @author andr83
  */
case class TextFileSink(
  path: String,
  codec: Option[Class[_ <: CompressionCodec]],
  serializer: () => Serializer,
  partitions: Seq[FieldFormatter] = Seq.empty[FieldFormatter],
  numPartitions: Option[Int] = None,
  fileNamePattern: Option[String] = None
) extends Sink {

  def this(config: Config) = this(
    path = config.getString("path"),
    codec = config.as[Option[String]]("codec") map HadoopUtils.getCodec,
    serializer = config.as[Option[Config]]("serializer")
      .map(serializerConf => () => SerDe(serializerConf))
      .getOrElse(StringSerializer.factory),
    partitions = if (config.hasPath("partitions"))
      FieldFormatter(config.getList("partitions"))
    else Seq.empty[FieldFormatter],
    numPartitions = config.as[Option[Int]]("numPartitions"),
    fileNamePattern = config.as[Option[String]]("fileNamePattern")
  )

  override def sink(rdd: RDD[PValue], time: Long): Unit = {
    try {
      if (partitions.nonEmpty || fileNamePattern.nonEmpty) {
        val pattern = fileNamePattern map (pattern => {
          pattern
            .replaceAllLiterally("${randomUUID}", UUID.randomUUID().toString)
            .replaceAllLiterally("${timeInMs}", time.toString)
        })

        val partitioner = if (partitions.isEmpty) DefaultPartitioner(pattern)
        else FieldsPartitioner(partitions, pattern)

        RDDUtils
          .serializeAndPartitionBy(rdd, serializer, partitioner, numPartitions)
          .saveAsHadoopFile(
            path,
            classOf[String],
            classOf[String],
            classOf[TextFileSink.RDDMultipleTextOutputFormat],
            codec = codec
          )
      } else {
        val serializedRdd = RDDUtils.serialize(rdd, serializer)
        codec match {
          case Some(c) => serializedRdd.saveAsTextFile(path, c)
          case None => serializedRdd.saveAsTextFile(path)
        }
      }
    } catch {
      case e: Exception =>
        logger.error(e.toString, e)
        throw e
    }
  }
}

object TextFileSink {

  class RDDMultipleTextOutputFormat extends MultipleTextOutputFormat[Any, Any] {

    override def generateActualKey(key: Any, value: Any): Any =
      NullWritable.get()

    override def generateFileNameForKeyValue(key: Any, value: Any, name: String): String = {
      key.asInstanceOf[String]
    }
  }

}


text:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'mvl-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {

  query: string = '';

  constructor(private router: Router) { }

  ngOnInit() {
  }

  onSearch(query) {
    this.router.navigate([query ? {q: query} : {} ]);
  }
}


text:
'''
Create ssh executor system
'''
from __future__ import absolute_import
# Import python libs
import os
import tarfile
import tempfile
import json
import shutil
from contextlib import closing

# Import salt libs
import salt.client.ssh.shell
import salt.client.ssh
import salt.utils
import salt.utils.thin
import salt.utils.url
import salt.roster
import salt.state
import salt.loader
import salt.minion

class SSHState(salt.state.State):
    '''
    Create a State object which wraps the SSH functions for state operations
    '''
    def __init__(self, opts, pillar=None, wrapper=None):
        self.wrapper = wrapper
        super(SSHState, self).__init__(opts, pillar)

    def load_modules(self, data=None, proxy=None):
        '''
        Load up the modules for remote compilation via ssh
        '''
        self.functions = self.wrapper
        self.utils = salt.loader.utils(self.opts)
        self.serializers = salt.loader.serializers(self.opts)
        locals_ = salt.loader.minion_mods(self.opts, utils=self.utils)
        self.states = salt.loader.states(self.opts, locals_, self.utils, self.serializers)
        self.rend = salt.loader.render(self.opts, self.functions)

    def check_refresh(self, data, ret):
        '''
        Stub out check_refresh
        '''
        return

    def module_refresh(self):
        '''
        Module refresh is not needed, stub it out
        '''
        return

class SSHHighState(salt.state.BaseHighState):
    '''
    Used to compile the highstate on the master
    '''
    stack = []

    def __init__(self, opts, pillar=None, wrapper=None, fsclient=None):
        self.client = fsclient
        salt.state.BaseHighState.__init__(self, opts)
        self.state = SSHState(opts, pillar, wrapper)
        self.matcher = salt.minion.Matcher(self.opts)

    def load_dynamic(self, matches):
        '''
        Stub out load_dynamic
        '''
        return

def lowstate_file_refs(chunks, extras=''):
    '''
    Create a list of file ref objects to reconcile
    '''
    refs = {}
    for chunk in chunks:
        if not isinstance(chunk, dict):
            continue
        saltenv = 'base'
        crefs = []
        for state in chunk:
            if state == '__env__':
                saltenv = chunk[state]
            elif state.startswith('__'):
                continue
            crefs.extend(salt_refs(chunk[state]))
        if crefs:
            if saltenv not in refs:
                refs[saltenv] = []
            refs[saltenv].append(crefs)
    if extras:
        extra_refs = extras.split(',')
        if extra_refs:
            for env in refs:
                for x in extra_refs:
                    refs[env].append([x])
    return refs

def salt_refs(data, ret=None):
    '''
    Pull salt file references out of the states
    '''
    proto = 'salt://'
    if ret is None:
        ret = []
    if isinstance(data, str):
        if data.startswith(proto) and data not in ret:
            ret.append(data)
    if isinstance(data, list):
        for comp in data:
            salt_refs(comp, ret)
    if isinstance(data, dict):
        for comp in data:
            salt_refs(data[comp], ret)
    return ret

def prep_trans_tar(file_client, chunks, file_refs, pillar=None, id_=None):
    '''
    Generate the execution package from the saltenv file refs and a low state
    data structure
    '''
    gendir = tempfile.mkdtemp()
    trans_tar = salt.utils.mkstemp()
    lowfn = os.path.join(gendir, 'lowstate.json')
    pillarfn = os.path.join(gendir, 'pillar.json')
    sync_refs = [
            [salt.utils.url.create('_modules')],
            [salt.utils.url.create('_states')],
            [salt.utils.url.create('_grains')],
            [salt.utils.url.create('_renderers')],
            [salt.utils.url.create('_returners')],
            [salt.utils.url.create('_output')],
            [salt.utils.url.create('_utils')],
            ]
    with salt.utils.fopen(lowfn, 'w+') as fp_:
        fp_.write(json.dumps(chunks))
    if pillar:
        with salt.utils.fopen(pillarfn, 'w+') as fp_:
            fp_.write(json.dumps(pillar))
    cachedir = os.path.join('salt-ssh', id_)
    for saltenv in file_refs:
        file_refs[saltenv].extend(sync_refs)
        env_root = os.path.join(gendir, saltenv)
        if not os.path.isdir(env_root):
            os.makedirs(env_root)
        for ref in file_refs[saltenv]:
            for name in ref:
                short = salt.utils.url.parse(name)[0]
                path = file_client.cache_file(name, saltenv, cachedir=cachedir)
                if path:
                    tgt = os.path.join(env_root, short)
                    tgt_dir = os.path.dirname(tgt)
                    if not os.path.isdir(tgt_dir):
                        os.makedirs(tgt_dir)
                    shutil.copy(path, tgt)
                    continue
                files = file_client.cache_dir(name, saltenv, cachedir=cachedir)
                if files:
                    for filename in files:
                        fn = filename[filename.find(short) + len(short):]
                        if fn.startswith('/'):
                            fn = fn.strip('/')
                        tgt = os.path.join(
                                env_root,
                                short,
                                fn,
                                )
                        tgt_dir = os.path.dirname(tgt)
                        if not os.path.isdir(tgt_dir):
                            os.makedirs(tgt_dir)
                        shutil.copy(filename, tgt)
                    continue
    try:
        # cwd may not exist if it was removed but salt was run from it
        cwd = os.getcwd()
    except OSError:
        cwd = None
    os.chdir(gendir)
    with closing(tarfile.open(trans_tar, 'w:gz')) as tfp:
        for root, dirs, files in os.walk(gendir):
            for name in files:
                full = os.path.join(root, name)
                tfp.add(full[len(gendir):].lstrip(os.sep))
    if cwd:
        os.chdir(cwd)
    shutil.rmtree(gendir)
    return trans_tar


text:
% TWO TRANSITION MODEL OF THE CELL CYCLE

% Script to run a simulation using a population of 100 asynchronous cells
% Use with classdef CellTwoCDK
% Section 1 creates an asynchronous population of 100 cells
% Section 2 runs the test simulation in which parameters may be altered

%-------------------------------------------------------------------------------------%

clear all
clear classes

% 1. INITIATE A TISSUE CONSISTING OF 100 ASYNCHRONOUS CELLS
% We advise using the stated values to produce a well distributed
% population.

% Set the number of steps to be taken during the simulation
Steps = 500;

% Select the model type
G1pDependency = 1; % enter 1 for model with production of CDKs dependent on size, enter 0 for independent.
G2pDependency = 1; % enter 1 for model with production of CDKm depednent on size, enter 0 for independent.
G1tDependency = 0; % enter 1 for model with Threshold_G1S dependent on size
G2tDependency = 0; % enter 1 for model with Threshold_G2M dependent on size

% Set parameter values for simulation
meanRGR = 0.018;
sdRGR = 0.0018;
pCDKs = 2.8;
pCDKm = 4;
ThresholdG1S = 1600;
ThresholdG2M = 2200;
meanDiv = 2;
sdDiv = 0.2;
Size = 20;

% Select RGR for first cell from a distribution based on the mean and sd
% given above
RGR = normrnd(meanRGR, sdRGR)

% Prepare two arrays of RGR values from the distribution to be used to
% determine the RGR of new cells
RGRsDaughter1 = [zeros, 10000];
for i = 1:10000
    RGRsDaughter1(i) = normrnd(meanRGR, sdRGR);
end

RGRsDaughter2 = [zeros, 10000];
for j = 1:10000
    RGRsDaughter2(j) = normrnd(meanRGR, sdRGR);
end

% Prepare an array of division ratios based on the input values
Ratios = [zeros, 10000];
for k = 1:10000
    Ratios(k) = normrnd(meanDiv, sdDiv);
end

% Initialize an array of empty CellTwoCDK objects
tissue = CellTwoCDK.empty(0, 10000);
% Fill properties of first cell
tissue(1) =  CellTwoCDK(RGR,pCDKs,pCDKm, Size, 0, 0, ThresholdG1S, ThresholdG2M,0,0,0,0,0,0);

% Initialize a cell array to record cell size in
SizeRecord = zeros(400, 5000);

% Initialize a cell array to record cell cycle and phase length
LengthRecord = zeros(10000, 3);

% Prepare the axes
figure();
hold on;

% Set time to 0
t = 0;

% Start simulation
tissue = GrowthIteration(tissue, Steps, t, G1pDependency, G2pDependency, G1tDependency, G2tDependency, SizeRecord, LengthRecord, Ratios, RGRsDaughter1, RGRsDaughter2, pCDKs, pCDKm, ThresholdG1S, ThresholdG2M);
title('Generation of asynchronous population')
xlabel('Time (hr)')
ylabel('Cell Area (um^2)')
hold off;

%--------------------------------------------------------------%

% 2. RUNNING THE TEST SIMULATION

% Set the conditions for the test simulation

% Set the number of steps to be taken during the simulation
Steps = 1000;

% Select the model type
G1pDependency = 1; % enter 1 for model with production of CDKs dependent on size, enter 0 for independent.
G2pDependency = 1; % enter 1 for model with production of CDKm dependent on size, enter 0 for independent.
G1tDependency = 0; % enter 1 for model with S Phase Threshold dependent on size
G2tDependency = 0; % enter 1 for model with M Phase Threshold dependent on size

% Set parameter values for simulation
meanRGR = 0.018;
sdRGR = 0.0018;
pCDKs = 2.8;
pCDKm = 4;
ThresholdG1S = 1600;
ThresholdG2M = 2200;
meanDiv = 2;
sdDiv = 0.2;
Size = 20;

% Select RGR for first cell from a distribution based on the mean and sd
% given above
RGR = normrnd(meanRGR, sdRGR)

% Prepare two arrays of RGR values from the distribution to be used to
% determine the RGR of new cells
RGRsDaughter1 = [zeros, 10000];
for i = 1:10000
    RGRsDaughter1(i) = normrnd(meanRGR, sdRGR);
end

RGRsDaughter2 = [zeros, 10000];
for j = 1:10000
    RGRsDaughter2(j) = normrnd(meanRGR, sdRGR);
end

% Prepare an array of division ratios based on the input values
Ratios = [zeros, 10000];
for k = 1:10000
    Ratios(k) = normrnd(meanDiv, sdDiv);
end

% Initialize a cell array to record cell size in
SizeRecord = zeros(400, 5000);

% Initialize a cell array to record cell cycle and phase length
LengthRecord = zeros(10000, 3);

% Prepare the axes
figure();
hold on;

% Set time to 0
t = 0;

% Start simulation
tissue = GrowthIteration(tissue, Steps, t, G1pDependency, G2pDependency, G1tDependency, G2tDependency, SizeRecord, LengthRecord, Ratios, RGRsDaughter1, RGRsDaughter2, pCDKs, pCDKm, ThresholdG1S, ThresholdG2M);
title('Model Population Simulation')
xlabel('Time (hr)')
ylabel('Ceall Area (um^2)')
hold off


text:
      Cloud program client
      by DvgCraft
      Wireless modem required

      DATE  07-07-2015
]]--

-- Variables
local version = "1.2.1"
local running = true
local tArgs = {...}
local dir = "/.DvgFiles/data/Cloud"

local username = ""
local pass = ""

local newUsername = ""
local newPass = ""
local userExists = nil
local mside = nil
local serverID = nil
local files = {}

-- Functions
function checkInstall()
  if not fs.exists("/.DvgFiles") then
    error("You have to install DvgFiles first. Download it here: (coming soon)")
  end
  if not fs.exists(dir) then
    fs.makeDir(dir)
    local file = fs.open(dir.."/version", "w")
    file.write(version)
    file.close()
    local file = fs.open(dir.."/serverID", "w")
    print("Server ID:")
    serverID = tonumber(read())
    file.write(serverID)
    file.close()
  end
  if not fs.exists("/.DvgFiles/settings/mside") then
    local file = fs.open("/.DvgFiles/settings/mside", "w")
    print("Modem side:")
    mside = read()
    file.write(mside)
    file.close()
  end
end

function register()
  print("Create username:")
  newUsername = read()
  print("Create password:")
  newPass = read()
  print("Confirm password:")
  if newPass ~= read() then
    error("Passwords do not correspond (#201.31)")
  end

  local newUser = {username = newUsername, pass = newPass}
  rednet.send(serverID, textutils.serialize(newUser), "DVG_CLOUD_NEWUSER_REQUEST")
  id, msg = rednet.receive("DVG_CLOUD_NEWUSER_ANSWER", 5)
  if msg == nil then
    error("Could not connect to server (#201.1)")
  elseif id == serverID then
    if msg == "SUCCESS" then
      print("User created. Login:")
    elseif msg == "FAILURE" then
      error("Username already exists. choose another (#201.32)")
    end
  end
end
function login(datagiven)
  if datagiven then
    username = tArgs[1]
    pass = tArgs[2]
  else
    print("Username:")
    username = read()
    print("Password:")
    pass = read()
  end
  local userInfo = {username = username, pass = pass}

  rednet.send(serverID, textutils.serialize(userInfo), "DVG_CLOUD_CHECKUSER_REQUEST")
  local id, msg = rednet.receive("DVG_CLOUD_CHECKUSER_ANSWER", 5)
  if msg == nil then
    error("Could not connect to server (#201.1)")
  end
  if msg == "SUCCESS" then
    userExists = true
  elseif msg == "FAILURE" then
    error("Username or password incorrect (#201.2)")
  else
    error("Something terrible happened! (#001)")
  end
end

function getFiles()
  rednet.send(serverID, username, "DVG_CLOUD_FILES_REQUEST")
  local id, msg = rednet.receive("DVG_CLOUD_FILES_ANSWER", 5)
  if msg == nil then
    msg  = {"Could not connect to server."}
    return msg
  elseif id == serverID then
    return textutils.unserialize(msg)
  end
end
function getFile(path, edit)
  local sendTab = {username = username, path = path}
  sendTab = textutils.serialize(sendTab)
  rednet.send(serverID, sendTab, "DVG_CLOUD_FILE_GET_REQUEST")
  print("Sent file request. waiting for answer...")
  local id, msg = rednet.receive("DVG_CLOUD_FILE_GET_ANSWER", 5)
  if msg == nil then
    print("Could not connect to server.")
    return false
  elseif msg == "FAILURE" then
    if edit then
      print("File name cannot be '#'")
    else
      print("No such program")
    end
    return false
  elseif id == serverID then
    local path = "/.DvgFiles/TEMP/Cloud_"..path

    msg = textutils.unserialize(msg)
    local file = fs.open(path, "w")
    for i = 1, #msg do
      file.writeLine(msg[i])
    end
    file.close()
    fs.delete(path)
    return true
  end
end
function edit(path)
  local returnTab = {username, path}
  local path = "/.DvgFiles/TEMP/Cloud_"..path
  shell.run("edit "..path)

  local file = fs.open(path, "r")
  line = file.readLine()
  while line do
    table.insert(returnTab, line)
    line = file.readLine()
  end
  file.close()
  fs.delete(path)

  rednet.send(serverID, textutils.serialize(returnTab), "DVG_CLOUD_FILE_POST_REQUEST")
end
function delete(path)
  local sendTab = {username, path}
  rednet.send(serverID, textutils.serialize(sendTab), "DVG_CLOUD_FILE_DELETE_REQUEST")
  local id, msg = rednet.receive("DVG_CLOUD_FILE_DELETE_ANSWER", 5)
  if msg == nil then
    print("Could not connect to server (#201.1)")
  elseif id == serverID then
    if msg == "SUCCESS" then
      print("File deleted.")
    elseif msg == "FAILURE" then
      print("File does not exist.")
    end
  end
end

-- Run
checkInstall()
if mside == nil then
  local file = fs.open("/.DvgFiles/settings/mside", "r")
  mside = file.readLine()
  file.close()
end
rednet.open(mside)

if serverID == nil then
  local file = fs.open("/.DvgFiles/data/Cloud/serverID", "r")
  serverID = tonumber(file.readLine())
  file.close()
end

if #tArgs == 2 then
  login(true)
else
  print("type L to login and R to register")
  input = read()
  if input:lower() == "r" then
    register()
  elseif input:lower() ~= "l" then
    running = false
  end
  login(false)
end

if not userExists then
  error("This should never happen... (#002)")
end

while running do
  write("Cloud> ")
  input = read()
  if #input == 0 then

  elseif input:sub(1,2) == "ls" then
    files = getFiles()
    textutils.pagedTabulate(files)
  elseif input:sub(1,4) == "edit" then
    local answer = getFile( input:sub(6), true )
    if answer then
      edit( input:sub(6) )
    end
  elseif input:sub(1,6) == "delete" or input:sub(1,6) == "remove" or input:sub(1,2) == "rm" then
    if input:sub(1,6) == "delete" or input:sub(1,6) == "remove" then
      sendTab = {username = username, path = input:sub(8)}
    elseif input:sub(1,2) == "rm" then
      sendTab = {username = username, path = input:sub(4)}
    end
    rednet.send(serverID, textutils.serialize(sendTab), "DVG_CLOUD_FILE_DELETE_REQUEST")
    local id, msg = rednet.receive("DVG_CLOUD_FILE_DELETE_ANSWER", 5)
    if msg == nil then
      print("Could not connect to server.")
    elseif msg == "FAILURE" then
      print("No matching files")
    end
  elseif input:lower() == "exit" then
    running = false
  else
    answer = getFile(input, false)
    if answer then
      shell.run("/.DvgFiles/TEMP/Cloud_"..input)
    end
  end
end


text:
/**
 * @author Hana Lee
 * @since 2016-05-04 15:04
 */

(function () {
  'use strict';

  angular
    .module('translate-chat')
    .factory('SocketService', SocketService);

  SocketService.$inject = ['socketFactory', 'CONFIG', 'STORAGE_KEYS'];

  function SocketService(socketFactory, CONFIG, STORAGE_KEYS) {
    var server = CONFIG.serverUrl + ':' + CONFIG.serverPort;
    var options = {
      reconnect : true,
      'reconnection delay' : 500,
      'max reconnection attempts' : 10
    };
    var user = localStorage.getItem(STORAGE_KEYS.USER);
    console.log('socket service : ', user);
    if (user) {
      options.query = 'user_id=' + JSON.parse(user).user_id;
    }
    var socket = io.connect(server, options);

    return socketFactory({
      ioSocket : socket
    });
  }
})();


text:
    Title:
    <input type="text" [(ngModel)]="imageMetadata.title" id="title" name="title">

      <template ngFor let-error [ngForOf]="formErrors['general']">

          If any of the month, day, and year fields are specified, then all three date fields must be specified.

      </template>

    Date Taken:

      <select id="month" name="month" [(ngModel)]="imageMetadata.capturedMonthHtmlValue" (change)="populateDayOptions();">
        <option value="">Month</option>
        <option value="1">January</option>
        <option value="2">February</option>
        <option value="3">March</option>
        <option value="4">April</option>
        <option value="5">May</option>
        <option value="6">June</option>
        <option value="7">July</option>
        <option value="8">August</option>
        <option value="9">September</option>
        <option value="10">October</option>
        <option value="11">November</option>
        <option value="12">December</option>
      </select>
      <select id="day" name="day" [(ngModel)]="imageMetadata.capturedDayHtmlValue" #dayOptionsContainer></select>
      <select id="year" name="year" [(ngModel)]="imageMetadata.capturedYearHtmlValue" #yearOptionsContainer (change)="populateDayOptions();"></select>

    Location:

      <input type="text" id="location" name="location" [(ngModel)]="imageMetadata.location">

    Notes:

      <textarea id="notes" name="notes" [(ngModel)]="imageMetadata.notes" cols="50" rows="4"></textarea>


text:
<!DOCTYPE html>

    <title>Subscribed</title>
    <?php include '../inner-head.php' ?>

    <?php include '../inner-header.php' ?>

    <?php
    $email = $_POST["email"];
    $servername ="localhost";
    $username = "blueteam";
    $password = "fr1end";
    $dbname = "blueteam";
    $table = "subscribers";

    //Connect to mySQL server
    $conn = new mysqli($servername, $username, $password, $dbname);

    //If connection failed, die.
    if($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sqlInsert = "INSERT INTO subscribers (subscriberID, subscriberEmail) VALUES(NULL, '".$email."');";
    $result = $conn->query($sqlInsert);
    ?>

You are now subscribed. Check your email for a confirmation and you will receive the next newsletter we send out.

    <?php include '../inner-footer.php' ?>


text:
var http = require('http');

var mongoose = require('mongoose');
mongoose.connect(process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/codebar-feedback');

var router = require('./lib/router');
var server = http.createServer();
server.on('request', router.handleRequest);

if (!module.parent) {
  server.listen(process.env.PORT || 8000);
}

module.exports = server;


text:
#include <plugininfo.hpp>

#include <cmdline.hpp>
#include <kdb.hpp>
#include <modules.hpp>
#include <plugin.hpp>

#include <iostream>

using namespace std;
using namespace kdb;
using namespace kdb::tools;

PluginInfoCommand::PluginInfoCommand ()
{
}

int PluginInfoCommand::execute (Cmdline const & cl)
{
	std::string subkey;
	if (cl.arguments.size () < 1 || cl.arguments.size () > 2)
	{
		throw invalid_argument ("Need 1 or 2 argument(s)");
	}

	if (cl.arguments.size () == 2)
	{
		subkey = cl.arguments[1];
	}
	std::string name = cl.arguments[0];

	KeySet conf;
	Key parentKey (std::string ("system:/elektra/modules/") + name, KEY_END);

	if (!cl.load)
	{
		KDB kdb;
		kdb.get (conf, parentKey);
	}

	if (!conf.lookup (parentKey))
	{
		if (!cl.load)
		{
			cerr << "Module does not seem to be loaded." << endl;
			cerr << "Now in fallback code. Will directly load config from plugin." << endl;
		}

		Modules modules;
		KeySet ks = cl.getPluginsConfig ();
		PluginPtr plugin;
		if (ks.size () == 0)
		{
			plugin = modules.load (name);
		}
		else
		{
			plugin = modules.load (name, ks);
		}

		// fix name for virtual plugins
		if (name != plugin->name ())
		{
			std::cerr << "Will use name " << plugin->name () << " for virtual plugin named " << name << std::endl;
			name = plugin->name ();
		}
		conf.append (plugin->getInfo ());
	}

	Key root (std::string ("system:/elektra/modules/") + name + "/exports", KEY_END);

	if (!subkey.empty ())
	{
		root.setName (std::string ("system:/elektra/modules/") + name + "/infos/" + subkey);
		Key k = conf.lookup (root);
		if (k)
		{
			cout << k.getString () << std::endl;
			return 0;
		}
		else
		{
			cerr << "clause not found" << std::endl;
			return 1;
		}
	}

	root.setName (std::string ("system:/elektra/modules/") + name + "/exports");

	ssize_t it = conf.search (root) + 1;
	if (it > 0)
	{
		cout << "Exported symbols: ";

		for (; it < conf.size (); ++it)
		{
			if (!conf.at (it).isBelow (root)) break;
			cout << conf.at (it).getBaseName () << " ";
		}
		cout << endl;
	}
	else
		cout << "no exported symbols found" << endl;

	root.setName (std::string ("system:/elektra/modules/") + name + "/infos");
	it = conf.search (root) + 1;

	if (it > 0)
	{
		for (; it < conf.size (); ++it)
		{
			if (!conf.at (it).isBelow (root)) break;
			cout << getStdColor (ANSI_COLOR::BOLD) << conf.at (it).getBaseName () << ": " << getStdColor (ANSI_COLOR::RESET)
			     << conf.at (it).getString () << endl;
		}
	}
	else
		cout << "no information found" << endl;

	return 0;
}

PluginInfoCommand::~PluginInfoCommand ()
{
}


text:
package ar.com.api.mk;

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

import ar.com.api.mk.impl.ApiConnectionImpl;

/**
 * The Mikrotik API connection. This is the class used to connect to a remote
 * Mikrotik and send commands to it.
 *
 * @author GideonLeGrange
 *
 *
 */
public abstract class ApiConnection implements AutoCloseable {

    /** default TCP port used by Mikrotik API */
    public static final int DEFAULT_PORT = 8728;
    /** default TCP TLS port used by Mikrotik API */
    public static final int DEFAULT_TLS_PORT = 8729;
    /** default connection timeout to use when opening the connection */
    public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
    /** default command timeout used for synchronous commands */
    public static final int DEFAULT_COMMAND_TIMEOUT = 60000;

    /**
     * Create a new API connection to the give device on the supplied port, using anonymous TLS for encryption.
     * @param host The host to which to connect.
     * @param port The TCP port to use.
     * @param timeout The connection timeout to use when opening the connection.
     * @return The ApiConnection
     * @throws ar.com.api.mk.MikrotikApiException Thrown if there is a problem connecting
     * @since 2.1
     */
    public static ApiConnection connectTLS(String host, int port, int timeout) throws MikrotikApiException {
        return ApiConnectionImpl.connect(host, port, true, timeout);
    }

    /**
     * Create a new API connection to the give device on the supplied port, using anonymous TLS for encryption.
     * @param host The host to which to connect.
     * @param port The TCP port to use.
     * @return The ApiConnection
     * @throws ar.com.api.mk.MikrotikApiException Thrown if there is a problem connecting
     */
    public static ApiConnection connectTLS(String host, int port) throws MikrotikApiException {
        return ApiConnectionImpl.connect(host, port, true, DEFAULT_CONNECTION_TIMEOUT);
    }

    /**
     * Create a new API connection to the give device on the default API port, using anonymous TLS for encryption.
     * @param host The host to which to connect.
     * @return The ApiConnection
     * @throws ar.com.api.mk.MikrotikApiException Thrown if there is a problem connecting
     */
    public static ApiConnection connectTLS(String host) throws MikrotikApiException {
        return ApiConnectionImpl.connect(host, DEFAULT_TLS_PORT, true, DEFAULT_CONNECTION_TIMEOUT);
    }

    /**
     * Create a new API connection to the give device on the supplied port
     * @param host The host to which to connect.
     * @param port The TCP port to use.
     * @param timeout The connection timeout to use when opening the connection.
     * @return The ApiConnection
     * @throws ar.com.api.mk.MikrotikApiException Thrown if there is a problem connecting
     * @since 2.1
     */
    public static ApiConnection connect(String host, int port, int timeout) throws MikrotikApiException {
        return ApiConnectionImpl.connect(host, port, false, timeout);
    }

    /**
     * Create a new API connection to the give device on the supplied port
     * @param host The host to which to connect.
     * @param port The TCP port to use.
     * @return The ApiConnection
     * @throws ar.com.api.mk.MikrotikApiException Thrown if there is a problem connecting
     */
    public static ApiConnection connect(String host, int port) throws MikrotikApiException {
        return ApiConnectionImpl.connect(host, port, false, DEFAULT_CONNECTION_TIMEOUT);
    }

    /**
     * Create a new API connection to the give device on the default API port.
     * @param host The host to which to connect.
     * @return The ApiConnection
     * @throws ar.com.api.mk.MikrotikApiException Thrown if there is a problem connecting
     */
   public static ApiConnection connect(String host) throws MikrotikApiException {
        return connect(host, DEFAULT_PORT);
    }

    /**
     * Check the state of connection.
     *
     * @return if connection is established to router it returns true.
     */
    public abstract boolean isConnected();

    /**
     * @throws ar.com.api.mk.MikrotikApiException
     * @deprecated Replaced by close() which conforms to AutoCloseable
     */
    @Deprecated
    public abstract void disconnect() throws MikrotikApiException;

    /**
     * Log in to the remote router.
     *
     * @param username - username of the user on the router
     * @param password - password for the user
     * @throws ar.com.api.mk.MikrotikApiException
     * @throws java.lang.InterruptedException
     */
    public abstract void login(String username, String password) throws MikrotikApiException,  InterruptedException;

    /** execute a command and return a list of results.
     * @param cmd Command to execute
     * @return The list of results
     * @throws ar.com.api.mk.MikrotikApiException
     */
    public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException;

    /** execute a command and attach a result listener to receive it's results.
     *
     * @param cmd Command to execute
     * @param lis ResultListener that will receive the results
     * @return A command object that can be used to cancel the command.
     * @throws MikrotikApiException
     */
    public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException;

    /** cancel a command
     * @param tag The tag of the command to cancel
     * @throws ar.com.api.mk.MikrotikApiException Thrown if there is a problem canceling the command */
    public abstract void cancel(String tag) throws MikrotikApiException;

    /** set the command timeout. The command timeout is used to time out API
     * commands after a specific time.
     *
     * Note: This is not the same as the timeout value passed in the connect() and
     * connectTLS() methods. This timeout is specific to synchronous commands, that
     * timeout is applied to opening the API socket.
     *
     * @param timeout The time out in milliseconds.
     * @throws MikrotikApiException Thrown if the timeout specified is invalid.
     * @since 2.1
     */
    public abstract void setTimeout(int timeout) throws MikrotikApiException;

    /**
     * Disconnect from the remote API
     * @throws ar.com.api.mk.ApiConnectionException Thrown if there is a problem closing the connection.
     * @since 2.2
    */
    @Override
    public abstract void close() throws ApiConnectionException;

}


text:
package org.exbin.framework.bined.operation;

import java.util.Random;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import org.exbin.auxiliary.paged_data.EditableBinaryData;
import org.exbin.auxiliary.paged_data.PagedData;
import org.exbin.bined.CodeAreaUtils;
import org.exbin.bined.capability.CaretCapable;
import org.exbin.bined.capability.ScrollingCapable;
import org.exbin.bined.operation.BinaryDataOperationException;
import org.exbin.bined.operation.swing.CodeAreaOperation;
import org.exbin.bined.operation.swing.CodeAreaOperationType;
import org.exbin.bined.operation.swing.ModifyDataOperation;
import org.exbin.bined.operation.swing.RemoveDataOperation;
import org.exbin.bined.operation.swing.command.CodeAreaCommand;
import org.exbin.bined.operation.swing.command.CodeAreaCommandType;
import org.exbin.bined.swing.CodeAreaCore;
import org.exbin.framework.bined.operation.InsertDataOperation.FillWithType;

/**
 * Replace data operation.
 *
 * @version 0.2.1 2021/09/26
 * @author ExBin Project (http://exbin.org)
 */
@ParametersAreNonnullByDefault
public class ReplaceDataOperation extends CodeAreaOperation {

    private final long position;
    private final long length;
    private final FillWithType fillWithType;
    private final EditableBinaryData data;

    public ReplaceDataOperation(CodeAreaCore codeArea, long position, long length, FillWithType fillWithType, @Nullable EditableBinaryData data) {
        super(codeArea);
        this.position = position;
        this.length = length;
        this.fillWithType = fillWithType;
        this.data = data;
    }

    @Nonnull
    @Override
    public CodeAreaOperationType getType() {
        return CodeAreaOperationType.MODIFY_DATA;
    }

    @Nullable
    @Override
    public void execute() throws BinaryDataOperationException {
        execute(false);
    }

    @Nullable
    @Override
    public CodeAreaOperation executeWithUndo() throws BinaryDataOperationException {
        return execute(true);
    }

    @Nullable
    private CodeAreaOperation execute(boolean withUndo) throws BinaryDataOperationException {
        long dataSize = codeArea.getDataSize();
        if (position > dataSize) {
            throw new BinaryDataOperationException("Unable to replace data outside of document");
        }

        CodeAreaOperation undoOperation = null;
        EditableBinaryData contentData = CodeAreaUtils.requireNonNull(((EditableBinaryData) codeArea.getContentData()));

        if (position == dataSize) {
            undoOperation = new RemoveDataOperation(codeArea, position, 0, length);
            contentData.insertUninitialized(dataSize, length);
        } else if (position + length > dataSize) {
            long diff = position + length - dataSize;
            if (withUndo) {
                // TODO use copy directly once delta is fixed
                PagedData origData = new PagedData();
                origData.insert(0, contentData.copy(position, length - diff));
                undoOperation = new CompoundCodeAreaOperation(codeArea);
                ((CompoundCodeAreaOperation) undoOperation).appendOperation(new ModifyDataOperation(codeArea, position, origData));
                ((CompoundCodeAreaOperation) undoOperation).appendOperation(new RemoveDataOperation(codeArea, dataSize, 0, diff));
            }

            contentData.insertUninitialized(dataSize, diff);
        } else if (withUndo) {
            // TODO use copy directly once delta is fixed
            PagedData origData = new PagedData();
            origData.insert(0, contentData.copy(position, length));
            undoOperation = new ModifyDataOperation(codeArea, position, origData);
        }

        switch (fillWithType) {
            case EMPTY: {
                for (long pos = position; pos < position + length; pos++) {
                    contentData.setByte(pos, (byte) 0x0);
                }
                break;
            }
            case SPACE: {
                for (long pos = position; pos < position + length; pos++) {
                    contentData.setByte(pos, (byte) 0x20);
                }
                break;
            }
            case RANDOM: {
                Random random = new Random();
                for (long pos = position; pos < position + length; pos++) {
                    contentData.setByte(pos, (byte) random.nextInt());
                }
                break;
            }
            case SAMPLE: {
                if (data == null || data.isEmpty()) {
                    for (long pos = position; pos < position + length; pos++) {
                        contentData.setByte(pos, (byte) 0xFF);
                    }
                } else {
                    long dataSizeLimit = data.getDataSize();
                    long pos = position;
                    long remain = length;
                    while (remain > 0) {
                        long seg = Math.min(remain, dataSizeLimit);
                        contentData.replace(pos, data, 0, seg);
                        pos += seg;
                        remain -= seg;
                    }
                }

                break;
            }
            default:
                throw CodeAreaUtils.getInvalidTypeException(fillWithType);
        }

        ((CaretCapable) codeArea).getCaret().setCaretPosition(position + length, 0);
        return undoOperation;
    }

    @Override
    public void dispose() throws BinaryDataOperationException {
        super.dispose();
        data.dispose();
    }

    @ParametersAreNonnullByDefault
    public static class ReplaceDataCommand extends CodeAreaCommand {

        private final ReplaceDataOperation operation;
        private CodeAreaOperation undoOperation;

        public ReplaceDataCommand(ReplaceDataOperation operation) {
            super(operation.getCodeArea());
            this.operation = operation;
        }

        @Override
        public CodeAreaCommandType getType() {
            return CodeAreaCommandType.DATA_MODIFIED;
        }

        @Override
        public void redo() throws BinaryDataOperationException {
            undoOperation = operation.executeWithUndo();
            ((ScrollingCapable) codeArea).revealCursor();
            codeArea.notifyDataChanged();
        }

        @Override
        public void undo() throws BinaryDataOperationException {
            undoOperation.execute();
            undoOperation.dispose();
            ((ScrollingCapable) codeArea).revealCursor();
            codeArea.notifyDataChanged();
        }

        @Override
        public boolean canUndo() {
            return true;
        }

        @Override
        public void dispose() throws BinaryDataOperationException {
            super.dispose();
            operation.dispose();
        }
    }
}


text:
require "pusher-fake/support/base"

# Reset channels between examples
RSpec.configure do |config|
  config.after(:each) do
    PusherFake::Channel.reset
  end
end