text:
<?php

declare (strict_types=1);
namespace Rector\MysqlToMysqli\Rector\FuncCall;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PHPStan\Type\ObjectType;
use PHPStan\Type\ResourceType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
 * @changelog https://www.php.net/manual/en/mysqli.error.php
 *
 * @see \Rector\Tests\MysqlToMysqli\Rector\FuncCall\MysqlQueryMysqlErrorWithLinkRector\MysqlQueryMysqlErrorWithLinkRectorTest
 */
final class MysqlQueryMysqlErrorWithLinkRector extends \Rector\Core\Rector\AbstractRector
{
    /**
     * @var array<string, string>
     */
    private const FUNCTION_RENAME_MAP = ['mysql_affected_rows' => 'mysqli_affected_rows', 'mysql_client_encoding' => 'mysqli_character_set_name', 'mysql_close' => 'mysqli_close', 'mysql_errno' => 'mysqli_errno', 'mysql_error' => 'mysqli_error', 'mysql_escape_string' => 'mysqli_real_escape_string', 'mysql_get_host_info' => 'mysqli_get_host_info', 'mysql_get_proto_info' => 'mysqli_get_proto_info', 'mysql_get_server_info' => 'mysqli_get_server_info', 'mysql_info' => 'mysqli_info', 'mysql_insert_id' => 'mysqli_insert_id', 'mysql_ping' => 'mysqli_ping', 'mysql_query' => 'mysqli_query', 'mysql_real_escape_string' => 'mysqli_real_escape_string', 'mysql_select_db' => 'mysqli_select_db', 'mysql_set_charset' => 'mysqli_set_charset', 'mysql_stat' => 'mysqli_stat', 'mysql_thread_id' => 'mysqli_thread_id'];
    /**
     * @var array<string, int>
     */
    private const FUNCTION_CONNECTION_PARAMETER_POSITION_MAP = ['mysql_affected_rows' => 0, 'mysql_client_encoding' => 0, 'mysql_close' => 0, 'mysql_errno' => 0, 'mysql_error' => 0, 'mysql_get_host_info' => 0, 'mysql_get_proto_info' => 0, 'mysql_get_server_info' => 0, 'mysql_info' => 0, 'mysql_insert_id' => 0, 'mysql_ping' => 0, 'mysql_query' => 1, 'mysql_real_escape_string' => 1, 'mysql_select_db' => 1, 'mysql_set_charset' => 1, 'mysql_stat' => 0, 'mysql_thread_id' => 0];
    public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
    {
        return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add mysql_query and mysql_error with connection', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE'
class SomeClass
{
    public function run()
    {
        $conn = mysqli_connect('host', 'user', 'pass');

        mysql_error();
        $sql = 'SELECT';

        return mysql_query($sql);
    }
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
class SomeClass
{
    public function run()
    {
        $conn = mysqli_connect('host', 'user', 'pass');

        mysqli_error($conn);
        $sql = 'SELECT';

        return mysqli_query($conn, $sql);
    }
}
CODE_SAMPLE
)]);
    }
    /**
     * @return array<class-string<Node>>
     */
    public function getNodeTypes() : array
    {
        return [\PhpParser\Node\Expr\FuncCall::class];
    }
    /**
     * @param FuncCall $node
     */
    public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
    {
        foreach (self::FUNCTION_RENAME_MAP as $oldFunction => $newFunction) {
            if (!$this->isName($node, $oldFunction)) {
                continue;
            }
            if ($node->args === [] || !$this->isProbablyMysql($node->args[0]->value)) {
                $connectionVariable = $this->findConnectionVariable($node);
                $this->removeExistingConnectionParameter($node);
                if (!$connectionVariable instanceof \PhpParser\Node\Expr) {
                    return null;
                }
                $node->args = \array_merge([new \PhpParser\Node\Arg($connectionVariable)], $node->args);
            }
            $node->name = new \PhpParser\Node\Name($newFunction);
            return $node;
        }
        return null;
    }
    private function isProbablyMysql(\PhpParser\Node\Expr $expr) : bool
    {
        if ($this->isObjectType($expr, new \PHPStan\Type\ObjectType('mysqli'))) {
            return \true;
        }
        $staticType = $this->getStaticType($expr);
        $resourceType = new \PHPStan\Type\ResourceType();
        if ($staticType->equals($resourceType)) {
            return \true;
        }
        if ($this->isUnionTypeWithResourceSubType($staticType, $resourceType)) {
            return \true;
        }
        if (!$expr instanceof \PhpParser\Node\Expr\Variable) {
            return \false;
        }
        return $this->isMysqliConnect($expr);
    }
    private function findConnectionVariable(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr
    {
        $connectionAssign = $this->betterNodeFinder->findFirstPrevious($funcCall, function (\PhpParser\Node $node) : ?bool {
            if (!$node instanceof \PhpParser\Node\Expr\Assign) {
                return null;
            }
            return $this->isObjectType($node->expr, new \PHPStan\Type\ObjectType('mysqli'));
        });
        if (!$connectionAssign instanceof \PhpParser\Node\Expr\Assign) {
            return null;
        }
        return $connectionAssign->var;
    }
    private function removeExistingConnectionParameter(\PhpParser\Node\Expr\FuncCall $funcCall) : void
    {
        /** @var string $functionName */
        $functionName = $this->getName($funcCall);
        if (!isset(self::FUNCTION_CONNECTION_PARAMETER_POSITION_MAP[$functionName])) {
            return;
        }
        $connectionPosition = self::FUNCTION_CONNECTION_PARAMETER_POSITION_MAP[$functionName];
        unset($funcCall->args[$connectionPosition]);
    }
    private function isUnionTypeWithResourceSubType(\PHPStan\Type\Type $staticType, \PHPStan\Type\ResourceType $resourceType) : bool
    {
        if ($staticType instanceof \PHPStan\Type\UnionType) {
            foreach ($staticType->getTypes() as $type) {
                if ($type->equals($resourceType)) {
                    return \true;
                }
            }
        }
        return \false;
    }
    private function isMysqliConnect(\PhpParser\Node\Expr\Variable $variable) : bool
    {
        return (bool) $this->betterNodeFinder->findFirstPrevious($variable, function (\PhpParser\Node $node) use($variable) : bool {
            if (!$node instanceof \PhpParser\Node\Expr\Assign) {
                return \false;
            }
            if (!$node->expr instanceof \PhpParser\Node\Expr\FuncCall) {
                return \false;
            }
            if (!$this->nodeComparator->areNodesEqual($node->var, $variable)) {
                return \false;
            }
            return $this->isName($node->expr, 'mysqli_connect');
        });
    }
}


text:
#ifndef __ICU_DATA_VER_H__
#define __ICU_DATA_VER_H__

#include "unicode/utypes.h"

#ifndef U_HIDE_DRAFT_API
/**
 * @draft ICU 49
 */
#define U_ICU_VERSION_BUNDLE "icuver"

/**
 * @draft ICU 49
 */
#define U_ICU_DATA_KEY "DataVersion"

/**
 * Retrieves the data version from icuver and stores it in dataVersionFillin.
 *
 * @param dataVersionFillin icuver data version information to be filled in if not-null
 * @param status stores the error code from the calls to resource bundle
 *
 * @draft ICU 49
 */
U_DRAFT void U_EXPORT2 u_getDataVersion(UVersionInfo dataVersionFillin, UErrorCode *status);
#endif  /* U_HIDE_DRAFT_API */

#endif

redpajama_set_name: RedPajamaGithub


text:
package org.uberfire.client.mvp;

import org.jboss.errai.common.client.dom.HTMLElement;
import org.uberfire.workbench.model.NamedPosition;

public interface TemplatedActivity {

    /**
     * Returns the HTMLElement that contains the child WorkbenchPanelView at the given position.
     * @return the HTMLElement that contains the child at the given position, or null if the given position does not exist
     * within this activity's view.
     */
    HTMLElement resolvePosition(NamedPosition p);

    /**
     * Returns the HTMLElement that is the root panel of this activity.
     */
    HTMLElement getRootElement();
}


text:
using Xunit;
using System.Collections.Generic;

#pragma warning disable 0414

namespace System.Reflection.Tests
{
    public class FieldInfoRTArrayTests
    {
        [Fact]
        public static void SetValue_aArray()
        {
            FieldInfo fi = GetField(type, "aArray");

            fi.SetValue(obj, ATypeWithMixedAB);
            Assert.Equal(ATypeWithMixedAB, fi.GetValue(obj));

            fi.SetValue(obj, ATypeWithAllA);
            Assert.Equal(ATypeWithAllA, fi.GetValue(obj));

            fi.SetValue(obj, ATypeWithAllB);
            Assert.Equal(ATypeWithAllB, fi.GetValue(obj));

            fi.SetValue(obj, BTypeWithAllB);
            Assert.Equal(BTypeWithAllB, fi.GetValue(obj));

            fi.SetValue(obj, BTypeWithAllB_Contra);
            Assert.Equal(BTypeWithAllB_Contra, fi.GetValue(obj));
        }

        [Fact]
        public static void SetValue_bArray()
        {
            FieldInfo fi = GetField(type, "bArray");

            Assert.Throws<ArgumentException>(() => fi.SetValue(obj, ATypeWithMixedAB));
            Assert.Throws<ArgumentException>(() => fi.SetValue(obj, ATypeWithAllA));
            Assert.Throws<ArgumentException>(() => fi.SetValue(obj, ATypeWithAllB));

            fi.SetValue(obj, BTypeWithAllB);
            Assert.Equal(BTypeWithAllB, fi.GetValue(obj));

            fi.SetValue(obj, BTypeWithAllB_Contra);
            Assert.Equal(BTypeWithAllB_Contra, fi.GetValue(obj));
        }

        [Fact]
        public static void SetValue_iArray()
        {
            FieldInfo fi = GetField(type, "iArray");

            fi.SetValue(obj, mixedMN);
            Assert.Equal(mixedMN, fi.GetValue(obj));
        }

        [Fact]
        public static void SetValue_intArray()
        {
            FieldInfo fi = GetField(type, "intArray");

            fi.SetValue(obj, mixedInt);
            Assert.Equal(mixedInt, fi.GetValue(obj));

            Assert.Throws<ArgumentException>(() => fi.SetValue(obj, allByte));
        }

        [Fact]
        public static void SetValue_objectArray()
        {
            FieldInfo fi = GetField(type, "objectArray");

            fi.SetValue(obj, mixedMN);
            Assert.Equal(mixedMN, fi.GetValue(obj));

            fi.SetValue(obj, BTypeWithAllB_Contra);

            Assert.Equal(BTypeWithAllB_Contra, fi.GetValue(obj));
            Assert.Throws<ArgumentException>(() => fi.SetValue(obj, mixedInt));
            Assert.Throws<ArgumentException>(() => fi.SetValue(obj, allByte));
        }

