text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Mail;
use DB;
use App;
use App\Worker;
use App\Supervisor;
use App\Department;
use App\Timecard;
use App\Mail\WorkerWelcomeMessage;
use App\Mail\SupervisorWelcomeMessage;
use App\Mail\ResetPassword;

class CoordinatorController extends Controller
{
    public function main() {

      $role = session('role');
      if ($role !== "coordinator") {
        session()->flush();
        return redirect("/");
      }

      // username
      $user = session('user');

      // role
      $role = ucfirst(session('role'));
      // name
      $name = session('name');

      // count active timecards
      $activeTimecards = $this->countActiveTimecards();
      // count unsigned timecards
      $unsignedTimecards = $this->countUnsignedTimecards();
      // count submitted timecards
      $submittedTimecards = $this->countSubmittedTimecards();
      // get payscales
      $payscales = $this->getPayscales();
      // get total paid
      $totalPaid = $this->getTotalPaid();
      // get top workers
      $topWorkers = $this->topWorkers();

      $data = array(
        'name' => $name,
        'activeTimecards' => $activeTimecards,
        'unsignedTimecards' => $unsignedTimecards,
        'submittedTimecards' => $submittedTimecards,
        'payscales' => $payscales,
        'totalPaid' => $totalPaid,
        'topWorkers' => $topWorkers
      );

      return view('coordinator/main', ['data' => $data]);
    }
    public function logout() {
      session()->flush();
      return redirect('/');
    }

    public function showWorkersList() {
      if (session('role') !== 'coordinator') {
        session()->flush();
        return redirect('/');
      }

      // get worker objects
    }
    public function showWorkersAdd() {
      $user = session('user');
      $name = session('name');
      $role = session('role');

      if ($role !== "coordinator") {
        return redirect("/");
      }

      return view("/coordinator/workers/add", ['user'=>$user, 'name'=>$name, 'role'=>$role]);

    }
    public function workersAdd(Request $request) {
      $this->validate($request, [
        'email' => 'email|required',
        'firstname' => 'alpha|required',
        'lastname' => 'alpha|required',
      ]);

      // assign variables
      $email = $request->input('email');
      $firstname = $request->input('firstname');
      $lastname = $request->input('lastname');
      $departments = $request->input('departments');

      // check that departments is not empty
      if (empty($departments)) {
        $error = array('Please choose at least one department.');
        $errors = new MessageBag($error);

        return back()->withInput()->with('errors', $errors);
      }

      // check worker doesn't already exist
      $present = Worker::where('email', $email)->count();
      if ($present == 0) {}
      else {
        $error = array('Worker already exists.');
        $errors = new MessageBag($error);
        return back()->withInput()->with('errors',$errors);
      }

      // generate token
      $bytes = random_bytes(20);
      $token = bin2hex($bytes);

      // construct name;
      $name = ucfirst(strtolower($firstname)) . " " . ucfirst(strtolower($lastname));

      // new worker object
      $worker = new Worker;
      $worker->name = $name;
      $worker->email = $email;
      $worker->token = $token;

      // save to db
      $worker->save();

      // add departments into db
      foreach($departments as $department) {
        $entry = new Department;
        $entry->email = $email;
        $entry->department = $department;

        $entry->create();
      }

      // send email to worker
      Mail::to($worker->email)->send(new WorkerWelcomeMessage($worker));

      return redirect("/coordinator")->with('status','Worker successfully added.');

    }
    public function showWorkersEdit() {
      if (session('role') !== "coordinator") {
        return redirect("/");
      }

      // get all workers
      $workers = Worker::get();

      return view("/coordinator/workers/edit")->with('workers',$workers);
    }
    public function showWorker(Worker $worker){

      if (session('role') !== "coordinator") {
        session()->flush();
        return redirect('/');
      }

      $departments = $worker->departments();
      $data = array('worker'=> $worker, 'departments' => $departments);
      return view('/coordinator/workers/editWorker')->with('data', $data);
    }
    public function workerEdit(Request $request, Worker $worker) {
      if (session('role') !== 'coordinator') {
        session()->flush();
        return redirect('/');
      }

      $this->validate($request, [
        'action' => 'required',
        'departments' => 'required|array'
      ]);

      $action = $request->input('action');
      $departments = $request->input('departments');

      if ($action === "save") {

        $worker = Worker::where('email',$worker->email)->first();

        $worker->setDepartments($departments);

        $worker->save();

        return redirect("/coordinator")->with('status','Worker successfully modified.');
      }
      if ($action === "reset") {
        $worker->password = NULL;

        // generate token
        $bytes = random_bytes(20);
        $token = bin2hex($bytes);

        $worker->token = $token;

        $worker->save();

        // send email to worker
        Mail::to($worker->email)->send(new ResetPassword($worker));

        return redirect("/coordinator")->with('status','Password was reset and an email was sent to the worker.');
      }
      if ($action === "cancel") {
        return redirect('/coordinator');
      }
      if ($action === "delete") {
        $worker->delete();

        return redirect('/coordinator')->with('status', 'Worker deleted.');
      }

      return redirect('/coordinator');

    }

    public function showSupervisorsAdd() {
      $role = session('role');

      if ($role !== "coordinator") {
        return redirect("/");
      }

      return view('/coordinator/supervisors/add');
    }
    public function supervisorsAdd(Request $request) {
      $this->validate($request, [
        'email' => 'email|required',
        'firstname' => 'alpha|required',
        'lastname' => 'alpha|required'
      ]);

      // assign variables
      $email = $request->input('email');
      $firstname = $request->input('firstname');
      $lastname = $request->input('lastname');
      $departments = $request->input('departments');

      // check departments array is not empty
      if (empty($departments)) {
        $error = array("Please choose at least one department.");
        $errors = new MessageBag($error);
        return back()->withInput()->with('errors', $errors);
      }

      // check that worker doesn't already exist
      $present = Supervisor::where('email',$email)->count();
      if ($present != 0) {
        $message = array("Supervisor is already present in the database.");
        $errors = new MessageBag($message);
        return back()->withInput()->with('errors', $errors);
      }

      // generate token
      $bytes = random_bytes(20);
      $token = bin2hex($bytes);

      // construct name;
      $name = ucfirst(strtolower($firstname)) . " " . ucfirst(strtolower($lastname));

      // new worker object
      $supervisor = new Supervisor;
      $supervisor->name = $name;
      $supervisor->email = $email;
      $supervisor->token = $token;

      // save to db
      $supervisor->save();

      // create department entries
      foreach($departments as $department) {
        $entry = new Department;
        $entry->email = $email;
        $entry->department = $department;

        $entry->save();
      }

      // send email to worker
      Mail::to($supervisor->email)->send(new SupervisorWelcomeMessage($supervisor));

      return redirect('/coordinator')->with('status', 'Supervisor successfully added');

    }
    public function showSupervisorsEdit() {
      if (session('role') !== 'coordinator') {
        session()->flush();
        return redirect('/');
      }

      $supervisors = Supervisor::get();

      return view('/coordinator/supervisors/edit')->with('supervisors', $supervisors);
    }
    public function showSupervisor(Supervisor $supervisor) {
      if (session('role') !== 'coordinator') {
        session()->flush();
        return redirect('/');
      }

      $departments = $supervisor->departments();
      $data = array(
        'supervisor' => $supervisor,
        'departments' => $departments
      );

      return view('/coordinator/supervisors/editSupervisor')->with('data', $data);
    }
    public function supervisorEdit(Request $request, Supervisor $supervisor) {
      if (session('role') !== 'coordinator') {
        session()->flush();
        return redirect('/');
      }

      $action = $request->input('action');
      $departments = $request->input('departments');

      if ($action === 'save') {
        $supervisor->setDepartments($departments);

        return redirect('/coordinator')->with('status', 'Supervisor successfully updated.');

      }
      if ($action === 'delete') {
        $supervisor->delete();

        return redirect('/coordinator')->with('status', 'Supervisor deleted.');
      }
      if ($action === 'cancel') {
        return redirect('/coordinator');
      }
      if ($action === 'reset') {

        $supervisor->password = NULL;

        // generate token
        $bytes = random_bytes(20);
        $token = bin2hex($bytes);

        $supervisor->token = $token;

        $supervisor->save();
        // send email to worker
        Mail::to($supervisor->email)->send(new ResetPassword($supervisor));

        return redirect("/coordinator")->with('status','Password was reset and an email was sent to the supervisor.');
      }

    }

    public function showPayscales() {
      $results = DB::table('payscales')->get();

      $payscales = array();
      foreach ($results as $result) {
        $payscales[$result->grade] = $result->pay;
      }

      return view('/coordinator/payments/payscales')->with('payscales', $payscales);

    }
    public function payscales(Request $request) {
      $this->validate($request, [
        'u' => 'required|numeric',
        's' => 'required|numeric',
        'o' => 'required|numeric'
      ]);

      $u = $request->input('u');
      $s = $request->input('s');
      $o = $request->input('o');

      DB::table('payscales')->where('grade','u')->update(['pay' => $u]);
      DB::table('payscales')->where('grade', 's')->update(['pay' => $s]);
      DB::table('payscales')->where('grade', 'o')->update(['pay' => $o]);

      return redirect('/coordinator')->with('status', 'Payscales updated.');
    }

