text:
package com.formulasearchengine.mathmltools.nativetools;

import com.formulasearchengine.mathmltools.nativetools.CommandExecutor;
import com.formulasearchengine.mathmltools.nativetools.NativeResponse;
import org.apache.logging.log4j.Level;
import org.junit.jupiter.api.Test;

import java.nio.file.Paths;
import java.util.LinkedList;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Note that those tests base on the fact, that the command echo is one
 * of the rare commands that are available on all operating systems.
 *
 * @author Andre Greiner-Petter
 */
public class CommandExecutorTest {

    private static final String ROBUST_ECHO_COMMAND = "echo";
    private static final String TEST_STRING = "TEST-IS";
    private static final String NEW_LINE = System.lineSeparator();

    @Test
    public void simpleEchoTest() {
        CommandExecutor executor = new CommandExecutor("JUnit-Test", ROBUST_ECHO_COMMAND, TEST_STRING);
        NativeResponse response = executor.exec();
        assertEchoNativeResponse(response);
    }

    @Test
    public void simpleEchoWithTimeoutTest() {
        CommandExecutor executor = new CommandExecutor("JUnit-Test", ROBUST_ECHO_COMMAND, TEST_STRING);
        NativeResponse response = executor.exec(1000, Level.DEBUG);
        assertEchoNativeResponse(response);
    }

    @Test
    public void changeWorkingDirectoryTest() {
        CommandExecutor executor = new CommandExecutor("JUnit-Test", ROBUST_ECHO_COMMAND, TEST_STRING);
        String homeDir = System.getProperty("user.home");
        executor.setWorkingDirectoryForProcess(Paths.get(homeDir));
        NativeResponse response = executor.execWithoutTimeout();
        assertEchoNativeResponse(response);
    }

    @Test
    public void simpleEchoNoWaitingTest() {
        LinkedList<String> args = new LinkedList<>();
        args.add("JUnit-Test");     // service name
        args.add(ROBUST_ECHO_COMMAND);   // command
        args.add(TEST_STRING);      // command argument
        CommandExecutor executor = new CommandExecutor(args);
        NativeResponse response = executor.execWithoutTimeout(Level.INFO);
        assertEchoNativeResponse(response);
    }

    private void assertEchoNativeResponse(NativeResponse response) {
        assertEquals(0, response.getStatusCode(), "Executed without exit code 0.");
        assertEquals(TEST_STRING + NEW_LINE, response.getResult(), "The result is not what we expected.");
        assertNull(response.getThrowedException(), "Expected no error for " + ROBUST_ECHO_COMMAND);
    }

    @Test
    public void robustCommandExistsTest() {
        assertTrue(CommandExecutor.commandCheck(ROBUST_ECHO_COMMAND),
                "Robust command " + ROBUST_ECHO_COMMAND + " doesn't exists?");
    }

    @Test
    public void notRobustCommandExistsTest() {
        assertFalse(CommandExecutor.commandCheck(ROBUST_ECHO_COMMAND + "XYZ"),
                "Fake command " + ROBUST_ECHO_COMMAND + "XYC exists? What the hack is that?");
    }

    @Test
    public void brokenCommandWithLogLevelTest() {
        CommandExecutor executor = new CommandExecutor("JUnit-Test", ROBUST_ECHO_COMMAND + "XYZ", TEST_STRING);
        NativeResponse response = executor.exec(Level.TRACE);
        assertInvalidCommandResponse(response);
    }

    @Test
    public void brokenCommandWithoutTimeoutTest() {
        CommandExecutor executor = new CommandExecutor("JUnit-Test", ROBUST_ECHO_COMMAND + "XYZ", TEST_STRING);
        NativeResponse response = executor.execWithoutTimeout();
        assertInvalidCommandResponse(response);
    }

