text:
package heng.shi.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class IndexController {
    @RequestMapping(value = "/")
    public String index(HttpServletRequest request) {
        request.getSession();
        return "index";
    }

}


text:
using Newtonsoft.Json;

namespace CoCSharp.Logic
{
    /// <summary>
    /// Represents an object in a <see cref="Village"/>.
    /// </summary>
    public abstract class VillageObject
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="VillageObject"/> class.
        /// </summary>
        public VillageObject()
        {
            // Space
        }

        /// <summary>
        /// Initailizes a new instance of the <see cref="VillageObject"/> class
        /// with the specified data ID.
        /// </summary>
        /// <param name="dataID">Data ID of the <see cref="VillageObject"/>.</param>
        public VillageObject(int dataID)
        {
            DataID = dataID;
        }

        /// <summary>
        /// Gets or sets the data ID of the <see cref="VillageObject"/>.
        /// </summary>
        [JsonProperty("data")]
        public int DataID { get; set; } //TODO: Hide this thing

        /// <summary>
        /// Gets or sets the X coordinate of the <see cref="VillageObject"/>.
        /// </summary>
        [JsonProperty("x")]
        public int X { get; set; }

        /// <summary>
        /// Gets or sets the y coordinate of the <see cref="VillageObject"/>.
        /// </summary>
        [JsonProperty("y")]
        public int Y { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var dateFormat = require('dateformat');
var request = require('request');
var cheerio = require('cheerio');

module.exports = function() {

  function getLunchTodayCafeTechno() {
    return new Promise(function(resolve, reject) {
      var url = 'http://www.cafetechno.fi/meny/';

      request(url, function (error, response, html) {
        if (!error && response.statusCode == 200) {
          var currentDate = new Date();
          currentDate = dateFormat(currentDate, 'isoDate');
          var currentWeekNumber = dateFormat(currentDate, "W");
          var currentDayNumber = dateFormat(currentDate, "N");
          var result = 'CafeTechno ' + dateFormat(currentDate, "fullDate") + ' \n\n';

          // Get data from the website
          var $ = cheerio.load(html,{
            decodeEntities: false
          });

          $weekNumber = $('.menu-title2').html();

          var dishesPerDay = [];
          $('.menu-description2').children('p').each(function(i, elem) {
            dishesPerDay[i] = $(this).text();
          });

          // Extract weeknumber from the string
	        var weekNumberEnd = $weekNumber.replace(/[A-Za-z. $-]/g, '');

          console.log('currentWeekNumber: ' + currentWeekNumber);
          console.log('currentDayNumber: ' + currentDayNumber);
          console.log('weekNumberEnd: ' + weekNumberEnd);

          // Find the paragraph with the correct weekday name
          var dishesFound = false;

          if (currentWeekNumber === weekNumberEnd) {

            if (currentDayNumber == 1) {
              dishesPerDay.forEach(function(element) {
                if (element.includes("MÅNDAG") || element.includes("måndag") || element.includes("Måndag")) {
                  result += element.toLowerCase();
                }
              }, this);
            }

            if (currentDayNumber == 2) {
              dishesPerDay.forEach(function(element) {
                if (element.includes("TISDAG") || element.includes("tisdag") || element.includes("Tisdag")) {
                  result += element.toLowerCase();
                }
              }, this);
            }

            if (currentDayNumber == 3) {
              dishesPerDay.forEach(function(element) {
                if (element.includes("ONSDAG") || element.includes("onsdag") || element.includes("Onsdag")) {
                  result += element.toLowerCase();
                }
              }, this);
            }

            if (currentDayNumber == 4) {
              dishesPerDay.forEach(function(element) {
                if (element.includes("TORSDAG") || element.includes("torsdag") || element.includes("Torsdag")) {
                  result += element.toLowerCase();
                }
              }, this);
            }

            if (currentDayNumber == 5) {
              dishesPerDay.forEach(function(element) {
                if (element.includes("FREDAG") || element.includes("fredag") || element.includes("Fredag")) {
                  result += element.toLowerCase();
                }
              }, this);
            }

          }
            // Send the result
            resolve(result);
        }

      });
    });
  }

  return {
    getLunchTodayCafeTechno: getLunchTodayCafeTechno
  };

}


text:
#ifndef _SYS_TYPES_H_
#define _SYS_TYPES_H_

typedef signed char s8_t;		/**< Signed 8 bits type */
typedef unsigned char u8_t;		/**< Unsigned 8 bits type */

typedef signed short s16_t;		/**< Signed 16 bits type */
typedef unsigned short u16_t;		/**< Unsigned 16 bits type */

typedef signed int s32_t;		/**< Signed 32 bits type */
typedef unsigned int u32_t;		/**< Unsigned 32 bits type */

#if __SIZEOF_LONG__ > 4
typedef signed long s64_t;		/**< Signed 64 bits type */
typedef unsigned long u64_t;		/**< Unsigned 64 bits type */
#else
typedef signed long long s64_t;		/**< Signed 64 bits type */
typedef unsigned long long u64_t;	/**< Unsigned 64 bits type */
#endif

#ifdef __KERNEL__

typedef u64_t clock_t;  /**< System times in clock ticks or CLOCKS_PER_SEC */
typedef s32_t clockid_t; /**< Clock ID type in the clock and timer functions */
typedef u32_t dev_t;	/**< Used for device IDs */
typedef u32_t gid_t;	/**< Used for group IDs */
typedef s64_t id_t;	/**< Used as a general identifier */
typedef u64_t ino_t;	/**< Used for file serial numbers */
typedef s32_t key_t;	/**< Used for XSI interprocess communication */
typedef u16_t mode_t;	/**< Used for some file attributes */
typedef u16_t nlink_t;	/**< Used for link counts */
typedef s64_t off_t;	/**< Used for file sizes */
typedef s16_t pid_t;	/**< Used for process IDs and process group IDs */

#ifndef _SIZE_T
#define _SIZE_T
typedef u32_t size_t;	/**< Used for sizes of objects */
#endif

#ifndef _SSIZE_T
#define _SSIZE_T
typedef s32_t ssize_t;	/**< Used for a count of bytes or an error indication */
#endif

#ifndef _TIME_T
#define _TIME_T
typedef s64_t time_t;	/**< Time in seconds since 1 Jan 1970 0000 GMT */
#endif

typedef u16_t uid_t;	/**< Used for user IDs */

typedef s64_t useconds_t;	/**< Used for time in microseconds */

/** @{ */
/* File system */
typedef u32_t blkcnt_t;		/**< Used for file block counts */
typedef u64_t blksize_t;	/**< Used for block sizes */
typedef u64_t fsblkcnt_t;	/**< Used for file system block counts */
typedef u64_t fsfilcnt_t;	/**< Used for file system file counts */
/** @} */

#endif /* __KERNEL__ */

#endif /* _SYS_TYPES_H_ */


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('service:ripple', 'Unit | Service | ripple', {
  // Specify the other units that are required for this test.
  // needs: ['service:foo']
});

// Replace this with your real tests.
test('it exists', function(assert) {
  var service = this.subject();
  assert.ok(service);
});


text:
<?php namespace Infinety\CRUD\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CrudRequest extends FormRequest {

	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		// only allow creates if the user is logged in
		return \Auth::check();
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		return [
			// 'name' => 'required|min:3|max:255'
		];
	}

	// OPTIONAL OVERRIDE
    // public function forbiddenResponse()
    // {
        // Optionally, send a custom response on authorize failure
        // (default is to just redirect to initial page with errors)
        //
        // Can return a response, a view, a redirect, or whatever else
        // return Response::make('Permission denied foo!', 403);
    // }

    // OPTIONAL OVERRIDE
    // public function response()
    // {
        // If you want to customize what happens on a failed validation,
        // override this method.
        // See what it does natively here:
        // https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/Http/FormRequest.php
    // }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
TriangularNCellStateView
</TITLE>

<META NAME="keywords" CONTENT="cellularAutomata.cellState.view.TriangularNCellStateView class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

cellularAutomata.cellState.view

Class TriangularNCellStateView

java.lang.Object
  cellularAutomata.cellState.view.CellStateView
      cellularAutomata.cellState.view.NCellStateView
          cellularAutomata.cellState.view.TriangularNCellStateView

public class TriangularNCellStateView
extends NCellStateView

A view that displays hexagons for the cell state.

Author:

David Bahr

Field Summary

Fields inherited from class cellularAutomata.cellState.view.CellStateView

COLOR_SCHEME, DEFAULT_COLOR_SCHEME

Constructor Summary

TriangularNCellStateView()

Method Summary

 java.awt.Shape
getAverageDisplayShape(CellState[] states,
                       int width,
                       int height,
                       java.lang.Object[] parameters)

          Creates a triangle Shape appropriate for displaying as the average of the
 states given in the array.

 java.awt.Shape
getDisplayShape(CellState state,
                int width,
                int height,
                java.lang.Object[] parameters)

          Creates a triangle to display.

Methods inherited from class cellularAutomata.cellState.view.NCellStateView

getColor

Methods inherited from class cellularAutomata.cellState.view.CellStateView

getDisplayColor, getStroke, getTaggedColor

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TriangularNCellStateView

public TriangularNCellStateView()

Method Detail

getAverageDisplayShape

public java.awt.Shape getAverageDisplayShape(CellState[] states,
                                             int width,
                                             int height,
                                             java.lang.Object[] parameters)

Creates a triangle Shape appropriate for displaying as the average of the
 states given in the array. Overrides parent class.

Overrides:
getAverageDisplayShape in class NCellStateView

Parameters:
states - The states that are being averaged, and for which an averaged
            display shape is needed.
width - The width of the rectangle that bounds this Shape. May be
            ignored.
height - The height of the rectangle that bounds this Shape. May be
            ignored.
parameters - Any additional parameters necessary to calculate and return
            the correct shape. May be null.

Returns:
The triangle shape to be displayed.
See Also:
CellStateView.getDisplayColor(
      cellularAutomata.cellState.model.CellState, Object[])

getDisplayShape

public java.awt.Shape getDisplayShape(CellState state,
                                      int width,
                                      int height,
                                      java.lang.Object[] parameters)

Creates a triangle to display. Overrides parent class.

Overrides:
getDisplayShape in class NCellStateView

Parameters:
state - The cell state that will be displayed.
width - The width of the rectangle that bounds this Shape. May be
            ignored.
height - The height of the rectangle that bounds this Shape. May be
            ignored.
parameters - Any additional parameters necessary to calculate and return
            the correct shape. May be null.

Returns:
The shape to be displayed. May be null (in which case the CA
         graphics should use a default shape).
See Also:
CellStateView.getDisplayShape(
      cellularAutomata.cellState.model.CellState, int, int, Object[])

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
#include "asylo/platform/posix/threading/thread_manager.h"

#include <pthread.h>
#include <sys/mman.h>

#include <algorithm>
#include <atomic>
#include <cstdlib>
#include <memory>

#include "asylo/platform/posix/pthread_impl.h"
#include "asylo/platform/primitives/trusted_primitives.h"
#include "asylo/platform/primitives/trusted_runtime.h"

namespace asylo {
namespace {

// Returns when |predicate| returns true. |mutex| must be locked.
void WaitFor(const std::function<bool()> &predicate, pthread_cond_t *cond,
             pthread_mutex_t *mutex) {
  while (!predicate()) {
    int ret = pthread_cond_wait(cond, mutex);
    CHECK_EQ(ret, 0);
  }
}

}  // namespace

using pthread_impl::PthreadMutexLock;

bool ReturnFalse() { return false; }

ThreadManager::Thread::Thread(const ThreadOptions &options,
                              std::function<int()> start_routine, void *tls)
    : start_routine_(std::move(start_routine)),
      detached_(options.detached),
      tls_(tls) {}

void ThreadManager::Thread::Run() {
  // Unblock anyone waiting for thread to start.
  UpdateThreadState(ThreadState::RUNNING);

  // Run the thread and store the start function's return value.
  start_routine_();

  // Run cleanup routines, if any.
  RunCleanupRoutines();

  // Unblock anyone waiting for this to finish.
  UpdateThreadState(ThreadState::DONE);
}

void *ThreadManager::Thread::GetReturnValue() const { return ret_; }

bool ThreadManager::Thread::detached() const {
  return detached_.load(std::memory_order_relaxed);
}

void ThreadManager::Thread::UpdateThreadId(const pthread_t thread_id) {
  PthreadMutexLock lock(&lock_);
  thread_id_ = thread_id;
}

pthread_t ThreadManager::Thread::GetThreadId() {
  PthreadMutexLock lock(&lock_);
  return thread_id_;
}

void *ThreadManager::Thread::GetThreadTls() {
  PthreadMutexLock lock(&lock_);
  return tls_;
}

void ThreadManager::Thread::SetTid(const pid_t tid) {
  PthreadMutexLock lock(&lock_);
  auto thread = reinterpret_cast<struct __pthread_info *>(thread_id_);
  thread->tid = tid;
}

void ThreadManager::Thread::UpdateThreadResult(void *ret) { ret_ = ret; }

void ThreadManager::Thread::UpdateThreadState(const ThreadState &new_state) {
  PthreadMutexLock lock(&lock_);
  this->state_ = new_state;
  int ret = pthread_cond_broadcast(&state_change_cond_);
  CHECK_EQ(ret, 0);
}

void ThreadManager::Thread::WaitForThreadToEnterState(
    const ThreadState &desired_state,
    const std::function<bool()> &alternative_predicate) {
  PthreadMutexLock lock(&lock_);
  WaitFor(
      [this, desired_state, alternative_predicate]() {
        return state_ == desired_state || alternative_predicate();
      },
      &state_change_cond_, &lock_);
}

void ThreadManager::Thread::WaitForThreadToExitState(
    const ThreadState &undesired_state) {
  PthreadMutexLock lock(&lock_);
  WaitFor([this, undesired_state]() { return state_ != undesired_state; },
          &state_change_cond_, &lock_);
}

void ThreadManager::Thread::SignalStateWaiters() {
  PthreadMutexLock lock(&lock_);
  int ret = pthread_cond_broadcast(&state_change_cond_);
  CHECK_EQ(ret, 0);
}

void ThreadManager::Thread::Detach() {
  detached_.store(true, std::memory_order_relaxed);

  PthreadMutexLock lock(&lock_);
  int ret = pthread_cond_broadcast(&state_change_cond_);
  CHECK_EQ(ret, 0);
}

void ThreadManager::Thread::PushCleanupRoutine(
    const std::function<void()> &func) {
  cleanup_functions_.push(func);
}

void ThreadManager::Thread::PopCleanupRoutine(bool execute) {
  // pthread_cleanup_push and pthread_cleanup_pop are guaranteed by the compiler
  // (at compile-time!) to always occur in pairs. An attempt to pop an empty
  // stack means something is wrong internally.
  CHECK(!cleanup_functions_.empty());

  std::function<void()> func = cleanup_functions_.top();
  cleanup_functions_.pop();

  if (execute) {
    func();
  }
}

void ThreadManager::Thread::RunCleanupRoutines() {
  while (!cleanup_functions_.empty()) {
    PopCleanupRoutine(/*execute=*/true);
  }
}

ThreadManager *ThreadManager::GetInstance() {
  static ThreadManager *instance = new ThreadManager();
  return instance;
}

std::shared_ptr<ThreadManager::Thread> ThreadManager::EnqueueThread(
    const ThreadOptions &options, const std::function<int()> &start_routine,
    void *tls) {
  PthreadMutexLock lock(&threads_lock_);

  queued_threads_.emplace(
      std::make_shared<Thread>(options, start_routine, tls));
  std::shared_ptr<Thread> thread = queued_threads_.back();

  // If a Thread object cannot be allocated, abort.
  CHECK(thread != nullptr);

  pthread_cond_broadcast(&threads_cond_);
  return thread;
}

std::shared_ptr<ThreadManager::Thread> ThreadManager::DequeueThread(pid_t tid) {
  PthreadMutexLock lock(&threads_lock_);
  // There should be a one-to-one mapping of threads donated to the enclave
  // and threads created from above at the pthread API layer waiting to run.
  // If a thread gets donated and there's no thread waiting to run, something
  // has gone very wrong.
  CHECK(!queued_threads_.empty());

  std::shared_ptr<Thread> thread = queued_threads_.front();
  queued_threads_.pop();

  // Bind the Thread we just took off the queue to the thread id of the donated
  // enclave thread we're running under.
  const pthread_t thread_id = pthread_self();
  thread->UpdateThreadId(thread_id);

  threads_[thread_id] = thread;
  thread->SetTid(tid);
  reinterpret_cast<__pthread_info *>(thread->GetThreadTls())->thread_id =
      thread_id;

  pthread_cond_broadcast(&threads_cond_);
  return thread;
}

int ThreadManager::CreateThread(const std::function<int()> &start_routine,
                                pid_t *tid, void *tls) {
  pthread_attr_t *attr = reinterpret_cast<struct __pthread_info *>(tls)->attr;
  ThreadOptions options;
  if (attr && attr->detach_state == PTHREAD_CREATE_DETACHED) {
    options.detached = true;
  }
  std::shared_ptr<Thread> thread = EnqueueThread(options, start_routine, tls);

  // Exit and create a thread to enter with EnclaveCall DonateThread.
  if (asylo::primitives::TrustedPrimitives::CreateThread()) {
    return ECHILD;
  }

  // Wait until a thread enters and executes the job.
  thread->WaitForThreadToExitState(Thread::ThreadState::QUEUED);

  if (tid) {
    *tid = reinterpret_cast<struct __pthread_info *>(tls)->tid;
  }

  return 0;
}

// StartThread is called from trusted_application.cc as the start routine when
// a new thread is donated to the Enclave.
int ThreadManager::StartThread(pid_t tid) {
  std::shared_ptr<Thread> thread = DequeueThread(tid);

  // Update the thread info in pthread_self.
  enc_update_pthread_info(thread->GetThreadTls());

  // Run the start_routine.
  thread->Run();

  // Wait for the caller to join before releasing the thread if the thread is
  // joinable.
  bool skipped_join = false;
  thread->WaitForThreadToEnterState(
      Thread::ThreadState::JOINED, [&thread, this, &skipped_join]() {
        // Not joinable. Bail without waiting.
        if (thread->detached()) {
          return true;
        }

        // If we're finalizing, don't wait because this will cause a freeze if
        // an enclave forgets to join a thread.
        if (finalizing_.load()) {
          skipped_join = true;
          return true;
        }

        return false;
      });

  {
    PthreadMutexLock threads_lock(&threads_lock_);
    // Remember that this thread should have been joined, in case that join is
    // called later on this thread.
    if (skipped_join) {
      zombie_threads_.insert(pthread_self());
    }
    threads_.erase(pthread_self());
    pthread_cond_broadcast(&threads_cond_);
  }

  // Thread finished execution, reset the thread ID and release the TLS memory.
  munmap(reinterpret_cast<struct __pthread_info *>(pthread_self())->self,
         reinterpret_cast<struct __pthread_info *>(pthread_self())->tls_size);
  return 0;
}

void ThreadManager::UpdateThreadResult(const pthread_t thread_id, void *ret) {
  std::shared_ptr<Thread> thread = GetThread(thread_id);
  if (thread != nullptr) {
    thread->UpdateThreadResult(ret);
  }
}

int ThreadManager::JoinThread(const pthread_t thread_id,
                              void **return_value_out) {
  std::shared_ptr<Thread> thread = GetThread(thread_id);
  if (thread == nullptr) {
    // If we're finalizing, check to see if the thread was previously finished
    // without being joined.
    if (finalizing_.load()) {
      PthreadMutexLock threads_lock(&threads_lock_);
      if (zombie_threads_.erase(thread_id)) {
        return 0;
      }
    }
    return ESRCH;
  }

  // Wait until the job is finished executing.
  thread->WaitForThreadToEnterState(Thread::ThreadState::DONE,
                                    std::bind(&Thread::detached, thread));

  if (thread->detached()) {
    return EINVAL;
  }

  if (return_value_out != nullptr) {
    *return_value_out = thread->GetReturnValue();
  }

  thread->UpdateThreadState(Thread::ThreadState::JOINED);

  return 0;
}

int ThreadManager::DetachThread(const pthread_t thread_id) {
  std::shared_ptr<Thread> thread = GetThread(thread_id);
  if (thread == nullptr) {
    return ESRCH;
  }

  if (thread->detached()) {
    return EINVAL;
  }

  thread->Detach();

  return 0;
}

std::shared_ptr<ThreadManager::Thread> ThreadManager::GetThread(
    pthread_t thread_id) {
  PthreadMutexLock lock(&threads_lock_);
  auto it = threads_.find(thread_id);
  if (it == threads_.end()) {
    return nullptr;
  }
  return it->second;
}

void ThreadManager::PushCleanupRoutine(const std::function<void()> &func) {
  std::shared_ptr<Thread> thread = GetThread(pthread_self());

  // This is only ever called on pthread_self, so the thread should always be
  // found.
  CHECK(thread != nullptr);

  // No lock needed since this is a per-thread data structure.
  thread->PushCleanupRoutine(func);
}

void ThreadManager::PopCleanupRoutine(bool execute) {
  std::shared_ptr<Thread> thread = GetThread(pthread_self());

  // This is only ever called on pthread_self, so the thread should always be
  // found.
  CHECK(thread != nullptr);

  // No lock needed since this is a per-thread data structure.
  thread->PopCleanupRoutine(execute);
}

void ThreadManager::Finalize() {
  finalizing_.store(true);
  PthreadMutexLock lock(&threads_lock_);

  // In case any threads are waiting to be joined, let's signal them now so they
  // stop waiting while we finalize.
  for (auto &thread : threads_) {
    thread.second->SignalStateWaiters();
  }

  // Wait for any expected threads to be donated and all threads to return from
  // start_routine.
  WaitFor([this]() { return queued_threads_.empty() && threads_.empty(); },
          &threads_cond_, &threads_lock_);
}

}  // namespace asylo


text:
% ------------------------------------------------------------------------
% ------------------------------------------------------------------------
% ICMC: Modelo de Trabalho Acadêmico (tese de doutorado, dissertação de
% mestrado e trabalhos monográficos em geral) em conformidade com
% ABNT NBR 14724:2011: Informação e documentação - Trabalhos acadêmicos -
% Apresentação
% ------------------------------------------------------------------------
% ------------------------------------------------------------------------

% Opções:
%   Qualificação          = qualificacao
%   Curso                 = doutorado/mestrado
%   Situação do trabalho  = pre-defesa/pos-defesa (exceto para qualificação)
%   Versão para impressão = impressao
\documentclass[doutorado, pos-defesa]{packages/icmc}

% ---------------------------------------------------------------------------
% Pacotes Opcionais
% ---------------------------------------------------------------------------
\usepackage{rotating}           % Usado para rotacionar o texto
\usepackage[all,knot,arc,import,poly]{xy}   % Pacote para desenhos gráficos
% Este pacote pode conflitar com outros pacotes gráficos como o ``pictex''
% Então é necessário usar apenas um dos pacotes conflitantes
\newcommand{\VerbL}{0.52\textwidth}
\newcommand{\LatL}{0.42\textwidth}
% ---------------------------------------------------------------------------

% ---
% Informações de dados para CAPA e FOLHA DE ROSTO
% ---
% Tanto na capa quanto nas folhas de rosto apenas a primeira letra da primeira palavra (ou nomes próprios) devem estar em letra maiúscula, todas as demais devem ser em letra minúscula.
\tituloPT{Modelo de teses e dissertações em LaTeX do ICMC}
\tituloEN{Model of theses and dissertations in LaTeX of the ICMC}
\autor[Antonelli, H. L.]{Humberto Lidio Antonelli}
\genero{M} % Gênero do autor (M = Masculino / F = Feminino)
\orientador[Orientadora]{Profa. Dra.}{Renata Pontin de Mattos Fortes}
%\coorientador{Prof. Dr.}{Fulano de Tal}
\curso{CCMC}
\data{11}{08}{2021} % Data do depósito
\idioma{PT} % Idioma principal do documento (PT = português / EN = inglês)
% ---

% ---
% RESUMOS
% ---

% Resumo em PORTUGUÊS
% conter no máximo 500 palavras
% conter no mínimo 1 e no máximo 5 palavras-chave
\textoresumo[brazil]{
    Este trabalho é um breve modelo  para a escrita de monografias de qualificação, dissertações e teses utilizando o ambiente \LaTeX, de acordo com as normas exigidas pelo Instituto de Ciências Matemáticas e de Computação (ICMC), da Universidade de São Paulo (USP). Para a confecção deste modelo foi utilizado a última versão (1.9.7) do pacote de classes \textit{abnTeX2} que segue as normas da Associação Brasileira de Normas Técnicas. A elaboração de uma monografia, dissertação ou tese pode ser feita sobrescrevendo o conteúdo deste modelo.
    }{Modelo, Monografia de qualificação, Dissertação, Tese, Latex}

% resumo em INGLÊS
% conter no máximo 500 palavras
% conter no mínimo 1 e no máximo 5 palavras-chave
\textoresumo[english]{
    This paper is a brief model for writing qualification monographs, dissertations and thesis using \LaTeX environment, in accordance with the standards required by the Institute of Mathematics and Computer Sciences (ICMC), University of São Paulo (USP). For making this model, the latest version (1.9.7) \textit{abnTeX2} classes package was used. This package follow the rules of the Brazilian Association of Technical Standards. A drafting a monograph, dissertation or thesis can be done by overwriting the contents of this model.
    }{Template, Qualification monograph, Dissertation, Thesis, Latex}

% ----------------------------------------------------------
% ELEMENTOS PRÉ-TEXTUAIS
% ----------------------------------------------------------

% Inserir a ficha catalográfica
\incluifichacatalografica{tex/pre-textual/ficha-catalografica.pdf}

% DEDICATÓRIA / AGRADECIMENTO / EPÍGRAFE
\textodedicatoria*{tex/pre-textual/dedicatoria}
\textoagradecimentos*{tex/pre-textual/agradecimentos}
\textoepigrafe*{tex/pre-textual/epigrafe}

% Inclui a lista de figuras
\incluilistadefiguras

% Inclui a lista de tabelas
\incluilistadetabelas

% Inclui a lista de quadros
\incluilistadequadros

% Inclui a lista de algoritmos
\incluilistadealgoritmos

% Inclui a lista de códigos
\incluilistadecodigos

% Inclui a lista de siglas e abreviaturas
\incluilistadesiglas

% Inclui a lista de símbolos
\incluilistadesimbolos

% ----
% Início do documento
% ----
\begin{document}
% ----------------------------------------------------------
% ELEMENTOS TEXTUAIS
% ----------------------------------------------------------
\textual

\chapter{Introdução}
\label{chapter:introducao}
\input{tex/introducao}

\chapter{Instalando o abnTeX2}
\label{chapter:instalando-abntex}
\input{tex/instalando-abntex}

\chapter{Orientações gerais}
\label{chapter:orientacoes-gerais}
\input{tex/orientacoes-gerais}

\chapter{Configuração dos elementos pré-textuais}
\label{chapter:config-pre-textual}
\input{tex/config-pre-textual}

\chapter{Corpos flutuantes}
\label{chapter:corpos-flutuantes}
\input{tex/corpos-flutuantes}

\chapter{Listas}
\label{chapter:listas}
\input{tex/listas}

\chapter{Ferramentas úteis}
\label{chapter:ferramentas-uteis}
\input{tex/ferramentas-uteis}

\chapter{Citações e referências}
\label{chapter:citacoes}
\input{tex/citacoes}

% ---
% Finaliza a parte no bookmark do PDF, para que se inicie o bookmark na raiz
% ---
\bookmarksetup{startatroot}%
% ---

% ----------------------------------------------------------
% ELEMENTOS PÓS-TEXTUAIS
% ----------------------------------------------------------
\postextual

% ----------------------------------------------------------
% Referências bibliográficas
% ----------------------------------------------------------
\bibliography{references}

% ---------------------------------------------------------------------
% GLOSSÁRIO
% ---------------------------------------------------------------------

% Arquivo que contém as definições que vão aparecer no glossário
\input{tex/glossario}
% Comando para incluir todas as definições do arquivo glossario.tex
\glsaddall
% Impressão do glossário
\printglossaries

% ----------------------------------------------------------
% Apêndices
% ----------------------------------------------------------

% ---
% Inicia os apêndices
% ---
\begin{apendicesenv}

    \chapter{Documento básico usando a classe \textit{icmc}}
    \label{chapter:documento-basico}
    \input{tex/appendix/documento-basico}

    \chapter{Configuração do programa JabRef}
    \label{chapter:configuracao-jabref}
    \input{tex/appendix/configuracao-jabref}

\end{apendicesenv}
% ---

% ----------------------------------------------------------
% Anexos
% ----------------------------------------------------------

% ---
% Inicia os anexos
% ---
\begin{anexosenv}

    \chapter{Páginas interessantes na Internet}
    \label{chapter:paginas-interessantes}
    \input{tex/annex/paginas-interessantes}

\end{anexosenv}
% ---

\end{document}


text:
Micro app to display a home dashboard showing temperature, power
usage and other data collected from local sensors. The dashboard is updated
in realtime using socket.io.

The dashboards listens on a number of mqtt topics for updates and then
forwards the updates to clients using socket.io.  It provides a simple way
to display iot sensor data on a client.

This is an example display:

![picture of dashboard main window](pictures/dashboard_main_window.jpg?raw=true)

The following project can be used to connect sensors temperature
sensors and power sensors:

* [PI433WirelessRecvMananager](https://github.com/mhdawson/PI433WirelessRecvManager)

# Usage

After installation modify ../lib/config.json to match your configuration.

The configuration entries that must be updated include:

* mqttServerUrl - url of the mqtt server to connect to.  This can either start
  with tcp:// or mqtts://. If it starts with mqtts://  there must be a subdirectory
  in the lib directory called mqttclient which contains ca.cert, client.cert,
  client.key which contain the key and associated certificates for a client
  which is authorized to connect to the mqtt server.
* dashboardEntries - array in which each entry contains a name and topic field.
  The name is what will be displayed as the label in the dashboard and the topic
  is the topic on which the dashboard will listen for updates.  Updates on the
  topic should be in the form of yyyyy,xxxx:value were yyyyy is generally a
  timestamp and the dasboard will extract the value after the ':' character and
  display it as the value for the corresponding label
* serverPort - port on which the dashboard listens for connections
* title - title for the dashbaord paged (optional)

As a micro-app the dashboard also supports other options like authentication and
tls for the dashboard connection.  See the documentation for the micro-app-framework
for additional details.

The following is an example configuration file:

{
  "title": "House Data",
  "serverPort": 3000,
  "mqttServerUrl": ""tcp://10.1.1.1:1883",
  "dashboardEntries": [ {"name": "Inside temp", "topic": "house/temp2"},
                        {"name": "Outside temp", "topic": "house/lacrossTX141/20/temp"},
                        {"name": "Timestamp", "topic": "house/time"} ]
}

# Installation

Simply run npm install micro-app-simple-dashboard.

# Running

To run the simple-dashboard app, add node.js to your path (currently requires 4.x or better) and
then run:

npm start

from the directory in which the micro-app-simple-dashboard was installed.

Once the server is started. Point your browser at the host/port for the server.
If you have configured your browser to allow javascript to close the current page
the original window will be closed and one with the correct size of the
simple-dashboard app page will be created.

# Example

The following is the page shown for a sample configuration:

![picture of dashboard main window](pictures/dashboard_main_window.jpg?raw=true)

# Key Depdencies

## micro-app-framework
As a micro-app the onetime password app depends on the micro-app-framework:

* [micro-app-framework npm](https://www.npmjs.com/package/micro-app-framework)
* [micro-app-framework github](https://github.com/mhdawson/micro-app-framework)

See the documentation on the micro-app-framework for more information on general
configuration options that are availble (ex using tls, authentication, serverPort, etc).

# TODO
* option to support different skins
* better/more precise layout


text:
package org.hswebframework.web.system.authorization.api;

public interface UsernameValidator {

    void validate(String password);

}


text:
  <ion-row align-items-center>
    <ion-col col-4 text-left>
      <button ion-button clear icon-only color="grey" (click)="backdropDismiss()">
        <ion-icon name="arrow-round-back"></ion-icon>
      </button>
    </ion-col>
    <ion-col col-4 text-center class="destination-title">{{ title }}</ion-col>
  </ion-row>

    <ion-item-divider>

        Bitcoin Wallets

    </ion-item-divider>

    <ion-list>
      <button ion-item detail-none *ngFor="let wallet of walletsBtc" class="wallet-button" (click)="selectWallet(wallet)">
        <ion-icon item-start>

        </ion-icon>
        <ion-icon item-end>

        </ion-icon>

{{wallet.name}}

            Incomplete

            Needs backup

              {{wallet.status && wallet.status.totalBalanceStr ? (wallet.status.totalBalanceStr) : ( wallet.cachedBalance ? wallet.cachedBalance + (wallet.cachedBalanceUpdatedOn ? ' · ' + ( wallet.cachedBalanceUpdatedOn * 1000 | amTimeAgo) : '') : '')}}

            Scanning funds
            [
              Balance Hidden]
             1" translate>{{wallet.credentials.m}}-of-{{wallet.credentials.n}}
            <ion-icon *ngIf="!wallet.balanceHidden && wallet.status && (wallet.status.totalBalanceSat != wallet.status.spendableAmount)" name="timer"></ion-icon>
            {{wallet.error}}

      </button>
    </ion-list>

    <ion-item-divider>

        Bitcoin Cash Wallets

    </ion-item-divider>

    <ion-list>
      <button ion-item detail-none *ngFor="let wallet of walletsBch" class="wallet-button" (click)="selectWallet(wallet)">
        <ion-icon item-start>

        </ion-icon>
        <ion-icon item-end>

        </ion-icon>

{{wallet.name}}

            Incomplete

            Needs backup

              {{wallet.status && wallet.status.totalBalanceStr ? (wallet.status.totalBalanceStr) : ( wallet.cachedBalance ? wallet.cachedBalance + (wallet.cachedBalanceUpdatedOn ? ' · ' + ( wallet.cachedBalanceUpdatedOn * 1000 | amTimeAgo) : '') : '')}}

            Scanning funds
            [
              Balance Hidden]
             1">{{wallet.credentials.m}}-of-{{wallet.credentials.n}}
            <ion-icon *ngIf="!wallet.balanceHidden && wallet.status && (wallet.status.totalBalanceSat != wallet.status.spendableAmount)" name="timer"></ion-icon>
            {{wallet.error}}

      </button>
    </ion-list>


text:
import logging
import numpy as np
import pandas as pd

from dowhy.utils.api import parse_state

class DoSampler:
    """Base class for a sampler from the interventional distribution.

    """

    def __init__(self, data,
                 params=None, variable_types=None,
                 num_cores=1, causal_model=None, keep_original_treatment=False):
        """
        Initializes a do sampler with data and names of relevant variables.

        Do sampling implements the do() operation from Pearl (2000). This is an operation is defined on a causal
        bayesian network, an explicit implementation of which is the basis for the MCMC sampling method.

        We abstract the idea behind the three-step process to allow other methods, as well. The `disrupt_causes`
        method is the means to make treatment assignment ignorable. In the Pearlian framework, this is where we cut the
        edges pointing into the causal state. With other methods, this will typically be by using some approach which
        assumes conditional ignorability (e.g. weighting, or explicit conditioning with Robins G-formula.)

        Next, the `make_treatment_effective` method reflects the assumption that the intervention we impose is
        "effective". Most simply, we fix the causal state to some specific value. We skip this step there is no value
        specified for the causal state, and the original values are used instead.

        Finally, we sample from the resulting distribution. This can be either from a `point_sample` method, in the case
        that the inference method doesn't support batch sampling, or the `sample` method in the case that it does. For
        convenience, the `point_sample` method parallelizes with `multiprocessing` using the `num_cores` kwargs to set
        the number of cores to use for parallelization.

        While different methods will have their own class attributes, the `_df` method should be common to all methods.
        This is them temporary dataset which starts as a copy of the original data, and is modified to reflect the steps
        of the do operation. Read through the existing methods (weighting is likely the most minimal) to get an idea of
        how this works to implement one yourself.

        :param data: pandas.DataFrame containing the data
        :param identified_estimand: dowhy.causal_identifier.IdentifiedEstimand: and estimand using a backdoor method
        for effect identification.
        :param treatments: list or str:  names of the treatment variables
        :param outcomes: list or str: names of the outcome variables
        :param variable_types: dict: A dictionary containing the variable's names and types. 'c' for continuous, 'o'
        for ordered, 'd' for discrete, and 'u' for unordered discrete.
        :param keep_original_treatment: bool: Whether to use `make_treatment_effective`, or to keep the original
        treatment assignments.
        :param params: (optional) additional method parameters

        """
        self._data = data.copy()
        self._causal_model = causal_model
        self._target_estimand = self._causal_model.identify_effect()
        self._target_estimand.set_identifier_method("backdoor")
        self._treatment_names = parse_state(self._causal_model._treatment)
        self._outcome_names = parse_state(self._causal_model._outcome)
        self._estimate = None
        self._variable_types = variable_types
        self.num_cores = num_cores
        self.point_sampler = True
        self.sampler = None
        self.keep_original_treatment = keep_original_treatment

        if params is not None:
            for key, value in params.items():
                setattr(self, key, value)

        self._df = self._data.copy()

        if not self._variable_types:
            self._infer_variable_types()
        self.dep_type = [self._variable_types[var] for var in self._outcome_names]
        self.indep_type = [self._variable_types[var] for var in
                           self._treatment_names + self._target_estimand.get_backdoor_variables()]
        self.density_types = [self._variable_types[var] for var in self._target_estimand.get_backdoor_variables()]

        self.outcome_lower_support = self._data[self._outcome_names].min().values
        self.outcome_upper_support = self._data[self._outcome_names].max().values

        self.logger = logging.getLogger(__name__)

    def _sample_point(self, x_z):
        """
        OVerride this if your sampling method only allows sampling a point at a time.
        :param : numpy.array: x_z is a numpy array containing the values of x and z in the order of the list given by
        self._treatment_names + self._target_estimand.get_backdoor_variables()
        :return: numpy.array:  a sampled outcome point
        """
        raise NotImplementedError

    def reset(self):
        """
        If your `DoSampler` has more attributes that the `_df` attribute, you should reset them all to their
        initialization values by overriding this method.
        :return:
        """
        self._df = self._data.copy()

    def make_treatment_effective(self, x):
        """
        This is more likely the implementation you'd like to use, but some methods may require overriding this method
        to make the treatment effective.
        :param x:
        :return:
        """
        if not self.keep_original_treatment:
            self._df[self._treatment_names] = x

    def disrupt_causes(self):
        """
        Override this method to render treatment assignment conditionally ignorable
        :return:
        """
        raise NotImplementedError

    def point_sample(self):
            if self.num_cores == 1:
                sampled_outcomes = self._df[self._treatment_names +
                                            self._target_estimand.get_backdoor_variables()].apply(self._sample_point, axis=1)
            else:
                from multiprocessing import Pool
                p = Pool(self.num_cores)
                sampled_outcomes = np.array(p.map(self.sampler.sample_point,
                                            self._df[self._treatment_names +
                                                     self._target_estimand.get_backdoor_variables()].values))
                sampled_outcomes = pd.DataFrame(sampled_outcomes, columns=self._outcome_names)
            self._df[self._outcome_names] = sampled_outcomes

    def sample(self):
        """
        By default, this expects a sampler to be built on class initialization which contains a `sample` method.
        Override this method if you want to use a different approach to sampling.
        :return:
        """
        sampled_outcomes = self.sampler.sample(self._df[self._treatment_names +
                                                        self._target_estimand.get_backdoor_variables()].values)
        sampled_outcomes = pd.DataFrame(sampled_outcomes, columns=self._outcome_names)
        self._df[self._outcome_names] = sampled_outcomes

    def do_sample(self, x):
        self.reset()
        self.disrupt_causes()
        self.make_treatment_effective(x)
        if self.point_sampler:
            self.point_sample()
        else:
            self.sample()
        return self._df

    def _infer_variable_types(self):
        raise NotImplementedError('Variable type inference not implemented. Use the variable_types kwarg.')


text:
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.hadoop.hive.metastore.api;

import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;

public enum LockType implements org.apache.thrift.TEnum {
  SHARED_READ(1),
  SHARED_WRITE(2),
  EXCLUSIVE(3);

  private final int value;

  private LockType(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static LockType findByValue(int value) {
    switch (value) {
      case 1:
        return SHARED_READ;
      case 2:
        return SHARED_WRITE;
      case 3:
        return EXCLUSIVE;
      default:
        return null;
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>de.dbis.slave</title>
<meta name="date" content="2014-06-29">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package de.dbis.slave

Class Summary

Class
Description

RabbitMQReceive

Receives the video from server and forwards it to the transcoder.

RabbitMQSend

Sends the notification to the server when the video is transcoded.

Transcode

Transcodes the given video to MP4.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
@extends('app')

@section('content')

            Videouri technology implies automatic indexing of video files over the Internet.
            If you find your own video using Videouri and believe that it is being accessible in a abusive way and constitutes
            your copyright infringement, please perform the following actions. Note that Videouri does not host any of the content
            that can be accessed using Videouri's search results list. Videouri provides links to third-party broadcasting network
            websites and video hosting services only. As a content owner you must realise that removing links to your work from
            Videouri may not result in removing the original source of the video from the third-party service. Therefore content
            owners take the responsibility of contacting the video hosting websites by themselves to demand the removal of their
            digital video property.

            Videouri is in compliance with the

                Digital Millennium Copyright Act
             ("DMCA").
            In accordance with this copyright law Videouri is obliged to respond operatively to claims of copyright infringement
            that are reported to service. In case you are a copyright owner or an authorized person which can act on behalf of
            the owner of the copyright, and believe that your work is being accessible in a abusive way and constitutes your
            copyright infringement, please report the following information to Videouri support team:

                an electronic or physical signature of copyright owner or an authorized person which can act on behalf of the
                owner of the copyright;

                a description of copyrighted file that has been infringed in your opinion. In case if there are multiple
                files, you should provide a detailed list of the files. Note that you are obliged to pay  for all possible
                damages connected with material misrepresentation will in case the file does not infringe your copyrights;

                the complete URL to each file, video or image that you claim is infringing. Videouri requires a sufficient
                information to establish the location of the potentially infringing files on the website and to delete them
                from the Videouri's search results;

                your email, telephone number, and your address;

                a statement by you that you have a good faith belief that the disputed use of the specific file is not
                authorized by the law, the copyright owner, or its agent; and,

                a statement by you, made under penalty of perjury, that the information listed above in your notice is true
                and that you are the owner of the copyright or authorized person which can act on the copyright owner's behalf.

            Send the infringement notice via email to contact@videouri.com.

@endsection


text:
Beta Theta Theta Chi

Beta Theta Chapter of Theta Chi, founded March 24th 1940. Extending helping hand to all who seek it, and developing a brotherhood of Resolute Men at Drexel University

          Find Out More

We've got what you need!

Start Bootstrap has everything you need to get your new website up and running in no time! All of the templates and themes on Start Bootstrap are open source, free to download, and easy to use. No strings attached!

                    Get Started!


text:
package com.github.expixel.imgur.models.response;

import com.github.expixel.imgur.models.special.ImgurGalleryItem;

/**
 * @author ExPixel
 */
public class ImgurTag {
	private String name;
	private int followers;
	private int total_items;
	private ImgurTagFollower[] following;
	private ImgurGalleryItem items;

	public String getName() {
		return name;
	}

	public int getFollowers() {
		return followers;
	}

	public int getTotalItems() {
		return total_items;
	}

	public ImgurTagFollower[] getFollowing() {
		return following;
	}

	public ImgurGalleryItem getItems() {
		return items;
	}

	public static class ImgurTagFollower {
		private String id;
		private String name;
	}
}


text:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="/src/style.css">

    <link rel="stylesheet" type="text/css" href="http://livefyre-cdn.s3.amazonaws.com/libs/sdk/v2.5.1/rc/builds/9/streamhub-sdk.min.css">


text:
var AST = require('./ast');

function handle(obj, collect, context) {
  return handlers[obj.type](obj, collect, context);
}

var handlers = {
  Node: function(node, collect, context) {
    collect('<' + node.name);
    node.attributes.forEach(function(attribute) {
      handle(attribute, collect, context);
    });
    if(!node.children.length) {
      collect(' />');
      return;
    }
    collect('>');
    node.children.forEach(function(child) {
      handle(child, collect, context);
    });
    collect('</' + node.name + '>');
  },
  Attribute: function(attribute, collect, context) {
    collect(' ' + attribute.name + '="');
    handle(attribute.value, collect, context);
    collect('"');
  },
  Literal: function(literal, collect) {
    collect(literal.value);
  },
  Identifier: function(identifier, collect, context) {
    collect({
      type: 'Identifier',
      value: context + '.' + identifier.name
    });
  },
  Conditional: function(conditional, collect, context) {
    console.log(conditional);
    collect({
      type: 'JSLiteral',
      value: 'if(' + context + '.' + conditional.condition + ') {'
    });
    conditional.trueBranch.forEach(function(child) {
      handle(child, collect, context);
    });
    if(!conditional.falseBranch.length) {
      return collect({
        type: 'JSLiteral',
        value: '}'
      });
    }
    collect({
      type: 'JSLiteral',
      value: '} else {'
    });
    conditional.falseBranch.forEach(function(child) {
      handle(child, collect, context);
    });
    collect({
      type: 'JSLiteral',
      value: '}'
    });
  }
}

module.exports = function(block) {
  var ast = AST(block);
  var stack = [];
  function collect(value) {
    if(typeof value == 'string') {
      value = {
        type: 'Literal',
        value: value
      }
    }
    var n = stack.length - 1;
    if(n >= 0 && value.type == 'Literal' && stack[n].type == 'Literal') {
      stack[n].value += value.value;
    } else {
      stack.push(value);
    }
  }
  handle(ast, collect, 'data');
  return new Function('data', 'var a = [];\n' + stack.map(function(item) {
    if(item.type == 'Literal') {
      return 'a.push(\'' + item.value + '\');';
    }
    if(item.type == 'JSLiteral') {
      return item.value;
    }
    return 'a.push(' + item.value + ');';
  }).join('\n') + '\nreturn a.join(\'\');');
};


text:
/**
 * @file
 * This file contains the APIs for KeepAlive Mechanism.
 * In order to ensure that the connection between an OIC Devices,
 * when using CoAP over TCP, OIC Device should send application layer
 * KeepAlive messages.
 */
#ifndef KEEP_ALIVE_H_
#define KEEP_ALIVE_H_

#include "octypes.h"
#include "ocserverrequest.h"
#include "ocresource.h"

#ifdef __cplusplus
extern "C"
{
#endif

/**
 * Name of resource type.
 */
#define KEEPALIVE_RESOURCE_TYPE_NAME "oic.wk.ping"

/**
 * Name of resource interface.
 */
#define KEEPALIVE_RESOURCE_INTF_NAME OC_RSRVD_INTERFACE_READ_WRITE

/**
 * URI of the resource.
 */
#define KEEPALIVE_RESOURCE_URI "/oic/ping"

/**
 * Initialize the KeepAlive.
 * @param[in]   mode        Host mode of operation.
 * @return  ::OC_STACK_OK or Appropriate error code.
 */
OCStackResult InitializeKeepAlive(OCMode mode);

/**
 * Terminates the KeepAlive.
 * @param[in]   mode        Host mode of operation.
 * @return  ::OC_STACK_OK or Appropriate error code.
 */
OCStackResult TerminateKeepAlive(OCMode mode);

/**
 * Process the KeepAlive timer to send ping message to OIC Server.
 */
void ProcessKeepAlive();

/**
 * This API will be called from RI layer whenever there is a request for KeepAlive.
 * Virtual Resource.
 * @param[in]   request     Received request information.
 * @param[in]   resource    Resource handle used for sending the response.
 * @return  ::OC_STACK_OK or Appropriate error code.
 */
OCStackResult HandleKeepAliveRequest(OCServerRequest *request,
                                     const OCResource *resource);

/**
 * API to handle the connected device for KeepAlive.
 * @param[in]   endpoint        Remote endpoint information.
 * @param[in]   isConnected     Whether keepalive message needs to be sent.
 * @param[in]   isClient        Host Mode of Operation.
 */
void HandleKeepAliveConnCB(const CAEndpoint_t *endpoint, bool isConnected, bool isClient);

#ifdef __cplusplus
} // extern "C"
#endif

#endif // KEEP_ALIVE_H_


text:
import { ElementHandle, Page } from 'puppeteer';
import AuthenticatedPage from 'app/page/authenticated-page';
import { waitForDocumentTitle } from 'utils/waits-utils';
import AdminTable from 'app/component/admin-table';
import ClrIconLink from 'app/element/clr-icon-link';

const PageTitle = 'Institution Admin | All of Us Researcher Workbench';

export const LabelAlias = {
  CreateNewInstitution: 'Institution admin table'
};

export default class InstitutionAdminPage extends AuthenticatedPage {
  constructor(page: Page) {
    super(page);
  }

  async isLoaded(): Promise<boolean> {
    await Promise.all([waitForDocumentTitle(this.page, PageTitle)]);
    await this.getInstitutionTable().exists();
    return true;
  }

  getInstitutionTable(): AdminTable {
    return new AdminTable(this.page);
  }

  getCreateNewInstitutionBtn(): ClrIconLink {
    return ClrIconLink.findByName(this.page, { name: LabelAlias.CreateNewInstitution, iconShape: 'plus-circle' });
  }

  // click institution name on the institution-list-page
  async clickInstitutionNameLink(institutionName: string): Promise<void> {
    const nameLink = await this.getInstitutionNameLink(institutionName);
    await nameLink.click();
  }

  async getInstitutionNameLink(institutionName: string): Promise<ElementHandle> {
    return this.page.waitForXPath(this.institutionNameLinkSelector(institutionName));
  }

  private institutionNameLinkSelector(institutionName: string): string {
    return `//tr/td/a[text()="${institutionName}"]`;
  }
}


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

namespace Stall
{
    public static class Errors
    {
        public const int ShowHelp = 0;
        public const int NoArgs = ShowHelp + 1;
        public const int CutShort = NoArgs + 1;
        public const int BadPath = CutShort + 1;
        public const int BadVersion = BadPath + 1;
        public const int ExistingFolder = BadVersion + 1;
        public const int ExistingKey = ExistingFolder + 1;
        public const int RemoveFailed = ExistingKey + 1;
        public const int NoTargets = RemoveFailed + 1;
        public const int TwoDirectories = NoTargets + 1;
        public const int MissingArgs = TwoDirectories + 1;
        public const int BadAbsolute = MissingArgs + 1;
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:padding="10dp"
    android:orientation="vertical"
    android:layout_height="match_parent" >

    <TextView
        android:text="Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_marginBottom="10dp"
        android:layout_height="wrap_content" />

    <TextView
        android:text="Age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/etAge"
        android:layout_width="match_parent"
        android:layout_marginBottom="10dp"
        android:layout_height="wrap_content" />

    <TextView
        android:text="Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_marginBottom="10dp"
        android:layout_height="wrap_content" />

    <TextView
        android:text="Password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textPassword"
        android:layout_marginBottom="10dp"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/bRegister"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register" />

</LinearLayout>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Threading.Tasks;
using Azure.Core.TestFramework;
using NUnit.Framework;
using Azure.ResourceManager.ConnectedVMwarevSphere.Models;
using Azure.ResourceManager.ConnectedVMwarevSphere.Tests.Helpers;
using Azure.ResourceManager.Resources.Models;

namespace Azure.ResourceManager.ConnectedVMwarevSphere.Tests.tests.Tests
{
    public class VirtualMachineTemplateTests : ConnectedVMwareTestBase
    {
        public VirtualMachineTemplateTests(bool isAsync) : base(isAsync)
        {
        }

        private async Task<VirtualMachineTemplateCollection> GetVirtualMachineTemplateCollectionAsync()
        {
            var resourceGroup = await CreateResourceGroupAsync();
            return resourceGroup.GetVirtualMachineTemplates();
        }

        [TestCase]
        [RecordedTest]
        public async Task CreateDelete()
        {
            var vmtemplateName = Recording.GenerateAssetName("testvmtemplate");
            var _virtualMachineTemplateCollection = await GetVirtualMachineTemplateCollectionAsync();
            var _extendedLocation = new ExtendedLocation()
            {
                Name = CustomLocationId,
                ExtendedLocationType = EXTENDED_LOCATION_TYPE
            };
            var virtualMachineTemplateBody = new VirtualMachineTemplateData(DefaultLocation);
            virtualMachineTemplateBody.MoRefId = "vm-70";
            virtualMachineTemplateBody.VCenterId = VcenterId;
            virtualMachineTemplateBody.ExtendedLocation = _extendedLocation;
            // create virtual machine template
            VirtualMachineTemplateResource vmtemplate1 = (await _virtualMachineTemplateCollection.CreateOrUpdateAsync(WaitUntil.Completed, vmtemplateName, virtualMachineTemplateBody)).Value;
            Assert.IsNotNull(vmtemplate1);
            Assert.AreEqual(vmtemplate1.Id.Name, vmtemplateName);
        }

        [TestCase]
        [RecordedTest]
        public async Task Get()
        {
            var vmtemplateName = Recording.GenerateAssetName("testvmtemplate");
            var _virtualMachineTemplateCollection = await GetVirtualMachineTemplateCollectionAsync();
            var _extendedLocation = new ExtendedLocation()
            {
                Name = CustomLocationId,
                ExtendedLocationType = EXTENDED_LOCATION_TYPE
            };
            var virtualMachineTemplateBody = new VirtualMachineTemplateData(DefaultLocation);
            virtualMachineTemplateBody.MoRefId = "vm-74";
            virtualMachineTemplateBody.VCenterId = VcenterId;
            virtualMachineTemplateBody.ExtendedLocation = _extendedLocation;
            // create virtual machine template
            VirtualMachineTemplateResource vmtemplate1 = (await _virtualMachineTemplateCollection.CreateOrUpdateAsync(WaitUntil.Completed, vmtemplateName, virtualMachineTemplateBody)).Value;
            Assert.IsNotNull(vmtemplate1);
            Assert.AreEqual(vmtemplate1.Id.Name, vmtemplateName);
            // get vm template
            vmtemplate1 = await _virtualMachineTemplateCollection.GetAsync(vmtemplateName);
            Assert.AreEqual(vmtemplate1.Id.Name, vmtemplateName);
        }

        [TestCase]
        [RecordedTest]
        public async Task Exists()
        {
            var vmtemplateName = Recording.GenerateAssetName("testvmtemplate");
            var _virtualMachineTemplateCollection = await GetVirtualMachineTemplateCollectionAsync();
            var _extendedLocation = new ExtendedLocation()
            {
                Name = CustomLocationId,
                ExtendedLocationType = EXTENDED_LOCATION_TYPE
            };
            var virtualMachineTemplateBody = new VirtualMachineTemplateData(DefaultLocation);
            virtualMachineTemplateBody.MoRefId = "vm-72";
            virtualMachineTemplateBody.VCenterId = VcenterId;
            virtualMachineTemplateBody.ExtendedLocation = _extendedLocation;
            // create virtual machine template
            VirtualMachineTemplateResource vmtemplate1 = (await _virtualMachineTemplateCollection.CreateOrUpdateAsync(WaitUntil.Completed, vmtemplateName, virtualMachineTemplateBody)).Value;
            Assert.IsNotNull(vmtemplate1);
            Assert.AreEqual(vmtemplate1.Id.Name, vmtemplateName);
            // check for exists vm template
            bool exists = await _virtualMachineTemplateCollection.ExistsAsync(vmtemplateName);
            Assert.IsTrue(exists);
        }

        [TestCase]
        [RecordedTest]
        public async Task GetAll()
        {
            var vmtemplateName = Recording.GenerateAssetName("testvmtemplate");
            var _virtualMachineTemplateCollection = await GetVirtualMachineTemplateCollectionAsync();
            var _extendedLocation = new ExtendedLocation()
            {
                Name = CustomLocationId,
                ExtendedLocationType = EXTENDED_LOCATION_TYPE
            };
            var virtualMachineTemplateBody = new VirtualMachineTemplateData(DefaultLocation);
            virtualMachineTemplateBody.MoRefId = "vm-11788";
            virtualMachineTemplateBody.VCenterId = VcenterId;
            virtualMachineTemplateBody.ExtendedLocation = _extendedLocation;
            // create virtual machine template
            VirtualMachineTemplateResource vmtemplate1 = (await _virtualMachineTemplateCollection.CreateOrUpdateAsync(WaitUntil.Completed, vmtemplateName, virtualMachineTemplateBody)).Value;
            Assert.IsNotNull(vmtemplate1);
            Assert.AreEqual(vmtemplate1.Id.Name, vmtemplateName);
            int count = 0;
            await foreach (var vmtemplate in _virtualMachineTemplateCollection.GetAllAsync())
            {
                count++;
            }
            Assert.GreaterOrEqual(count, 1);
        }

        [TestCase]
        [RecordedTest]
        public async Task GetAllInSubscription()
        {
            var vmtemplateName = Recording.GenerateAssetName("testvmtemplate");
            var _virtualMachineTemplateCollection = await GetVirtualMachineTemplateCollectionAsync();
            var _extendedLocation = new ExtendedLocation()
            {
                Name = CustomLocationId,
                ExtendedLocationType = EXTENDED_LOCATION_TYPE
            };
            var virtualMachineTemplateBody = new VirtualMachineTemplateData(DefaultLocation);
            virtualMachineTemplateBody.MoRefId = "vm-75";
            virtualMachineTemplateBody.VCenterId = VcenterId;
            virtualMachineTemplateBody.ExtendedLocation = _extendedLocation;
            // create virtual machine template
            VirtualMachineTemplateResource vmtemplate1 = (await _virtualMachineTemplateCollection.CreateOrUpdateAsync(WaitUntil.Completed, vmtemplateName, virtualMachineTemplateBody)).Value;
            Assert.IsNotNull(vmtemplate1);
            Assert.AreEqual(vmtemplate1.Id.Name, vmtemplateName);
            vmtemplate1 = null;
            await foreach (var vmtemplate in DefaultSubscription.GetVirtualMachineTemplatesAsync())
            {
                if (vmtemplate.Data.Name == vmtemplateName)
                {
                    vmtemplate1 = vmtemplate;
                }
            }
            Assert.NotNull(vmtemplate1);
        }
    }
}


text:
(function() {
    'use strict';

    angular
        .module('app.editAdd')
        .directive('uploadImage', UploadImageDirective);

    UploadImageDirective.$inject = [];

    /**
     * This function returns the directive set up.
     * @returns {*} Directive object as defined by AngularJS
     */
    function UploadImageDirective() {

        return {
            restrict: 'E',
            replace: false,
            controller: UploadImageController,
            controllerAs: 'uploadImgCtrl',
            bindToController: {
                image: '=',
                exceededSize: '=',
                type: '='
            },
            templateUrl: 'app/views/edit-add/edit-add.directives/upload-image/upload-image.template.html'
        };
    }

    UploadImageController.$inject = [];

    /**
     * @ngdoc function
     * @description
     * Controls the UploadImageDirective directive
     * @constructor
     */
    function UploadImageController() {
        var uploadImgCtrl = this;

        if (uploadImgCtrl.image === '' || !uploadImgCtrl.image) {
            var imgUrl;
            switch (uploadImgCtrl.type) {
                case 'phone':
                    imgUrl = 'assets/images/phone_25x42.svg';
                    break;
                case 'tablet':
                    imgUrl = 'assets/images/tablet_40x45.svg';
                    break;
                case 'laptop':
                    imgUrl = 'assets/images/laptop_56x38.svg';
                    break;
                case 'camera':
                    imgUrl = 'assets/images/camera_45x34.svg';
                    break;
                case 'software':
                    imgUrl = 'assets/images/code.svg';
                    break;
                case 'book':
                    imgUrl = 'assets/images/book.svg';
                    break;
                case 'misc':
                    imgUrl = 'assets/images/circle-thin-checkit-green.svg';
                    break;
                default:
                    imgUrl = 'assets/images/circle-thin-checkit-green.svg';
            }
            uploadImgCtrl.altImage = imgUrl;
            uploadImgCtrl.imageLoaded = true;
        }

        /**
         * Updates the image on the client first so the <img> tag's src attribute is updated
         * @param  {object} file The image file
         */
        uploadImgCtrl.updateImage = function(file) {
            if (file) {
                uploadImgCtrl.imageLoaded = false;
                uploadImgCtrl.image = file;
            }
        };

        /**
         * Called once the image has loaded from the server.
         * Used to display a loader spinner while the image loads.
         */
        uploadImgCtrl.onImageLoad = function() {
            uploadImgCtrl.imageLoaded = true;
        };
    }
})();


text:
package com.albedinsky.android.util;

import junit.framework.TestCase;

/**
 * @author Martin Albedinsky
 */
public final class LoggerTest extends TestCase {

	@SuppressWarnings("unused")
	private static final String TAG = "LoggerTest";

	public void testReset() {
		// Default enabled logs: DEBUG | INFO | WARN | ERROR
		Logger.reset();
		assertLogEnabled(Logger.DEBUG);
		assertLogEnabled(Logger.INFO);
		assertLogEnabled(Logger.WARN);
		assertLogEnabled(Logger.ERROR);
		assertLogDisabled(Logger.VERBOSE);
		assertLogDisabled(Logger.WTF);
	}

	public void testEnable() {
		Logger.disableAll();
		testEnableLog(Logger.VERBOSE);
		testEnableLog(Logger.DEBUG);
		testEnableLog(Logger.INFO);
		testEnableLog(Logger.WARN);
		testEnableLog(Logger.ERROR);
		testEnableLog(Logger.WTF);
	}

	private void testEnableLog(int log) {
		Logger.enable(log);
		assertLogEnabled(log);
	}

	public void testDisable() {
		Logger.enableAll();
		testDisableLog(Logger.VERBOSE);
		testDisableLog(Logger.DEBUG);
		testDisableLog(Logger.INFO);
		testDisableLog(Logger.WARN);
		testDisableLog(Logger.ERROR);
		testDisableLog(Logger.WTF);
	}

	private void testDisableLog(int log) {
		Logger.disable(log);
		assertLogDisabled(log);
	}

	public void testEnableAll() {
		Logger.enableAll();
		assertLogEnabled(Logger.VERBOSE | Logger.DEBUG | Logger.INFO | Logger.WARN | Logger.ERROR | Logger.WTF);
	}

	public void testDisableAll() {
		Logger.disableAll();
		assertLogDisabled(Logger.VERBOSE | Logger.DEBUG | Logger.INFO | Logger.WARN | Logger.ERROR | Logger.WTF);
	}

	public void testSwitchToDebugMode() {
		// Debug mode enabled logs: VERBOSE | DEBUG | INFO | WARN | ERROR
		Logger.switchToDebugMode();
		assertLogEnabled(Logger.VERBOSE | Logger.DEBUG | Logger.INFO | Logger.WARN | Logger.ERROR);
		assertLogDisabled(Logger.WTF);
	}

	public void testSwitchToReleaseMode() {
		// Release mode enabled logs: INFO | WARN | ERROR
		Logger.switchToReleaseMode();
		assertLogEnabled(Logger.INFO | Logger.WARN | Logger.ERROR);
		assertLogDisabled(Logger.VERBOSE | Logger.DEBUG | Logger.WTF);
	}

	private static void assertLogEnabled(int log) {
		assertTrue(Logger.isEnabled(log));
	}

	private static void assertLogDisabled(int log) {
		assertFalse(Logger.isEnabled(log));
	}
}


text:
import getParentNode from "./getParentNode.js";
import getComputedStyle from "./getComputedStyle.js";
import getNodeName from "./getNodeName.js";
import { isHTMLElement } from "./instanceOf.js";
export default function getScrollParent(node) {
  if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
    // $FlowFixMe: assume body is always available
    return node.ownerDocument.body;
  }

  if (isHTMLElement(node)) {
    // Firefox wants us to check `-x` and `-y` variations as well
    var _getComputedStyle = getComputedStyle(node),
        overflow = _getComputedStyle.overflow,
        overflowX = _getComputedStyle.overflowX,
        overflowY = _getComputedStyle.overflowY;

    if (/auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX)) {
      return node;
    }
  }

  return getScrollParent(getParentNode(node));
}


text:
/*\
title: $:/plugins/botwhytho/tiddlyCounter/tc_rate.js
type: application/javascript
module-type: macro

Macro that updates the current average rate of phenomenom being tracked in occurences per hour

\*/
(function(){

/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";

/*
Information about this macro
*/

exports.name = "tc_rate";

exports.params = [
	{name: "td"}
];
/*
Run the macro
*/

exports.run = function(td) {
			var tid = $tw.wiki.getTiddler(td);
			return tid.fields.count ? (parseFloat(tid.fields.count) / parseFloat(tid.fields.duration) * 3600).toFixed(2) : "";
};

})();


text:
const Benchmark = require('benchmark')
const testUtil = require('../test/helpers/utils')
const _ = require('lodash')
const async = require('async')

var lounge = require('../')
var userSchema, User, user, bucket

function connect (options, done) {
  if (lounge) {
    lounge.disconnect()
  }

  lounge = new lounge.Lounge() // recreate it

  var cluster = testUtil.getCluser()
  bucket = cluster.openBucket('lounge_test', function (err) {
    if (err) {
      return done(err)
    }

    if (options.removeMutateIn) {
      delete bucket.mutateIn
      bucket.mutateIn = null
    }

    lounge.connect({
      bucket: bucket
    }, done)
  })
}

function setup (options, done) {
  connect(options, err => {
    if (err) {
      return done(err)
    }

    userSchema = lounge.schema({
      name: String,
      email: { type: String, index: true, indexType: 'array' }
    })

    User = lounge.model('User', userSchema)

    done()
  })
}

let counter = 0

function testFnUser (deferred) {
  counter = counter + 1

  user = new User({
    name: 'Joe Smith',
    email: `joe+${counter}@gmail.com`
  })

  user.save({ waitForIndex: true }, err => {
    deferred.resolve(err)
  })
}

const results = {}

function complete (options, done) {
  results[options.name] = this.stats.mean * 1000
  if (options.flush) {
    bucket.manager().flush(done)
  } else {
    process.nextTick(done)
  }
}

function createTest (options, testFn) {
  return function testerFn (done) {
    console.dir(options, { depth: 3, colors: true })
    const onComplete = _.partial(complete, options, done)
    setup(options, () => {
      var benchNew = new Benchmark(options.name, testFn, {
        defer: true,
        onComplete,
        delay: 0.5
      })

      benchNew.run({ async: true })
    })
  }
}

function createDocs (done) {
  async.timesLimit(3000, 50, (n, cb) => {
    const keyCounter = counter + n
    const k = userSchema.getRefKey('email', `joe+${keyCounter}@gmail.com`)
    const id = `userid_${n}`
    bucket.upsert(k, { keys: [id] }, cb)
  }, done)
}

const testNew = createTest({ name: 'arrayindex.save.new', flush: true }, testFnUser)
const testSecond = createTest({ name: 'arrayindex.save.second', flush: true }, testFnUser)
const testNewOld = createTest({ name: 'arrayindex.save.new.old', removeMutateIn: true, flush: true }, testFnUser)
const testSecondOld = createTest({ name: 'arrayindex.save.second.old', removeMutateIn: true, flush: true }, testFnUser)

counter = 0
testNew(() => {
  counter = 0
  createDocs(() => {
    testSecond(() => {
      counter = 10000
      testNewOld(() => {
        counter = 10000
        createDocs(() => {
          testSecondOld(() => {
            console.dir(results, { depth: 3, colors: true })
            process.exit()
          })
        })
      })
    })
  })
})


text:
namespace cc {
class DisplayItemList;
}

namespace ui {
class ClipRecorder;
class PaintRecorder;
class TransformRecorder;

class COMPOSITOR_EXPORT PaintContext {
 public:
  // Construct a PaintContext that may only re-paint the area in the
  // |invalidation|.
  PaintContext(cc::DisplayItemList* list,
               float device_scale_factor,
               const gfx::Rect& invalidation,
               bool is_pixel_canvas);

  // Clone a PaintContext with an additional |offset|.
  PaintContext(const PaintContext& other, const gfx::Vector2d& offset);

  // Clone a PaintContext that has no consideration for invalidation.
  enum CloneWithoutInvalidation {
    CLONE_WITHOUT_INVALIDATION,
  };
  PaintContext(const PaintContext& other, CloneWithoutInvalidation c);

  PaintContext(const PaintContext&) = delete;
  PaintContext& operator=(const PaintContext&) = delete;

  ~PaintContext();

  // When true, IsRectInvalid() can be called, otherwise its result would be
  // invalid.
  bool CanCheckInvalid() const { return !invalidation_.IsEmpty(); }

  // The device scale of the frame being painted.
  float device_scale_factor() const { return device_scale_factor_; }

  // Returns true if the paint commands are recorded at pixel size instead of
  // DIP.
  bool is_pixel_canvas() const { return is_pixel_canvas_; }

  // When true, the |bounds| touches an invalidated area, so should be
  // re-painted. When false, re-painting can be skipped. Bounds should be in
  // the local space with offsets up to the painting root in the PaintContext.
  bool IsRectInvalid(const gfx::Rect& bounds) const {
    DCHECK(CanCheckInvalid());
    return invalidation_.Intersects(bounds + offset_);
  }

#if DCHECK_IS_ON()
  void Visited(void* visited) const {
    if (!root_visited_)
      root_visited_ = visited;
  }
  void* RootVisited() const { return root_visited_; }
  const gfx::Vector2d& PaintOffset() const { return offset_; }
#endif

  const gfx::Rect& InvalidationForTesting() const { return invalidation_; }

 private:
  // The Recorder classes need access to the internal canvas and friends, but we
  // don't want to expose them on this class so that people must go through the
  // recorders to access them.
  friend class ClipRecorder;
  friend class PaintRecorder;
  friend class TransformRecorder;
  // The Cache class also needs to access the DisplayItemList to append its
  // cache contents.
  friend class PaintCache;

  // Returns a rect with the given size in the space of the context's
  // containing layer.
  gfx::Rect ToLayerSpaceBounds(const gfx::Size& size_in_context) const;

  // Returns the given rect translated by the layer space offset.
  gfx::Rect ToLayerSpaceRect(const gfx::Rect& rect) const;

  raw_ptr<cc::DisplayItemList> list_;
  // The device scale of the frame being painted. Used to determine which bitmap
  // resources to use in the frame.
  float device_scale_factor_;
  // Invalidation in the space of the paint root (ie the space of the layer
  // backing the paint taking place).
  gfx::Rect invalidation_;
  // Offset from the PaintContext to the space of the paint root and the
  // |invalidation_|.
  gfx::Vector2d offset_;
  // If enabled, the paint commands are recorded at pixel size.
  const bool is_pixel_canvas_;

#if DCHECK_IS_ON()
  // Used to verify that the |invalidation_| is only used to compare against
  // rects in the same space.
  mutable raw_ptr<void> root_visited_;
  // Used to verify that paint recorders are not nested. True while a paint
  // recorder is active.
  mutable bool inside_paint_recorder_;
#endif
};

}  // namespace ui

#endif  // UI_COMPOSITOR_PAINT_CONTEXT_H_


text:
<!doctype html>
<title>invoking load by setting src</title>

<video></video>


text:
<?php
namespace AnhNhan\Converge\Modules\Newsroom\Controllers;

use AnhNhan\Converge as cv;
use AnhNhan\Converge\Modules\Newsroom\Activity\ChannelRecorder;
use AnhNhan\Converge\Modules\Newsroom\Storage\ChannelTransaction;
use AnhNhan\Converge\Modules\Newsroom\Transaction\ChannelEditor;
use AnhNhan\Converge\Storage\Transaction\TransactionEditor;
use AnhNhan\Converge\Storage\Transaction\TransactionEntity;
use AnhNhan\Converge\Views\Web\Response\ResponseHtml404;
use YamwLibs\Libs\Html\Markup\MarkupContainer;

use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * @author Anh Nhan Nguyen <anhnhan@outlook.com>
 */
final class ChannelEdit extends ChannelController
{
    public function requiredUserRoles($request)
    {
        return [
            'ROLE_USER',
        ];
    }

    public function handle()
    {
        $request = $this->request;
        $requestMethod = $request->getMethod();
        $query = $this->buildArticleQuery();

        $channel = $this->retrieveChannelObject($request, $query);
        if (!$channel)
        {
            return (new ResponseHtml404)->setText('This is not the channel you are looking for.');
        }

        $errors = [];
        $e_label = null;
        $e_slug = null;

        $channel_uid = $channel->uid;
        $channel_label = $channel->label;
        $channel_slug = $channel->slug;

        $title = $channel_uid ? 'Edit channel \'' . $channel_label . '\'' : 'Create channel';

        $payload = $this->payload_html;
        $payload->setTitle($title);
        $container = new MarkupContainer;
        $payload->setPayloadContents($container);

        if ($requestMethod == 'POST')
        {
            $channel_label = trim($request->request->get('label'));

            $channel_slug = trim($request->request->get('slug'));
            $channel_slug = to_slug($channel_slug);

            if (!strlen($channel_slug))
            {
                $channel_slug = to_slug($channel_label);
            }

            if (!strlen($channel_label))
            {
                $errors[] = 'We require a descriptive label';
                $e_label = 'Better don\'t leave this empty';
            }

            if (!strlen($channel_slug))
            {
                $errors[] = 'A slug needs to be provided';
                $e_slug = 'Should not be empty';
            }

            $exist_object = head($query->searchChannels([$channel_slug]));
            if (!$channel_uid && $exist_object)
            {
                $errors[] = 'Channel with slug already exists';
                $e_slug = 'Already in use';
            }

            if (!$errors)
            {
                $em = $this->app->getEntityManager();

                $editor = ChannelEditor::create($em)
                    ->setActor($this->user->uid)
                    ->setEntity($channel)
                    ->setBehaviourOnNoEffect(TransactionEditor::NO_EFFECT_SKIP)
                ;

                if (!$channel_uid)
                {
                    $editor->addTransaction(
                        ChannelTransaction::create(TransactionEntity::TYPE_CREATE, $channel_slug)
                    );
                }

                $editor
                    ->addTransaction(
                        ChannelTransaction::create(ChannelTransaction::TYPE_EDIT_LABEL, $channel_label)
                    )
                ;

                $recorder = new ChannelRecorder($this->externalApp('activity'));
                $recorder->record($editor->apply());

                $target_uri = '/newsroom/';
                return new RedirectResponse($target_uri);
            }
        }

        if ($errors) {
            $panel = panel()
                ->setHeader(cv\ht('h2', 'Sorry, there had been an error'))
                ->append(cv\ht('p', 'We can\'t continue until these issue(s) have been resolved:'))
            ;
            $list = cv\ht('ul');
            foreach ($errors as $e) {
                $list->append(cv\ht('li', $e));
            }
            $panel->append($list);
            $container->push($panel);
        }

        $form = form($title, $request->getPathInfo(), 'POST')
            ->append(form_textcontrol('Label', 'label', $channel_label)
                ->setError($e_label)
                ->addOption('placeholder', 'A Great Journey')
            )
            ->append(form_textcontrol('Slug', 'slug', $channel_slug)
                ->setError($e_slug)
                ->setHelp(cv\safeHtml('the identifier we use in urls, e.g. a/a-great-journey/article-name-here
usually, copy-paste the label here; we\'ll do the rest
can\'t be changed once created'))
                ->addOption('disabled', $channel_uid ? 'disabled' : null)
                ->addOption('placeholder', 'a-great-journey')
            )
            ->append(form_submitcontrol('newsroom/#' . $channel_uid))
        ;
        $container->push($form);

        return $payload;
    }
}


text:
html, body {
  width: 100%;
  height: 100%;
  color: #f2f2f2;
  background-color: #1b1b1b;
  font-family: Whitney,Helvetica,Arial,sans-serif; }

#slide-container {
  width: 100%;
  height: 100%;
  overflow: hidden; }

#slides {
  width: 200%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0; }

.slide {
  position: absolute;
  top: 0;
  left: 0;
  width: 50%;
  height: 100%; }

#slide-intro {
  background: url("/assets/images/tunnel.jpg") no-repeat center center;
  background-size: cover; }

#slide-contact {
  background: url("/assets/images/green-gradient.jpg") no-repeat center center;
  background-size: cover;
  -webkit-transform: translate(0, 100%);
  -ms-transform: translate(0, 100);
  transform: translate(100%, 0%); }


text:
Convert an octal number, represented as a string (e.g. '1735263'), to its
decimal equivalent using first principles (i.e. no, you may not use built-in or
external libraries to accomplish the conversion).

Implement octal to decimal conversion.  Given an octal input
string, your program should produce a decimal output.

## Note

- Implement the conversion yourself.
  Do not use something else to perform the conversion for you.
- Treat invalid input as octal 0.

## About Octal (Base-8)

Decimal is a base-10 system.

A number 233 in base 10 notation can be understood
as a linear combination of powers of 10:

- The rightmost digit gets multiplied by 10^0 = 1
- The next number gets multiplied by 10^1 = 10
- ...
- The *n*th number gets multiplied by 10^*(n-1)*.
- All these values are summed.

So:

```text
   233 # decimal
 = 2*10^2 + 3*10^1 + 3*10^0
 = 2*100  + 3*10   + 3*1
```

Octal is similar, but uses powers of 8 rather than powers of 10.

So:

```text
   233 # octal
 = 2*8^2 + 3*8^1 + 3*8^0
 = 2*64  + 3*8   + 3*1
 = 128   + 24    + 3
 = 155
```


text:
package org.reflection_no_reflection.generator.introspector;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.lang.model.element.Modifier;
import org.reflection_no_reflection.Annotation;
import org.reflection_no_reflection.Class;
import org.reflection_no_reflection.Field;
import org.reflection_no_reflection.Method;
import org.reflection_no_reflection.visit.ClassPoolVisitor;

/**
 * @author SNI.
 */
public class IntrospectorDumperClassPoolVisitor implements ClassPoolVisitor {

    private List<JavaFile> javaFiles = new ArrayList<>();
    private List<Class<?>> classList = new ArrayList<>();

    private Map<Class<? extends Annotation>, Set<Class<?>>> mapAnnotationTypeToClassContainingAnnotation = new HashMap<>();
    public static final ClassName BASE_REFLECTOR_TYPE_NAME = ClassName.get("org.reflection_no_reflection.runtime", "BaseReflector");
    public static final ClassName CLASS_TYPE_NAME = ClassName.get("org.reflection_no_reflection", "Class");
    public static final ClassName OBJECT_TYPE_NAME = ClassName.get("java.lang", "Object");
    public static final TypeName BYTE_TYPE_NAME = TypeName.get(byte.class);
    public static final TypeName SHORT_TYPE_NAME = TypeName.get(short.class);
    public static final TypeName INT_TYPE_NAME = TypeName.get(int.class);
    public static final TypeName LONG_TYPE_NAME = TypeName.get(long.class);
    public static final TypeName FLOAT_TYPE_NAME = TypeName.get(float.class);
    public static final TypeName DOUBLE_TYPE_NAME = TypeName.get(double.class);
    public static final TypeName CHAR_TYPE_NAME = TypeName.get(char.class);
    public static final TypeName BOOLEAN_TYPE_NAME = TypeName.get(boolean.class);
    public static final ClassName STRING_TYPE_NAME = ClassName.get("java.lang", "String");
    private List<Pattern> includes;
    private List<Pattern> excludes;

    @Override
    public <T> void visit(Class<T> clazz) {
        //TODO add all protected java & android packages
        String className = clazz.getName();
        boolean shouldIncludeClass = filter(className);
        System.out.println("Introspector for class:" + className + "=" + shouldIncludeClass);
        if (shouldIncludeClass) {
            classList.add(clazz);
        }
    }

    public boolean filter(String className) {
        if (className.indexOf('.') == -1) {
            return false;
        }

        boolean inIncludes = false;
        for (Pattern include : includes) {
            if (include.matcher(className).find()) {
                inIncludes = true;
                break;
            }
        }

        if (!inIncludes) {
            return false;
        }

        for (Pattern exclude : excludes) {
            if (exclude.matcher(className).find()) {
                return false;
            }
        }
        return true;
    }

    @Override public void visit(Field field) {

    }

    @Override public void visit(Method method) {

    }

    @Override public void visit(Annotation annotation) {

    }

    @Override public void visitAnnotationMethod(Annotation annotation, Method method) {

    }

    @Override public void endVisit(Class aClass) {

    }

    @Override public void endVisit(Annotation annotation) {

    }

    public Map<Class<? extends Annotation>, Set<Class<?>>> getMapAnnotationTypeToClassContainingAnnotation() {
        return mapAnnotationTypeToClassContainingAnnotation;
    }

    public List<JavaFile> getJavaFiles() {
        javaFiles.clear();
        for (Class<?> aClass : classList) {
            JavaFile javaFile = buildReflector(aClass);
            javaFiles.add(javaFile);
        }

        return javaFiles;
    }

    private JavaFile buildReflector(Class<?> aClass) {
        IntrospectorFieldSetterMethodCreator setterCreator = new IntrospectorFieldSetterMethodCreator();
        IntrospectorMethodInvokerCreator methodInvokerCreator = new IntrospectorMethodInvokerCreator();
        IntrospectorConstructorInvokerCreator constructorInvokerCreator = new IntrospectorConstructorInvokerCreator();
        final MethodSpec setObjectFieldMethod = setterCreator.createSetObjectFieldMethod(aClass);
        final MethodSpec setByteFieldMethod = setterCreator.createSetByteFieldMethod(aClass);
        final MethodSpec setShortFieldMethod = setterCreator.createSetShortFieldMethod(aClass);
        final MethodSpec setIntFieldMethod = setterCreator.createSetIntFieldMethod(aClass);
        final MethodSpec setLongFieldMethod = setterCreator.createSetLongFieldMethod(aClass);
        final MethodSpec setFloatFieldMethod = setterCreator.createSetFloatFieldMethod(aClass);
        final MethodSpec setDoubleFieldMethod = setterCreator.createSetDoubleFieldMethod(aClass);
        final MethodSpec setCharFieldMethod = setterCreator.createSetCharFieldMethod(aClass);
        final MethodSpec setBooleanFieldMethod = setterCreator.createSetBooleanFieldMethod(aClass);

        final MethodSpec methodInvokerMethod = methodInvokerCreator.createMethodInvoker(aClass);
        final MethodSpec constructorInvokerMethod = constructorInvokerCreator.createConstructorInvoker(aClass);

        TypeSpec.Builder reflectorType = TypeSpec.classBuilder(aClass.getSimpleName() + "$$Reflector")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .superclass(BASE_REFLECTOR_TYPE_NAME);

        doAddMethod(reflectorType, setObjectFieldMethod);
        doAddMethod(reflectorType, setByteFieldMethod);
        doAddMethod(reflectorType, setShortFieldMethod);
        doAddMethod(reflectorType, setIntFieldMethod);
        doAddMethod(reflectorType, setLongFieldMethod);
        doAddMethod(reflectorType, setFloatFieldMethod);
        doAddMethod(reflectorType, setDoubleFieldMethod);
        doAddMethod(reflectorType, setCharFieldMethod);
        doAddMethod(reflectorType, setBooleanFieldMethod);
        doAddMethod(reflectorType, methodInvokerMethod);
        doAddMethod(reflectorType, constructorInvokerMethod);
        final String aClassName = aClass.getName();
        return JavaFile.builder(aClassName.substring(0, aClassName.lastIndexOf('.')), reflectorType.build()).build();
    }

    private void doAddMethod(TypeSpec.Builder reflectorType, MethodSpec methodSpec) {
        if (methodSpec != null) {
            reflectorType.addMethod(methodSpec);
        }
    }

    public void setIncludes(List<Pattern> includes) {
        this.includes = includes;
    }

    public void setExcludes(List<Pattern> excludes) {
        this.excludes = excludes;
    }
}


text:
// Copyright (c) KriaSoft, LLC.  All rights reserved.
// Licensed under the Apache License, Version 2.0.  See LICENSE.txt in the project root for license information.

using Microsoft.AspNet.Identity;

namespace App.Server.Data
{
    public class ApplicationUserManager : UserManager<User, int>
    {
        public ApplicationUserManager(IUserStore<User, int> store)
            : base(store)
        {
        }
    }
}


text:
var LocalStrategy    = require('passport-local').Strategy;
var username;

var User       = require('../app/models/user');
var UserInfo   = require('../app/models/userinfo');
module.exports = function(passport) {

    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    //login
    passport.use('local-login', new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true
    },
    function(req, email, password, done) {
        if (email)
            email = email.toLowerCase();

        process.nextTick(function() {
            User.findOne({ 'local.email' :  email }, function(err, user) {

                if (err)
                    return done(err);

                if (!user)
                    return done(null, false, req.flash('loginMessage', 'No user found.'));

                if (!user.validPassword(password))
                    return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));

                else
                {
                    username=new String(email);
                    return done(null, user);
                }
            });
        });

    }));

    //sign-up
    passport.use('local-signup', new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true
    },
    function(req, email, password, done) {
        if (email)
            email = email.toLowerCase();
        process.nextTick(function() {
            // if the user is not already logged in:
            if (!req.user) {
                User.findOne({ 'local.email' :  email }, function(err, user) {
                    // if there are any errors, return the error
                    if (err)
                        return done(err);

                    // check to see if theres already a user with that email
                    if (user) {
                        return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
                    } else {

                        // create the user
                        var newUser            = new User();
                        newUser.local.email    = email;
                        newUser.local.password = newUser.generateHash(password);

                        newUser.save(function(err) {
                            if (err)
                                return done(err);

                            return done(null, newUser);
                        });
                        var date=new Date();
                        var newLoggedinUser=new UserInfo();
                        newLoggedinUser.profile.email=email;
                        newLoggedinUser.profile.dateOfLogin=date.getTime().toISOString();
                        // var array=[];
                        // array.push({question : 'hello' , date: date.getTime() });
                        // newLoggedinUser.profile.sessions.push({questions : array});
                        newLoggedinUser.save(function (err) {
                            if(err)
                                console.log('error in saving');
                        });
                    }

                });
            } else if ( !req.user.local.email ) {
                User.findOne({ 'local.email' :  email }, function(err, user) {
                    if (err)
                        return done(err);

                    if (user) {
                        return done(null, false, req.flash('loginMessage', 'That email is already taken.'));
                    } else {
                        var user = req.user;
                        user.local.email = email;
                        user.local.password = user.generateHash(password);
                        user.save(function (err) {
                            if (err)
                                return done(err);

                            return done(null,user);
                        });
                    }
                });
            } else {
                return done(null, req.user);
            }

        });

    }));

};