code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?php
namespace Tecnotek\ExpedienteBundle\Controller;
use Tecnotek\ExpedienteBundle\Entity\User;
use Tecnotek\ExpedienteBundle\Entity\Route;
use Tecnotek\ExpedienteBundle\Entity\Buseta;
use Tecnotek\ExpedienteBundle\Entity\Period;
use Tecnotek\ExpedienteBundle\Entity\Grade;
use Tecnotek\ExpedienteBundle\Entity\Course;
use Tecnotek\ExpedienteBundle\Entity\CourseEntry;
use Tecnotek\ExpedienteBundle\Entity\CourseClass;
use Tecnotek\ExpedienteBundle\Entity\StudentQualification;
use Tecnotek\ExpedienteBundle\Entity\SubCourseEntry;
use Tecnotek\ExpedienteBundle\Entity\AssignedTeacher;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class SuperAdminController extends Controller
{
public function indexAction($name = "John Doe")
{
return $this->render('TecnotekExpedienteBundle::index.html.twig', array('name' => $name));
}
public function administradorListAction($rowsPerPage = 10)
{
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT users FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_ADMIN'";
$query = $em->createQuery($dql);
$param = $this->get('request')->query->get('rowsPerPage');
if(isset($param) && $param != "")
$rowsPerPage = $param;
$dql2 = "SELECT count(users) FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_ADMIN'";
$page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$page/*page number*/,
$rowsPerPage/*limit per page*/
);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/list.html.twig', array(
'pagination' => $pagination, 'isTeacher' => true, 'rowsPerPage' => $rowsPerPage
));
}
public function administradorCreateAction()
{
$entity = new User();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/new.html.twig', array('entity' => $entity,
'form' => $form->createView()));
}
public function administradorShowAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:User")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/show.html.twig', array('entity' => $entity,
'form' => $form->createView()));
}
public function administradorSaveAction(){
$entity = new User();
$request = $this->getRequest();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$role = $em->getRepository('TecnotekExpedienteBundle:Role')->
findOneBy(array('role' => 'ROLE_ADMIN'));
$entity->getUserRoles()->add($role);
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_administrador',
array('id' => $entity->getId())));
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
));
}
}
public function administradorDeleteAction($id){
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $id );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('_expediente_sysadmin_administrador'));
}
public function administradorUpdateAction(){
$em = $this->getDoctrine()->getEntityManager();
$request = $this->get('request')->request;
$entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $request->get('userId'));
if ( isset($entity) ) {
$entity->setFirstname($request->get('firstname'));
$entity->setLastname($request->get('lastname'));
$entity->setUsername($request->get('username'));
$entity->setEmail($request->get('email'));
$entity->setActive(($request->get('active') == "on"));
$em->persist($entity);
$em->flush();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Administrador/show.html.twig', array('entity' => $entity,
'form' => $form->createView()));
} else {
return $this->redirect($this->generateUrl('_expediente_sysadmin_administrador'));
}
}
/* Metodos para CRUD de Coordinador */
public function coordinadorListAction($rowsPerPage = 10)
{
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT users FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_COORDINADOR'";
$query = $em->createQuery($dql);
$param = $this->get('request')->query->get('rowsPerPage');
if(isset($param) && $param != "")
$rowsPerPage = $param;
$dql2 = "SELECT count(users) FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_COORDINADOR'";
$page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$page/*page number*/,
$rowsPerPage/*limit per page*/
);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/list.html.twig', array(
'pagination' => $pagination, 'isTeacher' => true, 'rowsPerPage' => $rowsPerPage
));
}
public function coordinadorCreateAction()
{
$entity = new User();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/new.html.twig', array('entity' => $entity,
'form' => $form->createView()));
}
public function coordinadorShowAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:User")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/show.html.twig', array('entity' => $entity,
'form' => $form->createView()));
}
public function coordinadorSaveAction(){
$entity = new User();
$request = $this->getRequest();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$role = $em->getRepository('TecnotekExpedienteBundle:Role')->
findOneBy(array('role' => 'ROLE_COORDINADOR'));
$entity->getUserRoles()->add($role);
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_coordinador',
array('id' => $entity->getId())));
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
));
}
}
public function coordinadorDeleteAction($id){
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $id );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('_expediente_sysadmin_coordinador'));
}
public function coordinadorUpdateAction(){
$em = $this->getDoctrine()->getEntityManager();
$request = $this->get('request')->request;
$entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $request->get('userId'));
if ( isset($entity) ) {
$entity->setFirstname($request->get('firstname'));
$entity->setLastname($request->get('lastname'));
$entity->setUsername($request->get('username'));
$entity->setEmail($request->get('email'));
$entity->setActive(($request->get('active') == "on"));
$em->persist($entity);
$em->flush();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Coordinador/show.html.twig', array('entity' => $entity,
'form' => $form->createView()));
} else {
return $this->redirect($this->generateUrl('_expediente_sysadmin_coordinador'));
}
}
/* Final de los metodos para CRUD de Coordinador*/
/* Metodos para CRUD de Profesor */
public function profesorListAction($rowsPerPage = 10)
{
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT users FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_PROFESOR'";
$query = $em->createQuery($dql);
$param = $this->get('request')->query->get('rowsPerPage');
if(isset($param) && $param != "")
$rowsPerPage = $param;
$dql2 = "SELECT count(users) FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_PROFESOR'";
$page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$page/*page number*/,
$rowsPerPage/*limit per page*/
);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/list.html.twig', array(
'pagination' => $pagination, 'isTeacher' => true, 'rowsPerPage' => $rowsPerPage
));
}
public function profesorCreateAction()
{
$entity = new User();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/new.html.twig', array('entity' => $entity,
'form' => $form->createView()));
}
public function profesorShowAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:User")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/show.html.twig', array('entity' => $entity,
'form' => $form->createView()));
}
public function profesorSaveAction(){
$entity = new User();
$request = $this->getRequest();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$role = $em->getRepository('TecnotekExpedienteBundle:Role')->
findOneBy(array('role' => 'ROLE_PROFESOR'));
$entity->getUserRoles()->add($role);
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_profesor',
array('id' => $entity->getId())));
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
));
}
}
public function profesorDeleteAction($id){
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $id );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('_expediente_sysadmin_profesor'));
}
public function profesorUpdateAction(){
$em = $this->getDoctrine()->getEntityManager();
$request = $this->get('request')->request;
$entity = $em->getRepository("TecnotekExpedienteBundle:User")->find( $request->get('userId'));
if ( isset($entity) ) {
$entity->setFirstname($request->get('firstname'));
$entity->setLastname($request->get('lastname'));
$entity->setUsername($request->get('username'));
$entity->setEmail($request->get('email'));
$entity->setActive(($request->get('active') == "on"));
$em->persist($entity);
$em->flush();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\UserFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Profesor/show.html.twig', array('entity' => $entity,
'form' => $form->createView()));
} else {
return $this->redirect($this->generateUrl('_expediente_sysadmin_profesor'));
}
}
/* Final de los metodos para CRUD de Profesor*/
/* Metodos para CRUD de routes */
public function routeListAction($rowsPerPage = 10)
{
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT routes FROM TecnotekExpedienteBundle:Route routes";
$query = $em->createQuery($dql);
$param = $this->get('request')->query->get('rowsPerPage');
if(isset($param) && $param != "")
$rowsPerPage = $param;
$dql2 = "SELECT count(routes) FROM TecnotekExpedienteBundle:Route routes";
$page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$page/*page number*/,
$rowsPerPage/*limit per page*/
);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/list.html.twig', array(
'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 2
));
}
public function routeCreateAction()
{
$entity = new Route();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/new.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 2));
}
public function routeShowAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Route")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity);
if($entity->getRouteType() == 1) {
$students = $entity->getStudents();
} else {
//Get Students From Other Table
$students = $em->getRepository("TecnotekExpedienteBundle:StudentToRoute")->findByRoute($id);
}
$routes = $em->getRepository("TecnotekExpedienteBundle:Route")->findAll();
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/show.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 2, 'students' => $students, 'routes' => $routes));
}
public function routeSaveAction(){
$entity = new Route();
$request = $this->getRequest();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_route', array('id' => $entity->getId())));
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/new.html.twig', array(
'entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2
));
}
}
public function routeDeleteAction($id){
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Route")->find( $id );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('_expediente_sysadmin_route'));
}
public function routeEditAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Route")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/edit.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 2));
}
public function routeUpdateAction(){
$em = $this->getDoctrine()->getEntityManager();
$request = $this->get('request')->request;
$entity = $em->getRepository("TecnotekExpedienteBundle:Route")->find( $request->get('id'));
if ( isset($entity) ) {
$request = $this->getRequest();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\RouteFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_route_show_simple') . "/" . $entity->getId());
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Ruta/edit.html.twig', array(
'entity' => $entity, 'form' => $form->createView(), 'menuIndex' => 2
));
}
} else {
return $this->redirect($this->generateUrl('_expediente_sysadmin_route'));
}
}
/* Final de los metodos para CRUD de routes*/
/* Metodos para CRUD de buses */
public function busListAction($rowsPerPage = 10)
{
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT buses FROM TecnotekExpedienteBundle:Buseta buses";
$query = $em->createQuery($dql);
$param = $this->get('request')->query->get('rowsPerPage');
if(isset($param) && $param != "")
$rowsPerPage = $param;
$dql2 = "SELECT count(buses) FROM TecnotekExpedienteBundle:Buseta buses";
$page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$page/*page number*/,
$rowsPerPage/*limit per page*/
);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/list.html.twig', array(
'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 2
));
}
public function busCreateAction()
{
$entity = new Buseta();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/new.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 2));
}
public function busShowAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Buseta")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/show.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 2));
}
public function busEditAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Buseta")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/edit.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 2));
}
public function busSaveAction(){
$entity = new Buseta();
$request = $this->getRequest();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_bus',
array('id' => $entity->getId(), 'menuIndex' => 2)));
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 2
));
}
}
public function busDeleteAction($id){
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Buseta")->find( $id );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('_expediente_sysadmin_bus'));
}
public function busUpdateAction(){
$em = $this->getDoctrine()->getEntityManager();
$request = $this->getRequest();
$entity = $em->getRepository("TecnotekExpedienteBundle:Buseta")->find($request->get('id'));
if ( isset($entity) ) {
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\BusFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_bus_show_simple') . "/" . $entity->getId());
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Bus/edit.html.twig', array(
'entity' => $entity, 'form' => $form->createView(), 'updateRejected' => true, 'menuIndex' => 2
));
}
} else {
return $this->redirect($this->generateUrl('_expediente_sysadmin_bus'));
}
}
/* Final de los metodos para CRUD de buses*/
/* Metodos para CRUD de periods */
public function periodListAction($rowsPerPage = 10)
{
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT period FROM TecnotekExpedienteBundle:Period period";
$query = $em->createQuery($dql);
$param = $this->get('request')->query->get('rowsPerPage');
if(isset($param) && $param != "")
$rowsPerPage = $param;
$dql2 = "SELECT count(periods) FROM TecnotekExpedienteBundle:Period periods";
$page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$page/*page number*/,
$rowsPerPage/*limit per page*/
);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/list.html.twig', array(
'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 5
));
}
public function periodCreateAction()
{
$entity = new Period();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/new.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5));
}
public function periodShowAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/show.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5));
}
public function periodEditAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/edit.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5));
}
public function periodSaveAction(){
$entity = new Period();
$request = $this->getRequest();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_period',
array('id' => $entity->getId(), 'menuIndex' => 5)));
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5
));
}
}
public function periodDeleteAction($id){
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find( $id );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('_expediente_sysadmin_period'));
}
public function periodUpdateAction(){
$em = $this->getDoctrine()->getEntityManager();
$request = $this->getRequest();
$entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find($request->get('id'));
if ( isset($entity) ) {
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\PeriodFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_period_show_simple') . "/" . $entity->getId());
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/edit.html.twig', array(
'entity' => $entity, 'form' => $form->createView(), 'updateRejected' => true, 'menuIndex' => 5
));
}
} else {
return $this->redirect($this->generateUrl('_expediente_sysadmin_period'));
}
}
/* Final de los metodos para CRUD de periods */
/* Metodos para CRUD de grades */
public function gradeListAction($rowsPerPage = 10)
{
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT entity FROM TecnotekExpedienteBundle:Grade entity";
$query = $em->createQuery($dql);
$param = $this->get('request')->query->get('rowsPerPage');
if(isset($param) && $param != "")
$rowsPerPage = $param;
$dql2 = "SELECT count(entity) FROM TecnotekExpedienteBundle:Grade entity";
$page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$page/*page number*/,
$rowsPerPage/*limit per page*/
);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/list.html.twig', array(
'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 5
));
}
public function gradeCreateAction()
{
$entity = new Grade();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/new.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5));
}
public function gradeShowAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Grade")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/show.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5));
}
public function gradeEditAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Grade")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/edit.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5));
}
public function gradeSaveAction(){
$entity = new Grade();
$request = $this->getRequest();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_grade',
array('id' => $entity->getId(), 'menuIndex' => 5)));
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5
));
}
}
public function gradeDeleteAction($id){
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Grade")->find( $id );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('_expediente_sysadmin_grade'));
}
public function gradeUpdateAction(){
$em = $this->getDoctrine()->getEntityManager();
$request = $this->getRequest();
$entity = $em->getRepository("TecnotekExpedienteBundle:Grade")->find($request->get('id'));
if ( isset($entity) ) {
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\GradeFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_grade_show_simple') . "/" . $entity->getId());
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Grade/edit.html.twig', array(
'entity' => $entity, 'form' => $form->createView(), 'updateRejected' => true, 'menuIndex' => 5
));
}
} else {
return $this->redirect($this->generateUrl('_expediente_sysadmin_grade'));
}
}
/* Final de los metodos para CRUD de Grades */
/* Metodos para CRUD de courses */
public function courseListAction($rowsPerPage = 10)
{
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT entity FROM TecnotekExpedienteBundle:Course entity";
$query = $em->createQuery($dql);
$param = $this->get('request')->query->get('rowsPerPage');
if(isset($param) && $param != "")
$rowsPerPage = $param;
$dql2 = "SELECT count(entity) FROM TecnotekExpedienteBundle:Course entity";
$page = $this->getPaginationPage($dql2, $this->get('request')->query->get('page', 1), $rowsPerPage);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$page/*page number*/,
$rowsPerPage/*limit per page*/
);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/list.html.twig', array(
'pagination' => $pagination, 'rowsPerPage' => $rowsPerPage, 'menuIndex' => 5
));
}
public function courseCreateAction()
{
$entity = new Course();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/new.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5));
}
public function courseShowAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Course")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/show.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5));
}
public function courseEditAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Course")->find($id);
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity);
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/edit.html.twig', array('entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5));
}
public function courseSaveAction(){
$entity = new Course();
$request = $this->getRequest();
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_course',
array('id' => $entity->getId(), 'menuIndex' => 5)));
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(), 'menuIndex' => 5
));
}
}
public function courseDeleteAction($id){
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Course")->find( $id );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('_expediente_sysadmin_course'));
}
public function courseUpdateAction(){
$em = $this->getDoctrine()->getEntityManager();
$request = $this->getRequest();
$entity = $em->getRepository("TecnotekExpedienteBundle:Course")->find($request->get('id'));
if ( isset($entity) ) {
$form = $this->createForm(new \Tecnotek\ExpedienteBundle\Form\CourseFormType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('_expediente_sysadmin_course_show_simple') . "/" . $entity->getId());
} else {
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Course/edit.html.twig', array(
'entity' => $entity, 'form' => $form->createView(), 'updateRejected' => true, 'menuIndex' => 5
));
}
} else {
return $this->redirect($this->generateUrl('_expediente_sysadmin_course'));
}
}
/* Final de los metodos para CRUD de Courses */
public function adminPeriodAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Period")->find($id);
$grades = $em->getRepository("TecnotekExpedienteBundle:Grade")->findAll();
$institutions = $em->getRepository("TecnotekExpedienteBundle:Institution")->findAll();
$dql = "SELECT users FROM TecnotekExpedienteBundle:User users JOIN users.roles r WHERE r.role = 'ROLE_PROFESOR' ORDER BY users.firstname";
$query = $em->createQuery($dql);
$teachers = $query->getResult();
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Period/admin.html.twig', array('entity' => $entity,
'grades' => $grades, 'teachers' => $teachers, 'institutions' => $institutions,
'menuIndex' => 5));
}
public function createEditGroupAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$name = $request->get('name');
$teacherId = $request->get('teacherId');
$groupId = $request->get('groupId');
$periodId = $request->get('periodId');
$gradeId = $request->get('gradeId');
$institutionId = $request->get('institutionId');
$translator = $this->get("translator");
if( isset($name) && isset($teacherId) && isset($groupId)
&& isset($gradeId) && isset($periodId)) {
//Validate Parameters
if( strlen(trim($name)) < 1) {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
} else {
$em = $this->getDoctrine()->getEntityManager();
if($groupId == 0) {//New Group
$group = new \Tecnotek\ExpedienteBundle\Entity\Group();
$group->setPeriod($em->getRepository("TecnotekExpedienteBundle:Period")->find($periodId));
$group->setGrade($em->getRepository("TecnotekExpedienteBundle:Grade")->find($gradeId));
} else {//Edit Group
$group = $em->getRepository("TecnotekExpedienteBundle:Group")->find($groupId);
}
$group->setName($name);
$teacher = $em->getRepository("TecnotekExpedienteBundle:User")->find($teacherId);
$group->setTeacher($teacher);
$institution = $em->getRepository("TecnotekExpedienteBundle:Institution")->find($institutionId);
$group->setInstitution($institution);
$em->persist($group);
if($groupId == 0) {//New Group
//Get groups of period-grade to assigned teacher
$dql = "SELECT g FROM TecnotekExpedienteBundle:CourseClass g WHERE g.period = " . $periodId . " AND g.grade = " . $gradeId;
$query = $em->createQuery($dql);
$courses = $query->getResult();
foreach( $courses as $courseClass )
{
$assignedTeacher = new \Tecnotek\ExpedienteBundle\Entity\AssignedTeacher();
$assignedTeacher->setCourseClass($courseClass);
$assignedTeacher->setGroup($group);
$assignedTeacher->setTeacher($teacher);
$em->persist($assignedTeacher);
}
}
$em->flush();
return new Response(json_encode(array('error' => false, 'message' =>$translator->trans("messages.confirmation.password.change")
,'groupId' => $group->getId() )));
}
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::changeUserPasswordAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadPeriodInfoAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$gradeId = $request->get('gradeId');
$translator = $this->get("translator");
if( isset($gradeId) && isset($periodId)) {
$em = $this->getDoctrine()->getEntityManager();
//Get Groups
$sql = "SELECT g.id, g.name, g.user_id as 'teacherId', CONCAT(u.firstname,' ',u.lastname) as 'teacherName', institution.name as 'institutionName', institution.id as 'institutionId'"
. " FROM tek_groups g"
. " JOIN tek_users u ON u.id = g.user_id"
. " LEFT JOIN tek_institutions institution ON institution.id = g.institution_id"
. " WHERE g.period_id = " . $periodId . " AND g.grade_id = " . $gradeId
. " ORDER BY g.name";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$groups = $stmt->fetchAll();
//Get Courses
$sql = "SELECT cc.id, c.name, cc.user_id as 'teacherId', (CONCAT(u.firstname, ' ', u.lastname)) as 'teacherName', c.id as 'courseId' "
. " FROM tek_courses c, tek_course_class cc, tek_users u"
. " WHERE cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . " AND cc.course_id = c.id AND u.id = cc.user_id"
. " ORDER BY c.name";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$courses = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'groups' => $groups, 'courses' => $courses)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::changeUserPasswordAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function removeGroupAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$groupId = $request->get('groupId');
$translator = $this->get("translator");
if( isset($groupId) ) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:Group")->find( $groupId );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return new Response(json_encode(array('error' => false)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::removeGroupAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function removeEntryAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$entryId = $request->get('entryId');
$translator = $this->get("translator");
if( isset($entryId) ) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:CourseEntry")->find( $entryId );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return new Response(json_encode(array('error' => false)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::removeEntryAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function courseAssociationRemoveAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$associationId = $request->get('associationId');
$translator = $this->get("translator");
if( isset($associationId) ) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:CourseClass")->find( $associationId );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return new Response(json_encode(array('error' => false)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::removeGroupAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadAvailableCoursesAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$gradeId = $request->get('gradeId');
$translator = $this->get("translator");
if( isset($gradeId) && isset($periodId)) {
$em = $this->getDoctrine()->getEntityManager();
//Get Courses
$sql = "SELECT c.id, c.name"
. " FROM tek_courses c"
. " WHERE c.id not in (select cc.course_id from tek_course_class cc where cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . ")"
. " ORDER BY c.name";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$courses = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'courses' => $courses)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::loadAvailableCoursesAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function associateCourseAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$gradeId = $request->get('gradeId');
$courseId = $request->get('courseId');
$teacherId = $request->get('teacherId');
$translator = $this->get("translator");
if( isset($gradeId) && isset($periodId) && isset($courseId) && isset($teacherId)) {
$courseClass = new \Tecnotek\ExpedienteBundle\Entity\CourseClass();
$em = $this->getDoctrine()->getEntityManager();
$teacher = $em->getRepository("TecnotekExpedienteBundle:User")->find($teacherId);
$courseClass->setPeriod($em->getRepository("TecnotekExpedienteBundle:Period")->find($periodId));
$courseClass->setGrade($em->getRepository("TecnotekExpedienteBundle:Grade")->find($gradeId));
$courseClass->setTeacher($teacher);
$courseClass->setCourse($em->getRepository("TecnotekExpedienteBundle:Course")->find($courseId));
$em->persist($courseClass);
//Get groups of period-grade to assigned teacher
$dql = "SELECT g FROM TecnotekExpedienteBundle:Group g WHERE g.period = " . $periodId . " AND g.grade = " . $gradeId;
$query = $em->createQuery($dql);
$groups = $query->getResult();
foreach( $groups as $group )
{
$assignedTeacher = new \Tecnotek\ExpedienteBundle\Entity\AssignedTeacher();
$assignedTeacher->setCourseClass($courseClass);
$assignedTeacher->setGroup($group);
$assignedTeacher->setTeacher($teacher);
$em->persist($assignedTeacher);
}
$em->flush();
return new Response(json_encode(array('error' => false, 'courseClass' => $courseClass->getId())));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::loadAvailableCoursesAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadAvailableCoursesGroupsAction(){ //2016 - 4
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
//$gradeId = $request->get('gradeId');
$translator = $this->get("translator");
if(isset($periodId)) {
$em = $this->getDoctrine()->getEntityManager();
//Get Courses
$sql = "SELECT c.id, c.name"
. " FROM tek_courses c"
//. " WHERE c.id not in (select cc.course_id from tek_course_class cc where cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . ")"
. " ORDER BY c.name";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$courses = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'courses' => $courses)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::loadAvailableCoursesGroupsAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadAvailableCourseClassAction(){ //2016 -4
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$groupId = $request->get('groupId');
$keywords = preg_split("/[\s-]+/", $groupId);
$groupId = $keywords[0];
$gradeId = $keywords[1];
$translator = $this->get("translator");
if( isset($gradeId) && isset($periodId)) {
$em = $this->getDoctrine()->getEntityManager();
//Get Courses
$sql = "SELECT cc.id as courseclass, c.id as course, c.name as name"
. " FROM tek_courses c, tek_course_class cc"
. " WHERE cc.course_id = c.id and cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . " "
. " ORDER BY c.name";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$courses = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'courses' => $courses)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::loadAvailableCourseClassAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadCoursesExtraPointsAction(){ //2016 -5
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
/*$keywords = preg_split("/[\s-]+/", $groupId);
$groupId = $keywords[0];
$gradeId = $keywords[1];*/
$translator = $this->get("translator");
if( isset($periodId)) {
$em = $this->getDoctrine()->getEntityManager();
//Get Courses
$sql = "SELECT c.id, c.name as name"
. " FROM tek_courses c"
//. " WHERE cc.course_id = c.id and cc.period_id = " . $periodId . " AND cc.grade_id = " . $gradeId . " "
. " ORDER BY c.name";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$courses = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'courses' => $courses)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::loadAvailableCourseClassAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadCoursesByTeacherAction(){ //2016 - 4
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$teacherId = $request->get('teacherId');
$translator = $this->get("translator");
if( isset($periodId) && isset($teacherId)) {
$em = $this->getDoctrine()->getEntityManager();
/* $dql = "SELECT a FROM TecnotekExpedienteBundle:AssignedTeacher a WHERE a.period = $periodId AND a.user = $teacherId";
$query = $em->createQuery($dql);
$entries = $query->getResult();
*/
$stmt = $this->getDoctrine()->getEntityManager()
->getConnection()
->prepare('SELECT t.id as id, t.group_id, c.id as course, c.name as name, cc.id as courseclass, concat(g.grade_id,"-",g.name) as groupname
FROM `tek_assigned_teachers` t, tek_courses c, tek_course_class cc, tek_groups g
where cc.course_id = c.id and t.course_class_id = cc.id and g.id = t.group_id and cc.period_id = "'.$periodId.'" and t.user_id = "'.$teacherId.'"');
$stmt->execute();
$entity = $stmt->fetchAll();
$colors = array(
"one" => "#38255c",
"two" => "#04D0E6"
);
$html = "";
$groupOptions = "";
foreach( $entity as $entry ){
$html .= '<div id="courseTeacherRows_' . $entry['id'] . '" class="row userRow tableRowOdd">';
$html .= ' <div id="entryNameField_' . $entry['courseclass'] . '" name="entryNameField_' . $entry['courseclass'] . '" class="option_width" style="float: left; width: 150px;">' . $entry['name'] . '</div>';
$html .= ' <div id="entryCodeField_' . $entry['group_id'] . '" name="entryCodeField_' . $entry['group_id'] . '" class="option_width" style="float: left; width: 100px;">' . $entry['groupname'] . '</div>';
$html .= ' <div class="right imageButton deleteButton deleteTeacherAssigned" style="height: 16px;" title="Eliminar" rel="' . $entry['id'] . '"></div>';
$html .= ' <div class="clear"></div>';
$html .= '</div>';
}
$dql = "SELECT g FROM TecnotekExpedienteBundle:Group g WHERE g.period = $periodId";
$query = $em->createQuery($dql);
$results = $query->getResult();
$courseClassId = 0;
$groupOptions .= '<option value="0"></option>';
foreach( $results as $result ){
$groupOptions .= '<option value="' . $result->getId() . '-' . $result->getGrade()->getId() . '">'. $result->getGrade() . '-'. $result->getName() . '</option>';
}
return new Response(json_encode(array('error' => false, 'groupOptions' => $groupOptions, 'entriesHtml' => $html)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::loadCoursesByTeacherAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function removeTeacherAssignedAction(){ /// 2016 - 4
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$teacherAssignedId = $request->get('teacherAssignedId');
$translator = $this->get("translator");
if( isset($teacherAssignedId) ) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository("TecnotekExpedienteBundle:AssignedTeacher")->find( $teacherAssignedId );
if ( isset($entity) ) {
$em->remove($entity);
$em->flush();
}
return new Response(json_encode(array('error' => false)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::removeTeacherAssignedAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function createTeacherAssignedAction(){ //2016 - 4 temp
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$teacherId = $request->get('teacherId');
$courseClassId = $request->get('courseClassId');
$groupId = $request->get('groupId');
$keywords = preg_split("/[\s-]+/", $groupId);
$groupId = $keywords[0];
$gradeId = $keywords[1];
$translator = $this->get("translator");
if( isset($courseClassId) && isset($groupId) && isset($teacherId)) {
$em = $this->getDoctrine()->getEntityManager();
$assignedTeacher = new AssignedTeacher();
$assignedTeacher->setCourseClass($em->getRepository("TecnotekExpedienteBundle:CourseClass")->find($courseClassId));
$assignedTeacher->setGroup($em->getRepository("TecnotekExpedienteBundle:Group")->find($groupId));
$assignedTeacher->setTeacher($em->getRepository("TecnotekExpedienteBundle:User")->find($teacherId));
$em->persist($assignedTeacher);
$em->flush();
return new Response(json_encode(array('error' => false)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::createTeacherAssignedAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
/**/
public function getPaginationPage($dql, $currentPage, $rowsPerPage){
if(isset($currentPage) == false || $currentPage <= 1){
return 1;
} else {
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery($dql);
$total = $query->getSingleScalarResult();
//Check if current page has Results
if( $total > (($currentPage - 1) * $rowsPerPage)){//the page has results
return $currentPage;
} else {
$x = intval($total / $rowsPerPage);
if($x == 0){
return 1;
} else {
if( $total % ($x * $rowsPerPage) > 0){
return $x+1;
} else {
return $x;
}
}
}
}
}
public function changeUserPasswordAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$newPassword = $request->get('newPassword');
$confirmPassword = $request->get('confirmPassword');
$userId = $request->get('userId');
$em = $this->getDoctrine()->getEntityManager();
$user = $em->getRepository("TecnotekExpedienteBundle:User")->find($userId);
$translator = $this->get("translator");
if ( isset($user) ) {
$defaultController = new DefaultController();
$error = $defaultController->validateUserPassword($newPassword, $confirmPassword, $translator);
if ( isset($error) ) {
return new Response(json_encode(array('error' => true, 'message' => $error)));
} else {
$user->setPassword($newPassword);
$em->persist($user);
$em->flush();
return new Response(json_encode(array('error' => false, 'message' =>$translator->trans("messages.confirmation.password.change"))));
}
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.entity.not.found"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::changeUserPasswordAction [' . $info . "]");
return new Response($info);
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function enterQualificationsAction(){
$logger = $this->get("logger");
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT p FROM TecnotekExpedienteBundle:Period p ORDER BY p.year";
$query = $em->createQuery($dql);
$periods = $query->getResult();
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Qualification/index.html.twig', array('periods' => $periods,
'menuIndex' => 5));
}
public function enterQualificationssssAction(){
$logger = $this->get("logger");
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT e FROM TecnotekExpedienteBundle:CourseEntry e WHERE e.parent IS NULL ORDER BY e.sortOrder";
$query = $em->createQuery($dql);
$logger->err("-----> SQL: " . $query->getSQL());
$entries = $query->getResult();
$logger->err("-----> ENTRIES: " . sizeof($entries));
$temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry();
$html = '<div class="itemPromedioPeriodo itemHeader" style="margin-left: 0px; color: #fff;">Promedio Trimestral</div>';
/*
<div class="itemHeader itemNota" style="margin-left: 125px;">Tarea 2</div>
<div class="itemHeader itemPromedio" style="margin-left:150px;">Promedio Tareas </div>
<div class="itemHeader itemPorcentage" style="margin-left: 175px;">10 % Tarea</div>
<div class="itemHeaderCode itemNota" style="margin-left: 0px;"></div>
*/
$marginLeft = 34;
$marginLeftCode = 62;
$htmlCodes = '<div class="itemPromedioPeriodo itemHeaderCode" style="color: #fff;">SCIE</div>';
$jumpRight = 34;
$width = 32;
$html3 = '<div class="itemHeader2 itemPromedioPeriodo" style="width: 32px; color: #fff;">TRIM</div>';
$studentRow = "";
$studentsHeader = '';
$colors = array(
"one" => "#38255c",
"two" => "#04D0E6"
);
foreach( $entries as $entry )
{
$temp = $entry;
$childrens = $temp->getChildrens();
$size = sizeof($childrens);
$logger->err("-----> Childrens of " . $temp->getName() . ": " . sizeof($childrens));
if($size == 0){//No child
$studentRow .= '<input type="text" class="textField itemNota" tipo="1" rel="total_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '" std="stdId" >';
$htmlCodes .= '<div class="itemHeaderCode itemNota"></div>';
$html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
$studentRow .= '<div id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</div>';
$htmlCodes .= '<div class="itemHeaderCode itemPorcentage">' . $temp->getCode() . '</div>';
$html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
$html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * 2) + 2) . 'px">' . $temp->getName() . '</div>';
} else {
if($size == 1){//one child
foreach ( $childrens as $child){
$htmlCodes .= '<div class="itemHeaderCode itemNota"></div>';
$html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $child->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
}
$htmlCodes .= '<div class="itemHeaderCode itemPorcentage"></div>';
$html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
} else {//two or more
foreach ( $childrens as $child){
//$studentRow .= '<input type="text" class="textField itemNota">';
$studentRow .= '<input type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '" std="stdId" >';
$htmlCodes .= '<div class="itemHeaderCode itemNota">' . $child->getCode() . '</div>';
$html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $child->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
}
$studentRow .= '<div class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</div>';
$htmlCodes .= '<div class="itemHeaderCode itemPromedio"></div>';
$html .= '<div class="itemHeader itemPromedio" style="margin-left:' . $marginLeft . 'px;">Promedio ' . $temp->getName() . ' </div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
//$studentRow .= '<div class="itemHeaderCode itemPorcentage">-</div>';
$studentRow .= '<div id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</div>';
$htmlCodes .= '<div class="itemHeaderCode itemPorcentage">' . $temp->getCode() . '</div>';
$html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
$html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * ($size + 2)) + (($size + 1) * 2)) . 'px">' . $temp->getName() . '</div>';
}
}
/*$assignedTeacher = new \Tecnotek\ExpedienteBundle\Entity\AssignedTeacher();
$assignedTeacher->setCourseClass($courseClass);
$assignedTeacher->setGroup($group);
$assignedTeacher->setTeacher($teacher);
$em->persist($assignedTeacher);*/
}
$html = $htmlCodes . '<div class="clear"></div>' .
'<div style="position: relative; height: 152px; margin-left: -59px;">' . $html . '</div>' . '<div class="clear"></div>' .
$html3;
$students = $em->getRepository("TecnotekExpedienteBundle:Student")->findAll();
foreach($students as $student){
$studentsHeader .= '<div class="itemCarne">' . $student->getCarne() . '</div><div class="itemEstudiante">' . $student . '</div><div class="clear"></div>';
$row = str_replace("stdId", $student->getId(), $studentRow);
$html .= '<div class="clear"></div><div id="total_trim_' . $student->getId() . '" class="itemHeaderCode itemPromedioPeriodo"style="color: #fff;">-</div>' . $row;
}
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Qualification/index.html.twig', array('table' => $html,
'studentsHeader' => $studentsHeader, 'menuIndex' => 5));
}
public function loadEntriesByCourseAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$gradeId = $request->get('gradeId');
$courseId = $request->get('courseId');
$translator = $this->get("translator");
if( isset($gradeId) && isset($periodId) && isset($courseId)) {
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT e FROM TecnotekExpedienteBundle:CourseEntry e, TecnotekExpedienteBundle:CourseClass cc WHERE e.parent IS NULL AND e.courseClass = cc AND cc.period = $periodId AND cc.grade = $gradeId And cc.course = $courseId ORDER BY e.sortOrder";
$query = $em->createQuery($dql);
$entries = $query->getResult();
$colors = array(
"one" => "#38255c",
"two" => "#04D0E6"
);
$html = "";
$entriesOptions = "";
$temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry();
$dql = "SELECT cc FROM TecnotekExpedienteBundle:CourseClass cc WHERE cc.period = $periodId AND cc.grade = $gradeId And cc.course = $courseId";
$query = $em->createQuery($dql);
$results = $query->getResult();
$courseClassId = 0;
foreach( $results as $result ){
$courseClassId = $result->getId();
}
foreach( $entries as $entry ){
$temp = $entry;
$courseClassId = $temp->getCourseClass()->getId();
$childrens = $temp->getChildrens();
$size = sizeof($childrens);
$entriesOptions .= '<option value="' . $entry->getId() . '">' . $entry->getName() . '</option>';
$html .= '<div id="entryRow_' . $entry->getId() . '" class="row userRow tableRowOdd">';
$html .= ' <div id="entryNameField_' . $entry->getId() . '" name="entryNameField_' . $entry->getId() . '" class="option_width" style="float: left; width: 150px;">' . $entry->getName() . '</div>';
$html .= ' <div id="entryCodeField_' . $entry->getId() . '" name="entryCodeField_' . $entry->getId() . '" class="option_width" style="float: left; width: 100px;">' . $entry->getCode() . '</div>';
$html .= ' <div id="entryPercentageField_' . $entry->getId() . '" name="entryPercentageField_' . $entry->getId() . '" class="option_width" style="float: left; width: 100px;">' . $entry->getPercentage() . '</div>';
$html .= ' <div id="entryMaxValueField_' . $entry->getId() . '" name="entryMaxValueField_' . $entry->getId() . '" class="option_width" style="float: left; width: 100px;">' . $entry->getMaxValue() . '</div>';
$html .= ' <div id="entryOrderField_' . $entry->getId() . '" name="entryOrderField_' . $entry->getId() . '" class="option_width" style="float: left; width: 100px;">' . $entry->getSortOrder() . '</div>';
$html .= ' <div id="entryParentField_' . $entry->getId() . '" name="entryParentField_' . $entry->getId() . '" class="option_width" style="float: left; width: 150px;">' . $entry->getParent() . '</div>';
$html .= ' <div class="right imageButton deleteButton deleteEntry" style="height: 16px;" title="Eliminar" rel="' . $entry->getId() . '"></div>';
$html .= ' <div class="right imageButton editButton editEntry" title="Editar" rel="' . $entry->getId() . '" entryParent="0"></div>';
$html .= ' <div class="clear"></div>';
$html .= '</div>';
foreach ( $childrens as $child){
$html .= '<div id="entryRow_' . $child->getId() . '" class="row userRow tableRowOdd">';
$html .= ' <div id="entryNameField_' . $child->getId() . '" name="entryNameField_' . $child->getId() . '" class="option_width" style="float: left; width: 150px;">' . $child->getName() . '</div>';
$html .= ' <div id="entryCodeField_' . $child->getId() . '" name="entryCodeField_' . $child->getId() . '" class="option_width" style="float: left; width: 100px;">' . $child->getCode() . '</div>';
$html .= ' <div id="entryPercentageField_' . $child->getId() . '" name="entryPercentageField_' . $child->getId() . '" class="option_width" style="float: left; width: 100px;">' . $child->getPercentage() . '</div>';
$html .= ' <div id="entryMaxValueField_' . $child->getId() . '" name="entryMaxValueField_' . $child->getId() . '" class="option_width" style="float: left; width: 100px;">' . $child->getMaxValue() . '</div>';
$html .= ' <div id="entryOrderField_' . $child->getId() . '" name="entryOrderField_' . $child->getId() . '" class="option_width" style="float: left; width: 100px;">' . $child->getSortOrder() . '</div>';
$html .= ' <div id="entryParentField_' . $child->getId() . '" name="entryParentField_' . $child->getId() . '" class="option_width" style="float: left; width: 150px;">' . $child->getParent() . '</div>';
$html .= ' <div class="right imageButton deleteButton deleteEntry" style="height: 16px;" title="Eliminar" rel="' . $child->getId() . '"></div>';
$html .= ' <div class="right imageButton editButton editEntry" title="Editar" rel="' . $child->getId() . '" entryParent="' . $entry->getId() . '"></div>';
$html .= ' <div class="clear"></div>';
$html .= '</div>';
}
/*if($size == 0){//No child
$studentRow .= '<input type="text" class="textField itemNota" tipo="1" rel="total_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '" std="stdId" >';
$htmlCodes .= '<div class="itemHeaderCode itemNota"></div>';
$html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
$studentRow .= '<div id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</div>';
$htmlCodes .= '<div class="itemHeaderCode itemPorcentage">' . $temp->getCode() . '</div>';
$html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
$html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * 2) + 2) . 'px">' . $temp->getName() . '</div>';
} else {
if($size == 1){//one child
foreach ( $childrens as $child){
$htmlCodes .= '<div class="itemHeaderCode itemNota"></div>';
$html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $child->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
}
$htmlCodes .= '<div class="itemHeaderCode itemPorcentage"></div>';
$html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
} else {//two or more
foreach ( $childrens as $child){
//$studentRow .= '<input type="text" class="textField itemNota">';
$studentRow .= '<input type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '" std="stdId" >';
$htmlCodes .= '<div class="itemHeaderCode itemNota">' . $child->getCode() . '</div>';
$html .= '<div class="itemHeader itemNota" style="margin-left: ' . $marginLeft . 'px;">' . $child->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
}
$studentRow .= '<div class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</div>';
$htmlCodes .= '<div class="itemHeaderCode itemPromedio"></div>';
$html .= '<div class="itemHeader itemPromedio" style="margin-left:' . $marginLeft . 'px;">Promedio ' . $temp->getName() . ' </div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
//$studentRow .= '<div class="itemHeaderCode itemPorcentage">-</div>';
$studentRow .= '<div id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</div>';
$htmlCodes .= '<div class="itemHeaderCode itemPorcentage">' . $temp->getCode() . '</div>';
$html .= '<div class="itemHeader itemPorcentage" style="margin-left: ' . $marginLeft . 'px;">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
$html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * ($size + 2)) + (($size + 1) * 2)) . 'px">' . $temp->getName() . '</div>';
}
}*/
}
return new Response(json_encode(array('error' => false, 'entries' => $entriesOptions, 'entriesHtml' => $html, 'courseClassId' => $courseClassId)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::loadEntriesByCourseAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function createEntryAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$parentId = $request->get('parentId');
$name = $request->get('name');
$code = $request->get('code');
$maxValue = $request->get('maxValue');
$percentage = $request->get('percentage');
$sortOrder = $request->get('sortOrder');
$courseClassId = $request->get('courseClassId');
$entryId = $request->get('entryId');
$translator = $this->get("translator");
if( isset($parentId) && isset($name) && isset($code) && isset($maxValue) && isset($percentage)
&& isset($sortOrder) && isset($courseClassId) && isset($entryId)) {
$em = $this->getDoctrine()->getEntityManager();
if($entryId == 0){//Is new
$courseEntry = new CourseEntry();
$courseEntry->setCourseClass($em->getRepository("TecnotekExpedienteBundle:CourseClass")->find($courseClassId));
} else {//Is editing
$courseEntry = $em->getRepository("TecnotekExpedienteBundle:CourseEntry")->find($entryId);
}
$courseEntry->setName($name);
$courseEntry->setCode($code);
$courseEntry->setMaxValue($maxValue);
$courseEntry->setPercentage($percentage);
$courseEntry->setSortOrder($sortOrder);
if($parentId == 0){
$courseEntry->removeParent();
}else {
$parent = $em->getRepository("TecnotekExpedienteBundle:CourseEntry")->find($parentId);
if(isset($parent)) $courseEntry->setParent($parent);
}
$em->persist($courseEntry);
$em->flush();
return new Response(json_encode(array('error' => false)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::createEntryAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
/******************************* Funciones para la administracion de las calificaciones *******************************/
public function loadLevelsOfPeriodAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$translator = $this->get("translator");
if( isset($periodId) ) {
$em = $this->getDoctrine()->getEntityManager();
//Get Groups
$sql = "SELECT grade.id as 'id', grade.name as 'name'
FROM tek_groups g, tek_grades grade
WHERE g.period_id = " . $periodId . " AND g.grade_id = grade.id
GROUP BY grade.id
ORDER BY grade.id, g.name;";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$levels = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'levels' => $levels)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadGroupsOfPeriodAndLevelAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$levelId = $request->get('levelId');
$translator = $this->get("translator");
if( isset($periodId) && isset($levelId) ) {
$em = $this->getDoctrine()->getEntityManager();
//Get Groups
$sql = "SELECT CONCAT(g.id,'-',grade.id) as 'id', CONCAT(grade.name, ' :: ', g.name) as 'name'" .
" FROM tek_groups g, tek_grades grade" .
" WHERE g.period_id = " . $periodId . " AND g.grade_id = grade.id";
if($levelId != 0){
$sql .= " AND grade.id = " . $levelId;
}
$sql .+
" GROUP BY g.id" .
" ORDER BY grade.id, g.name";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$groups = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'groups' => $groups)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadGroupsOfPeriodAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$translator = $this->get("translator");
if( isset($periodId) ) {
$em = $this->getDoctrine()->getEntityManager();
$user = $this->get('security.context')->getToken()->getUser();
//Get Groups
$sql = "SELECT CONCAT(g.id,'-',grade.id) as 'id', CONCAT(grade.name, ' :: ', g.name) as 'name'" .
" FROM tek_groups g, tek_grades grade" .
" WHERE g.period_id = " . $periodId . " AND g.institution_id in ("
. $user->getInstitutionsIdsStr() . ")"
. " AND g.grade_id = grade.id" .
" GROUP BY g.id" .
" ORDER BY grade.id, g.name";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$groups = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'groups' => $groups)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadCourseOfGroupByTeacherAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$keywords = preg_split("/[\s-]+/", $request->get('groupId'));
$groupId = $keywords[0];
$translator = $this->get("translator");
if( isset($groupId) ) {
$em = $this->getDoctrine()->getEntityManager();
//Get Courses
$sql = "SELECT course.id, course.name " .
" FROM tek_assigned_teachers tat, tek_course_class tcc, tek_courses course " .
" WHERE tat.group_id = " . $groupId . " AND tat.course_class_id = tcc.id AND tcc.course_id = course.id" .
" ORDER BY course.name ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$courses = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'courses' => $courses)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadPrintableGroupQualificationsAction(){
$logger = $this->get('logger');
$translator = $this->get("translator");
try {
$request = $this->get('request');
$periodId = $request->get('periodId');
$groupId = $request->get('groupId');
$courseId = $request->get('courseId');
if( !isset($courseId) || !isset($groupId) || !isset($periodId)) {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
$keywords = preg_split("/[\s-]+/", $groupId);
$groupId = $keywords[0];
$gradeId = $keywords[1];
if( isset($courseId) && isset($groupId) && isset($periodId)) {
$em = $this->getDoctrine()->getEntityManager();
$group = $em->getRepository("TecnotekExpedienteBundle:Group")->find( $groupId );
$grade = $group->getGrade();
$course = $em->getRepository("TecnotekExpedienteBundle:Course")->find( $courseId );
$title = "Calificaciones del grupo: " . $group->getGrade() . "-" . $group . " en la materia: " . $course. " en el Periodo: " . $periodId;
$dql = "SELECT ce FROM TecnotekExpedienteBundle:CourseEntry ce "
. " JOIN ce.courseClass cc"
. " WHERE ce.parent IS NULL AND cc.period = " . $periodId . " AND cc.grade = " . $gradeId
. " AND cc.course = " . $courseId
. " ORDER BY ce.sortOrder";
$query = $em->createQuery($dql);
$entries = $query->getResult();
$temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry();
$html = '<tr style="height: 75px; line-height: 0px;"><td class="celesteOscuro" style="min-width: 75px; font-size: 12px; height: 75px;">Carne</td>';
$html .= '<td class="celesteClaro bold" style="min-width: 300px; font-size: 12px; height: 75px;">Estudiante</td>';
$html .= '<td class="azul" style="vertical-align: bottom; padding: 1.5625em 0.625em; height: 75px;"><div class="verticalText" style="color: #000;">Promedio</div></td>';
$marginLeft = 48;
$marginLeftCode = 62;
$htmlCodes = '<tr style="height: 25px;"><td class="celesteOscuro" style="width: 75px; font-size: 10px;"></td>';
$htmlCodes .= '<td class="celesteClaro bold" style="width: 300px; font-size: 8px;"></td>';
$htmlCodes .= '<td class="azul" style="color: #000;"></td>';
$jumpRight = 46;
$width = 44;
$html3 = '<tr style="height: 25px; line-height: 0px;" class="noPrint"><td class="celesteOscuro bold headcolcarne" style="min-width: 75px; font-size: 12px;">Carne</td>';
$html3 .= '<td class="celesteClaro bold headcolnombre" style="min-width: 300px; font-size: 12px;">Estudiante</td>';
$html3 .= '<td class="azul headcoltrim" style="color: #000;">TRIM1111</td>';
$studentRow = '';
$studentsHeader = '';
$colors = array(
"one" => "#38255c",
"two" => "#04D0E6"
);
$dql = "SELECT stdy FROM TecnotekExpedienteBundle:Student std, TecnotekExpedienteBundle:StudentYear stdy "
. " WHERE stdy.student = std AND stdy.group = " . $groupId . " AND stdy.period = " . $periodId
. " ORDER BY std.lastname, std.firstname";
$query = $em->createQuery($dql);
$students = $query->getResult();
$studentsCount = sizeof($students);
$rowIndex = 1;
$colsCounter = 1;
$specialCounter = 1;
foreach( $entries as $entry )
{
$temp = $entry;
$childrens = $temp->getChildrens();
$size = sizeof($childrens);
if($size == 0){//No child
//Find SubEntries
$dql = "SELECT ce FROM TecnotekExpedienteBundle:SubCourseEntry ce "
. " WHERE ce.parent = " . $temp->getId() . " AND ce.group = " . $groupId
. " ORDER BY ce.sortOrder";
$query = $em->createQuery($dql);
$subentries = $query->getResult();
$size = sizeof($subentries);
if($size > 1){
foreach( $subentries as $subentry )
{
//$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>';
$studentRow .= '<td class="celesteClaro noPrint"><div><input disabled="disabled" tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></div></td>';
$colsCounter++;
$htmlCodes .= '<td class="celesteClaro noPrint"></td>';
$specialCounter++;
$html .= '<td class="celesteClaro noPrint"><div class="verticalText">' . $subentry->getCode() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
}
//$studentRow .= '<td class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>';
$studentRow .= '<td class="celesteOscuro noPrint" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>';
$htmlCodes .= '<td class="celesteOscuro noPrint"></td>';
$specialCounter++;
$html .= '<td class="celesteOscuro noPrint"><div class="verticalText">Promedio ' . $temp->getCode() . ' </div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
//$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>';
$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>';
$htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>';
$specialCounter++;
$html .= '<td class="morado" style="padding: 1.5625em 0.625em; vertical-align: bottom;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getCode() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
// $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * (sizeof($subentries)+1)) + ((sizeof($subentries)) * 2) ) . 'px">' . $temp->getCode() . '</div>';
$html3 .= '<td class="celesteClaro noPrint" colspan="' . (sizeof($subentries)+2) . '">' . $temp->getCode() . '</td>';
} else {
if($size == 1){
foreach( $subentries as $subentry )
{
//$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>';
$studentRow .= '<td class="celesteClaro noPrint"><div style="height: 15px;"><input disabled="disabled" tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></div></td>';
$colsCounter++;
$htmlCodes .= '<td class="celesteClaro noPrint"></td>';
$specialCounter++;
$html .= '<td class="celesteClaro noPrint"><div class="verticalText">' . $subentry->getCode() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
}
//$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>';
$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>';
$htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>';
$specialCounter++;
$html .= '<td class="morado" style="padding: 1.5625em 0.625em; vertical-align: bottom;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getCode() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
$html3 .= '<td class="celesteClaro noPrint" colspan="' . (sizeof($subentries)+1) . '">' . $temp->getName() . '</td>';
}
}
} else {
}
}
$htmlCodes .= "</tr>";
$html .= "</tr>";
$html3 .= "</tr>";
$html = '<table class="tableQualifications" style="border-spacing: 0px; border-collapse: collapse;">' . $htmlCodes . $html;
$studentRowIndex = 0;
foreach($students as $stdy){
$html .= '<tr style="height: 25px; line-height: 0px;">';
$studentRowIndex++;
$html .= '<td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;">' . $stdy->getStudent()->getCarne() . '</td>';
$html .= '<td class="celesteClaro bold headcolnombre" style="width: 300px; font-size: 12px;">' . $stdy->getStudent() . '</td>';
$row = str_replace("stdId", $stdy->getStudent()->getId(), $studentRow);
$row = str_replace("stdyIdd", $stdy->getId(), $row);
//tabIndexColXx
for ($i = 1; $i <= $colsCounter; $i++) {
$indexVar = "tabIndexCol" . $i . "x";
$row = str_replace($indexVar, "" . ($studentRowIndex + (($i - 1) * $studentsCount)), $row);
}
$dql = "SELECT qua FROM TecnotekExpedienteBundle:StudentQualification qua"
. " WHERE qua.studentYear = " . $stdy->getId();
$query = $em->createQuery($dql);
$qualifications = $query->getResult();
foreach($qualifications as $qualification){
$row = str_replace("val_" . $stdy->getStudent()->getId() . "_" .
$qualification->getSubCourseEntry()->getId() . "_", $qualification->getQualification(), $row);
}
$html .= '<td id="total_trim_' . $stdy->getStudent()->getId() . '" class="azul headcoltrim" style="color: #000;">-</td>' . $row . "</tr>";
}
$html .= "</table>";
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Qualification/courseGroupQualification.html.twig',
array('table' => $html, 'studentsCounter' => $studentsCount,
"codesCounter" => $specialCounter, 'menuIndex' => 5, 'title' => $title,
"notaMin" => $grade->getNotaMin()));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('Teacher::loadEntriesByCourseAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}
public function loadGroupQualificationsAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$periodId = $request->get('periodId');
$groupId = $request->get('groupId');
$keywords = preg_split("/[\s-]+/", $groupId);
$groupId = $keywords[0];
$gradeId = $keywords[1];
$courseId = $request->get('courseId');
$translator = $this->get("translator");
if( isset($courseId) && isset($groupId) && isset($periodId)) {
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT ce FROM TecnotekExpedienteBundle:CourseEntry ce "
. " JOIN ce.courseClass cc"
. " WHERE ce.parent IS NULL AND cc.period = " . $periodId . " AND cc.grade = " . $gradeId
. " AND cc.course = " . $courseId
. " ORDER BY ce.sortOrder";
$query = $em->createQuery($dql);
$entries = $query->getResult();
$temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry();
$html = '<tr style="height: 175px; line-height: 0px;"><td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px; height: 175px;"></td>';
$html .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px; height: 175px;"></td>';
$html .= '<td class="azul headcoltrim" style="vertical-align: bottom; padding: 0.5625em 0.625em; height: 175px; line-height: 220px;"><div class="verticalText" style="color: #fff;">Promedio Trimestral</div></td>';
$marginLeft = 48;
$marginLeftCode = 62;
$htmlCodes = '<tr style="height: 30px;"><td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;"></td>';
$htmlCodes .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px;"></td>';
$htmlCodes .= '<td class="azul headcoltrim" style="color: #fff;">SCIE</td>';
$jumpRight = 46;
$width = 44;
$html3 = '<tr style="height: 30px; line-height: 0px;" class="noPrint"><td class="celesteOscuro bold headcolcarne" style="width: 75px; font-size: 12px;">Carne</td>';
$html3 .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 12px;">Estudiante</td>';
$html3 .= '<td class="azul headcoltrim" style="color: #fff;">TRIM</td>';
$studentRow = '';
$studentsHeader = '';
$colors = array(
"one" => "#38255c",
"two" => "#04D0E6"
);
$dql = "SELECT stdy FROM TecnotekExpedienteBundle:Student std, TecnotekExpedienteBundle:StudentYear stdy "
. " WHERE stdy.student = std AND stdy.group = " . $groupId . " AND stdy.period = " . $periodId
. " ORDER BY std.lastname, std.firstname";
$query = $em->createQuery($dql);
$students = $query->getResult();
$studentsCount = sizeof($students);
$rowIndex = 1;
$colsCounter = 1;
$specialCounter = 1;
foreach( $entries as $entry )
{
$temp = $entry;
$childrens = $temp->getChildrens();
$size = sizeof($childrens);
if($size == 0){//No child
//Find SubEntries
$dql = "SELECT ce FROM TecnotekExpedienteBundle:SubCourseEntry ce "
. " WHERE ce.parent = " . $temp->getId() . " AND ce.group = " . $groupId
. " ORDER BY ce.sortOrder";
$query = $em->createQuery($dql);
$subentries = $query->getResult();
$size = sizeof($subentries);
if($size > 1){
foreach( $subentries as $subentry )
{
//$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>';
$studentRow .= '<td class="celesteClaro"><div><input style="background-color: #A4D2FD;" disabled="disabled" tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></input></div></td>';
$colsCounter++;
$htmlCodes .= '<td class="celesteClaro"></td>';
$specialCounter++;
$html .= '<td class="celesteClaro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $subentry->getName() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
}
//$studentRow .= '<td class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>';
$studentRow .= '<td class="celesteOscuro" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>';
$htmlCodes .= '<td class="celesteOscuro"></td>';
$specialCounter++;
$html .= '<td class="celesteOscuro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">Promedio ' . $temp->getName() . ' </div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
//$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>';
$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>';
$htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>';
$specialCounter++;
$html .= '<td class="morado" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
// $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * (sizeof($subentries)+1)) + ((sizeof($subentries)) * 2) ) . 'px">' . $temp->getName() . '</div>';
$html3 .= '<td class="celesteClaro" colspan="' . (sizeof($subentries)+2) . '">' . $temp->getName() . '</td>';
} else {
if($size == 1){
foreach( $subentries as $subentry )
{
//$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>';
$studentRow .= '<td class="celesteClaro"><div><input style="background-color: #A4D2FD;" disabled="disabled" tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></input></div></td>';
$colsCounter++;
$htmlCodes .= '<td class="celesteClaro"></td>';
$specialCounter++;
$html .= '<td class="celesteClaro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $subentry->getName() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
}
//$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>';
$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>';
$htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>';
$specialCounter++;
$html .= '<td class="morado" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
$html3 .= '<td class="celesteClaro" colspan="' . (sizeof($subentries)+1) . '">' . $temp->getName() . '</td>';
}
}
} else {
}
}
$htmlCodes .= "</tr>";
$html .= "</tr>";
$html3 .= "</tr>";
$html = '<table class="tableQualifications">' . $htmlCodes . $html . $html3;
$studentRowIndex = 0;
foreach($students as $stdy){
$html .= '<tr style="height: 30px; line-height: 0px;">';
$studentRowIndex++;
$html .= '<td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;">' . $stdy->getStudent()->getCarne() . '</td>';
$html .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 12px;">' . $stdy->getStudent() . '</td>';
$row = str_replace("stdId", $stdy->getStudent()->getId(), $studentRow);
$row = str_replace("stdyIdd", $stdy->getId(), $row);
//tabIndexColXx
for ($i = 1; $i <= $colsCounter; $i++) {
$indexVar = "tabIndexCol" . $i . "x";
$row = str_replace($indexVar, "" . ($studentRowIndex + (($i - 1) * $studentsCount)), $row);
}
$dql = "SELECT qua FROM TecnotekExpedienteBundle:StudentQualification qua"
. " WHERE qua.studentYear = " . $stdy->getId();
$query = $em->createQuery($dql);
$qualifications = $query->getResult();
foreach($qualifications as $qualification){
$row = str_replace("val_" . $stdy->getStudent()->getId() . "_" . $qualification->getSubCourseEntry()->getId() . "_", "" . $qualification->getQualification(), $row);
}
$html .= '<td id="total_trim_' . $stdy->getStudent()->getId() . '" class="azul headcoltrim" style="color: #fff;">-</td>' . $row . "</tr>";
}
$html .= "</table>";
return new Response(json_encode(array('error' => false, 'html' => $html, "studentsCounter" => $studentsCount, "codesCounter" => $specialCounter)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('Teacher::loadEntriesByCourseAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function saveStudentQualificationAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$subentryId = $request->get('subentryId');
$studentYearId = $request->get('studentYearId');
$qualification = $request->get('qualification');
$translator = $this->get("translator");
$logger->err('--> ' . $subentryId . " :: " . $studentYearId . " :: " . $qualification);
if( !isset($qualification) || $qualification == ""){
$qualification = -1;
}
if( isset($subentryId) || isset($studentYearId) ) {
$em = $this->getDoctrine()->getEntityManager();
$studentQ = $em->getRepository("TecnotekExpedienteBundle:StudentQualification")->findOneBy(array('subCourseEntry' => $subentryId, 'studentYear' => $studentYearId));
if ( isset($studentQ) ) {
$studentQ->setQualification($qualification);
} else {
$studentQ = new StudentQualification();
$studentQ->setSubCourseEntry($em->getRepository("TecnotekExpedienteBundle:SubCourseEntry")->find( $subentryId ));
$studentQ->setStudentYear($em->getRepository("TecnotekExpedienteBundle:StudentYear")->find( $studentYearId ));
$studentQ->setQualification($qualification);
}
$em->persist($studentQ);
$em->flush();
return new Response(json_encode(array('error' => false)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('SuperAdmin::saveStudentQualificationAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function generateExcelAction(){
$excelService = $this->get('export.excel')->setNameOfSheet("Notas");
//$this->get('export.excel')->createSheet();
$filepath = "export/excel/groupNotes";
$request = $this->get('request')->request;
//$periodId = $request->get('periodId');
$periodId = 1;
//$groupId = $request->get('groupId');
$groupId = "1-1";
$keywords = preg_split("/[\s-]+/", $groupId);
$groupId = $keywords[0];
$gradeId = $keywords[1];
//$courseId = $request->get('courseId');
$courseId = "42";
$translator = $this->get("translator");
if( isset($courseId) && isset($groupId) && isset($periodId)) {
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT ce FROM TecnotekExpedienteBundle:CourseEntry ce "
. " JOIN ce.courseClass cc"
. " WHERE ce.parent IS NULL AND cc.period = " . $periodId . " AND cc.grade = " . $gradeId
. " AND cc.course = " . $courseId
. " ORDER BY ce.sortOrder";
$query = $em->createQuery($dql);
$entries = $query->getResult();
$temp = new \Tecnotek\ExpedienteBundle\Entity\CourseEntry();
//$html = '<tr style="height: 175px; line-height: 0px;"><td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px; height: 175px;"></td>';
//$html .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px; height: 175px;"></td>';
$excelService->writeCellByPositionWithOptions(2,2,"Promedio Trimestral",
array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => '2b34ee', 'color' => 'ffffff', 'bold' => true));
//$html .= '<td class="azul headcoltrim" style="vertical-align: bottom; padding: 0.5625em 0.625em; height: 175px; line-height: 220px;"><div class="verticalText" style="color: #fff;">Promedio Trimestral</div></td>';
$marginLeft = 48;
$marginLeftCode = 62;
//$htmlCodes = '<tr style="height: 30px;"><td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;"></td>';
//$htmlCodes .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px;"></td>';
//$htmlCodes .= '<td class="azul headcoltrim" style="color: #fff;">SCIE</td>';
$excelService->writeCellByPositionWithOptions(1,2,"SCIE",
array('height' => 15, 'width' => 5, 'backgroundColor' => '2b34ee', 'color' => 'ffffff', 'bold' => true));
$jumpRight = 46;
$width = 44;
$excelService->writeCellByPositionWithOptions(1,0,"",
array('height' => 15, 'width' => 5, 'backgroundColor' => '82c0fd', 'bold' => true));
$excelService->writeCellByPositionWithOptions(1,1,"",
array('height' => 15, 'width' => 5, 'backgroundColor' => 'A4D2FD', 'bold' => true));
$excelService->writeCellByPositionWithOptions(2,0,"",
array('height' => 195, 'width' => 5, 'backgroundColor' => '82c0fd', 'bold' => true));
$excelService->writeCellByPositionWithOptions(2,1,"",
array('height' => 195, 'width' => 5, 'backgroundColor' => 'A4D2FD', 'bold' => true));
$excelService->writeCellByPositionWithOptions(3,0,"Carne",
array('height' => 15, 'width' => 5, 'backgroundColor' => '82c0fd', 'bold' => true));
$excelService->writeCellByPositionWithOptions(3,1,"Estudiante",
array('height' => 15, 'width' => 5, 'backgroundColor' => 'A4D2FD', 'bold' => true));
$excelService->writeCellByPositionWithOptions(3,2,"TRIM",
array('height' => 15, 'width' => 5, 'backgroundColor' => '2b34ee', 'color' => 'ffffff', 'bold' => true));
//$html3 = '<tr style="height: 30px; line-height: 0px;" class="noPrint"><td class="celesteOscuro bold headcolcarne" style="width: 75px; font-size: 12px;">Carne</td>';
//$html3 .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 12px;">Estudiante</td>';
//$html3 .= '<td class="azul headcoltrim" style="color: #fff;">TRIM</td>';
$studentRow = '';
$studentsHeader = '';
$colors = array(
"one" => "#38255c",
"two" => "#04D0E6"
);
$dql = "SELECT stdy FROM TecnotekExpedienteBundle:Student std, TecnotekExpedienteBundle:StudentYear stdy "
. " WHERE stdy.student = std AND stdy.group = " . $groupId . " AND stdy.period = " . $periodId
. " ORDER BY std.lastname, std.firstname";
$query = $em->createQuery($dql);
$students = $query->getResult();
$studentsCount = sizeof($students);
$rowIndex = 1;
$colsCounter = 1;
$specialCounter = 1;
$colsIndex = 3;
foreach( $entries as $entry )
{
$temp = $entry;
$childrens = $temp->getChildrens();
$size = sizeof($childrens);
if($size == 0){//No child
//Find SubEntries
$dql = "SELECT ce FROM TecnotekExpedienteBundle:SubCourseEntry ce "
. " WHERE ce.parent = " . $temp->getId() . " AND ce.group = " . $groupId
. " ORDER BY ce.sortOrder";
$query = $em->createQuery($dql);
$subentries = $query->getResult();
$size = sizeof($subentries);
if($size > 1){
foreach( $subentries as $subentry )
{
$excelService->writeCellByPositionWithOptions(1,$colsIndex,"",
array('height' => 15, 'width' => 5, 'backgroundColor' => 'A4D2FD'));
$excelService->writeCellByPositionWithOptions(2,$colsIndex,$subentry->getName(),
array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => 'A4D2FD'));
$colsIndex += 1;
//$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>';
/*$studentRow .= '<td class="celesteClaro"><div><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="2" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" max="' . $subentry->getMaxValue() . '" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></div></td>';
$colsCounter++;
$htmlCodes .= '<td class="celesteClaro"></td>';
$specialCounter++;
$html .= '<td class="celesteClaro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $subentry->getName() . '</div></td>';*/
$marginLeft += $jumpRight; $marginLeftCode += 25;
}
$excelService->writeCellByPositionWithOptions(1,$colsIndex,"",
array('height' => 15, 'width' => 5, 'backgroundColor' => '5F96E7'));
$excelService->writeCellByPositionWithOptions(2,$colsIndex,'Promedio ' . $temp->getName(),
array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => '5F96E7'));
$colsIndex += 1;
//$studentRow .= '<td class="itemHeaderCode itemPromedio" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>';
/*$studentRow .= '<td class="celesteOscuro" id="prom_' . $temp->getId() . '_stdId" perc="' . $temp->getPercentage() . '">-</td>';
$htmlCodes .= '<td class="celesteOscuro"></td>';
$specialCounter++;
$html .= '<td class="celesteOscuro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">Promedio ' . $temp->getName() . ' </div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;*/
//$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>';
/*$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>';
$htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>';
$specialCounter++;
$html .= '<td class="morado" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
// $html3 .= '<div class="itemHeader2 itemNota" style="width: ' . (($width * (sizeof($subentries)+1)) + ((sizeof($subentries)) * 2) ) . 'px">' . $temp->getName() . '</div>';
$html3 .= '<td class="celesteClaro" colspan="' . (sizeof($subentries)+2) . '">' . $temp->getName() . '</td>';*/
$excelService->writeCellByPositionWithOptions(1,$colsIndex,$temp->getCode(),
array('height' => 15, 'width' => 5, 'backgroundColor' => 'B698EE'));
$excelService->writeCellByPositionWithOptions(2,$colsIndex,$temp->getPercentage() . '% ' . $temp->getName(),
array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => 'B698EE'));
$colsIndex += 1;
} else {
if($size == 1){
foreach( $subentries as $subentry )
{
//$studentRow .= '<td class=""><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></td>';
/*$studentRow .= '<td class="celesteClaro"><div><input tabIndex=tabIndexCol'. $colsCounter . 'x type="text" class="textField itemNota item_' . $temp->getId() . '_stdId" val="val_stdId_' . $subentry->getId() . '_" tipo="1" max="' . $subentry->getMaxValue() . '" child="' . $size . '" parent="' . $temp->getId() . '" rel="total_' . $temp->getId() . '_stdId" perc="' . $subentry->getPercentage() . '" std="stdId" entry="' . $subentry->getId() . '" stdyId="stdyIdd"></div></td>';
$colsCounter++;
$htmlCodes .= '<td class="celesteClaro"></td>';
$specialCounter++;
$html .= '<td class="celesteClaro" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $subentry->getName() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;*/
$excelService->writeCellByPositionWithOptions(1,$colsIndex,"",
array('height' => 15, 'width' => 5, 'backgroundColor' => 'A4D2FD'));
$excelService->writeCellByPositionWithOptions(2,$colsIndex,$temp->getPercentage() . '% ' . $temp->getName(),
array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => 'A4D2FD'));
$colsIndex += 1;
}
//$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="itemHeaderCode itemPorcentage nota_stdId">-</td>';
/*$studentRow .= '<td id="total_' . $temp->getId() . '_stdId" class="morado bold nota_stdId">-</td>';
$htmlCodes .= '<td class="morado bold">' . $temp->getCode() . '</td>';
$specialCounter++;
$html .= '<td class="morado" style="vertical-align: bottom; padding: 0.5625em 0.625em;"><div class="verticalText">' . $temp->getPercentage() . '% ' . $temp->getName() . '</div></td>';
$marginLeft += $jumpRight; $marginLeftCode += 25;
$html3 .= '<td class="celesteClaro" colspan="' . (sizeof($subentries)+1) . '">' . $temp->getName() . '</td>';*/
$excelService->writeCellByPositionWithOptions(1,$colsIndex,$temp->getCode(),
array('height' => 15, 'width' => 5, 'backgroundColor' => 'B698EE'));
$excelService->writeCellByPositionWithOptions(2,$colsIndex,$temp->getPercentage() . '% ' . $temp->getName(),
array('rotation' => 90, 'height' => 195, 'width' => 5, 'backgroundColor' => 'B698EE'));
$colsIndex += 1;
}
}
} else {
}
}
/* $htmlCodes .= "</tr>";
$html .= "</tr>";
$html3 .= "</tr>";
$html = '<table class="tableQualifications">' . $htmlCodes . $html . $html3;*/
$studentRowIndex = 4;
foreach($students as $stdy){
//$html .= '<tr style="height: 30px; line-height: 0px;">';
$excelService->writeCellByPositionWithOptions($studentRowIndex,0,$stdy->getStudent()->getCarne(),
array('height' => 15, 'width' => 10, 'backgroundColor' => '82c0fd'));
$excelService->writeCellByPositionWithOptions($studentRowIndex,1,$stdy->getStudent(),
array('height' => 15, 'width' => 40, 'backgroundColor' => 'A4D2FD'));
$studentRowIndex++;
/*$html .= '<td class="celesteOscuro headcolcarne" style="width: 75px; font-size: 10px;">' . $stdy->getStudent()->getCarne() . '</td>';
$html .= '<td class="celesteClaro bold headcolnombre" style="width: 250px; font-size: 8px;">' . $stdy->getStudent() . '</td>';
$row = str_replace("stdId", $stdy->getStudent()->getId(), $studentRow);
$row = str_replace("stdyIdd", $stdy->getId(), $row);
//tabIndexColXx
for ($i = 1; $i <= $colsCounter; $i++) {
$indexVar = "tabIndexCol" . $i . "x";
$row = str_replace($indexVar, "" . ($studentRowIndex + (($i - 1) * $studentsCount)), $row);
}
$dql = "SELECT qua FROM TecnotekExpedienteBundle:StudentQualification qua"
. " WHERE qua.studentYear = " . $stdy->getId();
$query = $em->createQuery($dql);
$qualifications = $query->getResult();
foreach($qualifications as $qualification){
$row = str_replace("val_" . $stdy->getStudent()->getId() . "_" . $qualification->getSubCourseEntry()->getId() . "_", "" . $qualification->getQualification(), $row);
}
$html .= '<td id="total_trim_' . $stdy->getStudent()->getId() . '" class="azul headcoltrim" style="color: #fff;">-</td>' . $row . "</tr>";*/
}
$excelService->applyBorderByRange(0, 1, $colsIndex - 1, $studentRowIndex - 1);
//$html .= "</table>";
}
/*$excelService->writeCellByPosition(1,1,"probando 1");
$excelService->writeCellByPosition(1,2,"probando 2");
$excelService->writeCellByPosition(2,1,"probando 3");*/
//$excelService->writeCellByPosition(row,col,"");
$excelService->writeExport($filepath);
/*$response = new Response();
$response->setContent("<html><body>OK!!!</body></html>");
$response->setStatusCode(200);
/*$response->headers->add('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->add('Content-Disposition', 'attachment;filename=stdream2.xls');*/
//return $response;
return new Response(json_encode(array('error' => false)));
//create the response
/*$response = $excelService->getResponse();
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment;filename=stdream2.xls');
// If you are using a https connection, you have to set those two headers for compatibility with IE <9
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
return $response;*/
}
public function loadGroupsOfYearAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$year = $request->get('year');
$loadOnlyBachelors = $request->get('loadOnlyBachelors');
if ( !isset($loadOnlyBachelors) ) {
$loadOnlyBachelors = false;
} else {
$loadOnlyBachelors = ($loadOnlyBachelors == "true");
}
$translator = $this->get("translator");
if( isset($year) ) {
$em = $this->getDoctrine()->getEntityManager();
$user = $this->get('security.context')->getToken()->getUser();
//Get Groups
$sqlOnlyBachelors = $loadOnlyBachelors? " AND grade.number = 11 ":"";
$sql = "SELECT CONCAT(g.id,'-',grade.id) as 'id', CONCAT(grade.name, ' :: ', g.name) as 'name'" .
" FROM tek_groups g, tek_periods p, tek_grades grade" .
" WHERE p.orderInYear = 3 AND g.period_id = p.id AND p.year = " . $year . " AND g.grade_id = grade.id" .
"" . $sqlOnlyBachelors . " AND g.institution_id in (" . $user->getInstitutionsIdsStr() . ")" .
" GROUP BY CONCAT(grade.name, ' :: ', g.name)" .
" ORDER BY g.id";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$groups = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'groups' => $groups)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('Admin::loadGroupsOfYearAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function loadCoursesOfGroupAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$keywords = preg_split("/[\s-]+/", $request->get('groupId'));
$groupId = $keywords[0];
$translator = $this->get("translator");
if( isset($groupId) ) {
$em = $this->getDoctrine()->getEntityManager();
//Get Courses
$sql = "SELECT course.id, course.name " .
" FROM tek_assigned_teachers tat, tek_course_class tcc, tek_courses course " .
" WHERE tat.group_id = " . $groupId . " AND tat.course_class_id = tcc.id AND tcc.course_id = course.id" .
" GROUP BY course.id" .
" ORDER BY course.name ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$courses = $stmt->fetchAll();
return new Response(json_encode(array('error' => false, 'courses' => $courses)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
public function questionnairesAction(){
$em = $this->getDoctrine()->getEntityManager();
$dql = "SELECT q FROM TecnotekExpedienteBundle:Questionnaire q";
$query = $em->createQuery($dql);
$questionnaires = $query->getResult();
$groups = $em->getRepository('TecnotekExpedienteBundle:QuestionnaireGroup')->findAll();
$institutions = $em->getRepository('TecnotekExpedienteBundle:Institution')->findAll();
return $this->render('TecnotekExpedienteBundle:SuperAdmin:Questionnaires/list.html.twig', array(
'questionnaires' => $questionnaires, 'groups' => $groups, 'institutions' => $institutions
));
}
public function saveQuestionnaireConfigAction(){
$logger = $this->get('logger');
if ($this->get('request')->isXmlHttpRequest())// Is the request an ajax one?
{
try {
$request = $this->get('request')->request;
$questionnaireId = $request->get('q');
$field = $request->get('field');
$val = $request->get('val');
$translator = $this->get("translator");
if( isset($questionnaireId) && isset($field) && isset($val) ) {
$em = $this->getDoctrine()->getEntityManager();
$q = new \Tecnotek\ExpedienteBundle\Entity\Questionnaire();
$q = $em->getRepository('TecnotekExpedienteBundle:Questionnaire')->find($questionnaireId);
switch($field){
case 'group':
$qGroup = $em->getRepository('TecnotekExpedienteBundle:QuestionnaireGroup')->find($val);
$q->setGroup($qGroup);
break;
case 'teacher':
$q->setEnabledForTeacher($val == 1);
break;
case 'institution':
$values = preg_split("/[\s-]+/", $val);
$institution =
$em->getRepository('TecnotekExpedienteBundle:Institution')->find($values[0]);
if($values[1] == 0){
$q->getInstitutions()->removeElement($institution);
} else {
$q->getInstitutions()->add($institution);
}
break;
default:
break;
}
$em->persist($q);
$em->flush();
return new Response(json_encode(array('error' => false)));
} else {
return new Response(json_encode(array('error' => true, 'message' =>$translator->trans("error.paramateres.missing"))));
}
}
catch (Exception $e) {
$info = toString($e);
$logger->err('Admin::loadGroupsOfPeriodAction [' . $info . "]");
return new Response(json_encode(array('error' => true, 'message' => $info)));
}
}// endif this is an ajax request
else
{
return new Response("<b>Not an ajax call!!!" . "</b>");
}
}
}
| selimcr/Tecnotek_Expediente | src/Tecnotek/ExpedienteBundle/Controller/SuperAdminController.php | PHP | mit | 153,919 |
/**
* create edit language file link
*/
export default (lang) => {
return `https://github.com/electerm/electerm-locales/edit/master/locales/${lang}.js`
}
| electerm/electerm | src/client/common/create-lang-edit-link.js | JavaScript | mit | 159 |
2014.11.12
## 目标
* 微博详情加载更多
* 个人主页加载更多
* 微博详情模块,在单击时,应该是整个 body 区都能触发事件,而不只是内容区。但是,点击图片时,要显示
大图,而不是进入微博详情。
* bug: 上拉时文字显示应该为“上拉”
* 保存用户编辑过但没发出的微博
## 完成
* 微博详情加载更多
* 个人主页加载更多
* bugfix: 请求列表为空时,addAll 出 null 异常,需要判空
## Q&A
Q: ListView 的 setOnItemClickListener 失效
A: 如果 ListView 的 item 中包含有 button 等控件,它们会获得焦点,item 就无法获得了,因而无法响应点击
事件。
| minixalpha/Webo | doc/day28.md | Markdown | mit | 696 |
using System.Security.Cryptography.X509Certificates;
using Xunit;
namespace OpenGost.Security.Cryptography.X509Certificates
{
public class GostECDsaCertificateExtensionsTests : CryptoConfigRequiredTest
{
[Theory]
[InlineData("GostECDsa256")]
[InlineData("GostECDsa512")]
public void GetPublicKeyFromX509Certificate2(string certificateName)
{
var certificate = new X509Certificate2(
ResourceUtils.GetBinaryResource(
$"OpenGost.Security.Cryptography.Tests.Resources.{certificateName}.cer"));
using (var publicKey = certificate.GetECDsaPublicKey())
{
Assert.NotNull(publicKey);
}
}
}
}
| sergezhigunov/gost | tests/OpenGost.Security.Cryptography.Tests/X509Certificates/GostECDsaCertificateExtensionsTests.cs | C# | mit | 748 |
using System;
//using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using NUnit.Framework;
using BrowserStack;
using System.Text;
using System.IO;
namespace BrowserStack_Unit_Tests
{
[TestClass]
public class BrowserStackTunnelTests
{
private TunnelClass tunnel;
[TestMethod]
public void TestInitialState()
{
tunnel = new TunnelClass();
Assert.AreEqual(tunnel.localState, LocalState.Idle);
Assert.NotNull(tunnel.getOutputBuilder());
}
[TestMethod]
public void TestBinaryPathIsSet()
{
tunnel = new TunnelClass();
tunnel.addBinaryPath("dummyPath");
Assert.AreEqual(tunnel.getBinaryAbsolute(), "dummyPath");
}
[TestMethod]
public void TestBinaryPathOnNull()
{
tunnel = new TunnelClass();
tunnel.addBinaryPath(null);
string expectedPath = Path.Combine(Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%"), ".browserstack");
expectedPath = Path.Combine(expectedPath, "BrowserStackLocal.exe");
Assert.AreEqual(tunnel.getBinaryAbsolute(), expectedPath);
}
[TestMethod]
public void TestBinaryPathOnEmpty()
{
tunnel = new TunnelClass();
tunnel.addBinaryPath("");
string expectedPath = Path.Combine(Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%"), ".browserstack");
expectedPath = Path.Combine(expectedPath, "BrowserStackLocal.exe");
Assert.AreEqual(tunnel.getBinaryAbsolute(), expectedPath);
}
[TestMethod]
public void TestBinaryPathOnFallback()
{
string expectedPath = "dummyPath";
tunnel = new TunnelClass();
tunnel.addBinaryPath("dummyPath");
Assert.AreEqual(tunnel.getBinaryAbsolute(), expectedPath);
tunnel.fallbackPaths();
expectedPath = Path.Combine(Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%"), ".browserstack");
expectedPath = Path.Combine(expectedPath, "BrowserStackLocal.exe");
Assert.AreEqual(tunnel.getBinaryAbsolute(), expectedPath);
tunnel.fallbackPaths();
expectedPath = Directory.GetCurrentDirectory();
expectedPath = Path.Combine(expectedPath, "BrowserStackLocal.exe");
Assert.AreEqual(tunnel.getBinaryAbsolute(), expectedPath);
tunnel.fallbackPaths();
expectedPath = Path.GetTempPath();
expectedPath = Path.Combine(expectedPath, "BrowserStackLocal.exe");
Assert.AreEqual(tunnel.getBinaryAbsolute(), expectedPath);
}
[TestMethod]
public void TestBinaryPathOnNoMoreFallback()
{
tunnel = new TunnelClass();
tunnel.addBinaryPath("dummyPath");
tunnel.fallbackPaths();
tunnel.fallbackPaths();
tunnel.fallbackPaths();
Assert.Throws(typeof(Exception),
new TestDelegate(testFallbackException),
"Binary not found or failed to launch. Make sure that BrowserStackLocal.exe is not already running."
);
}
[TestMethod]
public void TestBinaryArguments()
{
tunnel = new TunnelClass();
tunnel.addBinaryArguments("dummyArguments");
Assert.AreEqual(tunnel.getBinaryArguments(), "dummyArguments");
}
[TestMethod]
public void TestBinaryArgumentsAreEmptyOnNull()
{
tunnel = new TunnelClass();
tunnel.addBinaryArguments(null);
Assert.AreEqual(tunnel.getBinaryArguments(), "");
}
public void testFallbackException()
{
tunnel.fallbackPaths();
}
public class TunnelClass : BrowserStackTunnel
{
public StringBuilder getOutputBuilder()
{
return output;
}
public string getBinaryAbsolute()
{
return binaryAbsolute;
}
public string getBinaryArguments()
{
return binaryArguments;
}
}
}
}
| browserstack/browserstack-local-csharp | BrowserStackLocal/BrowserStackLocal Unit Tests/BrowserStackTunnelTests.cs | C# | mit | 3,863 |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using Yaapii.Atoms.Fail;
using Yaapii.Atoms.Scalar;
namespace Yaapii.Atoms.Enumerable
{
/// <summary>
/// The greatest item in the given <see cref="IEnumerable{T}"/>
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class Max<T> : ScalarEnvelope<T>
where T : IComparable<T>
{
/// <summary>
/// The greatest item in the given <see cref="IEnumerable{T}"/>
/// </summary>
/// <param name="items">list of items</param>
public Max(params Func<T>[] items) : this(
new Enumerable.Mapped<Func<T>, IScalar<T>>(
item => new Live<T>(() => item.Invoke()),
new ManyOf<Func<T>>(items)
)
)
{ }
/// <summary>
/// The greatest item in the given <see cref="IEnumerable{T}"/>
/// </summary>
/// <param name="items">list of items</param>
public Max(IEnumerable<T> items) : this(
new Enumerable.Mapped<T, IScalar<T>>(item => new Live<T>(item), items))
{ }
/// <summary>
/// The greatest item in the given items.
/// </summary>
/// <param name="items">list of items</param>
public Max(params T[] items) : this(
new Enumerable.Mapped<T, IScalar<T>>(item => new Live<T>(item), items))
{ }
/// <summary>
/// The greatest item in the given <see cref="IEnumerable{T}"/>
/// </summary>
/// <param name="items">list of items</param>
public Max(params IScalar<T>[] items) : this(new ManyOf<IScalar<T>>(items))
{ }
/// <summary>
/// The greatest item in the given <see cref="IEnumerable{T}"/>
/// </summary>
/// <param name="items">list of items</param>
public Max(IEnumerable<IScalar<T>> items)
: base(() =>
{
var e = items.GetEnumerator();
if (!e.MoveNext())
{
throw new NoSuchElementException("Can't find greater element in an empty iterable");
}
T max = e.Current.Value();
while (e.MoveNext())
{
T next = e.Current.Value();
if (next.CompareTo(max) > 0)
{
max = next;
}
}
return max;
})
{ }
}
public static class Max
{
/// <summary>
/// The greatest item in the given <see cref="IEnumerable{T}"/>
/// </summary>
/// <param name="items">list of items</param>
public static IScalar<T> New<T>(params Func<T>[] items)
where T : IComparable<T>
=> new Max<T>(items);
/// <summary>
/// The greatest item in the given <see cref="IEnumerable{T}"/>
/// </summary>
/// <param name="items">list of items</param>
public static IScalar<T> New<T>(IEnumerable<T> items)
where T : IComparable<T>
=> new Max<T>(items);
/// <summary>
/// The greatest item in the given items.
/// </summary>
/// <param name="items">list of items</param>
public static IScalar<T> New<T>(params T[] items)
where T : IComparable<T>
=> new Max<T>(items);
/// <summary>
/// The greatest item in the given <see cref="IEnumerable{T}"/>
/// </summary>
/// <param name="items">list of items</param>
public static IScalar<T> New<T>(params IScalar<T>[] items)
where T : IComparable<T>
=> new Max<T>(items);
/// <summary>
/// The greatest item in the given <see cref="IEnumerable{T}"/>
/// </summary>
/// <param name="items">list of items</param>
public static IScalar<T> New<T>(IEnumerable<IScalar<T>> items)
where T : IComparable<T>
=> new Max<T>(items);
}
}
| icarus-consulting/Yaapii.Atoms | src/Yaapii.Atoms/Scalar/Max.cs | C# | mit | 5,198 |
"""
The MIT License (MIT)
Copyright (c) 2016 Louis-Philippe Querel l_querel@encs.concordia.ca
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from utility.abstract_override import AbstractOverride
class JdkOverride(AbstractOverride):
def _get_override_format(self):
return 'JAVA_HOME="%s"'
def _get_default_format(self):
return ''
def __init__(self, *args):
AbstractOverride.__init__(self, *args)
self.name = "JDK"
| louisq/staticguru | utility/jdk_override.py | Python | mit | 1,445 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>bit by bit: bbb::container_info::is_unordered_multiset< type > Struct Template Reference</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">bit by bit
 <span id="projectnumber">0.0.1</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('../../',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="../../dc/d34/namespacebbb.html">bbb</a></li><li class="navelem"><a class="el" href="../../d8/db2/namespacebbb_1_1container__info.html">container_info</a></li><li class="navelem"><a class="el" href="../../d6/d4e/structbbb_1_1container__info_1_1is__unordered__multiset.html">is_unordered_multiset</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">bbb::container_info::is_unordered_multiset< type > Struct Template Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><code>#include "<a class="el" href="../../dc/da2/container__traits_8hpp_source.html">container_traits.hpp</a>"</code></p>
<p>Inherits false_type.</p>
<hr/>The documentation for this struct was generated from the following file:<ul>
<li>bbb/core/traits/<a class="el" href="../../dc/da2/container__traits_8hpp_source.html">container_traits.hpp</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
</body>
</html>
| 2bbb/bit_by_bit | docs/d6/d4e/structbbb_1_1container__info_1_1is__unordered__multiset.html | HTML | mit | 3,615 |
using System;
using System.Diagnostics.Tracing;
namespace tracelogging
{
public sealed class MySource : EventSource
{
MySource()
: base(EventSourceSettings.EtwSelfDescribingEventFormat)
{
}
[Event(1)]
public void TestEventMethod(int i, string s)
{
WriteEvent(1, i, s);
}
public static MySource Logger = new MySource();
}
class Program
{
static void Main(string[] args)
{
MySource.Logger.TestEventMethod(1, "Hello World!");
MySource.Logger.Write("TestEvent", new { field1 = "Hello", field2 = 3, field3 = 6 });
MySource.Logger.Write("TestEvent1", new { field1 = "Hello", field2 = 3, });
MySource.Logger.Write("TestEvent2", new { field1 = "Hello" });
MySource.Logger.Write("TestEvent3", new { field1 = new byte[10] });
}
}
}
| brianrob/coretests | managed/tracelogging/Program.cs | C# | mit | 925 |
/*
Módulo: Financeiro
Função: Relatório Recebimento por Cliente
Autor.: Jackson Patrick Werka
Data..: 01/07/2012
© Copyright 2012-2012 SoftGreen - All Rights Reserved
*/
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "uFin3015.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
__fastcall TFin3015::TFin3015(TComponent* Owner)
: TfrmRelatBase01(Owner)
{
}
//---------------------------------------------------------------------------
| jpwerka/SistemaSFG | Financeiro/uFin3015.cpp | C++ | mit | 669 |
* Correctly set test adapter when configure the queue adapter on a per job.
Fixes #26360.
*Yuji Yaginuma*
* Push skipped jobs to `enqueued_jobs` when using `perform_enqueued_jobs` with a `only` filter in tests
*Alexander Pauly*
* Removed deprecated support to passing the adapter class to `.queue_adapter`.
*Rafael Mendonça França*
* Removed deprecated `#original_exception` in `ActiveJob::DeserializationError`.
*Rafael Mendonça França*
* Added instance variable `@queue` to JobWrapper.
This will fix issues in [resque-scheduler](https://github.com/resque/resque-scheduler) `#job_to_hash` method,
so we can use `#enqueue_delayed_selection`, `#remove_delayed` method in resque-scheduler smoothly.
*mu29*
* Yield the job instance so you have access to things like `job.arguments` on the custom logic after retries fail.
*DHH*
* Added declarative exception handling via `ActiveJob::Base.retry_on` and `ActiveJob::Base.discard_on`.
Examples:
class RemoteServiceJob < ActiveJob::Base
retry_on CustomAppException # defaults to 3s wait, 5 attempts
retry_on AnotherCustomAppException, wait: ->(executions) { executions * 2 }
retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3
retry_on Net::OpenTimeout, wait: :exponentially_longer, attempts: 10
discard_on ActiveJob::DeserializationError
def perform(*args)
# Might raise CustomAppException or AnotherCustomAppException for something domain specific
# Might raise ActiveRecord::Deadlocked when a local db deadlock is detected
# Might raise Net::OpenTimeout when the remote service is down
end
end
*DHH*
Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/activejob/CHANGELOG.md) for previous changes.
| bolek/rails | activejob/CHANGELOG.md | Markdown | mit | 1,881 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_PT" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About bitcoinlite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>bitcoinlite</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The bitcoinlite developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Este é um programa experimental.
Distribuído sob uma licença de software MIT/X11, por favor verifique o ficheiro anexo license.txt ou http://www.opensource.org/licenses/mit-license.php.
Este produto inclui software desenvolvido pelo Projecto OpenSSL para uso no OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por Eric Young (eay@cryptsoft.com) e software UPnP escrito por Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Clique duas vezes para editar o endereço ou o rótulo</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Criar um novo endereço</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copie o endereço selecionado para a área de transferência</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your bitcoinlite addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Copiar Endereço</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a bitcoinlite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Apagar o endereço selecionado da lista</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified bitcoinlite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>E&liminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Copiar &Rótulo</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Ficheiro separado por vírgulas (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sem rótulo)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Diálogo de Frase-Passe</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Escreva a frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nova frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repita a nova frase de segurança</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Escreva a nova frase de seguraça da sua carteira. <br/> Por favor, use uma frase de <b>10 ou mais caracteres aleatórios,</b> ou <b>oito ou mais palavras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Encriptar carteira</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquear carteira</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Desencriptar carteira</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Alterar frase de segurança</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Escreva a frase de segurança antiga seguida da nova para a carteira.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirmar encriptação da carteira</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Tem a certeza que deseja encriptar a carteira?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANTE: Qualquer cópia de segurança anterior da carteira deverá ser substituída com o novo, actualmente encriptado, ficheiro de carteira. Por razões de segurança, cópias de segurança não encriptadas efectuadas anteriormente do ficheiro da carteira tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Atenção: A tecla Caps Lock está activa!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Carteira encriptada</translation>
</message>
<message>
<location line="-58"/>
<source>bitcoinlite will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>A encriptação da carteira falhou</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>As frases de segurança fornecidas não coincidem.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>O desbloqueio da carteira falhou</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>A desencriptação da carteira falhou</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>A frase de segurança da carteira foi alterada com êxito.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+280"/>
<source>Sign &message...</source>
<translation>Assinar &mensagem...</translation>
</message>
<message>
<location line="+242"/>
<source>Synchronizing with network...</source>
<translation>Sincronizando com a rede...</translation>
</message>
<message>
<location line="-308"/>
<source>&Overview</source>
<translation>Visã&o geral</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Mostrar visão geral da carteira</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transações</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Navegar pelo histórico de transações</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>Fec&har</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Sair da aplicação</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about bitcoinlite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Sobre &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar informação sobre Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opções...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>E&ncriptar Carteira...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Guardar Carteira...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Mudar &Palavra-passe...</translation>
</message>
<message numerus="yes">
<location line="+250"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-247"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Send coins to a bitcoinlite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Modify configuration options for bitcoinlite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Faça uma cópia de segurança da carteira para outra localização</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Mudar a frase de segurança utilizada na encriptação da carteira</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>Janela de &depuração</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Abrir consola de diagnóstico e depuração</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verificar mensagem...</translation>
</message>
<message>
<location line="-200"/>
<source>bitcoinlite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Carteira</translation>
</message>
<message>
<location line="+178"/>
<source>&About bitcoinlite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>Mo&strar / Ocultar</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>&File</source>
<translation>&Ficheiro</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>Con&figurações</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>A&juda</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Barra de separadores</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[rede de testes]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>bitcoinlite client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to bitcoinlite network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-284"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+288"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Atualizado</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Recuperando...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Transação enviada</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Transação recebida</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Quantia: %2
Tipo: %3
Endereço: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid bitcoinlite address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>A carteira está <b>encriptada</b> e atualmente <b>desbloqueada</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>A carteira está <b>encriptada</b> e atualmente <b>bloqueada</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. bitcoinlite can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Alerta da Rede</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Quantidade:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Quantia:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioridade:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Taxa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Saída Baixa:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>não</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Depois de taxas:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Troco:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(des)seleccionar todos</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Modo de árvore</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Modo lista</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmados</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmada</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioridade</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Copiar endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar rótulo</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copiar ID da Transação</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Copiar quantidade</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Taxa de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Taxa depois de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Prioridade de Cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar output baixo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar alteração</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>o maior</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>médio-alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>médio</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>baixo-médio</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>baixo</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>O mais baixo</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>sim</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(Sem rótulo)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>Alteração de %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(Alteração)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Endereço</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Rótulo</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>E&ndereço</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Novo endereço de entrada</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Novo endereço de saída</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar endereço de entrada</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar endereço de saída</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>O endereço introduzido "%1" já se encontra no livro de endereços.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid bitcoinlite address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Impossível desbloquear carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Falha ao gerar nova chave.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>bitcoinlite-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opções</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Pagar &taxa de transação</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start bitcoinlite after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start bitcoinlite on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Rede</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the bitcoinlite client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapear porta usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the bitcoinlite network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP do proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Porta:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Porta do proxy (p.ex. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Versão SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Versão do proxy SOCKS (p.ex. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Janela</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Apenas mostrar o ícone da bandeja após minimizar a janela.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizar para a bandeja e não para a barra de ferramentas</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimize ao invés de sair da aplicação quando a janela é fechada. Com esta opção selecionada, a aplicação apenas será encerrada quando escolher Sair da aplicação no menú.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizar ao fechar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>Vis&ualização</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Linguagem da interface de utilizador:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting bitcoinlite.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unidade a usar em quantias:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Escolha a subdivisão unitária a ser mostrada por defeito na aplicação e ao enviar moedas.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show bitcoinlite addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Mostrar en&dereços na lista de transações</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Escolha para mostrar funcionalidades de controlo "coin" ou não.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>padrão</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting bitcoinlite.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>O endereço de proxy introduzido é inválido. </translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulário</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the bitcoinlite network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Carteira</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>O seu saldo disponível para gastar</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Imaturo:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>O saldo minado ainda não maturou</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>O seu saldo total actual</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Transações recentes</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>fora de sincronia</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nome do Cliente</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>N/D</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Versão do Cliente</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informação</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Usando versão OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Tempo de início</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Rede</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Número de ligações</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Cadeia de blocos</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Número actual de blocos</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Total estimado de blocos</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Tempo do último bloco</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Abrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the bitcoinlite-Qt help message to get a list with possible bitcoinlite command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Data de construção</translation>
</message>
<message>
<location line="-104"/>
<source>bitcoinlite - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>bitcoinlite Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Ficheiro de registo de depuração</translation>
</message>
<message>
<location line="+7"/>
<source>Open the bitcoinlite debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Limpar consola</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the bitcoinlite RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use as setas para cima e para baixo para navegar no histórico e <b>Ctrl-L</b> para limpar o ecrã.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Digite <b>help</b> para visualizar os comandos disponíveis.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Enviar Moedas</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Funcionalidades de Coin Controlo:</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Entradas</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>Selecção automática</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Fundos insuficientes!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Quantidade:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Quantia:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 BC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Prioridade:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Taxa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Output Baixo:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Depois de taxas:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar para múltiplos destinatários de uma vez</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Adicionar &Destinatário</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Limpar Tudo</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 BC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirme ação de envio</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Enviar</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a bitcoinlite address (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Copiar quantidade</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Taxa de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Taxa depois de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Prioridade de Cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar output baixo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar alteração</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirme envio de moedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>O endereço de destino não é válido, por favor verifique.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>A quantia a pagar deverá ser maior que 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>A quantia excede o seu saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>O total excede o seu saldo quando a taxa de transação de %1 for incluída.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Endereço duplicado encontrado, apenas poderá enviar uma vez para cada endereço por cada operação de envio.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid bitcoinlite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(Sem rótulo)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Qu&antia:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar A:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Escreva um rótulo para este endereço para o adicionar ao seu livro de endereços</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>Rótu&lo:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Cole endereço da área de transferência</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a bitcoinlite address (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Assinaturas - Assinar / Verificar uma Mensagem</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>A&ssinar Mensagem</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Pode assinar mensagens com os seus endereços para provar que são seus. Tenha atenção ao assinar mensagens ambíguas, pois ataques de phishing podem tentar enganá-lo, de modo a assinar a sua identidade para os atacantes. Apenas assine declarações completamente detalhadas com as quais concorde.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Cole endereço da área de transferência</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Escreva aqui a mensagem que deseja assinar</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiar a assinatura actual para a área de transferência</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this bitcoinlite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Repôr todos os campos de assinatura de mensagem</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Limpar &Tudo</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Verificar Mensagem</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Introduza o endereço de assinatura, mensagem (assegure-se de copiar quebras de linha, espaços, tabuladores, etc. exactamente) e assinatura abaixo para verificar a mensagem. Tenha atenção para não ler mais na assinatura do que o que estiver na mensagem assinada, para evitar ser enganado por um atacante que se encontre entre si e quem assinou a mensagem.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified bitcoinlite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Repôr todos os campos de verificação de mensagem</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a bitcoinlite address (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Clique "Assinar mensagem" para gerar a assinatura</translation>
</message>
<message>
<location line="+3"/>
<source>Enter bitcoinlite signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>O endereço introduzido é inválido. </translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Por favor verifique o endereço e tente de novo.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>O endereço introduzido não refere a chave alguma.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>O desbloqueio da carteira foi cancelado.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>A chave privada para o endereço introduzido não está disponível.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Assinatura de mensagem falhou.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mensagem assinada.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>A assinatura não pôde ser descodificada.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Por favor verifique a assinatura e tente de novo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>A assinatura não condiz com o conteúdo da mensagem.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verificação da mensagem falhou.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mensagem verificada.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/desligado</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/não confirmada</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmações</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Origem</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Gerado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Para</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>endereço próprio</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>rótulo</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Crédito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>matura daqui por %n bloco</numerusform><numerusform>matura daqui por %n blocos</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>não aceite</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Débito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Taxa de transação</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Valor líquido</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensagem</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentário</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID da Transação</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informação de depuração</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transação</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Entradas</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>verdadeiro</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falso</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ainda não foi transmitida com sucesso</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>desconhecido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalhes da transação</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta janela mostra uma descrição detalhada da transação</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmada (%1 confirmações)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Gerado mas não aceite</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Recebido com</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recebido de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado para</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pagamento ao próprio</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minadas</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/d)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado da transação. Pairar por cima deste campo para mostrar o número de confirmações.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Data e hora a que esta transação foi recebida.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Endereço de destino da transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Quantia retirada ou adicionada ao saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Todas</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoje</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Este mês</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mês passado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este ano</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Período...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recebida com</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviada para</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Para si</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minadas</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Outras</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Escreva endereço ou rótulo a procurar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Quantia mínima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copiar endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copiar ID da Transação</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editar rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Mostrar detalhes da transação</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Ficheiro separado por vírgula (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmada</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Período:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>até</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>bitcoinlite version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Utilização:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or bitcoinlited</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Listar comandos</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Obter ajuda para um comando</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Opções:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: bitcoinlite.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: bitcoinlited.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Especifique ficheiro de carteira (dentro da pasta de dados)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especificar pasta de dados</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Definir o tamanho da cache de base de dados em megabytes (por defeito: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 28756)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Manter no máximo <n> ligações a outros nós da rede (por defeito: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Especifique o seu endereço público</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Tolerância para desligar nós mal-formados (por defeito: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Número de segundos a impedir que nós mal-formados se liguem de novo (por defeito: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv4: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 28755)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceitar comandos da consola e JSON-RPC</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr o processo como um daemon e aceitar comandos</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Utilizar a rede de testes - testnet</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv6, a usar IPv4: %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong bitcoinlite will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Atenção: wallet.dat corrupto, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar de uma cópia de segurança.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Opções de criação de bloco:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Apenas ligar ao(s) nó(s) especificado(s)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descobrir endereço IP próprio (padrão: 1 ao escutar e sem -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Falhou a escutar em qualquer porta. Use -listen=0 se quer isto.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Armazenamento intermédio de recepção por ligação, <n>*1000 bytes (por defeito: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Armazenamento intermédio de envio por ligação, <n>*1000 bytes (por defeito: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Apenas ligar a nós na rede <net> (IPv4, IPv6 ou Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Opções SSL: (ver a Wiki Bitcoin para instruções de configuração SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Definir tamanho minímo de um bloco em bytes (por defeito: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especificar tempo de espera da ligação em millisegundos (por defeito: 5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Nome de utilizador para ligações JSON-RPC</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupta, recuperação falhou</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Palavra-passe para ligações JSON-RPC</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinliterpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "bitcoinlite Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitir ligações JSON-RPC do endereço IP especificado</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Enviar comandos para o nó a correr em <ip> (por defeito: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Executar comando quando mudar o melhor bloco (no comando, %s é substituído pela hash do bloco)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Atualize a carteira para o formato mais recente</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Definir o tamanho da memória de chaves para <n> (por defeito: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Reexaminar a cadeia de blocos para transações em falta na carteira</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usar OpenSSL (https) para ligações JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Ficheiro de certificado do servidor (por defeito: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Chave privada do servidor (por defeito: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Esta mensagem de ajuda</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. bitcoinlite is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>bitcoinlite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Incapaz de vincular a %s neste computador (vínculo retornou erro %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Carregar endereços...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Erro ao carregar wallet.dat: Carteira danificada</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of bitcoinlite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart bitcoinlite to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Erro ao carregar wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Endereço -proxy inválido: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Rede desconhecida especificada em -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Versão desconhecida de proxy -socks requisitada: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Não conseguiu resolver endereço -bind: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Não conseguiu resolver endereço -externalip: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Quantia inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Quantia inválida</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fundos insuficientes</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Carregar índice de blocos...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Adicione um nó ao qual se ligar e tentar manter a ligação aberta</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. bitcoinlite is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Carregar carteira...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Impossível mudar a carteira para uma versão anterior</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Impossível escrever endereço por defeito</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Reexaminando...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Carregamento completo</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Para usar a opção %s</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Erro</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Deverá definir rpcpassword=<password> no ficheiro de configuração:
%s
Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.</translation>
</message>
</context>
</TS> | bitcoinlitedev/bitcoinlite-master | src/qt/locale/bitcoin_pt_PT.ts | TypeScript | mit | 119,136 |
<?php
namespace felpado\tests;
use felpado as f;
/*
* Code from https://github.com/nikic/iter/blob/master/test/IterFnTest.php
*/
class not_fnTest extends felpadoTestCase
{
public function testIt() {
$constFalse = f\not_fn(function() { return true; });
$constTrue = f\not_fn(function() { return false; });
$invert = f\not_fn(function($bool) { return $bool; });
$nand = f\not_fn(f\operator('&&'));
$this->assertEquals(false, $constFalse());
$this->assertEquals(true, $constTrue());
$this->assertEquals(false, $invert(true));
$this->assertEquals(true, $invert(false));
$this->assertEquals(false, $nand(true, true));
$this->assertEquals(true, $nand(true, false));
}
}
| pablodip/felpado | tests/functions/not_fnTest.php | PHP | mit | 758 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("16-SubsetWithSumS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("16-SubsetWithSumS")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0bbfe77c-7409-4639-bf56-3c9ee7025042")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| svetlai/TelerikAcademy | Programming-with-C#/C#-Part-2/01-Arrays/16-SubsetWithSumS/Properties/AssemblyInfo.cs | C# | mit | 1,410 |
# Games
The repo serves to hold all of the data for the website codingtime.io. The corresponding code for each game can be found in the GameCode repo.
| chriszbest/Games | README.md | Markdown | mit | 152 |
# ethereumjs-icap
[](https://www.npmjs.org/package/ethereumjs-icap)
[](https://travis-ci.org/ethereumjs/ethereumjs-icap)
[](https://coveralls.io/r/ethereumjs/ethereumjs-icap)
[](https://gitter.im/ethereum/ethereumjs-lib) or #ethereumjs on freenode
Utilities for handling [ICAP](https://github.com/ethereum/wiki/wiki/ICAP:-Inter-exchange-Client-Address-Protocol) addresses.
It works in Node.js as well as in the browser via `browserify`. When minified for a browser, it should be less than 4K in size.
## API
* `fromAddress(address, print, nonstd)` - try encoding an address into an IBAN
* `fromAsset(asset, print)` - try encoding an asset description into an IBAN
* `toAddress(iban)` - try decoding an IBAN into an address
* `toAsset(iban)` - try decoding an IBAN into an asset description
* `encode(address/asset)` - encode an address or asset description into an IBAN
* `decode(iban)` - decode an IBAN into an address or asset description
* `encodeBBAN(address/asset)` - encode an address or asset description into a BBAN
* `decodeBBAN(bban)` - decode a BBAN into an address or asset description
* `isICAP(iban)` - return true if input is a valid ICAP, otherwise false
* `isAddress(iban)` - return true if the input is a valid ICAP with an address, otherwise false
* `isAsset(iban)` - return true if the input is a valid ICAP with an asset description, otherwise false
All of the above methods will throw exceptions on invalid inputs. The `to*` and `from*` method will also check for the expected inputs and outputs.
The `print` parameter above, when set to true, will create an IBAN in the *print format*, which is space delimited groups of four characters: `XE73 38O0 73KY GTWW ZN0F 2WZ0 R8PX 5ZPP ZS`
The `address` parameter only supports `0x` prefixed input and will include that in the output.
The `nonstd` parameter of `fromAddress`, when set to true, will turn on support for the *basic ICAP format* generating an invalid IBAN, but encoding the entire 160 bits of an Ethereum address.
## Examples
```js
ICAP.fromAsset({
asset: 'ETH',
institution: 'XREG',
client: 'GAVOFYORK'
})
// returns 'XE81ETHXREGGAVOFYORK'
ICAP.fromAddress('0x00c5496aee77c1ba1f0854206a26dda82a81d6d8')
// returns 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'
ICAP.toAsset('XE81ETHXREGGAVOFYORK')
// returns {
// asset: 'ETH',
// institution: 'XREG',
// client: 'GAVOFYORK'
// }
ICAP.toAddress('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS')
// returns '0x00c5496aee77c1ba1f0854206a26dda82a81d6d8'
```
## *Direct* address generation
A *direct address ICAP* is an address less than 155 bits of length and therefore it safely fits into the length restrictions of IBAN (and the checksum method used).
That upper limit is `0x03ffffffffffffffffffffffffffffffffffffff` or `XE91GTJRJEU5043IEF993XWE21DBF0BVGF`.
The following simple bruteforce code can be used to generate such addresses:
```js
const ethUtil = require('ethereumjs-util')
function generateDirectAddress () {
while(true) {
var privateKey = crypto.randomBytes(32) // or your favourite other random method
if (ethUtil.privateToAddress(privateKey)[0] <= 3) {
return privateKey
}
}
}
```
Alternatively [`ethereumjs-wallet`](http://npmjs.com/packages/ethereumjs-wallet) can be used to generate compatible addresses.
| ethereumjs/ethereumjs-icap | README.md | Markdown | mit | 3,666 |
## 愿一切越来越好! | lczhai/lczhai.github.io | README.md | Markdown | mit | 29 |
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009-2014 Alan Wright. All rights reserved.
// Distributable under the terms of either the Apache License (Version 2.0)
// or the GNU Lesser General Public License.
/////////////////////////////////////////////////////////////////////////////
#ifndef COLLECTION_H
#define COLLECTION_H
#include <vector>
#include "LuceneSync.h"
namespace Lucene {
/// Utility template class to handle collections that can be safely copied and shared
template <class TYPE>
class Collection : public LuceneSync {
public:
typedef Collection<TYPE> this_type;
typedef boost::shared_ptr<this_type> shared_ptr;
typedef std::vector<TYPE> collection_type;
typedef typename collection_type::iterator iterator;
typedef typename collection_type::const_iterator const_iterator;
typedef TYPE value_type;
virtual ~Collection() {
}
protected:
boost::shared_ptr<collection_type> container;
public:
static this_type newInstance(int32_t size = 0) {
this_type instance;
instance.container = Lucene::newInstance<collection_type>(size);
return instance;
}
template <class ITER>
static this_type newInstance(ITER first, ITER last) {
this_type instance;
instance.container = Lucene::newInstance<collection_type>(first, last);
return instance;
}
void reset() {
resize(0);
}
void resize(int32_t size) {
if (size == 0) {
container.reset();
} else {
container->resize(size);
}
}
int32_t size() const {
return (int32_t)container->size();
}
bool empty() const {
return container->empty();
}
void clear() {
container->clear();
}
iterator begin() {
return container->begin();
}
iterator end() {
return container->end();
}
const_iterator begin() const {
return container->begin();
}
const_iterator end() const {
return container->end();
}
void add(const TYPE& type) {
container->push_back(type);
}
void add(int32_t pos, const TYPE& type) {
container->insert(container->begin() + pos, type);
}
template <class ITER>
void addAll(ITER first, ITER last) {
container->insert(container->end(), first, last);
}
template <class ITER>
void insert(ITER pos, const TYPE& type) {
container->insert(pos, type);
}
template <class ITER>
ITER remove(ITER pos) {
return container->erase(pos);
}
template <class ITER>
ITER remove(ITER first, ITER last) {
return container->erase(first, last);
}
void remove(const TYPE& type) {
container->erase(std::remove(container->begin(), container->end(), type), container->end());
}
template <class PRED>
void remove_if(PRED comp) {
container->erase(std::remove_if(container->begin(), container->end(), comp), container->end());
}
TYPE removeFirst() {
TYPE front = container->front();
container->erase(container->begin());
return front;
}
TYPE removeLast() {
TYPE back = container->back();
container->pop_back();
return back;
}
iterator find(const TYPE& type) {
return std::find(container->begin(), container->end(), type);
}
template <class PRED>
iterator find_if(PRED comp) {
return std::find_if(container->begin(), container->end(), comp);
}
bool contains(const TYPE& type) const {
return (std::find(container->begin(), container->end(), type) != container->end());
}
template <class PRED>
bool contains_if(PRED comp) const {
return (std::find_if(container->begin(), container->end(), comp) != container->end());
}
bool equals(const this_type& other) const {
return equals(other, std::equal_to<TYPE>());
}
template <class PRED>
bool equals(const this_type& other, PRED comp) const {
if (container->size() != other.container->size()) {
return false;
}
return std::equal(container->begin(), container->end(), other.container->begin(), comp);
}
int32_t hashCode() {
return (int32_t)(int64_t)container.get();
}
void swap(this_type& other) {
container.swap(other->container);
}
TYPE& operator[] (int32_t pos) {
return (*container)[pos];
}
const TYPE& operator[] (int32_t pos) const {
return (*container)[pos];
}
operator bool() const {
return container.get() != NULL;
}
bool operator! () const {
return !container;
}
bool operator== (const this_type& other) {
return (container == other.container);
}
bool operator!= (const this_type& other) {
return (container != other.container);
}
};
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1) {
Collection<TYPE> result = Collection<TYPE>::newInstance();
result.add(a1);
return result;
}
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1, const TYPE& a2) {
Collection<TYPE> result = newCollection(a1);
result.add(a2);
return result;
}
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1, const TYPE& a2, const TYPE& a3) {
Collection<TYPE> result = newCollection(a1, a2);
result.add(a3);
return result;
}
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1, const TYPE& a2, const TYPE& a3, const TYPE& a4) {
Collection<TYPE> result = newCollection(a1, a2, a3);
result.add(a4);
return result;
}
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1, const TYPE& a2, const TYPE& a3, const TYPE& a4, const TYPE& a5) {
Collection<TYPE> result = newCollection(a1, a2, a3, a4);
result.add(a5);
return result;
}
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1, const TYPE& a2, const TYPE& a3, const TYPE& a4, const TYPE& a5, const TYPE& a6) {
Collection<TYPE> result = newCollection(a1, a2, a3, a4, a5);
result.add(a6);
return result;
}
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1, const TYPE& a2, const TYPE& a3, const TYPE& a4, const TYPE& a5, const TYPE& a6, const TYPE& a7) {
Collection<TYPE> result = newCollection(a1, a2, a3, a4, a5, a6);
result.add(a7);
return result;
}
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1, const TYPE& a2, const TYPE& a3, const TYPE& a4, const TYPE& a5, const TYPE& a6, const TYPE& a7, const TYPE& a8) {
Collection<TYPE> result = newCollection(a1, a2, a3, a4, a5, a6, a7);
result.add(a8);
return result;
}
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1, const TYPE& a2, const TYPE& a3, const TYPE& a4, const TYPE& a5, const TYPE& a6, const TYPE& a7, const TYPE& a8, const TYPE& a9) {
Collection<TYPE> result = newCollection(a1, a2, a3, a4, a5, a6, a7, a8);
result.add(a9);
return result;
}
template <typename TYPE>
Collection<TYPE> newCollection(const TYPE& a1, const TYPE& a2, const TYPE& a3, const TYPE& a4, const TYPE& a5, const TYPE& a6, const TYPE& a7, const TYPE& a8, const TYPE& a9, const TYPE& a10) {
Collection<TYPE> result = newCollection(a1, a2, a3, a4, a5, a6, a7, a8, a9);
result.add(a10);
return result;
}
}
#endif
| afklm/lucenekit | Pod/Libraries/Header/Collection.h | C | mit | 7,497 |
@font-face {
font-family: 'layouter';
src: url('../fonts/layouter.eot?42hzee');
src: url('../fonts/layouter.eot?42hzee#iefix') format('embedded-opentype'),
url('../fonts/layouter.ttf?42hzee') format('truetype'),
url('../fonts/layouter.woff?42hzee') format('woff'),
url('../fonts/layouter.svg?42hzee#icomoon') format('svg');
font-weight: normal;
font-style: normal;
}
[class^="icon-"], [class*=" icon-"] {
/* use !important to prevent issues with browser extensions that change fonts */
font-family: 'layouter' !important;
speak: none;
font-size: 1.5em;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
vertical-align: middle;
/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.layouterRow--outer + .layouter-row--outer {
margin-top: 2px;
}
.layouterRow--inner {
background-size: cover;
background-repeat: no-repeat;
}
.layouterRow--parallax {
background-attachment: fixed;
background-position: center;
}
.layouterRow--inner.show-grid [class^=col-] {
border: 2px dashed #1F5E8E;
margin-bottom: -4px;
}
#id_container_type li {
display: inline-block;
width: 250px;
text-align: center;
border: 0;
padding-bottom: 15px;
user-select: none;
}
#id_container_type li span {
padding-bottom: 7px;
display: inline-block;
}
#id_container_type li.checked {
border: 1px solid black;
margin-bottom: -1px;
margin-right: -1px;
margin-left: -1px;
margin-top: -1px;
}
#id_container_type input[type=radio] {
display: none;
}
.quarter:before {
content: "\e900";
}
.third:before {
content: "\e901";
}
.half:before {
content: "\e903";
}
.two-third:before {
content: "\e904";
}
.three-quarter:before {
content: "\e905";
}
.full-width:before {
content: "\e906";
}
.layouterRow--equalHeight {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
} | Blueshoe/djangocms-layouter | layouter/static/layouter/css/layouter.css | CSS | mit | 1,983 |
<?php
namespace Brainwave\Database;
/**
* Narrowspark - a PHP 5 framework
*
* @author Daniel Bannert <info@anolilab.de>
* @copyright 2014 Daniel Bannert
* @link http://www.narrowspark.de
* @license http://www.narrowspark.com/license
* @version 0.9.3-dev
* @package Narrowspark/framework
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Narrowspark is an open source PHP 5 framework, based on the Slim framework.
*
*/
use \Pimple\Container;
use \Brainwave\Support\Arr;
use \Brainwave\Database\Connection\ConnectionFactory;
use \Brainwave\Database\Connection\Interfaces\ConnectionInterface;
use \Brainwave\Database\Connection\Interfaces\ConnectionResolverInterface;
/**
* DatabaseManager
*
* @package Narrowspark/Database
* @author Daniel Bannert
* @since 0.9.2-dev
*
*/
class DatabaseManager implements ConnectionResolverInterface
{
/**
* The application instance.
*
* @var \Pimple\Container
*/
protected $app;
/**
* The database connection factory instance.
*
* @var \Brainwave\Database\Connection\ConnectionFactory
*/
protected $factory;
/**
* The active connection instances.
*
* @var array
*/
protected $connections = [];
/**
* The custom connection resolvers.
*
* @var array
*/
protected $extensions = [];
/**
* Create a new database manager instance.
*
* @param \Pimple\Container $app
* @param \Brainwave\Database\Connection\ConnectionFactory $factory
* @return void
*/
public function __construct(Container $app, ConnectionFactory $factory)
{
$this->app = $app;
$this->factory = $factory;
}
/**
* Get a database connection instance.
*
* @param string $name
* @return \Brainwave\Database\Connection\Connection
*/
public function connection($name = null)
{
// If we haven't created this connection, we'll create it based on the config
// provided in the application. Once we've created the connections we will
// set the "fetch mode" for PDO which determines the query return types.
if (!isset($this->connections[$name])) {
$connection = $this->makeConnection($name);
$this->connections[$name] = $this->prepare($connection);
}
return $this->connections[$name];
}
/**
* Disconnect from the given database and remove from local cache.
*
* @param string $name
* @return void
*/
public function purge($name = null)
{
$this->disconnect($name);
unset($this->connections[$name]);
}
/**
* Disconnect from the given database.
*
* @param string $name
* @return void
*/
public function disconnect($name = null)
{
if (isset($this->connections[$name = $name ?: $this->getDefaultConnection()])) {
$this->connections[$name]->disconnect();
}
}
/**
* Reconnect to the given database.
*
* @param string $name
* @return \Brainwave\Database\Connection\Connection
*/
public function reconnect($name = null)
{
$this->disconnect($name = $name ?: $this->getDefaultConnection());
if (!isset($this->connections[$name])) {
return $this->connection($name);
} else {
return $this->refreshPdoConnections($name);
}
}
/**
* Refresh the PDO connections on a given connection.
*
* @param string $name
* @return \Brainwave\Database\Connection\Connection
*/
protected function refreshPdoConnections($name)
{
$fresh = $this->makeConnection($name);
return $this->connections[$name]->setPdo($fresh->getPdo());
}
/**
* Make the database connection instance.
*
* @param string $name
* @return \Brainwave\Database\Connection\Connection
*/
protected function makeConnection($name)
{
$config = $this->getConfig($name);
// First we will check by the connection name to see if an extension has been
// registered specifically for that connection. If it has we will call the
// Closure and pass it the config allowing it to resolve the connection.
if (isset($this->extensions[$name])) {
return call_user_func($this->extensions[$name], $config, $name);
}
$driver = $config['driver'];
// Next we will check to see if an extension has been registered for a driver
// and will call the Closure if so, which allows us to have a more generic
// resolver for the drivers themselves which applies to all connections.
if (isset($this->extensions[$driver])) {
return call_user_func($this->extensions[$driver], $config, $name);
}
return $this->factory->make($config, $name);
}
/**
* Prepare the database connection instance.
*
* @param \Brainwave\Database\Connection\Interfaces\ConnectionInterface $connection
* @return \Brainwave\Database\Connection\Connection
*/
protected function prepare(ConnectionInterface $connection)
{
$connection->setFetchMode($this->app['settings']['database::fetch']);
// The database connection can also utilize a cache manager instance when cache
// functionality is used on queries, which provides an expressive interface
// to caching both fluent queries and Eloquent queries that are executed.
$app = $this->app;
$connection->setCacheManager(function () use ($app) {
return $app['cache'];
});
// Here we'll set a reconnector callback. This reconnector can be any callable
// so we will set a Closure to reconnect from this manager with the name of
// the connection, which will allow us to reconnect from the connections.
$connection->setReconnector(function (ConnectionInterface $connection) {
$this->reconnect($connection->getName());
});
return $connection;
}
/**
* Get the configuration for a connection.
*
* @param string $name
* @return array
*
* @throws \InvalidArgumentException
*/
protected function getConfig($name)
{
$name = $name ?: $this->getDefaultConnection();
// To get the database connection configuration, we will just pull each of the
// connection configurations and get the configurations for the given name.
// If the configuration doesn't exist, we'll throw an exception and bail.
$connections = $this->app['settings']['database::connections'];
if (is_null($config = Arr::arrayGet($connections, $name))) {
throw new \InvalidArgumentException("Database [$name] not configured.");
}
return $config;
}
/**
* Get the default connection name.
*
* @return string
*/
public function getDefaultConnection()
{
return $this->app['settings']['database::default'];
}
/**
* Set the default connection name.
*
* @param string $name
* @return void
*/
public function setDefaultConnection($name)
{
$this->app['settings']['database::default'] = $name;
}
/**
* Register an extension connection resolver.
*
* @param string $name
* @param callable $resolver
* @return void
*/
public function extend($name, callable $resolver)
{
$this->extensions[$name] = $resolver;
}
/**
* Return all of the created connections.
*
* @return array
*/
public function getConnections()
{
return $this->connections;
}
/**
* Dynamically pass methods to the default connection.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return call_user_func_array(array($this->connection(), $method), $parameters);
}
}
| ovr/framework-2 | src/Brainwave/Database/DatabaseManager.php | PHP | mit | 8,220 |
# Acknowledgement
This package is from [crypt](https://github.com/xordataexchange/crypt)
[MIT license](https://github.com/xordataexchange/crypt/blob/master/LICENSE)
| fzerorubigd/onion | ciphers/secconf/README.md | Markdown | mit | 169 |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 21 16:29:34 2017
@author: ishort
"""
import math
""" procedure to generate Gaussian of unit area when passed a FWHM"""
#IDL: PRO GAUSS2,FWHM,LENGTH,NGAUS
def gauss2(fwhm, length):
#length=length*1l & FWHM=FWHM*1l
#NGAUS=FLTARR(LENGTH)
ngaus = [0.0 for i in range(length)]
#This expression for CHAR comes from requiring f(x=0.5*FWHM)=0.5*f(x=0):
#CHAR=-1d0*ALOG(0.5d0)/(0.5d0*0.5d0*FWHM*FWHM)
char = -1.0 * math.log(0.5) / (0.5*0.5*fwhm*fwhm)
#This expression for AMP (amplitude) comes from requiring that the
#area under the gaussian is unity:
#AMP=SQRT(CHAR/PI)
amp = math.sqrt(char/math.pi)
#FOR CNT=0l,(LENGTH-1) DO BEGIN
# X=(CNT-LENGTH/2)*1.d0
# NGAUS(CNT)=AMP*EXP(-CHAR*X^2)
#ENDFOR
for cnt in range(length):
x = 1.0 * (cnt - length/2)
ngaus[cnt] = amp * math.exp(-1.0*char*x*x)
return ngaus
| sevenian3/ChromaStarPy | Gauss2.py | Python | mit | 996 |
/**
* @author Ultimo <von.ultimo@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 0.1 (25-06-2017)
*
* Hier schreiben wir die JavaScript Funktionen.
* */
src="jquery-3.2.1.min";
$(document).ready(function(){
$("td:contains('-')").filter(":contains('€')").addClass('neg');
$(".betrag").filter(":contains('-')").addClass('neg');
});
function goBack() {
window.history.back();
} | vonUltimo/kasse | js/lib.js | JavaScript | mit | 446 |
AMD::Engine.routes.draw do
get '/amd/:asset', to: 'assets#finder'
end
| Yellowen/amd | config/routes.rb | Ruby | mit | 72 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Console-Input-Output")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Console-Input-Output")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("863d8aa0-f168-49fe-b8d2-ceffdd496f75")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| bstaykov/Telerik-CSharp-Part-1 | Console-Input-Output/Console-Input-Output/Properties/AssemblyInfo.cs | C# | mit | 1,416 |
<div class="navbar navbar-default navbar-static-top" ng-controller="NavbarCtrl">
<div class="container">
<div class="navbar-header">
<button class="navbar-toggle" type="button" ng-click="isCollapsed = !isCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="/" class="navbar-brand">sparksensor</a>
</div>
<div collapse="isCollapsed" class="navbar-collapse collapse" id="navbar-main">
<ul class="nav navbar-nav">
<li ng-repeat="item in menu" ng-class="{active: isActive(item.link)}">
<a ng-href="{{item.link}}">{{item.title}}</a>
</li>
</ul>
</div>
</div>
</div>
| geekfamily/sparksensor | client/components/navbar/navbar.html | HTML | mit | 789 |
var compare = require('typewiselite')
var search = require('binary-search')
function compareKeys (a, b) {
return compare(a.key, b.key)
}
module.exports = function (_compare) {
var ary = [], kv
_compare = _compare || compare
function cmp (a, b) {
return _compare(a.key, b.key)
}
return kv = {
getIndex: function (key) {
return search(ary, {key: key}, cmp, 0, ary.length - 1)
},
get: function (key) {
var i = this.getIndex(key)
return i >= 0 ? ary[i].value : undefined
},
has: function (key) {
return this.getIndex(key) >= 0
},
//update a key
set: function (key, value) {
return kv.add({key: key, value: value})
},
add: function (o) {
var i = search(ary, o, cmp)
//overwrite a key, or insert a key
if(i < 0) ary.splice(~i, 0, o)
else ary[i] = o
return i
},
toJSON: function () {
return ary.slice()
},
store: ary
}
}
module.exports.search = search
module.exports.compareKeys = compareKeys
| dominictarr/binary-map | index.js | JavaScript | mit | 1,040 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="Description" content="Basic Gray">
<meta name="author" content="CoffeeCup Software, Inc.">
<meta name="Copyright" content="Copyright (c) 2010 CoffeeCup, all rights reserved.">
<meta name="Customized" content="Chad Anderson and James Laprevote">
<title>Basic Gray Theme - About</title>
<link rel="stylesheet" href="stylesheets/default.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="javascripts/behavior.js"></script>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header id="mast">
<p align="right" > <a> login </a> <a> signup </a> </p>
<h1>Yardsale Addicts</h1>
</header>
<nav id="global">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="profile.html">Profile</a></li>
<li><a href="services.html">Yardsale Mapper</a></li>
<li><a href="contact.html">Contact</a></li>
<li><a class="selected" href="about.html">About</a></li>
</ul>
</nav>
<section id="intro">
<header>
<h2>Do you love yardsales as much as we do?</h2>
</header>
<p>The number of garage sales that occur in the Provo and Salt Lake areas is large. Garage sale hoping has become a Saturday activity for some, especially newlyweds looking to furnish their first apartment. While these individuals wish to furnish their apartment many lack the funds to just buy the items outright and the time to search KSL continuously for deals.
<br><br>Garage Sale Addict Solutions aims to help solve the headache of planning a route to garage sales in the local area. It will offer the ability to choose from a selection of yard sales and find a fast, convenient route between them. </p>
<div id="photo">
<div>
<h3>Photo of us?</h3>
</div>
</div>
</section>
<div id="main" class="clear">
</div>
<footer>
<div class="clear">
<section id="about">
<header>
<h3>About</h3>
</header>
<p>The number of garage sales that occur in the Provo and Salt Lake areas is large. Garage sale hoping has become a Saturday activity for some, especially newlyweds looking to furnish their first apartment. While these individuals wish to furnish their apartment many lack the funds to just buy the items outright and the time to search KSL continuously for deals.
<br>
Garage Sale Addict Solutions aims to help solve the headache of planning a route to garage sales in the local area. It will offer the ability to choose from a selection of yard sales and find a fast, convenient route between them.</p>
</section>
<section>
<header>
<h3>Recent Yardsales</h3>
</header>
<nav id="blogRoll">
<ul>
<li><a href="/">Page Link</a></li>
<li><a href="/">Page Link</a></li>
<li><a href="/">Page Link</a></li>
<li><a href="/">Page Link</a></li>
<li><a href="/">Page Link</a></li>
<li><a href="/">Page Link</a></li>
</ul>
</nav>
</section>
<section>
<header>
<h3>Site Map</h3>
</header>
<nav id="siteMap">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="profile.html">Profile</a></li>
<li><a href="services.html">Services</a></li>
<li><a href="contact.html">Contact</a></li>
<li><a href="about.html">About</a></li>
</ul>
</nav>
</section>
</div>
</footer>
</body>
</html>
| vorquel/yard-sale-mapper | webdesign/about.html | HTML | mit | 4,064 |
namespace Grauenwolf.TravellerTools.Names
{
public class RandomPerson
{
/// <summary>
/// Initializes a new instance of the <see cref="RandomName"/> class.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
internal RandomPerson(Result user)
{
FirstName = user.name.first.Substring(0, 1).ToUpper() + user.name.first.Substring(1);
LastName = user.name.last.Substring(0, 1).ToUpper() + user.name.last.Substring(1);
Gender = user.gender == "female" ? "F" : "M";
}
internal RandomPerson(string first, string last, string gender)
{
LastName = last.Substring(0, 1).ToUpper() + last.Substring(1); ;
FirstName = first.Substring(0, 1).ToUpper() + first.Substring(1); ;
Gender = gender;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string FullName { get { return FirstName + " " + LastName; } }
}
}
| Grauenwolf/TravellerTools | TravellerTools/Grauenwolf.TravellerTools.Services/Names/RandomPerson.cs | C# | mit | 1,109 |
# TinyUI
A Responsive UI
| leezng/TinyUI | README.md | Markdown | mit | 25 |
define( [
'jquery',
'angular',
'json!nuke/data/dummy_model.json',
'json!nuke/data/dummy_layout.json',
'text!nuke/demo.html'
], function( $, ng, dummyModel, dummyLayout, htmlDemoTemplate ) {
'use strict';
var module = ng.module( 'NukeDemoApp', [ 'nbe' ] )
.run( [ '$templateCache', function( $templateCache ) {
$templateCache.put( 'lib/demo.html', htmlDemoTemplate );
} ] );
///////////////////////////////////////////////////////////////////////////////////////////////////////////
function NukeDemoController( $scope, $timeout ) {
$scope.model = dummyModel;
$scope.layout = dummyLayout;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
module.controller( 'NukeDemoController', [ '$scope', '$timeout', NukeDemoController ] );
///////////////////////////////////////////////////////////////////////////////////////////////////////////
return module;
} );
| x1B/nbe | examples/nuke/lib/NukeDemoController.js | JavaScript | mit | 998 |
module Editor::Controllers::Document
class Export
include Editor::Action
include ::Noteshare::Core::Document
expose :document, :active_item
def call(params)
@active_item = 'editor'
@document = DocumentRepository.find params[:id]
ContentManager.new(@document).export
redirect_to "/document/#{params[:id]}"
end
end
end
| jxxcarlson/noteshare | apps/editor/controllers/document/export.rb | Ruby | mit | 368 |
Rethinker
=========
Rethinker offers a minimalist ActiveRecord-like API service layer for [RethinkDB](www.rethinkdb.com), the main focus is to simplify the relational queries for has-one, has-many, many-many relationships, with filters, and nested relational query support.
#Install
````
npm install rethinker
````
#Running Tests
Ensure that RethinkDB is [installed correctly](http://www.rethinkdb.com/docs/install/), and it's listening on port 28015. Then run the tests with
````
npm test
````
#Getting started
Let's assume we have the following entries and their relationships in our model:
A onlne course can be composed by many video lectures, which can be either be public or private, and a course is enrolled by many students.
And we would like to query the following:
- All courses along with their private lectures, with video related data if it's available
- All students with email ending in '@institution.org', along with their enrolled courses
##1. Initialize rethinker with database connection string
````javascript
var Rethinker = require('rethinker').init({
host: 'localhost',
port: 28015,
db: 'test',
pool: { // optional settings for pooling (further reference: https://github.com/coopernurse/node-pool)
max: 100,
min: 0,
log: false,
idleTimeoutMillis: 30000,
reapIntervalMillis: 15000
}
})
````
##2. Initialize services
````javascript
var LecturesService = Rethinker.extend({
modelName: 'Lecture',
tableName: 'lectures', // optional, by default it takes the modelName, lowercase it, and make it plural
relations: {
hasOne: {
course: { //for simplicity, 'has one course' is the same as 'belongsTo a course'
on: 'courseId', // attribute defined on the 'lectures' table
from: 'Course'
},
video: {
on: 'videoId',
from: 'Video'
}
}
}
});
var CoursesService = Rethinker.extend({
modelName: 'Course',
relations: {
hasMany: {
videoLectures: {
on: 'courseId',
from: 'Lecture',
filter : function(lecture){ // this will be used for 'filter' method in the rethinkdb API
return lecture.ne(null);
}
},
students: {
on: ['courseId', 'studentId'],
through: 'courses_students', //table 'courses_students' has to be created manually for now
from: 'Student'
}
},
hasOne: {
privateLecture: {
on: 'courseId',
from: 'Lecture',
filter: {
private: true
}
}
}
}
});
var StudentsService = Rethinker.extend({
modelName: 'Student',
relations: {
hasMany: {
'enrolledCourses': {
on: ['studentId', 'courseId'],
through: {
tableName: 'courses_students',
filter: {
enrolled: true
}
},
from: 'Course'
}
}
}
});
var VideosService = Rethinker.extend({
modelName: 'Video',
})
var lecturesService = new LecturesService(),
coursesService = new CoursesService(),
studentsService = new StudentsService(),
videosService = new VideosService();
````
##3. Querying data
#####All courses along with their private lectures ordered by createTime, with video related data if it's available
````
coursesService.findAllCourse(null, {
with : {
related : 'privateLecture',
orderBy : 'createTime desc',
with : 'video'
}
})
//Sample result
[{
id : '0f5a54ea-dba3-4eda-b44f-faf17ab1c9e4',
title : "Course I",
privateLecture : {
courseId : '0f5a54ea-dba3-4eda-b44f-faf17ab1c9e4',
private : true,
createTime : 1394630809686,
videoId : '400693be-de3d-4f41-80d3-86f58eb26cc6'
video : {
id : '400693be-de3d-4f41-80d3-86f58eb26cc6',
url : 'path/video1.mp4'
}
}
},
...
]
````
#####All students with email ending in '@institution.org', along with their enrolled courses
````
studentsService.findAllStudent(function(studentRow){
return studentRow('email').match('@institution.org')
}, {with : 'enrolledCourses'})
//Sample results
[{
name : "Khanh Luc",
email : "khanh@institution.org",
enrolledCourses : [{
id : "0f5a54ea-dba3-4eda-b44f-faf17ab1c9e4"
title : "Course I",
},
...
]
}
....
]
````
#CRUD operations
By initializing the service layer as:
```
var CoursesService = Rethinker.extend({modelName : 'Course'})
```
Rethinker adds the following methods to `CoursesService.prototype`
###Create
```
CoursesService.prototype.createCourse([jsonData, options]) -> Promise
```
The `options` argument is optional. It can be an object with the fields:
- `validate` : whether to call validation method on saving the data (default = true)
- `returnVals` : whether or not to return the saved value, it also supports multiple insert (default = true)
````javascript
//Example
var coursesService = CoursesService.getService(); // returns singleton instance of coursesService
coursesService.createCourse({ // insert a single course data
title : "Physics I"
}).then(function(course){
//course : {id: ... , title : 'Physics I'}
})
coursesService.createCourse([ // insert multiple courses data
{ title : "Physics II"},
{ title : "Physics III"}
]).then(function(courses){
//course : [{id: ... , title : 'Physics II'}, {id: ... , title : 'Physics III'}]
})
````
###Retrieve
```
CoursesService.prototype.findCourse([queryCriteria, options]) -> Promise
CoursesService.prototype.findAllCourse([queryCriteria, options]) -> Promise
```
The `queryCriteria` can be set as either object, function or string:
- `object/function`: the [filter](http://www.rethinkdb.com/api/javascript/#filter) method is invoked to query the data
- `string`: when options.index is not set, the value is treated as primary key, otherwise [getAll](http://www.rethinkdb.com/api/javascript/#getAll) method is invoked to query the data
In order to query all the data in the table, the `queryCriteria` argument can be set to `null` in `findAllCourses` method
The `options` argument is optional. It can be an object with the fields:
- `index` : same index value to be passed to the API
- `orderBy` : same as [orderBy](http://www.rethinkdb.com/api/javascript/#orderBy), with a minor syntax difference: `orderBy: r.desc('createTime')` can be written as `orderBy: 'createTime desc'`
- `fields` : same as [pluck](http://www.rethinkdb.com/api/javascript/#with_fields), it also can be provided with an array of field names: `fields : ['id', 'title', 'createTitle']`
- `with` : can be set as either string, array, or object
- `string` : name of the relationship previously defined
- `array` : an array of relational query options,
- `object` : used when need to apply some filtering or query nested relational data
- `related` : name of the relationship relative to the resulting queried data
- `filter` : filter the results using [filter](http://www.rethinkdb.com/api/javascript/#filter)
- `orderBy` : order the resulting relational data
- `fields` : pluck fields from the resulting relational data
- `with` : in case further nested relational data need to be fetched, same options above are also applied
````javascript
//Example
var lecturesService = LecturesService.getService(), // returns singleton instance of lecturesService
coursesService = CoursesService.getService();
lecturesService.findLecture('143ef66b-58fd-41d0-b019-30818841699f') // find lecture by id
lecturesService.findLecture(user.id, {index : 'userId'}) // retrieve a single lecture by secondary index 'userId'
lecturesService.findLecture({title : "Lecture I"}, {fields : 'title'}) // find lecture's title by title
lecturesService.findAllLecture(function(lecture){
return lecture.hasFields('videoId')
}, {orderBy : 'title desc'}) // find all lectures that has the videoId attribute, ordered by title
coursesService.findAllCourse(null, { // find all the courses with enrolled students, and private video lectures ordered by title
with : ['students', {
related : 'lectures',
filter : {
private : true
},
orderBy : 'title',
with : 'video'
}
]
}).then(function(courses){
/*
courses : [
{
id : '..',
title : 'Physics I',
lectures : [{ id: ..., title : 'Lecture I', private : true, videoId : ..., video : {...} }...],
students : [{ ... }]
},
...
]
*/
})
````
###Update
```
CoursesService.prototype.updateCourse([jsonData, queryCriteria, options]) -> Promise
CoursesService.prototype.updateAllCourse([jsonData, queryCriteria, options]) -> Promise
```
The `jsonData` is the data to be updated, `queryCriteria` and `options` are the same ones described in [Retrieve section](#retrieve), with additional options: `validate`, `returnVals` described in the [Create section](#create)
````javascript
//Example
var videosService = VideosService.getService(); // returns singleton instance of videosService
videosService.updateVideo({url : "path/newName.mp4"}, '3e3a00a1-7d5c-4ed3-9a10-7494d81919eb').then(function(){ // update video by it's primary key
}).then(function(video){
// video : video json data with updated values
})
videosService.updateAllVideo({url : "path/newName.mp4"}, req.user.id, {index : 'userId'}) // update all user's videos
.then(function(videos){
//returns an array of updated video values
})
````
###Delete
```
CoursesService.prototype.deleteCourse([queryCriteria, options]) -> Promise
```
`queryCriteria` and `options` are the same ones described in [Retrieve section](#retrieve)
````javascript
//Example
coursesService.findCourse({title : 'Physics I'})
.then(function(course){
return lecturesService.deleteLecture(course.id, {index : 'courseId'}) // delete all lectures in 'Physics I'
})
coursesService.deleteCourse() // delete all courses
````
#Additional methods
Also the following additional methods are available, all of them return promise
````
CoursesService.prototype.validateCourse([jsonData]) -> Promise // return false to cancel the persistence task
CoursesService.prototype.beforeCreateCourse([jsonData]) -> Promise // return false to cancel the insert task
CoursesService.prototype.beforeUpdateCourse([jsonData]) -> Promise // return false to cancel the update task
CoursesService.prototype.beforeSaveCourse([jsonData]) -> Promise // return false to cancel the persistence task
CoursesService.prototype.afterCreateCourse([jsonData]) -> Promise
CoursesService.prototype.afterUpdateCourse([jsonData]) -> Promise
CoursesService.prototype.existCourse([jsonData]) -> Promise
````
#Extend default methods
Each instance of Rethinker exposes the following attributes/methods that allow to build a complex queries more easily:
- `r` : exposes the [rethinkdb API](http://www.rethinkdb.com/api/javascript/#r)
- `table` : exposes the [table](http://www.rethinkdb.com/api/javascript/#table) instance, takes the this.tableName to initialize the `r.table(this.tableName)`
- `db` : expose the DB instance with the [run](http://www.rethinkdb.com/api/javascript/#run) method
- `buildQuery` : ` function buildQuery(queryCriteria, opts, tableName) -> Promise `
````javascript
OrdersService.prototype.someOtherBusinessLogics ...
OrdersService.prototype.findAllOrder = function (queryData, opts, filters) { // override the default findAll method to support extra filter options
!opts && (opts = {});
!filters && (filters = {});
var orderQuery = filters.q || "",
query = this.buildQuery(queryData, _.merge({orderBy: [filters.sort, filters.order].join(' ')}, opts));
if (orderQuery.length > 0) {
query = query.filter(function (order) {
return order('orderId').match(orderQuery)
.or(order('code').eq(orderQuery))
.or(order('user')('name').match(orderQuery))
.or(order('user')('email').match(orderQuery))
.or(order('user')('address').match(orderQuery));
});
}
return this.db.run(query);
};
````
Rethinker also exposes a `DB` instance, basically it wraps around the [run](http://www.rethinkdb.com/api/javascript/#run) method using pooling and returns a promise
````javascript
var r = require('rethinkdb'),
DB = require('rethinker').DB,
db = new DB({
host: 'localhost',
port: 28015,
db: 'test',
pool: { // optional settings for pooling (further reference: https://github.com/coopernurse/node-pool)
max: 100,
min: 0,
idleTimeoutMillis: 30000,
reapIntervalMillis: 15000
}
});
db.run(r.tableCreate('courses_students')).then(function(result){
});
````
#Save relational data
Currently it only supports saving has-one relationships
````javascript
var BookingService = Rethinker.extend({
modelName : 'Booking',
relations : {
hasOne : {
activeOrder : {
on : 'bookingId',
from : 'Order',
filter : {
active : true
}
sync : true
},
completedOrder : {
on : 'bookingId',
from : 'Order',
filter : {
active : false,
completed : true
}
sync : 'readOnly'
}
}
}
});
OrdersService = Rethinker.extend({
modelName : 'Order'
}
})
````
The `sync` property in each `relation` declaration is used to specify whether or not to save those related data.
When inserting the following data to the database:
````
var bookingService = new BookingService();
bookingService.createBooking({
date : new Date(),
userId : req.user.id,
activeOrder : {
active : true,
completed : false
},
completedOrder : {
active : false,
completed : true
}
});
````
It will generate the following data in 'booking' table and the 'orders' table:
````javascript
//booking table
{
id : 'b0de0baa-5028-4da4-ae08-456b1c0d7239'
date : ...
userId : ..
}
//orders table
{
id : ...
active : true,
completed : false,
bookingId : 'b0de0baa-5028-4da4-ae08-456b1c0d7239'
}
````
Notice that in order to avoid data duplicity, the `activeOrder`, and `completedOrder` attributes are not saved in the booking table. Also in the orders table, only the `activeOrder` is saved since it has the property `sync : true`
Please refer the [test](https://github.com/weisuke/rethinker/blob/master/test/test.js) file for further usage example of this option.
#FAQ
##Is this an ORM?
Not quite so, the main intend is to offer a wrapper around the official API, placing the main emphasis on querying relational (nested relational) data with less code, it's basically a mixin that decorates methods in a class prototype chain. If you are looking for fully featured ORM solution, there are couple of alternatives: [Thinky](http://thinky.io/), [Reheat](http://reheat.codetrain.io/)
##Does this offer validation layer?
Personally i use the `validate` hook along with [express-validator](https://github.com/chriso/validator.js) library to validate the incoming data manually, might consider to add a validation layer in the future releases.
##Can the API be simplified?
Like instead of `coursesService.findAllCourse`, can't it just be `courses.findAll`?
Sure thing, it's just my personal preference, when i'm refactoring, finding 'findAllCourse' usage is a lot more easier, and less error prone than just 'findAll', will consider to add an extra option for this.
##What version of RethinkDB supports?
As RethinkDB hasn't reach the LTS release yet, use of latest version of RethinkDB would be recommended.
| weisuke/rethinker | README.md | Markdown | mit | 16,016 |
---
title: chap3
---
* content
{:toc}
## 序言
* technique的地位
就像打高尔夫球需要不断练习挥杆动作basic swing,然后再练习其他技巧那样
BP就是我们的basic swing,即Learning的foundation,然后我们就得学习a suite of techniques用来improve我们的implemention
* 学习各种technique的方法:如何入门
available techniques 是非常多的,最好的入门方法就是,先对最重要的那些technique来一个in-depth study
理由:Mastering those important techniques一方面是因为这些technique很重要,另一方面是因为这些important technique能够加深我们对于NN中的问题的理解,因为这些technique就是为这些问题准备的嘛。
然后其他technique就可以在需要的时候去pick up啦
## The cross-entropy cost function
* 学习的理想情况:犯了错误更容易学习
就像学钢琴一样,你弹错了,有人指出来了,你改正了,很完美的一个学习流程哈
因此我们也期望NN能够learn fast from their errors,但对于输出层sigmoid+quadratic cost的组合来说,有一个很明显的缺陷,就是error大(作者给的例子就是,一个很简单的一个neuron的例子,学习一个w和b使得输出为0,此处error大指的是,初始化的w和b特别大,因此输出严重偏离0)的时候还没有error小(在此例子中,初始w和b都较小,因此error较小)的时候学的快,这是因为:
$$\begin{eqnarray}
\frac{\partial C}{\partial w} & = & (a-y)\sigma'(z) x = a \sigma'(z) \tag{55} \\
\frac{\partial C}{\partial b} & = & (a-y)\sigma'(z) = a \sigma'(z),
\tag{56}\end{eqnarray}$$
(注:上式中y为0,这个是作者给的例子即目标输出为0的情况,作者通过一个单neuron的例子来说明问题,实际上很多探索都是靠特殊情况或者说是简化后的问题来进行的,这是个通用的研究方法,一定要好好感受)
因此,当$z$过大或过小的时候$ \sigma'(z)$就会接近0,因此每次$w$和$b$更新就很小了,造成学习速率很慢( the problem of learning slowdown) 。
(注, $z$过大或过小就是, neuron saturation)
* 引入cross-entropy cost function
对于以上问题,一种解决方法就是精心设计一个新的cost function,将 $ \sigma'(z)$干掉,例如对于 $b$的更新:$ \frac{\partial C}{\partial b} = (a-y)\sigma'(z)$,我们期望将其变成 $ \frac{\partial C}{\partial b} = (a-y)$
现在开始探索,由于 $ \frac{\partial C}{\partial b} = \frac{\partial C}{\partial a} \sigma'(z) $,因此新的 cost function应该满足: $ \frac{\partial C}{\partial a} = (a-y) \frac{1}{ \sigma'(z) } = \frac{ a-y }{a(1-a) }= \frac{1}{1-a}-y[ \frac{1 }{a }+ \frac{1 }{1-a }] = \frac{1 }{1-a }= \frac{1-y }{1-a }- \frac{y }{a } $
对$a$积分得:$ \begin{eqnarray}
C = -[y \ln a + (1-y) \ln (1-a)]+ {\rm constant},
\tag{76}\end{eqnarray}$
因此我们就得到了 cross-entropy cost function
$ \begin{eqnarray}
C = -\frac{1}{n} \sum_x \left[y \ln a + (1-y ) \ln (1-a) \right],
\tag{57}\end{eqnarray}$
多个neuron的时候$ \begin{eqnarray} C = -\frac{1}{n} \sum_x
\sum_j \left[y_j \ln a^L_j + (1-y_j) \ln (1-a^L_j) \right].
\tag{63}\end{eqnarray}$
* 这是个reasonable的 cost function么
首先$C$非负,其次,当$a$和$y$接近的时候 $C$比较小,因为, $y=0$时,若我们的$ a \approx 0$那么上式的$ y \ln a$就是0,$ (1-y ) \ln (1-a)$也基本为0; $y=1$时,第二项为0,第一项也基本为0
cross-entropy的标准interpretation是information theory领域的。
可以认为,cross-entropy is a measure of surprise。我们的目标是学习到$x \rightarrow y = y(x)$,但实际上学习到的是$x \rightarrow a = a(x)$,其实 cross-entropy就是衡量我们学习到的平均意义上的surprise。
## Softmax
* 引入 softmax layer
应对the problem of learning slowdown,除了改变cost function之外,也可以改变output neuron,即采用softmax layers of neurons:$ \begin{eqnarray}
a^L_j = \frac{e^{z^L_j}}{\sum_k e^{z^L_k}},
\tag{78}\end{eqnarray}$
这个layer的特点很明显:所以输出$a^L_j$之和为1,其中任意一个 $a^L_j$增大,都会引起其他 $a^L_j$减小,以维持总和为1,因此可以解释为一个概率分布
* 应对 The learning slowdown problem
首先定义一个 log-likelihood cost function:$ \begin{eqnarray}
C \equiv -\ln a^L_y.
\tag{80}\end{eqnarray}$
对于Minist的例子来说,如果真实label是7,那么上式的cost就是$-\ln a^L_7$
下面我们推导以下$\sigma^L_j= \frac{\partial C}{\partial z^L_j} $,首先求$ \frac{\partial a^L_j}{\partial z^L_k} $,易求得,$ \frac{\partial a^L_j}{\partial z^L_k}= \begin{cases}a^L_j(1-a^L_j) & j= k\\-a^L_ja^L_k & j\neq k\end{cases}$
简化以下: $ \frac{\partial a^L_j}{\partial z^L_k}= a^L_j( \sigma_{jk} -a^L_k)$, 故,$ \frac{\partial C}{\partial z^L_j}= a^L_k-\sigma_{jk}$
上式的意思是,若$j==k$则$\frac{\partial C}{\partial z^L_j}= a^L_j-1$否则就是 $\frac{\partial C}{\partial z^L_j}= a^L_j$
再进一步:若j对应的输出就应该输出1,则对于$k\neq j$的neuron来说,他们对应的输出就应该是0(注意我们采用的是One-hot coding),因此这些index为$k$的neuron的error只能从$ z^L_j$得到,因此上式就有意义了,在以上推导的基础上,我们总结如下:$$ \begin{eqnarray}
\frac{\partial C}{\partial b^L_j} & = & a^L_j-y_j \tag{81} \\
\frac{\partial C}{\partial w^L_{jk}} & = & a^{L-1}_k (a^L_j-y_j)
\tag{82}\end{eqnarray}$$
因此softmax layer+ log-likelihood cost function也能搞定t he learning slowdown problem
当然a sigmoid output layer and cross-entropy, or a softmax output layer and log-likelihood都可以用,区别是后者可以将output解释为概率
* "softmax"名字的由来
对于$ \begin{eqnarray}
a^L_j = \frac{e^{c z^L_j}}{\sum_k e^{c z^L_k}},
\tag{83}\end{eqnarray}$
在$ c \rightarrow \infty $时,若$z ^L_j$最大,则 $a ^L_j$就为1,否则为0,因此 $ c =1 $的 softmax就是max的 a "softened" version of the maximum function
## Overfitting and regularization
* 引言
诺贝尔奖获得者Enrico Fermi曾经说道:"I remember my friend Johnny von Neumann used to say, with four parameters I can fit an elephant, and with five I can make him wiggle his trunk."
这段话的point就是,一个模型的 free parameters越多,它能够descrip的现象就越多
因此,一个复杂的模型即可以和当前data吻合,也可以和其他data吻合,这就意味着,这个model没法对当前的phenomenon 进行 capture any genuine insights,其直接后果就是无法generalize to new situations.
* 初识:过拟合或过训练
这样我们就很为难了,Fermi and von Neumann连对具有4个参数的模型都不满意,而一般的NN可是上万(甚至十亿多个)个参数啊!
构造一个泛化性能不好的模型也是很简单的,对于本书的Minist例子来说,如果不用五万个训练数据,而只用1000个,在使用30个hidden neuron的情况下基本上就会过拟合了,实际训练中会出现这么一种现象,就是在横轴为epoch时,训练误差会一直减小(很有可能训练精度到100%),但test 精度并不会一直增加,而是到了一定的epoch之后就不动了,也就是说,在某一个epoch之后,模型就过拟合或过训练了。
* 应对过拟合
过拟合是NN的一个 major problem。因此为了train effectively,应该想法去detect啥时候过拟合
一种简单的方法就是只观测test 精度的曲线,等它不升了就停止训练;或者当accuracy on the test data and the training data同时stop improving的时候停止训练。
更通常的做法是利用validation_data:当classification accuracy on the validation_data饱和的时候就停止训练,即**early stopping**。当然实际应用中不能立马知道啥时候饱和了,一般继续训练下去才能发现。
(实际上一般使用validation_data选择超参数)
我们来解释一下为啥使用 validation_data而不是用 test_data 来防止过拟合 因为你如果用test_data来决定啥时候停止训练的话,很可能选择的超参数就会 ** 过拟合到test_data ** ,因此一般要用 validation_data选择超参数,用 test_data来评估超参数(即模型),也就是模型的泛化性能。
这个 approach也叫做 hold out方法,即从 training_data中hold out出 validation_data。
(作者提到,这种方法最终也得靠test data来衡量性能,因此有可能我们用 validation_data选择超参数,在 test data上一看性能不行啊,再用 validation_dat选一组超参数吧,这样最后也会过拟合到 test data上,不过这个问题一般不用考虑)
* 初识: Regularization
reducing overfitting的一种方法就是增加训练数据,另一种方法就是减小NN的size,但是large networks have the potential to be more powerful than small networks,因此不采用这种方法了。
当然应对过拟合还有一些techniques,这些technique在有固定数目的训练数据和固定size的NN的情况下也可以用,即regularization techniques。
本节介绍weight decay or L2 regularization,以下就是regularized cross-entropy:$ \begin{eqnarray} C = -\frac{1}{n} \sum_{xj} \left[ y_j \ln a^L_j+(1-y_j) \ln
(1-a^L_j)\right] + \frac{\lambda}{2n} \sum_w w^2.
\tag{85}\end{eqnarray}$
当然quadratic cost也可以正则化:$ \begin{eqnarray} C = \frac{1}{2n} \sum_x \|y-a^L\|^2 +
\frac{\lambda}{2n} \sum_w w^2.
\tag{86}\end{eqnarray}$
理解方法就是将它们看作:$ \begin{eqnarray} C = C_0 + \frac{\lambda}{2n}
\sum_w w^2,
\tag{87}\end{eqnarray}$
正则化的效果就是让NN更prefer那些small weights,如果学习到的一组weight比较大,那么它对应的const部分必须小。因此正则化是一种折衷:between finding small weights and minimizing the original cost function。
偏微分:$$ \begin{eqnarray}
\frac{\partial C}{\partial w} & = & \frac{\partial C_0}{\partial w} +
\frac{\lambda}{n} w \tag{88} \\
\frac{\partial C}{\partial b} & = & \frac{\partial C_0}{\partial b}.
\tag{89}\end{eqnarray} $$
权值更新: $$\begin{eqnarray}
w & \rightarrow & w-\eta \frac{\partial C_0}{\partial
w}-\frac{\eta \lambda}{n} w \tag{91} \\
& = & \left(1-\frac{\eta \lambda}{n}\right) w -\eta \frac{\partial C_0}{\partial w}.
\tag{92} \end{eqnarray} $$
注意:这一项$ 1-\frac{\eta \lambda}{n}$使得权值不断减小,但$ -\eta \frac{\partial C_0}{\partial w}$可能会使其增加。
* Regularization的其它好处
除了reduce overfitting and to increase classification accuracies之外,还能使得每次训练的结果很稳定,即 the regularized runs have provided much more easily replicable results.
原因:对于未正则化的 cost function,权值矢量有可能会变得非常大,非常大的时候呢,这些权值矢量基本上都指着同一个方向(因为changes due to gradient descent only make tiny changes to the direction, when the length is long),这就使得权值矢量无法properly explore the weight space, and consequently harder to find good minima of the cost function.
(**注意:此处的length指的是 $\|\delta^l\|$** ,这个在第五章提到了)
* 为什么正则化可以减少过拟合
一般的解释就是:smaller weights are, in some sense, lower complexity, and so provide a simpler and more powerful explanation for the data, and should thus be preferred。
一种观点就是,in science,我们一般使用simpler explanation,因为simpler explanation一般不会很巧合地出现。对于NN来说,the smallness of the weights 一般意味着the behaviour of the network won't change too much if we change a few random inputs here and there. 即 a regularized network to learn the effects of local noise in the data。而对于有大weights的NN,large weights may change its behaviour quite a bit in response to small changes in the input.
也可以这么理解:正则化使得NN只能学习到一些简单的模型,这些模型只能学习到在data中经常出现的pattern。
但对于这个 "Occam's Razor"的idea,它并不是一个general scientific principle,作者也举出两个反例,证明complex explanations也会是对的。
作者给出三个警告:1 般情况下,很难确定哪个explanation更simple,2 即使能够确定,simplicity也必须谨慎使用 3 the true test of a model is not simplicity,而是其预测新的phenomenon时的效果。
* 正则化背后的boss:泛化性能,即: the question of how we generalize
正则化既不是最好的approach,也不能帮助我们理解generalization到底是怎么回事。
作者相信,在将来,我们可以develop more powerful techniques for regularization in artificial neural networks,使得我们能够generalize well even from small data sets.
实际上,本节的NN参数已经上万了,为啥还没有过拟合呢?
一种解释就是:"the dynamics of gradient descent learning in multilayer nets has a `self-regularization' effect"
* 为啥不对bias进行正则化
一般来说,对 bias进行正则化不影响结果。而且不管bias大不大,基本都不会影响neuron对于input的灵敏度。
而且大bias能够给我们的NN一些灵活性,即使得neuron更容易饱和,, which is sometimes desirable
## Other techniques for regularization
* L1 regularization
即:$ \begin{eqnarray} C = C_0 + \frac{\lambda}{n} \sum_w |w|.
\tag{95}\end{eqnarray}$
偏微分:$ \begin{eqnarray} \frac{\partial C}{\partial
w} = \frac{\partial C_0}{\partial w} + \frac{\lambda}{n} \, {\rm
sgn}(w),
\tag{96}\end{eqnarray} $
权值更新: $ \begin{eqnarray} w \rightarrow w' =
w-\frac{\eta \lambda}{n} \mbox{sgn}(w) - \eta \frac{\partial
C_0}{\partial w},
\tag{97}\end{eqnarray} $
对于L1 regularization,权值只是减去一个接近0的数,而L2 regularization减去的是权值的一定比例。
因此对于小的权值,L1 regularization shrinks the weight much more than L2 regularization. 总的效果就是,L1 regularization只保留一部分在high-importance connections中的权值,而将其余权值强迫变到0.
* Dropout
它不是修改cost function,而是修改网络结构本身。
我们临时性地,随机delete掉hidden neuron的一半,然后forward-propagate,backpropagate the result, also through the modified network.这样搞完a mini-batch of examples之后,再重复以上过程,即先恢复原网络结构,再随机干掉一半,再训练。
这样,学习到的权值即使干掉一半的hidden neurons也能效果好,因此实际运行NN的时候,也应该干掉一半 hidden neurons。
这个东西为啥能够有助于regularization呢?
我们先不管dropout的详细内容。如果我们用通常的方法训练出好多NN,每一个NN都会给出different results。我们一般对其结果平均一下,The reason is that the different networks may overfit in different ways, and averaging may help eliminate that kind of overfitting.
实际上dropout这个东西,就是同时训练好多个NN,因此dropout procedure就是平均了好多个不同的NN。
另外一个解释:这个technique减少了complex co-adaptations of neurons,由于一个neuron无法特别依赖于其他neuron了,它就得learn more robust features that are useful in conjunction with many different random subsets of the other neurons.
Dropout has been especially useful in training large, deep networks, where the problem of overfitting is often acute.
* Artificially expanding the training data
这么做到:making many small rotations of all the MNIST training images,
The general principle is to expand the training data by applying operations that reflect real-world variation.
* 岔个话题:An aside on big data and what it means to compare classification accuracies
比较算法的时候,人们都是在某些数据集上比较的,但对于不同的数据量,不同的算法效果可能差别很大。
In other words, more training data can sometimes compensate for differences in the machine learning algorithm used.
这就给我们提了个醒:很多人总是 focus on finding new tricks to wring out improved performance on standard benchmark data sets.实际上这些trick在更多数据集上很有可能没法用了,因此性能的提升很可能仅仅是历史的偶然(an accident of history)。
he message to take away, especially in practical applications, is that what we want is both better algorithms and better training data.
## Weight initialization
如果将所有的weight和bias都这么初始化:均值为0,标准差为1,那么很有可能会出现一种情况,即大家都很大,使得hidden neuron处于饱和状态,因此权值每次更新都会特别小,学习速率很慢。
对于output neuron来说,我们可以巧妙地设计cost function,但对于hidden neuron来说就没那么好办了,因此应该好好初始化啊。
分析一下初始权值比较大的原因:我们现在只考虑一个hidden neuron的情况,假如input neuron有1000个,简化一下问题,即输入x中有500个为0,500个为1,那么这个hidden neuron 就由 500 个标准差为1 的普通neuron 和 1 个标准差为1 的bias组成,即501个标准差为1的正态分布的随机变量之和组成,其z就服从一个高斯分布,均值为0,标准差为$\sqrt{501} \approx 22.4$
因此,如果将初始权值的标准差设为$1/\sqrt{n_{\rm in}}$,而bais的标准差仍然为1,那么z的均值仍然为0,标准差为:$\sqrt{500/1000+1} \approx1.22$,这样大多数权值就很小了
## Handwriting recognition revisited: the code
作者的code风格很好,单独搞了个cost function的class:
```
class CrossEntropyCost(object):
@staticmethod
def fn(a, y):
return np.sum(np.nan_to_num(-y*np.log(a)-(1-y)*np.log(1-a)))
@staticmethod
def delta(z, a, y):
return (a-y)
```
这个很值得学习嘛。
另外作者很感慨,实现 weight decay的也就一行代码而已,But although the modification is tiny, it has a big impact on results!
>We've spent thousands of words discussing regularization. It's conceptually quite subtle and difficult to understand. And yet it was trivial to add to our program! It occurs surprisingly often that sophisticated techniques can be implemented with small changes to code.
## 选择超参数 How to choose a neural network's hyper-parameters?
* 时运不济,命途多舛
超参数一开始很容易选的不恰当。而且 It's easy to feel lost in hyper-parameter space.
如果花了很长时间都没啥结果,那么,If the situation persists, it damages your confidence. Maybe neural networks are the wrong approach to your problem? Maybe you should quit your job and take up beekeeping?
* 本节目的
help you develop a workflow that enables you to do a pretty good job setting hyper-parameters.
* Broad strategy
首先,你的结果得比trivial算法的结果好(the first challenge is to get any non-trivial learning),即要比随机猜测好。
出了问题怎么办?人生经验:**将问题简化,即将问题规模减小,从而可以更快速地尝试各种参数**
这个简化是随问题而定的,如对于minist数据集来说,我可以只训练0和1这俩数字的image,可以先不包含隐含层,将validation images减少,从而可以更快地进行 monitoring。
你只要试出来的结果比随机猜测好,那么你就有信心继续往下调了。As with many things in life, getting started can be the hardest thing to do.
* Learning rate
我们可以用三个值试一下,画出他们仨对应的cost-epoch曲线,从而选一个合适的范围。
* Use early stopping to determine the number of training epochs
好消息就是, training epochs不依赖于其他超参数。
To implement early stopping we need to say more precisely what it means that the classification accuracy has stopped improving.
但这也不好判断嘛,更好的方法就是best classification accuracy doesn't improve for quite some time。
I suggest using the no-improvement-in-ten rule for initial experimentation, and gradually adopting more lenient rules, as you better understand the way your network trains: no-improvement-in-twenty, no-improvement-in-fifty, and so on.
* Automated techniques
手动调参容易建立对于how neural networks behave的直觉。
当然也有自动调参的,如grid search, Bengio大神12年有一篇paper用来讲achievements and the limitations of grid search,即Random search for hyper-parameter optimization
12年还有一篇用Bayesian来调参的,Practical Bayesian optimization of machine learning algorithms 还有源码: https://github.com/jaberg/hyperopt
* 总结一下
调参的困难在于,每个人对于调参的理解都不太一样,而且不同的人的方法甚至有冲突(many papers setting out (sometimes contradictory) recommendations for how to proceed)
当然还有一些paper进行trick大汇总:Practical recommendations for gradient-based training of deep architectures, by Yoshua Bengio (2012).
Efficient BackProp, by Yann LeCun, Léon Bottou, Genevieve Orr and Klaus-Robert Müller (1998)
还有一本书:Neural Networks: Tricks of the Trade, edited by Grégoire Montavon, Geneviève Orr, and Klaus-Robert Müller.
## Other techniques
* 引言
本章介绍的那些technique啊,一部分原因是因为这些technique的确很重要,但The larger point是让我们熟悉一下NN中那些出现的问题。
* Hessian technique
BP只用了$C(w+\Delta w)$的一阶展开,而 Hessian technique用到了一阶和二阶项。即:$ \begin{eqnarray}
C(w+\Delta w) \approx C(w) + \nabla C \cdot \Delta w +
\frac{1}{2} \Delta w^T H \Delta w.
\tag{105}\end{eqnarray}$
权值更新:$ \begin{eqnarray}
\Delta w = -H^{-1} \nabla C.
\tag{106}\end{eqnarray}$
有一些theoretical and empirical results表明 Hessian technique比BP收敛快。由于采用了cost function的二阶信息,因此 Hessian technique避免了BP的很多不足。但 it's very difficult to apply in practice.其中一个原因就是计算量太大了。
* Momentum-based gradient descent
这个东西inspire自Hessian technique,但不需要计算大矩阵。有梯度信息,也有information about how the gradient is changing.
关键就是增加了一个速度项,使得梯度直接作用于速度项,然后速度项再和权值直接挂钩,即冲量-速度-位置这么一个关系。
## Other models of artificial neuron
现在比sigmoid network效果好的model多的是啊,而且他们还learn faster, generalize better to test data, or perhaps do both.
一种就是tanh (pronounced "tanch") neuron,即$ \begin{eqnarray}
\tanh(z) \equiv \frac{e^z-e^{-z}}{e^z+e^{-z}}.
\tag{110}\end{eqnarray}$
实际上它就是:$ \begin{eqnarray}
\sigma(z) = \frac{1+\tanh(z/2)}{2},
\tag{111}\end{eqnarray}$
即只是将sigmoid给rescale一下,到[-1,1]
* tanh产生的原因
由于sigmoid中权值更新是$a^l_k \delta^{l+1}_j$,由于 $a^l_k$始终为正, 因此 $a^l_k \delta^{l+1}_j$只取决于$ \delta^{l+1}_j$,因此和连接到同一个neuron的权值会同时增大或减小,这样很不爽嘛。
而tanh的好处在于 $a^l_k$可正可负。
* 那种neuron更好?
现在没有证据表明谁学习更快,泛化性能更好
* ReLU:rectified linear neuron or rectified linear unit
即:$ \begin{eqnarray}
\max(0, w \cdot x+b).
\tag{112}\end{eqnarray}$
这哥们儿的梯度就是x,因此永不饱和嘛。
## On stories in neural networks
In many parts of science ,越是简单的现象, it's possible to obtain very solid, very reliable evidence for quite general hypotheses.
但NN有大量的参数,而且参数间还有相互作用,因此很难establish reliable general statements
完全理解NN其实就是tests the limits of the human mind。因此大家都在更新各种结论。
没有人能够investigate all these heuristic explanations in depth.
Does this mean you should reject heuristic explanations as unrigorous, and not sufficiently evidence-based? No! In fact, we need such heuristics to inspire and guide our thinking.
这就和大航海时代一样,不断发现,不断修正认知。
it's more important to explore boldly than it is to be rigorously correct in every step of your thinking.
we need good stories to help motivate and inspire us, and rigorous in-depth investigation in order to uncover the real facts of the matter.
| marquistj13/MyBlog | _collection_ReadingNotes_DeepLearning/Neural_Networks_And_Deep_Learning/5chap3.md | Markdown | mit | 24,742 |
from . import config
from django.shortcuts import render
from mwoauth import ConsumerToken, Handshaker, tokens
def requests_handshaker():
consumer_key = config.OAUTH_CONSUMER_KEY
consumer_secret = config.OAUTH_CONSUMER_SECRET
consumer_token = ConsumerToken(consumer_key, consumer_secret)
return Handshaker("https://meta.wikimedia.org/w/index.php", consumer_token)
def get_username(request):
handshaker = requests_handshaker()
if 'access_token_key' in request.session:
access_key = request.session['access_token_key'].encode('utf-8')
access_secret = request.session['access_token_secret'].encode('utf-8')
access_token = tokens.AccessToken(key=access_key, secret=access_secret)
return handshaker.identify(access_token)['username']
else:
return None
| harej/requestoid | authentication.py | Python | mit | 819 |
using UnityEngine;
using System.Collections;
public class Menu : MonoBehaviour
{
public GUIStyle exit;
public GUIStyle play;
// Use this for initialization
void Start () {
Screen.showCursor = true;
}
// Update is called once per frame
void Update () {
}
void OnGUI() {
if (GUI.Button(new Rect(Screen.width/3,Screen.height/3*2, 250, 150), "", play))
Application.LoadLevel(1);
if (GUI.Button(new Rect(Screen.width/3*2,Screen.height/3*2, 250,150), "", exit))
Application.Quit();
}
}
| lazokin/FollowZeus | Assets/Scripts/Menu.cs | C# | mit | 516 |
package org.gw4e.eclipse.builder.exception;
/*-
* #%L
* gw4e
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2017 gw4e-project
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import org.gw4e.eclipse.builder.GW4EParser;
import org.gw4e.eclipse.builder.Location;
public class SeverityConfigurationException extends BuildPolicyConfigurationException {
/**
*
*/
private static final long serialVersionUID = 1L;
public SeverityConfigurationException(Location location, String message,ParserContextProperties p) {
super(location, message,p);
}
public int getProblemId () {
return GW4EParser.INVALID_SEVERITY;
}
}
| gw4e/gw4e.project | bundles/gw4e-eclipse-plugin/src/org/gw4e/eclipse/builder/exception/SeverityConfigurationException.java | Java | mit | 1,676 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace VSCodeDebug
{
// ---- Types -------------------------------------------------------------------------
public class Message
{
public int id { get; }
public string format { get; }
public dynamic variables { get; }
public dynamic showUser { get; }
public dynamic sendTelemetry { get; }
public Message(int id, string format, dynamic variables = null, bool user = true, bool telemetry = false) {
this.id = id;
this.format = format;
this.variables = variables;
this.showUser = user;
this.sendTelemetry = telemetry;
}
}
public class StackFrame
{
public int id { get; }
public Source source { get; }
public int line { get; }
public int column { get; }
public string name { get; }
public string presentationHint { get; }
public StackFrame(int id, string name, Source source, int line, int column, string hint) {
this.id = id;
this.name = name;
this.source = source;
// These should NEVER be negative
this.line = Math.Max(0, line);
this.column = Math.Max(0, column);
this.presentationHint = hint;
}
}
public class Scope
{
public string name { get; }
public int variablesReference { get; }
public bool expensive { get; }
public Scope(string name, int variablesReference, bool expensive = false) {
this.name = name;
this.variablesReference = variablesReference;
this.expensive = expensive;
}
}
public class Variable
{
public string name { get; }
public string value { get; }
public string type { get; }
public int variablesReference { get; }
public Variable(string name, string value, string type, int variablesReference = 0) {
this.name = name;
this.value = value;
this.type = type;
this.variablesReference = variablesReference;
}
}
public class Thread
{
public int id { get; }
public string name { get; }
public Thread(int id, string name) {
this.id = id;
if (name == null || name.Length == 0) {
this.name = string.Format("Thread #{0}", id);
} else {
this.name = name;
}
}
}
public class Source
{
public string name { get; }
public string path { get; }
public int sourceReference { get; }
public string presentationHint { get; }
public Source(string name, string path, int sourceReference, string hint) {
this.name = name;
this.path = path;
this.sourceReference = sourceReference;
this.presentationHint = hint;
}
}
public class Breakpoint
{
public bool verified { get; }
public int line { get; }
public Breakpoint(bool verified, int line) {
this.verified = verified;
this.line = line;
}
}
// ---- Events -------------------------------------------------------------------------
public class InitializedEvent : Event
{
public InitializedEvent()
: base("initialized") { }
}
public class StoppedEvent : Event
{
public StoppedEvent(int tid, string reasn, string txt = null)
: base("stopped", new {
threadId = tid,
reason = reasn,
text = txt
}) { }
}
public class ExitedEvent : Event
{
public ExitedEvent(int exCode)
: base("exited", new { exitCode = exCode } ) { }
}
public class TerminatedEvent : Event
{
public TerminatedEvent()
: base("terminated") { }
}
public class ThreadEvent : Event
{
public ThreadEvent(string reasn, int tid)
: base("thread", new {
reason = reasn,
threadId = tid
}) { }
}
public class OutputEvent : Event
{
public OutputEvent(string cat, string outpt)
: base("output", new {
category = cat,
output = outpt
}) { }
}
// ---- Response -------------------------------------------------------------------------
public class Capabilities : ResponseBody {
public bool supportsConfigurationDoneRequest;
public bool supportsFunctionBreakpoints;
public bool supportsConditionalBreakpoints;
public bool supportsEvaluateForHovers;
public dynamic[] exceptionBreakpointFilters;
}
public class ErrorResponseBody : ResponseBody {
public Message error { get; }
public ErrorResponseBody(Message error) {
this.error = error;
}
}
public class StackTraceResponseBody : ResponseBody
{
public StackFrame[] stackFrames { get; }
public int totalFrames { get; }
public StackTraceResponseBody(List<StackFrame> frames, int total) {
stackFrames = frames.ToArray<StackFrame>();
totalFrames = total;
}
}
public class ScopesResponseBody : ResponseBody
{
public Scope[] scopes { get; }
public ScopesResponseBody(List<Scope> scps) {
scopes = scps.ToArray<Scope>();
}
}
public class VariablesResponseBody : ResponseBody
{
public Variable[] variables { get; }
public VariablesResponseBody(List<Variable> vars) {
variables = vars.ToArray<Variable>();
}
}
public class ThreadsResponseBody : ResponseBody
{
public Thread[] threads { get; }
public ThreadsResponseBody(List<Thread> ths) {
threads = ths.ToArray<Thread>();
}
}
public class EvaluateResponseBody : ResponseBody
{
public string result { get; }
public int variablesReference { get; }
public EvaluateResponseBody(string value, int reff = 0) {
result = value;
variablesReference = reff;
}
}
public class SetBreakpointsResponseBody : ResponseBody
{
public Breakpoint[] breakpoints { get; }
public SetBreakpointsResponseBody(List<Breakpoint> bpts = null) {
if (bpts == null)
breakpoints = new Breakpoint[0];
else
breakpoints = bpts.ToArray<Breakpoint>();
}
}
// ---- The Session --------------------------------------------------------
public abstract class DebugSession : ProtocolServer
{
private bool _clientLinesStartAt1 = true;
private bool _clientPathsAreURI = true;
public DebugSession()
{
}
public void SendResponse(Response response, dynamic body = null)
{
if (body != null) {
response.SetBody(body);
}
SendMessage(response);
}
public void SendErrorResponse(Response response, int id, string format, dynamic arguments = null, bool user = true, bool telemetry = false)
{
var msg = new Message(id, format, arguments, user, telemetry);
var message = Utilities.ExpandVariables(msg.format, msg.variables);
response.SetErrorBody(message, new ErrorResponseBody(msg));
SendMessage(response);
}
protected override void DispatchRequest(string command, dynamic args, Response response)
{
if (args == null) {
args = new { };
}
try {
switch (command) {
case "initialize":
if (args.linesStartAt1 != null) {
_clientLinesStartAt1 = (bool)args.linesStartAt1;
}
var pathFormat = (string)args.pathFormat;
if (pathFormat != null) {
switch (pathFormat) {
case "uri":
_clientPathsAreURI = true;
break;
case "path":
_clientPathsAreURI = false;
break;
default:
SendErrorResponse(response, 1015, "initialize: bad value '{_format}' for pathFormat", new { _format = pathFormat });
return;
}
}
Initialize(response, args);
break;
case "launch":
Launch(response, args);
break;
case "attach":
Attach(response, args);
break;
case "disconnect":
Disconnect(response, args);
break;
case "next":
Next(response, args);
break;
case "continue":
Continue(response, args);
break;
case "stepIn":
StepIn(response, args);
break;
case "stepOut":
StepOut(response, args);
break;
case "pause":
Pause(response, args);
break;
case "stackTrace":
StackTrace(response, args);
break;
case "scopes":
Scopes(response, args);
break;
case "variables":
Variables(response, args);
break;
case "source":
Source(response, args);
break;
case "threads":
Threads(response, args);
break;
case "setBreakpoints":
SetBreakpoints(response, args);
break;
case "setFunctionBreakpoints":
SetFunctionBreakpoints(response, args);
break;
case "setExceptionBreakpoints":
SetExceptionBreakpoints(response, args);
break;
case "evaluate":
Evaluate(response, args);
break;
default:
SendErrorResponse(response, 1014, "unrecognized request: {_request}", new { _request = command });
break;
}
}
catch (Exception e) {
SendErrorResponse(response, 1104, "error while processing request '{_request}' (exception: {_exception})", new { _request = command, _exception = e.Message });
}
if (command == "disconnect") {
Stop();
}
}
public abstract void Initialize(Response response, dynamic args);
public abstract void Launch(Response response, dynamic arguments);
public abstract void Attach(Response response, dynamic arguments);
public abstract void Disconnect(Response response, dynamic arguments);
public virtual void SetFunctionBreakpoints(Response response, dynamic arguments)
{
}
public virtual void SetExceptionBreakpoints(Response response, dynamic arguments)
{
}
public abstract void SetBreakpoints(Response response, dynamic arguments);
public abstract void Continue(Response response, dynamic arguments);
public abstract void Next(Response response, dynamic arguments);
public abstract void StepIn(Response response, dynamic arguments);
public abstract void StepOut(Response response, dynamic arguments);
public abstract void Pause(Response response, dynamic arguments);
public abstract void StackTrace(Response response, dynamic arguments);
public abstract void Scopes(Response response, dynamic arguments);
public abstract void Variables(Response response, dynamic arguments);
public abstract void Source(Response response, dynamic arguments);
public abstract void Threads(Response response, dynamic arguments);
public abstract void Evaluate(Response response, dynamic arguments);
// protected
protected int ConvertDebuggerLineToClient(int line)
{
return _clientLinesStartAt1 ? line : line - 1;
}
protected int ConvertClientLineToDebugger(int line)
{
return _clientLinesStartAt1 ? line : line + 1;
}
protected string ConvertDebuggerPathToClient(string path)
{
if (_clientPathsAreURI) {
try {
var uri = new System.Uri(path);
return uri.AbsoluteUri;
}
catch {
return null;
}
}
else {
return path;
}
}
protected string ConvertClientPathToDebugger(string clientPath)
{
if (clientPath == null) {
return null;
}
if (_clientPathsAreURI) {
if (Uri.IsWellFormedUriString(clientPath, UriKind.Absolute)) {
Uri uri = new Uri(clientPath);
return uri.LocalPath;
}
Program.Log("path not well formed: '{0}'", clientPath);
return null;
}
else {
return clientPath;
}
}
}
}
| Microsoft/vscode-mono-debug | src/DebugSession.cs | C# | mit | 11,204 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_27) on Thu Jan 23 20:12:05 EST 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.lucene.search.BooleanQuery.TooManyClauses (Lucene 4.6.1 API)</title>
<meta name="date" content="2014-01-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.lucene.search.BooleanQuery.TooManyClauses (Lucene 4.6.1 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/lucene/search/BooleanQuery.TooManyClauses.html" title="class in org.apache.lucene.search">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/lucene/search//class-useBooleanQuery.TooManyClauses.html" target="_top">FRAMES</a></li>
<li><a href="BooleanQuery.TooManyClauses.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.lucene.search.BooleanQuery.TooManyClauses" class="title">Uses of Class<br>org.apache.lucene.search.BooleanQuery.TooManyClauses</h2>
</div>
<div class="classUseContainer">No usage of org.apache.lucene.search.BooleanQuery.TooManyClauses</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/lucene/search/BooleanQuery.TooManyClauses.html" title="class in org.apache.lucene.search">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/lucene/search//class-useBooleanQuery.TooManyClauses.html" target="_top">FRAMES</a></li>
<li><a href="BooleanQuery.TooManyClauses.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| OrlandoLee/ForYou | lucene/lib/lucene-4.6.1/docs/core/org/apache/lucene/search/class-use/BooleanQuery.TooManyClauses.html | HTML | mit | 4,927 |
---
layout: comune
title: San Giuseppe Jato (Sicilia)
---
La pagina dell'albo pretorio del **Comune di San Giuseppe Jato** è questa: [http://156.54.128.62/sgjato](http://156.54.128.62/sgjato)
Adesso puoi seguire le nuove pubblicazioni in albo in due modi dedicati:
* su un canale **Telegram** [https://telegram.me/albopretoriosangiuseppejato](https://telegram.me/albopretoriosangiuseppejato);
* iscrivendoti a un **feed RSS** [http://feeds.feedburner.com/AlbopretorioSanGiuseppeJato](http://feeds.feedburner.com/AlbopretorioSanGiuseppeJato).
| aborruso/albo-pop | _comune/sangiuseppejato.md | Markdown | mit | 546 |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* This is where the magic happens. The Game object is the heart of your game,
* providing quick access to common functions and handling the boot process.
*
* "Hell, there are no rules here - we're trying to accomplish something."
* Thomas A. Edison
*
* @class Phaser.Game
* @constructor
* @param {object} [gameConfig={}] - The game configuration object
*/
Phaser.Game = function (gameConfig) {
/**
* @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
* @readonly
*/
this.id = Phaser.GAMES.push(this) - 1;
/**
* @property {object} config - The Phaser.Game configuration object.
*/
this.config = null;
/**
* @property {object} physicsConfig - The Phaser.Physics.World configuration object.
*/
this.physicsConfig = null;
/**
* @property {string|HTMLElement} parent - The Games DOM parent.
* @default
*/
this.parent = '';
/**
* The current Game Width in pixels.
*
* _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
*
* @property {integer} width
* @readonly
* @default
*/
this.width = 800;
/**
* The current Game Height in pixels.
*
* _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
*
* @property {integer} height
* @readonly
* @default
*/
this.height = 600;
/**
* The resolution of your game. This value is read only, but can be changed at start time it via a game configuration object.
*
* @property {integer} resolution
* @readonly
* @default
*/
this.resolution = 1;
/**
* @property {integer} _width - Private internal var.
* @private
*/
this._width = 800;
/**
* @property {integer} _height - Private internal var.
* @private
*/
this._height = 600;
/**
* @property {boolean} transparent - Use a transparent canvas background or not.
* @default
*/
this.transparent = false;
/**
* @property {boolean} antialias - Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally.
* @default
*/
this.antialias = false;
/**
* @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
* @default
*/
this.preserveDrawingBuffer = false;
/**
* Clear the Canvas each frame before rendering the display list.
* You can set this to `false` to gain some performance if your game always contains a background that completely fills the display.
* @property {boolean} clearBeforeRender
* @default
*/
this.clearBeforeRender = true;
/**
* @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
* @protected
*/
this.renderer = null;
/**
* @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, or Phaser.HEADLESS.
* @readonly
*/
this.renderType = Phaser.AUTO;
/**
* @property {Phaser.StateManager} state - The StateManager.
*/
this.state = null;
/**
* @property {boolean} isBooted - Whether the game engine is booted, aka available.
* @readonly
*/
this.isBooted = false;
/**
* @property {boolean} isRunning - Is game running or paused?
* @readonly
*/
this.isRunning = false;
/**
* @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
* @protected
*/
this.raf = null;
/**
* @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
*/
this.add = null;
/**
* @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
*/
this.make = null;
/**
* @property {Phaser.Cache} cache - Reference to the assets cache.
*/
this.cache = null;
/**
* @property {Phaser.Input} input - Reference to the input manager
*/
this.input = null;
/**
* @property {Phaser.Loader} load - Reference to the assets loader.
*/
this.load = null;
/**
* @property {Phaser.Math} math - Reference to the math helper.
*/
this.math = null;
/**
* @property {Phaser.Net} net - Reference to the network class.
*/
this.net = null;
/**
* @property {Phaser.ScaleManager} scale - The game scale manager.
*/
this.scale = null;
/**
* @property {Phaser.SoundManager} sound - Reference to the sound manager.
*/
this.sound = null;
/**
* @property {Phaser.Stage} stage - Reference to the stage.
*/
this.stage = null;
/**
* @property {Phaser.Time} time - Reference to the core game clock.
*/
this.time = null;
/**
* @property {Phaser.TweenManager} tweens - Reference to the tween manager.
*/
this.tweens = null;
/**
* @property {Phaser.World} world - Reference to the world.
*/
this.world = null;
/**
* @property {Phaser.Physics} physics - Reference to the physics manager.
*/
this.physics = null;
/**
* @property {Phaser.PluginManager} plugins - Reference to the plugin manager.
*/
this.plugins = null;
/**
* @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
*/
this.rnd = null;
/**
* @property {Phaser.Device} device - Contains device information and capabilities.
*/
this.device = Phaser.Device;
/**
* @property {Phaser.Camera} camera - A handy reference to world.camera.
*/
this.camera = null;
/**
* @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
*/
this.canvas = null;
/**
* @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
*/
this.context = null;
/**
* @property {Phaser.Utils.Debug} debug - A set of useful debug utilities.
*/
this.debug = null;
/**
* @property {Phaser.Particles} particles - The Particle Manager.
*/
this.particles = null;
/**
* @property {Phaser.Create} create - The Asset Generator.
*/
this.create = null;
/**
* If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped.
* You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application.
* Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully.
* @property {boolean} lockRender
* @default
*/
this.lockRender = false;
/**
* @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
* @default
* @readonly
*/
this.stepping = false;
/**
* @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects.
* @default
* @readonly
*/
this.pendingStep = false;
/**
* @property {number} stepCount - When stepping is enabled this contains the current step cycle.
* @default
* @readonly
*/
this.stepCount = 0;
/**
* @property {Phaser.Signal} onPause - This event is fired when the game pauses.
*/
this.onPause = null;
/**
* @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
*/
this.onResume = null;
/**
* @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
*/
this.onBlur = null;
/**
* @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
*/
this.onFocus = null;
/**
* @property {boolean} _paused - Is game paused?
* @private
*/
this._paused = false;
/**
* @property {boolean} _codePaused - Was the game paused via code or a visibility change?
* @private
*/
this._codePaused = false;
/**
* The ID of the current/last logic update applied this render frame, starting from 0.
* The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.`
* @property {integer} currentUpdateID
* @protected
*/
this.currentUpdateID = 0;
/**
* Number of logic updates expected to occur this render frame; will be 1 unless there are catch-ups required (and allowed).
* @property {integer} updatesThisFrame
* @protected
*/
this.updatesThisFrame = 1;
/**
* @property {number} _deltaTime - Accumulate elapsed time until a logic update is due.
* @private
*/
this._deltaTime = 0;
/**
* @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame.
* @private
*/
this._lastCount = 0;
/**
* @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented.
* @private
*/
this._spiraling = 0;
/**
* @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap)
* @private
*/
this._kickstart = true;
/**
* If the game is struggling to maintain the desired FPS, this signal will be dispatched.
* The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value.
* @property {Phaser.Signal} fpsProblemNotifier
* @public
*/
this.fpsProblemNotifier = new Phaser.Signal();
/**
* @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? Set to true if you know you need this. You can toggle it on the fly.
*/
this.forceSingleUpdate = true;
/**
* @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched.
* @private
*/
this._nextFpsNotification = 0;
// Parse the configuration object
if (typeof gameConfig !== 'object')
{
throw new Error('Missing game configuration object: ' + gameConfig);
}
this.parseConfig(gameConfig);
this.device.whenReady(this.boot, this);
return this;
};
Phaser.Game.prototype = {
/**
* Parses a Game configuration object.
*
* @method Phaser.Game#parseConfig
* @protected
*/
parseConfig: function (config) {
this.config = config;
if (config['enableDebug'] === undefined)
{
this.config.enableDebug = true;
}
if (config['width'])
{
this._width = config['width'];
}
if (config['height'])
{
this._height = config['height'];
}
if (config['renderer'])
{
this.renderType = config['renderer'];
}
if (config['parent'])
{
this.parent = config['parent'];
}
if (config['transparent'] !== undefined)
{
this.transparent = config['transparent'];
}
if (config['antialias'] !== undefined)
{
this.antialias = config['antialias'];
}
if (config['resolution'])
{
this.resolution = config['resolution'];
}
if (config['preserveDrawingBuffer'] !== undefined)
{
this.preserveDrawingBuffer = config['preserveDrawingBuffer'];
}
if (config['clearBeforeRender'] !== undefined)
{
this.clearBeforeRender = config['clearBeforeRender'];
}
if (config['physicsConfig'])
{
this.physicsConfig = config['physicsConfig'];
}
var seed = [(Date.now() * Math.random()).toString()];
if (config['seed'])
{
seed = config['seed'];
}
this.rnd = new Phaser.RandomDataGenerator(seed);
var state = null;
if (config['state'])
{
state = config['state'];
}
this.state = new Phaser.StateManager(this, state);
},
/**
* Initialize engine sub modules and start the game.
*
* @method Phaser.Game#boot
* @protected
*/
boot: function () {
if (this.isBooted)
{
return;
}
this.onPause = new Phaser.Signal();
this.onResume = new Phaser.Signal();
this.onBlur = new Phaser.Signal();
this.onFocus = new Phaser.Signal();
this.isBooted = true;
PIXI.game = this;
this.math = Phaser.Math;
this.scale = new Phaser.ScaleManager(this, this._width, this._height);
this.stage = new Phaser.Stage(this);
this.setUpRenderer();
this.world = new Phaser.World(this);
this.add = new Phaser.GameObjectFactory(this);
this.make = new Phaser.GameObjectCreator(this);
this.cache = new Phaser.Cache(this);
this.load = new Phaser.Loader(this);
this.time = new Phaser.Time(this);
this.tweens = new Phaser.TweenManager(this);
this.input = new Phaser.Input(this);
this.sound = new Phaser.SoundManager(this);
this.physics = new Phaser.Physics(this, this.physicsConfig);
this.particles = new Phaser.Particles(this);
this.create = new Phaser.Create(this);
this.plugins = new Phaser.PluginManager(this);
this.net = new Phaser.Net(this);
this.time.boot();
this.stage.boot();
this.world.boot();
this.scale.boot();
this.input.boot();
this.sound.boot();
this.state.boot();
if (this.config['enableDebug'])
{
this.debug = new Phaser.Utils.Debug(this);
this.debug.boot();
}
else
{
this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {} };
}
this.showDebugHeader();
this.isRunning = true;
if (this.config && this.config['forceSetTimeOut'])
{
this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']);
}
else
{
this.raf = new Phaser.RequestAnimationFrame(this, false);
}
this._kickstart = true;
if (window['focus'])
{
if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus))
{
window.focus();
}
}
this.raf.start();
},
/**
* Displays a Phaser version debug header in the console.
*
* @method Phaser.Game#showDebugHeader
* @protected
*/
showDebugHeader: function () {
if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner)
{
return;
}
var v = Phaser.VERSION;
var r = 'Canvas';
var a = 'HTML Audio';
var c = 1;
if (this.renderType === Phaser.WEBGL)
{
r = 'WebGL';
c++;
}
else if (this.renderType === Phaser.HEADLESS)
{
r = 'Headless';
}
if (this.device.webAudio)
{
a = 'WebAudio';
c++;
}
if (this.device.chrome)
{
var args = [
'%c %c %c Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665',
'background: #fb8cb3',
'background: #d44a52',
'color: #ffffff; background: #871905;',
'background: #d44a52',
'background: #fb8cb3',
'background: #ffffff'
];
for (var i = 0; i < 3; i++)
{
if (i < c)
{
args.push('color: #ff2424; background: #fff');
}
else
{
args.push('color: #959595; background: #fff');
}
}
console.log.apply(console, args);
}
else if (window['console'])
{
console.log('Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' | http://phaser.io');
}
},
/**
* Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
*
* @method Phaser.Game#setUpRenderer
* @protected
*/
setUpRenderer: function () {
if (this.config['canvas'])
{
this.canvas = this.config['canvas'];
}
else
{
this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true);
}
if (this.config['canvasStyle'])
{
this.canvas.style = this.config['canvasStyle'];
}
else
{
this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
}
if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && !this.device.webGL))
{
if (this.device.canvas)
{
// They requested Canvas and their browser supports it
this.renderType = Phaser.CANVAS;
this.renderer = new PIXI.CanvasRenderer(this);
this.context = this.renderer.context;
}
else
{
throw new Error('Phaser.Game - Cannot create Canvas or WebGL context, aborting.');
}
}
else
{
// They requested WebGL and their browser supports it
this.renderType = Phaser.WEBGL;
this.renderer = new PIXI.WebGLRenderer(this);
this.context = null;
this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false);
this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false);
}
if (this.device.cocoonJS)
{
this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false;
}
if (this.renderType !== Phaser.HEADLESS)
{
this.stage.smoothed = this.antialias;
Phaser.Canvas.addToDOM(this.canvas, this.parent, false);
Phaser.Canvas.setTouchAction(this.canvas);
}
},
/**
* Handles WebGL context loss.
*
* @method Phaser.Game#contextLost
* @private
* @param {Event} event - The webglcontextlost event.
*/
contextLost: function (event) {
event.preventDefault();
this.renderer.contextLost = true;
},
/**
* Handles WebGL context restoration.
*
* @method Phaser.Game#contextRestored
* @private
*/
contextRestored: function () {
this.renderer.initContext();
this.cache.clearGLTextures();
this.renderer.contextLost = false;
},
/**
* The core game loop.
*
* @method Phaser.Game#update
* @protected
* @param {number} time - The current time as provided by RequestAnimationFrame.
*/
update: function (time) {
this.time.update(time);
if (this._kickstart)
{
this.updateLogic(this.time.desiredFpsMult);
// call the game render update exactly once every frame
this.updateRender(this.time.slowMotion * this.time.desiredFps);
this._kickstart = false;
return;
}
// if the logic time is spiraling upwards, skip a frame entirely
if (this._spiraling > 1 && !this.forceSingleUpdate)
{
// cause an event to warn the program that this CPU can't keep up with the current desiredFps rate
if (this.time.time > this._nextFpsNotification)
{
// only permit one fps notification per 10 seconds
this._nextFpsNotification = this.time.time + 10000;
// dispatch the notification signal
this.fpsProblemNotifier.dispatch();
}
// reset the _deltaTime accumulator which will cause all pending dropped frames to be permanently skipped
this._deltaTime = 0;
this._spiraling = 0;
// call the game render update exactly once every frame
this.updateRender(this.time.slowMotion * this.time.desiredFps);
}
else
{
// step size taking into account the slow motion speed
var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps;
// accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals
this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0);
// call the game update logic multiple times if necessary to "catch up" with dropped frames
// unless forceSingleUpdate is true
var count = 0;
this.updatesThisFrame = Math.floor(this._deltaTime / slowStep);
if (this.forceSingleUpdate)
{
this.updatesThisFrame = Math.min(1, this.updatesThisFrame);
}
while (this._deltaTime >= slowStep)
{
this._deltaTime -= slowStep;
this.currentUpdateID = count;
this.updateLogic(this.time.desiredFpsMult);
count++;
if (this.forceSingleUpdate && count === 1)
{
break;
}
else
{
this.time.refresh();
}
}
// detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly)
if (count > this._lastCount)
{
this._spiraling++;
}
else if (count < this._lastCount)
{
// looks like it caught up successfully, reset the spiral alert counter
this._spiraling = 0;
}
this._lastCount = count;
// call the game render update exactly once every frame unless we're playing catch-up from a spiral condition
this.updateRender(this._deltaTime / slowStep);
}
},
/**
* Updates all logic subsystems in Phaser. Called automatically by Game.update.
*
* @method Phaser.Game#updateLogic
* @protected
* @param {number} timeStep - The current timeStep value as determined by Game.update.
*/
updateLogic: function (timeStep) {
if (!this._paused && !this.pendingStep)
{
if (this.stepping)
{
this.pendingStep = true;
}
this.scale.preUpdate();
this.debug.preUpdate();
this.camera.preUpdate();
this.physics.preUpdate();
this.state.preUpdate(timeStep);
this.plugins.preUpdate(timeStep);
this.stage.preUpdate();
this.state.update();
this.stage.update();
this.tweens.update();
this.sound.update();
this.input.update();
this.physics.update();
this.particles.update();
this.plugins.update();
this.stage.postUpdate();
this.plugins.postUpdate();
}
else
{
// Scaling and device orientation changes are still reflected when paused.
this.scale.pauseUpdate();
this.state.pauseUpdate();
this.debug.preUpdate();
}
this.stage.updateTransform();
},
/**
* Runs the Render cycle.
* It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required.
* It then calls the renderer, which renders the entire display list, starting from the Stage object and working down.
* It then calls plugin.render on any loaded plugins, in the order in which they were enabled.
* After this State.render is called. Any rendering that happens here will take place on-top of the display list.
* Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled.
* This method is called automatically by Game.update, you don't need to call it directly.
* Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean.
* Phaser will only render when this boolean is `false`.
*
* @method Phaser.Game#updateRender
* @protected
* @param {number} elapsedTime - The time elapsed since the last update.
*/
updateRender: function (elapsedTime) {
if (this.lockRender)
{
return;
}
this.state.preRender(elapsedTime);
if (this.renderType !== Phaser.HEADLESS)
{
this.renderer.render(this.stage);
this.plugins.render(elapsedTime);
this.state.render(elapsedTime);
}
this.plugins.postRender(elapsedTime);
},
/**
* Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
* Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors!
*
* @method Phaser.Game#enableStep
*/
enableStep: function () {
this.stepping = true;
this.pendingStep = false;
this.stepCount = 0;
},
/**
* Disables core game loop stepping.
*
* @method Phaser.Game#disableStep
*/
disableStep: function () {
this.stepping = false;
this.pendingStep = false;
},
/**
* When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
* This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
*
* @method Phaser.Game#step
*/
step: function () {
this.pendingStep = false;
this.stepCount++;
},
/**
* Nukes the entire game from orbit.
*
* Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins.
*
* Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM
* and resets the PIXI default renderer.
*
* @method Phaser.Game#destroy
*/
destroy: function () {
this.raf.stop();
this.state.destroy();
this.sound.destroy();
this.scale.destroy();
this.stage.destroy();
this.input.destroy();
this.physics.destroy();
this.plugins.destroy();
this.state = null;
this.sound = null;
this.scale = null;
this.stage = null;
this.input = null;
this.physics = null;
this.plugins = null;
this.cache = null;
this.load = null;
this.time = null;
this.world = null;
this.isBooted = false;
this.renderer.destroy(false);
Phaser.Canvas.removeFromDOM(this.canvas);
PIXI.defaultRenderer = null;
Phaser.GAMES[this.id] = null;
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#gamePaused
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
gamePaused: function (event) {
// If the game is already paused it was done via game code, so don't re-pause it
if (!this._paused)
{
this._paused = true;
this.time.gamePaused();
if (this.sound.muteOnPause)
{
this.sound.setMute();
}
this.onPause.dispatch(event);
// Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
if (this.device.cordova && this.device.iOS)
{
this.lockRender = true;
}
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#gameResumed
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
gameResumed: function (event) {
// Game is paused, but wasn't paused via code, so resume it
if (this._paused && !this._codePaused)
{
this._paused = false;
this.time.gameResumed();
this.input.reset();
if (this.sound.muteOnPause)
{
this.sound.unsetMute();
}
this.onResume.dispatch(event);
// Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
if (this.device.cordova && this.device.iOS)
{
this.lockRender = false;
}
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#focusLoss
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
focusLoss: function (event) {
this.onBlur.dispatch(event);
if (!this.stage.disableVisibilityChange)
{
this.gamePaused(event);
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#focusGain
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
focusGain: function (event) {
this.onFocus.dispatch(event);
if (!this.stage.disableVisibilityChange)
{
this.gameResumed(event);
}
}
};
Phaser.Game.prototype.constructor = Phaser.Game;
/**
* The paused state of the Game. A paused game doesn't update any of its subsystems.
* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
* @name Phaser.Game#paused
* @property {boolean} paused - Gets and sets the paused state of the Game.
*/
Object.defineProperty(Phaser.Game.prototype, "paused", {
get: function () {
return this._paused;
},
set: function (value) {
if (value === true)
{
if (this._paused === false)
{
this._paused = true;
this.sound.setMute();
this.time.gamePaused();
this.onPause.dispatch(this);
}
this._codePaused = true;
}
else
{
if (this._paused)
{
this._paused = false;
this.input.reset();
this.sound.unsetMute();
this.time.gameResumed();
this.onResume.dispatch(this);
}
this._codePaused = false;
}
}
});
/**
*
* "Deleted code is debugged code." - Jeff Sickel
*
* ヽ(〃^▽^〃)ノ
*
*/
| vpmedia/phaser2-lite | src/core/Game.js | JavaScript | mit | 31,942 |
# iota
Infix Operators for Test Assertions
## What is this?
When you are writing tests, it's common to want to check a number of properties against a given value.
```clojure
(require '[clojure.test :refer :all]
'[schema.core :as s])
(deftest my-test
(let [response ...]
(is (= (:status response) 200))
(is (= (count (get-in response [:headers "content-length"])) (count "Hello World!")))
(is (= (count (get-in response [:headers "content-type"])) "text/plain;charset=utf-8"))
(is (nil? (s/check s/Str (get-in response [:headers "content-type"]))))
(is (instance? java.nio.ByteBuffer response))
))
```
This can get a bit cumbersome.
__iota__ is a micro-library that provides a single macro, `juxt.iota/given`, that allows you to create triples, each of which expands into a `clojure.test/is` assertion.
```clojure
(require '[clojure.test :refer :all]
'[schema.core :as s]
'[juxt.iota :refer [given]])
(deftest my-test
(given response
:status := 200
:headers :⊃ {"content-length" (count "Hello World!")
"content-type" "text/plain;charset=utf-8"}
[:headers "content-type"] :- s/Str
:body :instanceof java.nio.ByteBuffer))
```
It's a little less typing, which might give you the extra time to add more checks, improving your testing.
## Valid operators
Operator | Meaning
----------------------------------|-------------------
`:=` or `:equals` | is equal to
`:!=` or `:not-equals` | isn't equal to
`:-` or `:conforms` | conforms to schema
`:!-` or `:not-conforms` | doesn't conform to schema
`:?` or `:satisfies` | satifies predicate
`:!?` or `:not-satisfies` | doesn't satisfy predicate
`:#` or `:matches` | matches regex
`:!#` or `:not-matches` | doesn't match regex
`:>` or `:⊃` or `:superset` | is superset of
`:!>` or `:⊅` or `:not-superset` | isn't superset of
`:<` or `:⊂` or `:subset` | is subset of
`:!<` or `:⊄` or `:not-subset` | isn't subset of
`:instanceof` or `:instance` | is instance of
`:!instanceof` or `:not-instance` | isn't instance of
## Valid test clauses
In each of these cases `v` represents the given value.
Test clause | Meaning
---------------|------------------
Keyword | Use the keyword as a function: `(:kw v)`
String | Call `get` on the value with the string: `(get v "x")`
Long | Cast the value to a vector, then look up the index with `get`: `(get (vec v) 5)`
Function | Call the function on the value: `(count v)`
## Paths
The left hand operand of your expressions can be a vector, which acts as a path. A bit like `->` but you can also use strings and numbers as well as keywords and functions. A (contrived) example:
```clojure
(deftest contrived-test
(given {:a {"b" '({} {} {:x 1})}}
[:a "b" 2] := {:x 1}
[:a "b" count] := 3))
```
## Installation
Add the following dependency to your `project.clj` file
```clojure
[juxt/iota "0.2.3"]
```
## Copyright & License
The MIT License (MIT)
Copyright © 2015 JUXT LTD.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| juxt/iota | README.md | Markdown | mit | 4,211 |
#include "pci.h"
#include "pciids.h"
#include "kstdio.h"
#include "heap.h"
#include "ehci.h"
#define headerAddress(bus,dev,func,reg) \
((uint32_t)((((bus) & 0xFF) << 16) | (((dev) & 0x1F) << 11) | \
(((func) & 0x07) << 8) | (((reg) & 0x3F) << 2) | 0x80000000L)) \
uint8_t pci_read_8(int bus, int dev, int function, int reg)
{
uint32_t address = headerAddress(bus, dev, function, reg/4 );
outl(PCI_CONFIG_PORT,address);
return inb(PCI_DATA_PORT + (reg%4));
}
uint16_t pci_read_16(int bus, int dev, int function, int reg)
{
uint32_t address = headerAddress(bus, dev, function, reg/2 );
outl(PCI_CONFIG_PORT,address);
return inw(PCI_DATA_PORT + (reg%2));
}
uint32_t pci_read_32(int bus, int dev, int function, int reg)
{
uint32_t address = headerAddress(bus, dev, function, reg );
outl(PCI_CONFIG_PORT,address);
return inl(PCI_DATA_PORT);
}
void pci_write_8(int bus, int dev, int function, int reg, uint8_t data)
{
uint32_t address = headerAddress(bus, dev, function, reg/4 );
outl(PCI_CONFIG_PORT,address);
return outb(PCI_DATA_PORT + (reg%4), data);
}
void pci_write_16(int bus, int dev, int function, int reg, uint16_t data)
{
uint32_t address = headerAddress(bus, dev, function, reg/2 );
outl(PCI_CONFIG_PORT,address);
return outw(PCI_DATA_PORT + (reg%2), data);
}
void pci_write_32(int bus, int dev, int function, int reg, uint32_t data)
{
uint32_t address = headerAddress(bus, dev, function, reg );
outl(PCI_CONFIG_PORT,address);
return outl(PCI_DATA_PORT, data);
}
void pci_read_device(int bus, int dev, int function, PCI_device_t* device)
{
uint32_t address;
size_t cnt;
for(cnt=0;cnt<64;cnt++)
{
address = headerAddress(bus,dev,function,cnt);
outl(PCI_CONFIG_PORT,address);
device->header[cnt] = inl(PCI_DATA_PORT);
}
}
void pci_device_dump(PCI_device_t* device)
{
for(int i=0;i!=PCI_DEVICE_INFO_TABLE_LEN;i++)
{
PCI_device_info_t* info = &PCI_device_info_table[i];
if(info->vendor_id == device->vendorId &&
info->device_id == device->deviceId)
{
for(int i=0;i!=PCI_VENDOR_INFO_TABLE_LEN;i++)
{
if(PCI_vendor_info_table[i].vendor_id == device->vendorId)
{
kp("\t%2x:%2x %s %s",device->classCode,device->subClassCode,PCI_vendor_info_table[i].vendor_name,info->device_name);
}
}
break;
}
}
}
void pci_read_bar(uint32_t id, uint32_t idx,uint32_t* address,uint32_t* mask)
{
uint32_t reg = 4 + idx;
*address = pci_read_32(PCI_EXTRACT(id),reg);
pci_write_32(PCI_EXTRACT(id),reg,0xffffffff);
*mask = pci_read_32(PCI_EXTRACT(id),reg);
pci_write_32(PCI_EXTRACT(id),reg,*address);
}
void pci_init()
{
kp("PCI Initializing");
PCI_device_t* device = (PCI_device_t*)kmalloc(sizeof(PCI_device_t));
int cnt = 0;
for(int bus = 0;bus!=0xFF;bus++)
{
for(int dev = 0;dev!=32;dev++)
{
for(int func = 0;func!=8;func++)
{
device->header[0] = pci_read_32(bus,dev,func,0);
if(device->vendorId == 0 || device->vendorId == 0xFFFF || device->deviceId == 0xFFFF)
continue;
pci_read_device(bus,dev,func,device);
//pci_device_dump(device);
//ehci_init(PCI_ID(bus,dev,func),device);
cnt++;
}
}
}
}
| zzh8829/OSPP | zos/src/pci.c | C | mit | 3,137 |
module ActiveModelSerializers
module Adapter
class JsonApi
class Relationship
# {http://jsonapi.org/format/#document-resource-object-related-resource-links Document Resource Object Related Resource Links}
# {http://jsonapi.org/format/#document-links Document Links}
# {http://jsonapi.org/format/#document-resource-object-linkage Document Resource Relationship Linkage}
# {http://jsonapi.org/format/#document-meta Document Meta}
def initialize(parent_serializer, serializable_resource_options, association)
serializer = association.serializer
options = association.options
links = association.links
meta = association.meta
@object = parent_serializer.object
@scope = parent_serializer.scope
@association_options = options || {}
@serializable_resource_options = serializable_resource_options
@data = data_for(serializer)
@links = (links || {}).each_with_object({}) do |(key, value), hash|
result = Link.new(parent_serializer, value).as_json
hash[key] = result if result
end
@meta = meta.respond_to?(:call) ? parent_serializer.instance_eval(&meta) : meta
end
def as_json
hash = {}
hash[:data] = data if association_options[:include_data]
links = self.links
hash[:links] = links if links.any?
meta = self.meta
hash[:meta] = meta if meta
hash
end
protected
attr_reader :object, :scope, :data, :serializable_resource_options,
:association_options, :links, :meta
private
def data_for(serializer)
if serializer.respond_to?(:each)
serializer.map { |s| ResourceIdentifier.new(s, serializable_resource_options).as_json }
elsif association_options[:virtual_value]
association_options[:virtual_value]
elsif serializer && serializer.object
ResourceIdentifier.new(serializer, serializable_resource_options).as_json
end
end
end
end
end
end
| sixthedge/cellar | src/totem/api/vendor/active_model_serializers-0.10.2/lib/active_model_serializers/adapter/json_api/relationship.rb | Ruby | mit | 2,158 |
# -*- coding: utf-8 -*-
""" Request Management System - Controllers """
prefix = request.controller
resourcename = request.function
if prefix not in deployment_settings.modules:
session.error = T("Module disabled!")
redirect(URL(r=request, c="default", f="index"))
# Options Menu (available in all Functions' Views)
menu = [
[T("Home"), False, URL(r=request, f="index")],
[T("Requests"), False, URL(r=request, f="req"), [
[T("List"), False, URL(r=request, f="req")],
[T("Add"), False, URL(r=request, f="req", args="create")],
# @ToDo Search by priority, status, location
#[T("Search"), False, URL(r=request, f="req", args="search")],
]],
[T("All Requested Items"), False, URL(r=request, f="ritem")],
]
if session.rcvars:
if "hms_hospital" in session.rcvars:
hospital = db.hms_hospital
query = (hospital.id == session.rcvars["hms_hospital"])
selection = db(query).select(hospital.id, hospital.name, limitby=(0, 1)).first()
if selection:
menu_hospital = [
[selection.name, False, URL(r=request, c="hms", f="hospital", args=[selection.id])]
]
menu.extend(menu_hospital)
if "cr_shelter" in session.rcvars:
shelter = db.cr_shelter
query = (shelter.id == session.rcvars["cr_shelter"])
selection = db(query).select(shelter.id, shelter.name, limitby=(0, 1)).first()
if selection:
menu_shelter = [
[selection.name, False, URL(r=request, c="cr", f="shelter", args=[selection.id])]
]
menu.extend(menu_shelter)
response.menu_options = menu
def index():
""" Module's Home Page
Default to the rms_req list view.
"""
request.function = "req"
request.args = []
return req()
#module_name = deployment_settings.modules[prefix].name_nice
#response.title = module_name
#return dict(module_name=module_name, a=1)
def req():
""" RESTful CRUD controller """
resourcename = request.function # check again in case we're coming from index()
tablename = "%s_%s" % (prefix, resourcename)
table = db[tablename]
# Pre-processor
def prep(r):
response.s3.cancel = r.here()
if r.representation in shn_interactive_view_formats and r.method != "delete":
# Don't send the locations list to client (pulled by AJAX instead)
r.table.location_id.requires = IS_NULL_OR(IS_ONE_OF_EMPTY(db, "gis_location.id"))
#if r.method == "create" and not r.component:
# listadd arrives here as method=None
if not r.component:
table.datetime.default = request.utcnow
table.person_id.default = s3_logged_in_person()
# @ToDo Default the Organisation too
return True
response.s3.prep = prep
# Post-processor
def postp(r, output):
if r.representation in shn_interactive_view_formats:
#if r.method == "create" and not r.component:
# listadd arrives here as method=None
if r.method != "delete" and not r.component:
# Redirect to the Assessments tabs after creation
r.next = r.other(method="ritem", record_id=s3xrc.get_session(prefix, resourcename))
# Custom Action Buttons
if not r.component:
response.s3.actions = [
dict(label=str(T("Open")), _class="action-btn", url=str(URL(r=request, args=["[id]", "update"]))),
dict(label=str(T("Items")), _class="action-btn", url=str(URL(r=request, args=["[id]", "ritem"]))),
]
return output
response.s3.postp = postp
s3xrc.model.configure(table,
#listadd=False, #@todo: List add is causing errors with JS - FIX
editable=True)
return s3_rest_controller(prefix,
resourcename,
rheader=shn_rms_req_rheader)
def shn_rms_req_rheader(r):
""" Resource Header for Requests """
if r.representation == "html":
if r.name == "req":
req_record = r.record
if req_record:
_next = r.here()
_same = r.same()
try:
location = db(db.gis_location.id == req_record.location_id).select(limitby=(0, 1)).first()
location_represent = shn_gis_location_represent(location.id)
except:
location_represent = None
rheader_tabs = shn_rheader_tabs( r,
[(T("Edit Details"), None),
(T("Items"), "ritem"),
]
)
rheader = DIV( TABLE(
TR( TH( T("Message") + ": "),
TD(req_record.message, _colspan=3)
),
TR( TH( T("Time of Request") + ": "),
req_record.datetime,
TH( T( "Location") + ": "),
location_represent,
),
TR( TH( T("Priority") + ": "),
req_record.priority,
TH( T("Document") + ": "),
document_represent(req_record.document_id)
),
),
rheader_tabs
)
return rheader
return None
def ritem():
""" RESTful CRUD controller """
tablename = "%s_%s" % (prefix, resourcename)
table = db[tablename]
s3xrc.model.configure(table, insertable=False)
return s3_rest_controller(prefix, resourcename)
def store_for_req():
store_table = None
return dict(store_table = store_table)
| ptressel/sahana-eden-madpub | controllers/rms.py | Python | mit | 6,228 |
#![crate_name = "rusoto"]
#![crate_type = "lib"]
#![cfg_attr(feature = "unstable", feature(custom_derive, plugin))]
#![cfg_attr(feature = "unstable", plugin(serde_macros))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", allow(cyclomatic_complexity, used_underscore_binding, ptr_arg, suspicious_else_formatting))]
#![allow(dead_code)]
#![cfg_attr(not(feature = "unstable"), deny(warnings))]
//! Rusoto is an [AWS](https://aws.amazon.com/) SDK for Rust.
//! A high level overview is available in `README.md` at https://github.com/rusoto/rusoto.
//!
//! # Example
//!
//! The following code shows a simple example of using Rusoto's DynamoDB API to
//! list the names of all tables in a database.
//!
//! ```rust,ignore
//! use std::default::Default;
//!
//! use rusoto::{DefaultCredentialsProvider, Region};
//! use rusoto::dynamodb::{DynamoDbClient, ListTablesInput};
//!
//! let provider = DefaultCredentialsProvider::new().unwrap();
//! let client = DynamoDbClient::new(provider, Region::UsEast1);
//! let list_tables_input: ListTablesInput = Default::default();
//!
//! match client.list_tables(&list_tables_input) {
//! Ok(output) => {
//! match output.table_names {
//! Some(table_name_list) => {
//! println!("Tables in database:");
//!
//! for table_name in table_name_list {
//! println!("{}", table_name);
//! }
//! },
//! None => println!("No tables in database!"),
//! }
//! },
//! Err(error) => {
//! println!("Error: {:?}", error);
//! },
//! }
extern crate chrono;
extern crate hyper;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate log;
extern crate md5;
extern crate regex;
extern crate ring;
extern crate rustc_serialize;
extern crate serde;
extern crate serde_json;
extern crate time;
extern crate url;
extern crate xml;
pub use credential::{
AwsCredentials,
ChainProvider,
CredentialsError,
EnvironmentProvider,
IamProvider,
ProfileProvider,
ProvideAwsCredentials,
DefaultCredentialsProvider,
DefaultCredentialsProviderSync,
};
pub use region::{ParseRegionError, Region};
pub use request::{DispatchSignedRequest, HttpResponse, HttpDispatchError};
pub use signature::SignedRequest;
mod credential;
mod param;
mod region;
mod request;
mod xmlerror;
mod xmlutil;
mod serialization;
#[macro_use] mod signature;
#[cfg(test)]
mod mock;
#[cfg(feature = "acm")]
pub mod acm;
#[cfg(feature = "cloudhsm")]
pub mod cloudhsm;
#[cfg(feature = "cloudtrail")]
pub mod cloudtrail;
#[cfg(feature = "codecommit")]
pub mod codecommit;
#[cfg(feature = "codedeploy")]
pub mod codedeploy;
#[cfg(feature = "codepipeline")]
pub mod codepipeline;
#[cfg(feature = "cognito-identity")]
pub mod cognitoidentity;
#[cfg(feature = "config")]
pub mod config;
#[cfg(feature = "datapipeline")]
pub mod datapipeline;
#[cfg(feature = "devicefarm")]
pub mod devicefarm;
#[cfg(feature = "directconnect")]
pub mod directconnect;
#[cfg(feature = "ds")]
pub mod ds;
#[cfg(feature = "dynamodb")]
pub mod dynamodb;
#[cfg(feature = "dynamodbstreams")]
pub mod dynamodbstreams;
#[cfg(feature = "ec2")]
pub mod ec2;
#[cfg(feature = "ecr")]
pub mod ecr;
#[cfg(feature = "ecs")]
pub mod ecs;
#[cfg(feature = "emr")]
pub mod emr;
#[cfg(feature = "elastictranscoder")]
pub mod elastictranscoder;
#[cfg(feature = "events")]
pub mod events;
#[cfg(feature = "firehose")]
pub mod firehose;
#[cfg(feature = "iam")]
pub mod iam;
#[cfg(feature = "inspector")]
pub mod inspector;
#[cfg(feature = "iot")]
pub mod iot;
#[cfg(feature = "kinesis")]
pub mod kinesis;
#[cfg(feature = "kms")]
pub mod kms;
#[cfg(feature = "logs")]
pub mod logs;
#[cfg(feature = "machinelearning")]
pub mod machinelearning;
#[cfg(feature = "marketplacecommerceanalytics")]
pub mod marketplacecommerceanalytics;
#[cfg(feature = "opsworks")]
pub mod opsworks;
#[cfg(feature = "route53domains")]
pub mod route53domains;
#[cfg(feature = "s3")]
pub mod s3;
#[cfg(feature = "sqs")]
pub mod sqs;
#[cfg(feature = "ssm")]
pub mod ssm;
#[cfg(feature = "storagegateway")]
pub mod storagegateway;
#[cfg(feature = "swf")]
pub mod swf;
#[cfg(feature = "waf")]
pub mod waf;
#[cfg(feature = "workspaces")]
pub mod workspaces;
/*
#[cfg(feature = "gamelift")]
pub mod gamelift;
#[cfg(feature = "support")]
pub mod support;
*/
| indiv0/rusoto | src/lib.rs | Rust | mit | 4,398 |
w6 w40 w9 w14 w16 w60 w63 w21 w32 QUERY3 w14 w31 w17 w86 w36 w17 w11 w81 w14 w10 QUERY3 w11 w35 w28 w8 w14 w17 w17 <A HREF = page68.html > QUERY1 QUERY2 QUERY3 w18 w40 w7 </A> w16 w10 <A HREF = page68.html > QUERY1 </A> w90 w91 w16 <A HREF = page41.html > w20 QUERY1 w16 </A> w11 w31 w6 QUERY2 w1 w12 w13 w5 w2 w13 w10 w4 w7 w74 w8 QUERY1 w86 w2 w16 w18 w20 w3 w19 w3 QUERY3 w16 w10 w79 w9 w15 w18 w80 w4 w16 w13 w15 w9 w20 w12 <A HREF = page72.html > QUERY1 QUERY2 QUERY3 w18 </A> | mmallett/coms572 | lab1/res/intranet5/page95.html | HTML | mit | 483 |
w5 w7 QUERY3 w76 w25 w16 w1 w30 w5 w3 w98 w7 QUERY1 w80 <A HREF = page97.html > QUERY1 QUERY2 QUERY3 w59 QUERY2 w81 QUERY2 </A> <A HREF = page90.html > QUERY2 w5 w32 </A> w18 <A HREF = page15.html > w21 w3 w97 w8 w4 </A> <A HREF = page71.html > QUERY1 </A> w14 w5 w13 w18 QUERY1 w6 w48 w11 w17 QUERY2 w14 w4 <A HREF = page35.html > QUERY1 QUERY2 QUERY3 QUERY1 w14 </A> w43 w40 QUERY2 w17 w12 w16 QUERY2 w12 w16 w19 w56 w82 <A HREF = page80.html > w5 w17 w12 w15 w34 </A> QUERY2 w2 w91 w11 w20 w13 w15 w98 w1 QUERY1 w12 <A HREF = page88.html > w44 QUERY1 w31 w82 w3 </A> w17 w2 w11 w50 QUERY3 w70 w58 | mmallett/coms572 | lab1/res/intranet5/page42.html | HTML | mit | 601 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../openssl_sys/fn.EVP_PKEY_get1_EC_KEY.html">
</head>
<body>
<p>Redirecting to <a href="../../openssl_sys/fn.EVP_PKEY_get1_EC_KEY.html">../../openssl_sys/fn.EVP_PKEY_get1_EC_KEY.html</a>...</p>
<script>location.replace("../../openssl_sys/fn.EVP_PKEY_get1_EC_KEY.html" + location.search + location.hash);</script>
</body>
</html> | malept/guardhaus | main/openssl_sys/evp/fn.EVP_PKEY_get1_EC_KEY.html | HTML | mit | 425 |
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="layoutclass_pic"><div class="layoutclass_first_pic"><table class="ztable"><tr><th class="ztd1"><b>成語 </b></th><td class="ztd2">侮由自取</td></tr>
<tr><th class="ztd1"><b>典源 </b></th><td class="ztd2"> 此處所列為「<a href="/cgi-bin/cydic/gsweb.cgi?o=dcydic&schfmt=text&gourl=%3De0%26sec%3Dsec1%26op%3Dsid%3D%22CW0000000791%22.%26v%3D-1" class="clink" target=_blank>咎由自取</a>」之典源,提供參考。</font> #<font class="dianuan_mark">《三國志.卷四○.蜀書.劉彭廖李劉魏楊傳》</font><font size=-2 color="#999900"><font class="dianyuanfont"><b><i>1></i></b></font></font><br><font size=4 color="#808080">評曰:「劉封處嫌疑之地,而思防不足以自衛。彭羕、廖立以才拔進,李嚴以幹局達,魏延以勇略任,楊儀以當官顯,劉琰舊仕,並咸貴重。</font>覽其舉措,跡<font size=-2 color="#999900"><font class="dianyuanfont"><b><i>2></i></b></font></font>其規矩<font size=-2 color="#999900"><font class="dianyuanfont"><b><i>3></i></b></font></font>,招禍取咎<font size=-2 color="#999900"><font class="dianyuanfont"><b><i>4></i></b></font></font>,無不自己也。」</font> <br><font class="dianuan_mark2">〔注解〕</font><br></font>
<div class="Rulediv"><font class="english_word">(1)</font> 典故或見於<font class="dianuan_mark"><font class="dianuan_mark">《戰國策.齊策四》</font></font>。</font></div>
<div class="Rulediv"><font class="english_word">(2)</font> 跡:追蹤、探究。</font></div>
<div class="Rulediv"><font class="english_word">(3)</font> 規距:指行為法度、標準。</font></div>
<div class="Rulediv"><font class="english_word">(4)</font> 招禍取咎:招來災禍。</font><font size=4 ></div><br><font class="dianuan_mark2">〔參考資料〕</font><br></font> <font class="dianuan_mark"><font class="dianuan_mark">《戰國策.齊策四》</font></font><br>齊宣王見顏斶,曰:「斶前!」斶亦曰:「王前!」宣王不悅。左右曰:「王,人君也。斶,人臣也。王曰『斶前』,亦曰『王前』,可乎?」斶對曰:「夫斶前為慕勢,王前為趨士。與使斶為趨勢,不如使王為趨士。」王忿然作色曰:「王者貴乎?士貴乎?」對曰:「士貴耳,王者不貴。」……宣王曰:「嗟乎!君子焉可侮哉,寡人自取病耳!及今聞君子之言,乃今聞細人之行,願請受為弟子。且顏先生與寡人游,食必太牢,出必乘車,妻子衣服麗都。」</font></td></tr>
</td></tr></table></div> <!-- layoutclass_first_pic --><div class="layoutclass_second_pic"></div> <!-- layoutclass_second_pic --></div> <!-- layoutclass_pic --></td></tr></table>
| BuzzAcademy/idioms-moe-unformatted-data | all-data/3000-3999/3200-31.html | HTML | mit | 2,962 |
<!DOCTYPE html>
<!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en" dir="ltr">
<!--<![endif]-->
<!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) -->
<!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca -->
<head>
<!-- Title begins / Début du titre -->
<title>
GiltteryStar Technologies Ltd -
Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
</title>
<!-- Title ends / Fin du titre -->
<!-- Meta-data begins / Début des métadonnées -->
<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />
<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />
<!-- EPI-11240 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- MCG-202 -->
<meta content="width=device-width,initial-scale=1" name="viewport">
<!-- EPI-11567 -->
<meta name = "format-detection" content = "telephone=no">
<!-- EPI-12603 -->
<meta name="robots" content="noarchive">
<!-- EPI-11190 - Webtrends -->
<script>
var startTime = new Date();
startTime = startTime.getTime();
</script>
<!--[if gte IE 9 | !IE ]><!-->
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">
<!--<![endif]-->
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">
<!--[if lt IE 9]>
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" />
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script>
<![endif]-->
<!--[if lte IE 9]>
<![endif]-->
<noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript>
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<script>dataLayer1 = [];</script>
<!-- End Google Tag Manager -->
<!-- EPI-11235 -->
<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body class="home" vocab="http://schema.org/" typeof="WebPage">
<!-- EPIC HEADER BEGIN -->
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script>
<!-- End Google Tag Manager -->
<!-- EPI-12801 -->
<span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span>
<ul id="wb-tphp">
<li class="wb-slc">
<a class="wb-sl" href="#wb-cont">Skip to main content</a>
</li>
<li class="wb-slc visible-sm visible-md visible-lg">
<a class="wb-sl" href="#wb-info">Skip to "About this site"</a>
</li>
</ul>
<header role="banner">
<div id="wb-bnr" class="container">
<section id="wb-lng" class="visible-md visible-lg text-right">
<h2 class="wb-inv">Language selection</h2>
<div class="row">
<div class="col-md-12">
<ul class="list-inline mrgn-bttm-0">
<li><a href="nvgt.do?V_TOKEN=1492288524919&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=19499&V_SEARCH.docsStart=19498&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/?_flId?_flxKy=e1s1&estblmntNo=234567041301&profileId=61&_evId=bck&lang=eng&V_SEARCH.showStricts=false&prtl=1&_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li>
</ul>
</div>
</div>
</section>
<div class="row">
<div class="brand col-xs-8 col-sm-9 col-md-6">
<a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a>
</div>
<section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn">
<h2>Search and menus</h2>
<ul class="list-inline text-right chvrn">
<li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li>
</ul>
<div id="mb-pnl"></div>
</section>
<!-- Site Search Removed -->
</div>
</div>
<nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement">
<h2 class="wb-inv">Topics menu</h2>
<div class="container nvbar">
<div class="row">
<ul class="list-inline menu">
<li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li>
<li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li>
<li><a href="https://travel.gc.ca/">Travel</a></li>
<li><a href="https://www.canada.ca/en/services/business.html">Business</a></li>
<li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li>
<li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li>
<li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li>
<li><a href="https://www.canada.ca/en/services.html">More services</a></li>
</ul>
</div>
</div>
</nav>
<!-- EPIC BODY BEGIN -->
<nav role="navigation" id="wb-bc" class="" property="breadcrumb">
<h2 class="wb-inv">You are here:</h2>
<div class="container">
<div class="row">
<ol class="breadcrumb">
<li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li>
<li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li>
<li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li>
</ol>
</div>
</div>
</nav>
</header>
<main id="wb-cont" role="main" property="mainContentOfPage" class="container">
<!-- End Header -->
<!-- Begin Body -->
<!-- Begin Body Title -->
<!-- End Body Title -->
<!-- Begin Body Head -->
<!-- End Body Head -->
<!-- Begin Body Content -->
<br>
<!-- Complete Profile -->
<!-- Company Information above tabbed area-->
<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>
<h1 id="wb-cont">
Company profile - Canadian Company Capabilities
</h1>
<div class="profileInfo hidden-print">
<ul class="list-inline">
<li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&rstBtn.x=" class="btn btn-link">New Search</a> |</li>
<li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">
<input type="hidden" name="lang" value="eng" />
<input type="hidden" name="profileId" value="" />
<input type="hidden" name="prtl" value="1" />
<input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" />
<input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />
<input type="hidden" name="V_SEARCH.depth" value="1" />
<input type="hidden" name="V_SEARCH.showStricts" value="false" />
<input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />
</form></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=19497&V_DOCUMENT.docRank=19498&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492288557906&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567156587&profileId=&key.newSearchLabel=">Previous Company</a></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=19499&V_DOCUMENT.docRank=19500&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492288557906&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567035703&profileId=&key.newSearchLabel=">Next Company</a></li>
</ul>
</div>
<details>
<summary>Third-Party Information Liability Disclaimer</summary>
<p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p>
</details>
<h2>
GiltteryStar Technologies Ltd
</h2>
<div class="row">
<div class="col-md-5">
<h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2>
<p>GiltteryStar Technologies Ltd</p>
<p><a href="mailto:jianzhang_2006@yahoo.com" title="jianzhang_2006@yahoo.com">jianzhang_2006@yahoo.com</a></p>
</div>
<div class="col-md-4 mrgn-sm-sm">
<h2 class="h5 mrgn-bttm-0">Mailing Address:</h2>
<address class="mrgn-bttm-md">
87 Castlethorpe Cres<br/>
NEPEAN,
Ontario<br/>
K2G 5R2
<br/>
</address>
<h2 class="h5 mrgn-bttm-0">Location Address:</h2>
<address class="mrgn-bttm-md">
87 Castlethorpe Cres<br/>
NEPEAN,
Ontario<br/>
K2G 5R2
<br/>
</address>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(613) 225-7215
</p>
<p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>:
(613) 225-7215</p>
</div>
<div class="col-md-3 mrgn-tp-md">
</div>
</div>
<div class="row mrgn-tp-md mrgn-bttm-md">
<div class="col-md-12">
<h2 class="wb-inv">Company Profile</h2>
<br> Software consulting services - Enterprise Application Development<br>
</div>
</div>
<!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> -->
<div class="wb-tabs ignore-session">
<div class="tabpanels">
<details id="details-panel1">
<summary>
Full profile
</summary>
<!-- Tab 1 -->
<h2 class="wb-invisible">
Full profile
</h2>
<!-- Contact Information -->
<h3 class="page-header">
Contact information
</h3>
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Jian
Zhang
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
Data Provider<br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(613) 225-7215
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
zhgchn@yahoo.com
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Company Description -->
<h3 class="page-header">
Company description
</h3>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
541510 - Computer Systems Design and Related Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Alternate Industries (NAICS):
</strong>
</div>
<div class="col-md-7">
541690 - Other Scientific and Technical Consulting Services<br>
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</div>
</div>
</section>
<!-- Products / Services / Licensing -->
<h3 class="page-header">
Product / Service / Licensing
</h3>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Enterprise Application Development<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Business requirements analysis, solution architecture design, application development and deployment<br>
<br>
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Technology Profile -->
<!-- Market Profile -->
<!-- Sector Information -->
<details class="mrgn-tp-md mrgn-bttm-md">
<summary>
Third-Party Information Liability Disclaimer
</summary>
<p>
Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.
</p>
</details>
</details>
<details id="details-panel2">
<summary>
Contacts
</summary>
<h2 class="wb-invisible">
Contact information
</h2>
<!-- Contact Information -->
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Jian
Zhang
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
Data Provider<br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(613) 225-7215
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
zhgchn@yahoo.com
</div>
</div>
</section>
</details>
<details id="details-panel3">
<summary>
Description
</summary>
<h2 class="wb-invisible">
Company description
</h2>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
541510 - Computer Systems Design and Related Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Alternate Industries (NAICS):
</strong>
</div>
<div class="col-md-7">
541690 - Other Scientific and Technical Consulting Services<br>
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</div>
</div>
</section>
</details>
<details id="details-panel4">
<summary>
Products, services and licensing
</summary>
<h2 class="wb-invisible">
Product / Service / Licensing
</h2>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Enterprise Application Development<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Business requirements analysis, solution architecture design, application development and deployment<br>
<br>
</div>
</div>
</section>
</details>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
Last Update Date 2016-03-01
</div>
</div>
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
<!-- End Body Content -->
<!-- Begin Body Foot -->
<!-- End Body Foot -->
<!-- END MAIN TABLE -->
<!-- End body -->
<!-- Begin footer -->
<div class="row pagedetails">
<div class="col-sm-5 col-xs-12 datemod">
<dl id="wb-dtmd">
<dt class=" hidden-print">Date Modified:</dt>
<dd class=" hidden-print">
<span><time>2017-03-02</time></span>
</dd>
</dl>
</div>
<div class="clear visible-xs"></div>
<div class="col-sm-4 col-xs-6">
</div>
<div class="col-sm-3 col-xs-6 text-right">
</div>
<div class="clear visible-xs"></div>
</div>
</main>
<footer role="contentinfo" id="wb-info">
<nav role="navigation" class="container wb-navcurr">
<h2 class="wb-inv">About government</h2>
<!-- EPIC FOOTER BEGIN -->
<!-- EPI-11638 Contact us -->
<ul class="list-unstyled colcount-sm-2 colcount-md-3">
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&from=Industries">Contact us</a></li>
<li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li>
<li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li>
<li><a href="https://www.canada.ca/en/news.html">News</a></li>
<li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li>
<li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li>
<li><a href="http://pm.gc.ca/eng">Prime Minister</a></li>
<li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li>
<li><a href="http://open.canada.ca/en/">Open government</a></li>
</ul>
</nav>
<div class="brand">
<div class="container">
<div class="row">
<nav class="col-md-10 ftr-urlt-lnk">
<h2 class="wb-inv">About this site</h2>
<ul>
<li><a href="https://www.canada.ca/en/social.html">Social media</a></li>
<li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li>
<li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li>
</ul>
</nav>
<div class="col-xs-6 visible-sm visible-xs tofpg">
<a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a>
</div>
<div class="col-xs-6 col-md-2 text-right">
<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>
</div>
</div>
</div>
</div>
</footer>
<!--[if gte IE 9 | !IE ]><!-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script>
<!--<![endif]-->
<!--[if lt IE 9]>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script>
<![endif]-->
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script>
<!-- EPI-10519 -->
<span class="wb-sessto"
data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span>
<script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script>
<!-- EPI-11190 - Webtrends -->
<script src="/eic/home.nsf/js/webtrends.js"></script>
<script>var endTime = new Date();</script>
<noscript>
<div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&WT.js=No&WT.tv=9.4.0&dcssip=www.ic.gc.ca"/></div>
</noscript>
<!-- /Webtrends -->
<!-- JS deps -->
<script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script>
<!-- EPI-11262 - Util JS -->
<script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script>
<!-- EPI-11383 -->
<script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script>
<span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span>
</body></html>
<!-- End Footer -->
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
| GoC-Spending/data-corporations | html/234567110032.html | HTML | mit | 33,187 |
<?php
/**
* Project: Epsilon
* Date: 10/26/15
* Time: 5:30 PM
*
* @link https://github.com/falmar/Epsilon
* @author David Lavieri (falmar) <daviddlavier@gmail.com>
* @copyright 2015 David Lavieri
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
*/
namespace Epsilon\Environment;
defined('EPSILON_EXEC') or die();
use Epsilon\Factory;
use Epsilon\Object\Object;
/**
* Class Cookie
*
* @package Epsilon\Environment
*/
class Cookie extends Object
{
private static $Instance;
private $Cookies;
private $newCookies;
public $Lifespan;
public $Path;
public $Domain;
/**
* Load the active cookies of the current session
*
* @param array $Options
*/
public function __construct($Options = [])
{
parent::__construct($Options);
if (!isset($this->Cookies)) {
$this->Cookies = &$_COOKIE;
}
$this->newCookies = [];
}
/**
* @return Cookie
*/
public static function getInstance()
{
if (!isset(self::$Instance)) {
self::$Instance = new Cookie();
}
return self::$Instance;
}
/**
* Set a cookie
*
* @param string $Key
* @param mixed $Value
* @param int|NULL $Lifespan seconds
*/
function set($Key, $Value, $Lifespan = null)
{
if ($Value === null) {
$Lifespan = time() - 1;
}
$this->newCookies[$Key] = [
'value' => base64_encode($Value),
'lifespan' => $Lifespan
];
$Lifespan = time() + ((is_int($Lifespan)) ? $Lifespan : $this->Lifespan);
if (!Factory::getApplication()->isCLI()) {
setcookie($Key, base64_encode($Value), $Lifespan, $this->Path, $this->Domain);
}
}
/**
* @param $Key
* @return null|string
*/
function get($Key)
{
if (isset($this->newCookies[$Key])) {
$value = $this->newCookies[$Key]['value'];
} elseif (isset($this->Cookies[$Key])) {
$value = $this->Cookies[$Key];
} else {
$value = null;
}
return ($value) ? base64_decode($value) : null;
}
}
| falmar/Epsilon | Libraries/Epsilon/Environment/Cookie.php | PHP | mit | 2,264 |
<!DOCTYPE html>
<!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en" dir="ltr">
<!--<![endif]-->
<!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) -->
<!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca -->
<head>
<!-- Title begins / Début du titre -->
<title>
Industrial Engines Limited -
Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
</title>
<!-- Title ends / Fin du titre -->
<!-- Meta-data begins / Début des métadonnées -->
<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />
<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />
<!-- EPI-11240 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- MCG-202 -->
<meta content="width=device-width,initial-scale=1" name="viewport">
<!-- EPI-11567 -->
<meta name = "format-detection" content = "telephone=no">
<!-- EPI-12603 -->
<meta name="robots" content="noarchive">
<!-- EPI-11190 - Webtrends -->
<script>
var startTime = new Date();
startTime = startTime.getTime();
</script>
<!--[if gte IE 9 | !IE ]><!-->
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">
<!--<![endif]-->
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">
<!--[if lt IE 9]>
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" />
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script>
<![endif]-->
<!--[if lte IE 9]>
<![endif]-->
<noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript>
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<script>dataLayer1 = [];</script>
<!-- End Google Tag Manager -->
<!-- EPI-11235 -->
<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body class="home" vocab="http://schema.org/" typeof="WebPage">
<!-- EPIC HEADER BEGIN -->
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script>
<!-- End Google Tag Manager -->
<!-- EPI-12801 -->
<span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span>
<ul id="wb-tphp">
<li class="wb-slc">
<a class="wb-sl" href="#wb-cont">Skip to main content</a>
</li>
<li class="wb-slc visible-sm visible-md visible-lg">
<a class="wb-sl" href="#wb-info">Skip to "About this site"</a>
</li>
</ul>
<header role="banner">
<div id="wb-bnr" class="container">
<section id="wb-lng" class="visible-md visible-lg text-right">
<h2 class="wb-inv">Language selection</h2>
<div class="row">
<div class="col-md-12">
<ul class="list-inline mrgn-bttm-0">
<li><a href="nvgt.do?V_TOKEN=1492293393711&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=22901&V_SEARCH.docsStart=22900&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn//cache/index2.php?_flId?_flxKy=e1s1&estblmntNo=234567041301&profileId=61&_evId=bck&lang=eng&V_SEARCH.showStricts=false&prtl=1&_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li>
</ul>
</div>
</div>
</section>
<div class="row">
<div class="brand col-xs-8 col-sm-9 col-md-6">
<a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a>
</div>
<section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn">
<h2>Search and menus</h2>
<ul class="list-inline text-right chvrn">
<li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li>
</ul>
<div id="mb-pnl"></div>
</section>
<!-- Site Search Removed -->
</div>
</div>
<nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement">
<h2 class="wb-inv">Topics menu</h2>
<div class="container nvbar">
<div class="row">
<ul class="list-inline menu">
<li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li>
<li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li>
<li><a href="https://travel.gc.ca/">Travel</a></li>
<li><a href="https://www.canada.ca/en/services/business.html">Business</a></li>
<li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li>
<li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li>
<li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li>
<li><a href="https://www.canada.ca/en/services.html">More services</a></li>
</ul>
</div>
</div>
</nav>
<!-- EPIC BODY BEGIN -->
<nav role="navigation" id="wb-bc" class="" property="breadcrumb">
<h2 class="wb-inv">You are here:</h2>
<div class="container">
<div class="row">
<ol class="breadcrumb">
<li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li>
<li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li>
<li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li>
</ol>
</div>
</div>
</nav>
</header>
<main id="wb-cont" role="main" property="mainContentOfPage" class="container">
<!-- End Header -->
<!-- Begin Body -->
<!-- Begin Body Title -->
<!-- End Body Title -->
<!-- Begin Body Head -->
<!-- End Body Head -->
<!-- Begin Body Content -->
<br>
<!-- Complete Profile -->
<!-- Company Information above tabbed area-->
<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>
<h1 id="wb-cont">
Company profile - Canadian Company Capabilities
</h1>
<div class="profileInfo hidden-print">
<ul class="list-inline">
<li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&rstBtn.x=" class="btn btn-link">New Search</a> |</li>
<li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">
<input type="hidden" name="lang" value="eng" />
<input type="hidden" name="profileId" value="" />
<input type="hidden" name="prtl" value="1" />
<input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" />
<input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />
<input type="hidden" name="V_SEARCH.depth" value="1" />
<input type="hidden" name="V_SEARCH.showStricts" value="false" />
<input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />
</form></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=22899&V_DOCUMENT.docRank=22900&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492293397815&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567004774&profileId=&key.newSearchLabel=">Previous Company</a></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=22901&V_DOCUMENT.docRank=22902&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492293397815&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567011447&profileId=&key.newSearchLabel=">Next Company</a></li>
</ul>
</div>
<details>
<summary>Third-Party Information Liability Disclaimer</summary>
<p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p>
</details>
<h2>
Industrial Engines Limited
</h2>
<div class="row">
<div class="col-md-5">
<h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2>
<p>Industrial Engines Limited</p>
<div class="mrgn-tp-md"></div>
<p class="mrgn-bttm-0" ><a href="http://www.industrialengines.ca"
target="_blank" title="Website URL">http://www.industrialengines.ca</a></p>
<p><a href="mailto:iel@industrialengines.ca" title="iel@industrialengines.ca">iel@industrialengines.ca</a></p>
</div>
<div class="col-md-4 mrgn-sm-sm">
<h2 class="h5 mrgn-bttm-0">Mailing Address:</h2>
<address class="mrgn-bttm-md">
121-788 Caldew St<br/>
DELTA,
British Columbia<br/>
V3M 5S2
<br/>
</address>
<h2 class="h5 mrgn-bttm-0">Location Address:</h2>
<address class="mrgn-bttm-md">
121-788 Caldew St<br/>
DELTA,
British Columbia<br/>
V3M 5S2
<br/>
</address>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(604) 525-8529
</p>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(877) 438-6560</p>
<p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>:
(604) 525-0974</p>
</div>
<div class="col-md-3 mrgn-tp-md">
</div>
</div>
<div class="row mrgn-tp-md mrgn-bttm-md">
<div class="col-md-12">
<h2 class="wb-inv">Company Profile</h2>
<br> Industrial Engines Limited was incorporated in 1959 with the
<br>express purpose of producing and marketing engine driven products
<br>for sale in the electrical power generation, industrial and marine
<br>markets in Canada. A steady growth has been achieved since
<br>incorporation and products are now marketed to Distributors,
<br>Original Equipment Manufacturers, Boat Builders, and other users
<br>throughout Western Canada and Internationally.
<br>
<br>The company is located in adequate facilities in South Vancouver
<br>adjacent to the Vancouver International Airport. The buildings
<br>include offices, manufacturing, assembly, servicing, testing,
<br>warehouse and parts distribution.
<br>
<br>The company has an engineering and technical staff which is
<br>capable of designing and developing unique products to meet
<br>special applications and customer needs. Company systems are
<br>fully computerized and supported by an IBM main frame and P.C.
<br>equipment. The working capital position of the company is very
<br>adequate and excellent banking relations are maintained
<br>with the Canadian Imperial Bank of Commerce, Vancouver, B.C.
<br>
<br>Major suppliers of Industrial Engines Limited include Ford Motor
<br>Company, Kubota Canada Ltd., Newage International and Borg
<br>Warner.<br>
</div>
</div>
<!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> -->
<div class="wb-tabs ignore-session">
<div class="tabpanels">
<details id="details-panel1">
<summary>
Full profile
</summary>
<!-- Tab 1 -->
<h2 class="wb-invisible">
Full profile
</h2>
<!-- Contact Information -->
<h3 class="page-header">
Contact information
</h3>
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Abe
Bergler
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
General Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(604) 525-8529
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Ext:
</strong>
</div>
<div class="col-md-7">
338
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(604) 525-0974
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
iel@radiant.net
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Peter
Gordon
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
General Manager<br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(604) 525-8529
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(604) 525-0974
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
iel@industrialengines.ca
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Dennis
Forman
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
General Manager<br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(604) 525-8529
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(604) 525-0974
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
iel@industrialengines.ca
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Company Description -->
<h3 class="page-header">
Company description
</h3>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1959
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
Yes
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
333619 - Other Engine and Power Transmission Equipment Manufacturing
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Manufacturer / Processor / Producer
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Total Sales ($CDN):
</strong>
</div>
<div class="col-md-7">
$1,000,000 to $4,999,999
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Export Sales ($CDN):
</strong>
</div>
<div class="col-md-7">
$1 to $99,999
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
15
</div>
</div>
</section>
<!-- Products / Services / Licensing -->
<h3 class="page-header">
Product / Service / Licensing
</h3>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
GENERATOR SETS, DIESEL ENGINE, AC 50 TO 250KW <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, DIESEL & SEMI-DIESEL, MARINE, SHIPS <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, DIESEL & SEMI-DIESEL, MARINE, BOATS <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, GAS, MARINE, EXC OUTBOARD <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
SHIPS, PARTS, ATTACHMENTS & ACCESSORIES NES <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
GENERATOR SETS, DIESEL ENGINE, AC UNDER 50KW <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, DIESEL, NES, 100 BRAKE HP & UNDER <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, GAS, NES, OVER 11 BHP, TO 50 BHP <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, GAS, NES, OVER 50 BHP <br>
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Technology Profile -->
<!-- Market Profile -->
<h3 class="page-header">
Market profile
</h3>
<section class="container-fluid">
<h4>
Geographic markets:
</h4>
<h5>
Export experience:
</h5>
<ul>
<li>Bangladesh</li>
<li>Japan</li>
<li>United States</li>
<li>Alaska</li>
<li>Florida</li>
<li>Hawaii</li>
<li>Massachusetts</li>
<li>Minnesota</li>
</ul>
<h5>
Actively pursuing:
</h5>
<ul>
<li>Algeria</li>
<li>American Samoa</li>
<li>Australia</li>
<li>Cambodia</li>
<li>Cook Islands</li>
<li>Egypt</li>
<li>Fiji</li>
<li>French Polynesia</li>
<li>Guam</li>
<li>Guinea</li>
<li>Indonesia</li>
<li>Iran, Islamic Republic of</li>
<li>Iraq</li>
<li>Jordan</li>
<li>Korea, Democratic People's Republic of</li>
<li>Korea, Republic of</li>
<li>Lao People's Democratic Republic</li>
<li>Lebanon</li>
<li>Libyan Arab Jamahiriya</li>
<li>Macao</li>
<li>Malaysia</li>
<li>Mauritania</li>
<li>Morocco</li>
<li>New Caledonia</li>
<li>New Zealand</li>
<li>Papua New Guinea</li>
<li>Philippines</li>
<li>Samoa</li>
<li>Saudi Arabia</li>
<li>Singapore</li>
<li>Solomon Islands</li>
<li>Sudan</li>
<li>Syrian Arab Republic</li>
<li>Taiwan</li>
<li>Thailand</li>
<li>Tonga</li>
<li>Tunisia</li>
<li>Vanuatu</li>
<li>Viet Nam</li>
<li>Yemen</li>
<li>California</li>
<li>Oregon</li>
<li>Washington</li>
</ul>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Sector Information -->
<details class="mrgn-tp-md mrgn-bttm-md">
<summary>
Third-Party Information Liability Disclaimer
</summary>
<p>
Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.
</p>
</details>
</details>
<details id="details-panel2">
<summary>
Contacts
</summary>
<h2 class="wb-invisible">
Contact information
</h2>
<!-- Contact Information -->
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Abe
Bergler
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
General Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(604) 525-8529
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Ext:
</strong>
</div>
<div class="col-md-7">
338
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(604) 525-0974
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
iel@radiant.net
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Peter
Gordon
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
General Manager<br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(604) 525-8529
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(604) 525-0974
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
iel@industrialengines.ca
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Dennis
Forman
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
General Manager<br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(604) 525-8529
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(604) 525-0974
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
iel@industrialengines.ca
</div>
</div>
</section>
</details>
<details id="details-panel3">
<summary>
Description
</summary>
<h2 class="wb-invisible">
Company description
</h2>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1959
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
Yes
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
333619 - Other Engine and Power Transmission Equipment Manufacturing
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Manufacturer / Processor / Producer
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Total Sales ($CDN):
</strong>
</div>
<div class="col-md-7">
$1,000,000 to $4,999,999
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Export Sales ($CDN):
</strong>
</div>
<div class="col-md-7">
$1 to $99,999
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
15
</div>
</div>
</section>
</details>
<details id="details-panel4">
<summary>
Products, services and licensing
</summary>
<h2 class="wb-invisible">
Product / Service / Licensing
</h2>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
GENERATOR SETS, DIESEL ENGINE, AC 50 TO 250KW <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, DIESEL & SEMI-DIESEL, MARINE, SHIPS <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, DIESEL & SEMI-DIESEL, MARINE, BOATS <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, GAS, MARINE, EXC OUTBOARD <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
SHIPS, PARTS, ATTACHMENTS & ACCESSORIES NES <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
GENERATOR SETS, DIESEL ENGINE, AC UNDER 50KW <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, DIESEL, NES, 100 BRAKE HP & UNDER <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, GAS, NES, OVER 11 BHP, TO 50 BHP <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
ENGINES, GAS, NES, OVER 50 BHP <br>
</div>
</div>
</section>
</details>
<details id="details-panel6">
<summary>
Market
</summary>
<h2 class="wb-invisible">
Market profile
</h2>
<section class="container-fluid">
<h4>
Geographic markets:
</h4>
<h5>
Export experience:
</h5>
<ul>
<li>Bangladesh</li>
<li>Japan</li>
<li>United States</li>
<li>Alaska</li>
<li>Florida</li>
<li>Hawaii</li>
<li>Massachusetts</li>
<li>Minnesota</li>
</ul>
<h5>
Actively pursuing:
</h5>
<ul>
<li>Algeria</li>
<li>American Samoa</li>
<li>Australia</li>
<li>Cambodia</li>
<li>Cook Islands</li>
<li>Egypt</li>
<li>Fiji</li>
<li>French Polynesia</li>
<li>Guam</li>
<li>Guinea</li>
<li>Indonesia</li>
<li>Iran, Islamic Republic of</li>
<li>Iraq</li>
<li>Jordan</li>
<li>Korea, Democratic People's Republic of</li>
<li>Korea, Republic of</li>
<li>Lao People's Democratic Republic</li>
<li>Lebanon</li>
<li>Libyan Arab Jamahiriya</li>
<li>Macao</li>
<li>Malaysia</li>
<li>Mauritania</li>
<li>Morocco</li>
<li>New Caledonia</li>
<li>New Zealand</li>
<li>Papua New Guinea</li>
<li>Philippines</li>
<li>Samoa</li>
<li>Saudi Arabia</li>
<li>Singapore</li>
<li>Solomon Islands</li>
<li>Sudan</li>
<li>Syrian Arab Republic</li>
<li>Taiwan</li>
<li>Thailand</li>
<li>Tonga</li>
<li>Tunisia</li>
<li>Vanuatu</li>
<li>Viet Nam</li>
<li>Yemen</li>
<li>California</li>
<li>Oregon</li>
<li>Washington</li>
</ul>
</section>
</details>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
Last Update Date 2017-03-28
</div>
</div>
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
<!-- End Body Content -->
<!-- Begin Body Foot -->
<!-- End Body Foot -->
<!-- END MAIN TABLE -->
<!-- End body -->
<!-- Begin footer -->
<div class="row pagedetails">
<div class="col-sm-5 col-xs-12 datemod">
<dl id="wb-dtmd">
<dt class=" hidden-print">Date Modified:</dt>
<dd class=" hidden-print">
<span><time>2017-03-02</time></span>
</dd>
</dl>
</div>
<div class="clear visible-xs"></div>
<div class="col-sm-4 col-xs-6">
</div>
<div class="col-sm-3 col-xs-6 text-right">
</div>
<div class="clear visible-xs"></div>
</div>
</main>
<footer role="contentinfo" id="wb-info">
<nav role="navigation" class="container wb-navcurr">
<h2 class="wb-inv">About government</h2>
<!-- EPIC FOOTER BEGIN -->
<!-- EPI-11638 Contact us -->
<ul class="list-unstyled colcount-sm-2 colcount-md-3">
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&from=Industries">Contact us</a></li>
<li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li>
<li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li>
<li><a href="https://www.canada.ca/en/news.html">News</a></li>
<li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li>
<li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li>
<li><a href="http://pm.gc.ca/eng">Prime Minister</a></li>
<li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li>
<li><a href="http://open.canada.ca/en/">Open government</a></li>
</ul>
</nav>
<div class="brand">
<div class="container">
<div class="row">
<nav class="col-md-10 ftr-urlt-lnk">
<h2 class="wb-inv">About this site</h2>
<ul>
<li><a href="https://www.canada.ca/en/social.html">Social media</a></li>
<li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li>
<li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li>
</ul>
</nav>
<div class="col-xs-6 visible-sm visible-xs tofpg">
<a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a>
</div>
<div class="col-xs-6 col-md-2 text-right">
<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>
</div>
</div>
</div>
</div>
</footer>
<!--[if gte IE 9 | !IE ]><!-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script>
<!--<![endif]-->
<!--[if lt IE 9]>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script>
<![endif]-->
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script>
<!-- EPI-10519 -->
<span class="wb-sessto"
data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span>
<script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script>
<!-- EPI-11190 - Webtrends -->
<script src="/eic/home.nsf/js/webtrends.js"></script>
<script>var endTime = new Date();</script>
<noscript>
<div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&WT.js=No&WT.tv=9.4.0&dcssip=www.ic.gc.ca"/></div>
</noscript>
<!-- /Webtrends -->
<!-- JS deps -->
<script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script>
<!-- EPI-11262 - Util JS -->
<script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script>
<!-- EPI-11383 -->
<script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script>
<span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span>
</body></html>
<!-- End Footer -->
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
| GoC-Spending/data-corporations | html/205762600000.html | HTML | mit | 76,421 |
# Compiler, Flags, Directory Name and Executable Name
CC= g++
CFLAGS= -std=c++11
ODIR= ../obj
# Source codes and objects (Add here new .cpp tests separated by spaces)
SRCS= testPoint.cpp
EXEC= t1
OBJS= $(patsubst %.cpp,$(ODIR)/%.o,$(SRCS))
all: $(EXEC)
# Concatenate objects with your new directory
$(OBJS): | $(ODIR)
# Compile and create objects
$(ODIR)/%.o: %.cpp
$(CC) $(CFLAGS) -c $< -o $@
# Generate the executables
$(EXEC): $(OBJS)
$(CC) $(CFLAGS) $^ -o $@
rm -rf *.settings
# Delete objects, executables and new directories
clean:
rm -rf $(OBJS) $(ODIR) $(EDIR)/* $(EDIR) | marquesm91/TerminalSnake | tests/Makefile | Makefile | mit | 590 |
package org.jabref.gui.openoffice;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import org.jabref.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.logic.l10n.Localization;
import com.jgoodies.forms.builder.ButtonBarBuilder;
import com.jgoodies.forms.builder.FormBuilder;
import com.jgoodies.forms.layout.FormLayout;
/**
* Dialog for adding citation with page number info.
*/
class AdvancedCiteDialog {
private static boolean defaultInPar = true;
private boolean okPressed;
private final JDialog diag;
private final JTextField pageInfo = new JTextField(15);
public AdvancedCiteDialog(JabRefFrame parent) {
diag = new JDialog((JFrame) null, Localization.lang("Cite special"), true);
ButtonGroup bg = new ButtonGroup();
JRadioButton inPar = new JRadioButton(Localization.lang("Cite selected entries between parenthesis"));
JRadioButton inText = new JRadioButton(Localization.lang("Cite selected entries with in-text citation"));
bg.add(inPar);
bg.add(inText);
if (defaultInPar) {
inPar.setSelected(true);
} else {
inText.setSelected(true);
}
inPar.addChangeListener(changeEvent -> defaultInPar = inPar.isSelected());
FormBuilder builder = FormBuilder.create()
.layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref, 4dlu, pref"));
builder.add(inPar).xyw(1, 1, 3);
builder.add(inText).xyw(1, 3, 3);
builder.add(Localization.lang("Extra information (e.g. page number)") + ":").xy(1, 5);
builder.add(pageInfo).xy(3, 5);
builder.padding("10dlu, 10dlu, 10dlu, 10dlu");
diag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
JButton ok = new JButton(Localization.lang("OK"));
JButton cancel = new JButton(Localization.lang("Cancel"));
bb.addButton(ok);
bb.addButton(cancel);
bb.addGlue();
bb.padding("5dlu, 5dlu, 5dlu, 5dlu");
diag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
diag.pack();
ActionListener okAction = actionEvent -> {
okPressed = true;
diag.dispose();
};
ok.addActionListener(okAction);
pageInfo.addActionListener(okAction);
inPar.addActionListener(okAction);
inText.addActionListener(okAction);
Action cancelAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
okPressed = false;
diag.dispose();
}
};
cancel.addActionListener(cancelAction);
builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close");
builder.getPanel().getActionMap().put("close", cancelAction);
}
public void showDialog() {
diag.setLocationRelativeTo(diag.getParent());
diag.setVisible(true);
}
public boolean canceled() {
return !okPressed;
}
public String getPageInfo() {
return pageInfo.getText().trim();
}
public boolean isInParenthesisCite() {
return defaultInPar;
}
}
| tobiasdiez/jabref | src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.java | Java | mit | 3,726 |
//
// GuidExtensions.cs
//
// Author:
// Craig Fowler <craig@csf-dev.com>
//
// Copyright (c) 2015 CSF Software Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace CSF
{
/// <summary>
/// Extension methods for the <c>System.Guid</c> type.
/// </summary>
public static class GuidExtensions
{
#region constants
private const int GUID_BYTE_COUNT = 16;
private static readonly int[] REORDERING_MAP = new[] { 3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15 };
#endregion
#region extension methods
/// <summary>
/// Returns a byte array representing the given <c>System.Guid</c> in an RFC-4122 compliant format.
/// </summary>
/// <remarks>
/// <para>
/// The rationale for this method (and the reason for requiring it) is because Microsoft internally represent the
/// GUID structure in a manner which does not comply with RFC-4122's definition of a UUID. The first three blocks
/// of data (out of 4 total) are stored using the machine's native endianness. The RFC defines that these three
/// blocks should be represented in big-endian format. This does not cause a problem when getting a
/// string-representation of the GUID, since the framework automatically converts to big-endian format before
/// formatting as a string. When getting a byte array equivalent of the GUID though, it can cause issues if the
/// recipient of that byte array expects a standards-compliant UUID.
/// </para>
/// <para>
/// This method checks the architecture of the current machine. If it is little-endian then - before returning a
/// value - the byte-order of the first three blocks of data are reversed. If the machine is big-endian then the
/// bytes are left untouched (since they are already correct).
/// </para>
/// <para>
/// For more information, see https://en.wikipedia.org/wiki/Globally_unique_identifier#Binary_encoding
/// </para>
/// </remarks>
/// <returns>
/// A byte array representation of the GUID, in RFC-4122 compliant form.
/// </returns>
/// <param name='guid'>
/// The GUID for which to get the byte array.
/// </param>
public static byte[] ToRFC4122ByteArray(this Guid guid)
{
return BitConverter.IsLittleEndian? ReorderBytes(guid.ToByteArray()) : guid.ToByteArray();
}
/// <summary>
/// Returns a <c>System.Guid</c>, created from the given RFC-4122 compliant byte array.
/// </summary>
/// <remarks>
/// <para>
/// The rationale for this method (and the reason for requiring it) is because Microsoft internally represent the
/// GUID structure in a manner which does not comply with RFC-4122's definition of a UUID. The first three blocks
/// of data (out of 4 total) are stored using the machine's native endianness. The RFC defines that these three
/// blocks should be represented in big-endian format. This does not cause a problem when getting a
/// string-representation of the GUID, since the framework automatically converts to big-endian format before
/// formatting as a string. When getting a byte array equivalent of the GUID though, it can cause issues if the
/// recipient of that byte array expects a standards-compliant UUID.
/// </para>
/// <para>
/// This method checks the architecture of the current machine. If it is little-endian then - before returning a
/// value - the byte-order of the first three blocks of data are reversed. If the machine is big-endian then the
/// bytes are left untouched (since they are already correct).
/// </para>
/// <para>
/// For more information, see https://en.wikipedia.org/wiki/Globally_unique_identifier#Binary_encoding
/// </para>
/// </remarks>
/// <returns>
/// A GUID, created from the given byte array.
/// </returns>
/// <param name='guidBytes'>
/// A byte array representing a GUID, in RFC-4122 compliant form.
/// </param>
public static Guid FromRFC4122ByteArray(this byte[] guidBytes)
{
return new Guid(BitConverter.IsLittleEndian? ReorderBytes(guidBytes) : guidBytes);
}
#endregion
#region static methods
/// <summary>
/// Copies a byte array that represents a GUID, reversing the order of the bytes in data-blocks one to three.
/// </summary>
/// <returns>
/// A copy of the original byte array, with the modifications.
/// </returns>
/// <param name='guidBytes'>
/// A byte array representing a GUID.
/// </param>
public static byte[] ReorderBytes(byte[] guidBytes)
{
if(guidBytes == null)
{
throw new ArgumentNullException(nameof(guidBytes));
}
else if(guidBytes.Length != GUID_BYTE_COUNT)
{
throw new ArgumentException(Resources.ExceptionMessages.MustBeSixteenBytesInAGuid, nameof(guidBytes));
}
byte[] output = new byte[GUID_BYTE_COUNT];
for(int i = 0; i < GUID_BYTE_COUNT; i++)
{
output[i] = guidBytes[REORDERING_MAP[i]];
}
return output;
}
#endregion
}
}
| csf-dev/CSF.Core | CSF/GuidExtensions.cs | C# | mit | 6,175 |
<?php
/**
* Content wrappers
*
* This template can be overridden by copying it to yourtheme/woocommerce/global/wrapper-start.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see https://docs.woocommerce.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
$template = get_option( 'template' );
switch ( $template ) {
case 'twentyeleven' :
echo '<div id="primary"><div id="content" role="main" class="twentyeleven">';
break;
case 'twentytwelve' :
echo '<div id="primary" class="site-content"><div id="content" role="main" class="twentytwelve">';
break;
case 'twentythirteen' :
echo '<div id="primary" class="site-content"><div id="content" role="main" class="entry-content twentythirteen">';
break;
case 'twentyfourteen' :
echo '<div id="primary" class="content-area"><div id="content" role="main" class="site-content twentyfourteen"><div class="tfwc">';
break;
case 'twentyfifteen' :
echo '<div id="primary" role="main" class="content-area twentyfifteen"><div id="main" class="site-main t15wc">';
break;
case 'twentysixteen' :
echo '<div id="primary" class="content-area twentysixteen"><main id="main" class="site-main" role="main">';
break;
default :
echo '<div id="container"><div id="content" role="main">';
break;
}
| srjwebster/doubletrouble | woocommerce/global/wrapper-start.php | PHP | mit | 1,773 |
//******************************************************************************************************
// App.xaml.cs - Gbtc
//
// Copyright © 2010, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/eclipse-1.0.php
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 09/28/2009 - Mehulbhai P Thakkar
// Generated original version of source code.
//
//******************************************************************************************************
using System;
using System.Text;
using System.Windows;
using Microsoft.Maps.MapControl;
using openPDCManager.ModalDialogs;
using openPDCManager.Utilities;
namespace openPDCManager
{
public partial class App : Application
{
#region [ Properties ]
public string NodeValue { get; set; }
public string NodeName { get; set; }
public string TimeSeriesDataServiceUrl { get; set; }
public string RemoteStatusServiceUrl { get; set; }
public string RealTimeStatisticServiceUrl { get; set; }
public ApplicationIdCredentialsProvider Credentials { get; set; }
#endregion
#region [ Constructor ]
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
}
#endregion
#region [ Application Event Handlers ]
private void Application_Startup(object sender, StartupEventArgs e)
{
if ((e.InitParams != null) && (e.InitParams.ContainsKey("BaseServiceUrl")))
Resources.Add("BaseServiceUrl", e.InitParams["BaseServiceUrl"]);
ApplicationIdCredentialsProvider credentialsProvider = new ApplicationIdCredentialsProvider();
if ((e.InitParams != null) && (e.InitParams.ContainsKey("BingMapsKey")))
credentialsProvider.ApplicationId = e.InitParams["BingMapsKey"];
this.Credentials = credentialsProvider;
this.RootVisual = new MasterLayoutControl();
//Set default system settings if no settings exist.
ProxyClient.SetDefaultSystemSettings(false);
}
private void Application_Exit(object sender, EventArgs e)
{
}
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
//// If the app is running outside of the debugger then report the exception using
//// the browser's exception mechanism. On IE this will display it a yellow alert
//// icon in the status bar and Firefox will display a script error.
//if (!System.Diagnostics.Debugger.IsAttached)
//{
// // NOTE: This will allow the application to continue running after an exception has been thrown
// // but not handled.
// // For production applications this error handling should be replaced with something that will
// // report the error to the website and stop the application.
// e.Handled = true;
// Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
//}
StringBuilder sb = new StringBuilder();
sb.AppendLine("Exception Type: " + e.GetType().ToString());
sb.AppendLine("Error Message: " + e.ExceptionObject.Message);
sb.AppendLine("Stack Trace: " + e.ExceptionObject.StackTrace);
SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Application Error Occured", SystemMessage = sb.ToString(), UserMessageType = MessageType.Error },
ButtonType.OkOnly);
sm.ShowPopup();
}
#endregion
#region [ Methods ]
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
try
{
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
}
catch (Exception)
{
}
}
#endregion
}
} | GridProtectionAlliance/openPDC | Source/Applications/openPDCManager/Silverlight/App.xaml.cs | C# | mit | 4,907 |
# Apollo REST Data Source
This package exports a ([`RESTDataSource`](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-datasource-rest)) class which is used for fetching data from a REST API and exposing it via GraphQL within Apollo Server.
## Documentation
View the [Apollo Server documentation for data sources](https://www.apollographql.com/docs/apollo-server/features/data-sources/) for more details.
## Usage
To get started, install the `apollo-datasource-rest` package:
```bash
npm install apollo-datasource-rest
```
To define a data source, extend the [`RESTDataSource`](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-datasource-rest) class and implement the data fetching methods that your resolvers require. Data sources can then be provided via the `dataSources` property to the `ApolloServer` constructor, as demonstrated in the _Accessing data sources from resolvers_ section below.
Your implementation of these methods can call on convenience methods built into the [RESTDataSource](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-datasource-rest) class to perform HTTP requests, while making it easy to build up query parameters, parse JSON results, and handle errors.
```javascript
const { RESTDataSource } = require('apollo-datasource-rest');
class MoviesAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://movies-api.example.com/';
}
async getMovie(id) {
return this.get(`movies/${id}`);
}
async getMostViewedMovies(limit = 10) {
const data = await this.get('movies', {
per_page: limit,
order_by: 'most_viewed',
});
return data.results;
}
}
```
### HTTP Methods
The `get` method on the [RESTDataSource](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-datasource-rest) makes an HTTP `GET` request. Similarly, there are methods built-in to allow for POST, PUT, PATCH, and DELETE requests.
```javascript
class MoviesAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://movies-api.example.com/';
}
// an example making an HTTP POST request
async postMovie(movie) {
return this.post(
`movies`, // path
movie, // request body
);
}
// an example making an HTTP PUT request
async newMovie(movie) {
return this.put(
`movies`, // path
movie, // request body
);
}
// an example making an HTTP PATCH request
async updateMovie(movie) {
return this.patch(
`movies`, // path
{ id: movie.id, movie }, // request body
);
}
// an example making an HTTP DELETE request
async deleteMovie(movie) {
return this.delete(
`movies/${movie.id}`, // path
);
}
}
```
All of the HTTP helper functions (`get`, `put`, `post`, `patch`, and `delete`) accept a third options parameter, which can be used to set things like headers and referrers. For more info on the options available, see MDN's [fetch docs](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters).
### Intercepting fetches
Data sources allow you to intercept fetches to set headers, query parameters, or make other changes to the outgoing request. This is most often used for authorization or other common concerns that apply to all requests. Data sources also get access to the GraphQL context, which is a great place to store a user token or other information you need to have available.
You can easily set a header on every request:
```javascript
class PersonalizationAPI extends RESTDataSource {
willSendRequest(request) {
request.headers.set('Authorization', this.context.token);
}
}
```
Or add a query parameter:
```javascript
class PersonalizationAPI extends RESTDataSource {
willSendRequest(request) {
request.params.set('api_key', this.context.token);
}
}
```
If you're using TypeScript, make sure to import the `RequestOptions` type:
```javascript
import { RESTDataSource, RequestOptions } from 'apollo-datasource-rest';
class PersonalizationAPI extends RESTDataSource {
baseURL = 'https://personalization-api.example.com/';
willSendRequest(request: RequestOptions) {
request.headers.set('Authorization', this.context.token);
}
}
```
### Resolving URLs dynamically
In some cases, you'll want to set the URL based on the environment or other contextual values. You can use a getter for this:
```javascript
get baseURL() {
if (this.context.env === 'development') {
return 'https://movies-api-dev.example.com/';
} else {
return 'https://movies-api.example.com/';
}
}
```
If you need more customization, including the ability to resolve a URL asynchronously, you can also override `resolveURL`:
```javascript
async resolveURL(request: RequestOptions) {
if (!this.baseURL) {
const addresses = await resolveSrv(request.path.split("/")[1] + ".service.consul");
this.baseURL = addresses[0];
}
return super.resolveURL(request);
}
```
### Accessing data sources from resolvers
To give resolvers access to data sources, you pass them as options to the `ApolloServer` constructor:
```javascript
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => {
return {
moviesAPI: new MoviesAPI(),
personalizationAPI: new PersonalizationAPI(),
};
},
context: () => {
return {
token: 'foo',
};
},
});
```
Apollo Server will put the data sources on the context for every request, so you can access them from your resolvers. It will also give your data sources access to the context. (The reason for not having users put data sources on the context directly is because that would lead to a circular dependency.)
From our resolvers, we can access the data source and return the result:
```javascript
Query: {
movie: async (_source, { id }, { dataSources }) => {
return dataSources.moviesAPI.getMovie(id);
},
mostViewedMovies: async (_source, _args, { dataSources }) => {
return dataSources.moviesAPI.getMostViewedMovies();
},
favorites: async (_source, _args, { dataSources }) => {
return dataSources.personalizationAPI.getFavorites();
},
},
```
| apollostack/apollo-server | packages/apollo-datasource-rest/README.md | Markdown | mit | 6,232 |
package com.ricex.aft.android.request;
import org.springframework.http.HttpStatus;
public class AFTResponse<T> {
/** The successful response from the server */
private final T response;
/** The error response from the server */
private final String error;
/** The HttpStatus code of the response */
private final HttpStatus statusCode;
/** Whether or not this response is valid */
private final boolean valid;
/** Creates a new instance of AFTResponse, representing a successful response
*
* @param response The parsed response received from the server
* @param statusCode The status code of the response
*/
public AFTResponse(T response, HttpStatus statusCode) {
this.response = response;
this.statusCode = statusCode;
this.error = null;
valid = true;
}
/** Creates a new instance of AFTResponse, representing an invalid (error) response
*
* @param response The response (if any) received from the server
* @param error The error message received from the server
* @param statusCode The status code of the response
*/
public AFTResponse(T response, String error, HttpStatus statusCode) {
this.response = response;
this.error = error;
this.statusCode = statusCode;
valid = false;
}
/** Whether or not this response is valid
*
* @return True if the server returned Http OK (200), otherwise false
*/
public boolean isValid() {
return valid;
}
/** The response from the server if valid
*
* @return The response from the server
*/
public T getResponse() {
return response;
}
/** Returns the error received by the server, if invalid response
*
* @return The error the server returned
*/
public String getError() {
return error;
}
/** Return the status code received from the server
*
* @return the status code received from the server
*/
public HttpStatus getStatusCode() {
return statusCode;
}
}
| mwcaisse/AndroidFT | aft-android/src/main/java/com/ricex/aft/android/request/AFTResponse.java | Java | mit | 1,925 |
<?php
/**
* Routes configuration
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different URLs to chosen controllers and their actions (functions).
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use Cake\Core\Plugin;
use Cake\Routing\Router;
Router::scope('/', function ($routes) {
/**
* Here, we are connecting '/' (base path) to a controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, src/Template/Pages/home.ctp)...
*/
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
/**
* ...and connect the rest of 'Pages' controller's URLs.
*/
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
Router::scope(
'/bookmarks',
['controller' => 'Bookmarks'],
function ($routes) {
$routes->connect('/tagged/*', ['action' => 'tags']);
}
);
/**
* Connect a route for the index action of any controller.
* And a more general catch all route for any action.
*
* The `fallbacks` method is a shortcut for
* `$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);`
* `$routes->connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);`
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->fallbacks();
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
| simkimsia/500-webapps | bookmarker/cake3_bookmarker/config/routes.php | PHP | mit | 2,129 |
/* app/ui/map/svg */
define(
[
'jquery',
'raphael',
'app/ui/map/data',
'app/ui/map/util',
'util/detector',
'pubsub'
],
function ($, Raphael, MapData, MapUtil, Detector) {
'use strict';
var SVG;
return {
nzte: {},
markers: [],
exports: {},
countryText: {},
sets: {},
continentSets: {},
text: {},
raphael: null,
_$container: null,
_isExportsMap: false,
init: function () {
SVG = this;
this._$container = $('.js-map-container');
this._isExportsMap = $('#js-map-nzte').length ? false : true;
//If already setup just show the map again
if (this._$container.is('.is-loaded')) {
this._$container.show();
return;
}
if (this._isExportsMap) {
this._initInteractiveMap();
return;
}
this._initRegularMap();
},
_initInteractiveMap: function () {
this._setUpMap();
this._drawMap();
this._createContinentSets();
this._initInteractiveMapEvents();
this._setLoaded();
this._hideLoader();
},
_initRegularMap: function () {
this._setUpMap();
this._drawMap();
this._createSets();
this._initRegularMapEvents();
this._setLoaded();
this._hideLoader();
},
_setLoaded: function () {
this._$container.addClass('is-loaded');
},
_hideLoader: function () {
$.publish('/loader/hide');
},
_setUpMap: function () {
var id = this._isExportsMap ? 'js-map-exports' : 'js-map-nzte';
this._$container.show();
this.raphael = Raphael(id, '100%', '100%');
this.raphael.setViewBox(0, 0, 841, 407, true);
this.raphael.canvas.setAttribute('preserveAspectRatio', 'xMinYMin meet');
},
_drawMap: function () {
this._addMainMap();
this._addContinentMarkers();
this._addContinentMarkerText();
if (this._isExportsMap) {
this._addCountryMarkers();
}
},
_addMainMap: function () {
var mainAttr = {
stroke: 'none',
fill: '#dededd',
'fill-rule': 'evenodd',
'stroke-linejoin': 'round'
};
this.nzte.main = this.raphael.path(MapData.main).attr(mainAttr);
},
_addContinentMarkers: function () {
var markerAttr = {
stroke: 'none',
fill: '#f79432',
'stroke-linejoin': 'round',
cursor: 'pointer'
};
var markerPaths = MapData.markers[0];
for (var continent in markerPaths) {
if (!this._isExportsMap || this._isExportsMap && continent !== 'new-zealand') {
this.markers[continent] = this.raphael.path(markerPaths[continent]).attr(markerAttr);
}
}
},
_addContinentMarkerText: function () {
var textAttr = {
stroke: 'none',
fill: '#ffffff',
'fill-rule': 'evenodd',
'stroke-linejoin': 'round',
cursor: 'pointer'
};
var textPaths = MapData.text[0];
for (var continent in textPaths) {
if (!this._isExportsMap || this._isExportsMap && continent !== 'new-zealand') {
this.text[continent] = this.raphael.path(textPaths[continent]).attr(textAttr);
}
}
},
_addCountryMarkers: function () {
var marker;
for (var region in this.markers) {
marker = this.markers[region];
this._createHoverBox(region, marker);
}
},
_createHoverBox: function (region, marker) {
var set;
var markerAttr = {
stroke: 'none',
fill: '#116697',
opacity: 0,
'stroke-linejoin': 'round'
};
var markerPaths = MapData.exportsText[0];
var country = markerPaths[region];
if (!country) {
return;
}
var countryText = markerPaths[region][0];
var numberOfCountries = Object.keys(countryText).length;
var markerBox = marker.getBBox();
var topX = markerBox.x;
var bottomY = markerBox.y2;
var width = region !== 'india-middle-east-and-africa' ? 150 : 200;
//Add the rectangle
this.exports[region] = this.raphael.rect(topX + 28, bottomY - 1, width, (21 * numberOfCountries) + 5).toBack().attr(markerAttr);
//Create a set to combine countries, hover box and region icon/text
set = this.raphael.set();
set.push(
this.exports[region]
);
//Add the country Text
this._addCountryText(markerBox, countryText, topX + 28, bottomY - 1, 21, region, set);
},
_addCountryText: function (markerBox, countryText, x, y, height, region, set) {
var updatedX = x + 10;
var updatedY = y + 10;
var textAttr = {
font: '13px Arial',
textAlign: 'left',
fill: "#ffffff",
cursor: 'pointer',
'text-decoration': 'underline',
'text-anchor': 'start',
opacity: 0
};
for (var country in countryText) {
var text = countryText[country].toUpperCase();
this.countryText[country] = this.raphael.text(updatedX, updatedY, text).toBack().attr(textAttr);
updatedY += height;
set.push(
this.countryText[country]
);
}
this.continentSets[region] = set.hide();
},
_createSets: function () {
for (var region in this.markers) {
var set = this.raphael.set();
set.push(
this.markers[region],
this.text[region]
);
this.sets[region] = set;
}
},
_createContinentSets: function () {
for (var region in this.markers) {
var set = this.raphael.set();
set.push(
this.markers[region],
this.text[region],
this.continentSets[region]
);
this.sets[region] = set;
}
},
_initInteractiveMapEvents: function () {
this._initCountryTextEvents();
this._initCountryHoverEvents();
},
_initRegularMapEvents: function () {
var bounceEasing = 'cubic-bezier(0.680, -0.550, 0.265, 1.550)';
var mouseOverMarkerBounce = {
transform: 's1.1'
};
var mouseOverMarkerBounceWithTranslate = {
transform: 's1.1t5,0'
};
var mouseOutMarkerBounce = {
transform: 's1'
};
var mouseOverMarker = {
fill: '#116697'
};
var mouseOutMarker = {
fill: '#f79432'
};
for (var region in this.sets) {
var set = this.sets[region];
var marker = this.markers[region];
var text = this.text[region];
(function (savedSet, savedRegion, savedMarker, savedText) {
savedSet.attr({
cursor: 'pointer'
});
savedSet.hover(function () {
//A slight translation is needed for 'india-middle-east-and-africa' so when hovered it isn't clipped by container
var transformAttr = savedRegion !== 'india-middle-east-and-africa' ? mouseOverMarkerBounce : mouseOverMarkerBounceWithTranslate;
savedMarker.animate(transformAttr, 250, bounceEasing);
savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo');
savedText.animate(transformAttr, 250, bounceEasing);
}, function () {
savedMarker.animate(mouseOutMarkerBounce, 250, bounceEasing);
savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine');
savedText.animate(mouseOutMarkerBounce, 250, bounceEasing);
});
savedSet.click(function () {
MapUtil.goToUrl(savedRegion, false);
});
})(set, region, marker, text);
}
},
_initCountryHoverEvents: function () {
var noHover = Detector.noSvgHover();
var mouseOverMarker = {
fill: '#116697'
};
var mouseOutMarker = {
fill: '#f79432'
};
for (var region in this.sets) {
var set = this.sets[region];
var continentSet = this.continentSets[region];
var marker = this.markers[region];
var text = this.text[region];
var hoverBox = this.exports[region];
(function (savedSet, savedContinentSet, savedRegion, savedMarker, savedText, savedBox) {
savedSet.attr({
cursor: 'pointer'
});
if (noHover) {
savedMarker.data('open', false);
savedSet.click(function () {
if (savedMarker.data('open') === false) {
SVG._closeAllContinents();
savedMarker.data('open', true);
savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo');
savedContinentSet.show().toFront().animate({ opacity: 1 }, 250, 'easeInOutExpo');
} else {
savedMarker.data('open', false);
savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine');
savedContinentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack();
}
});
savedSet.hover(function () {
savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo');
}, function () {
savedMarker.data('open') === false && savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine');
});
} else {
savedSet.hover(function () {
savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo');
savedContinentSet.show().toFront().animate({ opacity: 1 }, 250, 'easeInOutExpo');
}, function () {
savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine');
savedContinentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack();
});
}
})(set, continentSet, region, marker, text, hoverBox);
}
},
_closeAllContinents: function () {
for (var region in this.sets) {
var continentSet = this.continentSets[region];
var marker = this.markers[region];
var mouseOutMarker = {
fill: '#f79432'
};
marker.data('open', false);
marker.animate(mouseOutMarker, 250, 'easeInOutSine');
continentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack();
}
},
_initCountryTextEvents: function () {
for (var country in this.countryText) {
var text = this.countryText[country];
(function (savedText, savedCountry) {
savedText.click(function () {
MapUtil.goToUrl(savedCountry, true);
});
savedText.hover(function () {
savedText.animate({ 'fill-opacity': 0.6 }, 250, 'easeInOutSine');
}, function () {
savedText.animate({ 'fill-opacity': 1 }, 250, 'easeInOutSine');
});
})(text, country);
}
}
};
}
); | patocallaghan/questionnaire-js | original/assets/scripts/src/app/ui/map/svg.js | JavaScript | mit | 9,939 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['dsn'] The full DSN string describe a connection to the database.
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database driver. e.g.: mysqli.
| Currently supported:
| cubrid, ibase, mssql, mysql, mysqli, oci8,
| odbc, pdo, postgre, sqlite, sqlite3, sqlsrv
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Query Builder class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
| NOTE: For MySQL and MySQLi databases, this setting is only used
| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
| (and in table creation queries made with DB Forge).
| There is an incompatibility in PHP with mysql_real_escape_string() which
| can make your site vulnerable to SQL injection if you are using a
| multi-byte character set and are running versions lower than these.
| Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['encrypt'] Whether or not to use an encrypted connection.
|
| 'mysql' (deprecated), 'sqlsrv' and 'pdo/sqlsrv' drivers accept TRUE/FALSE
| 'mysqli' and 'pdo/mysql' drivers accept an array with the following options:
|
| 'ssl_key' - Path to the private key file
| 'ssl_cert' - Path to the public key certificate file
| 'ssl_ca' - Path to the certificate authority file
| 'ssl_capath' - Path to a directory containing trusted CA certificats in PEM format
| 'ssl_cipher' - List of *allowed* ciphers to be used for the encryption, separated by colons (':')
| 'ssl_verify' - TRUE/FALSE; Whether verify the server certificate or not ('mysqli' only)
|
| ['compress'] Whether or not to use client compression (MySQL only)
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
| - good for ensuring strict SQL while developing
| ['ssl_options'] Used to set various SSL options that can be used when making SSL connections.
| ['failover'] array - A array with 0 or more data for connections if the main should fail.
| ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.
| NOTE: Disabling this will also effectively disable both
| $this->db->last_query() and profiling of DB queries.
| When you run a query, with this setting set to TRUE (default),
| CodeIgniter will store the SQL statement for debugging purposes.
| However, this may cause high memory usage, especially if you run
| a lot of SQL queries ... disable this to avoid that problem.
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the 'default' group).
|
| The $query_builder variables lets you determine whether or not to load
| the query builder class.
*/
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost:8889',
'username' => 'root',
'password' => 'root',
'database' => 'belttest',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
| khandroj/lampbelttest | application/config/database.php | PHP | mit | 4,535 |
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
meta: {
version: '2.0.0',
banner: '/*! Ebla - v<%= meta.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> ' +
'Monospaced */'
},
concat: {
dist: {
src: ['<banner:meta.banner>',
'javascripts/libs/jquery.cookie.js',
'javascripts/ebla/ebla.js',
'javascripts/ebla/debug.js',
'javascripts/ebla/flash-message.js',
'javascripts/ebla/compatibility.js',
'javascripts/ebla/elements.js',
'javascripts/ebla/controls.js',
'javascripts/ebla/data.js',
'javascripts/ebla/images.js',
'javascripts/ebla/layout.js',
'javascripts/ebla/loader.js',
'javascripts/ebla/navigation.js',
'javascripts/ebla/navigation.event.js',
'javascripts/ebla/navigation.keyboard.js',
'javascripts/ebla/placesaver.js',
'javascripts/ebla/progress.js',
'javascripts/ebla/resize.js',
'javascripts/ebla/toc.js',
'javascripts/ebla/init.js',
'javascripts/ebla/book.js'],
dest: 'javascripts/ebla.js'
}
},
uglify: {
dist: {
src: ['<banner:meta.banner>', 'javascripts/ebla.js'],
dest: 'javascripts/ebla.min.js'
}
},
sass: {
dist: {
options: {
style: 'compressed'
},
files: {
'stylesheets/ebla.css': 'stylesheets/ebla.scss',
'stylesheets/book.css': 'stylesheets/book.scss'
}
}
},
watch: {
files: ['javascripts/ebla/*.js', 'stylesheets/*.scss'],
tasks: ['sass', 'concat', 'uglify']
},
jshint: {
files: ['Gruntfile.js', 'javascripts/ebla.js'],
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
browser: true,
jquery: true,
devel: true,
globals: {
Modernizr: true,
debug: true,
bookData: true,
bookJson: true
}
},
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
// Default task.
grunt.registerTask('default', ['sass', 'concat', 'jshint', 'uglify']);
};
| monospaced/paperback | ebla/Gruntfile.js | JavaScript | mit | 2,746 |
<?php
// src/AppBundle/Entity/Blog.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="blog")
*/
class Blog
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=100)
*/
protected $title;
/**
* @ORM\Column(type="decimal", scale=2)
*/
protected $body;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
* @return Blog
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set body
*
* @param string $body
* @return Blog
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* Get body
*
* @return string
*/
public function getBody()
{
return $this->body;
}
}
| codeglider/SymfonyShoeStoreDemo | src/AppBundle/Entity/Blog.php | PHP | mit | 1,238 |
import {Chart} from 'react-google-charts';
import React, {Component, PropTypes} from 'react';
import DataFormatter from '../../utils/DataFormatter';
class EnvyBarChart extends Component {
constructor(props) {
super(props);
this.state={
options:{
hAxis: {title: 'Event Type'},
vAxis: {title: 'Envy Events'},
legend: 'none',
},
};
}
generateGraph(events) {
var formatter = new DataFormatter();
var result = formatter.generateEnvyGraph(events);
return result;
}
render() {
var data = this.generateGraph(this.props.events);
return (
<Chart
chartType="ColumnChart"
data={data}
options={this.state.options}
graph_id="EnvyBarChart"
width='40vw'
height='50vh'
/>
);
}
};
EnvyBarChart.propTypes = {
events: PropTypes.array.isRequired
}
export default EnvyBarChart; | papernotes/actemotion | src/components/charts/EnvyBarChart.js | JavaScript | mit | 828 |
using ApiAiSDK.Model;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UPT.BOT.Aplicacion.DTOs.BOT;
using UPT.BOT.Distribucion.Bot.Acceso.Documento;
namespace UPT.BOT.Distribucion.Bot.BotService.Dialogos.Documento
{
[Serializable]
public class BoletinDialog : BaseDialog, IDialog<object>
{
private AIResponse response;
public BoletinDialog(AIResponse response)
{
this.response = response;
}
public async Task StartAsync(IDialogContext context)
{
IMessageActivity actividaMensaje = context.MakeMessage();
actividaMensaje.Text = response.Result.Fulfillment.Speech ?? string.Empty;
actividaMensaje.Recipient = actividaMensaje.From;
actividaMensaje.Type = ActivityTypes.Message;
await context.PostAsync(actividaMensaje);
List<BoletinDto> entidades = new BoletinProxy(ruta).Obtener();
List<Attachment> listaAdjuntos = new List<Attachment>();
HeroCard tarjetaFormato = new HeroCard("Boletines");
tarjetaFormato.Subtitle = "Puedes descargar boletines que te serán de gran ayuda!";
tarjetaFormato.Buttons = entidades.Select(p => new CardAction
{
Title = p.DescripcionTitulo,
Value = p.DescripcionUrl,
Type = ActionTypes.DownloadFile
}).ToList();
listaAdjuntos.Add(tarjetaFormato.ToAttachment());
IMessageActivity actividadTarjeta = context.MakeMessage();
actividadTarjeta.Recipient = actividadTarjeta.From;
actividadTarjeta.Attachments = listaAdjuntos;
actividadTarjeta.AttachmentLayout = AttachmentLayoutTypes.List;
actividadTarjeta.Type = ActivityTypes.Message;
await context.PostAsync(actividadTarjeta);
context.Done(this);
}
}
}
| williamccondori/UPT.BOT | UPT.BOT.Distribucion.Bot.BotService/Dialogos/Documento/BoletinDialog.cs | C# | mit | 2,032 |
"use strict";
let mongoose = require('mongoose'),
Schema = mongoose.Schema,
EmailValidator = require('./emailValidator');
class User {
constructor(explicitConnection) {
this.explicitConnection = explicitConnection;
this.schema = new Schema({
email: {
type: 'string',
trim: true,
required: true
},
organization: {
type: 'string',
trim: true,
required: true
},
password: {type: 'string', required: true},
isVisibleAccount: {type: 'boolean'},
userApiKey: {type: 'string'},
userApiSecret: {type: 'string'},
linkedApps: {},
avatarProto: {type: 'string'},
gmailAccount: {type: 'string'},
facebookAccount: {type: 'string'},
twitterAccount: {type: 'string'},
fullname: {type: 'string'},
loginHistories: [],
changeProfileHistories: [],
changeAuthorizationHistories: [],
sparqlQuestions: [],
blockingHistories: [],
authorizations: {},
tripleUsage: {type: 'number', default: 0},
tripleUsageHistory: [],
isBlocked: {
type: 'boolean',
required: true
},
blockedCause: {
type: 'string',
}
}).index({ email: 1, organization: 1 }, { unique: true });
}
getModel() {
if (this.explicitConnection === undefined) {
return mongoose.model('User', this.schema);
} else {
return this.explicitConnection.model('User', this.schema);
}
}
}
module.exports = User; | koneksys/KLD | api/model/user.js | JavaScript | mit | 1,603 |
package cn.edu.ustc.appseed.clubseed.activity;
/*
* Show the detail content of the event which you select.
* Why to use a custom toolbar instead of the default toolbar in ActionBarActivity?
* Because the custom toolbar is very convenient to edit it and good to unify the GUI.
*/
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import cn.edu.ustc.appseed.clubseed.R;
import cn.edu.ustc.appseed.clubseed.data.Event;
import cn.edu.ustc.appseed.clubseed.data.ViewActivityPhp;
import cn.edu.ustc.appseed.clubseed.fragment.NoticeFragment;
import cn.edu.ustc.appseed.clubseed.fragment.StarFragment;
import cn.edu.ustc.appseed.clubseed.utils.AppUtils;
public class StarContentActivity extends ActionBarActivity {
private Toolbar toolbar;
private TextView mTextView;
private ImageView mImageView;
private TextView nullTextView;
private Event mEvent;
int ID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_content);
toolbar = (Toolbar) findViewById(R.id.toolbar);
mTextView = (TextView) findViewById(R.id.textViewEventContent);
mImageView = (ImageView) findViewById(R.id.imgContent);
if (toolbar != null) {
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back));
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
ID = getIntent().getIntExtra(StarFragment.EXTRA_ID, 0);
mEvent = AppUtils.savedEvents.get(ID);
setTitle(mEvent.getTitle());
mTextView.setText(mEvent.getContent());
mImageView.setImageBitmap(mEvent.getBitmap());
}
}
| leerduo/ClubSeed | app/src/main/java/cn/edu/ustc/appseed/clubseed/activity/StarContentActivity.java | Java | mit | 2,293 |
---
layout: post
title: "Le Voyage"
date: 2016-09-29
---
Premier avion :
* LYS -> AMS
* 1h40 de vol
* Beaucoup de français dans l'avion
* Une colation étonnante (cf image 1)
* .. Bref un vol court et tranquile

<figure>
<figcaption>Image 1. Ce pot de yaourt plein d'eau aura suscité notre curiosité.</figcaption>
</figure>
Aéroport d'Amsterdam :
* 2h55 d'escale
* Notre dernier Burger King
* L'aéroport possède un genre de centre commercial géant
* 20 minutes à pied pour aller jusqu'à notre porte d'embarquement
Deuxième avion :
* AMS -> KIX
* 10h55 de vol
* Un avion qui effectuait son 2e vol commercial
* Avec des tablettes pour regarder des films (6 en tout) (cf image 2)
* Et le hublot teintable
* 4 colations/ repas dont un dîner, une glace, un petit déjeuné (cf image 3)
* Long
* Très long

<figure>
<figcaption>Image 2. Cette tablette m'a sauvé de l'ennui, ou m'a empêché de dormir.</figcaption>
</figure>

<figure>
<figcaption>Image 3. Ce premier repas japonais était super!</figcaption>
</figure>
En résumé de ce voyage : J'avais fait exprès de faire une nuit blanche entre Mardi et Mercredi afin de dormir dans l'avion dans la nuit de Mercredi à Jeudi.
J'ai dormi 1h dans l'avion.
Mais étonnament je n'étais pas trop fatigué dans la journée de Jeudi !
La suite dans le prochain article !
| KevinBulme/Jankenpon | _posts/2016-09-29-le_voyage.md | Markdown | mit | 1,536 |
package com.smbc.droid;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.android.volley.toolbox.NetworkImageView;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ComicPagerAdapter adapter = new ComicPagerAdapter( getSupportFragmentManager());
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
// findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// viewPager.setCurrentItem(viewPager.getCurrentItem()+1, true);
// }
// });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| nindalf/smbc-droid | app/src/main/java/com/smbc/droid/MainActivity.java | Java | mit | 1,709 |
#pragma once
#include "Task.h"
namespace vlp {
class WaitTask : public Task {
public:
void run(Engine& engine) override;
};
} | jenningsm42/vulpan | vulpan/include/WaitTask.h | C | mit | 131 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace image_viewer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ImageForm());
}
}
}
| rjclaasen/image-viewer | Program.cs | C# | mit | 517 |
using System;
using OKHOSTING.UI.Controls;
using OKHOSTING.UI.Controls.Layouts;
using OKHOSTING.UI.Xamarin.Mac.Controls;
using OKHOSTING.UI.Xamarin.Mac.Controls.Layout;
namespace OKHOSTING.UI.Xamarin.Mac
{
public class Platform
{
public override T Create<T>()
{
T control = null;
if (typeof(T) == typeof(IAutocomplete))
{
control = new Autocomplete() as T;
}
else if (typeof(T) == typeof(IButton))
{
control = new Button() as T;
}
else if (typeof(T) == typeof(ICalendar))
{
control = new Calendar() as T;
}
else if (typeof(T) == typeof(ICheckBox))
{
control = new CheckBox() as T;
}
else if (typeof(T) == typeof(IHyperLink))
{
control = new HyperLink() as T;
}
else if (typeof(T) == typeof(IImage))
{
control = new Image() as T;
}
else if (typeof(T) == typeof(ILabel))
{
control = new Label() as T;
}
else if (typeof(T) == typeof(ILabelButton))
{
control = new LabelButton() as T;
}
else if (typeof(T) == typeof(IListPicker))
{
control = new ListPicker() as T;
}
else if (typeof(T) == typeof(IPasswordTextBox))
{
control = new PasswordTextBox() as T;
}
else if (typeof(T) == typeof(ITextArea))
{
control = new TextArea() as T;
}
else if (typeof(T) == typeof(ITextBox))
{
control = new TextBox() as T;
}
else if (typeof(T) == typeof(IGrid))
{
control = new Grid() as T;
}
else if (typeof(T) == typeof(IStack))
{
control = new Stack() as T;
}
return control;
}
public override void Finish()
{
base.Finish();
}
//virtual
public virtual Color Parse(global::Xamarin.Mac.Color color)
{
return new Color((int) color.A, (int) color.R, (int) color.G, (int) color.B);
}
public virtual global::Xamarin.Mac.Color Parse(Color color)
{
return global::Xamarin.Mac.Color.FromRgba(color.Alpha, color.Red, color.Green, color.Blue);
}
public virtual HorizontalAlignment Parse(global::Xamarin.Mac.LayoutAlignment horizontalAlignment)
{
switch (horizontalAlignment)
{
case global::Xamarin.Mac.LayoutAlignment.Start:
return HorizontalAlignment.Left;
case global::Xamarin.Mac.LayoutAlignment.Center:
return HorizontalAlignment.Center;
case global::Xamarin.Mac.LayoutAlignment.End:
return HorizontalAlignment.Right;
case global::Xamarin.Mac.LayoutAlignment.Fill:
return HorizontalAlignment.Fill;
}
return HorizontalAlignment.Left;
}
public virtual global::Xamarin.Mac.LayoutAlignment Parse(HorizontalAlignment horizontalAlignment)
{
switch (horizontalAlignment)
{
case HorizontalAlignment.Left:
return global::Xamarin.Mac.LayoutAlignment.Start;
case HorizontalAlignment.Center:
return global::Xamarin.Mac.LayoutAlignment.Center;
case HorizontalAlignment.Right:
return global::Xamarin.Mac.LayoutAlignment.End;
case HorizontalAlignment.Fill:
return global::Xamarin.Mac.LayoutAlignment.Fill;
}
throw new ArgumentOutOfRangeException("horizontalAlignment");
}
public virtual VerticalAlignment ParseVerticalAlignment(global::Xamarin.Mac.LayoutAlignment verticalAlignment)
{
switch (verticalAlignment)
{
case global::Xamarin.Mac.LayoutAlignment.Start:
return VerticalAlignment.Top;
case global::Xamarin.Mac.LayoutAlignment.Center:
return VerticalAlignment.Center;
case global::Xamarin.Mac.LayoutAlignment.End:
return VerticalAlignment.Bottom;
case global::Xamarin.Mac.LayoutAlignment.Fill:
return VerticalAlignment.Fill;
}
return VerticalAlignment.Top;
}
public virtual global::Xamarin.Mac.LayoutAlignment Parse(VerticalAlignment verticalAlignment)
{
switch (verticalAlignment)
{
case VerticalAlignment.Top:
return global::Xamarin.Mac.LayoutAlignment.Start;
case VerticalAlignment.Center:
return global::Xamarin.Mac.LayoutAlignment.Center;
case VerticalAlignment.Bottom:
return global::Xamarin.Mac.LayoutAlignment.End;
case VerticalAlignment.Fill:
return global::Xamarin.Mac.LayoutAlignment.Fill;
}
return global::Xamarin.Mac.LayoutAlignment.Start;
}
public HorizontalAlignment Parse(global::Xamarin.Mac.TextAlignment textAlignment)
{
switch (textAlignment)
{
case global::Xamarin.Mac.TextAlignment.Start:
return HorizontalAlignment.Left;
case global::Xamarin.Mac.TextAlignment.Center:
return HorizontalAlignment.Center;
case global::Xamarin.Mac.TextAlignment.End:
return HorizontalAlignment.Right;
}
return HorizontalAlignment.Left;
}
public global::Xamarin.Mac.TextAlignment ParseTextAlignment(HorizontalAlignment alignment)
{
switch (alignment)
{
case HorizontalAlignment.Left:
return global::Xamarin.Mac.TextAlignment.Start;
case HorizontalAlignment.Center:
return global::Xamarin.Mac.TextAlignment.Center;
case HorizontalAlignment.Right:
return global::Xamarin.Mac.TextAlignment.End;
case HorizontalAlignment.Fill:
return global::Xamarin.Mac.TextAlignment.Start;
}
return global::Xamarin.Mac.TextAlignment.Start;
}
//static
public static new Platform Current
{
get
{
var platform = (Platform)UI.Platform.Current;
if (platform == null)
{
platform = new Platform();
UI.Platform.Current = platform;
}
return platform;
}
}
}
} | okhosting/OKHOSTING.UI | src/Xamarin/OKHOSTING.UI.Xamarin.Mac/Platform.cs | C# | mit | 5,381 |
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/togo/health/" />
</head></html> | okfn/opendataindex-2015 | country/overview/Togo/health/index.html | HTML | mit | 132 |
MIT License
Copyright (c) 2016 Dan Guevarra
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| dngv/JCAPOrbisAlign | LICENSE.md | Markdown | mit | 1,069 |
module.export = {
}; | Force-Wj/chat-demo | src/base/util.js | JavaScript | mit | 22 |
(function (ns) {
// dependencies
var assert = require('assert');
var esgraph = require('esgraph');
var worklist = require('analyses');
var common = require("../../base/common.js");
var Context = require("../../base/context.js");
var Base = require("../../base/index.js");
var codegen = require('escodegen');
var annotateRight = require("./infer_expression.js");
var InferenceScope = require("./registry/").InferenceScope;
var System = require("./registry/system.js");
var Annotations = require("./../../type-system/annotation.js");
var walk = require('estraverse');
var Tools = require("../settools.js");
var Shade = require("../../interfaces.js");
var walkes = require('walkes');
var validator = require('../validator');
var TypeInfo = require("../../type-system/typeinfo.js").TypeInfo;
// shortcuts
var Syntax = common.Syntax;
var Set = worklist.Set;
var FunctionAnnotation = Annotations.FunctionAnnotation;
var ANNO = Annotations.ANNO;
function findConstantsFor(ast, names, constantVariables) {
var result = new Set(), annotation, name, formerValue;
constantVariables = constantVariables ? constantVariables.values() : [];
walkes(ast, {
AssignmentExpression: function(recurse) {
if (this.left.type != Syntax.Identifier) {
Shade.throwError(ast, "Can't find constant for computed left expression");
}
name = this.left.name;
if(names.has(name)) {
annotation = ANNO(this.right);
if(annotation.hasConstantValue()) {
switch(this.operator) {
case "=":
result.add({ name: name, constant: TypeInfo.copyStaticValue(annotation)});
break;
case "-=":
case "+=":
case "*=":
case "/=":
formerValue = constantVariables.filter(function(v){ return v.name == name; });
if(formerValue.length) {
var c = formerValue[0].constant, v;
switch(this.operator) {
case "+=":
v = c + TypeInfo.copyStaticValue(annotation);
break;
case "-=":
v = c - TypeInfo.copyStaticValue(annotation);
break;
case "*=":
v = c * TypeInfo.copyStaticValue(annotation);
break;
case "/=":
v = c / TypeInfo.copyStaticValue(annotation);
break;
}
result.add({ name: name, constant: v});
}
break;
default:
assert(!this.operator);
}
}
}
recurse(this.right);
},
VariableDeclarator: function(recurse) {
name = this.id.name;
if (this.init && names.has(name)) {
annotation = ANNO(this.init);
if(annotation.hasConstantValue()) {
result.add({ name: name, constant: TypeInfo.copyStaticValue(annotation)});
}
}
recurse(this.init);
},
UpdateExpression: function(recurse) {
if(this.argument.type == Syntax.Identifier) {
name = this.argument.name;
annotation = ANNO(this);
if(annotation.hasConstantValue()) {
var value = TypeInfo.copyStaticValue(annotation);
if (!this.prefix) {
value = this.operator == "--" ? --value : ++value;
}
result.add({ name: name, constant: value});
}
}
}
});
return result;
}
/**
*
* @param ast
* @param {AnalysisContext} context
* @param {*} opt
* @constructor
*/
var TypeInference = function (ast, context, opt) {
opt = opt || {};
this.context = context;
this.propagateConstants = opt.propagateConstants || false;
};
Base.extend(TypeInference.prototype, {
/**
* @param {*} ast
* @param {*} opt
* @returns {*}
*/
inferBody: function (ast, opt) {
var cfg = esgraph(ast, { omitExceptions: true }),
context = this.context,
propagateConstants = this.propagateConstants;
//console.log("infer body", cfg)
var result = worklist(cfg,
/**
* @param {Set} input
* @this {FlowNode}
* @returns {*}
*/
function (input) {
if (!this.astNode || this.type) // Start and end node do not influence the result
return input;
//console.log("Analyze", codegen.generate(this.astNode), this.astNode.type);
// Local
if(propagateConstants) {
this.kill = this.kill || Tools.findVariableAssignments(this.astNode, true);
}
annotateRight(context, this.astNode, propagateConstants ? input : null );
this.decl = this.decl || context.declare(this.astNode);
//context.computeConstants(this.astNode, input);
if(!propagateConstants) {
return input;
}
var filteredInput = null, generate = null;
if (this.kill.size) {
// Only if there's an assignment, we need to generate
generate = findConstantsFor(this.astNode, this.kill, propagateConstants ? input : null);
var that = this;
filteredInput = new Set(input.filter(function (elem) {
return !that.kill.some(function(tokill) { return elem.name == tokill });
}));
}
var result = Set.union(filteredInput || input, generate);
// console.log("input:", input);
// console.log("kill:", this.kill);
// console.log("generate:", generate);
// console.log("filteredInput:", filteredInput);
// console.log("result:", result);
return result;
}
, {
direction: 'forward',
merge: worklist.merge(function(a,b) {
if (!a && !b)
return null;
//console.log("Merge", a && a.values(), b && b.values())
var result = Set.intersect(a, b);
//console.log("Result", result && result.values())
return result;
})
});
//Tools.printMap(result, cfg);
return ast;
}
});
/**
*
* @param ast
* @param {AnalysisContext} context
* @param opt
* @returns {*}
*/
var inferProgram = function (ast, context, opt) {
opt = opt || {};
//var globalScope = createGlobalScope(ast);
//registerSystemInformation(globalScope, opt);
var typeInference = new TypeInference(ast, context, opt);
var result = typeInference.inferBody(ast, opt);
return result;
};
ns.infer = inferProgram;
}(exports));
| xml3d/shade.js | src/analyze/typeinference/typeinference.js | JavaScript | mit | 8,226 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>plugin_mmasgis: Class Members - Variables</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.3 -->
<script type="text/javascript"><!--
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">plugin_mmasgis</div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li id="searchli">
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li class="current"><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li><a href="functions.html"><span>All</span></a></li>
<li><a href="functions_func.html"><span>Functions</span></a></li>
<li class="current"><a href="functions_vars.html"><span>Variables</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="functions_vars.html#index__"><span>_</span></a></li>
<li><a href="functions_vars_0x61.html#index_a"><span>a</span></a></li>
<li><a href="functions_vars_0x62.html#index_b"><span>b</span></a></li>
<li><a href="functions_vars_0x63.html#index_c"><span>c</span></a></li>
<li><a href="functions_vars_0x64.html#index_d"><span>d</span></a></li>
<li><a href="functions_vars_0x65.html#index_e"><span>e</span></a></li>
<li><a href="functions_vars_0x66.html#index_f"><span>f</span></a></li>
<li><a href="functions_vars_0x67.html#index_g"><span>g</span></a></li>
<li><a href="functions_vars_0x68.html#index_h"><span>h</span></a></li>
<li><a href="functions_vars_0x69.html#index_i"><span>i</span></a></li>
<li><a href="functions_vars_0x6c.html#index_l"><span>l</span></a></li>
<li><a href="functions_vars_0x6d.html#index_m"><span>m</span></a></li>
<li><a href="functions_vars_0x6e.html#index_n"><span>n</span></a></li>
<li><a href="functions_vars_0x6f.html#index_o"><span>o</span></a></li>
<li><a href="functions_vars_0x70.html#index_p"><span>p</span></a></li>
<li><a href="functions_vars_0x71.html#index_q"><span>q</span></a></li>
<li><a href="functions_vars_0x72.html#index_r"><span>r</span></a></li>
<li><a href="functions_vars_0x73.html#index_s"><span>s</span></a></li>
<li><a href="functions_vars_0x74.html#index_t"><span>t</span></a></li>
<li><a href="functions_vars_0x75.html#index_u"><span>u</span></a></li>
<li><a href="functions_vars_0x76.html#index_v"><span>v</span></a></li>
<li class="current"><a href="functions_vars_0x77.html#index_w"><span>w</span></a></li>
</ul>
</div>
</div>
<div class="contents">
 
<h3><a class="anchor" id="index_w"></a>- w -</h3><ul>
<li>w
: <a class="el" href="classmmasgis_1_1albero_1_1MainWindowAlbero.html#ad4bd4eed0219da0e6aaed5945638dd23">mmasgis::albero::MainWindowAlbero</a>
, <a class="el" href="classmmasgis_1_1anagrafica_1_1MainWindowAnagrafica.html#a1bc4ff8390a93a2cb0b73e1e1d4b5452">mmasgis::anagrafica::MainWindowAnagrafica</a>
, <a class="el" href="classmmasgis_1_1esportazione_1_1MainWindowEsportazione.html#ad47aee177a33770336a42cbd624bd62d">mmasgis::esportazione::MainWindowEsportazione</a>
, <a class="el" href="classmmasgis_1_1interrogazioni_1_1MainWindowQuery.html#aaacb944e93db5c958556b9c7d61ac65e">mmasgis::interrogazioni::MainWindowQuery</a>
, <a class="el" href="classmmasgis_1_1separatore_1_1MainWindowSeparazione.html#a0f504c51f055e94210c180cfbc8b325b">mmasgis::separatore::MainWindowSeparazione</a>
, <a class="el" href="classmmasgis_1_1risultati_1_1testDialog.html#a9d885f43e0848adc8dcf0d51435444fb">mmasgis::risultati::testDialog</a>
, <a class="el" href="classmmasgis_1_1configurazione_1_1WindowConfigurazione.html#ad0dfca362c3b3bfb2f80ac4372840c6e">mmasgis::configurazione::WindowConfigurazione</a>
</li>
<li>wordButton
: <a class="el" href="classmmasgis_1_1Ui__anagrafica_1_1Ui__MainWindowAnagrafica.html#a5fbf4cb32bba565cfbc33fddb9bddd72">mmasgis::Ui_anagrafica::Ui_MainWindowAnagrafica</a>
, <a class="el" href="classmmasgis_1_1Ui__risultati_1_1Ui__MainWindowResults.html#aaedae776b011373ede31b5fa6d689c6c">mmasgis::Ui_risultati::Ui_MainWindowResults</a>
</li>
<li>Wsq
: <a class="el" href="classmmasgis_1_1interrogazioni_1_1MainWindowQuery.html#a724b158501be469ff56ec8c904b6fa46">mmasgis::interrogazioni::MainWindowQuery</a>
</li>
</ul>
</div>
<!--- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Variables</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Tue Apr 17 2012 16:46:02 for plugin_mmasgis by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </small></address>
</body>
</html>
| arpho/mmasgis5 | DocumentazioneSoftware/html/functions_vars_0x77.html | HTML | mit | 7,913 |
# Angular2-Notifications-Lite
A light and easy to use notifications library for Angular 2 & 4. It features both regular page notifications (toasts) and push notifications.
Forked From [Angular2-Notifications](http://flauc.github.io/angular2-notifications)
Updates: Compatible with Angular 2 & Angular 4. Removed animations module.
## Example
Take a look at the live demo here: [Live Demo](http://flauc.github.io/angular2-notifications)
## Setup
Download the library with npm
```
npm install --save angular2-notifications-lite
```
## Documentation
```
import { SimpleNotificationsModule } from 'angular2-notifications-lite';
```
| shibulijack/angular2-notifications-lite | README.md | Markdown | mit | 657 |
package lab;
public class IntArrayWorker
{
/** two dimensional matrix */
private int[][] matrix = null;
/** set the matrix to the passed one
* @param theMatrix the one to use
*/
public void setMatrix(int[][] theMatrix)
{
matrix = theMatrix;
}
/**
* Method to return the total
* @return the total of the values in the array
*/
public int getTotal()
{
int total = 0;
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
total = total + matrix[row][col];
}
}
return total;
}
/**
* Method to return the total using a nested for-each loop
* @return the total of the values in the array
*/
public int getTotalNested()
{
int total = 0;
for (int[] rowArray : matrix)
{
for (int item : rowArray)
{
total = total + item;
}
}
return total;
}
/**
* Method to fill with an increasing count
*/
public void fillCount()
{
int numCols = matrix[0].length;
int count = 1;
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < numCols; col++)
{
matrix[row][col] = count;
count++;
}
}
}
/**
* print the values in the array in rows and columns
*/
public void print()
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
System.out.print( matrix[row][col] + " " );
}
System.out.println();
}
System.out.println();
}
public int getCount(int num){
int count = 0;
for(int row = 0; row < matrix.length; row++)
for(int col = 0; col < matrix[0].length; col++)
if(matrix[row][col] == num)
count++;
return count;
}
public int getColTotal(int col){
int total = 0;
for(int row = 0; row < matrix.length; row++)
total += matrix[row][col];
return total;
}
public int getLargest(){
int largest = matrix[0][0];
for(int row = 0; row < matrix.length; row++)
for(int col = 0; col < matrix[0].length; col++)
if(matrix[row][col] > largest)
largest = matrix[row][col];
return largest;
}
/**
* fill the array with a pattern
*/
public void fillPattern1()
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length;
col++)
{
if (row < col)
matrix[row][col] = 1;
else if (row == col)
matrix[row][col] = 2;
else
matrix[row][col] = 3;
}
}
}
} | Zedai/APCOMSCI | ApComSci/pictures_lab/lab/IntArrayWorker.java | Java | mit | 2,755 |
# Contributing
**Mule** is open source software; contributions from the community are encouraged. Please take a moment to read these guidelines before submitting changes.
### Code style
All PHP code must adhere to the [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) standard.
### Branching and pull requests
As a guideline, please follow this process:
1. [Fork the repository](https://help.github.com/articles/fork-a-repo).
2. Create a topic branch for the change:
* New features should branch from **develop**.
* Bug fixes to existing versions should branch from **master**.
* Please ensure the branch is clearly labelled as a feature or fix.
3. Make the relevant changes.
4. [Squash](http://git-scm.com/book/en/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) commits if necessary.
4. Submit a pull request to the **develop** branch.
Please note this is a general guideline only.
For more information on the branching structure please see the [git-flow cheatsheet](http://danielkummer.github.com/git-flow-cheatsheet/).
| IcecaveLabs/mule | CONTRIBUTING.md | Markdown | mit | 1,110 |
<meta charset="utf-8">
<title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.title }}</title>
<meta name="description" content="{{ page.description }}">
<meta name="keywords" content="{{ page.tags | join: ', ' }}">
<meta property="og:locale" content="en_US">
<meta property="og:title" content="{% if page.title %}{{ page.title }} – {% endif %}{{ site.title }}">
<meta property="og:description" content="{% if page.description %}{{ page.description | strip_html | strip_newlines | truncate: 120 }}{% else %}{{ page.content | strip_html | strip_newlines | truncate: 120 }}{% endif %}">
<meta property="og:url" content="{{ site.url }}{{ page.url }}">
<meta property="og:site_name" content="{{ site.title }}">
<link href="{{ site.url }}/feed.xml" type="application/atom+xml" rel="alternate" title="{{ site.title }} Feed">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Type -->
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Crimson+Text:400,400italic,700,700italic" rel='stylesheet' type='text/css' />
<link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700" rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{{ site.url }}/assets/css/entypo.css" media="all">
<!-- In order to use Calendas Plus, you must first purchase it. Then, create a font-face package using FontSquirrel.
<link rel='stylesheet' href='{{ site.url }}/assets/cal.css' media='all' />
-->
<!-- For all browsers -->
<link rel="stylesheet" href="{{ site.url }}/assets/css/i.css">
<!-- Fresh Squeezed jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta http-equiv="cleartype" content="on">
<!-- Load Modernizr -->
<script src="{{ site.url }}/assets/js/vendor/modernizr-2.6.2.custom.min.js"></script>
<!-- Icons -->
<!-- 16x16 -->
<link rel="shortcut icon" href="{{ site.url }}/favicon.ico">
<div id="bump">
<body class="">
<header class="site-header darken">
<div class="wrap">
<hgroup>
<h1><a href="/">{{ site.title }}</a></h1>
</hgroup>
<a href="#nav" class="menu"><span class='icons'>☰</span></a>
<nav role="navigation">
<ul>
<li class="timer">
<span>30</span>
<i>:</i>
<span>00</span>
<svg version="1.1" id="timer" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 443.022 511.494" style="enable-background:new 0 0 443.022 511.494;" xml:space="preserve">
<polygon id="timerBackground" style="fill:#292929;" points="221.564,505.721 5.054,380.78 5,130.808 221.457,5.773 437.967,130.714 438.021,380.687 "/>
<path id="timerBorder" style="fill:#3B3B3B;" d="M221.565,511.494L0.055,383.668L0,127.922L221.456,0l221.51,127.826l0.057,255.746L221.565,511.494z M10.054,377.893l211.509,122.055l211.458-122.146l-0.053-244.199L221.458,11.547L10.001,133.693L10.054,377.893z"/>
<g id="timerPause" style="display:none;">
<rect x="131.477" y="159.077" style="display:inline;fill:#F7DD46;" width="61" height="196"/>
<rect x="251.477" y="159.077" style="display:inline;fill:#F7DD46;" width="61" height="196"/>
</g>
<polygon id="timerPlay" style="fill:#F7DD46;" points="151.477,151.574 333.284,256.542 151.477,361.508 "/>
<!-- <polygon id="timerPosition" style="fill:#F7DD46;" points="433.003,133.65 433.056,377.849 433.038,377.859 443.005,383.651 443.058,383.62 443.001,127.875 442.946,127.843 432.985,133.64 "/> -->
</svg>
</li>
<li>
<a href="/" title="{{ site.title }}">Home</a>
</li>
{% for link in site.links %}
<li><a href="{% if link.external %}{{ link.url }}{% else %}{{ site.url }}{{ link.url }}{% endif %}" {% if link.external %}target="_blank"{% endif %}>{{ link.title }}</a></li>
{% endfor %}
</ul>
</nav>
</div>
</header>
| sum37/es6aday.github.io | _includes/head-dark.html | HTML | mit | 4,260 |
#include <bits/stdc++.h>
using namespace std;
vector<int> adj[143];
int n; bool seen[143];
int dfs(int u) {
seen[u] = true;
int result = 0;
for (int v: adj[u])
if (!seen[v])
result += dfs(v) + 1;
return result;
}
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
while (cin >> n && n) {
for (int i=0, sz; i<n; ++i) {
cin >> sz;
adj[i].resize(sz);
for (int j=0; j<sz; ++j) {
cin >> adj[i][j];
--adj[i][j];
}
}
int mx=-1, mxi;
for (int i=0; i<n; ++i) {
memset(seen, 0, n);
int c = dfs(i);
if (mx < c) {
mx = c;
mxi = i;
}
}
cout << mxi+1 << "\n";
}
}
| arash16/prays | UVA/vol-109/10926.cpp | C++ | mit | 815 |
<?php
namespace SergeiK\izVladimiraBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
class CarAdmin extends Admin
{
/**
* @param DatagridMapper $datagridMapper
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('title', null, array(
'label' => 'Название'
))
->add('publish', null, array(
'label' => 'Опубликованно'
))
->add('seats', null, array(
'label' => 'Колличество посадочных мест'
))
;
}
/**
* @param ListMapper $listMapper
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('id')
->add('title', null, array(
'label' => 'Название'
))
->add('seats', null, array(
'label' => 'Колличество посадочных мест'
))
->add('publish', null, array(
'label' => 'Опубликованно'
))
->add('_action', 'actions', array(
'actions' => array(
'edit' => array(),
'delete' => array(),
)
))
;
}
/**
* @param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title', null, array(
'label' => 'Название'
))
->add('seats', null, array(
'label' => 'Колличество посадочных мест'
))
->add('adds', 'textarea', array(
'label' => 'Дополнительная информация',
'attr' => array(
'class' => 'ckeditor'
)
))
->add('images', 'sonata_type_collection', array(
'required' => false,
'by_reference' => false,
'label' => 'Фото'
), array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position'
)
)
->add('publish', null, array(
'label' => 'Опубликовать'
))
;
}
/**
* @param ShowMapper $showMapper
*/
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('id')
->add('title', null, array(
'label' => 'Название'
))
->add('seats', null, array(
'label' => 'Колличество посадочных мест'
))
->add('adds', null, array(
'label' => 'Дополнительная информация'
))
;
}
public function prePersist($car){
foreach($car->getImages() as $image){
$image->setCar($car);
}
}
public function preUpdate($car){
foreach($car->getImages() as $image){
$image->setCar($car);
}
}
}
| SergeiKutanov/izvladimira | src/SergeiK/izVladimiraBundle/Admin/CarAdmin.php | PHP | mit | 3,503 |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace NAudio.Lame
{
/// <summary>
/// Decoder for ID3v2 tags
/// </summary>
public static class ID3Decoder
{
/// <summary>
/// Read an ID3v2 Tag from the current position in a stream.
/// </summary>
/// <param name="stream"><see cref="Stream"/> positioned at start of ID3v2 Tag.</param>
/// <returns><see cref="ID3TagData"/> with tag content.</returns>
public static ID3TagData Decode(Stream stream)
{
byte[] header = new byte[10];
int rc = stream.Read(header, 0, 10);
if (rc != 10 || !ValidateTagHeader(header))
throw new InvalidDataException("Bad ID3 Tag Header");
// decode size field and confirm range
int size = DecodeHeaderSize(header, 6);
if (size < 10 || size >= (1 << 28))
throw new InvalidDataException($"ID3 header size '{size:#,0}' out of range.");
// Load entire tag into buffer and parse
var buffer = new byte[10 + size];
#pragma warning disable IDE0059 // Unnecessary assignment of a value
rc = stream.Read(buffer, 0, buffer.Length);
#pragma warning restore IDE0059 // Unnecessary assignment of a value
return InternalDecode(buffer, 0, size, header[5]);
}
/// <summary>
/// Read an ID3v2 Tag from the supplied array.
/// </summary>
/// <param name="buffer">Array containing complete ID3v2 Tag.</param>
/// <returns><see cref="ID3TagData"/> with tag content.</returns>
public static ID3TagData Decode(byte[] buffer)
{
// Check header
if (!ValidateTagHeader(buffer))
throw new InvalidDataException("Bad ID3 Tag Header");
// decode size field and confirm range
int size = DecodeHeaderSize(buffer, 6);
if (size < 10 || size > (buffer.Length - 10))
throw new InvalidDataException($"ID3 header size '{size:#,0}' out of range.");
// Decode tag content
return InternalDecode(buffer, 10, size, buffer[5]);
}
/// <summary>
/// Decode frames from ID3 tag
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="size"></param>
/// <param name="flags"></param>
/// <returns></returns>
private static ID3TagData InternalDecode(byte[] buffer, int offset, int size, byte flags)
{
// copy tag body data into array and remove unsynchronization padding if present
byte[] bytes = new byte[size];
Array.Copy(buffer, offset, bytes, 0, size);
if ((flags & 0x80) != 0)
bytes = UnsyncBytes(bytes);
var res = new ID3TagData();
int pos = 0;
// skip extended header if present
if ((flags & 0x40) != 0)
{
var ehSize = DecodeBEInt32(bytes, pos);
pos += ehSize + 4;
}
// load all frames from the tag buffer
for (var frame = ID3FrameData.ReadFrame(bytes, pos, out int frameSize); frameSize > 0 && frame != null; frame = ID3FrameData.ReadFrame(bytes, pos, out frameSize))
{
switch (frame.FrameID)
{
case "TIT2":
res.Title = frame.ParseString();
break;
case "TPE1":
res.Artist = frame.ParseString();
break;
case "TALB":
res.Album = frame.ParseString();
break;
case "TYER":
res.Year = frame.ParseString();
break;
case "COMM":
res.Comment = frame.ParseCommentText();
break;
case "TCON":
res.Genre = frame.ParseString();
break;
case "TRCK":
res.Track = frame.ParseString();
break;
case "TIT3":
res.Subtitle = frame.ParseString();
break;
case "TPE2":
res.AlbumArtist = frame.ParseString();
break;
case "TXXX":
{
var udt = frame.ParseUserDefinedText();
res.UserDefinedText[udt.Key] = udt.Value;
break;
}
case "APIC":
{
var pic = frame.ParseAPIC();
res.AlbumArt = pic?.ImageBytes;
break;
}
default:
break;
}
pos += frameSize;
}
return res;
}
/// <summary>
/// Check ID3v2 tag header is correctly formed
/// </summary>
/// <param name="buffer">Array containing ID3v2 header</param>
/// <returns>True if checks pass, else false</returns>
private static bool ValidateTagHeader(byte[] buffer)
=> buffer?.Length >= 4 && buffer[0] == 'I' && buffer[1] == 'D' && buffer[2] == '3' && buffer[3] == 3 && buffer[4] == 0;
/// <summary>
/// Decode a 28-bit integer stored in the low 7 bits of 4 bytes at the offset, most-significant bits first (big-endian).
/// </summary>
/// <param name="buffer">Array containing value to decode.</param>
/// <param name="offset">Offset in array of the 4 bytes containing the value.</param>
/// <returns>Decoded value.</returns>
private static int DecodeHeaderSize(byte[] buffer, int offset)
=> (int)(
((uint)buffer[offset] << 21) |
((uint)buffer[offset + 1] << 14) |
((uint)buffer[offset + 2] << 7) |
buffer[offset + 3]
);
/// <summary>
/// Read 16-bit integer from <paramref name="buffer"/> as 2 big-endian bytes at <paramref name="offset"/>.
/// </summary>
/// <param name="buffer">Byte array containing value.</param>
/// <param name="offset">Offset in byte array to start of value.</param>
/// <returns>16-bit integer value.</returns>
private static short DecodeBEInt16(byte[] buffer, int offset)
=> (short)((buffer[offset] << 8) | buffer[offset + 1]);
/// <summary>
/// Read 32-bit integer from <paramref name="buffer"/> as 4 big-endian bytes at <paramref name="offset"/>.
/// </summary>
/// <param name="buffer">Byte array containing value.</param>
/// <param name="offset">Offset in byte array to start of value.</param>
/// <returns>32-bit integer value.</returns>
private static int DecodeBEInt32(byte[] buffer, int offset)
=> ((buffer[offset] << 24) | (buffer[offset + 1] << 16) | (buffer[offset + 2] << 8) | (buffer[offset + 3]));
/// <summary>
/// Remove NUL bytes inserted by 'unsynchronisation' of data buffer.
/// </summary>
/// <param name="buffer">Buffer with 'unsynchronized' data.</param>
/// <returns>New array with insertions removed.</returns>
private static byte[] UnsyncBytes(IEnumerable<byte> buffer)
{
IEnumerable<byte> ProcessBuffer()
{
byte prev = 0;
foreach (var b in buffer)
{
if (b != 0 || prev != 0xFF)
yield return b;
prev = b;
}
}
return ProcessBuffer().ToArray();
}
/// <summary>
/// Represents an ID3 frame read from the tag.
/// </summary>
private class ID3FrameData
{
/// <summary>
/// Four-character Frame ID.
/// </summary>
public readonly string FrameID;
/// <summary>
/// Size of the frame in bytes, not including the header. Should equal the size of the Data buffer.
/// </summary>
public readonly int Size;
/// <summary>
/// Frame header flags.
/// </summary>
public readonly short Flags;
/// <summary>
/// Frame content as bytes.
/// </summary>
public readonly byte[] Data;
// private constructor
private ID3FrameData(string frameID, int size, short flags, byte[] data)
{
FrameID = frameID;
Size = size;
Flags = flags;
Data = data;
}
/// <summary>
/// Read an ID3v2 content frame from the supplied buffer.
/// </summary>
/// <param name="buffer">Array containing content frame data.</param>
/// <param name="offset">Offset of start of content frame data.</param>
/// <param name="size">Output: total bytes consumed by frame, including header, or -1 if no frame available.</param>
/// <returns><see cref="ID3FrameData"/> with frame, or null if no frame available.</returns>
public static ID3FrameData ReadFrame(byte[] buffer, int offset, out int size)
{
size = -1;
if ((buffer.Length - offset) <= 10)
return null;
// Extract header data
string frameID = Encoding.ASCII.GetString(buffer, offset, 4);
int frameLength = DecodeBEInt32(buffer, offset + 4);
short frameFlags = DecodeBEInt16(buffer, offset + 8);
// copy frame content to byte array
byte[] content = new byte[frameLength];
Array.Copy(buffer, offset + 10, content, 0, frameLength);
// Decompress if necessary
if ((frameFlags & 0x80) != 0)
{
using (var ms = new MemoryStream())
using (var dec = new DeflateStream(new MemoryStream(content), CompressionMode.Decompress))
{
dec.CopyTo(ms);
content = ms.ToArray();
}
}
// return frame
size = 10 + frameLength;
return new ID3FrameData(frameID, frameLength, frameFlags, content);
}
/// <summary>
/// Read an ASCII string from an array, NUL-terminated or optionally end of buffer.
/// </summary>
/// <param name="buffer">Array containing ASCII string.</param>
/// <param name="offset">Start of string in array.</param>
/// <param name="requireTerminator">If true then fail if no terminator found.</param>
/// <returns>String from buffer, string.Empty if 0-length, null on failure.</returns>
private static string GetASCIIString(byte[] buffer, ref int offset, bool requireTerminator)
{
int start = offset;
int position = offset;
for (; position < buffer.Length && buffer[position] != 0; position++) ;
if (requireTerminator && position >= buffer.Length)
return null;
int length = position - start;
offset = position + 1;
return length < 1 ? string.Empty : Encoding.ASCII.GetString(buffer, start, length);
}
/// <summary>
/// Read a Unicode string from an array, NUL-terminated or optionally end of buffer.
/// </summary>
/// <param name="buffer">Array containing ASCII string.</param>
/// <param name="offset">Start of string in array.</param>
/// <param name="requireTerminator">If true then fail if no terminator found.</param>
/// <returns>String from buffer, string.Empty if 0-length, null on failure.</returns>
private static string GetUnicodeString(byte[] buffer, ref int offset, bool requireTerminator = true)
{
int start = offset;
int position = offset;
for (; position < buffer.Length - 1 && (buffer[position] != 0 || buffer[position + 1] != 0); position += 2) ;
if (requireTerminator && position >= buffer.Length)
return null;
int length = position - start;
offset = position + 2;
string res = LameDLLWrap.UCS2.GetString(buffer, start, length);
return res;
}
delegate string delGetString(byte[] buffer, ref int offset, bool requireTeminator);
private delGetString GetGetString()
{
byte encoding = Data[0];
if (encoding == 0)
return GetASCIIString;
if (encoding == 1)
return GetUnicodeString;
throw new InvalidDataException($"Invalid string encoding: {encoding}");
}
/// <summary>
/// Parse the frame content as a string.
/// </summary>
/// <returns>String content, string.Empty if 0-length.</returns>
/// <exception cref="InvalidDataException">Invalid string encoding.</exception>
public string ParseString()
{
int position = 1;
return GetGetString()(Data, ref position, false);
}
/// <summary>
/// Parse the frame content as a Comment (COMM) frame, return comment text only.
/// </summary>
/// <returns>Comment text only. Language and short description omitted.</returns>
public string ParseCommentText()
{
var getstr = GetGetString();
int position = 1;
string language = Encoding.ASCII.GetString(Data, position, 3);
position += 3;
string shortdesc = getstr(Data, ref position, true);
string comment = getstr(Data, ref position, false);
return comment;
}
/// <summary>
/// Parse the frame content as a User-Defined Text Information (TXXX) frame.
/// </summary>
/// <returns><see cref="KeyValuePair{TKey, TValue}"/> with content, or exception on error.</returns>
public KeyValuePair<string, string> ParseUserDefinedText()
{
byte encoding = Data[0];
delGetString getstring;
if (encoding == 0)
getstring = GetASCIIString;
else if (encoding == 1)
getstring = GetUnicodeString;
else
throw new InvalidDataException($"Unknown string encoding: {encoding}");
int position = 1;
string description = getstring(Data, ref position, true);
string value = getstring(Data, ref position, false);
return new KeyValuePair<string, string>(description, value);
}
/// <summary>
/// Parse the frame content as an attached picture (APIC) frame.
/// </summary>
/// <returns><see cref="APICData"/> object </returns>
public APICData ParseAPIC()
{
if (FrameID != "APIC")
return null;
var getstr = GetGetString();
// get attributes
int position = 1;
string mime = getstr(Data, ref position, true);
byte type = Data[position++];
string description = getstr(Data, ref position, true);
// get image content
int datalength = Data.Length - position;
byte[] imgdata = new byte[datalength];
Array.Copy(Data, position, imgdata, 0, datalength);
return new APICData
{
MIMEType = mime,
ImageType = type,
Description = description,
ImageBytes = imgdata,
};
}
/// <summary>
/// Data for an Attached Picture (APIC) frame.
/// </summary>
public class APICData
{
/// <summary>
/// MIME type of contained image
/// </summary>
public string MIMEType;
/// <summary>
/// Type of image. Refer to http://id3.org/id3v2.3.0#Attached_picture for list of values.
/// </summary>
public byte ImageType;
/// <summary>
/// Picture description.
/// </summary>
public string Description;
/// <summary>
/// Picture file content.
/// </summary>
public byte[] ImageBytes;
}
}
}
}
| Corey-M/NAudio.Lame | NAudio.Lame/ID3Decoder.cs | C# | mit | 17,597 |
//
// CORTransparentViewController.h
// CORKit
//
// Created by Seiya Sasaki on 2014/02/20.
// Copyright (c) 2014年 Seiya Sasaki. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void (^CORTransparentPresentCompletion)();
@interface CORTransparentViewController : UIViewController
- (void)presentTransparentViewController:(UIViewController *)viewController animated:(BOOL)animated completion:(CORTransparentPresentCompletion)completion;
- (void)dismissTransparentViewControllerAnimated:(BOOL)animated completion:(CORTransparentPresentCompletion)completion;
@end
| seiyavw/CORKit | CORKit/Extension/CORTransparentViewController.h | C | mit | 579 |
module Daemontools
VERSION = "0.1.3"
end
| vladimirich/daemontools | lib/daemontools/version.rb | Ruby | mit | 43 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ListRange} from '@angular/cdk/collections';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
Inject,
Input,
NgZone,
OnDestroy,
OnInit,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {DomSanitizer, SafeStyle} from '@angular/platform-browser';
import {animationFrameScheduler, fromEvent, Observable, Subject} from 'rxjs';
import {sampleTime, take, takeUntil} from 'rxjs/operators';
import {CdkVirtualForOf} from './virtual-for-of';
import {VIRTUAL_SCROLL_STRATEGY, VirtualScrollStrategy} from './virtual-scroll-strategy';
/** Checks if the given ranges are equal. */
function rangesEqual(r1: ListRange, r2: ListRange): boolean {
return r1.start == r2.start && r1.end == r2.end;
}
/** A viewport that virtualizes it's scrolling with the help of `CdkVirtualForOf`. */
@Component({
moduleId: module.id,
selector: 'cdk-virtual-scroll-viewport',
templateUrl: 'virtual-scroll-viewport.html',
styleUrls: ['virtual-scroll-viewport.css'],
host: {
'class': 'cdk-virtual-scroll-viewport',
'[class.cdk-virtual-scroll-orientation-horizontal]': 'orientation === "horizontal"',
'[class.cdk-virtual-scroll-orientation-vertical]': 'orientation === "vertical"',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkVirtualScrollViewport implements OnInit, OnDestroy {
/** Emits when the viewport is detached from a CdkVirtualForOf. */
private _detachedSubject = new Subject<void>();
/** Emits when the rendered range changes. */
private _renderedRangeSubject = new Subject<ListRange>();
/** The direction the viewport scrolls. */
@Input() orientation: 'horizontal' | 'vertical' = 'vertical';
/** The element that wraps the rendered content. */
@ViewChild('contentWrapper') _contentWrapper: ElementRef;
/** A stream that emits whenever the rendered range changes. */
renderedRangeStream: Observable<ListRange> = this._renderedRangeSubject.asObservable();
/**
* The total size of all content (in pixels), including content that is not currently rendered.
*/
_totalContentSize = 0;
/** The transform used to offset the rendered content wrapper element. */
_renderedContentTransform: SafeStyle;
/** The raw string version of the rendered content transform. */
private _rawRenderedContentTransform: string;
/** The currently rendered range of indices. */
private _renderedRange: ListRange = {start: 0, end: 0};
/** The length of the data bound to this viewport (in number of items). */
private _dataLength = 0;
/** The size of the viewport (in pixels). */
private _viewportSize = 0;
/** The pending scroll offset to be applied during the next change detection cycle. */
private _pendingScrollOffset: number | null;
/** the currently attached CdkVirtualForOf. */
private _forOf: CdkVirtualForOf<any> | null;
/** The last rendered content offset that was set. */
private _renderedContentOffset = 0;
/**
* Whether the last rendered content offset was to the end of the content (and therefore needs to
* be rewritten as an offset to the start of the content).
*/
private _renderedContentOffsetNeedsRewrite = false;
/** Observable that emits when the viewport is destroyed. */
private _destroyed = new Subject<void>();
/** Whether there is a pending change detection cycle. */
private _isChangeDetectionPending = false;
/** A list of functions to run after the next change detection cycle. */
private _runAfterChangeDetection: Function[] = [];
constructor(public elementRef: ElementRef, private _changeDetectorRef: ChangeDetectorRef,
private _ngZone: NgZone, private _sanitizer: DomSanitizer,
@Inject(VIRTUAL_SCROLL_STRATEGY) private _scrollStrategy: VirtualScrollStrategy) {}
ngOnInit() {
// It's still too early to measure the viewport at this point. Deferring with a promise allows
// the Viewport to be rendered with the correct size before we measure. We run this outside the
// zone to avoid causing more change detection cycles. We handle the change detection loop
// ourselves instead.
this._ngZone.runOutsideAngular(() => Promise.resolve().then(() => {
this._measureViewportSize();
this._scrollStrategy.attach(this);
fromEvent(this.elementRef.nativeElement, 'scroll')
// Sample the scroll stream at every animation frame. This way if there are multiple
// scroll events in the same frame we only need to recheck our layout once.
.pipe(sampleTime(0, animationFrameScheduler), takeUntil(this._destroyed))
.subscribe(() => this._scrollStrategy.onContentScrolled());
this._markChangeDetectionNeeded();
}));
}
ngOnDestroy() {
this.detach();
this._scrollStrategy.detach();
this._destroyed.next();
// Complete all subjects
this._renderedRangeSubject.complete();
this._detachedSubject.complete();
this._destroyed.complete();
}
/** Attaches a `CdkVirtualForOf` to this viewport. */
attach(forOf: CdkVirtualForOf<any>) {
if (this._forOf) {
throw Error('CdkVirtualScrollViewport is already attached.');
}
// Subscribe to the data stream of the CdkVirtualForOf to keep track of when the data length
// changes. Run outside the zone to avoid triggering change detection, since we're managing the
// change detection loop ourselves.
this._ngZone.runOutsideAngular(() => {
this._forOf = forOf;
this._forOf.dataStream.pipe(takeUntil(this._detachedSubject)).subscribe(data => {
const newLength = data.length;
if (newLength !== this._dataLength) {
this._dataLength = newLength;
this._scrollStrategy.onDataLengthChanged();
}
});
});
}
/** Detaches the current `CdkVirtualForOf`. */
detach() {
this._forOf = null;
this._detachedSubject.next();
}
/** Gets the length of the data bound to this viewport (in number of items). */
getDataLength(): number {
return this._dataLength;
}
/** Gets the size of the viewport (in pixels). */
getViewportSize(): number {
return this._viewportSize;
}
// TODO(mmalerba): This is technically out of sync with what's really rendered until a render
// cycle happens. I'm being careful to only call it after the render cycle is complete and before
// setting it to something else, but its error prone and should probably be split into
// `pendingRange` and `renderedRange`, the latter reflecting whats actually in the DOM.
/** Get the current rendered range of items. */
getRenderedRange(): ListRange {
return this._renderedRange;
}
/**
* Sets the total size of all content (in pixels), including content that is not currently
* rendered.
*/
setTotalContentSize(size: number) {
if (this._totalContentSize !== size) {
this._totalContentSize = size;
this._markChangeDetectionNeeded();
}
}
/** Sets the currently rendered range of indices. */
setRenderedRange(range: ListRange) {
if (!rangesEqual(this._renderedRange, range)) {
this._renderedRangeSubject.next(this._renderedRange = range);
this._markChangeDetectionNeeded(() => this._scrollStrategy.onContentRendered());
}
}
/**
* Gets the offset from the start of the viewport to the start of the rendered data (in pixels).
*/
getOffsetToRenderedContentStart(): number | null {
return this._renderedContentOffsetNeedsRewrite ? null : this._renderedContentOffset;
}
/**
* Sets the offset from the start of the viewport to either the start or end of the rendered data
* (in pixels).
*/
setRenderedContentOffset(offset: number, to: 'to-start' | 'to-end' = 'to-start') {
const axis = this.orientation === 'horizontal' ? 'X' : 'Y';
let transform = `translate${axis}(${Number(offset)}px)`;
this._renderedContentOffset = offset;
if (to === 'to-end') {
// TODO(mmalerba): The viewport should rewrite this as a `to-start` offset on the next render
// cycle. Otherwise elements will appear to expand in the wrong direction (e.g.
// `mat-expansion-panel` would expand upward).
transform += ` translate${axis}(-100%)`;
this._renderedContentOffsetNeedsRewrite = true;
}
if (this._rawRenderedContentTransform != transform) {
// We know this value is safe because we parse `offset` with `Number()` before passing it
// into the string.
this._rawRenderedContentTransform = transform;
this._renderedContentTransform = this._sanitizer.bypassSecurityTrustStyle(transform);
this._markChangeDetectionNeeded(() => {
if (this._renderedContentOffsetNeedsRewrite) {
this._renderedContentOffset -= this.measureRenderedContentSize();
this._renderedContentOffsetNeedsRewrite = false;
this.setRenderedContentOffset(this._renderedContentOffset);
} else {
this._scrollStrategy.onRenderedOffsetChanged();
}
});
}
}
/** Sets the scroll offset on the viewport. */
setScrollOffset(offset: number) {
// Rather than setting the offset immediately, we batch it up to be applied along with other DOM
// writes during the next change detection cycle.
this._pendingScrollOffset = offset;
this._markChangeDetectionNeeded();
}
/** Gets the current scroll offset of the viewport (in pixels). */
measureScrollOffset(): number {
return this.orientation === 'horizontal' ?
this.elementRef.nativeElement.scrollLeft : this.elementRef.nativeElement.scrollTop;
}
/** Measure the combined size of all of the rendered items. */
measureRenderedContentSize(): number {
const contentEl = this._contentWrapper.nativeElement;
return this.orientation === 'horizontal' ? contentEl.offsetWidth : contentEl.offsetHeight;
}
/**
* Measure the total combined size of the given range. Throws if the range includes items that are
* not rendered.
*/
measureRangeSize(range: ListRange): number {
if (!this._forOf) {
return 0;
}
return this._forOf.measureRangeSize(range, this.orientation);
}
/** Update the viewport dimensions and re-render. */
checkViewportSize() {
// TODO: Cleanup later when add logic for handling content resize
this._measureViewportSize();
this._scrollStrategy.onDataLengthChanged();
}
/** Measure the viewport size. */
private _measureViewportSize() {
const viewportEl = this.elementRef.nativeElement;
this._viewportSize = this.orientation === 'horizontal' ?
viewportEl.clientWidth : viewportEl.clientHeight;
}
/** Queue up change detection to run. */
private _markChangeDetectionNeeded(runAfter?: Function) {
if (runAfter) {
this._runAfterChangeDetection.push(runAfter);
}
// Use a Promise to batch together calls to `_doChangeDetection`. This way if we set a bunch of
// properties sequentially we only have to run `_doChangeDetection` once at the end.
if (!this._isChangeDetectionPending) {
this._isChangeDetectionPending = true;
this._ngZone.runOutsideAngular(() => Promise.resolve().then(() => {
if (this._ngZone.isStable) {
this._doChangeDetection();
} else {
this._ngZone.onStable.pipe(take(1)).subscribe(() => this._doChangeDetection());
}
}));
}
}
/** Run change detection. */
private _doChangeDetection() {
this._isChangeDetectionPending = false;
// Apply changes to Angular bindings.
this._ngZone.run(() => this._changeDetectorRef.detectChanges());
// Apply the pending scroll offset separately, since it can't be set up as an Angular binding.
if (this._pendingScrollOffset != null) {
if (this.orientation === 'horizontal') {
this.elementRef.nativeElement.scrollLeft = this._pendingScrollOffset;
} else {
this.elementRef.nativeElement.scrollTop = this._pendingScrollOffset;
}
}
for (let fn of this._runAfterChangeDetection) {
fn();
}
this._runAfterChangeDetection = [];
}
}
| amcdnl/material2 | src/cdk-experimental/scrolling/virtual-scroll-viewport.ts | TypeScript | mit | 12,339 |
module Devise
module Hooks
# A small warden proxy so we can remember, forget and
# sign out users from hooks.
class Proxy #:nodoc:
include Devise::Controllers::Rememberable
include Devise::Controllers::SignInOut
attr_reader :warden
delegate :cookies, :env, :to => :warden
def initialize(warden)
@warden = warden
end
def session
warden.request.session
end
end
end
end
| QARIO/dochive | vendor/bundle/gems/devise-3.2.3/lib/devise/hooks/proxy.rb | Ruby | mit | 454 |
import array
import numbers
real_types = [numbers.Real]
int_types = [numbers.Integral]
iterable_types = [set, list, tuple, array.array]
try:
import numpy
except ImportError:
pass
else:
real_types.extend([numpy.float32, numpy.float64])
int_types.extend([numpy.int32, numpy.int64])
iterable_types.append(numpy.ndarray)
# use these with isinstance to test for various types that include builtins
# and numpy types (if numpy is available)
real_types = tuple(real_types)
int_types = tuple(int_types)
iterable_types = tuple(iterable_types)
| DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.util/src/openmdao/util/typegroups.py | Python | mit | 558 |
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width initial-scale=1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title>
<meta name="description" content="{{ site.description }}">
<link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
<link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="{{ site.baseurl }}/js/jquery.backstretch.min.js"></script>
</head>
| codeforamerica/atlanta-procurement-www | _includes/head.html | HTML | mit | 718 |
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { toggleSelect } from '../actions/users';
import { createLink } from '../../utils';
class User extends Component {
render() {
const profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'bigger') : '';
const small_profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'mini') : '';
var description = this.props.user.description;
if(description) {
description = description.replace(/@[A-Za-z_0-9]+/g, id => createLink(`https://twitter.com/${id.substring(1)}`, id));
this.props.user.entities.description.urls.forEach(url => description = description.replace(new RegExp(url.url, 'g'), createLink(url.expanded_url, url.expanded_url)));
}
return this.props.settings.showMode === 'card' ? (
<li className={'responsive-card ' + (this.props.user.select ? 'responsive-card--selected' : '')}>
<input type="checkbox" checked={this.props.user.select} className="user__select" onChange={this.props.toggleSelect} />
<div alt="" className="card-img-top" style={{
backgroundImage: this.props.user.profile_banner_url ? `url(${this.props.user.profile_banner_url + '/600x200'})` : 'none',
backgroundColor: !this.props.user.profile_banner_url ? `#${this.props.user.profile_link_color}` : 'transparent'
}} onClick={this.props.toggleSelect}></div>
<div className="card-block">
<div className="media">
<div className="media-left">
<img src={profile_image_url_https} width="73" height="73" className="media-left__icon" />
</div>
<div className="media-body">
<div className="card-title">
<div className="card-title__name">
{this.props.user.name}
</div>
<div className="card-title__screen-name">
<small>
<a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new" title={this.props.user.id_str}>@{this.props.user.screen_name}</a>
{this.props.user.protected ? (
<span>
<i className="fa fa-lock"></i>
</span>
) : null}
</small>
</div>
</div>
</div>
</div>
</div>
<ul className="list-group list-group-flush">
{
this.props.user.entities && this.props.user.entities.url ? (
<li className="list-group-item">
<a href={this.props.user.entities.url.urls[0].url} target="_new">
<i className="fa fa-link fa-fw"></i> {this.props.user.entities.url.urls[0].expanded_url ? this.props.user.entities.url.urls[0].expanded_url : this.props.user.entities.url.urls[0].url}</a>
</li>
) : null
}
{
this.props.user.location ? (
<li className="list-group-item">
<i className="fa fa-map-marker fa-fw"></i>
{this.props.user.location}
</li>
) : null
}
</ul>
{this.props.user.entities && !this.props.user.entities.url && !this.props.user.location ? <hr /> : null}
<div className="card-block">
<p className="card-text" dangerouslySetInnerHTML={{__html: description}}>
</p>
</div>
</li>
) : (
<tr onClick={e => {
if(['A', 'INPUT'].includes(e.target.tagName)) {
e.stopPropagation();
} else {
this.props.toggleSelect();
}
}}>
<td className="user-list-table__checkbox user-list-table__checkbox--row">
<input type="checkbox" checked={this.props.user.select} onChange={this.props.toggleSelect} />
</td>
<td className="user-list-table__name user-list-table__name--row"><img src={small_profile_image_url_https} width="24" height="24" /> {this.props.user.name}</td>
<td>
<a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new">{this.props.user.screen_name}</a>
{this.props.user.protected ? (
<span>
<i className="fa fa-lock"></i>
</span>
) : null}
</td>
<td>{this.props.user.friends_count}</td>
<td>{this.props.user.followers_count}</td>
<td>{this.props.user.status ? moment(new Date(this.props.user.status.created_at)).format('YYYY/MM/DD HH:mm:ss') : null}</td>
</tr>
);
}
}
User.propTypes = {
userId: PropTypes.string.isRequired,
user: PropTypes.object.isRequired,
settings: PropTypes.object.isRequired
};
User.defaultProps = {
userId: '0',
user: {},
settings: {}
};
function mapStateToProps(state, ownProps) {
return {
user: state.users.users.allUserInfo[ownProps.userId],
settings: state.settings
};
}
function mapDispatchToProps(dispatch, ownProps) {
return {
toggleSelect() {
dispatch(toggleSelect(ownProps.userId));
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(User);
| sunya9/follow-manager | src/containers/User.js | JavaScript | mit | 5,320 |
<?php
/**
* This file is part of the PPI Framework.
*
* @copyright Copyright (c) 2011-2013 Paul Dragoonis <paul@ppi.io>
* @license http://opensource.org/licenses/mit-license.php MIT
* @link http://www.ppi.io
*/
namespace PPICacheModule\Cache\Driver;
use PPICacheModule\Cache\CacheInterface;
/**
* Memory cache driver.
*
* @author Vítor Brandão <vitor@ppi.io>
* @package PPI
* @subpackage Cache
*/
class MemoryCache implements CacheInterface
{
/**
* @var array $data
*/
protected $data = array();
/**
* {@inheritdoc}
*/
public function get($key)
{
return isset($this->data[$key]) ? new CacheItem($key, $this->data[$key]) : false;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$this->data[$key] = $value;
return true;
}
/**
* {@inheritdoc}
*/
public function remove($key)
{
unset($this->data[$key]);
return true;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys)
{
$items = array();
foreach ($keys as $key) {
$items[$key] = $this->get($key);
}
return $items;
}
/**
* {@inheritdoc}
*/
public function setMultiple($items, $ttl = null)
{
$results = array();
foreach ($items as $key => $item) {
$this->data[$key] = $item;
$results[$key] = true;
}
return $results;
}
/**
* {@inheritdoc}
*/
public function removeMultiple($keys)
{
$results = array();
foreach ($keys as $key) {
unset($this->data[$key]);
$results[$key] = true;
}
return $results;
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->data = array();
return true;
}
}
| ppi/cache | Cache/Driver/MemoryCache.php | PHP | mit | 1,925 |
/***
* Textile parser for JavaScript
*
* Copyright (c) 2012 Borgar Þorsteinsson (MIT License).
*
*/
/*jshint
laxcomma:true
laxbreak:true
eqnull:true
loopfunc:true
sub:true
*/
;(function(){
"use strict";
/***
* Regular Expression helper methods
*
* This provides the `re` object, which contains several helper
* methods for working with big regular expressions (soup).
*
*/
var re = {
_cache: {}
, pattern: {
'punct': "[!-/:-@\\[\\\\\\]-`{-~]"
, 'space': '\\s'
}
, escape: function ( src ) {
return src.replace( /[\-\[\]\{\}\(\)\*\+\?\.\,\\\^\$\|\#\s]/g, "\\$&" );
}
, collapse: function ( src ) {
return src.replace( /(?:#.*?(?:\n|$))/g, '' )
.replace( /\s+/g, '' )
;
}
, expand_patterns: function ( src ) {
// TODO: provide escape for patterns: \[:pattern:] ?
return src.replace( /\[\:\s*(\w+)\s*\:\]/g, function ( m, k ) {
return ( k in re.pattern )
? re.expand_patterns( re.pattern[ k ] )
: k
;
})
;
}
, isRegExp: function ( r ) {
return Object.prototype.toString.call( r ) === "[object RegExp]";
}
, compile: function ( src, flags ) {
if ( re.isRegExp( src ) ) {
if ( arguments.length === 1 ) { // no flags arg provided, use the RegExp one
flags = ( src.global ? 'g' : '' ) +
( src.ignoreCase ? 'i' : '' ) +
( src.multiline ? 'm' : '' );
}
src = src.source;
}
// don't do the same thing twice
var ckey = src + ( flags || '' );
if ( ckey in re._cache ) { return re._cache[ ckey ]; }
// allow classes
var rx = re.expand_patterns( src );
// allow verbose expressions
if ( flags && /x/.test( flags ) ) {
rx = re.collapse( rx );
}
// allow dotall expressions
if ( flags && /s/.test( flags ) ) {
rx = rx.replace( /([^\\])\./g, '$1[^\\0]' );
}
// TODO: test if MSIE and add replace \s with [\s\u00a0] if it is?
// clean flags and output new regexp
flags = ( flags || '' ).replace( /[^gim]/g, '' );
return ( re._cache[ ckey ] = new RegExp( rx, flags ) );
}
};
/***
* JSONML helper methods - http://www.jsonml.org/
*
* This provides the `JSONML` object, which contains helper
* methods for rendering JSONML to HTML.
*
* Note that the tag ! is taken to mean comment, this is however
* not specified in the JSONML spec.
*
*/
var JSONML = {
escape: function ( text, esc_quotes ) {
return text.replace( /&(?!(#\d{2,}|#x[\da-fA-F]{2,}|[a-zA-Z][a-zA-Z1-4]{1,6});)/g, "&" )
.replace( /</g, "<" )
.replace( />/g, ">" )
.replace( /"/g, esc_quotes ? """ : '"' )
.replace( /'/g, esc_quotes ? "'" : "'" )
;
}
, toHTML: function ( jsonml ) {
jsonml = jsonml.concat();
// basic case
if ( typeof jsonml === "string" ) {
return JSONML.escape( jsonml );
}
var tag = jsonml.shift()
, attributes = {}
, content = []
, tag_attrs = ""
, a
;
if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !_isArray( jsonml[ 0 ] ) ) {
attributes = jsonml.shift();
}
while ( jsonml.length ) {
content.push( JSONML.toHTML( jsonml.shift() ) );
}
for ( a in attributes ) {
tag_attrs += ( attributes[ a ] == null )
? " " + a
: " " + a + '="' + JSONML.escape( String( attributes[ a ] ), true ) + '"'
;
}
// be careful about adding whitespace here for inline elements
if ( tag == "!" ) {
return "<!--" + content.join( "" ) + "-->";
}
else if ( tag === "img" || tag === "br" || tag === "hr" || tag === "input" ) {
return "<" + tag + tag_attrs + " />";
}
else {
return "<" + tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">";
}
}
};
// merge object b properties into obect a
function merge ( a, b ) {
for ( var k in b ) {
a[ k ] = b[ k ];
}
return a;
}
var _isArray = Array.isArray || function ( a ) { return Object.prototype.toString.call(a) === '[object Array]'; };
/* expressions */
re.pattern[ 'blocks' ] = '(?:b[qc]|div|notextile|pre|h[1-6]|fn\\d+|p|###)';
re.pattern[ 'pba_class' ] = '\\([^\\)]+\\)';
re.pattern[ 'pba_style' ] = '\\{[^\\}]+\\}';
re.pattern[ 'pba_lang' ] = '\\[[^\\[\\]]+\\]';
re.pattern[ 'pba_align' ] = '(?:<>|<|>|=)';
re.pattern[ 'pba_pad' ] = '[\\(\\)]+';
re.pattern[ 'pba_attr' ] = '(?:[:pba_class:]|[:pba_style:]|[:pba_lang:]|[:pba_align:]|[:pba_pad:])*';
re.pattern[ 'url_punct' ] = '[.,«»″‹›!?]';
re.pattern[ 'html_id' ] = '[a-zA-Z][a-zA-Z\\d:]*';
re.pattern[ 'html_attr' ] = '(?:"[^"]+"|\'[^\']+\'|[^>\\s]+)';
re.pattern[ 'tx_urlch' ] = '[\\w"$\\-_.+!*\'(),";\\/?:@=&%#{}|\\\\^~\\[\\]`]';
re.pattern[ 'tx_cite' ] = ':((?:[^\\s()]|\\([^\\s()]+\\)|[()])+?)(?=[!-\\.:-@\\[\\\\\\]-`{-~]+(?:$|\\s)|$|\\s)';
re.pattern[ 'listhd' ] = '[\\t ]*[\\#\\*]*(\\*|\\#(?:_|\\d+)?)[:pba_attr:](?: \\S|\\.\\s*(?=\\S|\\n))';
re.pattern[ 'ucaps' ] = "A-Z"+
// Latin extended À-Þ
"\u00c0-\u00d6\u00d8-\u00de"+
// Latin caps with embelishments and ligatures...
"\u0100\u0102\u0104\u0106\u0108\u010a\u010c\u010e\u0110\u0112\u0114\u0116\u0118\u011a\u011c\u011e\u0120\u0122\u0124\u0126\u0128\u012a\u012c\u012e\u0130\u0132\u0134\u0136\u0139\u013b\u013d\u013f"+
"\u0141\u0143\u0145\u0147\u014a\u014c\u014e\u0150\u0152\u0154\u0156\u0158\u015a\u015c\u015e\u0160\u0162\u0164\u0166\u0168\u016a\u016c\u016e\u0170\u0172\u0174\u0176\u0178\u0179\u017b\u017d"+
"\u0181\u0182\u0184\u0186\u0187\u0189-\u018b\u018e-\u0191\u0193\u0194\u0196-\u0198\u019c\u019d\u019f\u01a0\u01a2\u01a4\u01a6\u01a7\u01a9\u01ac\u01ae\u01af\u01b1-\u01b3\u01b5\u01b7\u01b8\u01bc"+
"\u01c4\u01c7\u01ca\u01cd\u01cf\u01d1\u01d3\u01d5\u01d7\u01d9\u01db\u01de\u01e0\u01e2\u01e4\u01e6\u01e8\u01ea\u01ec\u01ee\u01f1\u01f4\u01f6-\u01f8\u01fa\u01fc\u01fe"+
"\u0200\u0202\u0204\u0206\u0208\u020a\u020c\u020e\u0210\u0212\u0214\u0216\u0218\u021a\u021c\u021e\u0220\u0222\u0224\u0226\u0228\u022a\u022c\u022e\u0230\u0232\u023a\u023b\u023d\u023e"+
"\u0241\u0243-\u0246\u0248\u024a\u024c\u024e"+
"\u1e00\u1e02\u1e04\u1e06\u1e08\u1e0a\u1e0c\u1e0e\u1e10\u1e12\u1e14\u1e16\u1e18\u1e1a\u1e1c\u1e1e\u1e20\u1e22\u1e24\u1e26\u1e28\u1e2a\u1e2c\u1e2e\u1e30\u1e32\u1e34\u1e36\u1e38\u1e3a\u1e3c\u1e3e\u1e40"+
"\u1e42\u1e44\u1e46\u1e48\u1e4a\u1e4c\u1e4e\u1e50\u1e52\u1e54\u1e56\u1e58\u1e5a\u1e5c\u1e5e\u1e60\u1e62\u1e64\u1e66\u1e68\u1e6a\u1e6c\u1e6e\u1e70\u1e72\u1e74\u1e76\u1e78\u1e7a\u1e7c\u1e7e"+
"\u1e80\u1e82\u1e84\u1e86\u1e88\u1e8a\u1e8c\u1e8e\u1e90\u1e92\u1e94\u1e9e\u1ea0\u1ea2\u1ea4\u1ea6\u1ea8\u1eaa\u1eac\u1eae\u1eb0\u1eb2\u1eb4\u1eb6\u1eb8\u1eba\u1ebc\u1ebe"+
"\u1ec0\u1ec2\u1ec4\u1ec6\u1ec8\u1eca\u1ecc\u1ece\u1ed0\u1ed2\u1ed4\u1ed6\u1ed8\u1eda\u1edc\u1ede\u1ee0\u1ee2\u1ee4\u1ee6\u1ee8\u1eea\u1eec\u1eee\u1ef0\u1ef2\u1ef4\u1ef6\u1ef8\u1efa\u1efc\u1efe"+
"\u2c60\u2c62-\u2c64\u2c67\u2c69\u2c6b\u2c6d-\u2c70\u2c72\u2c75\u2c7e\u2c7f"+
"\ua722\ua724\ua726\ua728\ua72a\ua72c\ua72e\ua732\ua734\ua736\ua738\ua73a\ua73c\ua73e"+
"\ua740\ua742\ua744\ua746\ua748\ua74a\ua74c\ua74e\ua750\ua752\ua754\ua756\ua758\ua75a\ua75c\ua75e\ua760\ua762\ua764\ua766\ua768\ua76a\ua76c\ua76e\ua779\ua77b\ua77d\ua77e"+
"\ua780\ua782\ua784\ua786\ua78b\ua78d\ua790\ua792\ua7a0\ua7a2\ua7a4\ua7a6\ua7a8\ua7aa";
var re_block = re.compile( /^([:blocks:])/ )
, re_block_se = re.compile( /^[:blocks:]$/ )
, re_block_normal = re.compile( /^(.*?)($|\r?\n(?=[:listhd:])|\r?\n(?:\s*\n|$)+)/, 's' )
, re_block_extended = re.compile( /^(.*?)($|\r?\n(?=[:listhd:])|\r?\n+(?=[:blocks:][:pba_attr:]\.))/, 's' )
, re_ruler = /^(\-\-\-+|\*\*\*+|___+)(\r?\n\s+|$)/
, re_list = re.compile( /^((?:[:listhd:][^\0]*?(?:\r?\n|$))+)(\s*\n|$)/,'s' )
, re_list_item = re.compile( /^([\#\*]+)([^\0]+?)(\n(?=[:listhd:])|$)/, 's' )
, re_deflist = /^((?:- (?:[^\n]\n?)+?)+:=(?: *\n[^\0]+?=:(?:\n|$)|(?:[^\0]+?(?:$|\n(?=\n|- )))))+/
, re_deflist_item = /^((?:- (?:[^\n]\n?)+?)+):=( *\n[^\0]+?=:\s*(?:\n|$)|(?:[^\0]+?(?:$|\n(?=\n|- ))))/
, re_table = re.compile( /^((?:table[:pba_attr:]\.\n)?(?:(?:[:pba_attr:]\.[^\n\S]*)?\|.*?\|[^\n\S]*(?:\n|$))+)([^\n\S]*\n)?/, 's' )
, re_table_head = /^table(_?)([^\n]+)\.\s?\n/
, re_table_row = re.compile( /^([:pba_attr:]\.[^\n\S]*)?\|(.*?)\|[^\n\S]*(\n|$)/, 's' )
, re_fenced_phrase = /^\[(__?|\*\*?|\?\?|[\-\+\^~@%])([^\n]+)\1\]/
, re_phrase = /^([\[\{]?)(__?|\*\*?|\?\?|[\-\+\^~@%])/
, re_text = re.compile( /^.+?(?=[\\<!\[_\*`]|\n|$)/, 's' )
, re_image = re.compile( /^!(?!\s)([:pba_attr:](?:\.[^\n\S]|\.(?:[^\.\/]))?)([^!\s]+?) ?(?:\(((?:[^\(\)]+|\([^\(\)]+\))+)\))?!(?::([^\s]+?(?=[!-\.:-@\[\\\]-`{-~](?:$|\s)|\s|$)))?/ )
, re_image_fenced = re.compile( /^\[!(?!\s)([:pba_attr:](?:\.[^\n\S]|\.(?:[^\.\/]))?)([^!\s]+?) ?(?:\(((?:[^\(\)]+|\([^\(\)]+\))+)\))?!(?::([^\s]+?(?=[!-\.:-@\[\\\]-`{-~](?:$|\s)|\s|$)))?\]/ )
// NB: there is an exception in here to prevent matching "TM)"
, re_caps = re.compile( /^((?!TM\)|tm\))[[:ucaps:]](?:[[:ucaps:]\d]{1,}(?=\()|[[:ucaps:]\d]{2,}))(?:\((.*?)\))?(?=\W|$)/ )
, re_link = re.compile( /^"(?!\s)((?:[^\n"]|"(?![\s:])[^\n"]+"(?!:))+)"[:tx_cite:]/ )
, re_link_fenced = /^\["([^\n]+?)":((?:\[[a-z0-9]*\]|[^\]])+)\]/
, re_link_ref = re.compile( /^\[([^\]]+)\]((?:https?:\/\/|\/)\S+)(?:\s*\n|$)/ )
, re_link_title = /\s*\(((?:\([^\(\)]*\)|[^\(\)])+)\)$/
, re_footnote_def = /^fn\d+$/
, re_footnote = /^\[(\d+)(\!?)\]/
// HTML
, re_html_tag_block = re.compile( /^\s*<([:html_id:](?::[a-zA-Z\d]+)*)((?:\s[^=\s\/]+(?:\s*=\s*[:html_attr:])?)+)?\s*(\/?)>(\n*)/ )
, re_html_tag = re.compile( /^<([:html_id:])((?:\s[^=\s\/]+(?:\s*=\s*[:html_attr:])?)+)?\s*(\/?)>(\n*)/ )
, re_html_comment = re.compile( /^<!--(.+?)-->/, 's' )
, re_html_end_tag = re.compile( /^<\/([:html_id:])([^>]*)>/ )
, re_html_attr = re.compile( /^\s*([^=\s]+)(?:\s*=\s*("[^"]+"|'[^']+'|[^>\s]+))?/ )
, re_entity = /&(#\d\d{2,}|#x[\da-fA-F]{2,}|[a-zA-Z][a-zA-Z1-4]{1,6});/
// glyphs
, re_dimsign = /([\d\.,]+['"]? ?)x( ?)(?=[\d\.,]['"]?)/g
, re_emdash = /(^|[\s\w])--([\s\w]|$)/g
, re_trademark = /(\b ?|\s|^)(?:\((?:TM|tm)\)|\[(?:TM|tm)\])/g
, re_registered = /(\b ?|\s|^)(?:\(R\)|\[R\])/gi
, re_copyright = /(\b ?|\s|^)(?:\(C\)|\[C\])/gi
, re_apostrophe = /(\w)\'(\w)/g
, re_double_prime = re.compile( /(\d*[\.,]?\d+)"(?=\s|$|[:punct:])/g )
, re_single_prime = re.compile( /(\d*[\.,]?\d+)'(?=\s|$|[:punct:])/g )
, re_closing_dquote = re.compile( /([^\s\[\(])"(?=$|\s|[:punct:])/g )
, re_closing_squote = re.compile( /([^\s\[\(])'(?=$|\s|[:punct:])/g )
// pba
, re_pba_classid = /^\(([^\(\)\n]+)\)/
, re_pba_padding_l = /^(\(+)/
, re_pba_padding_r = /^(\)+)/
, re_pba_align_blk = /^(<>|<|>|=)/
, re_pba_align_img = /^(<|>|=)/
, re_pba_valign = /^(~|\^|\-)/
, re_pba_colspan = /^\\(\d+)/
, re_pba_rowspan = /^\/(\d+)/
, re_pba_styles = /^\{([^\}]*)\}/
, re_pba_css = /^\s*([^:\s]+)\s*:\s*(.+)\s*$/
, re_pba_lang = /^\[([^\[\]\n]+)\]/
;
var phrase_convert = {
'*': 'strong'
, '**': 'b'
, '??': 'cite'
, '_': 'em'
, '__': 'i'
, '-': 'del'
, '%': 'span'
, '+': 'ins'
, '~': 'sub'
, '^': 'sup'
, '@': 'code'
};
// area, base, basefont, bgsound, br, col, command, embed, frame, hr,
// img, input, keygen, link, meta, param, source, track or wbr
var html_singletons = {
'br': 1
, 'hr': 1
, 'img': 1
, 'link': 1
, 'meta': 1
, 'wbr': 1
, 'area': 1
, 'param': 1
, 'input': 1
, 'option': 1
, 'base': 1
};
var pba_align_lookup = {
'<': 'left'
, '=': 'center'
, '>': 'right'
, '<>': 'justify'
};
var pba_valign_lookup = {
'~':'bottom'
, '^':'top'
, '-':'middle'
};
// HTML tags allowed in the document (root) level that trigger HTML parsing
var allowed_blocktags = {
'p': 0
, 'hr': 0
, 'ul': 1
, 'ol': 0
, 'li': 0
, 'div': 1
, 'pre': 0
, 'object': 1
, 'script': 0
, 'noscript': 0
, 'blockquote': 1
, 'notextile': 1
};
function ribbon ( feed ) {
var _slot = null
, org = feed + ''
, pos = 0
;
return {
save: function () {
_slot = pos;
}
, load: function () {
pos = _slot;
feed = org.slice( pos );
}
, advance: function ( n ) {
pos += ( typeof n === 'string' ) ? n.length : n;
return ( feed = org.slice( pos ) );
}
, lookbehind: function ( nchars ) {
nchars = nchars == null ? 1 : nchars;
return org.slice( pos - nchars, pos );
}
, startsWith: function ( s ) {
return feed.substring(0, s.length) === s;
}
, valueOf: function(){
return feed;
}
, toString: function(){
return feed;
}
};
}
function builder ( arr ) {
var _arr = _isArray( arr ) ? arr : [];
return {
add: function ( node ) {
if ( typeof node === 'string' &&
typeof _arr[_arr.length - 1 ] === 'string' ) {
// join if possible
_arr[ _arr.length - 1 ] += node;
}
else if ( _isArray( node ) ) {
var f = node.filter(function(s){ return s !== undefined; });
_arr.push( f );
}
else if ( node ) {
_arr.push( node );
}
return this;
}
, merge: function ( s ) {
for (var i=0,l=s.length; i<l; i++) {
this.add( s[i] );
}
return this;
}
, linebreak: function () {
if ( _arr.length ) {
this.add( '\n' );
}
}
, get: function () {
return _arr;
}
};
}
function copy_pba ( s, blacklist ) {
if ( !s ) { return undefined; }
var k, d = {};
for ( k in s ) {
if ( k in s && ( !blacklist || !(k in blacklist) ) ) {
d[ k ] = s[ k ];
}
}
return d;
}
function parse_html_attr ( attr ) {
// parse ATTR and add to element
var _attr = {}
, m
, val
;
while ( (m = re_html_attr.exec( attr )) ) {
_attr[ m[1] ] = ( typeof m[2] === 'string' )
? m[2].replace( /^(["'])(.*)\1$/, '$2' )
: null
;
attr = attr.slice( m[0].length );
}
return _attr;
}
// This "indesciminately" parses HTML text into a list of JSON-ML element
// No steps are taken however to prevent things like <table><p><td> - user can still create nonsensical but "well-formed" markup
function parse_html ( src, whitelist_tags ) {
var org = src + ''
, list = []
, root = list
, _stack = []
, m
, oktag = whitelist_tags ? function ( tag ) { return tag in whitelist_tags; } : function () { return true; }
, tag
;
src = (typeof src === 'string') ? ribbon( src ) : src;
// loop
do {
if ( (m = re_html_comment.exec( src )) && oktag('!') ) {
src.advance( m[0] );
list.push( [ '!', m[1] ] );
}
// end tag
else if ( (m = re_html_end_tag.exec( src )) && oktag(m[1]) ) {
tag = m[1];
var junk = m[2];
if ( _stack.length ) {
for (var i=_stack.length-1; i>=0; i--) {
var head = _stack[i];
if ( head[0] === tag ) {
_stack.splice( i );
list = _stack[ _stack.length - 1 ] || root;
break;
}
}
}
src.advance( m[0] );
}
// open/void tag
else if ( (m = re_html_tag.exec( src )) && oktag(m[1]) ) {
src.advance( m[0] );
tag = m[1];
var single = m[3] || m[1] in html_singletons
, tail = m[4]
, element = [ tag ]
;
// attributes
if ( m[2] ) { element.push( parse_html_attr( m[2] ) ); }
// tag
if ( single ) { // single tag
// let us add the element and continue our quest...
list.push( element );
if ( tail ) { list.push( tail ); }
}
else { // open tag
if ( tail ) { element.push( tail ); }
// TODO: some things auto close other things: <td>, <li>, <p>, <table>
// if ( tag === 'p' && _stack.length ) {
// var seek = /^(p)$/;
// for (var i=_stack.length-1; i>=0; i--) {
// var head = _stack[i];
// if ( seek.test( head[0] ) /* === tag */ ) {
// //src.advance( m[0] );
// _stack.splice( i );
// list = _stack[i] || root;
// }
// }
// }
// TODO: some elements can move parser into "text" mode
// style, xmp, iframe, noembed, noframe, textarea, title, script, noscript, plaintext
//if ( /^(script)$/.test( tag ) ) { }
_stack.push( element );
list.push( element );
list = element;
}
}
else {
// no match, move by all "uninteresting" chars
m = /([^<]+|[^\0])/.exec( src );
if ( m ) {
list.push( m[0] );
}
src.advance( m ? m[0].length || 1 : 1 );
}
}
while ( src.valueOf() );
return root;
}
/* attribute parser */
function parse_attr ( input, element, end_token ) {
/*
The attr bit causes massive problems for span elements when parentheses are used.
Parentheses are a total mess and, unsurprisingly, cause trip-ups:
RC: `_{display:block}(span) span (span)_` -> `<em style="display:block;" class="span">(span) span (span)</em>`
PHP: `_{display:block}(span) span (span)_` -> `<em style="display:block;">(span) span (span)</em>`
PHP and RC seem to mostly solve this by not parsing a final attr parens on spans if the
following character is a non-space. I've duplicated that: Class/ID is not matched on spans
if it is followed by `end_token` or <space>.
Lang is not matched here if it is followed by the end token. Theoretically I could limit the lang
attribute to /^\[[a-z]{2+}(\-[a-zA-Z0-9]+)*\]/ because Textile is layered on top of HTML which
only accepts valid BCP 47 language tags, but who knows what atrocities are being preformed
out there in the real world. So this attempts to emulate the other libraries.
*/
input += '';
if ( !input || element === 'notextile' ) { return undefined; }
var m
, st = {}
, o = { 'style': st }
, remaining = input
, is_block = element === 'table' || element === 'td' || re_block_se.test( element ) // "in" test would be better but what about fn#.?
, is_img = element === 'img'
, is_list = element === 'li'
, is_phrase = !is_block && !is_img && element !== 'a'
, re_pba_align = ( is_img ) ? re_pba_align_img : re_pba_align_blk
;
do {
if ( (m = re_pba_styles.exec( remaining )) ) {
m[1].split(';').forEach(function(p){
var d = p.match( re_pba_css );
if ( d ) { st[ d[1] ] = d[2]; }
});
remaining = remaining.slice( m[0].length );
continue;
}
if ( (m = re_pba_lang.exec( remaining )) ) {
var rm = remaining.slice( m[0].length );
if (
( !rm && is_phrase ) ||
( end_token && end_token === rm.slice(0,end_token.length) )
) {
m = null;
}
else {
o['lang'] = m[1];
remaining = remaining.slice( m[0].length );
}
continue;
}
if ( (m = re_pba_classid.exec( remaining )) ) {
var rm = remaining.slice( m[0].length );
if (
( !rm && is_phrase ) ||
( end_token && (rm[0] === ' ' || end_token === rm.slice(0,end_token.length)) )
) {
m = null;
}
else {
var bits = m[1].split( '#' );
if ( bits[0] ) { o['class'] = bits[0]; }
if ( bits[1] ) { o['id'] = bits[1]; }
remaining = rm;
}
continue;
}
if ( is_block || is_list ) {
if ( (m = re_pba_padding_l.exec( remaining )) ) {
st[ "padding-left" ] = ( m[1].length ) + "em";
remaining = remaining.slice( m[0].length );
continue;
}
if ( (m = re_pba_padding_r.exec( remaining )) ) {
st[ "padding-right" ] = ( m[1].length ) + "em";
remaining = remaining.slice( m[0].length );
continue;
}
}
// only for blocks:
if ( is_img || is_block || is_list ) {
if ( (m = re_pba_align.exec( remaining )) ) {
var align = pba_align_lookup[ m[1] ];
if ( is_img ) {
o[ 'align' ] = align;
}
else {
st[ 'text-align' ] = align;
}
remaining = remaining.slice( m[0].length );
continue;
}
}
// only for table cells
if ( element === 'td' || element === 'tr' ) {
if ( (m = re_pba_valign.exec( remaining )) ) {
st[ "vertical-align" ] = pba_valign_lookup[ m[1] ];
remaining = remaining.slice( m[0].length );
continue;
}
}
if ( element === 'td' ) {
if ( (m = re_pba_colspan.exec( remaining )) ) {
o[ "colspan" ] = m[1];
remaining = remaining.slice( m[0].length );
continue;
}
if ( (m = re_pba_rowspan.exec( remaining )) ) {
o[ "rowspan" ] = m[1];
remaining = remaining.slice( m[0].length );
continue;
}
}
}
while ( m );
// collapse styles
var s = [];
for ( var v in st ) { s.push( v + ':' + st[v] ); }
if ( s.length ) { o.style = s.join(';'); } else { delete o.style; }
return remaining == input
? undefined
: [ input.length - remaining.length, o ]
;
}
/* glyph parser */
function parse_glyphs ( src ) {
if ( typeof src !== 'string' ) { return src; }
// NB: order is important here ...
return src
// arrow
.replace( /([^\-]|^)->/, '$1→' ) // arrow
// dimensions
.replace( re_dimsign, '$1×$2' ) // dimension sign
// ellipsis
.replace( /([^.]?)\.{3}/g, '$1…' ) // ellipsis
// dashes
.replace( re_emdash, '$1—$2' ) // em dash
.replace( / - /g, ' – ' ) // en dash
// legal marks
.replace( re_trademark, '$1™' ) // trademark
.replace( re_registered, '$1®' ) // registered
.replace( re_copyright, '$1©' ) // copyright
// double quotes
.replace( re_double_prime, '$1″' ) // double prime
.replace( re_closing_dquote, '$1”' ) // double closing quote
.replace( /"/g, '“' ) // double opening quote
// single quotes
.replace( re_single_prime, '$1′' ) // single prime
.replace( re_apostrophe, '$1’$2' ) // I'm an apostrophe
.replace( re_closing_squote, '$1’' ) // single closing quote
.replace( /'/g, '‘' )
// fractions and degrees
.replace( /[\(\[]1\/4[\]\)]/, '¼' )
.replace( /[\(\[]1\/2[\]\)]/, '½' )
.replace( /[\(\[]3\/4[\]\)]/, '¾' )
.replace( /[\(\[]o[\]\)]/, '°' )
.replace( /[\(\[]\+\/\-[\]\)]/, '±' )
;
}
/* list parser */
function list_pad ( n ) {
var s = '\n';
while ( n-- ) { s += '\t'; }
return s;
}
function parse_list ( src, options ) {
src = ribbon( src.replace( /(^|\r?\n)[\t ]+/, '$1' ) );
var stack = []
, curr_idx = {}
, last_idx = options._lst || {}
, list_pba
, item_index = 0
, m
, n
, s
;
while ( (m = re_list_item.exec( src )) ) {
var item = [ 'li' ]
, start_index = 0
, dest_level = m[1].length
, type = m[1].substr(-1) === '#' ? 'ol' : 'ul'
, new_li = null
, lst
, par
, pba
, r
;
// list starts and continuations
if ( n = /^(_|\d+)/.exec( m[2] ) ) {
item_index = isFinite( n[1] )
? parseInt( n[1], 10 )
: last_idx[ dest_level ] || curr_idx[ dest_level ] || 1;
m[2] = m[2].slice( n[1].length );
}
if ( pba = parse_attr( m[2], 'li' ) ) {
m[2] = m[2].slice( pba[0] );
pba = pba[1];
}
// list control
if ( /^\.\s*$/.test( m[2] ) ) {
list_pba = pba || {};
src.advance( m[0] );
continue;
}
// create nesting until we have correct level
while ( stack.length < dest_level ) {
// list always has an attribute object, this simplifies first-pba resolution
lst = [ type, {}, list_pad( stack.length + 1 ), (new_li = [ 'li' ]) ];
par = stack[ stack.length - 1 ];
if ( par ) {
par.li.push( list_pad( stack.length ) );
par.li.push( lst );
}
stack.push({
ul: lst
, li: new_li
, att: 0 // count pba's found per list
});
curr_idx[ stack.length ] = 1;
}
// remove nesting until we have correct level
while ( stack.length > dest_level ) {
r = stack.pop();
r.ul.push( list_pad( stack.length ) );
// lists have a predictable structure - move pba from listitem to list
if ( r.att === 1 && !r.ul[3][1].substr ) {
merge( r.ul[1], r.ul[3].splice( 1, 1 )[ 0 ] );
}
}
// parent list
par = stack[ stack.length - 1 ];
// have list_pba or start_index?
if ( item_index ) {
par.ul[1].start = curr_idx[ dest_level ] = item_index;
item_index = 0; // falsy prevents this from fireing until it is set again
}
if ( list_pba ) {
par.att = 9; // "more than 1" prevent pba transfers on list close
merge( par.ul[1], list_pba );
list_pba = null;
}
if ( !new_li ) {
par.ul.push( list_pad( stack.length ), item );
par.li = item;
}
if ( pba ) {
par.li.push( pba );
par.att++;
}
Array.prototype.push.apply( par.li, parse_inline( m[2].trim(), options ) );
src.advance( m[0] );
curr_idx[ dest_level ] = (curr_idx[ dest_level ] || 0) + 1;
}
// remember indexes for continuations next time
options._lst = curr_idx;
while ( stack.length ) {
s = stack.pop();
s.ul.push( list_pad( stack.length ) );
// lists have a predictable structure - move pba from listitem to list
if ( s.att === 1 && !s.ul[3][1].substr ) {
merge( s.ul[1], s.ul[3].splice( 1, 1 )[ 0 ] );
}
}
return s.ul;
}
/* definitions list parser */
function parse_deflist ( src, options ) {
src = ribbon( src.trim() );
var deflist = [ 'dl', '\n' ]
, terms
, def
, m
;
while ( (m = re_deflist_item.exec( src )) ) {
// add terms
terms = m[1].split( /(?:^|\n)\- / ).slice(1);
while ( terms.length ) {
deflist.push( '\t'
, [ 'dt' ].concat( parse_inline( terms.shift().trim(), options ) )
, '\n'
);
}
// add definitions
def = m[2].trim();
deflist.push( '\t'
, [ 'dd' ].concat(
/=:$/.test( def )
? parse_blocks( def.slice(0,-2).trim(), options )
: parse_inline( def, options )
)
, '\n'
);
src.advance( m[0] );
}
return deflist;
}
/* table parser */
function parse_table ( src, options ) {
src = ribbon( src.trim() );
var table = [ 'table' ]
, row
, inner
, pba
, more
, m
;
if ( (m = re_table_head.exec( src )) ) {
// parse and apply table attr
src.advance( m[0] );
pba = parse_attr( m[2], 'table' );
if ( pba ) {
table.push( pba[1] );
}
}
while ( (m = re_table_row.exec( src )) ) {
row = [ 'tr' ];
if ( m[1] && (pba = parse_attr( m[1], 'tr' )) ) {
// FIXME: requires "\.\s?" -- else what ?
row.push( pba[1] );
}
table.push( '\n\t', row );
inner = ribbon( m[2] );
do {
inner.save();
// cell loop
var th = inner.startsWith( '_' )
, cell = [ th ? 'th' : 'td' ]
;
if ( th ) {
inner.advance( 1 );
}
pba = parse_attr( inner, 'td' );
if ( pba ) {
inner.advance( pba[0] );
cell.push( pba[1] ); // FIXME: don't do this if next text fails
}
if ( pba || th ) {
var d = /^\.\s*/.exec( inner );
if ( d ) {
inner.advance( d[0] );
}
else {
cell = [ 'td' ];
inner.load();
}
}
var mx = /^(==.*?==|[^\|])*/.exec( inner );
cell = cell.concat( parse_inline( mx[0], options ) );
row.push( '\n\t\t', cell );
more = inner.valueOf().charAt( mx[0].length ) === '|';
inner.advance( mx[0].length + 1 );
}
while ( more );
row.push( '\n\t' );
src.advance( m[0] );
}
table.push( '\n' );
return table;
}
/* inline parser */
function parse_inline ( src, options ) {
src = ribbon( src );
var list = builder()
, m
, pba
;
// loop
do {
src.save();
// linebreak -- having this first keeps it from messing to much with other phrases
if ( src.startsWith( '\r\n' ) ) {
src.advance( 1 ); // skip cartridge returns
}
if ( src.startsWith( '\n' ) ) {
src.advance( 1 );
if ( options.breaks ) {
list.add( [ 'br' ] );
}
list.add( '\n' );
continue;
}
// inline notextile
if ( (m = /^==(.*?)==/.exec( src )) ) {
src.advance( m[0] );
list.add( m[1] );
continue;
}
// lookbehind => /([\s>.,"'?!;:])$/
var behind = src.lookbehind( 1 );
var boundary = !behind || /^[\s>.,"'?!;:()]$/.test( behind );
// FIXME: need to test right boundary for phrases as well
if ( (m = re_phrase.exec( src )) && ( boundary || m[1] ) ) {
src.advance( m[0] );
var tok = m[2]
, fence = m[1]
, phrase_type = phrase_convert[ tok ]
, code = phrase_type === 'code'
;
if ( (pba = !code && parse_attr( src, phrase_type, tok )) ) {
src.advance( pba[0] );
pba = pba[1];
}
// FIXME: if we can't match the fence on the end, we should output fence-prefix as normal text
// seek end
var m_mid;
var m_end;
if ( fence === '[' ) {
m_mid = '^(.*?)';
m_end = '(?:])';
}
else if ( fence === '{' ) {
m_mid = '^(.*?)';
m_end = '(?:})';
}
else {
var t1 = re.escape( tok.charAt(0) );
m_mid = ( code )
? '^(\\S+|\\S+.*?\\S)'
: '^([^\\s' + t1 + ']+|[^\\s' + t1 + '].*?\\S('+t1+'*))'
;
m_end = '(?=$|[\\s.,"\'!?;:()«»„“”‚‘’])';
}
var rx = re.compile( m_mid + '(' + re.escape( tok ) + ')' + m_end );
if ( (m = rx.exec( src )) && m[1] ) {
src.advance( m[0] );
if ( code ) {
list.add( [ phrase_type, m[1] ] );
}
else {
list.add( [ phrase_type, pba ].concat( parse_inline( m[1], options ) ) );
}
continue;
}
// else
src.load();
}
// image
if ( (m = re_image.exec( src )) || (m = re_image_fenced.exec( src )) ) {
src.advance( m[0] );
pba = m[1] && parse_attr( m[1], 'img' );
var attr = pba ? pba[1] : { 'src':'' }
, img = [ 'img', attr ]
;
attr.src = m[2];
attr.alt = m[3] ? ( attr.title = m[3] ) : '';
if ( m[4] ) { // +cite causes image to be wraped with a link (or link_ref)?
// TODO: support link_ref for image cite
img = [ 'a', { 'href': m[4] }, img ];
}
list.add( img );
continue;
}
// html comment
if ( (m = re_html_comment.exec( src )) ) {
src.advance( m[0] );
list.add( [ '!', m[1] ] );
continue;
}
// html tag
// TODO: this seems to have a lot of overlap with block tags... DRY?
if ( (m = re_html_tag.exec( src )) ) {
src.advance( m[0] );
var tag = m[1]
, single = m[3] || m[1] in html_singletons
, element = [ tag ]
, tail = m[4]
;
if ( m[2] ) {
element.push( parse_html_attr( m[2] ) );
}
if ( single ) { // single tag
list.add( element ).add( tail );
continue;
}
else { // need terminator
// gulp up the rest of this block...
var re_end_tag = re.compile( "^(.*?)(</" + tag + "\\s*>)", 's' );
if ( (m = re_end_tag.exec( src )) ) {
src.advance( m[0] );
if ( tag === 'code' ) {
element.push( tail, m[1] );
}
else if ( tag === 'notextile' ) {
list.merge( parse_inline( m[1], options ) );
continue;
}
else {
element = element.concat( parse_inline( m[1], options ) );
}
list.add( element );
continue;
}
// end tag is missing, treat tag as normal text...
}
src.load();
}
// footnote
if ( (m = re_footnote.exec( src )) && /\S/.test( behind ) ) {
src.advance( m[0] );
list.add( [ 'sup', { 'class': 'footnote', 'id': 'fnr' + m[1] },
( m[2] === '!' ? m[1] // "!" suppresses the link
: [ 'a', { href: '#fn' + m[1] }, m[1] ] )
] );
continue;
}
// caps / abbr
if ( (m = re_caps.exec( src )) ) {
src.advance( m[0] );
var caps = [ 'span', { 'class': 'caps' }, m[1] ];
if ( m[2] ) {
caps = [ 'acronym', { 'title': m[2] }, caps ]; // FIXME: use <abbr>, not acronym!
}
list.add( caps );
continue;
}
// links
if ( (boundary && (m = re_link.exec( src ))) || (m = re_link_fenced.exec( src )) ) {
src.advance( m[0].length );
var title = m[1].match( re_link_title )
, inner = ( title ) ? m[1].slice( 0, m[1].length - title[0].length ) : m[1]
;
if ( (pba = parse_attr( inner, 'a' )) ) {
inner = inner.slice( pba[0] );
pba = pba[1];
}
else {
pba = {};
}
if ( title && !inner ) { inner = title[0]; title = ""; }
pba.href = m[2];
if ( title ) { pba.title = title[1]; }
list.add( [ 'a', pba ].concat( parse_inline( inner.replace( /^(\.?\s*)/, '' ), options ) ) );
continue;
}
// no match, move by all "uninteresting" chars
m = /([a-zA-Z0-9,.':]+|[ \f\r\t\v\xA0\u2028\u2029]+|[^\0])/.exec( src );
if ( m ) {
list.add( m[0] );
}
src.advance( m ? m[0].length || 1 : 1 );
}
while ( src.valueOf() );
return list.get().map( parse_glyphs );
}
/* block parser */
function parse_blocks ( src, options ) {
var list = builder()
, paragraph = function ( s, tag, pba, linebreak ) {
tag = tag || 'p';
var out = [];
s.split( /(?:\r?\n){2,}/ ).forEach(function( bit, i ) {
if ( tag === 'p' && /^\s/.test( bit ) ) {
// no-paragraphs
// WTF?: Why does Textile not allow linebreaks in spaced lines
bit = bit.replace( /\r?\n[\t ]/g, ' ' ).trim();
out = out.concat( parse_inline( bit, options ) );
}
else {
if ( linebreak && i ) { out.push( linebreak ); }
out.push( pba ? [ tag, pba ].concat( parse_inline( bit, options ) )
: [ tag ].concat( parse_inline( bit, options ) ) );
}
});
return out;
}
, link_refs = {}
, m
;
src = ribbon( src.replace( /^( *\r?\n)+/, '' ) );
// loop
while ( src.valueOf() ) {
src.save();
// link_ref -- this goes first because it shouldn't trigger a linebreak
if ( (m = re_link_ref.exec( src )) ) {
src.advance( m[0] );
link_refs[ m[1] ] = m[2];
continue;
}
// add linebreak
list.linebreak();
// named block
if ( (m = re_block.exec( src )) ) {
src.advance( m[0] );
var block_type = m[0]
, pba = parse_attr( src, block_type )
;
if ( pba ) {
src.advance( pba[0] );
pba = pba[1];
}
if ( (m = /^\.(\.?)(?:\s|(?=:))/.exec( src )) ) {
// FIXME: this whole copy_pba seems rather strange?
// slurp rest of block
var extended = !!m[1];
m = ( extended ? re_block_extended : re_block_normal ).exec( src.advance( m[0] ) );
src.advance( m[0] );
// bq | bc | notextile | pre | h# | fn# | p | ###
if ( block_type === 'bq' ) {
var cite, inner = m[1];
if ( (m = /^:(\S+)\s+/.exec( inner )) ) {
if ( !pba ) { pba = {}; }
pba.cite = m[1];
inner = inner.slice( m[0].length );
}
// RedCloth adds all attr to both: this is bad because it produces duplicate IDs
list.add( [ 'blockquote', pba, '\n' ].concat(
paragraph( inner, 'p', copy_pba(pba, { 'cite':1, 'id':1 }), '\n' )
).concat(['\n']) );
}
else if ( block_type === 'bc' ) {
var sub_pba = ( pba ) ? copy_pba(pba, { 'id':1 }) : null;
list.add( [ 'pre', pba, ( sub_pba ? [ 'code', sub_pba, m[1] ] : [ 'code', m[1] ] ) ] );
}
else if ( block_type === 'notextile' ) {
list.merge( parse_html( m[1] ) );
}
else if ( block_type === '###' ) {
// ignore the insides
}
else if ( block_type === 'pre' ) {
// I disagree with RedCloth, but agree with PHP here:
// "pre(foo#bar).. line1\n\nline2" prevents multiline preformat blocks
// ...which seems like the whole point of having an extended pre block?
list.add( [ 'pre', pba, m[1] ] );
}
else if ( re_footnote_def.test( block_type ) ) { // footnote
// Need to be careful: RedCloth fails "fn1(foo#m). footnote" -- it confuses the ID
var fnid = block_type.replace( /\D+/g, '' );
if ( !pba ) { pba = {}; }
pba['class'] = ( pba['class'] ? pba['class'] + ' ' : '' ) + 'footnote';
pba['id'] = 'fn' + fnid;
list.add( [ "p", pba, [ 'a', { 'href': '#fnr' + fnid }, [ 'sup', fnid ] ], ' ' ].concat( parse_inline( m[1], options ) ) );
}
else { // heading | paragraph
list.merge( paragraph( m[1], block_type, pba, '\n' ) );
}
continue;
}
else {
src.load();
}
}
// HTML comment
if ( (m = re_html_comment.exec( src )) ) {
src.advance( m[0] + (/(?:\s*\n+)+/.exec( src ) || [])[0] );
list.add( [ '!', m[1] ] );
continue;
}
// block HTML
if ( (m = re_html_tag_block.exec( src )) ) {
var tag = m[1]
, single = m[3] || tag in html_singletons
, tail = m[4]
;
// Unsurprisingly, all Textile implementations I have tested have trouble parsing simple HTML:
//
// "<div>a\n<div>b\n</div>c\n</div>d"
//
// I simply match them here as there is no way anyone is using nested HTML today, or if they
// are, then this will at least output less broken HTML as redundant tags will get quoted.
// Is block tag? ...
if ( tag in allowed_blocktags ) {
src.advance( m[0] );
var element = [ tag ];
if ( m[2] ) {
element.push( parse_html_attr( m[2] ) );
}
if ( single ) { // single tag
// let us add the element and continue our quest...
list.add( element );
continue;
}
else { // block
// gulp up the rest of this block...
var re_end_tag = re.compile( "^(.*?)(\\s*)(</" + tag + "\\s*>)(\\s*)", 's' );
if ( (m = re_end_tag.exec( src )) ) {
src.advance( m[0] );
if ( tag === 'pre' ) {
element.push( tail );
element = element.concat( parse_html( m[1].replace( /(\r?\n)+$/, '' ), { 'code': 1 } ) );
if ( m[2] ) { element.push( m[2] ); }
list.add( element );
}
else if ( tag === 'notextile' ) {
element = parse_html( m[1].trim() );
list.merge( element );
}
else if ( tag === 'script' || tag === 'noscript' ) {
//element = parse_html( m[1].trim() );
element.push( tail + m[1] );
list.add( element );
}
else {
// These strange (and unnecessary) linebreak tests are here to get the
// tests working perfectly. In reality, this doesn't matter one bit.
if ( /\n/.test( tail ) ) { element.push( '\n' ); }
if ( /\n/.test( m[1] ) ) {
element = element.concat( parse_blocks( m[1], options ) );
}
else {
element = element.concat( parse_inline( m[1].replace( /^ +/, '' ), options ) );
}
if ( /\n/.test( m[2] ) ) { element.push( '\n' ); }
list.add( element );
}
continue;
}
/*else {
// end tag is missing, treat tag as normal text...
}*/
}
}
src.load();
}
// ruler
if ( (m = re_ruler.exec( src )) ) {
src.advance( m[0] );
list.add( [ 'hr' ] );
continue;
}
// list
if ( (m = re_list.exec( src )) ) {
src.advance( m[0] );
list.add( parse_list( m[0], options ) );
continue;
}
// definition list
if ( (m = re_deflist.exec( src )) ) {
src.advance( m[0] );
list.add( parse_deflist( m[0], options ) );
continue;
}
// table
if ( (m = re_table.exec( src )) ) {
src.advance( m[0] );
list.add( parse_table( m[1], options ) );
continue;
}
// paragraph
m = re_block_normal.exec( src );
list.merge( paragraph( m[1], 'p', undefined, "\n" ) );
src.advance( m[0] );
}
return list.get().map( fix_links, link_refs );
}
// recurse the tree and swap out any "href" attributes
function fix_links ( jsonml ) {
if ( _isArray( jsonml ) ) {
if ( jsonml[0] === 'a' ) { // found a link
var attr = jsonml[1];
if ( typeof attr === "object" && 'href' in attr && attr.href in this ) {
attr.href = this[ attr.href ];
}
}
for (var i=1,l=jsonml.length; i<l; i++) {
if ( _isArray( jsonml[i] ) ) {
fix_links.call( this, jsonml[i] );
}
}
}
return jsonml;
}
/* exposed */
function textile ( txt, opt ) {
// get a throw-away copy of options
opt = merge( merge( {}, textile.defaults ), opt || {} );
// run the converter
return parse_blocks( txt, opt ).map( JSONML.toHTML ).join( '' );
}
// options
textile.defaults = {
'breaks': true // single-line linebreaks are converted to <br> by default
};
textile.setOptions = textile.setoptions = function ( opt ) {
merge( textile.defaults, opt );
return this;
};
textile.parse = textile.convert = textile;
textile.html_parser = parse_html;
textile.jsonml = function ( txt, opt ) {
// get a throw-away copy of options
opt = merge( merge( {}, textile.defaults ), opt || {} );
// parse and return tree
return [ 'html' ].concat( parse_blocks( txt, opt ) );
};
textile.serialize = JSONML.toHTML;
if ( typeof module !== 'undefined' && module.exports ) {
module.exports = textile;
}
else {
this.textile = textile;
}
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
}());
| muffinmad/atom-textile-preview | lib/textile.js | JavaScript | mit | 45,902 |
/**
* Style for forms
*/
label {
font-size: smaller;
}
input[type=text],
input[type=password] {
font-size: 1.2em;
width: 300px;
}
input[type=submit],
input[type=reset] {
font-size: 1.2em;
}
textarea {
font-size: 1.2em;
width: 300px;
min-height: 200px;
}
p.buttons {
padding-top: 22px;
padding-bottom: 22px;
}
.forms{
width: 700px;
background-color: #eee;
}
.cform-columns-2 .cform-column-1,
.cform-columns-2 .cform-column-2 {
background-color: #eee;
float: left; width: 50%;
}
.cform-columns-2 .cform-buttonbar {
clear: both;
background-color: #eee;
padding: 1em;
border: 1px solid #aaa;
}
.cform-columns-2 .cform-buttonbar p {
margin-bottom: 0;
} | roka13/wgtotw | webroot/css/form.css | CSS | mit | 705 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>バンガロール滞在日誌みたいな</title>
<meta name="description" content="インドのバンガロールで過ごす日々を綴るやつ" />
<link href="//fonts.googleapis.com/css?family=Noto+Sans:300,400,700" rel="stylesheet" type="text/css">
<link href="//fonts.googleapis.com/css?family=Noto+Serif:400,700,400italic" rel="stylesheet" type="text/css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="//stay-india.github.io/themes/Saga/assets/css/style.css?v=1.0.0" rel="stylesheet" type="text/css">
<link href="//stay-india.github.io/themes/Saga/assets/css/animate.min.css?v=1.0.0" rel="stylesheet" type="text/css">
<link href="//stay-india.github.io/themes/Saga/favicon.ico" rel="shortcut icon">
<link rel="canonical" href="https://stay-india.github.io" />
<meta name="generator" content="Ghost ?" />
<link rel="alternate" type="application/rss+xml" title="バンガロール滞在日誌みたいな" href="https://stay-india.github.io/rss" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">
</head>
<body class="tag-template tag-hotel home-template">
<header id="header" class="animated fadeIn">
<div class="header-background">
<section class="blog-content">
<a id="site-url" class="blog-title" href="https://stay-india.github.io">バンガロール滞在日誌みたいな</a>
<span class="blog-description">インドのバンガロールで過ごす日々を綴るやつ</span>
<nav class="links fadeIn animated">
<ul>
<!-- <li class="rss"><a title="RSS Feed" href="/rss/"><i class="fa fa-fw fa-rss-square"></i></a></li> -->
<li class="github"><a title="GitHub" href="https://github.com/naru0504"><i class="fa fa-fw fa-github-square"></i></a></li>
<li class="facebook"><a title="Facebook" href="https://facebook.com/naru0504"><i class="fa fa-fw fa-facebook-square"></i></a></li>
<li class="twitter"><a title="Twitter" href="https://twitter.com/naru0504"><i class="fa fa-fw fa-twitter-square"></i></a></li>
<li class="instagram"><a title="Instagram" href="https://instagram.com/naru0504"><i class="fa fa-fw fa-instagram"></i></a></li>
<li class="pinterest"><a title="Pinterest" href="https://pinterest.com/naru0504"><i class="fa fa-fw fa-pinterest-square"></i></a></li>
<li class="flickr"><a title="Flickr" href="https://www.flickr.com/photos/126633715@N07/"><i class="fa fa-fw fa-flickr"></i></a></li>
</ul>
</nav>
</section>
<section class="header-content">
<h1 class="tag-title animated fadeInUp">hotel</h1>
<span class="tag-data"><span class="tag-description animated fadeInUp"></span></span>
</section>
</div>
</header>
<main id="main" class="archive">
<section id="feed" class="feed">
<article class="post tag-india tag-north_india tag-trip tag-hotel" style="opacity: 0;">
<a href="https://stay-india.github.io/2015/10/27/north_india_trip_onedayhotel.html" class="post-image">
<img src="https://cloud.githubusercontent.com/assets/8326452/10753469/2f46b2e4-7cb7-11e5-8cb8-c7799bb69fc1.png" alt="">
<h2 class="post-title">週末旅行日誌! 北インド編2 - #バンガロールの空港でワンデイホテルに泊まったよ!</h2>
</a> <section class="post-content">
つーかな。更新遅いってな。 怠慢かよ! って思うじゃん? 弁明させてくれ。 インドでは画像のアップロードに耐えられるネット環境なんてほとんど手に入れようがないんだよ(涙) それで結局、月曜日は疲れ過ぎてたしで今日なわけですわ。 まあどれだけネット環境を欲したかはおいおい書いていくんで進めていきましょうか。 前回の通りなんやかんやでデリーに行けなく…
</section>
<section class="post-meta">
<span class="date"><i class="fa fa-clock-o"></i> <a href="https://stay-india.github.io/2015/10/27/north_india_trip_onedayhotel.html"><time class="timesince" data-timesince="1445884200" datetime="2015-10-27T00:00" title="27 October 2015">2015-10-27 00:00:00<ago class="ago"></time></a></span>
<span class="tags"><i class="fa fa-tags"></i>
<span>
<a href="https://stay-india.github.io/tag/india">india</a>, <a href="https://stay-india.github.io/tag/north_india"> north_india</a>, <a href="https://stay-india.github.io/tag/trip"> trip</a>, <a href="https://stay-india.github.io/tag/hotel"> hotel</a></span>
</span>
</section>
</article></section>
<nav class="pagination" role="navigation">
<span class="page-number">Page 1 of 1</span>
</nav></main>
<footer class="animated fadeIn" id="footer">
<section class="colophon">
<section class="copyright">Copyright © <span itemprop="copyrightHolder">バンガロール滞在日誌みたいな</span>. <span rel="license">All Rights Reserved</span>.</section>
<section class="poweredby">Published with <a class="icon-ghost" href="http://hubpress.io">HubPress</a></section>
</section>
<section class="bottom">
<section class="attribution">
<a href="http://github.com/Reedyn/Saga">Built with <i class="fa fa-heart"></i> and Free and Open-Source Software</a>.
</section>
</section>
</footer>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?v="></script> <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js?v="></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js?v="></script>
<script type="text/javascript">
jQuery( document ).ready(function() {
// change date with ago
jQuery('ago.ago').each(function(){
var element = jQuery(this).parent();
element.html( moment(element.text()).fromNow());
});
});
hljs.initHighlightingOnLoad();
</script>
<script src="//stay-india.github.io/themes/Saga/assets/js/scripts.js?v=1.0.0"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-57794933-2', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| stay-india/stay-india.github.io | tag/hotel/index.html | HTML | mit | 7,170 |
package com.smartbit8.laravelstorm.run;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.ide.browsers.*;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter;
import com.intellij.util.xmlb.XmlSerializer;
import com.jetbrains.php.config.interpreters.PhpInterpreter;
import com.jetbrains.php.config.interpreters.PhpInterpretersManagerImpl;
import com.smartbit8.laravelstorm.ui.LaravelRunConfSettingsEditor;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
public class LaravelRunConf extends RunConfigurationBase {
private Project project;
private String host = "localhost";
private int port = 8000;
private String route = "/";
private WebBrowser browser;
private PhpInterpreter interpreter;
LaravelRunConf(@NotNull Project project, @NotNull ConfigurationFactory factory, String name) {
super(project, factory, name);
this.project = project;
}
@Override
public void createAdditionalTabComponents(AdditionalTabComponentManager manager, ProcessHandler startedProcess) {
LogTab logTab = new LogTab(getProject());
manager.addAdditionalTabComponent(logTab, "Laravel.log");
startedProcess.addProcessListener(new ProcessAdapter() {
@Override
public void startNotified(ProcessEvent event) {
logTab.start();
}
@Override
public void processTerminated(ProcessEvent event) {
startedProcess.removeProcessListener(this);
}
});
}
@Override
public void readExternal(Element element) throws InvalidDataException {
super.readExternal(element);
Settings settings = XmlSerializer.deserialize(element, Settings.class);
this.host = settings.host;
this.port = settings.port;
this.route = settings.route;
this.browser = WebBrowserManager.getInstance().findBrowserById(settings.browser);
this.interpreter = PhpInterpretersManagerImpl.getInstance(getProject()).findInterpreter(settings.interpreterName);
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
Settings settings = new Settings();
settings.host = this.host;
settings.port = this.port;
settings.route = this.route;
if (this.browser != null)
settings.browser = this.browser.getId().toString();
else
settings.browser = "";
if (this.interpreter != null)
settings.interpreterName = this.interpreter.getName();
else
settings.interpreterName = "";
XmlSerializer.serializeInto(settings, element, new SkipDefaultsSerializationFilter());
super.writeExternal(element);
}
@NotNull
@Override
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new LaravelRunConfSettingsEditor(getProject());
}
@Override
public void checkConfiguration() throws RuntimeConfigurationException {}
@Nullable
@Override
public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws ExecutionException {
return new CommandLineState(executionEnvironment) {
@NotNull
@Override
protected ProcessHandler startProcess() throws ExecutionException {
String phpExec = (interpreter != null? interpreter.getPathToPhpExecutable():"php");
GeneralCommandLine cmd = new GeneralCommandLine(phpExec, "artisan", "serve", "--host=" + host, "--port="+ port);
cmd.setWorkDirectory(project.getBasePath());
OSProcessHandler handler = new OSProcessHandler(cmd);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key outputType) {
String text = event.getText();
if (text != null){
if (text.startsWith("Laravel development server started:")){
BrowserLauncher.getInstance().browse("http://" + host + ":" + port +
(route.startsWith("/") ? route : "/" + route), browser);
handler.removeProcessListener(this);
}
}
}
});
// new LaravelRunMgr(handler, new File(getProject().getBasePath()+("/storage/logs/laravel.log")));
return handler;
}
};
}
public int getPort() {
return port;
}
public String getHost() {
return host;
}
public void setPort(int port) {
this.port = port;
}
public void setHost(String host) {
this.host = host;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public WebBrowser getBrowser() {
return browser;
}
public void setBrowser(WebBrowser browser) {
this.browser = browser;
}
public PhpInterpreter getInterpreter() {
return interpreter;
}
public void setInterpreter(PhpInterpreter interpreter) {
this.interpreter = interpreter;
}
public static class Settings {
public String host;
public int port;
public String route;
public String browser;
public String interpreterName;
}
}
| 3mmarg97/LaravelStorm | src/com/smartbit8/laravelstorm/run/LaravelRunConf.java | Java | mit | 6,140 |
# WiseFriend
User (mentee) can create an account
User can log in
When creating account, user will fill out profile and answer questions to be matched
User can browse a list of resources
After being matched - user can fill out surveys once per month in order to assess the quality of the match.
Mentor can create an account
When creating account, mentor will fill out profile and answer questions
Mentor can log in
After being approved, mentor will be offered a suggested match
They can accept or decline
After being matched - user can fill out surveys once per month in order to assess the quality of the match.
Mentors and mentees can message each other
Mentee:
first name
last name (optional)
location
age
gender
preference for mentor gender
top 5 challenges
Email
Phone (optional)
How do you prefer to communicate?
How did you hear about us?
Tell us about yourself
Mentor:
First name
last name
location
age
gender
preference for mentee gender
areas of expertise
Email
Phone
How do you prefer to communicate?
LinkedIn (optional)
How did you hear about us?
Tell us about yourself
Mentorship
mentor_id
mentee_id
accepted_by_mentor
match_score
mentor_surveys
mentor_id
how_satisfied
plan_to_continue?
comments
mentee_surveys
mentee_id
how_satisfied
plan_to_continue?
comments
| RonuGhoshal/WiseFriend | README.md | Markdown | mit | 1,289 |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :question do
sq_no '2'
query 'What is Ruby?'
question_type "Hard"
association :level
association :content
after(:build) do |question|
FactoryGirl.create(:correct, :question => question)
2.times {|i| FactoryGirl.create(:incorrect, :question => question)}
end
end
end
| techvision/brails | spec/factories/questions.rb | Ruby | mit | 411 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.