    private void assertInvalidCommandResponse(NativeResponse response) {
        assertEquals(1, response.getStatusCode(), "Unknown command " + ROBUST_ECHO_COMMAND + "XYZ executed with 0?");
        assertNull(response.getResult(), "Result for unknown command should be null.");
        assertNotNull(response.getThrowedException(), "Expected an exception for " + ROBUST_ECHO_COMMAND + "XYZ.");
        assertTrue(response.getMessage().contains("Error"), "Expected a message with 'Error' in it for unknown commands.");
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/ic_back_normal" android:state_pressed="false"/>
    <item android:drawable="@mipmap/ic_back_pressed" android:state_pressed="true"/>
</selector>

redpajama_set_name: RedPajamaGithub


text:
title: One-Shot Learning
localeTitle: Aprendizaje One-Shot
---
# Aprendizaje One-Shot

Los seres humanos aprenden conceptos nuevos con muy poca necesidad de repetición, por ejemplo, un niño puede generalizar el concepto de un "mono" de una sola imagen en un libro, sin embargo, nuestros mejores sistemas de aprendizaje profundo necesitan cientos o Miles de ejemplos para captar cualquier objeto, incluso hasta un punto de precisión decente. Esto motiva el entorno en el que estamos interesados: el aprendizaje "one-shot", que consiste en aprender una clase de un solo ejemplo etiquetado (o muy pocos).

Hay varios enfoques para el aprendizaje de One-Shot, tales como [funciones de similitud](https://www.coursera.org/lecture/convolutional-neural-networks/one-shot-learning-gjckG) , [El teorema de probabilidad de Bayes](https://www.youtube.com/watch?v=FIjy3lV_KJU) , DeepMind, ha desarrollado su propia versión de Neural Networks utilizando el enfoque de aprendizaje One-Shot.

### Más información:

*   [Siraj Raval en YouTube](https://www.youtube.com/watch?v=FIjy3lV_KJU&feature=youtu.be)
*   [Andrew Ng (Deeplearning.ai)](https://www.coursera.org/lecture/convolutional-neural-networks/one-shot-learning-gjckG)
*   [Artículo académico](http://web.mit.edu/cocosci/Papers/Science-2015-Lake-1332-8.pdf)
*   [Wikipedia](https://en.wikipedia.org/wiki/One-shot_learning)


text:
package com.jayseeofficial.rssconsumer.rss;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndEntry;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndFeed;
import com.jayseeofficial.rssconsumer.R;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by jon on 25/03/15.
 */
public class SyndFeedAdapter extends ArrayAdapter {

    List<SyndEntry> entries;
    Context context;

    private static final int ITEM_LAYOUT = R.layout.feed_list_item;

    public SyndFeedAdapter(Context context, SyndFeed feed) {
        super(context, ITEM_LAYOUT);
        entries = feed.getEntries();
        this.context = context;
    }

    @Override
    public int getCount() {
        return entries.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView != null) {
            holder = (ViewHolder) convertView.getTag();
        } else {
            convertView = LayoutInflater.from(context).inflate(ITEM_LAYOUT, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }

        holder.txtTitle.setText(entries.get(position).getTitle());
        holder.txtDetails.setText(entries.get(position).getLink());

        return convertView;
    }

    static class ViewHolder {
        @InjectView(R.id.txt_title)
        TextView txtTitle;
        @InjectView(R.id.txt_details)
        TextView txtDetails;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }
}


text:
package br.ufsc.lehmann.msm.artigo.problems;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import br.ufsc.core.trajectory.Semantic;
import br.ufsc.core.trajectory.SemanticTrajectory;
import br.ufsc.core.trajectory.StopSemantic;
import br.ufsc.lehmann.msm.artigo.AbstractProblem;

public class AmsterdamPark2005Problem extends AbstractProblem {

	private boolean onlyStops;
	private Integer[] users;
	private StopMoveStrategy strategy;

	public AmsterdamPark2005Problem(Integer... users) {
		this(false, users);
	}

	public AmsterdamPark2005Problem(boolean onlyStops, Integer... users) {
		this(PisaDataReader.STOP_CENTROID_SEMANTIC, onlyStops, users);
	}

	public AmsterdamPark2005Problem(StopSemantic stopSemantic,boolean onlyStops, Integer... users) {
		this(stopSemantic, StopMoveStrategy.CBSMoT, onlyStops, users);
	}

	public AmsterdamPark2005Problem(StopSemantic stopSemantic, StopMoveStrategy strategy, boolean onlyStops, Integer... users) {
		super(stopSemantic);
		this.strategy = strategy;
		this.onlyStops = onlyStops;
		this.users = users;
	}

	@Override
	public Semantic discriminator() {
		return AmsterdamPark2005DatabaseReader.TEAM;
	}

	@Override
	public String shortDescripton() {
		return "Amsterdan 2005 [" + stopSemantic().name() + "][onlyStops=" + onlyStops + "]" + (users != null ? "(Users " + Arrays.toString(users) + ")" : "");
	}

	protected List<SemanticTrajectory> load() {
		try {
			return new ArrayList<>(new AmsterdamPark2005DatabaseReader(onlyStops).read());
		} catch (NumberFormatException | InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException  e) {
			throw new RuntimeException(e);
		}
//		try {
//			return new ArrayList<>(new PisaDatabaseReader(onlyStops).read(users));
//		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
//			throw new RuntimeException(e);
//		}
	}

}


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

<title>IMetadataComponentSerializer (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.io.sstable.metadata

Interface IMetadataComponentSerializer<T extends MetadataComponent>

All Known Implementing Classes:

CompactionMetadata.CompactionMetadataSerializer, SerializationHeader.Serializer, StatsMetadata.StatsMetadataSerializer, ValidationMetadata.ValidationMetadataSerializer

public interface IMetadataComponentSerializer<T extends MetadataComponent>

Metadata component serializer

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

T
deserialize(Version version,
           DataInputPlus in)

Deserialize metadata component from given input.

void
serialize(Version version,
         T component,
         DataOutputPlus out)

Serialize metadata component to given output.

int
serializedSize(Version version,
              T component)

Calculate and return serialized size.

Method Detail

serializedSize

int serializedSize(Version version,
                   T component)
            throws java.io.IOException

Calculate and return serialized size.

Parameters:

version -

component - MetadataComponent to calculate serialized size

Returns:

serialized size of this component

Throws:

java.io.IOException

serialize

void serialize(Version version,
               T component,
               DataOutputPlus out)
        throws java.io.IOException

Serialize metadata component to given output.

Parameters:

version -

component - MetadataComponent to serialize

out - serialize destination

Throws:

java.io.IOException

deserialize

T deserialize(Version version,
              DataInputPlus in)
       throws java.io.IOException

Deserialize metadata component from given input.

Parameters:

version - serialize version

in - deserialize source

Returns:

Deserialized component

Throws:

java.io.IOException

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation


text:
package edu.northwestern.bioinformatics.studycalendar.web.subject;

import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivity;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import org.apache.commons.lang.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * @author Rhett Sutphin
 */
public class ScheduleDay implements Comparable<ScheduleDay> {
    private Date date;
    private Date today;
    private SortedSet<ScheduledActivity> activities;
    private boolean hasHiddenActivities;

    private static ThreadLocal<DateFormat> DATE_CLASS_FORMATTER = new ThreadLocal<DateFormat>();

    public ScheduleDay(Date date) {
        this(date, new Date());
    }

    public ScheduleDay(Date date, Date today) {
        this.date = date;
        this.today = today;
        activities = new TreeSet<ScheduledActivity>();
    }

    ////// LOGIC

    public int compareTo(ScheduleDay o) {
        return getDate().compareTo(o.getDate());
    }

    public boolean isToday() {
        return DateTools.daysEqual(getDate(), today);
    }

    public boolean isEmpty() {
        return getActivities().isEmpty() && !getHasHiddenActivities();
    }

    public String getDetailTimelineClasses() {
        Calendar queriableDate = Calendar.getInstance();
        queriableDate.setTime(getDate());

        List<String> classes = new ArrayList<String>(6);
        classes.add("day");
        classes.add(dateClass(getDate()));
        if (queriableDate.get(Calendar.DAY_OF_MONTH) == 1) classes.add("month-start");
        if (queriableDate.get(Calendar.DAY_OF_YEAR) == 1) classes.add("year-start");
        if (isToday()) classes.add("today");
        if (!isEmpty()) classes.add("has-activities");

        return StringUtils.join(classes.iterator(), ' ');
    }

    private static String dateClass(Date date) {
        if (DATE_CLASS_FORMATTER.get() == null) {
            DATE_CLASS_FORMATTER.set(new SimpleDateFormat("yyyy-MM-dd"));
        }
        return "date-" + DATE_CLASS_FORMATTER.get().format(date);
    }

    ////// BEAN PROPERTIES

    public Date getDate() {
        return date;
    }

    public SortedSet<ScheduledActivity> getActivities() {
        return activities;
    }

    public boolean getHasHiddenActivities() {
        return hasHiddenActivities;
    }

    public void setHasHiddenActivities(boolean hasHiddenActivities) {
        this.hasHiddenActivities = hasHiddenActivities;
    }
}


text:
require 'spec_helper'

describe Wimdu::Partner::Edomizil::Customer do

  context 'params' do

    let(:booking){
      user = FactoryGirl.build(:user, firstname: 'john', lastname: 'wayne')
      FactoryGirl.build(:booking, user: user)
    }

    subject{
      Wimdu::Partner::Edomizil::Customer.from_wimdu_booking(booking)
    }

    context 'language' do

      it 'should return 1 if the language is de' do
        subject.language = 'de'
        subject.params['sprache'].should == 1
      end

      it 'should return 3 if the language is fr' do
        subject.language = 'fr'
        subject.params['sprache'].should == 3
      end

      it 'should return 4 if the language is es' do
        subject.language = 'es'
        subject.params['sprache'].should == 4
      end

      it 'should return 5 if the language is it' do
        subject.language = 'it'
        subject.params['sprache'].should == 5
      end

      it 'otherwise is should return 2' do
        subject.language = 'zz'
        subject.params['sprache'].should == 2
      end

    end

    it 'should map the parameters to match the query' do
      raise subject.errors.full_messages.inspect unless subject.valid?
      subject.params.should == {"anrede"=>1,
                                "action" => "sendKundendaten",
                                "vorname"=>"john",
                                "name"=>"wayne",
                                "strasse"=>"Winstrasse",
                                "plz"=>"123666",
                                "ort"=>"Berlin",
                                "land"=>"DE",
                                "email"=>"test.test@email.com",
                                "telefon"=>"4901777428760",
                                "hausnummer" => ".",
                                "sprache"=>1}
    end

  end

end


text:
package com.cognifide.slice.testhelper;

import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author Mariusz Kubiś Date: 22.04.15
 */
public class ClassURLProducer {

	private Set<String> classPaths;

	public ClassURLProducer(Set<String> classPaths) {
		this.classPaths = classPaths;
	}

	public Set<URL> getUrls() {

		Set<URL> urlSet = new LinkedHashSet<URL>();
		for (String classPath : classPaths) {
			URL url = getClass().getClassLoader().getResource(classPath + ".class");
			if (url != null) {
				urlSet.add(url);
			}
		}
		return urlSet;
	}
}


text:
backfeed
========

Aplicativo para coletar feedbacks das apresentações.
O objetivo do desenvolvimento desta aplicação é treinar o uso do knockoutjs com requirejs e jQuery.

INSTRUÇÕES
==========
1- Este aplicativo foi re-configurado para usar o banco de dados hsqldb na memória. Para preencher o dados iniciais, pode-se editar o arquivo import.sql.


text:
#include "../NumericTypes.h"
#include "../BitsRequired.h"
#include "../BitSize.h"
#include "LsbMask.h"

namespace Ardutils
{
	template< unsigned Number, typename T = LeastUInt<BitsRequired<Number>::Value> >
	struct TrailingZeroes;

	template< unsigned Number, typename T >
	struct TrailingZeroes
	{
		TrailingZeroes(void) = delete;
		constexpr static const unsigned Value = ((Number & LsbMask<BitSize<T>::Value>::Value) == 0) ? 1 + TrailingZeroes<(Number >> 1), T>::Value : 0;
	};

	template< typename T >
	struct TrailingZeroes<1, T>
	{
		TrailingZeroes(void) = delete;
		constexpr static const unsigned Value = 0;
	};

	template< typename T >
	struct TrailingZeroes<0, T>
	{
		TrailingZeroes(void) = delete;
		constexpr static const unsigned Value = BitSize<T>::Value;
	};
}


text:
<?php

defined('_JEXEC') or die('Restricted access');

// Include interface definition
//CFactory::load( 'models' , 'tags' );

class CTableVideo extends JTable  implements CTaggable_Item
{
	//Table's field
	var $id 			= null;
	var $title 			= null;
  	var $type 			= null;
	var $video_id 	    = null;
  	var $description 	= null;
  	var $creator 		= null;
  	var $creator_type	= null;
	var $created 		= null;
	var $permissions	= null;
	var $category_id 	= null;
	var $hits 			= null;
	var $published		= null;
	var $featured		= null;
	var $duration 		= null;
	var $status 		= null;
	var $thumb			= null;
	var $path			= null;
	var $groupid		= null;
	var $storage		= null;
	var $location		= null;
	var $latitude		= null;
	var $longitude		= null;

	//non-table fields
	var $_wallcount		= 0;
	var $_size			= 0;
	var $_width			= 0;
	var $_height		= 0;
	var $_lastupdated	= null;

	var $_videoUrl		= null;
	var $_videoId		= null;
	var $_thumbnail		= null;
	var $_provider		= null;

	/**
	 * Constructor
	 */
	public function __construct(&$db)
	{
		parent::__construct( '#__community_videos', 'id', $db );

		require_once(JPATH_ROOT .'/components/com_community/libraries/core.php');

		$config			= CFactory::getConfig();
		$this->_size	= $config->get('videosSize');
		$this->_width	= CVideosHelper::getVideoSize('width');
		$this->_height	= CVideosHelper::getVideoSize('height');
		$this->storage	= 'file';

		$this->hits		= 0;

 	 	// load helpers

	}

	/**
	 * Load the object and the video provider as well
	 */
	public function load( $oid = null, $reset = true)
	{
		if( parent::load( $oid ) )
		{
			// @todo: make sure loading is done ok
			$providerName	= JString::strtolower($this->type);
			if (empty($providerName)) {
				return false;
			}
			$libraryPath	= COMMUNITY_COM_PATH .'/libraries/videos' .'/'. $providerName . '.php';

			require_once($libraryPath);
			$className		 = 'CTableVideo' . JString::ucfirst($providerName);
			$this->_provider = new $className( $this->_db );

			return true;
		}
		return false;

	}

	/**
	 * Initialize the video with a new url
	 */
	public function init($url)
	{
		// create the provider
		// $this->_provider should be null here

		$videoLib 	= new CVideoLibrary();

		$this->_provider = $videoLib->getProvider($url);
		$isValid = $this->_provider->isValid();

		if($isValid)
		{
			$this->title	= $this->_provider->getTitle();
			$this->type		= $this->_provider->getType();
			$this->video_id	= $this->_provider->getId();
			$this->duration	= $this->_provider->getDuration();
			$this->status	= 'ready';
			$this->thumb	= $this->_provider->getThumbnail();
			$this->path 	= $url;
			$this->description=	$this->_provider->getDescription();
			$this->status	= 'ready';
		}

		return $isValid;
	}

	/**
	 * Make sure hits are user and session sensitive
	 */
	public function hit($pk = null)
	{
		$session = JFactory::getSession();
		if( $session->get('view-video-'. $this->id, false) == false ) {
			parent::hit();
		}
		$session->set('view-video-'. $this->id, true);
	}

	/**
	 * Verify whether weblinks is accessible
	 *
	 * @param $url
	 * @return boolean
	 */
	public function isValid() {
	}

	public function getId() {
		return $this->id;
	}

	public function getType() {
		return $this->type;
	}

	/**
	 * Get video's title from videoid
	 *
	 * @access 	public
	 * @param 	videoid
	 * @return video title
	 */
	public function getTitle($escape = true)
	{
		//CError::assert($this->title, '', '!empty');
		$this->title	= $this->title ? $this->title : JText::_('COM_COMMUNITY_VIDEOS_TITLE_EMPTY');

		return $escape ? CStringHelper::escape($this->title) : $this->title;
	}

	/**
	 * Get video's description from videoid
	 *
	 * @access 	public
	 * @return desctiption
	 */
	public function getDescription($escape = true)
	{
		if(empty($this->description))
		{
			$this->description = JText::_('COM_COMMUNITY_VIDEOS_NOT_AVAILABLE');
		}

		return $escape ? CStringHelper::escape($this->description) : $this->description;
	}

	/**
	 * Get video duration
	 *
	 * @return $duration seconds
	 */
	public function getDuration()
	{
		//CError::assert($this->duration, '', '!empty');
		if (empty($this->duration))
		{
			$this->duration = 0;
		}
		return $this->duration;
	}

	public function getDurationInHMS()
	{
		if($this->duration != 0)
		{
			$duration = CVideosHelper::formatDuration( (int)($this->duration), 'HH:MM:SS' );
			$duration = CVideosHelper::toNiceHMS( $duration );
		}
		else
		{
			$duration = JText::_('COM_COMMUNITY_VIDEOS_DURATION_NOT_AVAILABLE');
		}

		return $duration;
	}

	/**
	 * Get video's thumbnail URL from videoid
	 *
	 * @access 	public
	 * @param 	videoid
	 * @return url
	 */
	public function getThumbnail()
	{
		$config = CFactory::getConfig();
		$file   = $this->thumb;

		// Site origin
		if (JString::substr($file, 0, 4)=='http')
		{
			$uri = $file;
			return $uri;
		}

		// Remote storage
		if($this->storage != 'file')
		{

			$storage = CStorage::getStorage($this->storage);
			$uri = $storage->getURI($file);
			return $uri;
		}

		// Default thumbnail
		if (empty($file) || !JFile::exists(JPATH_ROOT.'/'.$file))
		{

			$template = new CTemplateHelper();
			$asset = $template->getTemplateAsset('video_thumb.png', 'images');
			$uri = $asset->url;
			return $uri;
		}

		// Strip cdn path if exists.
		// Note: At one point, cdn path was stored along with the thumbnail path
		//       in the db which is the mistake we are trying to rectify here.
		$file   = str_ireplace($config->get('videocdnpath'), '', $file);

		// CDN or local
		$baseUrl = $config->get('videobaseurl') or
		$baseUrl = JURI::root();
		$uri = str_replace('\\', '/', rtrim($baseUrl, '/') . '/' . ltrim($file, '/'));
		return $uri;
	}

	public function getSize() {
		return $this->_size;
	}

	public function getWidth() {
		return $this->_width;
	}

	public function getHeight() {
		return $this->_height;
	}

	public function getWallCount()
	{
		$query	= ' SELECT COUNT(*)'
				. ' FROM ' . $this->_db->quoteName('#__community_wall')
				. ' WHERE ' . $this->_db->quoteName('type') . ' = ' . $this->_db->quote('videos')
				. ' AND ' . $this->_db->quoteName('published') . ' = ' . $this->_db->quote(1)
				. ' AND ' . $this->_db->quoteName('contentid') . ' = ' . $this->_db->quote($this->id)
				;
		$this->_db->setQuery($query);
		$this->_wallcount	= $this->_db->loadResult();

		return $this->_wallcount;
	}

	public function getLastUpdated($raw = false)
	{
		$this->_lastupdated	= $this->created;

		if($raw)
		{
			return $this->_lastupdated;
		}

		if($this->_lastupdated == '0000-00-00 00:00:00' || $this->_lastupdated == '')
		{
			$this->_lastupdated	= $this->created;

			if($this->_lastupdated == '' || $this->_lastupdated == '0000-00-00 00:00:00')
			{
				$this->_lastupdated	= JText::_( 'COM_COMMUNITY_NO_LAST_ACTIVITY' );
			}
			else
			{
				$lastUpdated	= new JDate( $this->_lastupdated );
				$this->_lastupdated	= CActivityStream::_createdLapse( $lastUpdated, false );
			}
		}
		else
		{
			$lastUpdated	= new JDate( $this->_lastupdated );
			$this->_lastupdated	= CActivityStream::_createdLapse( $lastUpdated, false );
		}

		return $this->_lastupdated;
	}

	public function isPending()
	{
		return ($this->status == 'pending');
	}

        public function isExist () {
            $query =    ' SELECT ' . $this->_db->quoteName('id') .
                        ' FROM ' . $this->_db->quoteName('#__community_videos') .
                        ' WHERE ' . $this->_db->quoteName('creator') . ' = ' . (int)$this->creator .
                        ' AND ' . $this->_db->quoteName('creator_type') . ' = ' . $this->_db->quote($this->creator_type) .
                        ' AND ' . $this->_db->quoteName('path') . ' = ' . $this->_db->quote($this->path);
            $this->_db->setQuery($query);
            return $this->_db->loadResult();
        }
	public function check()
	{
		// Santinise data
		$safeHtmlFilter		= CFactory::getInputFilter();

		$this->title		= $safeHtmlFilter->clean($this->title);
		$this->description 	= $safeHtmlFilter->clean($this->description);
		$this->category_id	= JString::trim((int)$this->category_id);
		$this->permissions	= JString::trim((int)$this->permissions);

		// Validate user information
		if ($this->title == '')
			$this->title = JText::_('COM_COMMUNITY_VIDEOS_TITLE_EMPTY');

		if ($this->description == '')
			$this->description = JText::_('COM_COMMUNITY_VIDEOS_NO_DESCRIPTION');

		if ($this->created == null) {
			$now = JFactory::getDate();
			$this->created = $now->toSql();
		}

		if ($this->published == null)
			$this->published = 1;

		return true;
	}

	/**
	 * @return $embedvideo specific embeded code to play the video
	 */
	public function getViewHTML($videoWidth='' , $videoHeight='', $defaultView=true)
	{
		$id				= ($this->type=='file') ? $this->id : $this->video_id;
		$videoWidth		= $videoWidth ? $videoWidth : $this->getWidth();
		$videoHeight	= $videoHeight ? $videoHeight : $this->getHeight();

		if ($defaultView)
		{
			$html		= $this->_provider->getViewHTML($id, $videoWidth , $videoHeight );
		} else {
			$html		= $this->_provider->getEmbedCode($id, $videoWidth , $videoHeight );
		}

		return $html;
	}

	/**
	 * Return the video provider object
	 */
	public function getProvider()
	{
		return $this->_provider;
	}

	public function store( $updateNulls = false )
	{
		if (empty($source)) {
			$source	= $this;
		}

		if (!$this->check()) {
			return false;
		}
		if (!parent::store()) {
			return false;
		}
		$this->setError('');
		return true;
	}

	/**
	 * Return true if it's not private video
	 */
	public function isPublic()
	{
		if ($this->creator_type == VIDEO_USER_TYPE)
		{
			return ($this->permissions <= 20);
		}
		if ($this->creator_type == VIDEO_GROUP_TYPE)
		{
			$group	= JTable::getInstance( 'Group' , 'CTable' );
			$group->load($this->groupid);
			return ($group->approvals == COMMUNITY_PUBLIC_GROUP);
		}
		return false;
	}

	public function getViewURI($route = true)
	{
		$uri = '';
		switch($this->creator_type)
		{
			case VIDEO_GROUP_TYPE :
				$uri	= 'index.php?option=com_community&view=videos&task=video&groupid='.$this->groupid.'&videoid='.$this->id;
				break;
			case VIDEO_USER_TYPE :
			default :
				$uri	= 'index.php?option=com_community&view=videos&task=video&userid='.$this->creator.'&videoid='.$this->id;
				break;
		}

		return $route ? CRoute::_($uri) : $uri;
	}

	public function getFlv()
	{
		$flv = '';

		if ($this->type != 'file') return $flv;

		$config		= CFactory::getConfig();
		$baseUrl	= $config->get( 'videobaseurl' );
		if ($config->get('enablevideopseudostream') && ($this->storage == 'file') && empty($baseUrl) )
		{
			$flv		= JURI::root() . 'components/com_community/libraries/streamer.php/'.base64_encode($this->path);
		}
		else
		{
			if( !empty($baseUrl) )
			{
				$flv	= rtrim( $baseUrl , '/' ) . '/' . $this->path;
			}
			else
			{

				$storage	= CStorage::getStorage($this->storage);
				$flv		= $storage->getURI($this->path);
			}
		}
		return $flv;
	}

	public function getURL($raw=false)
	{
		$url	= 'index.php?option=com_community&view=videos&task=video';
		if ($this->creator_type == VIDEO_GROUP_TYPE || !empty($this->groupid))
		{
			$url .= '&groupid='.$this->groupid;
		}
		else
		{
			// defaul as user type, VIDEO_USER_TYPE
			$url .= '&userid='.$this->creator;
		}
		$url	.= '&videoid='.$this->id;

		return CRoute::_( $url );
	}

	public function getPermalink()
	{
		$url	= 'index.php?option=com_community&view=videos&task=video';
		if ($this->creator_type == VIDEO_GROUP_TYPE)
		{
			$url .= '&groupid='.$this->groupid;
		}
		else
		{
			// defaul as user type, VIDEO_USER_TYPE
			$url .= '&userid='.$this->creator;
		}
		$url	.= '&videoid='.$this->id;

		return CRoute::getExternalURL( $url , false );
	}

	public function isOwner()
	{
		$my	= CFactory::getUser();
		return COwnerHelper::isMine($my->id, $this->creator);
	}

	public function isAdmin()
	{
		return COwnerHelper::isCommunityAdmin();
	}

	public function canEdit()
	{
		return ($this->isOwner() || $this->isAdmin());
	}

	public function getCreatorName()
	{
		$user = CFactory::getUser($this->creator);
		return $user->getDisplayName();
	}

	public function getHits()
	{
		return $this->hits;
	}

	public function getPlayerHTML($width=null, $height=null, $defaultView=true)
	{
		$id		= ($this->type=='file') ? $this->id : $this->video_id;
		$width	= ($width) ? $width : $this->_width;
		$height	= ($height) ? $height : $this->_height;

		if ($defaultView)
		{
			$html		= $this->_provider->getViewHTML($id, $width , $height );
		} else {
			$html		= $this->_provider->getEmbedCode($id, $width , $height );
		}

		return $html;
	}

	/**
	 * Return the title of the object
	 */
	public function tagGetTitle()
	{
		return $this->getTitle();
	}

	/**
	 * Return the HTML summary of the object
	 */
    public function tagGetHtml()
	{
		return '';
	}

	/**
	 * Return the internal link of the object
	 *
	 */
	public function tagGetLink()
	{
		return $this->getViewURI();
	}

	/**
	 * Return true if the user is allow to modify the tag
	 *
	 */
	public function tagAllow($userid)
	{
		return $this->canEdit($userid);
	}

	/**
	* Return the category name
	*
	*/
	public function getCategoryName(){
		$category	= JTable::getInstance( 'VideosCategory' , 'CTable' );
		$category->load( $this->category_id );

		return $category->name;
	}
}


text:
namespace DeviceSQL.Device.ROC.Message
{
    public interface IROCRequestMessage : IROCMessage
    {
        void ValidateResponse(IROCResponseMessage response);
    }
}


text:
require "helper"

require "gapic/grpc/service_stub"

require "google/cloud/ai_platform/v1/metadata_service"

class ::Google::Cloud::AIPlatform::V1::MetadataService::ClientPathsTest < Minitest::Test
  def test_artifact_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::AIPlatform::V1::MetadataService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.artifact_path project: "value0", location: "value1", metadata_store: "value2", artifact: "value3"
      assert_equal "projects/value0/locations/value1/metadataStores/value2/artifacts/value3", path
    end
  end

  def test_context_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::AIPlatform::V1::MetadataService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.context_path project: "value0", location: "value1", metadata_store: "value2", context: "value3"
      assert_equal "projects/value0/locations/value1/metadataStores/value2/contexts/value3", path
    end
  end

  def test_execution_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::AIPlatform::V1::MetadataService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.execution_path project: "value0", location: "value1", metadata_store: "value2", execution: "value3"
      assert_equal "projects/value0/locations/value1/metadataStores/value2/executions/value3", path
    end
  end

  def test_location_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::AIPlatform::V1::MetadataService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.location_path project: "value0", location: "value1"
      assert_equal "projects/value0/locations/value1", path
    end
  end

  def test_metadata_schema_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::AIPlatform::V1::MetadataService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.metadata_schema_path project: "value0", location: "value1", metadata_store: "value2", metadata_schema: "value3"
      assert_equal "projects/value0/locations/value1/metadataStores/value2/metadataSchemas/value3", path
    end
  end

  def test_metadata_store_path
    grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
    ::Gapic::ServiceStub.stub :new, nil do
      client = ::Google::Cloud::AIPlatform::V1::MetadataService::Client.new do |config|
        config.credentials = grpc_channel
      end

      path = client.metadata_store_path project: "value0", location: "value1", metadata_store: "value2"
      assert_equal "projects/value0/locations/value1/metadataStores/value2", path
    end
  end
end


text:
<annotation>
<folder>calculator</folder>
<filename>calculator_2_view_1_pose_10_lit_1.jpg</filename>
<source>
<database>photorealistic	rendering</database>
</source>
<size>
<width>640</width>
<height>480</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>calculator</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>224</xmin>
<ymin>208</ymin>
<xmax>400</xmax>
<ymax>288</ymax>
</bndbox>
</object>
</annotation>


text:
var assert = require('assert'),
    sinon  = require('sinon'),
    rewire = require('rewire'),
    events = require('events'),
    EJSON  = require('ddp-ejson');

var DDPClient = rewire("../lib/ddp-client");

var wsConstructor, wsMock;

function prepareMocks() {
  wsMock = new events.EventEmitter();

  wsConstructor = sinon.stub();
  wsConstructor.returns(wsMock);
  DDPClient.__set__('WebSocket', { Client: wsConstructor });
}

describe("Connect to remote server", function() {
  beforeEach(function() {
    prepareMocks();
  });

  it('should connect to localhost by default', function() {
    new DDPClient().connect();

    assert(wsConstructor.calledOnce);
    assert(wsConstructor.calledWithNew());
    assert(wsConstructor.call);
    assert.deepEqual(wsConstructor.args, [['ws://localhost:3000/websocket']]);
  });
  it('should connect to the provided host', function() {
    new DDPClient({'host': 'myserver.com'}).connect();
    assert.deepEqual(wsConstructor.args, [['ws://myserver.com:3000/websocket']]);
  });
  it('should connect to the provided host and port', function() {
    new DDPClient({'host': 'myserver.com', 'port': 42}).connect();
    assert.deepEqual(wsConstructor.args, [['ws://myserver.com:42/websocket']]);
  });
  it('should use ssl if the port is 443', function() {
    new DDPClient({'host': 'myserver.com', 'port': 443}).connect();
    assert.deepEqual(wsConstructor.args, [['wss://myserver.com:443/websocket']]);
  });
});

describe('Automatic reconnection', function() {
  beforeEach(function() {
    prepareMocks();
  });

  /* We should be able to get this test to work with clock.tick() but for some weird
     reasons it does not work. See: https://github.com/cjohansen/Sinon.JS/issues/283
   */
  it('should reconnect when the connection fails', function(done) {
    var ddpclient = new DDPClient({ auto_reconnect_timer: 10 });

    ddpclient.connect();
    wsMock.emit('close', {});

    // At this point, the constructor should have been called only once.
    assert(wsConstructor.calledOnce);

    setTimeout(function() {
      // Now the constructor should have been called twice
      assert(wsConstructor.calledTwice);
      done();
    }, 15);
  });

  it('should reconnect only once when the connection fails rapidly', function(done) {
    var ddpclient = new DDPClient({ auto_reconnect_timer: 5 });

    ddpclient.connect();
    wsMock.emit('close', {});
    wsMock.emit('close', {});
    wsMock.emit('close', {});

    // At this point, the constructor should have been called only once.
    assert(wsConstructor.calledOnce);

    setTimeout(function() {
      // Now the constructor should have been called twice
      assert(wsConstructor.calledTwice);
      done();
    }, 15);
  });
});

describe('EJSON', function() {
  var DDPMessage = '{"msg":"added","collection":"posts","id":"2trpvcQ4pn32ZYXco","fields":{"date":{"$date":1371591394454},"bindata":{"$binary":"QUJDRA=="}}}';
  var EJSONObject = EJSON.parse(DDPMessage);

  it('should be enabled by default', function(done) {
    var ddpclient = new DDPClient();

    assert(ddpclient.use_ejson);

    done();
  });

  it('should expose the EJSON object', function(done) {
    var ddpclient = new DDPClient();

    assert(ddpclient.EJSON);
    assert(ddpclient.EJSON.addType);

    done();
  });

  it('should not be used when disabled', function(done) {
    var ddpclient = new DDPClient({ use_ejson : false });

    assert(!ddpclient.use_ejson);

    ddpclient._message(DDPMessage);

    // ensure received dates not decoded from EJSON
    assert.deepEqual(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].date, {"$date":1371591394454});

    // ensure received binary data not decoded from EJSON date
    assert.deepEqual(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].bindata, {"$binary":"QUJDRA=="});

    ddpclient.socket = {};
    ddpclient.socket.send = function (opts) {
      // ensure sent dates not encoded into EJSON
      assert(opts.indexOf("date")          !== -1);
      assert(opts.indexOf("$date")         === -1);
      assert(opts.indexOf("1371591394454") === -1);

      // ensure sent binary data not encoded into EJSON
      assert(opts.indexOf("bindata")       !== -1);
      assert(opts.indexOf("$binary")       === -1);
      assert(opts.indexOf("QUJDRA==")      === -1);
    };

    ddpclient._send(EJSONObject.fields);

    done();
  });

  it('should be used if specifically enabled', function(done) {
    var ddpclient = new DDPClient({ use_ejson : true });

    assert(ddpclient.use_ejson);

    ddpclient._message(DDPMessage);

    assert.deepEqual(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].date, new Date(1371591394454));

    assert.deepEqual(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].bindata, new Uint8Array([65, 66, 67, 68]));

    ddpclient.socket = {};
    ddpclient.socket.send = function (opts) {
      assert(opts.indexOf("date")          !== -1);
      assert(opts.indexOf("$date")         !== -1);
      assert(opts.indexOf("1371591394454") !== -1);

      assert(opts.indexOf("bindata")       !== -1);
      assert(opts.indexOf("$binary")       !== -1);
      assert(opts.indexOf("QUJDRA==")      !== -1);
    };

    ddpclient._send(EJSONObject.fields);

    done();
  });

});

describe('Collection maintenance', function() {
  var addedMessage    = '{"msg":"added","collection":"posts","id":"2trpvcQ4pn32ZYXco","fields":{"text":"A cat was here","value":true}}';
  var changedMessage  = '{"msg":"changed","collection":"posts","id":"2trpvcQ4pn32ZYXco","fields":{"text":"A dog was here"}}';
  var changedMessage2 = '{"msg":"changed","collection":"posts","id":"2trpvcQ4pn32ZYXco","cleared":["value"]}';
  var removedMessage  = '{"msg":"removed","collection":"posts","id":"2trpvcQ4pn32ZYXco"}';

  it('should maintain collections by default', function() {
    var ddpclient = new DDPClient();
    ddpclient._message(addedMessage);
    // ensure collections exist and are populated by add messages
    assert.equal(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].text, "A cat was here");
  });

  it('should maintain collections if maintain_collections is true', function() {
    var ddpclient = new DDPClient({ maintain_collections : true });
    ddpclient._message(addedMessage);
    // ensure collections exist and are populated by add messages
    assert.equal(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].text, "A cat was here");
  });

  it('should not maintain collections if maintain_collections is false', function() {
    var ddpclient = new DDPClient({ maintain_collections : false });
    ddpclient._message(addedMessage);
    // ensure there are no collections
    assert(!ddpclient.collections);
  });

  it('should response to "added" messages', function() {
    var ddpclient = new DDPClient();
    ddpclient._message(addedMessage);
    assert.equal(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].text, "A cat was here");
    assert.equal(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].value, true);
  });

  it('should response to "changed" messages', function() {
    var ddpclient = new DDPClient();
    ddpclient._message(addedMessage);
    ddpclient._message(changedMessage);
    assert.equal(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].text, "A dog was here");
    assert.equal(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].value, true);
  });

  it('should response to "changed" messages with "cleared"', function() {
    var ddpclient = new DDPClient();
    ddpclient._message(addedMessage);
    ddpclient._message(changedMessage);
    ddpclient._message(changedMessage2);
    assert.equal(ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].text, "A dog was here");
    assert(!ddpclient.collections.posts['2trpvcQ4pn32ZYXco'].hasOwnProperty('value'));
  });

  it('should response to "removed" messages', function() {
    var ddpclient = new DDPClient();
    ddpclient._message(addedMessage);
    ddpclient._message(removedMessage);
    assert(!ddpclient.collections.posts.hasOwnProperty('2trpvcQ4pn32ZYXco'));
  });
});