    public function showPaymentsSelect() {
      if (session('role') !== 'coordinator') {
        session()->flush();
        return redirect('/');
      }

      return view('coordinator/payments/select');
    }
    public function paymentsSelect(Request $request) {
      $this->validate($request, [
        'startDate' => 'required|date',
        'endDate' => 'required|date'
      ]);

      $startDate = $request->input('startDate');
      $endDate = $request->input('endDate');

      // check startDate is a sunday
      $day = date('D', strtotime($startDate));
      if ($day !== 'Sun') {
        $error = array('Starting date must be a Sunday.');
        $errors = new MessageBag($error);
        return back()->with('errors', $errors);
      }

      // check endDate is a saturday
      $day = date('D', strtotime($endDate));
      if ($day !== 'Sat') {
        $error = array('Ending date must be a Saturday.');
        $errors = new MessageBag($error);
        return back()->with('errors', $errors);
      }

      // check endDate is not same as or before saturday
      if (strtotime($endDate) <= strtotime($startDate)) {
        $error = array('End date cannot be before or the same day as start date.');
        $errors = new MessageBag($error);
        return back()->with('errors', $errors);
      }

      $start = strtotime($startDate . " 00:00:00");
      $end = strtotime($endDate . " 23:59:59");

      // get all signed timecards
      $signed = Timecard::where('signed',1)->where('paid',0)->get();
      foreach($signed as $index => $timecard) {
        $cardStart = strtotime($timecard->startDate . " 00:00:00");
        $cardEnd = strtotime($timecard->endDate . " 23:59:59");

        if ($cardStart >= $start && $cardEnd <= $end) {}
        else {
          unset($signed[$index]);
        }
      }

      if (count($signed) == 0) {
        $error = array('There are no signed timedcards for the selected time period.');
        $errors = new MessageBag($error);
        return back()->withInput()->with('errors', $errors);
      }

      return view('coordinator/payments/confirm')
        ->with('startDate', $startDate)
        ->with('endDate', $endDate)
        ->with('timecards', $signed);
    }
    // public function showPaymentsConfirm() {
    //   if (session('role') !== 'coordinator') {
    //     session()->flush();
    //     return redirect('/');
    //   }
    //
    //
    //   $startDate = session('startDate');
    //   $endDate = session('endDate');
    //
    //   // change into timestamps
    //   $start = strtotime($startDate . " 00:00:00");
    //   $end = strtotime($endDate . " 23:59:59");
    //
    //   // get all unsigned timecards and check each one ends before end date.
    //   // remove timecards that do not end at or before the end date.
    //   $unsigned = Timecard::where('signed', 0)->get();
    //   foreach($unsigned as $index => $timecard) {
    //     $cardEnd = strtotime($timecard->endDate . " 23:59:59");
    //
    //     if ($cardEnd <= $end) {}
    //     else {
    //       unset($unsigned[$index]);
    //     }
    //   }
    //
    //   if (count($unsigned) !== 0) {
    //     return view('coordinator/payments/unsigned')->with('unsigned', $unsigned);
    //   }
    //
    //   // if no unsigned timecards, continue
    //   $signed = Timecard::where('signed',1)->where('paid',0)->get();
    //
    //   foreach($signed as $index => $timecard) {
    //
    //     $cardStart = strtotime($timecard->startDate . " 00:00:00");
    //     $cardEnd = strtotime($timecard->endDate . " 23:59:59");
    //
    //     if ($cardStart >= $start && $cardEnd <= $end) {}
    //     else {
    //       unset($signed[$index]);
    //     }
    //   }
    //
    //   if (empty($signed)) {
    //     $error = array('No signed timecards for the selected time period.');
    //     $errors = new MessageBag($error);
    //     return back()->withInput()->with('errors', $errors);
    //   }
    //
    //   return view('coordinator/payments/confirm')
    //     ->with('timecards', $signed)
    //     ->with('startDate', $startDate)
    //     ->with('endDate', $endDate);
    //
    // }
    public function paymentsConfirm(Request $request) {
      $this->validate($request, [
        'startDate' => 'required|date',
        'endDate' => 'required|date'
      ]);

      $startDate = $request->input('startDate');
      $endDate = $request->input('endDate');

      // timestamps
      $start = strtotime($startDate . " 00:00:00");
      $end = strtotime($endDate . " 23:59:59");

      // get all signed timecards
      $signed = Timecard::where('signed',1)->where('paid',0)->get();

      // remove all timecards not falling within date range.
      foreach($signed as $index => $timecard) {
        $cardStart = strtotime($timecard->startDate . " 00:00:00");
        $cardEnd = strtotime($timecard->endDate . " 23:59:59");

        if ($cardStart >= $start && $cardEnd <= $end) {}
        else {
          unset($signed[$index]);
        }
      }

      // mark remaining cards as paid
      foreach($signed as $timecard) {
        $timecard->paid = 1;
        $timecard->save();
      }

      $paid = Timecard::where('paid',1)->get();

      foreach($paid as $index => $timecard) {
        $cardStart = strtotime($timecard->startDate . " 00:00:00");
        $cardEnd = strtotime($timecard->endDate . " 23:59:59");

        if ($cardStart >= $start && $cardEnd <= $end) {}
        else {
          unset($paid[$index]);
        }
      }

      if (count($paid) == 0) {
        $error = array('No signed timecards for the selected time period.');
        $errors = new MessageBag($error);
        return view('coordinator/payments/select')->with('errors',$errors);
      }

      return view('coordinator/payments/report')
        ->with('timecards', $paid)
        ->with('startDate', $startDate)
        ->with('endDate', $endDate);

    }
    public function paymentsGeneratePDF(Request $request) {
      $this->validate($request, [
        'startDate' => 'required|date',
        'endDate' => 'required|date'
      ]);

      $startDate = $request->input('startDate');
      $endDate = $request->input('endDate');

      $start = strtotime($startDate . " 00:00:00");
      $end = strtotime($endDate . " 23:59:59");

      $paid = Timecard::where('paid',1)->orderBy('startDate')->get();

      foreach($paid as $index => $timecard) {
        $cardStart = strtotime($timecard->startDate . " 00:00:00");
        $cardEnd = strtotime($timecard->endDate . " 23:59:59");

        if ($cardStart >= $start && $cardEnd <= $end) {}
        else {
          unset($paid[$index]);
        }
      }

      $workerPayments = $this->workerPaymentsForDate($startDate, $endDate);
      $totalPaid = $this->totalPaidForDate($startDate, $endDate);
      $tardies = $this->tardiesForDate($startDate, $endDate);
      $absences = $this->absencesForDate($startDate, $endDate);
      $unsatisfactoryGrades = $this->unsatisfactoryGradesForDate($startDate, $endDate);
      $outstandingGrades = $this->outstandingGradesForDate($startDate, $endDate);

      $html = view('coordinator/payments/generatepdf',
        [
          'startDate' => $startDate,
          'endDate' => $endDate,
          'workerPayments' => $workerPayments,
          'timecards' => $paid,
          'totalPaid' => $totalPaid,
          'tardies' => $tardies,
          'absences' => $absences,
          'unsatisfactoryGrades' => $unsatisfactoryGrades,
          'outstandingGrades' => $outstandingGrades
      ]);

      $pdf = App::make('dompdf.wrapper')->setPaper('a4', 'landscape');
      $pdf->loadHTML($html);
      return $pdf->stream();

    }
    public function showGenerateReport() {
      return view('coordinator/payments/generate');
    }
    public function generateReport(Request $request) {
      // request validation
      $this->validate($request, [
        'startDate' => 'required|date',
        'endDate' => 'required|date'
      ]);

      $startDate = $request->input('startDate');
      $endDate = $request->input('endDate');

      $start = strtotime($startDate . " 00:00:00");
      $end = strtotime($endDate. " 23:59:59");

      // get all paid timecards
      $paid = Timecard::where('paid', 1)->get();
      $paid = $paid->sortBy('startDate');

      // remove timecards not matching specified date
      foreach($paid as $index => $timecard) {
        $cardStart = strtotime($timecard->cardStart . " 00:00:00");
        $cardEnd = strtotime($timecard->endDate . " 23:59:59");

        if ($cardStart >= $start && $cardEnd <= $end) {}
        else {
          unset($paid[$index]);
        }
      }

      // if no timecards for time period, return with error
      if (count($paid) == 0) {
        $error = array('There are no timecards matching the selected time period.');
        $errors = new MessageBag($error);
        return back()->withInput()->with('errors', $errors);
      }

      return view('coordinator.payments.report')
        ->with('startDate', $startDate)
        ->with('endDate', $endDate)
        ->with('timecards', $paid);
    }

    public function showTimecardsCreate() {
      $role = session('role');
      if ($role !== "coordinator") {
        session()->flush();
        return redirect('/');
      }

      return view('/coordinator/timecards/create');
    }
    public function showTimecardsActive() {
      $timecards = $this->activeTimecards();

      return $timecards;
    }
    public function showTimecardsUnsigned() {
      if (session('role') !== 'coordinator') {
        session()->flush();
        return redirect('/');
      }

      $unsigned = $this->unsignedTimecards();

      return view('/coordinator/timecards/unsigned')->with('timecards',$unsigned);
    }
    public function showTimecardsSubmitted() {
      if (session('role') !== 'coordinator') {
        session()->flush();
        return redirect('/');
      }

      $submitted = $this->submittedTimecards();

      // find and store start and end dates for these timecards
      $startDates = array();
      $endDates = array();

      foreach($submitted as $timecard) {
        $cardStart = $timecard->startDate;
        $cardEnd = $timecard->endDate;

        $startDates[] = $cardStart;
        $endDates[] = $cardEnd;
      }

      foreach($startDates as $date) {
        $date = strtotime($date);
      }
      foreach($endDates as $date) {
        $date = strtotime($date);
      }

      if (empty($startDates) && empty($endDates)){
        return back()->with('status', 'No submitted timecards.');
      }

      sort($startDates);
      rsort($endDates);

      $startDate = date('Y-m-d', strtotime($startDates[0]));
      $endDate = date('Y-m-d', strtotime($endDates[0]));

      // return view with variables
      return view('/coordinator/timecards/submitted')
        ->with('submitted', $submitted)
        ->with('startDate', $startDate)
        ->with('endDate', $endDate);

    }

    public function timecardsCreate(Request $request) {
      $this->validate($request, [
        'startDate' => 'date|required'
      ]);

      $startDate = $request->input('startDate');

      // check if date is a sunday
      $timestamp = strtotime($startDate);
      $day = date('D', $timestamp);
      if ($day !== 'Sun') {

        $message = array('Starting date must be on a Sunday.');
        $errors = new MessageBag($message);
        return back()->withInput()->with('errors', $errors);
      }

      // construct endDate
      $endTimestamp = strtotime('+6 days', strtotime($startDate));
      $endDate = date('Y-m-d', $endTimestamp);

      $skipped = 0;
      // all workers
      $workers = DB::table('workers')->get();
      foreach($workers as $worker) {

        $entity = new Worker();
        $entity->email = $worker->email;

        $departments = $entity->departments();
        foreach($departments as $department) {

          //check if timecard does not already exist
          $exists = DB::table('timecards')->where('worker', $worker->email)->where('department', $department)->
                    where('startDate', $startDate)->where('endDate', $endDate)->get();

          if (count($exists) !== 0) { $skipped++;}  // do nothing if timecard already exists
          else {
            $timecard = new Timecard;
            $timecard->worker = $worker->email;
            $timecard->name = $worker->name;
            $timecard->department = $department;
            $timecard->startDate = $startDate;
            $timecard->endDate = $endDate;

            $timecard->create();
          }

        }
      }

      return redirect('/coordinator')->with('status', 'Timecards successfully created.');
    }

