text:
using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.Common;
using MonoTorrent.Client.Messages;
using MonoTorrent.Client.Messages.Standard;
using MonoTorrent.Client.Messages.FastPeer;

namespace MonoTorrent.Client
{
    public class StandardPicker : PiecePicker
    {
        struct BinaryIndexComparer : IComparer<Piece>
        {
            int index;
            public BinaryIndexComparer(int index)
            {
                this.index = index;
            }

            public int Compare(Piece x, Piece y)
            {
                if (x == null)
                    return index.CompareTo(y.Index);
                return x.Index.CompareTo(index);
            }
        }

        static Predicate<Block> TimedOut = delegate(Block b) { return b.RequestTimedOut; };

        protected SortList<Piece> requests;

        public StandardPicker()
            : base(null)
        {
            requests = new SortList<Piece>();
        }

        public override void CancelRequest(PeerId peer, int piece, int startOffset, int length)
        {
            CancelWhere(delegate(Block b)
            {
                return b.StartOffset == startOffset &&
                       b.RequestLength == length &&
                       b.PieceIndex == piece &&
                       peer.Equals(b.RequestedOff);
            });
        }

        public override void CancelRequests(PeerId peer)
        {
            CancelWhere(delegate(Block b) { return peer.Equals(b.RequestedOff); });
        }

        public override void CancelTimedOutRequests()
        {
            CancelWhere(TimedOut);
        }

        void CancelWhere(Predicate<Block> predicate)
        {
            bool cancelled = false;
            requests.ForEach(delegate(Piece p) {
                for (int i = 0; i < p.Blocks.Length; i++) {
                    if (predicate(p.Blocks[i]) && !p.Blocks[i].Received) {
                        cancelled = true;
                        p.Blocks[i].CancelRequest();
                    }
                }
            });

            if (cancelled)
                requests.RemoveAll(delegate(Piece p) { return p.NoBlocksRequested; });
        }

        public override int CurrentRequestCount()
        {
            return (int)Toolbox.Accumulate<Piece>(requests, delegate(Piece p) { return p.TotalRequested - p.TotalReceived; });
        }

        public override List<Piece> ExportActiveRequests()
        {
            return new List<Piece>(requests);
        }

        public override void Initialise(BitField bitfield, TorrentFile[] files, IEnumerable<Piece> requests)
        {
            this.requests.Clear();
            foreach (Piece p in requests)
                this.requests.Add(p);
        }

        public override bool IsInteresting(BitField bitfield)
        {
            return !bitfield.AllFalse;
        }

        public override MessageBundle PickPiece(PeerId id, BitField peerBitfield, List<PeerId> otherPeers, int count, int startIndex, int endIndex)
        {
            RequestMessage message;
            MessageBundle bundle = null;
            // If there is already a request on this peer, try to request the next block. If the peer is choking us, then the only
            // requests that could be continued would be existing "Fast" pieces.
            if ((message = ContinueExistingRequest(id)) != null)
                return (bundle = new MessageBundle(message));

            // Then we check if there are any allowed "Fast" pieces to download
            if (id.IsChoking && (message = GetFromList(id, peerBitfield, id.IsAllowedFastPieces)) != null)
                return (bundle = new MessageBundle(message));

            // If the peer is choking, then we can't download from them as they had no "fast" pieces for us to download
            if (id.IsChoking)
                return null;

            // If we are only requesting 1 piece, then we can continue any existing. Otherwise we should try
            // to request the full amount first, then try to continue any existing.
            if (count == 1 && (message = ContinueAnyExisting(id)) != null)
                return (bundle = new MessageBundle(message));

            // We see if the peer has suggested any pieces we should request
            if ((message = GetFromList(id, peerBitfield, id.SuggestedPieces)) != null)
                return (bundle = new MessageBundle(message));

            // Now we see what pieces the peer has that we don't have and try and request one
            if ((bundle = GetStandardRequest(id, peerBitfield, otherPeers, startIndex, endIndex, count)) != null)
                return bundle;

            // If all else fails, ignore how many we're requesting and try to continue any existing
            if ((message = ContinueAnyExisting(id)) != null)
                return (bundle = new MessageBundle(message));

            return null;
        }

        public override void Reset()
        {
            requests.Clear();
        }

        public override bool ValidatePiece(PeerId id, int pieceIndex, int startOffset, int length, out Piece piece)
        {
            //Comparer.index = pieceIndex;
            int pIndex = requests.BinarySearch(null, new BinaryIndexComparer(pieceIndex));
            if (pIndex < 0)
            {
                piece = null;
                Logger.Log(null, "Validating: {0} - {1}: ", pieceIndex, startOffset);
                Logger.Log(null, "No piece");
                return false;
            }
            piece = requests[pIndex];
            // Pick out the block that this piece message belongs to
            int blockIndex = Block.IndexOf(piece.Blocks, startOffset, length);
            if (blockIndex == -1 || !id.Equals(piece.Blocks[blockIndex].RequestedOff))
            {
                Logger.Log (null, "Validating: {0} - {1}: ", pieceIndex, startOffset);
                Logger.Log (null, "no block");
                return false;
            }
            if (piece.Blocks[blockIndex].Received)
            {
                Logger.Log (null, "Validating: {0} - {1}: ", pieceIndex, startOffset);
                Logger.Log (null, "received");
                return false;
            }
            if (!piece.Blocks[blockIndex].Requested)
            {
                Logger.Log (null, "Validating: {0} - {1}: ", pieceIndex, startOffset);
                Logger.Log (null, "not requested");
                return false;
            }
            id.AmRequestingPiecesCount--;
            piece.Blocks[blockIndex].Received = true;

            if (piece.AllBlocksReceived)
                requests.RemoveAt(pIndex);
            return true;
        }

        public override RequestMessage ContinueExistingRequest(PeerId id)
        {
            for (int req = 0; req < requests.Count; req++)
            {
                Piece p = requests[req];
                // For each piece that was assigned to this peer, try to request a block from it
                // A piece is 'assigned' to a peer if he is the first person to request a block from that piece
                if (p.AllBlocksRequested || !id.Equals(p.Blocks[0].RequestedOff))
                    continue;

                for (int i = 0; i < p.BlockCount; i++)
                {
                    if (p.Blocks[i].Requested || p.Blocks[i].Received)
                        continue;

                    p.Blocks[i].Requested = true;
                    return p.Blocks[i].CreateRequest(id);
                }
            }

            // If we get here it means all the blocks in the pieces being downloaded by the peer are already requested
            return null;
        }

        protected RequestMessage ContinueAnyExisting(PeerId id)
        {
            // If this peer is currently a 'dodgy' peer, then don't allow him to help with someone else's
            // piece request.
            if (id.Peer.RepeatedHashFails != 0)
                return null;

            // Otherwise, if this peer has any of the pieces that are currently being requested, try to
            // request a block from one of those pieces
            foreach (Piece p in this.requests)
            {
                // If the peer who this piece is assigned to is dodgy or if the blocks are all request or
                // the peer doesn't have this piece, we don't want to help download the piece.
                if (p.AllBlocksRequested || p.AllBlocksReceived || !id.BitField[p.Index] ||
                    (p.Blocks[0].RequestedOff != null && p.Blocks[0].RequestedOff.Peer.RepeatedHashFails != 0))
                    continue;

                for (int i = 0; i < p.Blocks.Length; i++)
                    if (!p.Blocks[i].Requested && !p.Blocks[i].Received)
                    {
                        p.Blocks[i].Requested = true;
                        return p.Blocks[i].CreateRequest(id);
                    }
            }

            return null;
        }

        protected RequestMessage GetFromList(PeerId id, BitField bitfield, IList<int> pieces)
        {
            if (!id.SupportsFastPeer || !ClientEngine.SupportsFastPeer)
                return null;

            for (int i = 0; i < pieces.Count; i++)
            {
                int index = pieces[i];
                // A peer should only suggest a piece he has, but just in case.
                if (index >= bitfield.Length || !bitfield[index] || AlreadyRequested(index))
                    continue;

                pieces.RemoveAt(i);
                Piece p = new Piece(index, id.TorrentManager.Torrent.PieceLength, id.TorrentManager.Torrent.Size);
                this.requests.Add(p);
                p.Blocks[0].Requested = true;
                return p.Blocks[0].CreateRequest(id);
            }

            return null;
        }

        protected virtual MessageBundle GetStandardRequest(PeerId id, BitField current, List<PeerId> otherPeers, int startIndex, int endIndex, int count)
        {
            int piecesNeeded = (count * Piece.BlockSize) / id.TorrentManager.Torrent.PieceLength;
            if ((count * Piece.BlockSize) % id.TorrentManager.Torrent.PieceLength != 0)
                piecesNeeded++;
            int checkIndex = CanRequest(current, startIndex, endIndex, ref piecesNeeded);

            // Nothing to request.
            if (checkIndex == -1)
                return null;

            MessageBundle bundle = new MessageBundle();
            for (int i = 0; bundle.Messages.Count < count && i < piecesNeeded; i++)
            {
                // Request the piece
                Piece p = new Piece(checkIndex + i, id.TorrentManager.Torrent.PieceLength, id.TorrentManager.Torrent.Size);
                requests.Add(p);

                for (int j = 0; j < p.Blocks.Length && bundle.Messages.Count < count; j++)
                {
                    p.Blocks[j].Requested = true;
                    bundle.Messages.Add(p.Blocks[j].CreateRequest(id));
                }
            }
            return bundle;
        }

        protected bool AlreadyRequested(int index)
        {
            return requests.BinarySearch(null, new BinaryIndexComparer(index)) >= 0;
        }