text:
var todoApp = angular.module('todo', ['ui.sortable']);

todoApp.factory('todoAppStorage', function () {
    var STORAGE_ID = 'godo-angularjs';

    return {
        get: function () {
            return JSON.parse(localStorage.getItem(STORAGE_ID)) || [
                {
                    description: "Walk the dog",
                    complete: true,
                    itemID: 0
                },
                {
                    description: "Buy groceries",
                    complete: false,
                    itemID: 1
                },
                {
                    description: "Call mom",
                    complete: false,
                    itemID: 2
                },
                {
                    description: "Go jogging",
                    complete: true,
                    itemID: 3
                }
            ];
        },

        put: function (items) {
            localStorage.setItem(STORAGE_ID, JSON.stringify(items));
        }
    };
});

todoApp.factory('selectedStorage', function () {
    var STORAGE_ID = 'godo-selected';

    return {
        get: function () {
            return JSON.parse(localStorage.getItem(STORAGE_ID)) || {};
        },

        put: function (selected) {
            localStorage.setItem(STORAGE_ID, JSON.stringify(selected));
        }
    }
});

function ItemsController($scope, todoAppStorage, selectedStorage) {
    var items = $scope.items = todoAppStorage.get();
    var search = $scope.search = selectedStorage.get();
    $scope.editingItem = null;

    $scope.$watch('items', function (newValue, oldValue) {
        $scope.activeCount = $scope.itemCount(false);
        $scope.completedCount = items.length - $scope.activeCount;

        if (newValue !== oldValue) {
            todoAppStorage.put(items);
        }
    }, true);

    $scope.$watch('search', function (newValue, oldValue) {
        if (newValue !== oldValue) {
            selectedStorage.put(search);
        }
    }, true);

    $scope.itemCount = function (complete) {
        if (typeof (complete) === 'undefined' || complete === null) {
            return $scope.items.length;
        }
        else {
            var count = 0;
            angular.forEach($scope.items, function (item) {
                if (item.complete == complete) {
                    count++;
                }
            });

            return count;
        }
    }

    $scope.addItem = function (item) {
        var id = $scope.itemID++;
        $scope.trimItem(item);
        $scope.items.push({
            description: item.description,
            complete: false
        });

        item.description = "";
    }

    $scope.deleteItem = function (item) {
        $scope.items.splice($scope.items.indexOf(item), 1);
    }

    $scope.complete = function (item, complete) {
        if (typeof (complete) === 'undefined' || complete === null) {
            delete item.complete;
        }
        else {
            item.complete = complete;
        }
    }

    $scope.edit = function (item) {
        item.editing = true;
        $scope.editingItem = item;
    }

    $scope.doneEditing = function (item) {
        item.editing = false;
        if (item.description.length == 0) {
            $scope.deleteItem(item);
        }
        else {
            $scope.trimItem(item);
        }
        $scope.editingItem = null;
    }

    $scope.trimItem = function (item) {
        var maxLength = 29;
        if (item.description.length > maxLength) {
            item.description = item.description.substring(0, maxLength - 1);
        }
    }
};