    public function activeTimecards() {
      $start = "";
      $end = "";

      // get the day today
      $day = date('D');

      if ($day === 'Sun') {
        $start = strtotime('today');
        $start = date('Y-m-d', $start);

        $end = strtotime('today');
        $end = strtotime('+6 days', $end);
        $end = date('Y-m-d', $end);

      }

      else if ($day === 'Sat') {
        $end = strtotime('today');
        $end = date('Y-m-d', $end);

        $start = strtotime('Sunday last week');
        $start = date('Y-m-d', $start);
      }

      else {
        $start = strtotime('Sunday last week');
        $start = date('Y-m-d', $start);

        $end = strtotime('Saturday this week');
        $end = date('Y-m-d', $end);
      }

      $timecards = Timecard::where('startDate', $start)->where('endDate', $end)->get();

      return view('/coordinator/timecards/active')->with('timecards', $timecards);
    }
    public function unsignedTimecards() {
      $start = "";

      $day = date('D');

      if ($day === 'Sun') {
        $start = strtotime('today');
        $start = date('Y-m-d', $start);
        $start = $start . " 00:00:00";
        $start = strtotime($start);

      }
      else {
        $start = strtotime('Sunday last week');
        $start = date('Y-m-d', $start);
        $start = $start . " 00:00:00";
        $start = strtotime($start);

      }

      $timecards = Timecard::where('signed', 0)->get();

      foreach ($timecards as $index => $timecard) {
        $cardEnd = $timecard->endDate;
        $cardEnd = $cardEnd . " 23:59:59";
        $cardEnd = strtotime($cardEnd);

        if ($cardEnd > $start) {
          unset($timecards[$index]);
        }

      }

      return $timecards;
    }
    public function submittedTimecards() {
      $timecards = Timecard::where('signed',1)->where('paid',0)->get();

      return $timecards;
    }
    public function countActiveTimecards() {
      $start = "";
      $end = "";

      // check if today is Sunday
      $day = date('D');

      if ($day === 'Sun') {
        $start = strtotime('today');
        $start = date('Y-m-d', $start);
        $start = $start . " 00:00:00";
        $start = strtotime($start);

        $end = strtotime('today');
        $end = strtotime('+6 days', $end);
        $end = date('Y-m-d', $end);
        $end = $end . " 23:59:59";
        $end = strtotime($end);

      }

      if ($day === 'Sat') {
        $start = strtotime('Sunday last week');
        $start = date('Y-m-d', $start);
        $start = $start . " 00:00:00";
        $start = strtotime($start);

        $end = strtotime('today');
        $end = date('Y-m-d', $end);
        $end = $end . " 23:59:59";
        $end = strtotime($end);
      }

      else {
        $start = strtotime('Sunday last week');
        $start = date('Y-m-d', $start);
        $start = $start . " 00:00:00";
        $start = strtotime($start);

        $end = strtotime('Saturday this week');
        $end = date('Y-m-d', $end);
        $end = $end . " 23:59:59";
        $end = strtotime($end);

      }

      // get all unsigned timecards
      $unpaid = Timecard::where('paid',0)->get();

      foreach ($unpaid as $index => $timecard) {
        $cardStart = strtotime($timecard->startDate . " 00:00:00");
        $cardEnd = strtotime($timecard->endDate . " 23:59:59");

        if ($cardStart >= $start && $cardEnd <= $end) {}
        else {
          unset($unpaid[$index]);
        }
      }

      $count = count($unpaid);

      return $count;

    }
    public function countUnsignedTimecards() {
      $start = "";

      $today = strtotime('today');
      $day = date('D');

      if ($day === 'Sun') {
        $start = strtotime('today');
        $start = date('Y-m-d', $start);
        $start = $start . " 00:00:00";
        $start = strtotime($start);
      }
      else {
        $start = strtotime('Sunday last week');
        $start = date('Y-m-d', $start);
        $start = $start . " 00:00:00";
        $start = strtotime($start);
      }
      $count = 0;
      // get all unsigned timecards
      $unsigned = DB::table('timecards')->where('signed', 0)->get();
      if (count($unsigned) !== 0) {

        foreach($unsigned as $timecard) {
          $cardEnd = strtotime($timecard->endDate);
          if ($cardEnd <= $start) {
            $count++;
          }
        }
      }
      else { return 0; }

      return $count;
    }
    public function countSubmittedTimecards() {
      $count = DB::table('timecards')->where('signed', 1)->where('paid', 0)->count();

      return $count;
    }
    public function getPayscales() {
      $payscales = array();

      $rows = DB::table('payscales')->get();

      foreach($rows as $payscale) {
        $payscales[$payscale->grade] = $payscale->pay;
      }
      return $payscales;
    }
    public function getTotalPaid() {
      $paid = Timecard::where('paid',1)->get();

      $total = 0;

      foreach($paid as $timecard) {
        $total = $total + $timecard->pay;
      }

      return number_format($total);
    }
    public function totalPaidForDate($startDate, $endDate) {
      $paid = Timecard::where('paid',1)->get();

      $start = strtotime($startDate . " 00:00:00");
      $end = strtotime($endDate . " 23:59:59");

      foreach ($paid as $index => $timecard) {
        $cardStart = strtotime($timecard->startDate);
        $cardEnd = strtotime($timecard->endDate);

        if ($cardStart >= $start && $cardEnd <= $end) {}
        else {
          unset($paid[$index]);
        }
      }

      $total = 0;

      foreach ($paid as $timecard) {
        $total += $timecard->pay;
      }

      return number_format($total);
    }
    public function topWorkers() {

      $workers = Worker::get();

      $rankings = array();

      foreach($workers as $worker) {
        $total = $worker->totalEarnings();

        $rankings[$worker->name] = $total;
      }

      arsort($rankings);
      return $rankings;
    }
    public function tardiesForDate($startDate, $endDate) {

      $start = strtotime($startDate . " 00:00:00");
      $end = strtotime($endDate . " 23:59:59");

      $workers = Worker::get();

      $tardiesArray = array();

      foreach ($workers as $worker) {
        $timecards = Timecard::where('worker', $worker->email)->where('paid', 1)->get();

        $count = 0;

        foreach ($timecards as $index => $timecard) {
          $cardStart = strtotime($timecard->startDate . " 00:00:00");
          $cardEnd = strtotime($timecard->endDate . " 23:59:59");

          if ($cardStart >= $start && $cardEnd <= $end) {}
          else {
            unset($timecards[$index]);
          }
        }

        foreach($timecards as $index => $timecard) {
          $tardies = $timecard->tardies();

          $count += $tardies;
        }

        if ($count != 0) {
          $tardiesArray[] = array('name' => $worker->name, 'tardies' => $count);
        } else { continue; }
      }

      return $tardiesArray;

    }
    public function absencesForDate($startDate, $endDate) {
      $start = strtotime($startDate . " 00:00:00");
      $end = strtotime($endDate . " 23:59:59");

      $workers = Worker::get();

      $absencesArray = array();

      foreach ($workers as $worker) {
        $timecards = Timecard::where('worker', $worker->email)->where('paid', 1)->get();

        $count = 0;

        foreach ($timecards as $index => $timecard) {
          $cardStart = strtotime($timecard->startDate . " 00:00:00");
          $cardEnd = strtotime($timecard->endDate . " 23:59:59");

          if ($cardStart >= $start && $cardEnd <= $end) {}
          else {
            unset($timecards[$index]);
          }
        }

        foreach($timecards as $index => $timecard) {
          $absences = $timecard->absences();

          $count += $absences;
        }

        if ($count != 0) {
          $absencesArray[] = array('name' => $worker->name, 'absences' => $count);
        } else { continue; }
      }

      return $absencesArray;
    }
    public function workerPaymentsForDate($startDate, $endDate) {

      $workers = Worker::get();

      $array = array();
      foreach ($workers as $worker) {
        $sum = $worker->paymentForDate($startDate, $endDate);

        $array[$worker->name] = $sum;
      }

      return $array;
    }
    public function unsatisfactoryGradesForDate($startDate, $endDate) {
      $start = strtotime($startDate . " 00:00:00");
      $end = strtotime($endDate . " 23:59:59");

      $paid = Timecard::where('paid', 1)->where('grade', 'u')->get();

      foreach ($paid as $index => $timecard) {
        $cardStart = strtotime($timecard->startDate . " 00:00:00");
        $cardEnd = strtotime($timecard->endDate . " 23:59:59");

        if ($cardStart >= $start && $cardEnd <= $end) {}
        else {
          unset($paid[$index]);
        }
      }

      return $paid->sortBy('name');
    }
    public function outstandingGradesForDate($startDate, $endDate) {
      $start = strtotime($startDate . " 00:00:00");
      $end = strtotime($endDate . " 23:59:59");

      $paid = Timecard::where('paid', 1)->where('grade', 'o')->get();

      foreach ($paid as $index => $timecard) {
        $cardStart = strtotime($timecard->startDate . " 00:00:00");
        $cardEnd = strtotime($timecard->endDate . " 23:59:59");

        if ($cardStart >= $start && $cardEnd <= $end) {}
        else {
          unset($paid[$index]);
        }
      }

      return $paid->sortBy('startDate');
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: SparcISA::TagOverflow Class Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

Alphabetical List

Class List

Class Hierarchy

Class Members

SparcISA::TagOverflow

SparcISA::TagOverflow Class Reference
#include <faults.hh>

Inheritance diagram for SparcISA::TagOverflow:

<map name="SparcISA::TagOverflow_map">
<area href="classSparcISA_1_1SparcFault.html" alt="SparcISA::SparcFault< T >" shape="rect" coords="0,168,165,192">
<area href="classSparcISA_1_1SparcFaultBase.html" alt="SparcISA::SparcFaultBase" shape="rect" coords="0,112,165,136">
<area href="classFaultBase.html" alt="FaultBase" shape="rect" coords="0,56,165,80">
<area href="classRefCounted.html" alt="RefCounted" shape="rect" coords="0,0,165,24">
</map>
List of all members.

Detailed Description

Definition at line 130 of file faults.hh.
The documentation for this class was generated from the following file:

arch/sparc/faults.hh

<address style="align: right;">
Generated on Fri Apr 17 12:41:36 2015 for gem5 by  doxygen 1.4.7</address>

redpajama_set_name: RedPajamaGithub


text:
<html>
    <head>
	    <title>Angular 2 TypeScript</title>
        <script src="../node_modules/systemjs/dist/system.src.js"></script>
        <script src="../node_modules/angular2/bundles/angular2.dev.js"></script>
        <script>
            System.config({
                packages: {'app': {defaultExtension: 'js'}}
            });
            System.import('app/app');
        </script>

    </head>

    <body>
        <ts-comp></ts-comp>
    </body>
</html>


text:
'use strict';

var React = require('react-native');

var C = require('./iOS/App/c');
var LoginOrRegister = require('./iOS/App/Components/LoginOrRegister');

var {
  AppRegistry,
  NavigatorIOS,
  StyleSheet,
  Text,
  View,
} = React;

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row'
  }
});