        // Helper method to get field from Type type
        private static FieldInfo GetField(Type type, string fieldName)
        {
            TypeInfo ti = type.GetTypeInfo();
            IEnumerator<FieldInfo> alldefinedFields = ti.DeclaredFields.GetEnumerator();
            FieldInfo fi = null, found = null;

            while (alldefinedFields.MoveNext())
            {
                fi = alldefinedFields.Current;
                if (fi.Name.Equals(fieldName))
                {
                    //found type
                    found = fi;
                    break;
                }
            }
            return found;
        }

        // Reflection fields

        private static Type type = typeof(ArrayAsField);
        private static object obj = Activator.CreateInstance(typeof(ArrayAsField));

        private static A[] ATypeWithMixedAB = new A[] { new A(), new FieldInfoArrayB() };
        private static A[] ATypeWithAllA = new A[] { new A(), new A() };
        private static A[] ATypeWithAllB = new A[] { new FieldInfoArrayB(), new FieldInfoArrayB() };
        private static FieldInfoArrayB[] BTypeWithAllB = new FieldInfoArrayB[] { new FieldInfoArrayB(), new FieldInfoArrayB() };
        private static A[] BTypeWithAllB_Contra = new FieldInfoArrayB[] { new FieldInfoArrayB(), new FieldInfoArrayB() };

        private static I[] mixedMN = new I[] { new M(), new N() };
        private static int[] mixedInt = new int[] { 200, -200, (byte)30, (ushort)2 };
        private static byte[] allByte = new byte[] { 2, 3, 4 };
    }

    public class A { }
    public class FieldInfoArrayB : A { }

    public interface I { }
    public class M : I { }
    public class N : I { }

    public class ArrayAsField
    {
        public A[] aArray;
        public FieldInfoArrayB[] bArray;

        public I[] iArray;

        public int[] intArray;
        public object[] objectArray;
    }
}


text:
<?php
$f = fopen("config.php",'r');
$line = fgets($f);
fclose($f);
if($line != "<?php\n"){
  header("location:install.php");
}

$con = null;
?>

<title>Login</title>
<link rel="stylesheet" type="text/css" href="css/lingStudy.css">

<form action="loginUser.php" method="post" class="form-signin" id = "login_form"
style="visibility:hidden;">

Admin Login

<input type="text" name="username" size="20" placeholder="Username">
<input type="password" name="password" size="20" placeholder="Password">

<input type="submit" value="Log In" class="submitButton">
<button type="button" class="removalButton" onclick="uhOh();">Forgot Username/Password</button>
</form>

<form action="loginTester.php" method="post" class="form-signin" id = "testlog_form" >

<input type="text" name="sessID" size="20" placeholder="1 2 3">
<input type="text" name="testID" size="20" placeholder="A B C">

<input type="image" src="img/check.png" class="noTextSubmit" alt="Verify Test">
</form>

<?php

include("CloseSession.php");

?>


text:
                Why do we use Python ?

              Python is a general high-level programming language regarded for its simplicity and easy to use modules in Data science.

              We shall be using Python for the following:

Data Exploration

Data Manipulation

Data visualization


text:
package nl.xillio.xill.plugins.file.constructs;

import nl.xillio.xill.api.io.IOStream;

import java.io.IOException;
import java.nio.file.Path;

/**
 * This construct will open a file handle with write permissions.
 *
 * @author Thomas biesaart
 */
public class OpenWriteConstruct extends AbstractOpenConstruct {

    @Override
    protected IOStream open(Path path) throws IOException {
        return fileStreamFactory.openWrite(path);
    }
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/*
 * Edwin
 * 20/09/2012
 * Front end
 */

class M_about extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    private $table = 'pages_nathanu';
    private $pict = 'slider_foto';

    function get_all() {

        $data = $this->db->get($this->table);

        return $data->result();
    }

    public function get_foto() {
        $this->db->where('label', 'about_us');
        $data = $this->db->get($this->pict);
        return $data->result();
    }