todoApp.directive('onBlur', function () {
    return function (scope, elem, attrs) {
        elem.bind('blur', function () {
            scope.$apply(attrs.onBlur);
        });
    };
});

todoApp.directive('giveFocus', function todoFocus($timeout) {
	return function (scope, elem, attrs) {
		scope.$watch(attrs.giveFocus, function (newVal) {
			if (newVal) {
				$timeout(function () {
					elem[0].focus();
				}, 0, false);
			}
		});
	};
});


text:
<?php

/*
 * This file is part of By Night.
 * (c) 2013-2021 Guillaume Sainthillier <guillaume.sainthillier@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Form\Builder;

use App\Form\Type\HiddenDateType;
use App\Form\Type\ShortcutType;
use DateTime;
use DateTimeInterface;
use IntlDateFormatter;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class DateRangeBuilder
{
    public function finishView(FormView $view, FormInterface $form)
    {
        $fromName = $form->get('shortcut')->getConfig()->getOption('from');
        $toName = $form->get('shortcut')->getConfig()->getOption('to');

        $view->children['shortcut']->vars['attr']['data-from'] = $view->children[$fromName]->vars['id'];
        $view->children['shortcut']->vars['attr']['data-to'] = $view->children[$toName]->vars['id'];
        $view->children['shortcut']->vars['attr']['data-ranges'] = json_encode($fromName = $form->get('shortcut')->getConfig()->getOption('ranges'), \JSON_THROW_ON_ERROR);
    }

    public function addShortcutDateFields(FormBuilderInterface $builder, string $fromName, string $toName)
    {
        $ranges = [
            'N\'importe quand' => [(new DateTime('now'))->format('Y-m-d'), null],
            'Aujourd\'hui' => [(new DateTime('now'))->format('Y-m-d'), (new DateTime('now'))->format('Y-m-d')],
            'Demain' => [(new DateTime('tomorrow'))->format('Y-m-d'), (new DateTime('tomorrow'))->format('Y-m-d')],
            'Ce week-end' => [(new DateTime('friday this week'))->format('Y-m-d'), (new DateTime('sunday this week'))->format('Y-m-d')],
            'Cette semaine' => [(new DateTime('monday this week'))->format('Y-m-d'), (new DateTime('sunday this week'))->format('Y-m-d')],
            'Ce mois' => [(new DateTime('first day of this month'))->format('Y-m-d'), (new DateTime('last day of this month'))->format('Y-m-d')],
        ];
        $this->addDateFields($builder, $fromName, $toName, $ranges);
    }

    public function addDateFields(FormBuilderInterface $builder, string $fromName, string $toName, array $ranges = [])
    {
        $builder
            ->add($fromName, HiddenDateType::class)
            ->add($toName, HiddenDateType::class)
            ->add('shortcut', ShortcutType::class, [
                'from' => $fromName,
                'to' => $toName,
                'ranges' => $ranges,
            ])
            ->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) use ($ranges) {
                $form = $event->getForm();
                $shortcut = $form->get('shortcut');
                $fromName = $shortcut->getConfig()->getOption('from');
                $toName = $shortcut->getConfig()->getOption('to');

                /** @var \DateTimeInterface $from */
                $from = $form->get($fromName)->getData();

                /** @var \DateTimeInterface|null $to */
                $to = $form->get($toName)->getData();

                if (null === $from) {
                    return;
                }

                $from = $from->format('Y-m-d');
                if (null !== $to) {
                    $to = $to->format('Y-m-d');
                }

                foreach ($ranges as $label => $range) {
                    if ($range[0] === $from && $range[1] === $to) {
                        $shortcut->setData($label);

                        return;
                    }
                }

                //Custom dates
                $from = new \DateTime($from);
                if (null !== $to) {
                    $to = new \DateTime($to);
                }

                if (null === $to) {
                    $label = sprintf('A partir du %s', $this->formatDate($from));
                } elseif ($to->getTimestamp() === $from->getTimestamp()) {
                    $label = sprintf('Le %s', $this->formatDate($from));
                } else {
                    $label = sprintf('Du %s au %s', $this->formatDate($from), $this->formatDate($to));
                }
                $shortcut->setData($label);
            })
            ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($ranges) {
                $data = $event->getData();
                $form = $event->getForm();
                $shortcut = $form->get('shortcut');
                $fromName = $shortcut->getConfig()->getOption('from');
                $toName = $shortcut->getConfig()->getOption('to');

                $from = ($data[$fromName] ?? null) ?: null;
                $to = ($data[$toName] ?? null) ?: null;

                if (null === $from) {
                    return;
                }

                foreach ($ranges as $label => $range) {
                    if ($range[0] === $from && $range[1] === $to) {
                        $data['shortcut'] = $label;
                        $event->setData($data);

                        return;
                    }
                }

                //Custom dates
                $from = new \DateTime($from);
                if (null !== $to) {
                    $to = new \DateTime($to);
                }

                if (null === $to) {
                    $label = sprintf('A partir du %s', $this->formatDate($from));
                } elseif ($to->getTimestamp() === $from->getTimestamp()) {
                    $label = sprintf('Le %s', $this->formatDate($from));
                } else {
                    $label = sprintf('Du %s au %s', $this->formatDate($from), $this->formatDate($to));
                }
                $data['shortcut'] = $label;
                $event->setData($data);
            });
    }

    private function formatDate(DateTimeInterface $date)
    {
        $formatter = IntlDateFormatter::create(
            null,
            IntlDateFormatter::MEDIUM,
            IntlDateFormatter::NONE);

        return $formatter->format($date->getTimestamp());
    }
}