var mobile = React.createClass({
  render: function() {
    return (
        <NavigatorIOS
        style={ styles.container }
        initialRoute={{
          title: `Welcome to ${ C.AppName }`,
          component: LoginOrRegister
        }} />
    );
  }
});

AppRegistry.registerComponent('mobile', () => mobile);


text:
var pollCurrentTrack = function() {
   $.getJSON( "http://stream.idmradio.net:8000/status-json.xsl", function( data ) {
      $('.currently_playing').text('now playing : ' + data.icestats.source.title.toLowerCase());
      setTimeout(function(){pollCurrentTrack()}, 5000);
   });
}

$(document).ready(function(){
   pollCurrentTrack();
});


text:
@interface MaoBoLiVC : BaseVC

@end


text:
package com.rabidllamastudios.avigate.models;

import android.content.Intent;
import android.os.Bundle;

import com.rabidllamastudios.avigate.AvigateApplication;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * A data model class to communicate data to and from the Arduino
 * Can be constructed from a Bundle and converted into an Intent
 * This class stores Arduino configuration and commands as a JSON object & can return a JSON string
 * Created by Ryan Staatz on 11/30/15.
 **/
public class ArduinoPacket {
    private static final String PACKAGE_NAME = AvigateApplication.class.getPackage().getName();

    /** Intent action denoting that the ArduinoPacket is to be sent to the Arduino */
    public static final String INTENT_ACTION_INPUT = PACKAGE_NAME + ".action.ARDUINO_INPUT";
    /** Intent action denoting that the ArduinoPacket was created from data sent from the Arduino */
    public static final String INTENT_ACTION_OUTPUT = PACKAGE_NAME + ".action.ARDUINO_OUTPUT";

    //Key for the root JSON String of the ArduinoPacket when stored as a String Intent extra
    private static final String KEY_ROOT = "json";

    //JSON keys for key value pairs
    private static final String KEY_CALIBRATION_MODE = "calibrationMode";
    private static final String KEY_ERROR = "error";
    private static final String KEY_INPUT_CONFIG = "inputConfig";
    private static final String KEY_MAX = "max";
    private static final String KEY_MIN = "min";
    private static final String KEY_OUTPUT_CONFIG = "outputConfig";
    private static final String KEY_PIN = "pin";
    private static final String KEY_RECEIVER_CONTROL = "receiverControl";
    private static final String KEY_RECEIVER_ONLY = "receiverOnly";
    private static final String KEY_REQUEST = "request";
    private static final String KEY_STATUS = "status";
    private static final String KEY_VALUE ="value";

    //preset JSON value(s) for key value pairs
    private static final String VALUE_STATUS_READY = "ready";

    /** Denotes the type of servo on the craft. Cutover can refer to a transmitter gear switch */
    public enum ServoType {
        AILERON, ELEVATOR, RUDDER, THROTTLE, CUTOVER;

        /** Returns the corresponding String for the defined ServoType */
        public String getStringValue() {
            switch (this) {
                case AILERON:
                    return "aileron";
                case ELEVATOR:
                    return "elevator";
                case RUDDER:
                    return "rudder";
                case THROTTLE:
                    return "throttle";
                case CUTOVER:
                    return "cutover";
            }
            return null;
        }
    }

    private JSONObject rootJson;  //The JSON root object where all JSON data is stored

    public ArduinoPacket() {
        rootJson = new JSONObject();
    }