        private int CanRequest(BitField bitfield, int pieceStartIndex, int pieceEndIndex, ref int pieceCount)
        {
            int largestStart=0;
            int largestEnd=0;
            while ((pieceStartIndex = bitfield.FirstTrue(pieceStartIndex, pieceEndIndex)) != -1)
            {
                int end = bitfield.FirstFalse(pieceStartIndex, pieceEndIndex);
                if (end == -1)
                    end = Math.Min(pieceStartIndex + pieceCount, bitfield.Length);

                for (int i = pieceStartIndex; i < end; i++)
                    if (AlreadyRequested(i))
                        end = i;

                if ((end - pieceStartIndex) >= pieceCount)
                    return pieceStartIndex;

                if ((largestEnd - largestStart) < (end - pieceStartIndex))
                {
                    largestStart = pieceStartIndex;
                    largestEnd = end;
                }

                pieceStartIndex = Math.Max(pieceStartIndex + 1, end);
            }

            pieceCount = largestEnd - largestStart;
            return pieceCount == 0 ? -1 : largestStart;
        }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller
{
	function __construct()
	{
    parent::__construct();

    if($this->session->userdata('logged_in_user') == 1)
    {
      $this->load->model('User_model');
    }
    else
    {
      if($this->session->flashdata('username'))
      {
        $this->load->model('User_model');
        $username = $this->session->flashdata('username');
        $data['details'] = $this->User_model->get_user_details($username);
        foreach($data['details'] as $row)
        {
        $sessiondata = array('id'=>$row->user_id,
                            'user_name'=>$row->user_username,
                            'firstname'=>$row->user_firstname,
                             'middlename'=>$row->user_middlename,
                             'lastname'=>$row->user_lastname,
                             'department'=>$row->user_department,
                             'picture'=>$row->user_picture,
                             'logged_in_user'=>true
                            );
        }
        $this->session->set_userdata($sessiondata);
      }
      else
      {
  		   redirect('Login', 'refresh');
      }
    }
  }

  //===========================END===========================================//
  //=========================DASHBOARD====================================//

  function index()
  {
    $header['active_head'] = '';
    $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
    $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
    if($hasunread)
      $header['ihasunread'] = 1;
    else
      $header['ihasunread'] = 0;
    $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
    if($annunread)
      $header['ihasunreadann'] = 1;
    else
      $header['ihasunreadann'] = 0;
    $ID = $this->session->userdata['id'];
		$data['todolist'] = $this->User_model->get_todolist($ID);
    $this->load->view('User/user_header',$header);
    $this->load->view('User/user_index',$data);
  }

  function submit_todolist()
  {
    $data = array(
                  'todo_title'=>$this->input->post('title'),
                  'todo_employee_id_fk'=>$this->session->userdata['id'],
                  'todo_isfinished'=>0
                );

      $this->User_model->submit_todolist($data);
      redirect(base_url().'User');

  }

  function delete_one_todo()
  {
    $ID = $this->uri->segment(3);
    $this->User_model->delete_one_todo($ID);
  }

  function process_todo()
  {
    $ID = $this->uri->segment(3);

    $data['details'] = $this->User_model->todo_check($ID);
    foreach($data['details'] as $row)
    {
      if($row->todo_isfinished == 1)
      {
        $data = array('todo_isfinished'=>0);
      }else
      {
        $data = array('todo_isfinished'=>1);
      }
    }
    $this->User_model->process_todo($data,$ID);
  }

  //============================PROFILE===================================//
  function user_profile()
  {
    $header['active_head'] = '';
    $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
    $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
    if($hasunread)
      $header['ihasunread'] = 1;
    else
      $header['ihasunread'] = 0;
    $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
    if($annunread)
      $header['ihasunreadann'] = 1;
    else
      $header['ihasunreadann'] = 0;

    $ID = $this->session->userdata['id'];
		$data['userDetails'] = $this->User_model->get_one_user($ID);
      //var_dump($this->session->all_userdata());
    $this->load->view('User/user_header',$header);
    $this->load->view('User/user_user_profile',$data);
  }

  function submit_edit_one_user()
  {
      $id = $this->input->post('id');

      $uname = $this->input->post('uname');
      $firstname = $this->input->post('fname');
      $middlename = $this->input->post('mname');
      $lastname = $this->input->post('lname');
      $bday = $this->input->post('bday');
      $gender = $this->input->post('gender');
      $aboutme = $this->input->post('aboutme');
      $email = $this->input->post('email');
      $address = $this->input->post('address');
      $phone = $this->input->post('phone');
      $googleplus = $this->input->post('googleplus');
      $linkedin = $this->input->post('linkedin');
      $wordpress = $this->input->post('wordpress');
      $picture = $this->input->post('display_pic');

      $check = $this->input->post('check');

      if($check == 0)
      {
        $this->session->unset_userdata('user_name');
        $this->session->unset_userdata('firstname');
        $this->session->unset_userdata('middlename');
        $this->session->unset_userdata('lastname');

        $data = array('user_username'=>$uname,
                      'user_firstname'=>$firstname,
                      'user_middlename'=>$middlename,
                      'user_lastname'=>$lastname,
                      'user_birthday'=>$bday,
                      'user_gender'=>$gender,
                      'user_aboutme'=>$aboutme,
                      'user_email'=>$email,
                      'user_address'=>$address,
                      'user_cpnumber'=>$phone,
                      'user_google'=>$googleplus,
                      'user_linkedin'=>$linkedin,
                      'user_wordpress'=>$wordpress
                    );
          $this->session->set_userdata('user_name',$uname);
          $this->session->set_userdata('firstname',$firstname);
          $this->session->set_userdata('middlename',$middlename);
          $this->session->set_userdata('lastname',$lastname);

          //setall
          $this->User_model->edit_one_user_profile($data, $id);
        //var_dump($check);
        redirect(base_url().'User/user_profile');
        print_r($this->session->userdata());
      }

      else if ($check == 1)
      {
            $config['upload_path']          = getcwd().'\\assets\\files\\profile_pictures\\';
            $config['allowed_types']        = 'gif|jpg|png';

            $this->load->library('upload', $config);

            if ( ! $this->upload->do_upload('display_pic'))
            {
                    $error = array('error' => $this->upload->display_errors());
                    var_dump($error);
            }
            else
            {
                $this->session->unset_userdata('username');
                $this->session->unset_userdata('firstname');
                $this->session->unset_userdata('middlename');
                $this->session->unset_userdata('lastname');
                $this->session->unset_userdata('picture');

                $success = array('upload_data' => $this->upload->data());

                $add = './assets/files/profile_pictures/';
                $data = array('user_username'=>$uname,
                              'user_firstname'=>$firstname,
                              'user_middlename'=>$middlename,
                              'user_lastname'=>$lastname,
                              'user_birthday'=>$bday,
                              'user_gender'=>$gender,
                              'user_aboutme'=>$aboutme,
                              'user_email'=>$email,
                              'user_address'=>$address,
                              'user_cpnumber'=>$phone,
                              'user_google'=>$googleplus,
                              'user_linkedin'=>$linkedin,
                              'user_wordpress'=>$wordpress,
                              'user_picture'=>$add.$success['upload_data']['raw_name'].$success['upload_data']['file_ext']
                            );

                            $picture = $add.$success['upload_data']['raw_name'].$success['upload_data']['file_ext'];

                            $this->session->set_userdata('username',$username);
                            $this->session->set_userdata('firstname',$firstname);
                            $this->session->set_userdata('middlename',$middlename);
                            $this->session->set_userdata('lastname',$lastname);
                            $this->session->set_userdata('picture',$picture);

                            var_dump($success);
                            $this->User_model->edit_one_user_profile($data, $id);
                            redirect(base_url().'User/user_profile');
                            print_r($this->session->all_userdata());
              }
      }
      }

      function change_password()
      {
        $data['password'] = $this->User_model->check_password($this->input->post('userid'));
        if($data['password'])
        {
          foreach($data['password'] as $h)
          {
            $hash = $h->user_password;
          }

          if ($this->input->post('oldpassword')==$this->input->post('newpassword'))
          {
            echo 2;
          }
          else {
            if (password_verify($this->input->post('oldpassword'), $hash))
            {

              $id = $this->input->post('userid');
              $data = array('user_password'=>password_hash($this->input->post('newpassword'), PASSWORD_DEFAULT));

              $this->User_model->update_password($data,$id);

              echo 1;
             }else
              {
                echo 0;
              }
          }

    	}

  }

  function view_other_profile()
  {
    $header['active_head'] = '';
    $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
    $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
    if($hasunread)
      $header['ihasunread'] = 1;
    else
      $header['ihasunread'] = 0;
    $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
    if($annunread)
      $header['ihasunreadann'] = 1;
    else
      $header['ihasunreadann'] = 0;

    $ID = $this->uri->segment(3);
		$data['userDetails'] = $this->User_model->get_one_user($ID);
      //var_dump($this->session->all_userdata());
    $this->load->view('User/user_header',$header);
    $this->load->view('User/user_view_other_profile',$data);
  }
  //============================ANNOUNCEMEntS===================================//
  function announcements()
  {
    $header['active_head'] = '';
    $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
    $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
    if($hasunread)
      $header['ihasunread'] = 1;
    else
      $header['ihasunread'] = 0;
    $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
    if($annunread)
      $header['ihasunreadann'] = 1;
    else
      $header['ihasunreadann'] = 0;
    $dept = $this->session->userdata['department'];
    $data['announcements'] = $this->User_model->get_announce($dept);
    $this->User_model->set_read_announcements($this->session->userdata['id']);
    $this->load->view('User/user_header',$header);
    $this->load->view('User/user_announcements',$data);
  }

//============================GALLERY===================================//
function gallery()
{
  $header['active_head'] = 'gallery';
  $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
  $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
  if($hasunread)
    $header['ihasunread'] = 1;
  else
    $header['ihasunread'] = 0;
  $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
  if($annunread)
    $header['ihasunreadann'] = 1;
  else
    $header['ihasunreadann'] = 0;
  $data['gallery'] = $this->User_model->get_all_gallery();
  $this->load->view('User/user_header',$header);
  $this->load->view('User/user_gallery',$data);
}

function view_gallery()
{
  $header['active_head'] = 'gallery';
  $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
  $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
  if($hasunread)
    $header['ihasunread'] = 1;
  else
    $header['ihasunread'] = 0;
  $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
  if($annunread)
    $header['ihasunreadann'] = 1;
  else
    $header['ihasunreadann'] = 0;
  $id = $this->uri->segment(3);
  $data['gallery'] = $this->User_model->get_specific_gallery($id);
  foreach($data['gallery'] as $d)
  {
    $data['galleryname'] = $d->gfolder_name;
  }
  $data['galleryid'] = $id;
  $data['users'] = $this->User_model->get_users();
  $this->load->view('User/user_header',$header);
  $this->load->view('User/user_gallery_view',$data);
}

function upload_pictures()
{
  $header['active_head'] = 'gallery';
  $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
  $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
  if($hasunread)
    $header['ihasunread'] = 1;
  else
    $header['ihasunread'] = 0;
  $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
  if($annunread)
    $header['ihasunreadann'] = 1;
  else
    $header['ihasunreadann'] = 0;
  $use['gallery'] = $this->User_model->get_gallery_names();
  $data['gallery'] = array();
  foreach($use['gallery'] as $key => $value)
  {
    $data['gallerynew'][] = $value->gfolder_name;
  }

  $use['galleryid'] = $this->uri->segment(3);
  $use['galleryname'] = $this->User_model->get_gallery_name($use['galleryid']);
  foreach($use['galleryname'] as $u)
  {
    $data['galleryname'] = $u->gfolder_name;
  }
  $this->load->view('User/user_header',$header);
  $this->load->view('User/user_gallery_upload', $data);
}

function do_Upload_gallery()
 {
     $this->load->helper('inflector');
   $gallery = $this->input->post('gallery');
   $count = 1;
   $data['check'] = $this->User_model->check_existing_gallery($gallery);
   if($data['check'])
   {
     foreach($data['check'] as $d)
     {
       $gfolder_id = $d->gfolder_id;
     }
   }
   else
   {
     $data = array('gfolder_name'=>$gallery);
     $gfolder_id = $this->User_model->insert_new_gfolder($data);
     if (!file_exists( './assets/files/gallery/'.$gallery))
     {
      mkdir( './assets/files/gallery/'.$gallery, 0777, true);
    }
   }

   foreach($_FILES['file']['tmp_name'] as $index => $f)
   {
   $target_dir =  './assets/files/gallery/'.$gallery."/";
   $target_file = $target_dir . basename($_FILES["file"]["name"][$index]);
   $uploadOk = 1;
   $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
   $newname = $_FILES["file"]["name"][$index];
   $files_name = $_FILES["file"]["name"][$index];
   // Check if image file is a actual image or fake image
   if(isset($_POST["submit"])) {
       $check = getimagesize($_FILES["file"]["tmp_name"][$index]);
       if($check !== false) {
           echo "File is an image - " . $check["mime"] . ".";
           $uploadOk = 1;
       } else {
           echo "File is not an image.";
           $uploadOk = 0;
       }
   }
   // Check if file already exists
   if (file_exists($target_file)) {
     $name = $_FILES['file']['name'][$index];
     $actual_name = pathinfo($name,PATHINFO_FILENAME);
     $original_name = $actual_name;
     $extension = pathinfo($name, PATHINFO_EXTENSION);

     $i = 1;
     while(file_exists($target_dir.$actual_name.".".$extension))
     {
         $actual_name = (string)$original_name.'_'.$i;
         $files_name = $actual_name;
         $target_file = $target_dir.$actual_name.".".$extension;
         $i++;
     }
       $uploadOk = 1;
   }
   // Check file size
   // Check if $uploadOk is set to 0 by an error
   if ($uploadOk == 0) {
       echo "Sorry, your file was not uploaded.";
   // if everything is ok, try to upload file
   } else {

       if (move_uploaded_file($_FILES["file"]["tmp_name"][$index], $target_file)) {

          $this->create_thumbnail($target_file);
           $data = array('picture_name'=>$newname,
                          'picture_path'=>$target_file,
                          'picture_uploader_id'=>$this->session->userdata['id'],
                          'gfolder_id_fk'=>$gfolder_id);

            $this->User_model->insert_gallery_pictures($data);
            if($count == 1)
            {
              echo $gfolder_id;
            }
            else
            {
              //Do nothing
            }
            $count++;
       } else {
           echo "Sorry, there was an error uploading your file.";
       }
   }
 }

 }

   function create_thumbnail($target_file)
   {
     $this->load->library('image_lib');
     $config['image_library'] = 'gd2';
     $config['source_image'] = $target_file;
     $config['create_thumb'] = TRUE;
     $config['width']         = 500;
     $config['height']       = 500;

     $this->image_lib->initialize($config);
     $this->image_lib->resize();
   }

   function delete_one_picture()
   {
     $id = $this->uri->segment(3);
     $data['details'] = $this->User_model->get_one_picture($id);
     foreach($data['details'] as $d)
     {
       $path = $d->picture_path;
     }
     unlink($path);
     $this->User_model->delete_one_picture_model($id);
   }

   function manage_gallery()
   {
     $header['active_head'] = 'gallery';
     $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
     $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
     if($hasunread)
       $header['ihasunread'] = 1;
     else
       $header['ihasunread'] = 0;
     $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
     if($annunread)
       $header['ihasunreadann'] = 1;
     else
       $header['ihasunreadann'] = 0;
     $id = $this->uri->segment(3);
     $data['gallery'] = $this->User_model->get_specific_gallery_with_user_uploads($id,$this->session->userdata['id']);
     if($data['gallery'])
     {
       foreach($data['gallery'] as $d)
       {
         $data['galleryname'] = $d->gfolder_name;
       }
       $data['galleryid'] = $id;
       $this->load->view('User/user_header',$header);
       $this->load->view('User/user_gallery_manage',$data);
     }
     else
     {
       $this->session->set_flashdata('notify',"<script>
          new PNotify({
           title: 'Error',
           text: 'No pictures uploaded by you.',
           type: 'error'
        });
       </script>");
       redirect('User/view_gallery/'.$id);
     }
   }

   function delete_pictures()
   {
     foreach($this->input->post('pictures') as $id)
     {
       $data['details'] = $this->User_model->get_one_picture($id);
       foreach($data['details'] as $d)
       {
         $path = $d->picture_path;
         $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $d->picture_path);
         $ext = pathinfo($d->picture_path, PATHINFO_EXTENSION);
         $picture_name = $withoutExt.'_thumb.'.$ext;
         unlink($picture_name);
         unlink($path);
       }
       $this->User_model->delete_one_picture_model($id);
     }
     redirect('User/manage_gallery/'.$this->input->post('return'));
   }

   //===============================VIDEOS=======================================//
   function upload_videos()
   {
     $header['active_head'] = 'gallery';
     $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
     $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
     if($hasunread)
       $header['ihasunread'] = 1;
     else
       $header['ihasunread'] = 0;
     $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
     if($annunread)
       $header['ihasunreadann'] = 1;
     else
       $header['ihasunreadann'] = 0;
     $use['vfolder_name'] = $this->User_model->get_videos_folder();
     $data['vfolder_name'] = array();
     foreach($use['vfolder_name'] as $key => $value)
     {
       $data['vfolder_name'][] = $value->vfolder_name;
     }

     $use['vfolder_id'] = $this->uri->segment(3);
     $use['vfoldername'] = $this->User_model->get_videos_folder_name($use['vfolder_id']);
     foreach($use['vfoldername'] as $u)
     {
       $data['vfoldername'] = $u->vfolder_name;
     }
     $this->load->view('User/user_header',$header);
     $this->load->view('User/user_videos_upload', $data);
   }

   function do_upload_videos()
    {
      $this->load->helper('inflector');
      $videofolder = $this->input->post('gallery');
      $count = 1;
      $data['check'] = $this->User_model->check_existing_video_folder($videofolder);
      if($data['check'])
      {
        foreach($data['check'] as $d)
        {
          $vfolder_id = $d->vfolder_id;
        }
      }
      else
      {
        $data = array('vfolder_name'=>$videofolder);
        $vfolder_id = $this->User_model->insert_new_vfolder($data);
        mkdir( './assets/files/videos/'.$videofolder, 0777, true);
      }

      foreach($_FILES['file']['tmp_name'] as $index => $f)
      {
      $target_dir =  './assets/files/videos/'.$videofolder."/";
      $target_file = $target_dir . basename($_FILES["file"]["name"][$index]);
      $uploadOk = 1;
      $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
      $newname = $_FILES["file"]["name"][$index];
      $files_name = $_FILES["file"]["name"][$index];
      $actual_name = pathinfo($newname,PATHINFO_FILENAME);
      // Check if image file is a actual image or fake image
      // Check if file already exists
      if (file_exists($target_file)) {
        $name = $_FILES['file']['name'][$index];
        $actual_name = pathinfo($name,PATHINFO_FILENAME);
        $original_name = $actual_name;
        $extension = pathinfo($name, PATHINFO_EXTENSION);

        $i = 1;
        while(file_exists($target_dir.$actual_name.".".$extension))
        {
            $actual_name = (string)$original_name.'_'.$i;
            $files_name = $actual_name;
            $target_file = $target_dir.$actual_name.".".$extension;
            $i++;
        }
          $uploadOk = 1;
      }
      // Check file size

      // Check if $uploadOk is set to 0 by an error
      if ($uploadOk == 0) {
          echo "Sorry, your file was not uploaded.";
      // if everything is ok, try to upload file
      } else {

          if (move_uploaded_file($_FILES["file"]["tmp_name"][$index], $target_file)) {

            $this->create_thumbnail_videos($target_file, $target_dir.$actual_name.'.png');

              $data = array('video_name'=>$newname,
                             'video_path'=>$target_file,
                             'video_uploader_id'=>$this->session->userdata['id'],
                             'vfolder_id_fk'=>$vfolder_id);

               $this->User_model->insert_videos($data);
               if($count == 1)
               {
                 echo $vfolder_id;
               }
               else
               {
                 //Do nothing
               }
               $count++;
          } else {
              echo "Sorry, there was an error uploading your file.";
          }
      }
    }

    }

    function create_thumbnail_videos($target_file,$destFile)
    {
      // Change the path according to your server.
       $ffmpeg_path = './assets/ffmpeg/bin/';
       $target_file = '"'.$target_file.'"';
       $destFile = '"'.$destFile.'"';
       $output = array();

       $cmd = sprintf('%sffmpeg -i %s -an -ss 00:00:05 -r 1 -vframes 1 -y %s',
           $ffmpeg_path, $target_file, $destFile);
       if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
           $cmd = str_replace('/', DIRECTORY_SEPARATOR, $cmd);
       else
           $cmd = str_replace('\\', DIRECTORY_SEPARATOR, $cmd);

       exec($cmd, $output, $retval);

       if ($retval)
           return false;

       return $destFile;
    }

    function videos()
    {
      $header['active_head'] = 'gallery';
      $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
      $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
      if($hasunread)
        $header['ihasunread'] = 1;
      else
        $header['ihasunread'] = 0;
      $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
      if($annunread)
        $header['ihasunreadann'] = 1;
      else
        $header['ihasunreadann'] = 0;
      $data['videos'] = $this->User_model->get_all_videos();
      $this->load->view('User/user_header',$header);
      $this->load->view('User/user_videos',$data);
    }

    function view_videos()
    {
      $header['active_head'] = 'gallery';
      $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
      $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
      if($hasunread)
        $header['ihasunread'] = 1;
      else
        $header['ihasunread'] = 0;
      $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
      if($annunread)
        $header['ihasunreadann'] = 1;
      else
        $header['ihasunreadann'] = 0;
      $id = $this->uri->segment(3);
      $data['videos'] = $this->User_model->get_specific_videos($id);
      foreach($data['videos'] as $d)
      {
        $data['galleryname'] = $d->vfolder_name;
      }
      $data['galleryid'] = $id;
      $data['users'] = $this->User_model->get_users();
      $this->load->view('User/user_header',$header);
      $this->load->view('User/user_videos_view',$data);
    }

    function manage_videos()
    {
      $header['active_head'] = 'gallery';
      $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
      $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
      if($hasunread)
        $header['ihasunread'] = 1;
      else
        $header['ihasunread'] = 0;
      $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
      if($annunread)
        $header['ihasunreadann'] = 1;
      else
        $header['ihasunreadann'] = 0;
      $id = $this->uri->segment(3);
      $data['videos'] = $this->User_model->get_specific_videos_with_useruploads($id,$this->session->userdata['id']);
      if($data['videos'])
      {
        foreach($data['videos'] as $d)
        {
          $data['galleryname'] = $d->vfolder_name;
        }
        $data['galleryid'] = $id;
        $this->load->view('User/user_header',$header);
        $this->load->view('User/user_videos_manage',$data);
      }
      else
      {
        $this->session->set_flashdata('notify',"<script>
           new PNotify({
            title: 'Error',
            text: 'No videos uploaded by you.',
            type: 'error'
         });
        </script>");
        redirect('User/view_videos/'.$id);
      }
    }

    function delete_videos()
    {
      foreach($this->input->post('videos') as $id)
      {
        $data['details'] = $this->User_model->get_one_video($id);
        foreach($data['details'] as $d)
        {
          $path = $d->video_path;
          $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $d->video_path);
           $picture_name = $withoutExt.'.png.';
           unlink($picture_name);
           unlink($path);
        }
        $this->User_model->delete_one_video($id);
      }
      redirect('User/manage_videos/'.$this->input->post('return'));
    }

   //===========================FILES=====================//
   function view_files()
   {
     $header['active_head'] = 'upload_files';
     $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
     $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
     if($hasunread)
       $header['ihasunread'] = 1;
     else
       $header['ihasunread'] = 0;
     $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
     if($annunread)
       $header['ihasunreadann'] = 1;
     else
       $header['ihasunreadann'] = 0;
     $departmentid =  $this->session->userdata['department'];
     $data['folders'] = $this->User_model->get_folders_dept($departmentid);
     $data['departmentid'] = $departmentid;
     $this->load->view('User/user_header',$header);
     $this->load->view('User/user_files_view', $data);
   }

   function load_files()
   {
     $folderid = $this->uri->segment(3);
     $data['files'] = $this->User_model->get_files_folder($folderid);
     $data['departmentid'] = $this->session->userdata['department'];

     $get['foldername'] = $this->User_model->get_folder_name($folderid);
     foreach($get['foldername'] as $f)
     {
       $data['foldername'] = $f->ffolder_name;
       break;
     }
     $data['folderid'] = $folderid;
     $data['users'] = $this->User_model->get_user_names();
     $this->load->view('User/user_files_edit_modal');
     $this->load->view('User/user_files_content', $data);
   }

   function upload_files()
   {
       $header['active_head'] = 'files';
       $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
       $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
       if($hasunread)
         $header['ihasunread'] = 1;
       else
         $header['ihasunread'] = 0;
       $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
       if($annunread)
         $header['ihasunreadann'] = 1;
       else
         $header['ihasunreadann'] = 0;
       $data['foldernew'] = $this->User_model->get_folder_names_department($this->session->userdata['department']);
       $data['departments'] = $this->User_model->get_departments();
       $this->load->view('User/user_header',$header);
       $this->load->view('User/user_files_upload',$data);
   }

   function do_upload_files()
   {
       $this->load->helper('inflector');
       $foldername = $this->input->post('foldername');
       $maindept   = $this->input->post('maindept');
       $shareddept = explode(",",$this->input->post('shareddept'));
       $ffolder_id; //tblfiles_folder primary key

       $data['check'] = $this->User_model->check_existing_folder_department($foldername,$maindept);
       if($data['check'])
       {
         foreach($data['check'] as $d)
         {
           $ffolder_id = $d->ffolder_id;
         }
       }
       else
       {
         $data = array('ffolder_name'=>$foldername,
                       'ffolder_dept_id_fk'=>$maindept);
         $ffolder_id = $this->User_model->insert_new_ffolder($data);
         mkdir( './assets/files/documents/'.$foldername, 0777, true);
       }

       foreach($_FILES['file']['tmp_name'] as $index => $f)
       {
       $target_dir =  './assets/files/documents/'.$foldername."/";
       $target_file = $target_dir . basename($_FILES["file"]["name"][$index]);
       $uploadOk = 1;
       $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
       $newname = humanize(preg_replace('/\\.[^.\\s]{3,4}$/', '', $_FILES["file"]["name"][$index]));
       $files_name = $_FILES["file"]["name"][$index];
       // Check if image file is a actual image or fake image
       if(isset($_POST["submit"])) {
           $check = getimagesize($_FILES["file"]["tmp_name"][$index]);
           if($check !== false) {
               echo "File is an image - " . $check["mime"] . ".";
               $uploadOk = 1;
           } else {
               echo "File is not an image.";
               $uploadOk = 0;
           }
       }
       // Check if file already exists
       if (file_exists($target_file))
       {
         $name = $_FILES['file']['name'][$index];
         $actual_name = pathinfo($name,PATHINFO_FILENAME);
         $original_name = $actual_name;
         $extension = pathinfo($name, PATHINFO_EXTENSION);

         $i = 1;
         while(file_exists($target_dir.$actual_name.".".$extension))
         {
             $actual_name = (string)$original_name.'_'.$i;
             $files_name = $actual_name;
             $target_file = $target_dir.$actual_name.".".$extension;
             $i++;
         }
         echo $target_file;
         echo '<br>';
           echo $name;
           $uploadOk = 1;
       }
       // Check file size
       if ($_FILES["file"]["size"][$index] > 5000000) {
           echo "Sorry, your file is too large.";
           $uploadOk = 0;
       }
       // Check if $uploadOk is set to 0 by an error
       if ($uploadOk == 0) {
           echo "Sorry, your file was not uploaded.";
       // if everything is ok, try to upload file
       } else {

           if (move_uploaded_file($_FILES["file"]["tmp_name"][$index], $target_file)) {
             $data = array('files_display_name'=>$newname,
                           'files_user_id_fk'=>$this->session->userdata['id'],
                            'files_name'=>$files_name,
                            'files_path'=>$target_file,
                            'files_ffolder_id_fk'=>$ffolder_id);

              $this->User_model->insert_files_document($data);
           } else {
               echo "Sorry, there was an error uploading your file.";
           }
       }
     }
     foreach($shareddept as $key => $value)
     {
       if($key == 0)
       {

       }
       else
       {
         $data = array('shared_ffolder_id_fk'=>$ffolder_id,
                       'shared_dept_id_fk'=>$value);
         $this->User_model->insert_shared_documents($data);

       }
     }
   }

   function get_one_file()
   {
     $file_id = $this->uri->segment(3);
     $use['file'] = $this->User_model->get_one_file($file_id);
     foreach($use['file'] as $f)
     {
       $use['folder'] = $this->User_model->get_folder_name($f->files_ffolder_id_fk);
       foreach($use['folder'] as $u)
       {
           $foldername = $u->ffolder_name;
       }
       $data = array('id'=>$f->files_id,
                     'path'=>$f->files_path,
                     'display_name'=>$f->files_display_name,
                      'foldername'=>$foldername);
       break;
     }
     echo json_encode($data);
   }

     function download_one_file()
     {
       $id = $this->uri->segment(3);

       $data['file'] = $this->User_model->get_one_file($id);
       foreach($data['file'] as $d)
       {
         force_download($d->files_path, NULL);
       }
     }

     function delete_one_file()
     {
       $id = $this->uri->segment(3);

       $data['file'] = $this->User_model->get_one_file($id);
       foreach($data['file'] as $d)
       {
         unlink($d->files_path);
       }
       $data['archive'] = $this->User_model->get_archive_by_files_id($id);
       foreach($data['archive'] as $d)
       {
         unlink($d->archives_path);
       }
       $this->User_model->delete_archive_by_files_id($id);
       $this->User_model->delete_one_file($id);
     }

   function do_update_one_file()
   {
     $filechanged = $this->input->post('filechanged');

     $displayname = $this->input->post('displayname');
     $revision = $this->input->post('revision');
     $foldername = $this->input->post('foldername');
     $currentfileID = $this->input->post('old_file_id');

     if($filechanged == 1)
     {
       $target_dir =  './assets/files/documents/'.$foldername."/";

       $config['upload_path'] = $target_dir;
       $config['allowed_types'] = '*';

       $this->load->library('upload', $config);

       if (!$this->upload->do_upload('file'))
       {
           $status = 'error';
           $msg = $this->upload->display_errors('', '');
       }
       else
       {
           $success = array('upload_data' => $this->upload->data());

           $use['oldfile'] = $this->User_model->get_one_file($currentfileID);
           foreach($use['oldfile'] as $u)
           {
             $data = array('archive_path'=>$u->files_path,
                           'archive_display_name'=>$u->files_display_name,
                           'archive_version'=>$u->files_version,
                           'archive_user_id_fk'=>$u->files_user_id_fk,
                           'archive_timestamp'=>$u->files_timestamp,
                           'archive_files_id_fk'=>$u->files_id);
             $ffolder_id = $u->files_ffolder_id_fk;
             $files_id = $u->files_id;
             $current_version = $u->files_version;
           }

           $this->User_model->insert_file_archive($data);
           $final_version = '';
           if($revision == 0)
           {
             $add_version = 0.01;
             $added_version = $current_version + $add_version;
             $final_version = number_format($added_version, 2, '.' ,'');
           }
           else
           {
             $whole = floor($current_version);
             $decimal = $current_version - $whole;

             if($decimal == 0)
             {
             	$current_version += 0.01;
             	$final_version =  number_format(ceil($current_version), 1, '.' ,'');
             }
             else
             {
             	$final_version =  number_format(ceil($current_version), 1, '.' ,'');
             }
           }

           $data = array('files_display_name'=>$displayname,
                         'files_version'=>$final_version,
                         'files_user_id_fk'=>$this->session->userdata['id'],
                          'files_name'=>$success['upload_data']['file_name'],
                          'files_path'=>$success['upload_data']['full_path']);

            $this->User_model->update_file_contents($data,$files_id);

       }
       if($this->input->post('shared') == 1)
       {
         $isshared = 1;
       }
       else
       {
         $isshared = 0;
       }
       echo json_encode(array('isshared' => $isshared,'id' => $currentfileID, 'displayname' => $displayname, 'version' => $final_version, 'updatedname' =>"<p class=\"help-block\">Updated by:<a href=\"".base_url()."User/view_other_profile/{$this->session->userdata['id']}\">{$this->session->userdata['firstname']} {$this->session->userdata['lastname']}</a></p>"));
    }
     else
     {
       $use['oldfile'] = $this->User_model->get_one_file($currentfileID);
       foreach($use['oldfile'] as $u)
       {
         $current_version = $u->files_version;
       }
       $data = array('files_display_name'=>$displayname);

       $this->User_model->update_file_contents($data,$currentfileID);
       if($this->input->post('shared') == 1)
       {
         $isshared = 1;
       }
       else
       {
         $isshared = 0;
       }
       echo json_encode(array('isshared' => $isshared,'id' => $currentfileID, 'displayname' => $displayname, 'version' => $final_version, 'updatedname' =>"<p class=\"help-block\">Updated by:<a href=\"".base_url()."User/view_other_profile/{$this->session->userdata['id']}\">{$this->session->userdata['firstname']} {$this->session->userdata['lastname']}</a></p>"));
    }
   }

   function load_archive()
   {
     $filesid = $this->uri->segment(3);
     $data['archive'] = $this->User_model->get_files_archive($filesid);
     $data['departmentid'] = $this->uri->segment(4);
     $data['folderid'] = $this->uri->segment(5);
     $data['users'] = $this->User_model->get_user_names();
     $this->load->view('User/user_files_archive', $data);
   }

   function download_one_file_archive()
   {
     $id = $this->uri->segment(3);

     $data['file'] = $this->User_model->get_one_file_archive($id);
     foreach($data['file'] as $d)
     {
       force_download($d->archive_path, NULL);
     }
   }

   function delete_one_file_archive()
   {
     $id = $this->uri->segment(3);

     $data['file'] = $this->User_model->get_one_file_archive($id);
     foreach($data['file'] as $d)
     {
       unlink($d->archive_path);
     }
     $this->User_model->delete_one_file_archive($id);
   }

   function delete_folder_files()
   {
     $id = $this->uri->segment(3);

     $archivednumbers = array();

     $data['unlinkfiles'] = $this->User_model->get_all_files_by_folder($id);
     foreach($data['unlinkfiles'] as $u)
     {
       if($u->files_version == 1.0){}
       else
       {
         $archivednumbers[] = $u->files_id;
       }
     }

     if($archivednumbers)
     {
       foreach($archivednumbers as $i)
       {
         $data['archive'] = $this->User_model->get_archive_by_files_id($i);
         foreach($data['archive'] as $a)
         {
           unlink($a->archive_path);
           $this->User_model->delete_archive_by_files_id($i);
         }
       }
     }

     foreach($data['unlinkfiles'] as $u)
     {
       unlink($u->files_path);
     }

     $this->User_model->delete_files_by_folder($id);
     $this->User_model->delete_shared_by_folder($id);
     $this->User_model->delete_folder($id);
   }

   function view_shared_files()
   {
     $header['active_head'] = 'files';
     $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
     $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
     if($hasunread)
       $header['ihasunread'] = 1;
     else
       $header['ihasunread'] = 0;
     $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
     if($annunread)
       $header['ihasunreadann'] = 1;
     else
       $header['ihasunreadann'] = 0;
     $data['files'] = $this->User_model->get_shared_files($this->session->userdata['department']);
     $data['users'] = $this->User_model->get_user_names();
     $data['departments'] = $this->User_model->get_departments();

     $this->load->view('User/user_header',$header);
     $this->load->view('User/user_files_shared_view',$data);
     $this->load->view('User/user_files_edit_modal');
   }

   function view_shared_archive()
   {
     $header['active_head'] = 'files';
     $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
     $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
     if($hasunread)
       $header['ihasunread'] = 1;
     else
       $header['ihasunread'] = 0;
     $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
     if($annunread)
       $header['ihasunreadann'] = 1;
     else
       $header['ihasunreadann'] = 0;
     $filesid = $this->uri->segment(3);
     $data['archive'] = $this->User_model->get_files_archive($filesid);
     $data['departmentid'] = $this->uri->segment(4);
     $data['folderid'] = $this->uri->segment(5);
     $data['users'] = $this->User_model->get_user_names();
     $this->load->view('User/user_header',$header);
     $this->load->view('User/user_files_shared_archive', $data);
   }

   //============================MESSAGES===================================//
   function messages()
   {
     $header['active_head'] = 'messages';
     $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
     $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
     if($hasunread)
       $header['ihasunread'] = 1;
     else
       $header['ihasunread'] = 0;
     $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
     if($annunread)
       $header['ihasunreadann'] = 1;
     else
       $header['ihasunreadann'] = 0;

     $data['recipients'] = $this->User_model->get_list_employees();

     $this->load->view('User/user_header',$header);
     $this->load->view('User/user_messages',$data);
   }

   function do_message()
   {
     $id =$this->User_model->get_thread_number();

     $sender = $this->session->userdata['id'];
     $subject = $this->input->post('subject');
     $recipient = $this->input->post('recipient');
     $message = $this->input->post('message');

     $data = array('message_subject'=>$subject,
                   'message_id'=>$id,
                   'message_receiver'=>$recipient,
                   'message'=>$message,
                   'message_sender'=>$sender,
                   'thread_id_fk'=>$id
                 );

     $this->User_model->submit_one_message($data, $id);

   }

   //=======================================POLICIES===========================//
   function policies()
   {
     $header['active_head'] = '';
     $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
     $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
     if($hasunread)
       $header['ihasunread'] = 1;
     else
       $header['ihasunread'] = 0;
     $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
     if($annunread)
       $header['ihasunreadann'] = 1;
     else
       $header['ihasunreadann'] = 0;

     $data['policies'] = $this->User_model->get_policies_table();

     $this->load->view('User/user_header',$header);
     $this->load->view('User/user_policies_view',$data);
   }

   function view_contents_of_main()
   {
     $header['active_head'] = '';
     $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
     $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
     if($hasunread)
       $header['ihasunread'] = 1;
     else
       $header['ihasunread'] = 0;
     $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
     if($annunread)
       $header['ihasunreadann'] = 1;
     else
       $header['ihasunreadann'] = 0;
     $id = $this->uri->segment(3);

     $data['policies'] = $this->User_model->get_policies_table_specific($id);
     $data['sub1'] = $this->User_model->get_sub1_table_specific($id);

     $use['sub2'] = array();
     foreach($data['sub1'] as $s1)
     {
        $use['sub2'][] = $this->User_model->get_sub2_table_specific($s1->sub1_id);
     }

     $index = 0;
     $data['sub2'] = array();
     foreach($use['sub2'] as $s2)
     {
       $data['sub2'] = array_merge($data['sub2'], $use['sub2'][$index]);
       $index++;
     }
     $use['sub3'] = array();
     foreach($data['sub2'] as $s2)
     {
        $use['sub3'][] = $this->User_model->get_sub3_table_specific($s2->sub2_id);
     }

     $index = 0;
     $data['sub3'] = array();
     foreach($use['sub3'] as $s3)
     {
       $data['sub3'] = array_merge($data['sub3'], $use['sub3'][$index]);
       $index++;
     }

     $this->load->view('User/user_header',$header);
     $this->load->view('User/user_policies_view_contents_of_main',$data);
   }

   function view_main_page_policy()
   {
     $header['active_head'] = 'policies';
     $header['active_page'] = basename($_SERVER['PHP_SELF'], ".php");
     $hasunread = $this->User_model->get_unread_messages($this->session->userdata['id']);
     if($hasunread)
       $header['ihasunread'] = 1;
     else
       $header['ihasunread'] = 0;
     $annunread = $this->User_model->get_unread_ann($this->session->userdata['id']);
     if($annunread)
       $header['ihasunreadann'] = 1;
     else
       $header['ihasunreadann'] = 0;
     $id = $this->uri->segment(3);
     $type = $this->uri->segment(4);
     //0-main
     if($type == 0)
     {
       $use['content'] = $this->User_model->get_policy_details($id);

       foreach($use['content'] as $d)
       {
         $data['title'] = $d->policy_title;
         $data['content'] = $d->policy_content;
       }
    }

    else if($type == 1)
    {
       $use['content'] = $this->User_model->get_sub1_details($id);
       foreach($use['content'] as $d)
       {
         $data['title'] = $d->sub1_title;
         $data['content'] = $d->sub1_content;
       }
     }

     else if($type == 2)
     {
       $use['content'] = $this->User_model->get_sub2_details($id);
       foreach($use['content'] as $d)
       {
         $data['title'] = $d->sub2_title;
         $data['content'] = $d->sub2_content;
       }
     }

     else if($type == 3)
     {
       $use['content'] = $this->User_model->get_sub3_details($id);
       foreach($use['content'] as $d)
       {
         $data['title'] = $d->sub3_title;
         $data['content'] = $d->sub3_content;
       }
     }

     $this->load->view('Admin/admin_header',$header);
     $this->load->view('Admin/admin_policies_view_page',$data);
   }

}

?>

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <title>ewbClient</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateEmdefinitionstableTempTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('emdefinitionstable_temp', function(Blueprint $table)
		{
			$table->integer('definitionID', true);
			$table->integer('referenceDetailId');
			$table->string('dataItemName', 250)->nullable();
			$table->string('dataItemDescription', 250)->nullable();
			$table->string('codedValue', 250)->nullable();
			$table->string('codedValueType', 250)->nullable();
			$table->string('codedValueDescription', 250)->nullable();
			$table->string('dataItemId', 250)->nullable();
			$table->string('dataItemVersionId', 250)->nullable();
			$table->string('codedValueId', 250);
			$table->string('codedValueVersionId', 250)->nullable();
			$table->string('author', 200)->nullable();
			$table->integer('isMapped')->default(0);
			$table->integer('isMappedApprove')->default(0);
			$table->integer('mappedCodedStatus')->default(0);
			$table->integer('dataTypeSetStatus')->nullable()->default(0);
			$table->integer('mappedCodedComplete')->default(0);
			$table->string('additionalData', 250)->nullable();
			$table->timestamp('createdDate')->default(DB::raw('CURRENT_TIMESTAMP'));
			$table->dateTime('uploadedDate')->default('0000-00-00 00:00:00');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('emdefinitionstable_temp');
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.ceehack.trust"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.android.ceehack.trust.ActivityMain"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.android.ceehack.trust.ActivityParty"
            android:label="@string/title_activity_activity_party"
            android:parentActivityName="com.android.ceehack.trust.ui.MainSelectorActivity" >
        </activity>
        <activity
            android:name="com.android.ceehack.trust.ui.MainSelectorActivity"
            android:label="@string/title_activity_main_selector" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.android.ceehack.trust.ActivityDetail"
            android:label="@string/title_activity_activity_detail"
            android:parentActivityName="com.android.ceehack.trust.ActivityParty" >
        </activity>
        <activity
            android:name="com.android.ceehack.trust.ui.ActivityPartySelector"
            android:label="@string/title_activity_activity_party_selector" >
        </activity>
    </application>

</manifest>


text:
namespace PerformanceStubs {
    public interface IPerformanceTest {
        PerformanceTestSummary Run();
    }
}


text:
use ElectricCommander;
use ElectricCommander::PropMod qw(/myProject/modules);
use WebSphere::Util;
use WebSphere::WebSphere;
use warnings;
use strict;
$|=1;

# -------------------------------------------------------------------------
# Variables
# -------------------------------------------------------------------------

$::gCommands = q($[commands]);
$::gScriptFileSource = trim(q($[scriptfilesource]));
$::gScriptFile = trim(q($[scriptfile]));
$::gScriptFileAbsPath = trim(q($[scriptfileabspath]));
$::gWSAdminAbsPath = trim(q($[wsadminabspath]));
$::gClasspath = trim(q($[classpath]));
$::gJavaParams = trim(q($[javaparams]));
$::gConfigurationName = '$[configname]';
$::gAdditionalOptions = '$[additionalcommands]';

# -------------------------------------------------------------------------
# Main functions
# -------------------------------------------------------------------------

########################################################################
# main - contains the whole process to be done by the plugin, it builds
#        the command line, sets the properties and the working directory
#
# Arguments:
#   none
#
# Returns:
#   none
#
########################################################################
sub main() {

    # create args array
    my @args = ();
    my %props;
    my $actualOperativeSystem = $^O;
    # my $fixedLocation = $::gWSAdminAbsPath;
    my %configuration;

    #get an EC object
    my $ec = new ElectricCommander();
    $ec->abortOnError(0);
    # my $websphere = WebSphere::WebSphere->new_simple($ec);
    my $websphere = WebSphere::WebSphere->new(
        $ec,
        $::gConfigurationName,
        $::gWSAdminAbsPath
    );

    my $fixedLocation = $websphere->getWSAdminPath();
    if ($::gConfigurationName ne '') {
        %configuration = getConfiguration($ec, $::gConfigurationName);
    }

    push (@args, '"'.$fixedLocation.'"');

    if ($::gAdditionalOptions && $::gAdditionalOptions ne '') {
        push(@args, $::gAdditionalOptions);
    }

    if ($::gScriptFileSource eq 'suppliedfile') {
        if ($::gScriptFileAbsPath && $::gScriptFileAbsPath ne '') {
            push(@args, '-f "' . $::gScriptFileAbsPath . '"');
            push(@args, '-lang ' . DEFAULT_WSADMIN_LANGUAGE);
        }
    }
    elsif ($::gScriptFileSource eq 'newscriptfile') {
        my $file = 'generated_script.jython';
        $file = $websphere->write_jython_script(
            $file, {},
            augment_filename_with_random_numbers => 1,
            script => $::gScriptFile
        );
        push(@args, '-f ' . $file);
        push(@args, '-lang ' . DEFAULT_WSADMIN_LANGUAGE);
    }

    if($::gClasspath && $::gClasspath ne '') {
        push(@args, '-wsadmin_classpath "' . $::gClasspath . '"');
    }

    my $connectionType    = $configuration{conntype};
    if($connectionType && $connectionType ne '') {
        push(@args, '-conntype ' . $connectionType);
    }

    #inject config...
    if (%configuration) {
        my $hostParamName;
        if ($connectionType eq IPC_CONNECTION_TYPE){
            $hostParamName = '-ipchost';
        }
        else {
            $hostParamName = '-host';
        }
        if ($configuration{'websphere_url'} ne '') {
            push(@args, $hostParamName . ' ' . $configuration{'websphere_url'});
        }
        if ($configuration{'websphere_port'} ne '') {
            push(@args, '-port ' . $configuration{'websphere_port'});
        }
        if ($configuration{'user'} ne '') {
            push(@args, '-user ' . $configuration{'user'});
        }
        if ($configuration{'password'} ne '') {
            push(@args, '-password ' . $configuration{'password'});
        }
    }
    if ($::gJavaParams && $::gJavaParams ne '') {
        foreach my $param (split(SEPARATOR_CHAR, $::gJavaParams)) {
            push(@args, "-javaoption $param");
        }
    }
    if ($::gCommands && $::gCommands ne '') {
        foreach my $command (split("\n", $::gCommands)) {
            push(@args, '-command ' . $command);
        }
    }

    my $cmdLine = createCommandLine(\@args);
    my $escapedCmdLine = maskPassword($cmdLine, $configuration{'password'});

    $props{'runCustomJob'} = $escapedCmdLine;
    setProperties($ec, \%props);
    print "WSAdmin command line: $escapedCmdLine\n";
    #execute command
    my $content = `$cmdLine`;

    #print log
    print "$content\n";

    #evaluates if exit was successful to mark it as a success or fail the step
    if ($? == SUCCESS) {
        $ec->setProperty("/myJobStep/outcome", 'success');
        # set any additional error or warning conditions here
        # there may be cases that an error occurs and the exit code is 0.
        # we want to set to correct outcome for the running step
        if ($content =~ m/WSVR0028I:/) {
            # license expired warning
            $ec->setProperty("/myJobStep/outcome", 'warning');
      }
    }
    else {
        $ec->setProperty("/myJobStep/outcome", 'error');
    }
}

main();

1;


text:
<!DOCTYPE html>

    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Austin East is a developer and designer located in Orlando, Florida">
    <meta name="author" content="Austin East">

    <title>Austin East - Orlando based design and development</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/ae.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

Austin East

Developer, Designer

bio

Based in Orlando, Florida. In love with responsive design and pretty code. Interested in all things tech. Thrives on challenging projects. Proud cat father.

skills

Proficient knowledge in Javascript, HTML, and CSS, Python and C. Well versed in many CMS such as Wordpress and Squarespace.
Knowledgable in many industry standard design programs, inculding the Adobe Suite.

            View My Resume

Web

Nouveau Riche Collection

Storefront designed for Nouveau Riche's new fashion collection.

                            View the site

Team G Tennis

Designed (excluding graphics) and developed for tennis team "Team G".

                            View the site

Restoration Skincare

Storefront designed for Restoration Skincare.

                            View the site

2D Engine Project

Small game engine project.

                            View the page

Contact

Let's work together.

                     Email

Hosted for free by Dropbox. Find out how here.

Copyrighted © Austin East 2015


text:
% `template.tex', a bare-bones example employing the AIAA class.
%
% For a more advanced example that makes use of several third-party
% LaTeX packages, see `advanced_example.tex', but please read the
% Known Problems section of the users manual first.
%
% Typical processing for PostScript (PS) output:
%
%  latex template
%  latex template   (repeat as needed to resolve references)
%
%  xdvi template    (onscreen draft display)
%  dvips template   (postscript)
%  gv template.ps   (onscreen display)
%  lpr template.ps  (hardcopy)
%
% With the above, only Encapsulated PostScript (EPS) images can be used.
%
% Typical processing for Portable Document Format (PDF) output:
%
%  pdflatex template
%  pdflatex template      (repeat as needed to resolve references)
%
%  acroread template.pdf  (onscreen display)
%
% If you have EPS figures, you will need to use the epstopdf script
% to convert them to PDF because PDF is a limmited subset of EPS.
% pdflatex accepts a variety of other image formats such as JPG, TIF,
% PNG, and so forth -- check the documentation for your version.
%
% If you do *not* specify suffixes when using the graphicx package's
% \includegraphics command, latex and pdflatex will automatically select
% the appropriate figure format from those available.  This allows you
% to produce PS and PDF output from the same LaTeX source file.
%
% To generate a large format (e.g., 11"x17") PostScript copy for editing
% purposes, use
%
%  dvips -x 1467 -O -0.65in,0.85in -t tabloid template
%
% For further details and support, read the Users Manual, aiaa.pdf.

% Try to reduce the number of latex support calls from people who
% don't read the included documentation.
%
\typeout{}\typeout{If latex fails to find aiaa-tc, read the README file!}
%

\documentclass[]{aiaa-tc}% insert '[draft]' option to show overfull boxes

 \title{Bare-Bones \LaTeX\ Template for
        AIAA Technical Conference Papers}

 \author{
  First A. Author%
    \thanks{Job Title, Department, Address, and AIAA Member Grade.}
  \ and Second B. Author\thanksibid{1}\\
  {\normalsize\itshape
   Business or Academic Affiliation, City, Province, Zipcode, Country}\\
  \and
  Third C. Author%
   \thanks{Job Title, Department, Address, and AIAA Member Grade.}\\
  {\normalsize\itshape
  Business or Academic Affiliation, City, Province, Zipcode, Country}
 }

 % Data used by 'handcarry' option if invoked
 \AIAApapernumber{YEAR-NUMBER}
 \AIAAconference{Conference Name, Date, and Location}
 \AIAAcopyright{\AIAAcopyrightD{YEAR}}

 % Define commands to assure consistent treatment throughout document
 \newcommand{\eqnref}[1]{(\ref{#1})}
 \newcommand{\class}[1]{\texttt{#1}}
 \newcommand{\package}[1]{\texttt{#1}}
 \newcommand{\file}[1]{\texttt{#1}}
 \newcommand{\BibTeX}{\textsc{Bib}\TeX}

\begin{document}

\maketitle

\begin{abstract}
This is a bare-bones \LaTeX\ template of an AIAA technical conference paper.
It is intended to demonstrate the bare minimum set of \LaTeX\ commands
to produce an AIAA technical conference paper.
To explore more \LaTeX\ capabilities, see the advanced example, but
first read the Known Problems section of the user manual.
For detailed AIAA layout and style guidelines, please refer to the AIAA
author guide for paper submission, format, and other procedures.
\end{abstract}

\section*{Nomenclature}

\begin{tabbing}
  XXX \= \kill% this line sets tab stop
  $J$ \> Jacobian Matrix \\
  $f$ \> Residual value vector \\
  $x$ \> Variable value vector \\
  $F$ \> Force, N \\
  $m$ \> Mass, kg \\
  $\Delta x$ \> Variable displacement vector \\
  $\alpha$ \> Acceleration, m/s\textsuperscript{2} \\[5pt]
  \textit{Subscript}\\
  $i$ \> Variable number \\
 \end{tabbing}

\section{Introduction}

This would be a good place to insert some text that make sense relative
to the paper being written.
Of course, for example purposes, the text is quite meaningless.

\subsection{Background}

This background section is here only to demonstrate \verb|\subsection|
usage.
And following this, the next section level will need to be demonstrated.

\subsubsection{Detail}

Here is a \verb|\subsubsection| that would normally come in pairs of two
according to the requirements of an outline, but for the sake of
demonstration, we are only showing a single \verb|\subsubsection|.

\section{Model}

We should probably include some math.
Here we begin with Eq.~(\ref{e:function}) that demonstrates some math
typesetting.
\begin{equation}
 \label{e:function}
 \int_{0}^{r_{2}} F(r,\varphi) \, dr \, d\varphi =
    \left[ \sigma r_{2}/(2\mu_{0}) \right] \cdot
    \int_{0}^{\infty} \exp(-\rho|z_{j}-z_{i}|) \, \lambda^{-1}
\end{equation}
Eq.~(\ref{e:function}) is grand.
Some say it is due to Rebek.\cite{rebek:82bk}

\section{Results}

In this section we will introduce some figures and tables.
It can be seen in figure~\ref{f:magnetic_field} that magnetization is a
function of applied field.
\begin{figure}[htb]% order of placement preference: here, top, bottom
 \includegraphics{figure_magnet}
 \caption{Magnetization as a function of applied field, which has
   borders so thick that they overwhelm the data and for some reason the
   ordinate label is rotated 90 degrees to make it difficult to
   read. This figure also demonstrates the dangers of using a bitmap
   as opposed to a vector image.}
 \label{f:magnetic_field}
\end{figure}
Sometimes writing meaningless text can be quiet easy, but other times
one is hard pressed to keep the words flowing.\footnote{And sometimes
things get carried away in endless detail.}
Meanwhile back in the other world, table~\ref{t:scheme_comparison} shows
a nifty comparison.
\begin{table}% no placement specified: defaults to here, top, bottom, page
 \begin{center}
  \caption{Variable and Fixed Coefficient Runge-Kutta Schemes as a
           Function of Reynolds Number}
  \label{t:scheme_comparison}
  \begin{tabular}{rrr}
       Re & Vary & Fixed \\\hline
        1 &  868 & 4,271 \\
       10 &  422 & 2,736 \\
       25 &  252 & 1,374 \\
       50 &  151 &   736 \\
      100 &  110 &   387 \\
      500 &   85 &   136 \\
    1,000 &   77 &   117 \\
    5,000 &   81 &    98 \\
   10,000 &   82 &    99
  \end{tabular}
 \end{center}
\end{table}

\section{Conclusion}

After much typing, the paper can now conclude.
Four rocks were next to the channel.
This caused a few standing waves during the rip that one could ride on
the way in or jump on the way out.

\section*{Appendix}

An appendix, if needed, should appear before the acknowledgments.
Use the 'starred' version of the \verb|\section| commands to avoid
section numbering.

\section*{Acknowledgments}

A place to recognize others.

\begin{thebibliography}{9}% maximum number of references (for label width)
 \bibitem{rebek:82bk}
 Rebek, A., {\it Fickle Rocks}, Fink Publishing, Chesapeake, 1982.
\end{thebibliography}

\end{document}

% - Release $Name:  $ -


text:
"""
Default key bindings.::

    registry = load_key_bindings()
    app = Application(key_bindings_registry=registry)
"""
from __future__ import unicode_literals
from prompt_toolkit.key_binding.registry import ConditionalRegistry, MergedRegistry
from prompt_toolkit.key_binding.bindings.basic import load_basic_bindings, load_abort_and_exit_bindings, load_basic_system_bindings, load_auto_suggestion_bindings, load_mouse_bindings
from prompt_toolkit.key_binding.bindings.emacs import load_emacs_bindings, load_emacs_system_bindings, load_emacs_search_bindings, load_emacs_open_in_editor_bindings, load_extra_emacs_page_navigation_bindings
from prompt_toolkit.key_binding.bindings.vi import load_vi_bindings, load_vi_system_bindings, load_vi_search_bindings, load_vi_open_in_editor_bindings, load_extra_vi_page_navigation_bindings
from prompt_toolkit.filters import to_cli_filter

__all__ = (
    'load_key_bindings',
    'load_key_bindings_for_prompt',
)

def load_key_bindings(
        get_search_state=None,
        enable_abort_and_exit_bindings=False,
        enable_system_bindings=False,
        enable_search=False,
        enable_open_in_editor=False,
        enable_extra_page_navigation=False,
        enable_auto_suggest_bindings=False):
    """
    Create a Registry object that contains the default key bindings.

    :param enable_abort_and_exit_bindings: Filter to enable Ctrl-C and Ctrl-D.
    :param enable_system_bindings: Filter to enable the system bindings (meta-!
            prompt and Control-Z suspension.)
    :param enable_search: Filter to enable the search bindings.
    :param enable_open_in_editor: Filter to enable open-in-editor.
    :param enable_open_in_editor: Filter to enable open-in-editor.
    :param enable_extra_page_navigation: Filter for enabling extra page
        navigation. (Bindings for up/down scrolling through long pages, like in
        Emacs or Vi.)
    :param enable_auto_suggest_bindings: Filter to enable fish-style suggestions.
    """

    assert get_search_state is None or callable(get_search_state)

    # Accept both Filters and booleans as input.
    enable_abort_and_exit_bindings = to_cli_filter(enable_abort_and_exit_bindings)
    enable_system_bindings = to_cli_filter(enable_system_bindings)
    enable_search = to_cli_filter(enable_search)
    enable_open_in_editor = to_cli_filter(enable_open_in_editor)
    enable_extra_page_navigation = to_cli_filter(enable_extra_page_navigation)
    enable_auto_suggest_bindings = to_cli_filter(enable_auto_suggest_bindings)

    registry = MergedRegistry([
        # Load basic bindings.
        load_basic_bindings(),
        load_mouse_bindings(),

        ConditionalRegistry(load_abort_and_exit_bindings(),
                            enable_abort_and_exit_bindings),

        ConditionalRegistry(load_basic_system_bindings(),
                            enable_system_bindings),

        # Load emacs bindings.
        load_emacs_bindings(),

        ConditionalRegistry(load_emacs_open_in_editor_bindings(),
                            enable_open_in_editor),

        ConditionalRegistry(load_emacs_search_bindings(get_search_state=get_search_state),
                            enable_search),

        ConditionalRegistry(load_emacs_system_bindings(),
                            enable_system_bindings),

        ConditionalRegistry(load_extra_emacs_page_navigation_bindings(),
                            enable_extra_page_navigation),

        # Load Vi bindings.
        load_vi_bindings(get_search_state=get_search_state),

        ConditionalRegistry(load_vi_open_in_editor_bindings(),
                            enable_open_in_editor),

        ConditionalRegistry(load_vi_search_bindings(get_search_state=get_search_state),
                            enable_search),

        ConditionalRegistry(load_vi_system_bindings(),
                            enable_system_bindings),

        ConditionalRegistry(load_extra_vi_page_navigation_bindings(),
                            enable_extra_page_navigation),

        # Suggestion bindings.
        # (This has to come at the end, because the Vi bindings also have an
        # implementation for the "right arrow", but we really want the
        # suggestion binding when a suggestion is available.)
        ConditionalRegistry(load_auto_suggestion_bindings(),
                            enable_auto_suggest_bindings),
    ])

    return registry

def load_key_bindings_for_prompt(**kw):
    """
    Create a ``Registry`` object with the defaults key bindings for an input
    prompt.

    This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D),
    incremental search and auto suggestions.

    (Not for full screen applications.)
    """
    kw.setdefault('enable_abort_and_exit_bindings', True)
    kw.setdefault('enable_search', True)
    kw.setdefault('enable_auto_suggest_bindings', True)

    return load_key_bindings(**kw)


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

using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Instrumentation;

#endregion

namespace DotNetNuke.Services.Search
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The SearchConfig class provides a configuration class for Search
    /// </summary>
    /// -----------------------------------------------------------------------------
    [Obsolete("Deprecated in DNN 7.1.  No longer used in the Search infrastructure.")]
    [Serializable]
    public class SearchConfig
    {
    	private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (SearchConfig));
		#region "Private Members"

        private readonly bool _SearchIncludeCommon;
        private readonly bool _SearchIncludeNumeric;
        private readonly int _SearchMaxWordlLength;
        private readonly int _SearchMinWordlLength;

		#endregion

		#region "Constructor(s)"

        public SearchConfig(int portalID)
            : this(PortalController.Instance.GetPortalSettings(portalID))
        {
        }

        public SearchConfig(Dictionary<string, string> settings)
        {
            _SearchIncludeCommon = GetSettingAsBoolean("SearchIncludeCommon", settings, Host.SearchIncludeCommon);
            _SearchIncludeNumeric = GetSettingAsBoolean("SearchIncludeNumeric", settings, Host.SearchIncludeNumeric);
            _SearchMaxWordlLength = GetSettingAsInteger("MaxSearchWordLength", settings, Host.SearchMaxWordlLength);
            _SearchMinWordlLength = GetSettingAsInteger("MinSearchWordLength", settings, Host.SearchMinWordlLength);
        }

		#endregion

		#region "Public Properties"

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets whether to inlcude Common Words in the Search Index
        /// </summary>
        /// <remarks>Defaults to False</remarks>
        /// -----------------------------------------------------------------------------
        public bool SearchIncludeCommon
        {
            get
            {
                return _SearchIncludeCommon;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets whether to inlcude Numbers in the Search Index
        /// </summary>
        /// <remarks>Defaults to False</remarks>
        /// -----------------------------------------------------------------------------
        public bool SearchIncludeNumeric
        {
            get
            {
                return _SearchIncludeNumeric;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the maximum Search Word length to index
        /// </summary>
        /// <remarks>Defaults to 25</remarks>
        /// -----------------------------------------------------------------------------
        public int SearchMaxWordlLength
        {
            get
            {
                return _SearchMaxWordlLength;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the maximum Search Word length to index
        /// </summary>
        /// <remarks>Defaults to 3</remarks>
        /// -----------------------------------------------------------------------------
        public int SearchMinWordlLength
        {
            get
            {
                return _SearchMinWordlLength;
            }
        }

		#endregion

		#region "Private Methods"

        private bool GetSettingAsBoolean(string key, Dictionary<string, string> settings, bool defaultValue)
        {
            bool retValue = Null.NullBoolean;
            try
            {
                string setting = Null.NullString;
                settings.TryGetValue(key, out setting);
                if (string.IsNullOrEmpty(setting))
                {
                    retValue = defaultValue;
                }
                else
                {
                    retValue = (setting.ToUpperInvariant().StartsWith("Y") || setting.ToUpperInvariant() == "TRUE");
                }
            }
            catch (Exception exc)
            {
                //we just want to trap the error as we may not be installed so there will be no Settings
                Logger.Error(exc);

            }
            return retValue;
        }

        private int GetSettingAsInteger(string key, Dictionary<string, string> settings, int defaultValue)
        {
            int retValue = Null.NullInteger;
            try
            {
                string setting = Null.NullString;
                settings.TryGetValue(key, out setting);
                if (string.IsNullOrEmpty(setting))
                {
                    retValue = defaultValue;
                }
                else
                {
                    retValue = Convert.ToInt32(setting);
                }
            }
            catch (Exception exc)
            {
                //we just want to trap the error as we may not be installed so there will be no Settings
                Logger.Error(exc);

            }
            return retValue;
        }

		#endregion
    }
}


text:
package com.hannesdorfmann.mosby3.mvi.integrationtest.lifecycle.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;

import com.hannesdorfmann.mosby3.mvi.integrationtest.R;

public class MviFinishOnCreateContainerActivity extends FragmentActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycle);

        if (savedInstanceState == null) {
            MviFinishOnCreateFragment f = new MviFinishOnCreateFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.container, f).commitNow();
        }
    }
}


text:
// Copyright (C) 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

// file: rbbi_cache.h
//
#ifndef RBBI_CACHE_H
#define RBBI_CACHE_H

#include "unicode/utypes.h"

#if !UCONFIG_NO_BREAK_ITERATION

#include "unicode/rbbi.h"
#include "unicode/uobject.h"

#include "uvectr32.h"

U_NAMESPACE_BEGIN

/* DictionaryCache  stores the boundaries obtained from a run of dictionary characters.
 *                 Dictionary boundaries are moved first to this cache, then from here
 *                 to the main BreakCache, where they may inter-leave with non-dictionary
 *                 boundaries. The public BreakIterator API always fetches directly
 *                 from the main BreakCache, not from here.
 *
 *                 In common situations, the number of boundaries in a single dictionary run
 *                 should be quite small, it will be terminated by punctuation, spaces,
 *                 or any other non-dictionary characters. The main BreakCache may end
 *                 up with boundaries from multiple dictionary based runs.
 *
 *                 The boundaries are stored in a simple ArrayList (vector), with the
 *                 assumption that they will be accessed sequentially.
 */
class RuleBasedBreakIterator::DictionaryCache: public UMemory {
  public:
     DictionaryCache(RuleBasedBreakIterator *bi, UErrorCode &status);
     ~DictionaryCache();

     void reset();

     UBool following(int32_t fromPos, int32_t *pos, int32_t *statusIndex);
     UBool preceding(int32_t fromPos, int32_t *pos, int32_t *statusIndex);

    /**
     * Populate the cache with the dictionary based boundaries within a region of text.
     * @param startPos  The start position of a range of text
     * @param endPos    The end position of a range of text
     * @param firstRuleStatus The rule status index that applies to the break at startPos
     * @param otherRuleStatus The rule status index that applies to boundaries other than startPos
     * @internal
     */
    void populateDictionary(int32_t startPos, int32_t endPos,
                         int32_t firstRuleStatus, int32_t otherRuleStatus);

    RuleBasedBreakIterator *fBI;

    UVector32           fBreaks;                // A vector containing the boundaries.
    int32_t             fPositionInCache;       // Index in fBreaks of last boundary returned by following()
                                                //    or preceding(). Optimizes sequential access.
    int32_t             fStart;                 // Text position of first boundary in cache.
    int32_t             fLimit;                 // Last boundary in cache. Which is the limit of the
                                                //    text segment being handled by the dictionary.
    int32_t             fFirstRuleStatusIndex;  // Rule status info for first boundary.
    int32_t             fOtherRuleStatusIndex;  // Rule status info for 2nd through last boundaries.
};

/*
 * class BreakCache
 *
 * Cache of break boundary positions and rule status values.
 * Break iterator API functions, next(), previous(), etc., will use cached results
 * when possible, and otherwise cache new results as they are obtained.
 *
 * Uniformly caches both dictionary and rule based (non-dictionary) boundaries.
 *
 * The cache is implemented as a single circular buffer.
 */

/*
 * size of the circular cache buffer.
 */

class RuleBasedBreakIterator::BreakCache: public UMemory {
  public:
                BreakCache(RuleBasedBreakIterator *bi, UErrorCode &status);
    virtual     ~BreakCache();
    void        reset(int32_t pos = 0, int32_t ruleStatus = 0);
    void        next() {    if (fBufIdx == fEndBufIdx) {
                                nextOL();
                            } else {
                                fBufIdx = modChunkSize(fBufIdx + 1);
                                fTextIdx = fBI->fPosition = fBoundaries[fBufIdx];
                                fBI->fRuleStatusIndex = fStatuses[fBufIdx];
                            }
                }

    void        nextOL();
    void        previous(UErrorCode &status);

    // Move the iteration state to the position following the startPosition.
    // Input position must be pinned to the input length.
    void        following(int32_t startPosition, UErrorCode &status);

    void        preceding(int32_t startPosition, UErrorCode &status);

    /*
     * Update the state of the public BreakIterator (fBI) to reflect the
     * current state of the break iterator cache (this).
     */
    int32_t     current();

    /**
     * Add boundaries to the cache near the specified position.
     * The given position need not be a boundary itself.
     * The input position must be within the range of the text, and
     * on a code point boundary.
     * If the requested position is a break boundary, leave the iteration
     * position on it.
     * If the requested position is not a boundary, leave the iteration
     * position on the preceding boundary and include both the
     * preceding and following boundaries in the cache.
     * Additional boundaries, either preceding or following, may be added
     * to the cache as a side effect.
     *
     * Return FALSE if the operation failed.
     */
    UBool populateNear(int32_t position, UErrorCode &status);

    /**
     *  Add boundary(s) to the cache following the current last boundary.
     *  Return FALSE if at the end of the text, and no more boundaries can be added.
     *  Leave iteration position at the first newly added boundary, or unchanged if no boundary was added.
     */
    UBool populateFollowing();

    /**
     *  Add one or more boundaries to the cache preceding the first currently cached boundary.
     *  Leave the iteration position on the first added boundary.
     *  Return false if no boundaries could be added (if at the start of the text.)
     */
    UBool populatePreceding(UErrorCode &status);

    enum UpdatePositionValues {
        RetainCachePosition = 0,
        UpdateCachePosition = 1
    };

    /*
     * Add the boundary following the current position.
     * The current position can be left as it was, or changed to the newly added boundary,
     * as specified by the update parameter.
     */
    void addFollowing(int32_t position, int32_t ruleStatusIdx, UpdatePositionValues update);

    /*
     * Add the boundary preceding the current position.
     * The current position can be left as it was, or changed to the newly added boundary,
     * as specified by the update parameter.
     */
    bool addPreceding(int32_t position, int32_t ruleStatusIdx, UpdatePositionValues update);

    /**
     *  Set the cache position to the specified position, or, if the position
     *  falls between to cached boundaries, to the preceding boundary.
     *  Fails if the requested position is outside of the range of boundaries currently held by the cache.
     *  The startPosition must be on a code point boundary.
     *
     *  Return TRUE if successful, FALSE if the specified position is after
     *  the last cached boundary or before the first.
     */
    UBool                   seek(int32_t startPosition);

    void dumpCache();

  private:
    static inline int32_t   modChunkSize(int index) { return index & (CACHE_SIZE - 1); }

    static constexpr int32_t CACHE_SIZE = 128;
    static_assert((CACHE_SIZE & (CACHE_SIZE-1)) == 0, "CACHE_SIZE must be power of two.");

    RuleBasedBreakIterator *fBI;
    int32_t                 fStartBufIdx;
    int32_t                 fEndBufIdx;    // inclusive

    int32_t                 fTextIdx;
    int32_t                 fBufIdx;

    int32_t                 fBoundaries[CACHE_SIZE];
    uint16_t                fStatuses[CACHE_SIZE];

    UVector32               fSideBuffer;
};

U_NAMESPACE_END

#endif // #if !UCONFIG_NO_BREAK_ITERATION

#endif // RBBI_CACHE_H