text:
package org.turbogwt.net.http.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.turbogwt.core.collections.client.JsArrayList;
import org.turbogwt.core.future.shared.DoneCallback;
import org.turbogwt.net.http.client.header.ContentTypeHeader;
import org.turbogwt.net.http.client.mock.ResponseMock;
import org.turbogwt.net.http.client.mock.ServerStub;
import org.turbogwt.net.serialization.shared.Json;

/**
 * @author Danilo Reinert
 */
public class GeneratedJsonSerdesTest extends GWTTestCase {

    @Override
    public String getModuleName() {
        return "org.turbogwt.net.http.HttpTest";
    }

    public void testGeneratedSingleDeserialization() {
        final Animal stuart = new Animal("Stuart", 3);

        final Requestor requestor = getRequestor();

        final String uri = "/animal";

        final String serialized = "{\"name\":\"Stuart\",\"age\":3}";

        ServerStub.responseFor(uri, ResponseMock.of(serialized, 200, "OK",
                new ContentTypeHeader("application/json")));

        final boolean[] callbackDoneCalled = new boolean[1];

        requestor.request(uri).get(Animal.class)
                .done(new DoneCallback<Animal>() {
                    @Override
                    public void onDone(Animal animal) {
                        callbackDoneCalled[0] = true;
                        assertEquals(stuart, animal);
                    }
                });

        ServerStub.triggerPendingRequest();

        assertTrue(callbackDoneCalled[0]);
    }

    public void testGeneratedArrayListDeserialization() {
        final Animal stuart = new Animal("Stuart", 3);
        final Animal march = new Animal("March", 5);
        final List<Animal> list = new ArrayList<Animal>();
        list.add(stuart); list.add(march);

        final Requestor requestor = getRequestor();

        final String uri = "/animals";

        final String serialized = "[{\"name\":\"Stuart\",\"age\":3},{\"name\":\"March\",\"age\":5}]";

        ServerStub.responseFor(uri, ResponseMock.of(serialized, 200, "OK",
                new ContentTypeHeader("application/json")));

        final boolean[] callbackDoneCalled = new boolean[1];

        requestor.request(uri).get(Animal.class, ArrayList.class)
                .done(new DoneCallback<Collection<Animal>>() {
                    @Override
                    public void onDone(Collection<Animal> animals) {
                        callbackDoneCalled[0] = true;
                        ArrayList<Animal> arrayList = (ArrayList<Animal>) animals;
                        assertTrue(Arrays.equals(list.toArray(), arrayList.toArray()));
                    }
                });

        ServerStub.triggerPendingRequest();

        assertTrue(callbackDoneCalled[0]);
    }

    public void testGeneratedCustomListDeserialization() {
        final Animal stuart = new Animal("Stuart", 3);
        final Animal march = new Animal("March", 5);
        final List<Animal> list = new ArrayList<Animal>();
        list.add(stuart); list.add(march);

        final Requestor requestor = getRequestor();

        final String uri = "/animals";

        final String serialized = "[{\"name\":\"Stuart\",\"age\":3},{\"name\":\"March\",\"age\":5}]";

        ServerStub.responseFor(uri, ResponseMock.of(serialized, 200, "OK",
                new ContentTypeHeader("application/json")));

        final boolean[] callbackDoneCalled = new boolean[1];

        requestor.request(uri).get(Animal.class, JsArrayList.class)
                .done(new DoneCallback<Collection<Animal>>() {
                    @Override
                    public void onDone(Collection<Animal> animals) {
                        callbackDoneCalled[0] = true;
                        JsArrayList<Animal> arrayList = (JsArrayList<Animal>) animals;
                        assertTrue(Arrays.equals(list.toArray(), arrayList.toArray()));
                    }
                });

        ServerStub.triggerPendingRequest();

        assertTrue(callbackDoneCalled[0]);
    }