    /** Constructor that takes a JSON String. Use toIntent or toJsonString methods to export data */
    public ArduinoPacket(String jsonString) {
        rootJson = new JSONObject();
        try {
            rootJson = (JSONObject) new JSONParser().parse(jsonString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /** Constructor that takes a bundle */
    public ArduinoPacket(Bundle bundle) {
        rootJson = new JSONObject();
        try {
            rootJson = (JSONObject) new JSONParser().parse(bundle.getString(KEY_ROOT));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /** Returns an Intent with the ArduinoPacket contents packaged as an Intent Extra */
    public Intent toIntent(String intentAction) {
        Intent intent = new Intent(intentAction);
        intent.putExtra(KEY_ROOT, rootJson.toJSONString());
        return intent;
    }

    /** Returns the stored JSON data as a string */
    public String toJsonString() {
        return rootJson.toJSONString();
    }

    /** Adds an Arduino status request to the JSON store */
    @SuppressWarnings("unchecked")
    public void addStatusRequest() {
        rootJson.put(KEY_REQUEST, KEY_STATUS);
    }

    /** Compares this ArduinoPacket with another ArduinoPacket
     * @param arduinoPacketObject the ArduinoPacket to compare
     * @return true if both ArduinoPackets have the same contents (JSON order does not matter)
     */
    @Override
    public boolean equals(Object arduinoPacketObject) {
        if (arduinoPacketObject == null) return false;
        if (!(arduinoPacketObject instanceof ArduinoPacket)) return false;
        ArduinoPacket arduinoPacket = (ArduinoPacket) arduinoPacketObject;
        String arduinoPacketJsonString = arduinoPacket.toJsonString();
        if (arduinoPacketJsonString == null) return false;
        JSONObject otherRootJson = new JSONObject();
        try {
            otherRootJson = (JSONObject) new JSONParser().parse(arduinoPacketJsonString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return servoEquals(otherRootJson, ServoType.AILERON)
                && servoEquals(otherRootJson, ServoType.ELEVATOR)
                && servoEquals(otherRootJson, ServoType.RUDDER)
                && servoEquals(otherRootJson, ServoType.THROTTLE)
                && servoEquals(otherRootJson, ServoType.CUTOVER);
    }

    /** Returns a JSON String containing the configuration values for the input ServoType
     * @param servoType the ServoType to retrieve the config JSON for
     * @param includeInputRanges determines whether the input min and max are included in the output
     * @return a JSON String with the config values. Returns null if no config exists.
     */
    @SuppressWarnings("unchecked")
    public String getConfigJson(ServoType servoType, boolean includeInputRanges) {
        if (rootJson.containsKey(servoType.getStringValue())) {
            JSONObject servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            //Don't include input range values from the input config
            JSONObject newInputConfigJson = new JSONObject();
            if (servoJson.containsKey(KEY_INPUT_CONFIG)) {
                JSONObject inputConfigJson = (JSONObject) servoJson.get(KEY_INPUT_CONFIG);
                if (includeInputRanges) {
                    if (inputConfigJson.containsKey(KEY_MAX)) {
                        newInputConfigJson.put(KEY_MAX, inputConfigJson.get(KEY_MAX));
                    }
                    if (inputConfigJson.containsKey(KEY_MIN)) {
                        newInputConfigJson.put(KEY_MIN, inputConfigJson.get(KEY_MIN));
                    }
                }
                if (inputConfigJson.containsKey(KEY_PIN)) {
                    newInputConfigJson.put(KEY_PIN, inputConfigJson.get(KEY_PIN));
                }
                if (inputConfigJson.containsKey(KEY_RECEIVER_ONLY)) {
                    newInputConfigJson.put(KEY_RECEIVER_ONLY,
                            inputConfigJson.get(KEY_RECEIVER_ONLY));
                }
            }
            //Keep all output config values
            JSONObject newOutputConfigJson = new JSONObject();
            if (servoJson.containsKey(KEY_OUTPUT_CONFIG)) {
                JSONObject outputConfigJson = (JSONObject) servoJson.get(KEY_OUTPUT_CONFIG);
                if (outputConfigJson.containsKey(KEY_MAX)) {
                    newOutputConfigJson.put(KEY_MAX, outputConfigJson.get(KEY_MAX));
                }
                if (outputConfigJson.containsKey(KEY_MIN)) {
                    newOutputConfigJson.put(KEY_MIN, outputConfigJson.get(KEY_MIN));
                }
                if (outputConfigJson.containsKey(KEY_PIN)) {
                    newOutputConfigJson.put(KEY_PIN, outputConfigJson.get(KEY_PIN));
                }
            }
            JSONObject newServoJson = new JSONObject();
            newServoJson.put(KEY_INPUT_CONFIG, newInputConfigJson);
            newServoJson.put(KEY_OUTPUT_CONFIG, newOutputConfigJson);
            JSONObject newRootJson = new JSONObject();
            newRootJson.put(servoType.getStringValue(), newServoJson);
            return newRootJson.toJSONString();
        }
        return null;
    }

    /** Retrieves any error message if present. Error messages only originate from the Arduino. */
    public String getErrorMessage() {
        if (rootJson.containsKey(KEY_ERROR)) return (String) rootJson.get(KEY_ERROR);
        return null;
    }

    /** Returns a JSONObject that contains the receiver input range for the input ServoType
     * @param servoType the
     * @return a JSONObject with the min and max receiver inputs. Returns null if no range exists.
     */
    @SuppressWarnings("unchecked")
    public String getInputRangeJson(ServoType servoType) {
        if (rootJson.containsKey(servoType.getStringValue())) {
            JSONObject servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_INPUT_CONFIG)) {
                JSONObject inputConfigJson = (JSONObject) servoJson.get(KEY_INPUT_CONFIG);
                if (inputConfigJson.containsKey(KEY_MAX) && inputConfigJson.containsKey(KEY_MIN)) {
                    JSONObject inputRangeJson = new JSONObject();
                    inputRangeJson.put(KEY_MAX, inputConfigJson.get(KEY_MAX));
                    inputRangeJson.put(KEY_MIN, inputConfigJson.get(KEY_MIN));
                    JSONObject newServoJson = new JSONObject();
                    newServoJson.put(KEY_INPUT_CONFIG, inputRangeJson);
                    JSONObject newRootJson = new JSONObject();
                    newRootJson.put(servoType.getStringValue(), newServoJson);
                    return newRootJson.toJSONString();
                }
            }
        }
        return null;
    }

    /** Gets the max receiver input value for the input ServoType. Returns -1 if no value exists */
    public int getInputMax(ServoType servoType) {
        Number inputMax = (Number) getInputConfigValue(servoType, KEY_MAX);
        if (inputMax == null) return -1;
        return inputMax.intValue();
    }

    /** Gets the min receiver input value for the input ServoType. Returns -1 if no value exists */
    public int getInputMin(ServoType servoType) {
        Number inputMin = (Number) getInputConfigValue(servoType, KEY_MIN);
        if (inputMin == null) return -1;
        return inputMin.intValue();
    }

    /** Gets the input pin for the input ServoType. Returns -1 if no value exists */
    public int getInputPin(ServoType servoType) {
        Number inputPin = (Number) getInputConfigValue(servoType, KEY_PIN);
        if (inputPin == null) return -1;
        return inputPin.intValue();
    }

    /** Gets the max servo output value for the input ServoType. Returns -1 if no value exists */
    public int getOutputMax(ArduinoPacket.ServoType servoType) {
        Number outputMax = getOutputConfigValue(servoType, KEY_MAX);
        if (outputMax == null) return -1;
        return outputMax.intValue();
    }

    /** Gets the min servo output value for the input ServoType. Returns -1 if no value exists */
    public int getOutputMin(ArduinoPacket.ServoType servoType) {
        Number outputMin = getOutputConfigValue(servoType, KEY_MIN);
        if (outputMin == null) return -1;
        return outputMin.intValue();
    }

    /** Gets the servo output pin for the input ServoType. Returns -1 if no value exists */
    public int getOutputPin(ServoType servoType) {
        Number outputPin =  getOutputConfigValue(servoType, KEY_PIN);
        if (outputPin == null) return -1;
        return outputPin.intValue();
    }

    /** Gets the position value in degrees) of a given ServoType. Returns -1 if no value exists */
    public int getServoValue(ServoType servoType) {
        //Returns -1 if said value does not exist
        if (rootJson.containsKey(servoType.getStringValue())) {
            JSONObject servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_VALUE)) {
                Number value = (Number) servoJson.get(KEY_VALUE);
                if (value != null) return value.intValue();
            }
        }
        return -1;
    }

    /** Returns true if the JSON store contains the calibrationMode JSON key */
    public boolean hasCalibrationMode() {
        return rootJson.containsKey(KEY_CALIBRATION_MODE);
    }

    /** Returns true if the JSON store contains duplicate pin numbers (input and output) */
    public boolean hasDuplicatePins() {
        List<Integer> pinList = new ArrayList<>();
        //Add output pin values
        if (getOutputPin(ServoType.AILERON) != -1) pinList.add(getOutputPin(ServoType.AILERON));
        if (getOutputPin(ServoType.ELEVATOR) != -1) pinList.add(getOutputPin(ServoType.ELEVATOR));
        if (getOutputPin(ServoType.RUDDER) != -1) pinList.add(getOutputPin(ServoType.RUDDER));
        if (getOutputPin(ServoType.THROTTLE) != -1) pinList.add(getOutputPin(ServoType.THROTTLE));

        //Add input pin values
        if (getInputPin(ServoType.AILERON) != -1) pinList.add(getInputPin(ServoType.AILERON));
        if (getInputPin(ServoType.ELEVATOR) != -1) pinList.add(getInputPin(ServoType.ELEVATOR));
        if (getInputPin(ServoType.RUDDER) != -1) pinList.add(getInputPin(ServoType.RUDDER));
        if (getInputPin(ServoType.THROTTLE) != -1) pinList.add(getInputPin(ServoType.THROTTLE));
        if (getInputPin(ServoType.CUTOVER) != -1) pinList.add(getInputPin(ServoType.CUTOVER));

        //Since sets do not allow duplicates, there are duplicates if the size of the set is smaller
        Set<Integer> pinSet = new HashSet<>(pinList);
        return pinSet.size() < pinList.size();
    }

    /** Returns true if the JSON store contains an error. Errors only originate from the Arduino */
    public boolean hasErrorMessage() {
        return rootJson.containsKey(KEY_ERROR);
    }

    /** Returns true if the JSON store contains a receiver input max for the input ServoType */
    public boolean hasInputMax(ServoType servoType) {
        return hasInputConfigValue(servoType, KEY_MAX);
    }

    /** Returns true if the JSON store contains a receiver input min for the input ServoType */
    public boolean hasInputMin(ServoType servoType) {
        return hasInputConfigValue(servoType, KEY_MIN);
    }

    /** Returns true if the JSON store contains a receiver input pin for the input ServoType */
    public boolean hasInputPin(ServoType servoType) {
        return hasInputConfigValue(servoType, KEY_PIN);
    }

    /** Returns true if all of the receiver input values have been set via calibration */
    public boolean hasInputRanges() {
        return (hasInputRange(ServoType.AILERON) && hasInputRange(ServoType.CUTOVER)
                && hasInputRange(ServoType.ELEVATOR) && hasInputRange(ServoType.RUDDER)
                && hasInputRange(ServoType.THROTTLE));
    }

    /** Returns true if the JSON store contains an output max value for the input ServoType */
    public boolean hasOutputMax(ServoType servoType) {
        return hasOutputConfigValue(servoType, KEY_MAX);
    }

    /** Returns true if the JSON store contains an output min value for the input ServoType */
    public boolean hasOutputMin(ServoType servoType) {
        return hasOutputConfigValue(servoType, KEY_MIN);
    }

    /** Returns true if the JSON store contains an output pin for the input ServoType */
    public boolean hasOutputPin(ServoType servoType) {
        return hasOutputConfigValue(servoType, KEY_PIN);
    }

    /** Returns true if the JSON store indicates that the Arduino will only accept receiver input */
    public boolean hasReceiverControl() {
        return rootJson.containsKey(KEY_RECEIVER_CONTROL);
    }

    /** Returns true if the input ServoType has been configured to only accept receiver input */
    public boolean hasReceiverOnly(ServoType servoType) {
        return hasInputConfigValue(servoType, KEY_RECEIVER_ONLY);
    }

    /** Returns true if the JSON store contains a servo position value for the input ServoType */
    public boolean hasServoValue(ServoType servoType) {
        if (rootJson.containsKey(servoType.getStringValue())) {
            JSONObject servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            return servoJson.containsKey(KEY_VALUE);
        }
        return false;
    }

    /** Returns true if the JSON store contains any servo output values */
    public boolean hasServoValue() {
        return (hasServoValue(ServoType.AILERON) || hasServoValue(ServoType.ELEVATOR)
                || hasServoValue(ServoType.RUDDER) || hasServoValue(ServoType.THROTTLE));
    }

    /** Returns true if the Arduino is now in calibration mode.
     * Use hasCalibrationMode method to determine whether to use this method
     * @return true if in calibration mode, false if in standard operating mode
     */
    public boolean isCalibrationMode() {
        return (boolean) rootJson.get(KEY_CALIBRATION_MODE);
    }

    /** Returns true if the Arduino is currently only accepting receiver input
     * Use hasReceiverControl method to determine whether to use this method
     * @return true if only accepting receiver input, false if accepting phone and receiver input
     */
    public boolean isReceiverControl() {
        return (boolean) rootJson.get(KEY_RECEIVER_CONTROL);
    }

    /** Returns true if the input servoType is only accepting receiver input, and not phone input */
    public boolean isReceiverOnly(ServoType servoType) {
        return (boolean) getInputConfigValue(servoType, KEY_RECEIVER_ONLY);
    }

    /** Returns true if the Arduino is ready to receive input from the phone */
    public boolean isStatusReady() {
        return rootJson.containsKey(KEY_STATUS)
                && rootJson.get(KEY_STATUS).equals(VALUE_STATUS_READY);
    }

    /** Tells the Arduino whether it should enter or leave calibration mode
     * Calibration mode is used to set the receiver input range for each configured servo
     * @param calibrationMode if true, the Arduino enters calibration mode, if false, leaves it
     */
    @SuppressWarnings("unchecked")
    public void setCalibrationMode(boolean calibrationMode) {
        rootJson.put(KEY_CALIBRATION_MODE, calibrationMode);
    }

    /** Sets the input control type for the input ServoType based on the input receiverOnly boolean
     * @param servoType the ServoType to set the input control property for
     * @param receiverOnly if true, the Arduino only accepts receiver input for this ServoType
     */
    @SuppressWarnings("unchecked")
    public void setInputControl(ServoType servoType, boolean receiverOnly) {
        JSONObject servoJson = new JSONObject();
        JSONObject inputConfigJson = new JSONObject();
        if (rootJson.containsKey(servoType.getStringValue())) {
            servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_INPUT_CONFIG)) {
                inputConfigJson = (JSONObject) servoJson.get(KEY_INPUT_CONFIG);
            }
        }
        inputConfigJson.put(KEY_RECEIVER_ONLY, receiverOnly);
        servoJson.put(KEY_INPUT_CONFIG, inputConfigJson);
        rootJson.put(servoType.getStringValue(), servoJson);
    }

    /** Sets the receiver input pin for the input ServoType */
    @SuppressWarnings("unchecked")
    public void setInputPin(ServoType servoType, int pinNumber) {
        JSONObject servoJson = new JSONObject();
        JSONObject inputConfigJson = new JSONObject();
        if (rootJson.containsKey(servoType.getStringValue())) {
            servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_INPUT_CONFIG)) {
                inputConfigJson = (JSONObject) servoJson.get(KEY_INPUT_CONFIG);
            }
        }
        inputConfigJson.put(KEY_PIN, (long) pinNumber);
        servoJson.put(KEY_INPUT_CONFIG, inputConfigJson);
        rootJson.put(servoType.getStringValue(), servoJson);
    }

    /** Sets the min and max receiver input values (in microseconds) based on the input ServoType
     * @param servoType the ServoType to set the input range for
     * @param inputMin the calibrated receiver input minimum for the input ServoType (microseconds)
     * @param inputMax the calibrated receiver input maximum for the input ServoType (microseconds)
     */
    @SuppressWarnings("unchecked")
    public void setInputRange(ServoType servoType, int inputMin, int inputMax) {
        JSONObject servoJson = new JSONObject();
        JSONObject inputConfigJson = new JSONObject();
        if (rootJson.containsKey(servoType.getStringValue())) {
            servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_INPUT_CONFIG)) {
                inputConfigJson = (JSONObject) servoJson.get(KEY_INPUT_CONFIG);
            }
        }
        inputConfigJson.put(KEY_MAX, (long) inputMax);
        inputConfigJson.put(KEY_MIN, (long) inputMin);
        servoJson.put(KEY_INPUT_CONFIG, inputConfigJson);
        rootJson.put(servoType.getStringValue(), servoJson);
    }

    /** Sets the min and max output values for the input ServoType (in degrees)
     * @param servoType the ServoType to set the output range for
     * @param outputMin the servo output minimum for the input ServoType (in degrees)
     * @param outputMax the servo output maximum for the input ServoType (in degrees)
     */
    @SuppressWarnings("unchecked")
    public void setOutputRange(ServoType servoType, int outputMin, int outputMax) {
        JSONObject servoJson = new JSONObject();
        JSONObject outputConfigJson = new JSONObject();
        if (rootJson.containsKey(servoType.getStringValue())) {
            servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_OUTPUT_CONFIG)) {
                outputConfigJson = (JSONObject) servoJson.get(KEY_OUTPUT_CONFIG);
            }
        }
        outputConfigJson.put(KEY_MAX, (long) outputMax);
        outputConfigJson.put(KEY_MIN, (long) outputMin);
        servoJson.put(KEY_OUTPUT_CONFIG, outputConfigJson);
        rootJson.put(servoType.getStringValue(), servoJson);
    }

    /** Sets the servo output pin number for the input ServoType */
    @SuppressWarnings("unchecked")
    public void setOutputPin(ServoType servoType, int pinNumber) {
        JSONObject servoJson = new JSONObject();
        JSONObject outputConfigJson = new JSONObject();
        if (rootJson.containsKey(servoType.getStringValue())) {
            servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_OUTPUT_CONFIG)) {
                outputConfigJson = (JSONObject) servoJson.get(KEY_OUTPUT_CONFIG);
            }
        }
        outputConfigJson.put(KEY_PIN, (long) pinNumber);
        servoJson.put(KEY_OUTPUT_CONFIG, outputConfigJson);
        rootJson.put(servoType.getStringValue(), servoJson);
    }

    /** Sets the positional output value of the input ServoType (in degrees) */
    @SuppressWarnings("unchecked")
    public void setServoValue(ServoType servoType, int value) {
        JSONObject servoJson = new JSONObject();
        if (rootJson.containsKey(servoType.getStringValue())) {
            servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
        }
        servoJson.put(KEY_VALUE, (long) value);
        rootJson.put(servoType.getStringValue(), servoJson);
    }

    //Returns the input min, max, or pin (as specified by jsonMinMaxKey)
    private Object getInputConfigValue(ServoType servoType, String jsonKey) {
        if (rootJson.containsKey(servoType.getStringValue())) {
            JSONObject servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_INPUT_CONFIG)) {
                JSONObject inputConfigJson = (JSONObject) servoJson.get(KEY_INPUT_CONFIG);
                if (inputConfigJson.containsKey(jsonKey)) {
                    return inputConfigJson.get(jsonKey);
                }
            }
        }
        return null;
    }

    //Returns the output min, max, or pin (as specified by jsonMinMaxKey)
    private Number getOutputConfigValue(ServoType servoType, String jsonKey) {
        if (rootJson.containsKey(servoType.getStringValue())) {
            JSONObject servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_OUTPUT_CONFIG)) {
                JSONObject outputConfigJson = (JSONObject) servoJson.get(KEY_OUTPUT_CONFIG);
                if (outputConfigJson.containsKey(jsonKey)) {
                    return (Number) outputConfigJson.get(jsonKey);
                }
            }
        }
        return null;
    }

    //Checks whether rootJson contains an inputConfig that contains a jsonKey for a given ServoType
    private boolean hasInputConfigValue(ServoType servoType, String jsonKey) {
        if (rootJson.containsKey(servoType.getStringValue())) {
            JSONObject servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_INPUT_CONFIG)) {
                JSONObject inputConfigJson = (JSONObject) servoJson.get(KEY_INPUT_CONFIG);
                return inputConfigJson.containsKey(jsonKey);
            }
        }
        return false;
    }

    //Checks whether rootJson contains receiver input min and max values for a given ServoType
    private boolean hasInputRange(ServoType servoType) {
        return hasInputConfigValue(servoType, KEY_MIN) && hasInputConfigValue(servoType, KEY_MAX);
    }

    //Checks whether rootJson contains an outputConfig that contains a jsonKey for a given ServoType
    private boolean hasOutputConfigValue(ServoType servoType, String jsonKey) {
        if (rootJson.containsKey(servoType.getStringValue())) {
            JSONObject servoJson = (JSONObject) rootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_OUTPUT_CONFIG)) {
                JSONObject outputConfigJson = (JSONObject) servoJson.get(KEY_OUTPUT_CONFIG);
                return outputConfigJson.containsKey(jsonKey);
            }
        }
        return false;
    }

    //Takes a ServoType and another (separate) rootJson object
    //Returns true if the input JSON object has the same config as the ServoType JSON of rootJSON
    private boolean servoEquals(JSONObject otherRootJson, ServoType servoType) {
        if (otherRootJson.containsKey(servoType.getStringValue())) {
            JSONObject servoJson = (JSONObject) otherRootJson.get(servoType.getStringValue());
            if (servoJson.containsKey(KEY_INPUT_CONFIG)) {
                JSONObject inputConfigJson = (JSONObject) servoJson.get(KEY_INPUT_CONFIG);
                if (inputConfigJson.containsKey(KEY_MAX)) {
                    Number inputMax1 = (Number) inputConfigJson.get(KEY_MAX);
                    Number inputMax2 = (Number) getInputConfigValue(servoType, KEY_MAX);
                    if (inputMax1 != null && !inputMax1.equals(inputMax2)) return false;
                } else if (hasInputMax(servoType)) {
                    return false;
                }
                if (inputConfigJson.containsKey(KEY_MIN)) {
                    Number inputMin1 = (Number) inputConfigJson.get(KEY_MIN);
                    Number inputMin2 = (Number) getInputConfigValue(servoType, KEY_MIN);
                    if (inputMin1 != null && !inputMin1.equals(inputMin2)) return false;
                } else if (hasInputMin(servoType)) {
                    return false;
                }
                if (inputConfigJson.containsKey(KEY_PIN)) {
                    Number inputPin1 = (Number) inputConfigJson.get(KEY_PIN);
                    Number inputPin2 = (Number) getInputConfigValue(servoType, KEY_PIN);
                    if (inputPin1 != null && !inputPin1.equals(inputPin2)) return false;
                } else if (hasInputPin(servoType)) {
                    return false;
                }
                if (inputConfigJson.containsKey(KEY_RECEIVER_ONLY)) {
                    boolean receiverOnly1 = (boolean) inputConfigJson.get(KEY_RECEIVER_ONLY);
                    boolean receiverOnly2 = (boolean) getInputConfigValue(servoType,
                            KEY_RECEIVER_ONLY);
                    if (receiverOnly1 != receiverOnly2) return false;
                } else if (hasReceiverOnly(servoType)) {
                    return false;
                }
            } else if (hasInputRange(servoType) || hasInputPin(servoType)
                    || hasReceiverOnly(servoType)) {
                return false;
            }

            if (servoJson.containsKey(KEY_OUTPUT_CONFIG)) {
                JSONObject outputConfigJson = (JSONObject) servoJson.get(KEY_OUTPUT_CONFIG);
                if (outputConfigJson.containsKey(KEY_MAX)) {
                    Number outputMax1 = (Number) outputConfigJson.get(KEY_MAX);
                    Number outputMax2 = getOutputConfigValue(servoType, KEY_MAX);
                    if (outputMax1 != null && !outputMax1.equals(outputMax2)) return false;
                } else if (hasOutputMax(servoType)) {
                    return false;
                }
                if (outputConfigJson.containsKey(KEY_MIN)) {
                    Number outputMin1 = (Number) outputConfigJson.get(KEY_MIN);
                    Number outputMin2 = getOutputConfigValue(servoType, KEY_MIN);
                    if (outputMin1 != null && !outputMin1.equals(outputMin2)) return false;
                } else if (hasOutputMin(servoType)) {
                    return false;
                }
                if (outputConfigJson.containsKey(KEY_PIN)) {
                    Number outputPin1 = (Number) outputConfigJson.get(KEY_PIN);
                    Number outputPin2 = getOutputConfigValue(servoType, KEY_PIN);
                    if (outputPin1 != null && !outputPin1.equals(outputPin2)) return false;
                } else if (hasOutputPin(servoType)) {
                    return false;
                }
            } else if (hasOutputMax(servoType) || hasOutputMin(servoType)
                    || hasOutputPin(servoType)) {
                return false;
            }

            if (servoJson.containsKey(KEY_VALUE)) {
                Number value1 = (Number) servoJson.get(KEY_VALUE);
                Number value2 = getServoValue(servoType);
                if (value1 != null && !value1.equals(value2)) return false;
            } else if (hasServoValue(servoType)) {
                return false;
            }

        } else if (rootJson.containsKey(servoType.getStringValue())) {
            return false;
        }
        return true;
    }

}