    function get_par($person) {
        $this->db->where('naam', $person);
        $data = $this->db->get($this->table);
        return $data->result();
    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */


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

namespace RootBee
{
    public class CredentialStorage
    {
        public static string[] GetCredentialFromLocker(string resourceName)
        {
            PasswordCredential credential = null;

            var vault = new PasswordVault();
            try
            {
                var credentialList = vault.FindAllByResource(resourceName);
                credential = credentialList[0];
                credential.RetrievePassword();
                return new string[] { credential.UserName, credential.Password };
            }
            catch (Exception)
            {
                return new string[] { "", "" };
            }

            //if (credentialList.Count > 0)
            //{

            //}
            //else
            //{

            //}

        }

        public static void DeleteCredentialFromLocker(string resourceName, string username, string password)
        {
            var vault = new PasswordVault();
            vault.Remove(new PasswordCredential(resourceName, username, password));
        }

        public static void CreateCredentialInLocker(string resourceName, string username, string password)
        {
            var vault = new PasswordVault();
            vault.Add(new PasswordCredential(resourceName, username, password));
        }

        public static void UpdateCredentialInLocker(string resourceName, string username, string password)
        {
            string[] oldCred = GetCredentialFromLocker(resourceName);
            DeleteCredentialFromLocker(resourceName, oldCred[0], oldCred[1]);
            CreateCredentialInLocker(resourceName, username, password);
        }
    }
}


text:
package gui.main;

import gui.BackEnd.UpdateDayProgress;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import util.GUIPallet;

/*
    BenjaminWilcox
    Aug 16, 2017
    GNGH2
 */
public class DayProgress extends JPanel
{

    private Dimension dayD = new Dimension(390, 100);
    private GUIPallet pallet = new GUIPallet();
    private JProgressBar progress = new JProgressBar();
    private JLabel label = new JLabel();

    public DayProgress()
    {
        new UpdateDayProgress().pasDayProgress(this);
        setPreferredSize(dayD);
        setBackground(pallet.getPanel());
        setLayout(new GridLayout(2, 1));
        label.setText("Next Day Progress: ");
        add(label);
        add(progress);
    }

    public void update(int i)
    {
        progress.setValue(i);
        label.setText("Next Day Progress: " + i * 100.00 / progress.getMaximum() + "%");
        validate();
    }

    public void setTotal(int i)
    {
        progress.setMaximum(i);
    }

}


text:
package org.wicketopia.model.proxy;

import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.testng.annotations.Test;
import org.wicketopia.util.Person;

import static org.testng.Assert.assertEquals;

/**
 * @since 1.0
 */
public class TestProxyModelManager {
//----------------------------------------------------------------------------------------------------------------------
// Other Methods
//----------------------------------------------------------------------------------------------------------------------

    @Test
    public void testCommit() {
        final ProxyModelManager mgr = new ProxyModelManager();
        final Person p = new Person();
        p.setFirst("OldFirst");
        p.setLast("OldLast");

        IModel<String> proxyFirst = mgr.proxy(new PropertyModel<String>(p, "first"));
        assertEquals(proxyFirst.getObject(), "OldFirst");
        IModel<String> proxyLast = mgr.proxy(new PropertyModel<String>(p, "last"));
        assertEquals(proxyLast.getObject(), "OldLast");
        proxyFirst.setObject("NewFirst");
        proxyLast.setObject("NewLast");
        assertEquals(p.getFirst(), "OldFirst");
        assertEquals(p.getLast(), "OldLast");

        mgr.commit();
        assertEquals(p.getFirst(), "NewFirst");
        assertEquals(p.getLast(), "NewLast");
    }
}


text:
<?php

/**
 * Class for accessing IMAP's SORT/SEARCH/ESEARCH result
 *
 * @package    Framework
 * @subpackage Storage
 */
class rcube_result_index
{
    public $incomplete = false;

    protected $raw_data;
    protected $mailbox;
    protected $meta = array();
    protected $params = array();
    protected $order = 'ASC';

    const SEPARATOR_ELEMENT = ' ';

    /**
     * Object constructor.
     */
    public function __construct($mailbox = null, $data = null)
    {
        $this->mailbox = $mailbox;
        $this->init($data);
    }

    /**
     * Initializes object with SORT command response
     *
     * @param string $data IMAP response string
     */
    public function init($data = null)
    {
        $this->meta = array();

        $data = explode('*', (string)$data);

        // ...skip unilateral untagged server responses
        for ($i=0, $len=count($data); $i<$len; $i++) {
            $data_item = &$data[$i];
            if (preg_match('/^ SORT/i', $data_item)) {
                // valid response, initialize raw_data for is_error()
                $this->raw_data = '';
                $data_item = substr($data_item, 5);
                break;
            }
            else if (preg_match('/^ (E?SEARCH)/i', $data_item, $m)) {
                // valid response, initialize raw_data for is_error()
                $this->raw_data = '';
                $data_item = substr($data_item, strlen($m[0]));

                if (strtoupper($m[1]) == 'ESEARCH') {
                    $data_item = trim($data_item);
                    // remove MODSEQ response
                    if (preg_match('/\(MODSEQ ([0-9]+)\)$/i', $data_item, $m)) {
                        $data_item = substr($data_item, 0, -strlen($m[0]));
                        $this->params['MODSEQ'] = $m[1];
                    }
                    // remove TAG response part
                    if (preg_match('/^\(TAG ["a-z0-9]+\)\s*/i', $data_item, $m)) {
                        $data_item = substr($data_item, strlen($m[0]));
                    }
                    // remove UID
                    $data_item = preg_replace('/^UID\s*/i', '', $data_item);

                    // ESEARCH parameters
                    while (preg_match('/^([a-z]+) ([0-9:,]+)\s*/i', $data_item, $m)) {
                        $param = strtoupper($m[1]);
                        $value = $m[2];

                        $this->params[$param] = $value;
                        $data_item = substr($data_item, strlen($m[0]));

                        if (in_array($param, array('COUNT', 'MIN', 'MAX'))) {
                            $this->meta[strtolower($param)] = (int) $value;
                        }
                    }

// @TODO: Implement compression using compressMessageSet() in __sleep() and __wakeup() ?
// @TODO: work with compressed result?!
                    if (isset($this->params['ALL'])) {
                        $data_item = implode(self::SEPARATOR_ELEMENT,
                            rcube_imap_generic::uncompressMessageSet($this->params['ALL']));
                    }
                }

                break;
            }

            unset($data[$i]);
        }

        $data = array_filter($data);

        if (empty($data)) {
            return;
        }

        $data = array_shift($data);
        $data = trim($data);
        $data = preg_replace('/[\r\n]/', '', $data);
        $data = preg_replace('/\s+/', ' ', $data);

        $this->raw_data = $data;
    }

    /**
     * Checks the result from IMAP command
     *
     * @return bool True if the result is an error, False otherwise
     */
    public function is_error()
    {
        return $this->raw_data === null ? true : false;
    }

    /**
     * Checks if the result is empty
     *
     * @return bool True if the result is empty, False otherwise
     */
    public function is_empty()
    {
        return empty($this->raw_data) ? true : false;
    }

    /**
     * Returns number of elements in the result
     *
     * @return int Number of elements
     */
    public function count()
    {
        if ($this->meta['count'] !== null)
            return $this->meta['count'];

        if (empty($this->raw_data)) {
            $this->meta['count']  = 0;
            $this->meta['length'] = 0;
        }
        else {
            $this->meta['count'] = 1 + substr_count($this->raw_data, self::SEPARATOR_ELEMENT);
        }

        return $this->meta['count'];
    }

    /**
     * Returns number of elements in the result.
     * Alias for count() for compatibility with rcube_result_thread
     *
     * @return int Number of elements
     */
    public function count_messages()
    {
        return $this->count();
    }

    /**
     * Returns maximal message identifier in the result
     *
     * @return int Maximal message identifier
     */
    public function max()
    {
        if (!isset($this->meta['max'])) {
            $this->meta['max'] = (int) @max($this->get());
        }

        return $this->meta['max'];
    }

    /**
     * Returns minimal message identifier in the result
     *
     * @return int Minimal message identifier
     */
    public function min()
    {
        if (!isset($this->meta['min'])) {
            $this->meta['min'] = (int) @min($this->get());
        }

        return $this->meta['min'];
    }

    /**
     * Slices data set.
     *
     * @param $offset Offset (as for PHP's array_slice())
     * @param $length Number of elements (as for PHP's array_slice())
     *
     */
    public function slice($offset, $length)
    {
        $data = $this->get();
        $data = array_slice($data, $offset, $length);

        $this->meta          = array();
        $this->meta['count'] = count($data);
        $this->raw_data      = implode(self::SEPARATOR_ELEMENT, $data);
    }

    /**
     * Filters data set. Removes elements not listed in $ids list.
     *
     * @param array $ids List of IDs to remove.
     */
    public function filter($ids = array())
    {
        $data = $this->get();
        $data = array_intersect($data, $ids);

        $this->meta          = array();
        $this->meta['count'] = count($data);
        $this->raw_data      = implode(self::SEPARATOR_ELEMENT, $data);
    }

    /**
     * Reverts order of elements in the result
     */
    public function revert()
    {
        $this->order = $this->order == 'ASC' ? 'DESC' : 'ASC';

        if (empty($this->raw_data)) {
            return;
        }

        $data = $this->get();
        $data = array_reverse($data);
        $this->raw_data = implode(self::SEPARATOR_ELEMENT, $data);

        $this->meta['pos'] = array();
    }

    /**
     * Check if the given message ID exists in the object
     *
     * @param int  $msgid     Message ID
     * @param bool $get_index When enabled element's index will be returned.
     *                        Elements are indexed starting with 0
     *
     * @return mixed False if message ID doesn't exist, True if exists or
     *               index of the element if $get_index=true
     */
    public function exists($msgid, $get_index = false)
    {
        if (empty($this->raw_data)) {
            return false;
        }

        $msgid = (int) $msgid;
        $begin = implode('|', array('^', preg_quote(self::SEPARATOR_ELEMENT, '/')));
        $end   = implode('|', array('$', preg_quote(self::SEPARATOR_ELEMENT, '/')));

        if (preg_match("/($begin)$msgid($end)/", $this->raw_data, $m,
            $get_index ? PREG_OFFSET_CAPTURE : null)
        ) {
            if ($get_index) {
                $idx = 0;
                if ($m[0][1]) {
                    $idx = 1 + substr_count($this->raw_data, self::SEPARATOR_ELEMENT, 0, $m[0][1]);
                }
                // cache position of this element, so we can use it in get_element()
                $this->meta['pos'][$idx] = (int)$m[0][1];

                return $idx;
            }
            return true;
        }

        return false;
    }

    /**
     * Return all messages in the result.
     *
     * @return array List of message IDs
     */
    public function get()
    {
        if (empty($this->raw_data)) {
            return array();
        }

        return explode(self::SEPARATOR_ELEMENT, $this->raw_data);
    }

    /**
     * Return all messages in the result.
     *
     * @return array List of message IDs
     */
    public function get_compressed()
    {
        if (empty($this->raw_data)) {
            return '';
        }

        return rcube_imap_generic::compressMessageSet($this->get());
    }

    /**
     * Return result element at specified index
     *
     * @param int|string  $index  Element's index or "FIRST" or "LAST"
     *
     * @return int Element value
     */
    public function get_element($index)
    {
        $count = $this->count();

        if (!$count) {
            return null;
        }

        // first element
        if ($index === 0 || $index === '0' || $index === 'FIRST') {
            $pos = strpos($this->raw_data, self::SEPARATOR_ELEMENT);
            if ($pos === false)
                $result = (int) $this->raw_data;
            else
                $result = (int) substr($this->raw_data, 0, $pos);

            return $result;
        }

        // last element
        if ($index === 'LAST' || $index == $count-1) {
            $pos = strrpos($this->raw_data, self::SEPARATOR_ELEMENT);
            if ($pos === false)
                $result = (int) $this->raw_data;
            else
                $result = (int) substr($this->raw_data, $pos);

            return $result;
        }

        // do we know the position of the element or the neighbour of it?
        if (!empty($this->meta['pos'])) {
            if (isset($this->meta['pos'][$index]))
                $pos = $this->meta['pos'][$index];
            else if (isset($this->meta['pos'][$index-1]))
                $pos = strpos($this->raw_data, self::SEPARATOR_ELEMENT,
                    $this->meta['pos'][$index-1] + 1);
            else if (isset($this->meta['pos'][$index+1]))
                $pos = strrpos($this->raw_data, self::SEPARATOR_ELEMENT,
                    $this->meta['pos'][$index+1] - $this->length() - 1);

            if (isset($pos) && preg_match('/([0-9]+)/', $this->raw_data, $m, null, $pos)) {
                return (int) $m[1];
            }
        }

        // Finally use less effective method
        $data = explode(self::SEPARATOR_ELEMENT, $this->raw_data);

        return $data[$index];
    }

    /**
     * Returns response parameters, e.g. ESEARCH's MIN/MAX/COUNT/ALL/MODSEQ
     * or internal data e.g. MAILBOX, ORDER
     *
     * @param string $param  Parameter name
     *
     * @return array|string Response parameters or parameter value
     */
    public function get_parameters($param=null)
    {
        $params = $this->params;
        $params['MAILBOX'] = $this->mailbox;
        $params['ORDER']   = $this->order;

        if ($param !== null) {
            return $params[$param];
        }

        return $params;
    }

    /**
     * Returns length of internal data representation
     *
     * @return int Data length
     */
    protected function length()
    {
        if (!isset($this->meta['length'])) {
            $this->meta['length'] = strlen($this->raw_data);
        }

        return $this->meta['length'];
    }
}


text:
// @vue/component
export default {
  computed: {
    validity: {
      // Expose validity property
      cache: false,
      get() /* istanbul ignore next */ {
        return this.$refs.input.validity
      }
    },
    validationMessage: {
      // Expose validationMessage property
      cache: false,
      get() /* istanbul ignore next */ {
        return this.$refs.input.validationMessage
      }
    },
    willValidate: {
      // Expose willValidate property
      cache: false,
      get() /* istanbul ignore next */ {
        return this.$refs.input.willValidate
      }
    }
  },
  methods: {
    setCustomValidity() /* istanbul ignore next */ {
      // For external handler that may want a setCustomValidity(...) method
      return this.$refs.input.setCustomValidity(...arguments)
    },
    checkValidity() /* istanbul ignore next */ {
      // For external handler that may want a checkValidity(...) method
      return this.$refs.input.checkValidity(...arguments)
    },
    reportValidity() /* istanbul ignore next */ {
      // For external handler that may want a reportValidity(...) method
      return this.$refs.input.reportValidity(...arguments)
    }
  }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. Pl. South Africa 10: t. 417. 1931

#### Original name
null

### Remarks
null


text:
Launching a tiny Linux with Vagrant
===================================

- Install [vagrant](http://vagrantup.com).
- Have a look at the available [vagrant boxes](https://atlas.hashicorp.com/boxes/search)
- Search for a `tiny` box for the provider `virtualbox`
- Click on the search result. There should be an instruction for how to initialize the box in a `fixed width font`
- Go into this [vagrant folder](https://github.com/rvosa/arangs2016/tree/master/docs/2016-05-10/vagrant) in the terminal. Then run the initialization command that was provided.
- There should now be a file called `Vagrantfile`. Open it in a text editor.
- Assign more RAM (2048) to the VM by editing the Vagrantfile.
- Turn on the GUI
- This box does not use `bash`, it uses `sh`. Specify this in the Vagrantfile using `config.ssh.shell="sh"`
- When you're done configuring the Vagrantfile, save it, then launch the VM with `vagrant up`
- There might be some error messages where it tries to "mount" folders. If you wait long enough it'll give up -
  it's not a problem. If it seems to hang when creating synced folders you can break out of this with Ctr+C,
  and then log in on the VM using `vagrant ssh`.
- This VM is again too minimal for us to do something useful with so feel free to destroy it (`vagrant destroy`).


text:
//--------------------------------------
// XerialJ
//
// DBRuntimeException.java
// Since: Sep 1, 2008 11:02:24 AM
//
// $URL$
// $Author$
//--------------------------------------
package org.xerial.db;

/**
 * An DBError indicates a serious error has occurred in the application, and the
 * application should not catch this type of exception.
 *
 * @author leo
 *
 */
public class DBError extends Error
{
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private final DBErrorCode errorCode;

    public DBError(DBErrorCode errorCode, String message)
    {
        this(errorCode, message, null);
    }

    protected DBError(DBErrorCode errorCode, String message, Throwable cause)
    {
        super(message, cause);
        this.errorCode = errorCode;
    }

    protected DBError()
    {
        this.errorCode = DBErrorCode.UnknownError;
    }

    public DBError(DBErrorCode errorCode, Throwable cause)
    {
        this(errorCode, null, cause);
    }

    public DBError(DBErrorCode errorCode)
    {
        this(errorCode, null, null);
    }

    public DBErrorCode getErrorCode()
    {
        return errorCode;
    }

    @Override
    public String toString()
    {
        String message = getLocalizedMessage();
        if (message == null)
            message = "";
        return String.format("[%s] %s", errorCode, message);
    }

}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("../src/index");
class EmployeeModel {
}
exports.EmployeeModel = EmployeeModel;
let validateAnsync = (firstName, message = '') => {
    let model = new EmployeeModel();
    model.firstName = firstName;
    let validator = new index_1.Validator(index_1.CascadeMode.StopOnFirstFailure);
    let rule = validator.addRule(model.firstName)
        .withParameterName('firstName')
        .required();
    if (message.length > 0)
        rule.withMessage(message);
    return validator.validateAsync(model);
};
describe('required validation', () => {
    it('can validate required field when input is valid', async () => {
        let result = await validateAnsync('validemail');
        expect(result.isValid())
            .toBeTruthy();
        expect(result.errors.length)
            .toBe(0);
    });
    it('can validate required field when input is whitespace', async () => {
        let result = await validateAnsync(' ');
        expect(result.isValid())
            .toBeFalsy();
        expect(result.errors.length)
            .toBe(1);
        expect(result.errors[0].propertyName)
            .toBe('firstName');
        expect(result.errors[0].propertyValue)
            .toBe(' ');
    });
    it('can validate required field when input is blank', async () => {
        let result = await validateAnsync('');
        expect(result.isValid())
            .toBeFalsy();
        expect(result.errors.length)
            .toBe(1);
        expect(result.errors[0].propertyName)
            .toBe('firstName');
        expect(result.errors[0].propertyValue)
            .toBe('');
    });
    it('can return the set custom error message', async () => {
        let result = await validateAnsync('', 'this is custom message');
        expect(result.isValid())
            .toBeFalsy();
        expect(result.errors.length)
            .toBe(1);
        expect(result.errors[0].errorMessage)
            .toBe('this is custom message');
    });
});


text:
import { Injectable } from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  ActivatedRoute
} from '@angular/router';

import { MenuService } from './menu/menu.service';
import { Menu } from './menu/menu';

@Injectable()
export class BreadcrumbmenuGuard implements CanActivate {

  constructor(private menuService: MenuService) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    // debugger
    let p = route.params
    let url: string = state.url;
    return true
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let menu: any = route.params
    if (menu.l) {
      this.menuService.getMenus().then(menus => {
        this.menuService.initBreadcrumbArray()
        this.setBreadcrumbArray(menu, menus)
        this.menuService.setMenuSelected(menu.l)
      })
    }
    return true
  }

  setBreadcrumbArray(target: Menu, menus: Array<Menu>): boolean {
    for (let m in menus) {
      let menu: Menu = menus[m]
      this.menuService.breadcrumbArray.push(menu)
      //get it
      if (menu.l == target.l) {
        return true
      } else if (menu.c && menu.c.length > 0) { //查詢咨菜單
        let isInChildren = this.setBreadcrumbArray(target, menu.c)
        if (isInChildren) {
          return true
        } else {
          this.menuService.breadcrumbArray.pop()
        }
      } else { //出棧
        this.menuService.breadcrumbArray.pop()
      }
    }
    menus.forEach(i => {

    })
  }
}


text:
layout: post
title:  "Delete duplicate-value nodes"
categories: implementation linked-list
author: "Rahul"
---
Delete duplicate-value nodes from a sorted linked list
Delete as few nodes as possible so that the list does not contain any value more than once.
The given head pointer may be null indicating that the list is empty
```python
def RemoveDuplicates(head):
    if (head is None):
        return None
    nextitem=head.next
    while(nextitem is not None and head.data == nextitem.data):
        nextitem=nextitem.next
    head.next = RemoveDuplicates(nextitem)
    return head

```


text:
extern HINSTANCE GlobalInstance;
extern UINT GlobalRefCount;

#define TRACE(msg) MessageBox (NULL, msg, "Trace", MB_OK);

#endif // _LISTSHELL_H


text:
package org.wso2.developerstudio.eclipse.gmf.esb.impl;

import org.eclipse.emf.ecore.EClass;

import org.wso2.developerstudio.eclipse.gmf.esb.EntitlementMediatorOutputConnector;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;

/**
 *
 * An implementation of the model object 'Entitlement Mediator Output Connector'.
 *
 *

 *

 *
 * @generated
 */
public class EntitlementMediatorOutputConnectorImpl extends OutputConnectorImpl implements EntitlementMediatorOutputConnector {
	/**
	 *
	 *
	 * @generated
	 */
	protected EntitlementMediatorOutputConnectorImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	protected EClass eStaticClass() {
		return EsbPackage.Literals.ENTITLEMENT_MEDIATOR_OUTPUT_CONNECTOR;
	}

} //EntitlementMediatorOutputConnectorImpl


text:
<?php
return array (
  'Following user' => 'Dem Nutzer folgen',
  'User followers' => 'Der Nutzer folgt',
);


text:
class User < ActiveRecord::Base
  serialize :urls

  # Restrict access to just these fields
  attr_accessible :name

  #::::::::::::::::::::::::::::::::::::::::::::::::::
  # Find a user using the nickname
  def self.find_user_by_nickname(user_id)
    user_id.blank? ? nil : User.first(:conditions => ['lower(nickname) = lower(?)', user_id])
  end

  #::::::::::::::::::::::::::::::::::::::::::::::::::
  # Find (or create) a user based on the omniauth params
  def self.auth!(omniauth)
    # Only allow instagram authentication
    raise 'fail' unless (omniauth['provider'] == 'instagram')

    # Find or create the user based on the uid
    user = User.find_or_initialize_by_uid(omniauth['uid'])

    # Update attributes to reflect current reality
    user_info        = omniauth['user_info']
    user.name        = user_info['name']
    user.nickname    = user_info['nickname']
    user.description = user_info['description']
    user.image       = user_info['image']
    user.urls        = user_info['urls']

    # Twitter specific info
    instagram_info       = omniauth['extra']['user_hash']
    user.photos_count    = instagram_info['counts']['media']
    user.friends_count   = instagram_info['counts']['follows']
    user.followers_count = instagram_info['counts']['followed_by']

    # OAuth info
    user.instagram_token  = omniauth['credentials']['token']

    # Save
    user.save!

    # Return the user we found
    user
  end
end


text:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Raven.Client.Documents;
using Raven.DependencyInjection;
using Raven.Identity;
using Sample.Mvc.Common;
using Sample.Mvc.Models;
using System.Collections.Generic;

namespace Sample.Mvc
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.Secure = CookieSecurePolicy.Always;
            });

            services
                .AddRavenDbDocStore() // Create our IDocumentStore singleton using the database settings in appsettings.json
                .AddRavenDbAsyncSession() // Create an Raven IAsyncDocumentSession for every request.
                .AddIdentity<AppUser, Raven.Identity.IdentityRole>() // Tell ASP.NET to use identity framework.
                .AddRavenDbIdentityStores<AppUser, Raven.Identity.IdentityRole>(); // Use Raven as the Identity store for user users and roles.

            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            // Required for Raven Identity to work with authorization and authentication.
            app.UseAuthentication();
            app.UseAuthorization();

            // Create the database if it doesn't exist.
            // Also, create our roles if they don't exist. Needed because we're doing some role-based auth in this demo.
            var docStore = app.ApplicationServices.GetRequiredService<IDocumentStore>();
            docStore.EnsureExists();
            docStore.EnsureRolesExist(new List<string> { AppUser.AdminRole, AppUser.ManagerRole });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Indices>
    <Index output="success.xml">
        <RequestPacket xmlns="http://www.emc.com/schemas/celerra/xml_api">
            <Request>
                <StartTask timeout="300">
                    <NewFileSystem name="test14">
                        <Mover mover="1"/>
                        <StoragePool mayContainSlices="true" pool="61"
                                     size="5120"/>
                    </NewFileSystem>
                </StartTask>
            </Request>
        </RequestPacket>
    </Index>
    <Index output="invalid_vdm_id.xml">
        <RequestPacket xmlns="http://www.emc.com/schemas/celerra/xml_api">
            <Request>
                <StartTask timeout="300">
                    <NewFileSystem name="test18">
                        <Vdm vdm="1"/>
                        <StoragePool mayContainSlices="true" pool="0"
                                     size="1"/>
                    </NewFileSystem>
                </StartTask>
            </Request>
        </RequestPacket>
    </Index>
    <Index output="invalid_pool.xml">
        <RequestPacket xmlns="http://www.emc.com/schemas/celerra/xml_api">
            <Request>
                <StartTask timeout="300">
                    <NewFileSystem name="test17">
                        <Mover mover="1"/>
                        <StoragePool mayContainSlices="true" pool="0"
                                     size="1"/>
                    </NewFileSystem>
                </StartTask>
            </Request>
        </RequestPacket>
    </Index>
    <Index output="invalid_size.xml">
        <RequestPacket xmlns="http://www.emc.com/schemas/celerra/xml_api">
            <Request>
                <StartTask timeout="300">
                    <NewFileSystem name="test16">
                        <Mover mover="1"/>
                        <StoragePool mayContainSlices="true" pool="59"
                                     size="1"/>
                    </NewFileSystem>
                </StartTask>
            </Request>
        </RequestPacket>
    </Index>
    <Index output="not_enough_space.xml">
        <RequestPacket xmlns="http://www.emc.com/schemas/celerra/xml_api">
            <Request>
                <StartTask timeout="300">
                    <NewFileSystem name="test15">
                        <Mover mover="1"/>
                        <StoragePool mayContainSlices="true" pool="59"
                                     size="5242880"/>
                    </NewFileSystem>
                </StartTask>
            </Request>
        </RequestPacket>
    </Index>
    <Index output="invalid_mover_id.xml">
        <RequestPacket xmlns="http://www.emc.com/schemas/celerra/xml_api">
            <Request>
                <StartTask timeout="300">
                    <NewFileSystem name="test13">
                        <Mover mover="6"/>
                        <StoragePool mayContainSlices="true" pool="61"
                                     size="5120"/>
                    </NewFileSystem>
                </StartTask>
            </Request>
        </RequestPacket>
    </Index>
    <Index output="create_fs_existed.xml">
        <RequestPacket xmlns="http://www.emc.com/schemas/celerra/xml_api">
            <Request>
                <StartTask timeout="300">
                    <NewFileSystem name="EG_TEST_POOL">
                        <Mover mover="1"/>
                        <StoragePool mayContainSlices="true" pool="32"
                                     size="10240"/>
                    </NewFileSystem>
                </StartTask>
            </Request>
        </RequestPacket>
    </Index>
</Indices>


text:
/* */
(function(process) {
  Autolinker.HtmlParser = Autolinker.Util.extend(Object, {
    htmlRegex: (function() {
      var tagNameRegex = /[0-9a-zA-Z][0-9a-zA-Z:]*/,
          attrNameRegex = /[^\s\0"'>\/=\x01-\x1F\x7F]+/,
          attrValueRegex = /(?:"[^"]*?"|'[^']*?'|[^'"=<>`\s]+)/,
          nameEqualsValueRegex = attrNameRegex.source + '(?:\\s*=\\s*' + attrValueRegex.source + ')?';
      return new RegExp(['(?:', '<(!DOCTYPE)', '(?:', '\\s+', '(?:', nameEqualsValueRegex, '|', attrValueRegex.source + ')', ')*', '>', ')', '|', '(?:', '<(/)?', '(' + tagNameRegex.source + ')', '(?:', '\\s+', nameEqualsValueRegex, ')*', '\\s*/?', '>', ')'].join(""), 'gi');
    })(),
    parse: function(html, options) {
      options = options || {};
      var processHtmlNodeVisitor = options.processHtmlNode || function() {},
          processTextNodeVisitor = options.processTextNode || function() {},
          htmlRegex = this.htmlRegex,
          currentResult,
          lastIndex = 0;
      while ((currentResult = htmlRegex.exec(html)) !== null) {
        var tagText = currentResult[0],
            tagName = currentResult[1] || currentResult[3],
            isClosingTag = !!currentResult[2],
            inBetweenTagsText = html.substring(lastIndex, currentResult.index);
        if (inBetweenTagsText) {
          processTextNodeVisitor(inBetweenTagsText);
        }
        processHtmlNodeVisitor(tagText, tagName.toLowerCase(), isClosingTag);
        lastIndex = currentResult.index + tagText.length;
      }
      if (lastIndex < html.length) {
        var text = html.substring(lastIndex);
        if (text) {
          processTextNodeVisitor(text);
        }
      }
    }
  });
})(require("process"));


text:
"""embARC MLI model adaptation tool"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys
import re
import shutil

try:
  from tensorflow.lite.python.util import convert_bytes_to_c_source, _convert_model_from_object_to_bytearray, \
    _convert_model_from_bytearray_to_object
except ImportError:
  print('Install TensorFlow package first to use MLI adaptation tool.')
  sys.exit(1)

# Model conversion functions
def convert_c_source_to_bytes(input_cc_file):
  """Converts C++ source file to bytes (immutable).

  Args:
    input_cc_file: A .cc file to process.

  Returns:
    A bytearray corresponding to the input cc file array.
  """
  pattern = re.compile(r'(((0x[0-9a-fA-F]+), ?)+)')
  model_bytearray = bytearray()

  with open(input_cc_file) as file_handle:
    for line in file_handle:
      values_match = pattern.search(line)

      if values_match is None:
        continue

      list_text = values_match.group(1)
      values_text = filter(None, list_text.split(','))

      values = [int(x, base=16) for x in values_text]
      model_bytearray.extend(values)

  return bytes(model_bytearray)

def convert_c_source_to_object(input_cc_file):
  """Converts C++ source file to an object for parsing."""
  with open(input_cc_file, 'r') as model_file:
    include_path, array_name = None, None
    for line in model_file:
      if '#include' in line and not include_path:
        include_path = line.strip('#include ').strip('"\n')
      if re.search(r"\[\].*[=]|\[[1-9][0-9]*\].*[=]", line) and not array_name:
        array_name = re.search(r"\w*(?=\[)", line).group()
      if include_path and array_name:
        break

  model_bytes = convert_c_source_to_bytes(input_cc_file)
  return _convert_model_from_bytearray_to_object(model_bytes), \
         include_path, array_name

def read_model(input_tflite_file):
  """Reads a tflite model as a python object."""

  with open(input_tflite_file, 'rb') as model_file:
    model_bytearray = bytearray(model_file.read())
    return _convert_model_from_bytearray_to_object(model_bytearray)

def write_model(model_object, output_tflite_file, include_path, array_name):
  """Writes the tflite model, a python object, into the output file.

  Args:
    model_object: A tflite model as a python object
    output_tflite_file: Full path name to the output tflite file.
    include_path: Path to model header file
    array_name: name of the array for .cc output

  Raises:
    ValueError: If file is not formatted in .cc or .tflite
  """
  model_bytearray = _convert_model_from_object_to_bytearray(model_object)
  if output_tflite_file.endswith('.cc'):
    mode = 'w'
    converted_model = convert_bytes_to_c_source(data=model_bytearray,
                                                array_name=array_name,
                                                include_path=include_path,
                                                use_tensorflow_license=True)[0]
  elif output_tflite_file.endswith('.tflite'):
    mode = 'wb'
    converted_model = model_bytearray
  else:
    raise ValueError('File format not supported')

  with open(output_tflite_file, mode) as output_file:
    output_file.write(converted_model)

# Helper functions
def transpose_weights(tensor, buffer, transpose_shape):
  """Transposes weights to embARC MLI format according to transpose_shape

  Args:
    tensor: A tensor to process
    buffer: A buffer relevant to the tensor
    transpose_shape: Target shape.
  """
  buffer.data = buffer.data \
    .reshape(tensor.shape) \
    .transpose(transpose_shape) \
    .flatten()

  tensor.shape = tensor.shape[transpose_shape]

  tensor.quantization.quantizedDimension = \
    transpose_shape.index(tensor.quantization.quantizedDimension)

# Layer-specific adaptation functions
def adapt_conv(operator, tensors, buffers):
  """Adapts weights tensors of convolution layers

  Args:
    operator: Operator index
    tensors: Model tensors dict
    buffers: Model buffers dict
  """
  transpose_weights(tensors[operator.inputs[1]],
                    buffers[tensors[operator.inputs[1]].buffer], [1, 2, 3, 0])

def adapt_dw(operator, tensors, _buffers):
  """Adapts weights tensors of depthwise convolution layers

  Args:
    operator: Operator index
    tensors: Model tensors dict
    _buffers: Model buffers dict
  """
  tensors[operator.inputs[1]].shape = \
    tensors[operator.inputs[1]].shape[[1, 2, 0, 3]]

def adapt_fc(operator, tensors, buffers):
  """Adapts weights tensors of fully connected layers

  Args:
    operator: Operator index
    tensors: Model tensors dict
    buffers: Model buffers dict
  """
  transpose_weights(tensors[operator.inputs[1]],
                    buffers[tensors[operator.inputs[1]].buffer], [1, 0])

# Op_codes that require additional adaptation for MLI
adapt_op_codes = {
    3: adapt_conv,  # CONV_2D
    4: adapt_dw,  # DEPTHWISE_CONV_2D
    9: adapt_fc  # FULLY_CONNECTED
}

def adapt_model_to_mli(model):
  """Adapts weights of the model to embARC MLI layout

  Args:
    model: TFLite model object
  """
  op_codes = [
      op_code.builtinCode
      if op_code.builtinCode != 0 else op_code.deprecatedBuiltinCode
      for op_code in model.operatorCodes
  ]
  for subgraph in model.subgraphs:
    for operator in subgraph.operators:
      try:
        adapt_op_codes[op_codes[operator.opcodeIndex]] \
          (operator, subgraph.tensors, model.buffers)
      except KeyError:
        continue

def main(argv):
  try:
    if len(sys.argv) == 3:
      tflite_input = argv[1]
      tflite_output = argv[2]
    elif len(sys.argv) == 2:
      tflite_input = argv[1]
      tflite_output = argv[1]
  except IndexError:
    print("Usage: %s <input cc/tflite> <output cc/tflite>" % (argv[0]))
  else:
    if tflite_input == tflite_output:
      path, filename = os.path.split(tflite_input)
      try:
        shutil.copyfile(tflite_input, path + '/orig_' + filename)
      except OSError as err:
        print('Error while creating backup file:', err)
    if tflite_input.endswith('.cc'):
      model, include_path, array_name = convert_c_source_to_object(
          tflite_input)
    elif tflite_input.endswith('.tflite'):
      model = read_model(tflite_input)
      include_path = ''
      array_name = os.path.split(tflite_output)[1].split('.')[0]
    else:
      raise ValueError('File format not supported')

    adapt_model_to_mli(model)
    write_model(model, tflite_output, include_path, array_name)

    print('Model was adapted to be used with embARC MLI.')

if __name__ == "__main__":
  main(sys.argv)


text:
<?php

namespace Blog\CoreBundle\Tests\Controller;

use Blog\ModelBundle\Entity\Author;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * Class AuthorControllerTest
 */
class AuthorControllerTest extends WebTestCase
{
    /**
     * Test show author
     */
    public function testShow()
    {
        $client = static::createClient();

        /** @var Author $author */
        $author = $client->getContainer()->get('doctrine')->getManager()->getRepository('ModelBundle:Author')->findFirst();
        $authorPostsCount = $author->getPosts()->count();

        $crawler = $client->request('GET', '/en/author/'.$author->getSlug());

        $this->assertTrue($client->getResponse()->isSuccessful(), 'The response was not successful');

        $this->assertCount($authorPostsCount, $crawler->filter('h2'), 'There should be '.$authorPostsCount.' posts');
    }
}


text:
#include <ecdaa.h>

#include "issuer_gen_keys_ZZZ.h"
#include "extract_gpk_ZZZ.h"
#include "member_gen_keys_ZZZ.h"
#include "issuer_issue_credential_ZZZ.h"
#include "member_process_credential_ZZZ.h"
#include "member_sign_ZZZ.h"
#include "verify_ZZZ.h"
#include "parse_cli.h"

#define EXPAND_CURVE_CASE(command, curve, ...) \
    case curve: \
        out = command ## _ ## curve(__VA_ARGS__); \
        break;

int main(int argc, char **argv) {
    struct cli_params params;

    parse_cli(argc, argv, &params);
    int out = 0;
    switch(params.command){
        case action_issuer_gen_keys:
            switch (params.curve) {
                EXPAND_CURVE_CASE(issuer_gen_keys, ZZZ, params.ipk, params.isk)
                default:
                    out = UNKNOWN_CURVE_ERROR;
                    break;
            }
            break;
        case action_extract_gpk:
            switch (params.curve) {
                EXPAND_CURVE_CASE(extract_gpk, ZZZ, params.ipk, params.gpk)
                default:
                    out = UNKNOWN_CURVE_ERROR;
                    break;
            }
            break;
        case action_member_gen_keys:
            switch (params.curve) {
                EXPAND_CURVE_CASE(member_gen_keys, ZZZ, params.nonce, params.pk, params.sk)
                default:
                    out = UNKNOWN_CURVE_ERROR;
                    break;
            }
            break;
        case action_issue_credential:
            switch (params.curve) {
                EXPAND_CURVE_CASE(issuer_issue_credential, ZZZ, params.pk, params.isk, params.cred, params.cred_sig, params.nonce)
                default:
                    out = UNKNOWN_CURVE_ERROR;
                    break;
            }
            break;
        case action_process_credential:
            switch (params.curve) {
                EXPAND_CURVE_CASE(member_process_credential, ZZZ, params.pk, params.gpk, params.cred, params.cred_sig)
                default:
                    out = UNKNOWN_CURVE_ERROR;
                    break;
            }
            break;
        case action_sign:
            switch (params.curve) {
                EXPAND_CURVE_CASE(member_sign, ZZZ, params.sk, params.cred, params.sig, params.message, params.basename)
                default:
                    out = UNKNOWN_CURVE_ERROR;
                    break;
            }
            break;
        case action_verify:
            switch (params.curve) {
                EXPAND_CURVE_CASE(verify, ZZZ, params.message, params.sig, params.gpk, params.sk_rev_list, params.num_sk_revs, params.bsn_rev_list, params.num_bsn_revs, params.basename)
                default:
                    out = UNKNOWN_CURVE_ERROR;
                    break;
            }
            break;
        case action_help:
            break;
    }

    switch(out){
        case WRITE_TO_FILE_ERROR:
            fprintf(stderr, "Error writing to a file\n");
            break;
        case READ_FROM_FILE_ERROR:
            fprintf(stderr, "Error reading a file\n");
            break;
        case KEY_CREATION_ERROR:
            fprintf(stderr, "Error creating a key pair\n");
            break;
        case DESERIALIZE_KEY_ERROR:
            fprintf(stderr, "Error deserializing a key\n");
            break;
        case VERIFY_ERROR:
            fprintf(stderr, "Signature doesn't verify\n");
            break;
        case CRED_CREATION_ERROR:
            fprintf(stderr, "Error creating DAA credentials\n" );
            break;
        case PARSE_REVOC_LIST_ERROR:
            fprintf(stderr, "Error while parsing a revocation list\n" );
            break;
        case SIGNING_ERROR:
            fprintf(stderr, "Error while signing\n");
            break;
        case UNKNOWN_CURVE_ERROR:
            fprintf(stderr, "Unrecognized curve name: '%d'\n", params.curve);
            break;
        case SUCCESS:
            fprintf(stderr, "ok\n");
            break;
    }

    if (out != SUCCESS)
        return 1;

    return 0;
}


text:
import sys

from django.core.management.color import color_style
from django.db import IntegrityError, migrations, transaction
from django.db.models import Q

WARNING = """
    A problem arose migrating proxy model permissions for {old} to {new}.

      Permission(s) for {new} already existed.
      Codenames Q: {query}

    Ensure to audit ALL permissions for {old} and {new}.
"""

def update_proxy_model_permissions(apps, schema_editor, reverse=False):
    """
    Update the content_type of proxy model permissions to use the ContentType
    of the proxy model.
    """
    style = color_style()
    Permission = apps.get_model("auth", "Permission")
    ContentType = apps.get_model("contenttypes", "ContentType")
    alias = schema_editor.connection.alias
    for Model in apps.get_models():
        opts = Model._meta
        if not opts.proxy:
            continue
        proxy_default_permissions_codenames = [
            "%s_%s" % (action, opts.model_name) for action in opts.default_permissions
        ]
        permissions_query = Q(codename__in=proxy_default_permissions_codenames)
        for codename, name in opts.permissions:
            permissions_query |= Q(codename=codename, name=name)
        content_type_manager = ContentType.objects.db_manager(alias)
        concrete_content_type = content_type_manager.get_for_model(
            Model, for_concrete_model=True
        )
        proxy_content_type = content_type_manager.get_for_model(
            Model, for_concrete_model=False
        )
        old_content_type = proxy_content_type if reverse else concrete_content_type
        new_content_type = concrete_content_type if reverse else proxy_content_type
        try:
            with transaction.atomic(using=alias):
                Permission.objects.using(alias).filter(
                    permissions_query,
                    content_type=old_content_type,
                ).update(content_type=new_content_type)
        except IntegrityError:
            old = "{}_{}".format(old_content_type.app_label, old_content_type.model)
            new = "{}_{}".format(new_content_type.app_label, new_content_type.model)
            sys.stdout.write(
                style.WARNING(WARNING.format(old=old, new=new, query=permissions_query))
            )

def revert_proxy_model_permissions(apps, schema_editor):
    """
    Update the content_type of proxy model permissions to use the ContentType
    of the concrete model.
    """
    update_proxy_model_permissions(apps, schema_editor, reverse=True)

class Migration(migrations.Migration):
    dependencies = [
        ("auth", "0010_alter_group_name_max_length"),
        ("contenttypes", "0002_remove_content_type_name"),
    ]
    operations = [
        migrations.RunPython(
            update_proxy_model_permissions, revert_proxy_model_permissions
        ),
    ]


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

 -->

<!--  These resources are around just to allow their values to be customized
     for different hardware and product builds.  -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string-array name="wfcOperatorErrorAlertMessages">
    <item msgid="5217754856196352581">"To make calls and send messages over Wi-Fi, first ask your operator to set up this service. Then turn on Wi-Fi calling again from Settings."</item>
  </string-array>
  <string-array name="wfcOperatorErrorNotificationMessages">
    <item msgid="4688475512286389971">"Register with your operator"</item>
  </string-array>
    <string name="wfcSpnFormat" msgid="5475635312889002673">"%s Wi-Fi Calling"</string>
</resources>


text:
Positive `tabindex` attribute values **must not** be used to create a logical tab order.

  `tabindex` values of `0` **must not** be used on elements that are not focusable by default.

  Rationale
  =========

  Typical BBC pages are made up of several shared components (Global navigation, page content, share tools,
  location service widgets, etc.) so no one piece of code has complete awareness of the content of the page
  or when the content updates. Positive `tabindex` values results in unpredictable tab order that do not occur
  if the natural order of content is relied upon.

  Using `tabindex="0"` on an element adds it to the document tab order, however it does not change the element
  type to allow it to be discovered by navigating by link or form element, nor does it bind click and key press
  handlers to the element. There are no circumstances in which it is not better to use a natively focusable
  control such as a `<a>` or `<button>`.

  Techniques
  ==========

  Pass:

    News

    <button type="submit">Search</button>

  Fail:

    <button type="submit" tabindex="2">Search</button>


text:
const HTMLErrorBuilder = function () {
  this.htmlTemplate = function (errorData) {
    let htmlString = `<h4>${errorData.titleKey}</h4>`

    if (errorData.bodyKey) {
      htmlString += `<p>${errorData.bodyKey}</p>`
    }

    if (errorData.scope) {
      htmlString += `<p>${errorData.scope}</p>`
    }

    if (errorData.level) {
      htmlString += `<p>${errorData.level}</p>`
    }

    if (errorData.createdOn) {
      htmlString += `<p style="font-size:smaller">createdOn: ${errorData.createdOn} UTC</p>`
    }

    return htmlString
  }

  this.extractPatternsFromString = function (regex, string) {
    let patternMap = {}
    let m

    while ((m = regex.exec(string)) !== null) {
      if (m.index === regex.lastIndex) {
        regex.lastIndex++
      }

      m.forEach((match, groupIndex) => {
        if (groupIndex === 1) {
          patternMap[match] = match
        }
      })
    }

    return Object.keys(patternMap)
  }

  this.searchValue = function (key, aJsonObject) {
    let keysToRetrieve = key.slice(1, key.length - 1).split('.')
    let value = aJsonObject
    let index = 0

    while (index < keysToRetrieve.length && value !== null && value !== undefined) {
      value = value[keysToRetrieve[index]]

      index++
    }

    if (value === null || value === undefined) {
      console.warn(`Could not find data for key "${key}" on "${JSON.stringify(aJsonObject)}"`)
    }

    return value
  }

  this.replaceValues = function (regex, templateString, receivedArgumentsData) {
    let stringToWorkOn = templateString
    let keysToReplace = this.extractPatternsFromString(regex, stringToWorkOn)

    if (receivedArgumentsData) {
      for (let i = 0; i < keysToReplace.length; i++) {
        let valueRetrieved = this.searchValue(keysToReplace[i], receivedArgumentsData)

        if (valueRetrieved !== null && valueRetrieved !== undefined) {
          stringToWorkOn = stringToWorkOn.replace(keysToReplace[i], valueRetrieved)
        }
      }
    }
    return stringToWorkOn
  }

  this.doBuild = function (errorData) {
    errorData.bodyKey = this.replaceValues(/(?=({[\w.]+}).*)/g, errorData.bodyKey, errorData.arguments)
    errorData.titleKey = this.replaceValues(/(?=({[\w.]+}).*)/g, errorData.titleKey, errorData.arguments)

    return this.htmlTemplate(errorData)
  }

  this.initialize = function () {
  }

  this.buildFor = function (errorData) {
    this.initialize()

    let buildedString = this.doBuild(errorData)

    this.initialize()

    return buildedString
  }
}

export default function (Vue, options) {
  let attributeName = (options && options.htmlErrorBuilderNameInApp) || 'ErrorBuilder'
  Vue.prototype[attributeName] = new HTMLErrorBuilder()
  Vue[attributeName] = Vue.prototype[attributeName]
}


text:
package coreClientThreads;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import common.FileControlPacket;
import coreClient.Global;

public class FileSendControlThread extends Thread
{
	private Socket fileSendControlSocket;
	private final static String serverIP = Global.serverIP;
	private final static int fileControlPort = Global.serverFileRequestPort;
	private ObjectOutputStream outStream;
	private ObjectInputStream inStream;
	private String destNick;
	private FileControlPacket fileControlPack;
	private String filePath;
	private String fileName;

	public FileSendControlThread(String dn, String fp)
	{
		super();
		destNick = dn;
		filePath = fp;
	}

	public void run()
	{
		System.out.println("File Sent Request Found.");
		String[] temp;
		temp = filePath.split("/");
		fileName = temp[temp.length - 1];
		fileControlPack = new FileControlPacket(false, destNick, false);
		fileControlPack.fileName = fileName;
		int retryCount = 3;
		System.out.println("FSCT: Pinging server for Client IP.");
		while (retryCount > 0)
		{
			try
			{
				sendFileControlPacket();
				break;
			}
			catch (IOException ex)
			{
				System.out
						.println("Retrying fileControlPacket send | FileSendControlThread.");
				retryCount--;
				continue;
			}
		}
		System.out.println("FSCT: Successfully Pinged Server. Waiting For Server to Send Back Control Packet");
		retryCount = 3;
		while (retryCount > 0)
		{
			try
			{
				receiveFileControlPacket();
				break;
			}
			catch (IOException ex)
			{
				System.out
						.println("Retrying fileControlPacket receive | FileSendControlThread.");
				retryCount--;
				continue;
			}
			catch (ClassNotFoundException e)
			{
				System.out
						.println("Invalid packet received | FileSendControlThread.");
				return;
			}
		}

		if (fileControlPack.isIP == true && fileControlPack.payload.equals("0.0.0.0"))
		{
			System.out.println("FSCT: User is offline. Try Again Later");
		}
		else
		{
			System.out.println("FSCT: Setting up connection directly to client");
			(new FileSenderThread(filePath,fileName,fileControlPack.payload)).start();

		}
	}

	private void receiveFileControlPacket() throws IOException,
			ClassNotFoundException
	{
		System.out.println("FSCT: Initializing Input Stream");
		inStream = new ObjectInputStream(fileSendControlSocket.getInputStream());
		System.out.println("FSCT: Reading FileControlPacket Object");
		fileControlPack = (FileControlPacket) inStream.readObject();
		fileSendControlSocket.close();
	}

	private void sendFileControlPacket() throws IOException
	{
		System.out.println("FSCT: Setting up a socket Connection");
		fileSendControlSocket = new Socket(serverIP, fileControlPort);
		System.out.println("FSCT: Initializing Output Stream");
		outStream = new ObjectOutputStream(
				fileSendControlSocket.getOutputStream());
		System.out.println("FSCT: Writing FIleControlPacket into outStream");
		outStream.writeObject(fileControlPack);
		outStream.flush();
	}
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ff.vr.annotate;
using System;

namespace ff.nodegraph
{
    public class NodeGraph : MonoBehaviour
    {
        public Guid GUID; // Iri
        public string objStateDescription = "";
        public string modelAuthor = "email@address.com";
        public string modelVersion = "v1";

        [HideInInspector]
        public Node Node;

        private void Awake()
        {
            CreateNodesFromHierachy();
            GUID = new Guid(GUIDHelper.ExtractGUIDFromName(this.name));
        }

        private void CreateNodesFromHierachy()
        {
            Node = Node.FindChildNodes(this.gameObject);
        }

    }
}


text:
[![Build Status](https://travis-ci.org/alsiola/react-doc-props.svg?branch=master)](https://travis-ci.org/alsiola/react-doc-props)
[![Coverage Status](https://coveralls.io/repos/github/alsiola/react-doc-props/badge.svg?branch=master)](https://coveralls.io/github/alsiola/react-doc-props?branch=master)
# react-doc-props

react-doc-props is a package that allows you to write comprehensive in-file documentation of React components.  This documentation will then generate the correct propTypes and defaultProps for your component.

## Installation
Install with your package manager of choice:

````
npm install --save react-doc-props
````

## Usage
The basic react-doc-props documentation object looks like this.
````
export const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        // a object of props keyed by propName - see below
    }
};
````

This documentation object is then converted to the appropriate propTypes and defaultProps objects, and applied to the component with the `setComponentProps` function:
````
import { setComponentProps } from 'react-doc-props';

setComponentProps(documentation, Component);
````

### Simple Prop Types

The `documentation.props` object is constructed using the propTypes exported by react-prop-docs:
````
import { string } from 'react-doc-props';
````

Which are then used in the documentation object:
````
const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        title: {
            type: string,
            description: 'The title of the component',
            default: 'A default title'
        }
    }
};
````

If a prop is required then, as with the React PropTypes, just add `.isRequired`:
````
const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        title: {
            type: string.isRequired,
            description: 'The title of the component',
            default: 'A default title'
        }
    }
};
````

The simple propTypes are all used in the same way, and all of the React PropTypes are available:
````
import { string, number, boolean, object, func, array, symbol, element, node, any } from 'react-doc-props';
````

### Shape
A shape propType is created by using the `shape` function from `react-doc-props`.  The shape required is passed as an argument - this argument should be an object with the same structure as the `documentation.props` object:
````
import { shape, string, number } from 'react-doc-props';

const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        user: {
            type: shape({
                name: {
                    type: string,
                    description: 'The users name'
                },
                age: {
                    type: number,
                    description: 'The users age in years'
                }
            }),
            description: 'The current user',
            default: {
                name: 'No name set',
                age: -1
            }
        }
    }
};
````

If a shape is required, then `shape.isRequired()` can be used:
````
import { shape, string, number } from 'react-doc-props';

const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        user: {
            type: shape.isRequired({
                name: {
                    type: string,
                    description: 'The users name'
                },
                age: {
                    type: number,
                    description: 'The users age in years'
                }
            }),
            description: 'The current user'
        }
    }
};
````

### InstanceOf
An instanceOf propType is created with the `instanceOf` function from `react-doc-props`.  It takes two arguments: the class the prop must be an instance of, and optionally a display name for that class.
````
import { instanceOf } from 'react-doc-props';

const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        loginMsg: {
            type: instanceOf(Message, 'Message'),
            description: 'A message about login.'
        }
    }
};
````

If the prop is required, then use the `instanceOf.isRequired()` function.

### ArrayOf and ObjectOf
ArrayOf and ObjectOf work in the same way, using `arrayOf` and `objectOf` respectively:
````
import { arrayOf, objectOf, string } from 'react-doc-props';

const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        names: {
            type: arrayOf(string),
            description: 'An array of user names.'
        },
        languages: {
            type: objectOf(string),
            description: 'The preferred language of a user keyed by user name'
        }
    }
};
````
Again, substitute with `arrayOf.isRequired` or `objectOf.isRequired` for required props.

### OneOf
OneOf prop types can be defined using the `oneOf` and `oneOf.isRequired` functions, with a single argument - an array of the possible values.
````
import { oneOf } from 'react-prop-types';

const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        openDirection: {
            type: oneOf( ['up', 'down', 'left', 'right'] ),
            description: 'An array of user names.'
        }
    }
};
````

### OneOfType
OneOfType prop types can be defined with the `oneOfType` and `oneOfType.isRequired` functions.  The single argument is an array of possible types.
````
import { oneOfType, string, number } from 'react-prop-types';

const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        time: {
            type: oneOfType([ string, number ]),
            description: 'The current time as a string or timestamp.'
        }
    }
};
````

### Custom Validator Functions
The use of custom validator functions is supported with the `custom` function, passing the validator function as an argument:
````
import { custom } from 'react-prop-types';

const singleCharStringValidator = (props, propName, component) => {
    if (!props[propName] ||typeof props[propName] !== 'string' || props[propName].length !== 1) {
        return new Error(`Invalid prop ${propName} supplied to ${component}.`);
    }
}

const documentation = {
    name: 'ComponentName',
    description: 'A description of the component',
    props: {
        initial: {
            type: custom(singleCharStringValidator)
            description: 'A single letter initial.'
        }
    }
};
````


text:
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- These settings headers are only used on tablets. -->

    <header
        android:fragment="com.texasgamer.zephyr.activity.PreferencesActivity$GeneralPreferenceFragment"
        android:icon="@drawable/ic_settings"
        android:title="@string/pref_header_general" />

    <header
        android:fragment="com.texasgamer.zephyr.activity.PreferencesActivity$NotificationPreferenceFragment"
        android:icon="@drawable/ic_notif"
        android:title="@string/pref_header_notifications" />

    <header
        android:icon="@drawable/ic_about"
        android:title="@string/about_title">
        <intent android:targetPackage="com.texasgamer.zephyr"
            android:targetClass="com.texasgamer.zephyr.activity.AboutActivity" />
    </header>

</preference-headers>


text:
hd44780 examples
================
The hd44780 library package inclues many examples that demonstrate the capabilities of the library.

#### The examples are broken up into various sub directories.

* `Documenatation`

The Documenation sketch is not really an example sketch.
It is a dummy sketch used to allow documentation to be accessed through the IDE when the sketched is loaded into the IDE.

* `ioClass`

Contains subdirectories for each included hd44780 i/o class containing example sketches
that are specific to the i/o class. They also contain wrapper sketches for the special purpose sketches mentioned above.

* `otherLibraries`

Contains subdirectories for other (non hd44780) libraries that contain wrapper sketches for various special purpose hd44780examples sketches.
Its primary purpose is to provide easy benchmarking of other libraries for comparison purposes by using LCDiSpeed.

**The sketches in the hd44780examples area are special purpose sketches that are used as include files for the i/o class examples.
They should not be looked at as examples for how to use the library.**
While the hd44780examples sketches can be modified to work standalone with any LiquidCrystal API compatible library, their primary purpose, as shipped in the hd44780 library package, is to act as an include file for the i/o class wrapper sketches and are not intended to be used directly.
**See the ioClass specific subdirectories for the examples for each ioClass.**


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- Spring MVC -->
   	<servlet>
   		<servlet-name>mvc-dispatcher</servlet-name>
   		<servlet-class>org.springframework.web.servlet.DispatcherServlet
   		</servlet-class>
   		<load-on-startup>1</load-on-startup>
   	</servlet>
   	<servlet-mapping>
   		<servlet-name>mvc-dispatcher</servlet-name>
   		<url-pattern>/</url-pattern>
   	</servlet-mapping>

   	<listener>
   		<listener-class>org.springframework.web.context.ContextLoaderListener
   		</listener-class>
   	</listener>

    <!-- Loads Spring Security config file -->
   	<context-param>
   		<param-name>contextConfigLocation</param-name>
   		<param-value>
   			/WEB-INF/spring-security.xml
   		</param-value>
   	</context-param>

   	<!-- Spring Security -->
   	<filter>
   		<filter-name>springSecurityFilterChain</filter-name>
   		<filter-class>org.springframework.web.filter.DelegatingFilterProxy
   		</filter-class>
   	</filter>

   	<filter-mapping>
   		<filter-name>springSecurityFilterChain</filter-name>
   		<url-pattern>/*</url-pattern>
   	</filter-mapping>

</web-app>


text:
{% extends "base.html" %}

{% block content %}
<link rel="stylesheet" href="/static/css/datepicker.css" />

 Server Settings

 Log Settings

            <form method="post">{% csrf_token %}

                Elastic Search Server :
                <input id="server_ip" type="text" value="{{ ip }}">

                <input type="button" class="btn-primary" value="Save" onclick="save_server();">

            </form>

                Choose Log Type

            <form method="post">{% csrf_token %}

                            Show on index page:
                            <input id="settings_index" type="text" value="">

                            Log column splitting delimiter:
                            <input id="settings_delimiter" type="text" value="">

                            Shown columns on page:
                            <input id="settings_shown" type="text" value="">

                            Filtered columns:
                            <input id="settings_filter" type="text" value="">

                    <input type="button" class="btn-primary" value="Save" onclick="save_log_settings();">

            </form>

</form>
{% endblock %}


text:
<?php

/*
 * This polyfill of hash_equals() is a modified edition of https://github.com/indigophp/hash-compat/tree/43a19f42093a0cd2d11874dff9d891027fc42214
 *
 * Copyright (c) 2015 Indigo Development Team
 * Released under the MIT license
 * https://github.com/indigophp/hash-compat/blob/43a19f42093a0cd2d11874dff9d891027fc42214/LICENSE
 */
if (!function_exists('hash_equals')) {
    defined('USE_MB_STRING') or define('USE_MB_STRING', function_exists('mb_strlen'));

    function hash_equals($knownString, $userString)
    {
        $strlen = function ($string) {
            if (USE_MB_STRING) {
                return mb_strlen($string, '8bit');
            }

            return strlen($string);
        };

        // Compare string lengths
        if (($length = $strlen($knownString)) !== $strlen($userString)) {
            return false;
        }

        $diff = 0;

        // Calculate differences
        for ($i = 0; $i < $length; $i++) {
            $diff |= ord($knownString[$i]) ^ ord($userString[$i]);
        }
        return $diff === 0;
    }
}

class LineBot
{
    public function __construct($channelAccessToken, $channelSecret)
    {
        $this->channelAccessToken = $channelAccessToken;
        $this->channelSecret = $channelSecret;
    }

    public function parseEvents()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            error_log("Method not allowed");
            exit();
        }

        $entityBody = file_get_contents('php://input');

        if (strlen($entityBody) === 0) {
            http_response_code(400);
            error_log("Missing request body");
            exit();
        }

        if (!hash_equals($this->sign($entityBody), $_SERVER['HTTP_X_LINE_SIGNATURE'])) {
            http_response_code(400);
            error_log("Invalid signature value");
            exit();
        }

        $data = json_decode($entityBody, true);
        if (!isset($data['events'])) {
            http_response_code(400);
            error_log("Invalid request body: missing events property");
            exit();
        }
        return $data['events'];
    }

	function multiCast($message){
    	$header = array(
            "Content-Type: application/json",
            'Authorization: Bearer ' . $this->channelAccessToken,
        );

        $ch   = curl_init('https://api.line.me/v2/bot/message/multicast');
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($message));
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		$response = curl_exec($ch);
		if($response === false){
			error_log("Error: connection");
		}else{
			$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
			$header = substr($response, 0, $header_size);
			$body = substr($response, $header_size);
			if($body){
				return json_decode($body);
			}else{
				error_log("Error: " . $header);
			}
		}
    }

    function pushMessage($uid, $messages){
        error_log("pushMessage");
        $header = array(
            "Content-Type: application/json",
            'Authorization: Bearer ' . $this->channelAccessToken,
        );

        $post = array('to' => $uid, 'messages' => $messages);

        error_log(json_encode($post));
        $ch   = curl_init('https://api.line.me/v2/bot/message/push');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($post));
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($ch);
        error_log("Push: " . $response);
        if($response === false){
            error_log("Error: connection");
        }else{
            $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header = substr($response, 0, $header_size);
            $body = substr($response, $header_size);
            if($body){
                return json_decode($body);
            }else{
                error_log("Error: " . $header);
            }
        }
    }

	function replyMessage($message){
    	$header = array(
            "Content-Type: application/json",
            'Authorization: Bearer ' . $this->channelAccessToken,
        );

        $ch   = curl_init('https://api.line.me/v2/bot/message/reply');
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($message));
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		$response = curl_exec($ch);
		if($response === false){
			error_log("Error: connection");
		}else{
			$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
			$header = substr($response, 0, $header_size);
			$body = substr($response, $header_size);
			if($body){
				error_log("Body: " . $body);
				return json_decode($body);
			}else{
				error_log("Error: " . $header);
			}
		}
    }

	function getProfil($userId){
    	$header = array(
            "Content-Type: application/json",
            'Authorization: Bearer ' . $this->channelAccessToken,
        );

        $ch   = curl_init('https://api.line.me/v2/bot/profile/' . $userId);
		curl_setopt($ch, CURLOPT_POST, false);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		$response = curl_exec($ch);
		if($response === false){
			error_log("Error: connection");
		}else{
			$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
			$header = substr($response, 0, $header_size);
			$body = substr($response, $header_size);
			if($body){
				error_log("Body: " . $body);
				return json_decode($body);
			}else{
				error_log("Error: " . $header);
			}
		}
    }

    private function sign($body)
    {
        $hash = hash_hmac('sha256', $body, $this->channelSecret, true);
        $signature = base64_encode($hash);
        return $signature;
    }
}


text:
<project>
<!-- This is an ant build script that can be included in the build script for "typical" web apps written with this
framework that need JS related build tasks. -->
	<property name="sql-src" location="src/main/sql" />
	<property name="test-sql-src" location="src/test/sql" />

	<target name="compile-sql" depends="init" description="Compile SQL query classes using 'SQLC'.">
		<java classname="net.metanotion.sqlc.SQLC" classpathref="run.classpath" failonerror="true" fork="true">
			<arg value="${codegen-out}" />
			<arg value="${sql-src}/queries/" />
			<arg value="${java-src}" />
		</java>
	</target>

	<target name="echo-db" depends="compile"
		description="Generate a file containing the SQL required to create the multitenant version of the application database.">
		<java classname="net.metanotion.sql.BuildDb" classpathref="run.classpath" failonerror="true" fork="true"
			output="${output}/${package-name}.multi.schema.sql">
			<arg value="-url:${db.server}" />
			<arg value="-user:${db.user}" />
			<arg value="-pass:${db.pass}" />
			<arg value="-database:${db.db-multi}" />
			<arg value="-create" />
			<arg value="-dropFirst" />
			<arg value="-class:${database-class-multi}" />
			<arg value="-dryrun" />
			<arg value="-echo" />
		</java>
	</target>

	<target name="echo-single-db" depends="compile"
		description="Generate a file containing the SQL required to create the single tenant version of the application database.">
		<java classname="net.metanotion.sql.BuildDb" classpathref="run.classpath" failonerror="true" fork="true"
			output="${output}/${package-name}.schema.sql">
			<arg value="-url:${db.server}" />
			<arg value="-user:${db.user}" />
			<arg value="-pass:${db.pass}" />
			<arg value="-database:${db.db-single}" />
			<arg value="-create" />
			<arg value="-dropFirst" />
			<arg value="-class:${database-class-single}" />
			<arg value="-dryrun" />
			<arg value="-echo" />
		</java>
	</target>

	<target name="build-db" depends="compile"
		description="Create a new database initialized with the multitenant application schema.">
		<java classname="net.metanotion.sql.BuildDb" classpathref="run.classpath" failonerror="true" fork="true">
			<arg value="-url:${db.server}" />
			<arg value="-user:${db.user}" />
			<arg value="-pass:${db.pass}" />
			<arg value="-database:${db.db-multi}" />
			<arg value="-create" />
			<arg value="-dropFirst" />
			<arg value="-class:${database-class-multi}" />
		</java>
	</target>

	<target name="build-single-db" depends="compile"
		description="Create a new database initialized with the single tenant application schema.">
		<java classname="net.metanotion.sql.BuildDb" classpathref="run.classpath" failonerror="true" fork="true">
			<arg value="-url:${db.server}" />
			<arg value="-user:${db.user}" />
			<arg value="-pass:${db.pass}" />
			<arg value="-database:${db.db-single}" />
			<arg value="-create" />
			<arg value="-dropFirst" />
			<arg value="-class:${database-class-single}" />
		</java>
	</target>

	<target name="add-test-users" depends="init" description="Add test users to the multitenant database.">
		<java classname="net.metanotion.sqlauthident.UserEditor" classpathref="run.classpath" fork="true">
			<arg value="-dbUrl:${db.server}${db.db-multi}" />
			<arg value="-dbUser:${db.user}" />
			<arg value="-dbPass:${db.pass}" />
			<arg value="-schema:admin" />
			<arg value="-file:${test-config}/users.json" />
		</java>
	</target>

	<target name="add-test-single-users" depends="init" description="Add test users to the single tenant database.">
		<java classname="net.metanotion.sqlauthident.UserEditor" classpathref="run.classpath" fork="true">
			<arg value="-dbUrl:${db.server}${db.db-single}" />
			<arg value="-dbUser:${db.user}" />
			<arg value="-dbPass:${db.pass}" />
			<arg value="-file:${test-config}/users.json" />
		</java>
	</target>
</project>


text:
<?php

declare(strict_types=1);

namespace generator\template;

use generator\helper\ClassHelper;

final class StereotypeFactory
{
    public static function create(array $params = []): StereoType|null
    {
        $obj = ClassHelper::create("generator\\template\\" . $type->name, $params);
        return ($obj instanceof StereoType) ? $obj : null;
    }
}


text:
package za.org.grassroot.services.exception;

/**
 * Created by luke on 2016/10/04.
 */
public class GroupSizeLimitExceededException extends RuntimeException {
}


text:
public class Foo {
  public static class Bar {}
}

class Goo {
  void test(){
    Supplier<Foo.Bar> s = () -> new Foo.Bar();
  }
}

interface Supplier<T> {
  T get();
}


text:
package co.cask.cdap.cli.command;

import co.cask.cdap.cli.ArgumentName;
import co.cask.cdap.cli.CLIConfig;
import co.cask.cdap.cli.ElementType;
import co.cask.cdap.cli.exception.CommandInputError;
import co.cask.cdap.cli.util.AbstractCommand;
import co.cask.cdap.cli.util.RowMaker;
import co.cask.cdap.cli.util.table.Table;
import co.cask.cdap.client.WorkflowClient;
import co.cask.cdap.common.NotFoundException;
import co.cask.cdap.common.UnauthenticatedException;
import co.cask.cdap.proto.WorkflowNodeStateDetail;
import co.cask.cdap.proto.id.ProgramRunId;
import co.cask.cdap.security.spi.authorization.UnauthorizedException;
import co.cask.common.cli.Arguments;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Command to get the node states associated with the Workflow run.
 */
public class GetWorkflowStateCommand extends AbstractCommand {
  private final ElementType elementType;
  private final WorkflowClient workflowClient;

  public GetWorkflowStateCommand(WorkflowClient workflowClient, CLIConfig cliConfig) {
    super(cliConfig);
    this.elementType = ElementType.WORKFLOW;
    this.workflowClient = workflowClient;
  }

  @Override
  public void perform(Arguments arguments, PrintStream printStream) throws Exception {
    String[] programIdParts = arguments.get(elementType.getArgumentName().toString()).split("\\.");

    if (programIdParts.length < 2) {
      throw new CommandInputError(this);
    }

    ProgramRunId programRunId = cliConfig.getCurrentNamespace().app(programIdParts[0]).workflow(programIdParts[1])
      .run(arguments.get(ArgumentName.RUN_ID.toString()));

    Table table = getWorkflowNodeStates(programRunId);
    cliConfig.getTableRenderer().render(cliConfig, printStream, table);
  }

  @Override
  public String getPattern() {
    return String.format("get workflow state <%s> <%s>", elementType.getArgumentName(), ArgumentName.RUN_ID);
  }

  @Override
  public String getDescription() {
    return "Gets the state of all nodes associated with the workflow for a given run id.";
  }

  private Table getWorkflowNodeStates(ProgramRunId programRunId)
    throws UnauthenticatedException, IOException, NotFoundException, UnauthorizedException {
    Map<String, WorkflowNodeStateDetail> workflowNodeStates = workflowClient.getWorkflowNodeStates(programRunId);
    List<Map.Entry<String, WorkflowNodeStateDetail>> nodeStates = new ArrayList<>();
    nodeStates.addAll(workflowNodeStates.entrySet());
    return Table.builder()
      .setHeader("node id", "node status", "runid", "failurecause")
      .setRows(nodeStates, new RowMaker<Map.Entry<String, WorkflowNodeStateDetail>>() {
        @Override
        public List<?> makeRow(Map.Entry<String, WorkflowNodeStateDetail> object) {
          return Lists.newArrayList(object.getValue().getNodeId(), object.getValue().getNodeStatus(),
                                    object.getValue().getRunId(), object.getValue().getFailureCause());
        }
      }).build();
  }
}