    public void testGeneratedSingleSerialization() {
        final Animal stuart = new Animal("Stuart", 3);

        final Requestor requestor = getRequestor();

        final String uri = "/animal";

        final String serialized = "{\"name\":\"Stuart\",\"age\":3}";

        ServerStub.responseFor(uri, ResponseMock.of(null, 200, "OK",
                new ContentTypeHeader("application/json")));

        final boolean[] callbackDoneCalled = new boolean[1];

        requestor.request(uri).payload(stuart).post()
                .done(new DoneCallback<Void>() {
                    @Override
                    public void onDone(Void ignored) {
                        callbackDoneCalled[0] = true;
                    }
                });

        ServerStub.triggerPendingRequest();

        assertTrue(callbackDoneCalled[0]);
        assertEquals(serialized, ServerStub.getRequestData(uri).getData());
    }

    public void testGeneratedArrayListSerialization() {
        final Animal stuart = new Animal("Stuart", 3);
        final Animal march = new Animal("March", 5);
        final List<Animal> list = new ArrayList<Animal>();
        list.add(stuart); list.add(march);

        final Requestor requestor = getRequestor();

        final String uri = "/animals";

        final String serialized = "[{\"name\":\"Stuart\",\"age\":3},{\"name\":\"March\",\"age\":5}]";

        ServerStub.responseFor(uri, ResponseMock.of(null, 200, "OK",
                new ContentTypeHeader("application/json")));

        final boolean[] callbackDoneCalled = new boolean[1];

        requestor.request(uri).payload(list).post()
                .done(new DoneCallback<Void>() {
                    @Override
                    public void onDone(Void ignored) {
                        callbackDoneCalled[0] = true;
                    }
                });

        ServerStub.triggerPendingRequest();

        assertTrue(callbackDoneCalled[0]);
        assertEquals(serialized, ServerStub.getRequestData(uri).getData());
    }

    public void testGeneratedCustomListSerialization() {
        final Animal stuart = new Animal("Stuart", 3);
        final Animal march = new Animal("March", 5);
        final List<Animal> list = new JsArrayList<Animal>();
        list.add(stuart); list.add(march);

        final Requestor requestor = getRequestor();

        final String uri = "/animals";

        final String serialized = "[{\"name\":\"Stuart\",\"age\":3},{\"name\":\"March\",\"age\":5}]";

        ServerStub.responseFor(uri, ResponseMock.of(null, 200, "OK",
                new ContentTypeHeader("application/json")));

        final boolean[] callbackDoneCalled = new boolean[1];

        requestor.request(uri).payload(list).post()
                .done(new DoneCallback<Void>() {
                    @Override
                    public void onDone(Void ignored) {
                        callbackDoneCalled[0] = true;
                    }
                });

        ServerStub.triggerPendingRequest();

        assertTrue(callbackDoneCalled[0]);
        assertEquals(serialized, ServerStub.getRequestData(uri).getData());
    }

    private Requestor getRequestor() {
        ServerStub.clearStub();
        return GWT.create(Requestor.class);
    }

    /**
     * Class to auto-generate serializer.
     */
    @Json({"app*/json*", "*/javascript*" })
    public static class Animal {

        private String name;
        private Integer age;

        public Animal() {
        }

        public Animal(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (!(o instanceof Animal)) {
                return false;
            }

            final Animal animal = (Animal) o;

            if (age != null ? !age.equals(animal.age) : animal.age != null) {
                return false;
            }
            if (name != null ? !name.equals(animal.name) : animal.name != null) {
                return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            int result = name != null ? name.hashCode() : 0;
            result = 31 * result + (age != null ? age.hashCode() : 0);
            return result;
        }
    }
}


text:
				{% for choice in sources %}
					{% include 'include/source_single.html' %}
				{% endfor %}


text:
class SkBitmap;

namespace content {

// Provides an interface to WebKit's image decoders.
//
// Note to future: This class should be deleted. We should have our own nice
// image decoders in base/gfx, and our port should use those. Currently, it's
// the other way around.
class ImageDecoder {
 public:
  // Use the constructor with desired_size when you think you may have an .ico
  // format and care about which size you get back. Otherwise, use the 0-arg
  // constructor.
  ImageDecoder();
  ImageDecoder(const gfx::Size& desired_icon_size);
  ~ImageDecoder();

  // Call this function to decode the image. If successful, the decoded image
  // will be returned. Otherwise, an empty bitmap will be returned.
  SkBitmap Decode(const unsigned char* data, size_t size) const;

  // Returns all frames found in the image represented by data. If there are
  // multiple frames at the same size, only the first one is returned.
  static std::vector<SkBitmap> DecodeAll(
      const unsigned char* data, size_t size);

 private:
  // Size will be empty to get the largest possible size.
  gfx::Size desired_icon_size_;

  DISALLOW_COPY_AND_ASSIGN(ImageDecoder);
};

}  // namespace content


text:
#ifndef _PROPERTIESPANEL_H_
#define _PROPERTIESPANEL_H_

#include <map>

#include <wx/panel.h>

class wxGridSizer;
class wxPropertyGridManager;

class EventArgs;
class MaterialController;
class MaterialEventArgs;
class MaterialPropertyGridPage;
class PassController;
class PassEventArgs;
class PassPropertyGridPage;
class ProjectEventArgs;
class SelectionEventArgs;
class TechniqueController;
class TechniqueEventArgs;
class TechniquePropertyGridPage;

//typedef std::map<Project*, ProjectP> ProjectPageMap;
typedef std::map<MaterialController*, int> MaterialPageIndexMap;
typedef std::map<TechniqueController*, int> TechniquePageIndexMap;
typedef std::map<PassController*, int> PassPageIndexMap;

class PropertiesPanel : public wxPanel
{
public:
	PropertiesPanel(wxWindow* parent,
		wxWindowID id = wxID_ANY,
		const wxPoint& pos = wxDefaultPosition,
		const wxSize& size = wxDefaultSize,
		long style = wxTAB_TRAVERSAL | wxNO_BORDER,
		const wxString& name = wxT("Properties Panel"));

	virtual ~PropertiesPanel();

	void selectionChanged(EventArgs& args);

	void projectRemoved(EventArgs& args);
	void materialRemoved(EventArgs& args);
	void techniqueRemoved(EventArgs& args);
	void passRemoved(EventArgs& args);

protected:
	wxGridSizer* mGridSizer;
	wxPropertyGridManager* mPropertyGrid;

	MaterialPageIndexMap mMaterialPageIndexMap;
	TechniquePageIndexMap mTechniquePageIndexMap;
	PassPageIndexMap mPassPageIndexMap;