text:
package org.prevayler.demos.memento.commands;

import org.prevayler.demos.memento.Account;
import org.prevayler.demos.memento.Bank;
import org.prevayler.util.memento.MementoCollector;
import org.prevayler.util.memento.MementoTransaction;

public class AccountDeletion extends MementoTransaction {
  private final long accountNumber;

  /**
   * Set by findObjects(...)
   */
  protected transient Bank bank;

  public AccountDeletion(Account account) {
    accountNumber = account.number();
  }

  protected void findObjects(Bank prevalentSystem) {
    bank = prevalentSystem;
  }

  protected void checkPrecondition() {
  }

  protected void createMementos(MementoCollector collector) {
    bank.createMemento(collector);
  }

  protected Account execute(MementoCollector collector) throws Bank.AccountNotFound {
    bank.deleteAccount(accountNumber);
    return null;
  }
}


text:
/**
 *
 */
package gov.nih.nci.cagrid.portal.portlet.browse;

import gov.nih.nci.cagrid.portal.domain.catalog.CatalogEntryRoleInstance;
import gov.nih.nci.cagrid.portal.domain.catalog.Comment;
import gov.nih.nci.cagrid.portal.domain.catalog.Temporal;
import gov.nih.nci.cagrid.portal.portlet.util.TemporalComparator;