	DECLARE_EVENT_TABLE()
};

#endif // _PROPERTIESPANEL_H_


text:
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using Faker;
using Twilio.Jwt.AccessToken;

namespace VideoQuickstart.Controllers
{
    public class TokenController : Controller
    {
        // GET: Token
        public ActionResult Index(string device)
        {
            // Load Twilio configuration from Web.config
            var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
            var apiKey = ConfigurationManager.AppSettings["TwilioApiKey"];
            var apiSecret = ConfigurationManager.AppSettings["TwilioApiSecret"];
            var videoConfigSid = ConfigurationManager.AppSettings["TwilioConfigurationSid"];

            // Create a random identity for the client
            var identity = Internet.UserName();

            var grants = new HashSet<IGrant>
            {
                // Grant access to Video
                new VideoGrant { ConfigurationProfileSid = videoConfigSid }
            };

            // Create an Access Token generator
            var token = new Token(accountSid, apiKey, apiSecret, identity: identity, grants: grants);

            return Json(new
            {
                identity,
                token = token.ToJwt()
            }, JsonRequestBehavior.AllowGet);
        }
    }
}


text:
#include <stdlib.h>
#include <string.h>
#include <sys/ptrace.h>

#include "ptrace.h"

#ifndef ZEND_EVAL
#define ZEND_EVAL               (1<<0)
#define ZEND_INCLUDE            (1<<1)
#define ZEND_INCLUDE_ONCE       (1<<2)
#define ZEND_REQUIRE            (1<<3)
#define ZEND_REQUIRE_ONCE       (1<<4)
#endif

#ifndef ZEND_USER_CODE
/* A quick check (type == ZEND_USER_FUNCTION || type == ZEND_EVAL_CODE) */
#define ZEND_USER_CODE(type) ((type & 1) == 0)
#endif

static int ptrace_fetch_str(pid_t pid, void *addr, char *buf, size_t size)
{
    char *p;
    int i, j;
    long val;

    for (i = 0; i < size; addr += sizeof(long)) {
        val = ptrace(PTRACE_PEEKDATA, pid, addr, NULL);
        if (val == -1) {
            return -1;
        }

        p = (char *) &val;
        for (j = 0; j < sizeof(long) && i < size; j++) {
            buf[i++] = *p++;
        }
    }
    buf[i] = '\0';

    return i;
}

static inline long ptrace_fetch_long(pid_t pid, void *addr)
{
    /* some debug code here, just this... */
    return ptrace(PTRACE_PEEKDATA, pid, (void *) addr, NULL);
}

/* quick ptrace fetch */
#define fetch_long(addr)    ptrace_fetch_long(pid, (void *) addr)
#define fetch_int(addr)     (int) (fetch_long(addr) & 0xFFFFFFFF)
#define fetch_ptr(addr)     (void *) fetch_long(addr)

#define fetch_str(addr, buf, size)  ptrace_fetch_str(pid, (void *) addr, buf, size)
#define fetch_zstr(addr, buf)       fetch_str(addr + 24, buf, fetch_long(addr + 16))

/* TODO store presets in local file */
static pt_ptrace_preset_t presets[] = {
    {70012, 1,/**/0, 40, 8, 48, 140, 144, 440,/**/480, 0, 56, 24, 32,/**/8, 16, 120, 8, 20, 24},
    {50619, 0,/**/0, 40, 8, 48, 140, 144, 440,/**/1120, 0, 48, 8, 32,/**/8, 16, 152, 8, 32, 40},
    {50533, 0,/**/0, 64, 8, 72, 156, 160, 448,/**/1120, 0, 48, 8, 32,/**/8, 16, 152, 8, 32, 40},
};

pt_ptrace_preset_t *pt_ptrace_preset(int version, void *addr_sapi_module,
        void *addr_sapi_globals, void *addr_executor_globals)
{
    int i;

    for (i = 0; i < sizeof(presets); i++) {
        if (version >= presets[i].version) {
            presets[i].sapi_module = addr_sapi_module;
            presets[i].sapi_globals = addr_sapi_globals;
            presets[i].executor_globals = addr_executor_globals;

            return &presets[i];
        }
    }

    return NULL;
}

long pt_ptrace_attach(pid_t pid)
{
    return ptrace(PTRACE_ATTACH, pid, NULL, NULL);
}

long pt_ptrace_detach(pid_t pid)
{
    return ptrace(PTRACE_DETACH, pid, NULL, NULL);
}

void *pt_ptrace_fetch_current_ex(pt_ptrace_preset_t *preset, pid_t pid)
{
    /* NULL means PHP is in-active */
    return fetch_ptr(preset->executor_globals + preset->EG_current_execute_data);
}

int pt_ptrace_build_status(pt_status_t *status, pt_ptrace_preset_t *preset,
        pid_t pid, void *addr_root_ex, int version_id)
{
    int i;
    void *addr_current_ex;

    memset(status, 0, sizeof(pt_status_t));

    /* version */
    status->php_version = sdscatprintf(sdsempty(), "%d.%d.%d",
            version_id / 10000, version_id % 10000 / 100, version_id % 100);

    /* request */
    pt_ptrace_build_request(&status->request, preset, pid);

    /* calculate stack depth */
    for (i = 0, addr_current_ex = addr_root_ex; addr_current_ex; i++) {
        addr_current_ex = fetch_ptr(addr_current_ex + preset->EX_prev_execute_data); /* prev */
    }
    status->frame_count = i;

    if (status->frame_count) {
        status->frames = calloc(status->frame_count, sizeof(pt_frame_t));
        for (i = 0, addr_current_ex = addr_root_ex; i < status->frame_count && addr_current_ex; i++) {
            pt_ptrace_build_frame(status->frames + i, preset, pid, addr_current_ex);
            addr_current_ex = fetch_ptr(addr_current_ex + preset->EX_prev_execute_data); /* prev */
        }
    } else {
        status->frames = NULL;
    }

    return 0;
}

int pt_ptrace_build_request(pt_request_t *request, pt_ptrace_preset_t *preset,
        pid_t pid)
{
    int i;
    long val;
    void *addr;
    static char buf[4096];

    /* init */
    memset(request, 0, sizeof(pt_request_t));

    request->type = PT_FRAME_STACK;

    /* sapi_module.name */
    addr = fetch_ptr(preset->sapi_module + preset->SM_name);
    if (addr != NULL) {
        fetch_str(addr, buf, sizeof(buf));
        request->sapi = sdsnew(buf);
    }

    /* sapi_globals request_info->path_translated */
    addr = fetch_ptr(preset->sapi_globals + preset->SG_request_info_path_translated);
    if (addr != NULL) {
        fetch_str(addr, buf, sizeof(buf));
        request->script = sdsnew(buf);
    }

    /* sapi_globals request_info->request_method */
    addr = fetch_ptr(preset->sapi_globals + preset->SG_request_info_request_method);
    if (addr != NULL) {
        fetch_str(addr, buf, sizeof(buf));
        request->method = sdsnew(buf);
    }

    /* sapi_globals request_info->request_uri */
    addr = fetch_ptr(preset->sapi_globals + preset->SG_request_info_request_uri);
    if (addr != NULL) {
        fetch_str(addr, buf, sizeof(buf));
        request->uri = sdsnew(buf);
    }

    /* argc, argv */
    request->argc = fetch_int(preset->sapi_globals + preset->SG_request_info_argc);
    if (request->argc) {
        request->argv = calloc(request->argc, sizeof(sds));
        addr = fetch_ptr(preset->sapi_globals + preset->SG_request_info_argv);
        for (i = 0; i < request->argc; i++) {
            fetch_str(addr + sizeof(char *) * i, buf, sizeof(buf));
            request->argv[i] = sdsnew(buf);
        }
    }

    /* sapi_globals global_request_time */
    val = fetch_long(preset->sapi_globals + preset->SG_global_request_time);
    request->time = (long) (*(double *) &val) * 1000000l;

    return 0;
}

int pt_ptrace_build_frame(pt_frame_t *frame, pt_ptrace_preset_t *preset,
        pid_t pid, void *addr_current_ex)
{
    static char buf[4096];

    memset(frame, 0, sizeof(pt_frame_t));

    /* types, level */
    frame->type = PT_FRAME_STACK;
    /* TODO frame->functype = internal ? PT_FUNC_INTERNAL : 0x00; */
    frame->level = 1;

    /* args init */
    frame->arg_count = 0;
    frame->args = NULL;

    void *addr_prev_ex = fetch_ptr(addr_current_ex + preset->EX_prev_execute_data);

    void *addr_ex_func = fetch_ptr(addr_current_ex + preset->EX_func);
    void *addr_ex_func_name = fetch_ptr(addr_ex_func + preset->EX_FUNC_name);
    void *addr_ex_func_scope = fetch_ptr(addr_ex_func + preset->EX_FUNC_scope);
    void *addr_ex_This = fetch_ptr(addr_current_ex + preset->EX_This);

    void *addr_caller_ex = addr_prev_ex ? addr_prev_ex : addr_current_ex;
    void *addr_caller_ex_opline = fetch_ptr(addr_caller_ex + preset->EX_opline);
    void *addr_caller_ex_func = fetch_ptr(addr_caller_ex + preset->EX_func);
    void *addr_caller_ex_func_oparray_filename = fetch_ptr(addr_caller_ex_func +
            preset->EX_FUNC_oparray_filename);

    /* names */
    if (addr_ex_func_name) {
        /* function name */
        if (preset->has_zend_string) {
            fetch_zstr(addr_ex_func_name, buf);
        } else {
            fetch_str(addr_ex_func_name, buf, sizeof(buf));
        }
        frame->function = sdsnew(buf);

        /*  functype, class name */
        if (addr_ex_func_scope) {
            void *addr_ex_func_scope_name = fetch_ptr(addr_ex_func_scope + preset->EX_FUNC_SCOPE_name);

            if (preset->has_zend_string) {
                fetch_zstr(addr_ex_func_scope_name, buf);
            } else {
                fetch_str(addr_ex_func_scope_name, buf, sizeof(buf));
            }
            frame->class = sdsnew(buf);

            frame->functype |= addr_ex_This ? PT_FUNC_MEMBER : PT_FUNC_STATIC;
        } else {
            frame->functype |= PT_FUNC_NORMAL;
        }
    } else {
        long ev = 0;

        if (addr_caller_ex && addr_caller_ex_opline) {
            ev = fetch_long(addr_caller_ex_opline + preset->EX_OPLINE_extended_value);
        }

        /* special user function */
        switch (ev) {
            case ZEND_INCLUDE_ONCE:
                frame->functype |= PT_FUNC_INCLUDE_ONCE;
                frame->function = "include_once";
                break;
            case ZEND_REQUIRE_ONCE:
                frame->functype |= PT_FUNC_REQUIRE_ONCE;
                frame->function = "require_once";
                break;
            case ZEND_INCLUDE:
                frame->functype |= PT_FUNC_INCLUDE;
                frame->function = "include";
                break;
            case ZEND_REQUIRE:
                frame->functype |= PT_FUNC_REQUIRE;
                frame->function = "require";
                break;
            case ZEND_EVAL:
                frame->functype |= PT_FUNC_EVAL;
                frame->function = "{eval}";
                break;
            default:
                /* should be function main */
                frame->functype |= PT_FUNC_NORMAL;
                frame->function = "{main}";
                break;
        }
        frame->function = sdsnew(frame->function);
    }

    /* lineno */
    if (addr_caller_ex && addr_caller_ex_opline) {
        frame->lineno = fetch_int(addr_caller_ex_opline + preset->EX_OPLINE_lineno);
    } else {
        frame->lineno = 0;
    }

    /* filename */
    unsigned char caller_func_type = fetch_long(addr_caller_ex_func + 0) & 0xFF;
    if (addr_caller_ex_func_oparray_filename && ZEND_USER_CODE(caller_func_type)) {
        if (preset->has_zend_string) {
            fetch_zstr(addr_caller_ex_func_oparray_filename, buf);
        } else {
            fetch_str(addr_caller_ex_func_oparray_filename, buf, sizeof(buf));
        }
        frame->filename = sdsnew(buf);
    } else {
        frame->filename = NULL;
    }

    return 0;
}


text:
package com.shalloui.tblite.mapper

/**
  * Typeclass for converting an object of type [[T]]
  * to and from Java maps, array, lists etc. Supports
  * sealed trait hierachies as well as optional values
  * (via Scala's Option type)
  *
  * @tparam T Type of objects we want to convert.
  *
  * Created by a.reisberg on 8/28/2016.
  */
trait Codec[T] {
  /**
    * Type of output given by encode
    */
  type Out

  /**
    * Encode an object t of type [[T]] to type [[Out]]
    * so it can be passed to Couchbase lite
    *
    * @param t object of type T to be converted
    * @return object of type [[Out]]
    */
  def encode(t: T): Out

  /**
    * Decode an object returned by Couchbase lite to
    * the desired type
    *
    * @param i Object coming from Couchbase lite
    * @return a possible value of type [[T]]
    */
  def decode(i: AnyRef): Option[T]
}

object Codec {
  type Aux[T, Out0] = Codec[T] {type Out = Out0}

  /**
    * Derive a Codec for type [[T]]
    *
    * @param encodeEv implicit parameter for the encoding part
    * @param decodeEv implicit parameter for the decoding part
    * @tparam T (Scala) type we want to convert
    * @return Codec
    */
  implicit def apply[T](implicit encodeEv: ToGen[T], decodeEv: FromAny[T]): Aux[T, encodeEv.Out] =
    aux[T, encodeEv.Out](encodeEv, decodeEv)

  /**
    * Similar to [[apply]] except that we can specify the output type
    *
    * @return Codec, where output type for encoding is specified by [[Out0]]
    */
  def aux[T, Out0](implicit encodeEv: ToGen.Aux[T, Out0], decodeEv: FromAny[T]): Aux[T, Out0] =
    new Codec[T] {
      type Out = Out0

      override def encode(t: T): Out = encodeEv(t)

      override def decode(i: AnyRef): Option[T] = decodeEv(i)
    }

  def noHintAux[T, Out0](implicit encodeEv: ToGen.Aux[T, Out0], decodeEv: FromAny[T]): Aux[T, Out0] =
    new Codec[T] {
      type Out = Out0

      override def encode(t: T): Out = encodeEv(t, typeHint = false)

      override def decode(i: AnyRef): Option[T] = decodeEv(i, typeHint = false)
    }