import java.util.Date;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * @author Joshua Phillips
 *
 */
public class CatalogEntryRoleInstanceViewBean implements Temporal {

	private CatalogEntryRoleInstance roleInstance;
	private SortedSet<Comment> orderedComments;

	@SuppressWarnings("unchecked")
	public CatalogEntryRoleInstanceViewBean(CatalogEntryRoleInstance roleInstance) {
		this.roleInstance = roleInstance;
		orderedComments = new TreeSet(new TemporalComparator());
		orderedComments.addAll(roleInstance.getComments());
	}

	public SortedSet<Comment> getOrderedComments(){
		return orderedComments;
	}

	public CatalogEntryRoleInstance getRoleInstance(){
		return roleInstance;
	}

	public Date getCreatedAt() {
		return getRoleInstance().getCreatedAt();
	}

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="co.dilaver.quoter.activities.ShareActivity">

    <item
        android:id="@+id/share_action_done"
        android:orderInCategory="100"
        android:title="@string/action_done"
        app:showAsAction="ifRoom"
        android:icon="@drawable/check"
        />

</menu>


text:
require 'ostruct'

module SmartAnswer
  class Flow
    attr_reader :nodes, :outcomes
    attr_accessor :state, :status, :need_id

    def initialize(&block)
      @nodes = []
      @state = nil
      instance_eval(&block) if block_given?
    end

    def use_shared_logic(filename)
      eval File.read(Rails.root.join('lib', 'flows', 'shared_logic', "#{filename}.rb")), binding
    end

    def name(name = nil)
      @name = name unless name.nil?
      @name
    end

    def satisfies_need(need_id)
      self.need_id = need_id
    end

    def draft?
      status == :draft
    end

    def status(s=nil)
      if s
        raise Flow::InvalidStatus unless [:published,:draft].include? s
        @status = s
      end

      @status
    end

    def section_slug(s=nil)
      ActiveSupport::Deprecation.warn("Sections are no longer handled within smartanswers.", caller(1))
      nil
    end

    def subsection_slug(s=nil)
      ActiveSupport::Deprecation.warn("Sections are no longer handled within smartanswers.", caller(1))
      nil
    end

    def multiple_choice(name, options = {}, &block)
      add_node Question::MultipleChoice.new(name, options, &block)
    end

    def country_select(name, options = {}, &block)
      add_node Question::CountrySelect.new(name, options, &block)
    end

    def date_question(name, &block)
      add_node Question::Date.new(name, &block)
    end

    def optional_date(name, &block)
      add_node Question::OptionalDate.new(name, &block)
    end

    def value_question(name, &block)
      add_node Question::Value.new(name, &block)
    end

    def money_question(name, &block)
      add_node Question::Money.new(name, &block)
    end

    def salary_question(name, &block)
      add_node Question::Salary.new(name, &block)
    end

    def checkbox_question(name, &block)
      add_node Question::Checkbox.new(name, &block)
    end

    def outcome(name, options = {}, &block)
      add_node Outcome.new(name, options, &block)
    end

    def outcomes
      @nodes.select(&:outcome?)
    end

    def questions
      @nodes.select(&:question?)
    end

    def node_exists?(node_or_name)
      @nodes.any? {|n| n.name == node_or_name.to_sym }
    end

    def node(node_or_name)
      @nodes.find {|n| n.name == node_or_name.to_sym } or raise "Node '#{node_or_name}' does not exist"
    end

    def start_state
      State.new(questions.first.name).freeze
    end

    def process(responses)
      responses.inject(start_state) do |state, response|
        return state if state.error
        begin
          state = node(state.current_node).transition(state, response)
          node(state.current_node).evaluate_precalculations(state)
        rescue ArgumentError, InvalidResponse => e
          state.dup.tap do |new_state|
            new_state.error = e.message
            new_state.freeze
          end
        end
      end
    end

    def path(responses)
      process(responses).path
    end

    def normalize_responses(responses)
      process(responses).responses
    end

    class InvalidStatus < StandardError; end

    private
      def add_node(node)
        raise "Node #{node.name} already defined" if node_exists?(node)
        @nodes << node
      end
  end
end


text:
<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use Input;
use Validator;
use Auth;
use Redirect;
use Session;
use App\Models\Users;
use Illuminate\Support\Facades\Crypt;
use View;

class LoginController extends BaseController {
    public function index() {
        return View::make('login.view');
//        $secret = Crypt::encrypt('admin');
//        echo $secret;
    }

    public function proseslogin() {
        $inp = Input::all();
        $rules = [
            'email' => 'required|email',
            'password' => 'required'
        ];
        $valid = Validator::make($inp, $rules); //pengecekan untuk Variabel Input terhadap Rule nya

        if ($valid->fails()) {
            return Redirect::to('/login')->withErrors($valid); //akan menampilkan error jika proses validasi Salah
        } else {
            $pass = $inp['password'];
            $email = $inp['email'];
            $data = [
                'email' => $email,
                'password' => $pass,
            ];
            if (Auth::attempt($data)) {
                Session::flash('message', 'Successfully Login!');
                return Redirect::intended('/gambar');
//                echo "sukses login";
            } else {
                Session::flash('message', 'Email dan Password no valid!');
                return Redirect::to('/login');
            }
        }
    }
    /**
     *
     * @return Redirect
     */
    public function doLogout() {
        Auth::Logout();
        return Redirect::to('/');
    }
}


text:
'use strict';

const insert = require('../schema/horizon_protocol').insert;
const writes = require('./writes');
const reql_options = require('./common').reql_options;

const Joi = require('joi');
const r = require('rethinkdb');

const run = (raw_request, context, ruleset, metadata, send, done) => {
  const parsed = Joi.validate(raw_request.options, insert);
  if (parsed.error !== null) { done(new Error(parsed.error.details[0].message)); }

  const collection = metadata.collection(parsed.value.collection);
  const conn = metadata.connection();

  // TODO: shortcut if validation isn't needed (for all write request types)
  const response_data = [ ];
  const valid_rows = [ ];
  for (let i = 0; i < parsed.value.data.length; ++i) {
    if (!ruleset.validate(context, null, parsed.value.data[i])) {
      response_data.push(new Error(writes.unauthorized_error));
    } else {
      valid_rows.push(parsed.value.data[i]);
      response_data.push(null);
    }
  }

  // TODO: shortcut if valid_rows is empty (for all write request types)
  collection.table
    .insert(valid_rows.map((row) => writes.apply_version(r.expr(row), 0)),
            { returnChanges: 'always' })
    .run(conn, reql_options)
    .then((insert_results) => {
      done(writes.make_write_response(response_data, insert_results));
    }).catch(done);
};

module.exports = { run };


text:
@interface HTEditItemsViewController : HTBaseViewController

@property (nonatomic,strong) HTMainItemModel *MainModel;

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Interface IQueryValidationDescriptors
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Interface IQueryValidationDescriptors
   ">
    <meta name="generator" content="docfx 2.9.3.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Interface IQueryValidationDescriptors

Defines a system for accessing validation descriptors for queries

Namespace:Bifrost.Read.Validation

Assembly:Bifrost.dll

Syntax

public interface IQueryValidationDescriptors

Methods

                |
                Improve this Doc

                View Source

GetDescriptorFor<TQuery>()

Get a <see cref="!:QueryValidationDescriptor<TQ>"></see> for a specific IQuery by its type

Declaration

IQueryValidationDescriptor GetDescriptorFor<TQuery>()where TQuery : IQuery

Returns

                    Type
                    Description

                    IQueryValidationDescriptor
                    IQueryValidationDescriptor describing the validation for the IQuery

Type Parameters

                    Name
                    Description

                    TQuery
                    Type of IQuery to get for

                |
                Improve this Doc

                View Source

HasDescriptorFor<TQuery>()

Checks if there is a <see cref="!:QueryValidationDescriptor<TQ>"></see> for a specific IQuery by its type

Declaration

bool HasDescriptorFor<TQuery>()where TQuery : IQuery

Returns

                    Type
                    Description

                    System.Boolean

True if there is a <see cref="!:QueryValidationDescriptor<TQ>"></see> for the query and false if not

Type Parameters

                    Name
                    Description

                    TQuery
                    Type of IQuery to check for

Extension Methods

                  ConceptExtensions.IsConcept(Object)

                  ConceptExtensions.GetConceptValue(Object)

                  DynamicExtensions.AsExpandoObject(Object)

                  MethodCalls.CallGenericMethod<TOut, T, T1, T2, T3>(T, Expression<Func<T, Func<T1, T2, T3, TOut>>>, T1, T2, T3, Type[])

                  MethodCalls.CallGenericMethod<TOut, T, T1, T2>(T, Expression<Func<T, Func<T1, T2, TOut>>>, T1, T2, Type[])

                  MethodCalls.CallGenericMethod<TOut, T, T1>(T, Expression<Func<T, Func<T1, TOut>>>, T1, Type[])

                  MethodCalls.CallGenericMethod<TOut, T>(T, Expression<Func<T, Func<TOut>>>, Type[])

                  MethodCalls.Generics<T>(T)

                    Improve this Doc

                    View Source

              Back to top