  def noHint[T](implicit encodeEv: ToGen[T], decodeEv: FromAny[T]): Aux[T, encodeEv.Out] =
    noHintAux[T, encodeEv.Out](encodeEv, decodeEv)
}


text:
<?php

defined('APP_ROOT') or define('APP_ROOT', realpath(__DIR__.'/../'));
putenv('APP_ROOT='.APP_ROOT);

defined('APP_ENV') or define('APP_ENV', getenv('APP_ENV') ?: 'development');

require APP_ROOT.'/vendor/autoload.php';

$app = require APP_ROOT.'/app/bootstrap.php';

$app = $app['stack']->resolve($app);

Stack\run($app);


text:
Classes
=======

This is a complete list of available classes:

- [`Phine\Bench\Exception\BenchException`](Phine/Bench/Exception/BenchException.md) — Exception throw for benchmark related errors.
- [`Phine\Bench\Suite`](Phine/Bench/Suite.md) — Manages a suite of individual tests.
- [`Phine\Bench\Test`](Phine/Bench/Test.md) — Manages the execution of an individual test.


text:
sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew tap caskroom/cask
brew tap caskroom/versions
brew tap homebrew/boneyard
brew tap homebrew/core
brew tap kong/kong
brew tap pivotal/tap

brew install python python2
brew cask install java java8

./pip3_install.sh
./pip_install.sh

./brew_cask_install.sh
./brew_install.sh


text:
  #define PLATFORM_SUN
#endif

// should be set before including anything
#define _FILE_OFFSET_BITS 64
//#include <unistd.h>
#include <inttypes.h>

#define finline inline

// default 64bit type
typedef int64_t __int64;
typedef uint64_t __uint64;

//define SEQAN_SWITCH_USE_FORWARDS t generated forwards
#define SEQAN_SWITCH_USE_FORWARDS

#include "platform_generated_forwards.h"

#ifndef SEQAN_HEADER_PLATFORM_GENERATED_FORWARDS_H
#error To use the SeqAn library you first have to execute 'make forwards' in the root directory
#endif


text:
package io.unicall.admin;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import io.unicall.entity.SysUserEntity;
import io.unicall.entity.UsernamePasswordUsertypeToken;
import io.unicall.utils.R;
import io.unicall.utils.ShiroUtils;

import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 *
 * @author unicall
 *
 * @date 2016年11月10日 下午1:15:31
 */
@Controller
public class SysLoginController {
	@Autowired
	private Producer producer;

	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
		out.flush();
	}

	/**
	 * 登录
//	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
//	public R login(String username, String password, String captcha)throws IOException {
	public R login(@ModelAttribute SysUserEntity user, String captcha)throws IOException {
		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		if(!captcha.equalsIgnoreCase(kaptcha)){
			return R.error("验证码不正确");
		}

		try{
			//通过ShiroUtils工具类,获取当前的用户
			Subject subject = ShiroUtils.getSubject();

			//sha256加密
			String password = new Sha256Hash(user.getPassword()).toHex();
			//收集用户身份和证明
//			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			UsernamePasswordToken token = new UsernamePasswordUsertypeToken(user.getUsername(), password,"1");

			//提交认证
			subject.login(token);
			//记住我
			token.setRememberMe(true);
		}catch (UnknownAccountException e) {
			return R.error(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			return R.error(e.getMessage());
		}catch (LockedAccountException e) {
			return R.error(e.getMessage());
		}catch (AuthenticationException e) {
			return R.error("账户验证失败");
		}

		return R.ok();
	}

	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login_uadf.html";
	}

}


text:
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render });

function preload() {

    game.load.image('atari', 'assets/sprites/atari130xe.png');
    game.load.spritesheet('bullets', 'assets/sprites/balls.png', 17, 17);

}

var bob;
var atari;
var balls;
var cursors;

function create() {

    game.physics.startSystem(Phaser.Physics.ARCADE);

    game.stage.backgroundColor = '#2d2d2d';

    bob = game.add.group();
    balls = game.add.group();

    balls.createMultiple(50, 'bullets');

    balls.setAll('anchor.x', 0.5);
    balls.setAll('anchor.y', 0.5);

    bob.add(balls);

    game.physics.arcade.enable(balls, true);

    atari = game.add.sprite(300, 450, 'atari');
    game.physics.arcade.enable(atari, true);
    game.physics.arcade.gravity.y = 400;
    atari.body.allowGravity = 0;
    atari.body.immovable = true;

    cursors = game.input.keyboard.createCursorKeys();

    game.time.events.loop(150, fire, this);

    game.add.text(16, 16, 'Left / Right to move', { font: '18px Arial', fill: '#ffffff' });

}

function fire() {

    var ball = balls.getFirstExists(false);

    if (ball)
    {
        ball.frame = game.rnd.integerInRange(0,6);
        ball.exists = true;
        ball.reset(game.world.randomX, 0);

        ball.body.bounce.y = 0.8;
    }

}

function reflect(a, ball) {

    if (ball.y > (atari.y + 5))
    {
        return true;
    }
    else
    {
        ball.body.velocity.x = atari.body.velocity.x;
        ball.body.velocity.y *= -(ball.body.bounce.y);

        return false;
    }

}

function update() {

    game.physics.arcade.collide(atari, balls, null, reflect, this);
    // game.physics.arcade.collide(atari, bob, null, reflect, this);

    atari.body.velocity.x = 0;

    if (cursors.left.isDown)
    {
        atari.body.velocity.x = -200;
    }
    else if (cursors.right.isDown)
    {
        atari.body.velocity.x = 200;
    }

    balls.forEachAlive(checkBounds, this);

}

function checkBounds(ball) {

    if (ball.y > 600)
    {
        ball.kill();
    }

}

function render() {

}


text:
var express = require('express'),

    path = require('path'),
    util = require('util'),

    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),

    methodOverride = require('method-override'),
    compression = require('compression'),

    errorHandler = require('errorHandler'),
    logger = require('morgan'),

    favicon = require('serve-favicon'),
    settings = require('./app/settings'),
    routes = require('./app/routes/index.js'),

    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),

    MongoStore = require('connect-mongo')(session),
    sessionStore = new MongoStore({
        url: settings.dbUrl
    }),

    User = require('./app/models/user.js'),
    Message = require('./app/models/message.js'),
    Room = require('./app/models/room.js')

app.set('port', process.env.PORT || 3000)
//app.set('views', path.join(__dirname, 'app/views'))
//app.set('view engine', 'ejs')

app.use(methodOverride())
app.use(bodyParser.urlencoded({
    extended: false
}))
app.use(bodyParser.json())
app.use(cookieParser())
app.use(session({
    secret: settings.cookieSecret,
    cookie: {
        maxAge: 1000 * 60 * 30
    },
    resave: true,
    saveUninitialized: false,
    store: sessionStore
}))
app.use(compression())
//app.use(favicon(path.join(__dirname, 'public/images/favicon.ico')))
app.use(express.static(path.join(__dirname, 'public')))

if ('development' === app.get('env')) {
    app.use(logger('dev'))
    app.use(errorHandler())
}

//app.get('/', function (req, res) {
//    res.sendFile(path.join(__dirname + '/public/chat.html'))
//})
routes(app)

app.get("*", function (req, res) {
    res.sendFile(path.join(__dirname + '/public/chat.html'))
})

http.listen(app.get('port'), function () {
    console.log('Server is running on ' + app.set('port'))
})

var messages = []
io.on('connection', function (socket) {
    var SYSTEM = {
        name: 'SYSTEM',
        avatarUrl: '/imgs/tx.jpg'
    }, _userId

    socket.on('getRooms', function (data) {
        _userId = data._userId
        var _usersLen = []
        Room.read(function (err, rooms) {
            if (err) {
                socket.emit('error', {
                    msg: err
                })
            } else {
                if (rooms.length === 0) {
                    return socket.emit('roomsData', {
                        rooms: rooms,
                        usersLen: _usersLen
                    })
                }
                var len = 0
                rooms.forEach(function (room) {
                    User.find({
                        _roomId: room._id
                    }, function (err, users) {
                        _usersLen.push(users.length)
                        len++
                        if (len === rooms.length) {
                            socket.emit('roomsData', {
                                rooms: rooms,
                                usersLen: _usersLen
                            })
                        }
                    })
                })
            }
        })
    })
    socket.on('createRoom', function (room) {
        var newRoom = new Room(room)
        newRoom.save(function (err, room) {
            if (err) {
                socket.emit('error', {
                    msg: err
                })
            } else {
                io.emit('roomAdded', room)
            }
        })
    })
    socket.on('joinRoom', function (join) {
        User.joinRoom(join, function (err, user) {
            if (err) {
                socket.emit('error', {
                    msg: err
                })
            } else {
                socket.join(join.room._id)
                socket.broadcast.in(join.room._id).emit('joinRoom', join)
                socket.broadcast.in(join.room._id).emit('messageAdded', {
                    content: join.user.name + '进入了聊天室',
                    creator: SYSTEM,
                    createAt: new Date()
                })
                socket.emit('joinRoom.' + join.user._id, join)
                socket.emit('joinRoom', join)
            }
        })
    })
    socket.on('getCurRoom', function (data) {
        _userId = data._userId
        var _users = [],
            _messages = []
        Room.findById(data.roomId, function (err, room) {
            if (err) {
                socket.emit('error', {
                    msg: err
                })
            } else {
                User.find({
                    _roomId: room._id
                }, function (err, users) {
                    if (err) return
                    _users = users
                    Message.find({
                        _roomId: room._id
                    }, function (err, messages) {
                        if (err) return
                        _messages = messages
                        socket.emit('curRoomData', {
                            room: room,
                            users: _users,
                            messages: _messages
                        })
                    })
                })
            }
        })
    })

    socket.on('createMessage', function (data) {
        var newMessage = new Message({
            content: data.content,
            creator: data.creator,
            _roomId: data._roomId
        })
        newMessage.save(function (err, message) {
            if (err) {
                socket.emit('error', {
                    msg: err
                })
            } else {
                socket.in(message._roomId).broadcast.emit('messageAdded', message)
                socket.emit('messageAdded', message)
            }
        })
    })

    socket.on('disconnect', function () {
        User.offline(_userId, function (err, user) {
            if (err) {
                socket.emit('error', {
                    msg: err
                })
            } else {
                socket.broadcast.in(user._roomId).emit('offline', user)
                socket.broadcast.in(user._roomId).emit('messageAdded', {
                    content: user.name + '离开了聊天室',
                    creator: SYSTEM,
                    createAt: new Date()
                })
                User.leaveRoom({
                    userId: user._id
                }, function () {})
            }
        })
    })
    socket.on('error', function (msg) {
        console.log('cao...')
    })

})