            Copyright © 2008-2017 Dolittle


text:
'use strict';

var brasil = require('brasil');

var Duplicata = (function() {
    function Duplicata() {

    }

    Duplicata.prototype.getNumero = function() {
        return this._numero;
    };

    Duplicata.prototype.comNumero = function(_numero) {
        this._numero = _numero;
        return this;
    };

    Duplicata.prototype.getVencimento = function() {
        return this._vencimento;
    };

    Duplicata.prototype.getVencimentoFormatado = function() {
        if(this._vencimento) {
            return brasil.formatacoes.data(this._vencimento);
        }

        return '';
    };

    Duplicata.prototype.comVencimento = function(_vencimento) {
        this._vencimento = new Date(_vencimento);
        return this;
    };

    Duplicata.prototype.getValor = function() {
        return this._valor;
    };

    Duplicata.prototype.getValorFormatado = function() {
        return brasil.formatacoes.dinheiro(this._valor || 0);
    };

    Duplicata.prototype.comValor = function(_valor) {
        this._valor = _valor;
        return this;
    };

    return Duplicata;
})();

module.exports = Duplicata;


text:
package com.wifiafterconnect.html;

import org.jsoup.nodes.Element;

import android.util.Log;

import com.wifiafterconnect.BuildConfig;
import com.wifiafterconnect.Constants;
import com.wifiafterconnect.WifiAuthParams;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class HtmlForm {
	// Empty strings if not available (see Jsoup docs : http://jsoup.org/apidocs/org/jsoup/nodes/Node.html#attr%28java.lang.String%29)
	protected String id;
	protected String action;
	protected String method;
	protected String onsubmit;
	protected URL actionURL;
	protected Map<String, HtmlInput> inputs = new HashMap<String,HtmlInput>();
	// This will store inputs in the same order they are found in original HTML
	protected ArrayList<HtmlInput> inputsList = new ArrayList<HtmlInput>();

	public void addInput (HtmlInput i) {
		if (i != null && i.isValid()) {
			inputs.put (i.getName(), i);
			inputsList.add (i);
		}
	}

	HtmlForm (Element e) {
		id = e.attr("id");
		setAction(e.attr("action"));

		method = e.attr("method");
		onsubmit = e.attr("onsubmit");

    	for (Element ie : e.getElementsByTag("input")) {
    		if (BuildConfig.DEBUG)
    			Log.d(Constants.TAG, "Parsing html: form input found : " + ie.toString());
    		boolean hidden = false;
    		for (Element parent = ie.parent(); parent != e ; parent = parent.parent())
    			// this weirdness is used in Colubris (now owned by HP) portals:
    			if (parent.hasClass("hidedata")|| parent.hasClass("hidden")) {
    				hidden = true;
    				break;
    			}
    		addInput(new HtmlInput (ie, hidden));
    	}
	}

	public String getOnsubmit() {
		return onsubmit;
	}

	public String getMethod () {
		return method.toUpperCase(Locale.ENGLISH);
	}

	public String getAction () {
		return action;
	}

	public String getId () {
		return id;
	}

	public Collection<HtmlInput> getInputs() {
		return inputs.values();
	}

	public boolean hasInput (String name) {
		return inputs.containsKey(name);
	}

	public boolean hasInputWithClass (String classAttr) {
		for (HtmlInput i :inputs.values()) {
			if (i.isClass (classAttr))
				return true;
		}
		return false;
	}

	public boolean hasVisibleInput (String name) {
		HtmlInput i = inputs.get(name);
		return (i != null && !i.isHidden());
	}

	public HtmlInput getInput (String name) {
		return inputs.get(name);
	}

	public HtmlInput getVisibleInput (String name) {
		HtmlInput i = getInput (name);
		return (i == null || i.isHidden()) ? null : i;
	}

	public HtmlInput getVisibleInputByType (String type) {
		for (HtmlInput i :inputs.values()) {
			if (!i.isHidden() && i.matchType (type))
				return i;
		}
		return null;
	}

	public boolean setInputValue (String name, String value) {
		HtmlInput i = inputs.get(name);
		if (i != null)
			i.setValue (value);
		return inputs.containsKey(name);
	}

	public String formatPostData () {
		StringBuilder postData = new StringBuilder();
		for (HtmlInput i :inputsList) {
			i.formatPostData(postData);
		}
		if (postData.length() > 0) {
			if (postData.charAt(0) == '&')
				postData.deleteCharAt(0);
		}
		return postData.toString();
	}

	public URL formatActionURL (URL originalURL) {
		URL result = originalURL;
		if (action != null) {
			String protocol;
			String authority = null;
			String file = action;
			String ref = null;
			if (actionURL != null) {
				protocol = actionURL.getProtocol();
				authority = actionURL.getAuthority();
				// we want to keep the query in as some portals use query params in post requests
				file = actionURL.getFile();
				ref = actionURL.getRef();
			}else {
				String origPath = originalURL.getPath(); //ignore query of original url
				if (file.isEmpty())
					file = origPath;
				else if (!file.startsWith("/")) {
					file = origPath.substring(0, origPath.lastIndexOf('/')+1) + file;
				}

				protocol = originalURL.getProtocol();
			}
			if (authority == null)
				authority = originalURL.getAuthority();

			String urlString = protocol + "://" + authority;
			if (file != null)
				urlString += file;
			if (ref != null)
				urlString += "#" + ref;
			if (BuildConfig.DEBUG)
				Log.d(Constants.TAG, "actionURL string = [" + urlString + "]");
			try {
				result = new URL (urlString);
			} catch (MalformedURLException e) {	}
		}else {
			// TODO need to check for onclick="form.action=" in type="submit" inputs
		}
		return result;
	}

	public WifiAuthParams fillParams (WifiAuthParams params) {

		for (HtmlInput i :inputsList) {
			if (!i.isHidden() && !params.hasParam(i.getName())) {
				HtmlInput param = new HtmlInput (i);
				params.add(param);
			}
		}
		return params;
	}

	public boolean isParamMissing (WifiAuthParams params, final String paramName) {
		return (hasVisibleInput(paramName) && (params == null || !params.hasParam (paramName)));
	}

	public void fillInputs (WifiAuthParams params) {
		if (params != null) {
			for (HtmlInput f :params.getFields()) {
				String value = f.getValue();
				HtmlInput i = inputs.get(f.getName());
				if (i!=null)
					i.setValue(value);
			}
		}
	}

	public boolean isSubmittable() {
		boolean missingValues = false;
		boolean hasSubmit = false;
		for (HtmlInput i :inputs.values()) {
			if (!i.isHidden() && i.getValue().isEmpty()
					&& (WifiAuthParams.isSupportedParamType(i) || i.matchType(HtmlInput.TYPE_CHECKBOX)))
				missingValues = true;
			if (i.matchType(HtmlInput.TYPE_SUBMIT))
				hasSubmit = true;
		}
		return !missingValues && hasSubmit;
	}

	public void setAction(String switchUrl) {
		action = (switchUrl == null)? "" : switchUrl;
		try {
			actionURL = new URL(action);
		} catch (MalformedURLException ex) {actionURL = null;}
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>flowable-drools-spke</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>process-manager</artifactId>

    <properties>
        <maven.compiler.source>14</maven.compiler.source>
        <maven.compiler.target>14</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.flowable</groupId>
            <artifactId>flowable-spring-boot-starter-rest</artifactId>
            <version>${flowable.version}</version>
        </dependency>
        <dependency>
            <groupId>org.flowable</groupId>
            <artifactId>flowable-spring-boot-starter-actuator</artifactId>
            <version>${flowable.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <version>${spring.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
@constructor jQuery.fn.cookie jQuery.cookie
@page jQuery.fn.cookie
@parent dom


text:
[![CI Status](https://github.com/itchyny/pihex-rs/workflows/CI/badge.svg)](https://github.com/itchyny/pihex-rs/actions)
[![crates.io](https://img.shields.io/crates/v/pihex.svg)](https://crates.io/crates/pihex)
[![release](https://img.shields.io/github/release/itchyny/pihex-rs/all.svg)](https://github.com/itchyny/pihex-rs/releases)
[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/itchyny/pihex-rs/blob/master/LICENSE)

Arbitrary place hexadecimal digits viewer of pi written in Rust.
The library is based on the Bailey-Borwein-Plouffe formula (BBP formula) and Bellard's formula.

```
 $ pihex
0: 243f 6a88 85a3 08d3 1319 8a2e 0370 7344
 $ pihex 1
2: 3f6a 8885 a308 d313 198a 2e03 7073 44a4
 $ pihex 4
4: 6a88 85a3 08d3 1319 8a2e 0370 7344 a409
 $ pihex 8
128: 9216 d5d9 8979 fb1b d131 0ba6 98df b5ac
 $ pihex 65536
65536: 3004 3414 c926 7212 d7fb 8a3f fc7c 7002
 $ pihex 1000000
1000000: 6c65 e52c b459 3500 50e4 bb17 8f4c 67a0
 $ pihex 10000000
10000000: 7af5 863e fed8 de97 033c d0f6 b80a 3d26
 $ pihex 100000000 # defaults to BBP formula
100000000: cb84 0e21 926e c5ae 0d2f 3405 1045 93cb
 $ pihex --formula=bellard 100000000 # yields the same result but faster than BBP formula
100000000: cb84 0e21 926e c5ae 0d2f 3405 1045 93cb
```
Refer to `pihex --help` for further details.

## Installation
### Homebrew
```shell
brew install itchyny/tap/pihex
```

### Build from source
```shell
git clone https://github.com/itchyny/pihex-rs
cd pihex-rs
cargo install --path .
export PATH=$PATH:$HOME/.cargo/bin
```

## Author
itchyny (https://github.com/itchyny)

## License
This software is released under the MIT License, see LICENSE.

## Disclaimer
I tested very carefully but this software does not always answer correctly due to the floating-point arithmetic inaccuracy.
If there's a place with over 53bit zeros in binary representation of pi (I'm not sure where it is), we never ensure the answer calculated by double-precision floating-point numbers is correct.
Therefore when you use this software, be careful the answer is not suffered from floating-point calculation errors.
If the successive digits in hexadecimal representation repeat '0' or 'f' over 13 times, it's highly inaccurate due to this calculation errors.

## References
- David H. Bailey, Peter Borwein, and Simon Plouffe, On the Rapid Computation of Various Polylogarithmic Constants, Mathematics of Computation 66, 903-913, 1997.
- David H. Bailey, The BBP Algorithm for Pi, September 17, 2006.
- Fabrice Bellard, A new formula to compute the n'th binary digit of pi, 1997.