text:
class User < ActiveRecord::Base
  include Debitcredit::Extension

  has_accounts do
    asset :cash

    def accounts_method
      :ok
    end
  end

  has_entries do
    def entries_method
      :ok
    end
  end
end


text:
package com.planet_ink.coffee_mud.Abilities.Songs;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Skill_Imitation extends BardSkill
{
	public String ID() { return "Skill_Imitation"; }
	public String name(){ return "Imitate";}
	public String displayText(){ return "";}
	protected int canAffectCode(){return CAN_MOBS;}
	protected int canTargetCode(){return 0;}
	public int abstractQuality(){return Ability.QUALITY_OK_SELF;}
	private static final String[] triggerStrings = {"IMITATE"};
	public String[] triggerStrings(){return triggerStrings;}
	public boolean isAutoInvoked(){return true;}
	public boolean canBeUninvoked(){return false;}
    public int classificationCode(){return Ability.ACODE_SKILL|Ability.DOMAIN_DECEPTIVE;}
	public String lastID="";
	public int craftType(){return Ability.ACODE_SPELL;}
	public int usageType(){return USAGE_MOVEMENT;}

	public Hashtable immitations=new Hashtable();
	public String[] lastOnes=new String[2];

	public void executeMsg(Environmental myHost, CMMsg msg)
	{
		super.executeMsg(myHost,msg);
		if((myHost==null)||(!(myHost instanceof MOB)))
		   return;
		MOB mob=(MOB)myHost;
		if(msg.tool()!=null)
		{
			if((msg.amISource(mob))
			&&((msg.tool().ID().equals("Skill_Spellcraft"))
				||(msg.tool().ID().equals("Skill_Songcraft"))
				||(msg.tool().ID().equals("Skill_Chantcraft"))
				||(msg.tool().ID().equals("Skill_Prayercraft")))
			&&(msg.tool().text().equals(lastOnes[0]))
			&&(msg.tool().text().length()>0)
			&&(!immitations.containsKey(msg.tool().text())))
			{
				Ability A=CMClass.getAbility(msg.tool().text());
				if(A!=null)	immitations.put(A.name(),lastOnes[1]);
			}
			else
			if((msg.tool() instanceof Ability)
			&&(!msg.amISource(mob))
			&&(msg.othersMessage()!=null))
			{
				lastOnes[0]=msg.tool().ID();
				lastOnes[1]=msg.othersMessage();
			}
		}

	}

	public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel)
	{
		Environmental target=null;
		if(commands.size()>1)
		{
			target=mob.location().fetchFromRoomFavorMOBs(null,(String)commands.lastElement(),Wearable.FILTER_ANY);
			if(target==null) target=mob.fetchInventory(null,(String)commands.lastElement());
			if(target!=null) commands.removeElementAt(commands.size()-1);
		}
		String cmd=(commands.size()>0)?CMParms.combine(commands,0).toUpperCase():"";
		StringBuffer str=new StringBuffer("");
		String found=null;
		for(Enumeration e=immitations.keys();e.hasMoreElements();)
		{
			String key=(String)e.nextElement();
			if((cmd.length()>0)&&(key.toUpperCase().startsWith(cmd)))
				found=key;
			str.append(key+" ");
		}
		if((cmd.length()==0)||(found==null))
		{
			if(found!=null) mob.tell("'"+cmd+"' is not something you know how to imitate.");
			mob.tell("Spells/Skills you may imitate: "+str.toString()+".");
			return true;
		}
		if(target==null) target=mob.getVictim();
		if(target==null) target=mob;

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_NOISYMOVEMENT|CMMsg.MASK_DELICATE|(auto?CMMsg.MASK_ALWAYS:0),(String)immitations.get(found));
			if(mob.location().okMessage(mob,msg))
				mob.location().send(mob,msg);
		}
		else
			return beneficialVisualFizzle(mob,null,"<S-NAME> attempt(s) to imitate "+found+", but fail(s).");

		return success;
	}
}

redpajama_set_name: RedPajamaGithub


text:
% Utilities for GSMsim
%
% Authors: Arne Norre Ekstroem and Jan Hvolgaard Mikkelsen
%
% These are the files in this directory, along with a brief
% introduction of the files. Refer to the individual files or the
% printed documentation for further details.
%
% inter_pos      - Script for calculating, and saving a GSM interleaving
%                  table.
% make_deinterleave_m
%                - As the name indicates, this tiny matlab script does
%                  construction of the deinterleave.m-function.
% make_interleave_m
%                - As the name indicates, this tiny matlab script does
%                  construction of the interleave.m-function.
%
% $Id: Contents.m,v 1.2 1997/11/12 11:35:22 aneks Exp $


text:
This page lists the API changes that occurred between the 0.4.x release and the 0.5.0 release. If you find that something was missed, please add it below.

## Node Creation
Node creation no longer takes a callback. This was changed to not give the appearance that the function is async. It returns immediately. This also simplifies code as you don't need to keep creating functions to use the new nodes.

Where you would previously do:

    doc.node('root', function(node) {
        node.node('child', function(child) {
        });
    });

You should now do:

    var root = doc.node('root');
    var child = root.node('child');

## Attributes
The attribute constructor no longer exists. To create an attribute just call the 'attr' method on a node. The constructor method was more verbose and error prone.

Old way

    var a = new libxmljs.Attribute(node, attr_name, attr_value);

New Way

    node.attr(attr_name, attr_value);

You can also pass an object to attr of key-value pairs to set multiple attributes.

## Sax Parsers

Sax parser is an event emitter. You can connect to all of the events after creating a sax parser using the typical event emitter api.

You can now do:

    var parser = new SaxPushParser();
    parser.on('startDocument', function() ... );

Sax parser constructor no longer takes a function to configure but instead an object which lists the callbacks.

Before you would do:

    var parser = new SaxPushParser(function(cb) {
        cb.onStartDocument(function() ... );
    });

You should now do (or better use the event emitter interface, see above):

    var parser = new SaxPushParser({
        startDocument: function() ...
    });

Or you can use the parser as an event emitter as described previously.

## Removed API

_parseHtmlFile_ and _parseXmlFile_ have been removed. Likewise, _SaxParser.parseFile_ has also been removed. If you want to read a file, use the nodejs file module instead.


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

function auth_success(req, response){
    window.location.href = ".";
}

function auth_error(req, error){

    var status = error.error.http_status;

    switch (status){
        case 401:
            $("#one_error").hide();
            $("#auth_error").fadeIn("slow");
            break;
        case 500:
            $("#auth_error").hide();
            $("#one_error").fadeIn("slow");
            break;
    }
}

function authenticate(){
    var username = $("#username").val();
    var password = $("#password").val();
    var remember = $("#check_remember").is(":checked");

    oZones.Auth.login({ data: {username: username
                                    , password: password}
                            , remember: remember
                            , success: auth_success
                            , error: auth_error
                        });
}

$(document).ready(function(){
    $("#login_form").submit(function (){
        authenticate();
        return false;
    });

    //compact login elements according to screen height
    if (screen.height <= 600){
        $('div#logo_sunstone').css("top","15px");
        $('div#login').css("top","10px");
        $('.error_message').css("top","10px");
    };

    $("input#username.box").focus();
});


text:
var mongoose = require('../../../app').mongoose;

var CreditScheme = new mongoose.Schema({
    credit : Number,
    percent: Number,
    setBy  : String,
    firmCode:String
});

module.exports = mongoose.model('credits', CreditScheme);


text:
@interface UIScrollView (SYRefresh)
@property(nonatomic,strong)SYRefreshView *sy_header;
@property(nonatomic,strong)SYRefreshView *sy_footer;
@end


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('corpus', '0013_auto_20150217_0053'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='message',
            name='topics',
        ),
        migrations.DeleteModel(
            name='Topic',
        ),
    ]


text:
use mouros::CVoid;
use mouros::tasks;
use mouros::tasks::CriticalLock;
use mouros::pool_alloc::Pool;

use mouros::mailbox;
use mouros::mailbox::Mailbox;
use mouros::mailbox::{RxChannelSpsc, TxChannelSpsc};

use crate::bindings::message_dispatcher as md;

use crate::bsp::i2c;

use core::ptr;
use core::mem;
use core::slice;

use core::convert::TryFrom;
use core::fmt::Write;

mod bmp085;
mod tsl2651;

#[derive(Copy, Clone)]
struct StdResponsePayload {
    channel: u32,
    value: f32,
}

#[allow(dead_code)]
union MessagePayload {
    channel_num_payload: u32,
    std_response: StdResponsePayload,
}

const GET_TEMPERATURE_MSG_ID: u32 = 0;
const GET_PRESSURE_MSG_ID: u32 = 1;
const GET_HUMIDITY_MSG_ID: u32 = 2;
const GET_LIGHT_LEVEL_MSG_ID: u32 = 3;

const TEMPERATURE_REPLY_MSG_ID: u32 = 4;
const PRESSURE_REPLY_MSG_ID: u32 = 5;
const HUMIDITY_REPLY_MSG_ID: u32 = 6;
const LIGHT_LEVEL_REPLY_MSG_ID: u32 = 7;

#[repr(i32)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum MeteoError {
    I2CCommError = -1,
    TxQueueFullError = -2,
    InvalidMsgError = -3,
    MsgCreationError = -4,
    SensorNotReadyError = -5,
    InvalidSensorData = -6,
}

static mut MESSAGE_ARR: Option<[md::message; 20]> = None;
static mut MESSAGE_POOL: Option<CriticalLock<Pool<md::message>>> = None;

static mut MESSAGE_PAYLOAD_ARR: Option<[MessagePayload; 20]> = None;
static mut MESSAGE_PAYLOAD_POOL: Option<CriticalLock<Pool<MessagePayload>>> = None;

unsafe extern "C" fn meteo_alloc(msg_type_id: u32) -> *mut md::message {
    let msg_pool = MESSAGE_POOL.as_ref().expect("message pool not initialized");
    let payload_pool = MESSAGE_PAYLOAD_POOL
        .as_ref()
        .expect("message payload pool not initialized");

    match msg_type_id {
        GET_TEMPERATURE_MSG_ID
        | GET_PRESSURE_MSG_ID
        | GET_HUMIDITY_MSG_ID
        | GET_LIGHT_LEVEL_MSG_ID
        | TEMPERATURE_REPLY_MSG_ID
        | PRESSURE_REPLY_MSG_ID
        | HUMIDITY_REPLY_MSG_ID
        | LIGHT_LEVEL_REPLY_MSG_ID => {
            let m = msg_pool.lock().take().and_then(|m| {
                if let Some(payload) = payload_pool.lock().take() {
                    *m = mem::zeroed();
                    *payload = mem::zeroed();

                    m.msg_type = msg_type_id;
                    m.data = payload as *mut MessagePayload as *mut CVoid;

                    Some(m)
                } else {
                    meteo_free(m);
                    None
                }
            });

            m.unwrap_or(&mut *ptr::null_mut())
        }
        _ => ptr::null_mut(),
    }
}

unsafe extern "C" fn meteo_free(msg: *mut md::message) {
    if msg.is_null() {
        return;
    }

    let msg_pool = MESSAGE_POOL.as_ref().expect("message pool not initialized");
    let payload_pool = MESSAGE_PAYLOAD_POOL
        .as_ref()
        .expect("message payload pool not initialized");

    match (*msg).msg_type {
        GET_TEMPERATURE_MSG_ID
        | GET_PRESSURE_MSG_ID
        | GET_HUMIDITY_MSG_ID
        | GET_LIGHT_LEVEL_MSG_ID
        | TEMPERATURE_REPLY_MSG_ID
        | PRESSURE_REPLY_MSG_ID
        | HUMIDITY_REPLY_MSG_ID
        | LIGHT_LEVEL_REPLY_MSG_ID => {
            if !(*msg).data.is_null() {
                payload_pool
                    .lock()
                    .give(&mut *((*msg).data as *mut MessagePayload));
            }
            msg_pool.lock().give(&mut *msg);
        }
        _ => {}
    }
}

unsafe extern "C" fn single_channel_num_parse(
    msg_ptr: *mut md::message,
    save_ptr: *mut u8,
) -> bool {
    if msg_ptr.is_null() || (*msg_ptr).data.is_null() || save_ptr.is_null() {
        return false;
    }

    let payload = unwrap_or_ret_false!(md::cstr_ptr_to_str_slice(save_ptr));
    let ch = unwrap_or_ret_false!(payload.parse::<u32>());

    let msg_data = (*msg_ptr).data as *mut MessagePayload;
    (*msg_data).channel_num_payload = ch;

    true
}

unsafe extern "C" fn std_response_serialize(
    msg_ptr: *const md::message,
    output_str: *mut u8,
    output_str_max_len: u32,
) -> isize {
    if msg_ptr.is_null() || (*msg_ptr).data.is_null() {
        return -1;
    }

    let buf = slice::from_raw_parts_mut(output_str, output_str_max_len as usize);
    let mut w = md::CStrWriter::new(buf);

    let payload = &*((*msg_ptr).data as *const StdResponsePayload);

    if write!(w, ",{},{}", payload.channel, payload.value).is_ok() {
        w.len() as isize
    } else {
        -1
    }
}

enum IncomingMsg<'payload> {
    GetTemperature(&'payload u32),
    GetPressure(&'payload u32),
    GetHumidity(&'payload u32),
    GetLightLevel(&'payload u32),
}

derive_message_wrapper!(IncomingMsg<'payload>, [
    GET_TEMPERATURE_MSG_ID => (|payload_ptr| {
        Ok(IncomingMsg::GetTemperature(&*(payload_ptr as *const u32)))
    }),
    GET_PRESSURE_MSG_ID => (|payload_ptr| {
        Ok(IncomingMsg::GetPressure(&*(payload_ptr as *const u32)))
    }),
    GET_HUMIDITY_MSG_ID => (|payload_ptr| {
        Ok(IncomingMsg::GetHumidity(&*(payload_ptr as *const u32)))
    }),
    GET_LIGHT_LEVEL_MSG_ID => (|payload_ptr| {
        Ok(IncomingMsg::GetLightLevel(&*(payload_ptr as *const u32)))
    })],
    meteo_alloc,
    meteo_free);

struct TemperatureReply<'payload>(&'payload mut u32, &'payload mut f32);

derive_message_wrapper!(TemperatureReply<'payload>,
    TEMPERATURE_REPLY_MSG_ID => (|payload_ptr| {
            let payload = &mut *(payload_ptr as *mut StdResponsePayload);
            Ok(TemperatureReply(&mut payload.channel, &mut payload.value))
    }),
    meteo_alloc,
    meteo_free);

struct PressureReply<'payload>(&'payload mut u32, &'payload mut f32);

derive_message_wrapper!(PressureReply<'payload>,
    PRESSURE_REPLY_MSG_ID => (|payload_ptr| {
            let payload = &mut *(payload_ptr as *mut StdResponsePayload);
            Ok(PressureReply(&mut payload.channel, &mut payload.value))
    }),
    meteo_alloc,
    meteo_free);

struct HumidityReply<'payload>(&'payload mut u32, &'payload mut f32);

derive_message_wrapper!(HumidityReply<'payload>,
    HUMIDITY_REPLY_MSG_ID => (|payload_ptr| {
            let payload = &mut *(payload_ptr as *mut StdResponsePayload);
            Ok(HumidityReply(&mut payload.channel, &mut payload.value))
    }),
    meteo_alloc,
    meteo_free);

struct LightLevelReply<'payload>(&'payload mut u32, &'payload mut f32);

derive_message_wrapper!(LightLevelReply<'payload>,
    LIGHT_LEVEL_REPLY_MSG_ID => (|payload_ptr| {
            let payload = &mut *(payload_ptr as *mut StdResponsePayload);
            Ok(LightLevelReply(&mut payload.channel, &mut payload.value))
    }),
    meteo_alloc,
    meteo_free);

static mut RX_QUEUE_ARR: Option<[*mut md::message; 20]> = None;
static mut RX_QUEUE: Option<Mailbox<*mut md::message>> = None;

static mut TX_QUEUE_ARR: Option<[*mut md::message; 20]> = None;
static mut TX_QUEUE: Option<Mailbox<*mut md::message>> = None;

static mut ERR_QUEUE_ARR: Option<[i32; 20]> = None;
static mut ERR_QUEUE: Option<Mailbox<i32>> = None;

static mut MSG_HANDLERS: Option<[md::message_handler; 8]> = None;
static mut MSG_CONF: Option<md::subsystem_message_conf> = None;

struct MeteoTaskCtx<'mb, 'mem: 'mb> {
    rx_msg_queue: RxChannelSpsc<'mb, 'mem, *mut md::message>,
    tx_msg_queue: TxChannelSpsc<'mb, 'mem, *mut md::message>,
    err_msg_queue: TxChannelSpsc<'mb, 'mem, i32>,
    press_sensor: bmp085::Bmp085,
    light_sensor: tsl2651::Tsl2561,
}

impl<'mb, 'mem> MeteoTaskCtx<'mb, 'mem> {
    fn send_msg<T>(&self, msg: md::MessageWrapper<T>) -> Result<(), MeteoError>
    where
        T: md::Wrappable,
    {
        self.tx_msg_queue.try_send(msg.into()).or_else(|err| {
            T::free(err.0);
            Err(MeteoError::TxQueueFullError)
        })
    }

    fn send_err(&self, err: MeteoError) {
        let _ = self.err_msg_queue.try_send(err as i32);
    }
}

static mut METEO_CTX: Option<MeteoTaskCtx> = None;

#[no_mangle]
pub unsafe extern "C" fn rust_meteo_init() -> *const CVoid {
    if METEO_CTX.is_some() {
        panic!("Meteo module already initialized.");
    }

    RX_QUEUE_ARR = Some(mem::zeroed());
    RX_QUEUE = Some(Mailbox::new(RX_QUEUE_ARR.as_mut().unwrap().as_mut()));

    TX_QUEUE_ARR = Some(mem::zeroed());
    TX_QUEUE = Some(Mailbox::new(TX_QUEUE_ARR.as_mut().unwrap().as_mut()));

    ERR_QUEUE_ARR = Some(mem::zeroed());
    ERR_QUEUE = Some(Mailbox::new(ERR_QUEUE_ARR.as_mut().unwrap().as_mut()));

    MESSAGE_ARR = Some(mem::zeroed());
    MESSAGE_POOL = Some(CriticalLock::new(Pool::new(
        MESSAGE_ARR.as_mut().unwrap().as_mut(),
    )));

    MESSAGE_PAYLOAD_ARR = Some(mem::zeroed());
    MESSAGE_PAYLOAD_POOL = Some(CriticalLock::new(Pool::new(
        MESSAGE_PAYLOAD_ARR.as_mut().unwrap().as_mut(),
    )));

    let (rx_msg_queue, _) = mailbox::channel_spsc(RX_QUEUE.as_mut().unwrap());
    let (_, tx_msg_queue) = mailbox::channel_spsc(TX_QUEUE.as_mut().unwrap());
    let (_, err_msg_queue) = mailbox::channel_spsc(ERR_QUEUE.as_mut().unwrap());

    MSG_HANDLERS = Some([
        md::message_handler {
            message_name: b"GET_TEMPERATURE\0" as *const u8,
            parsing_func: Some(single_channel_num_parse),
            serialization_func: None,
        },
        md::message_handler {
            message_name: b"GET_PRESSURE\0" as *const u8,
            parsing_func: Some(single_channel_num_parse),
            serialization_func: None,
        },
        md::message_handler {
            message_name: b"GET_HUMIDITY\0" as *const u8,
            parsing_func: Some(single_channel_num_parse),
            serialization_func: None,
        },
        md::message_handler {
            message_name: b"GET_LIGHT_LEVEL\0" as *const u8,
            parsing_func: Some(single_channel_num_parse),
            serialization_func: None,
        },
        md::message_handler {
            message_name: b"TEMPERATURE_REPLY\0" as *const u8,
            parsing_func: None,
            serialization_func: Some(std_response_serialize),
        },
        md::message_handler {
            message_name: b"PRESSURE_REPLY\0" as *const u8,
            parsing_func: None,
            serialization_func: Some(std_response_serialize),
        },
        md::message_handler {
            message_name: b"HUMIDITY_REPLY\0" as *const u8,
            parsing_func: None,
            serialization_func: Some(std_response_serialize),
        },
        md::message_handler {
            message_name: b"LIGHT_LEVEL_REPLY\0" as *const u8,
            parsing_func: None,
            serialization_func: Some(std_response_serialize),
        },
    ]);

    MSG_CONF = Some(md::subsystem_message_conf {
        subsystem_name: b"METEO\0" as *const u8,
        message_handlers: MSG_HANDLERS.as_ref().unwrap() as *const md::message_handler,
        num_message_types: MSG_HANDLERS.as_ref().unwrap().len() as u32,
        incoming_msg_queue: rx_msg_queue.get_raw_mailbox(),
        outgoing_msg_queue: tx_msg_queue.get_raw_mailbox(),
        outgoing_err_queue: err_msg_queue.get_raw_mailbox(),
        alloc_message: Some(meteo_alloc),
        free_message: Some(meteo_free),
    });

    md::dispatcher_register_subsystem(MSG_CONF.as_mut().unwrap());

    let mut press_sensor = bmp085::Bmp085::new(i2c::Peripheral::I2C3);
    press_sensor.set_precision(bmp085::Precision::UltraHigh);

    let light_sensor = tsl2651::Tsl2561::new(i2c::Peripheral::I2C3);

    METEO_CTX = Some(MeteoTaskCtx {
        rx_msg_queue,
        tx_msg_queue,
        err_msg_queue,
        press_sensor,
        light_sensor,
    });

    METEO_CTX.as_ref().unwrap() as *const MeteoTaskCtx as *const CVoid
}

fn process_msg(ctx: &mut MeteoTaskCtx, msg: md::MessageWrapper<IncomingMsg>) {
    let res = match *msg {
        IncomingMsg::GetTemperature(ch) => ctx.press_sensor.measure().and_then(|(t, _)| {
            md::MessageWrapper::new(msg.get_transaction_id(), TEMPERATURE_REPLY_MSG_ID)
                .map_err(|_| MeteoError::MsgCreationError)
                .and_then(|mut reply: md::MessageWrapper<TemperatureReply>| {
                    *reply.0 = *ch;
                    *reply.1 = t;

                    ctx.send_msg(reply)
                })
        }),
        IncomingMsg::GetPressure(ch) => ctx.press_sensor.measure().and_then(|(_, p)| {
            md::MessageWrapper::new(msg.get_transaction_id(), PRESSURE_REPLY_MSG_ID)
                .map_err(|_| MeteoError::MsgCreationError)
                .and_then(|mut reply: md::MessageWrapper<PressureReply>| {
                    *reply.0 = *ch;
                    *reply.1 = p;

                    ctx.send_msg(reply)
                })
        }),
        IncomingMsg::GetHumidity(ch) => {
            md::MessageWrapper::new(msg.get_transaction_id(), HUMIDITY_REPLY_MSG_ID)
                .map_err(|_| MeteoError::MsgCreationError)
                .and_then(|mut reply: md::MessageWrapper<HumidityReply>| {
                    *reply.0 = *ch;
                    *reply.1 = 0.0;

                    ctx.send_msg(reply)
                })
        }
        IncomingMsg::GetLightLevel(ch) => ctx.light_sensor
            .measure()
            .and_then(|level| {
                md::MessageWrapper::new(msg.get_transaction_id(), LIGHT_LEVEL_REPLY_MSG_ID)
                    .map_err(|_| MeteoError::MsgCreationError)
                    .and_then(|mut reply: md::MessageWrapper<LightLevelReply>| {
                        *reply.0 = *ch;
                        *reply.1 = level;

                        ctx.send_msg(reply)
                    })
            })
            .or_else(|err| {
                if err == MeteoError::SensorNotReadyError {
                    let _ = ctx.light_sensor.set_gain_and_integ_time(
                        tsl2651::Gain::Gain1x,
                        tsl2651::IntegrationTime::Time101ms,
                    );
                    let _ = ctx.light_sensor.set_state(tsl2651::State::On);
                }

                Err(err)
            }),
    };

    if let Err(e) = res {
        ctx.send_err(e);
    }
}

#[no_mangle]
pub extern "C" fn rust_meteo_comm_loop(ctx_raw: *mut CVoid) {
    let ctx = unsafe { &mut *(ctx_raw as *mut MeteoTaskCtx) };

    if let Ok(msg_ptr) = ctx.rx_msg_queue.try_recv() {
        if let Ok(msg) = md::MessageWrapper::try_from(msg_ptr) {
            process_msg(ctx, msg);
        } else {
            ctx.send_err(MeteoError::InvalidMsgError);
        }
    }

    tasks::sleep(50);
}


text:
#include <linux/pci.h>
#include <asm/io.h>
#include <asm/cayman.h>

void __iomem *ioport_map(unsigned long port, unsigned int len)
{
	if (port < 0x400)
		return (void __iomem *)((port << 2) | smsc_superio_virt);

	return (void __iomem *)port;
}


text:
using namespace otc;

char testSingleCharLabelPoly(const TestHarness &);
char testWordLabelPoly(const TestHarness &);
char testBifurcating(const TestHarness &);
char testMonotypic(const TestHarness &);
char testUnderscores(const TestHarness &);
char testWhitespaceHandling(const TestHarness &);
char testQuotedWordLabelPoly(const TestHarness &);
char testCommentPoly(const TestHarness &);
char testBranchLengths(const TestHarness &);
char testUnbalanced(const TestHarness &);
char testUnbalancedToManyClose(const TestHarness &);
char testEmptyClade(const TestHarness &);
char testEmptySib(const TestHarness &);
char testEmptyBranchLength(const TestHarness &);
char genericTokenTest(const TestHarness &th, const std::string &fn, const std::vector<std::string> & expected);
char genericOTCParsingErrorTest(const TestHarness &th, const std::string &fn);

char genericTokenTest(const TestHarness &th, const std::string &fn, const std::vector<std::string> & expected){
    std::ifstream inp;
    if (!th.openTestFile(fn, inp)) {
        return 'U';
    }
    std::vector<std::string> obtained;
    ConstStrPtr filenamePtr = ConstStrPtr(new std::string(th.getFilePath(fn)));
    FilePosStruct pos(filenamePtr);
    NewickTokenizer tokenizer(inp, pos);
    for (const auto & token : tokenizer) {
        obtained.push_back(token.content());
    }
    if (testVecElementEquality(expected, obtained)) {
        return '.';
    }
    return 'F';
}

char genericOTCParsingErrorTest(const TestHarness &th, const std::string &fn) {
    std::ifstream inp;
    if (!th.openTestFile(fn, inp)) {
        return 'U';
    }
    ConstStrPtr filenamePtr = ConstStrPtr(new std::string(th.getFilePath(fn)));
    FilePosStruct pos(filenamePtr);
    NewickTokenizer tokenizer(inp, pos);
    try {
        for (const auto & token : tokenizer) {
            assert(token.content().c_str());
        }
    } catch (const OTCParsingError &) {
        return '.';
    }
    std::cerr << "No OTCParsingError was raised!\n";
    return 'F';
}

char testSingleCharLabelPoly(const TestHarness &th) {
    const std::vector<std::string> expected = {"(", "A", ",", "B", ",", "C", ")", ";"};
    return genericTokenTest(th, "noids-abcnewick.tre", expected);
}

char testWordLabelPoly(const TestHarness &th) {
    const std::vector<std::string> expected = {"(", "AB", ",", "BC", ",", "CD", ")", ";"};
    return genericTokenTest(th, "noids-wordspolytomy.tre", expected);
}
char testBifurcating(const TestHarness &th) {
    const std::vector<std::string> expected = {"(", "AB",
                                                ",",
                                                    "(",
                                                        "(", "BC",
                                                             ",", "EF",
                                                        ")",
                                                         ",",
                                                         "CD",
                                                     ")",
                                                ")", ";"};
    return genericTokenTest(th, "noids-bifurcating.tre", expected);
}
char testMonotypic(const TestHarness &th) {
    const std::vector<std::string> expected = {"(", "(", "AB", ")",
                                                ",",
                                                    "(", "(",
                                                        "(", "(", "BC", ")",
                                                             ",", "EF",
                                                        ")",
                                                         ",",
                                                         "CD",
                                                     ")",")",
                                                ")", ";"};
    return genericTokenTest(th, "noids-monotypic.tre", expected);
}

char testBranchLengths(const TestHarness &th) {
    const std::vector<std::string> expected = {"(", "AB", ":", "0.1",
                                               ",", "BC", ":", "2",
                                               ",", "CD", ":", "7E-8",
                                               ",", "(",
                                                    "E 'H", ":", "75.246",
                                                    ",", "\'", ":", "7.315E-20",
                                               ")", "label for 5", ":", "5",
                                                ")", "some label", ":", "3", ";"};
    return genericTokenTest(th, "noids-branchlengths.tre", expected);
}

char testQuotedWordLabelPoly(const TestHarness &th) {
    const std::vector<std::string> expected = {"(", "AB",
                                               ",", "BC",
                                               ",", "CD",
                                               ",", "E \'H",
                                               ",", "\'",
                                               ")", ";"};
    return genericTokenTest(th, "noids-quotedwordspolytomy.tre", expected);
}

char testCommentPoly(const TestHarness &th) {
    const std::vector<std::string> expected = {"(", "AB", ",", "BC", ",", "CD", ")", ";"};
    return genericTokenTest(th, "noids-polytomywithcomments.tre", expected);
}
char testUnderscores(const TestHarness &th) {
    const std::vector<std::string> expected = {"(", "A B", ",", "B C", ",", "C_D", ")", ";"};
    return genericTokenTest(th, "noids-underscorehandling.tre", expected);
}
char testWhitespaceHandling(const TestHarness &th) {
    const std::vector<std::string> expected = {"(", "A B",
                                               ",", "B C",
                                               ",", "C_D",
                                               ",", "EX FZ", //warn but tolerate unquoted..
                                               ",", "G HY", //warn but normalize unquoted..
                                               ",", "I J", //warn but normalize unquoted even with newlines, I guess...
                                               ",", "Aembedded quoteJ", // ugh. I'll allowit
                                               ")", ";"};
    return genericTokenTest(th, "noids-whitespacehandling.tre", expected);
}
char testUnbalanced(const TestHarness &th) {
    return genericOTCParsingErrorTest(th, "noids-unbalanced.tre");
}
char testUnbalancedToManyClose(const TestHarness &th) {
    return genericOTCParsingErrorTest(th, "noids-unbalancedtoomanyclosed.tre");
}
char testEmptyClade(const TestHarness &th) {
    char r = '.';
    for (const auto & i : {"1", "2", "3", "4"} ) {
        std::string fn = "noids-emptyclade";
        fn += i;
        fn += ".tre";
        auto c = genericOTCParsingErrorTest(th, fn);
        if (c != '.') {
            r = c;
        }
    }
    return r;
}
char testEmptySib(const TestHarness &th) {
    char r = '.';
    for (const auto & i : {"1", "2", "3", "4"} ) {
        std::string fn = "noids-emptysib";
        fn += i;
        fn += ".tre";
        auto c = genericOTCParsingErrorTest(th, fn);
        if (c != '.') {
            r = c;
        }
    }
    return r;
}
char testEmptyBranchLength(const TestHarness &th) {
    char r = '.';
    for (const auto & i : {"1", "2", "3", "4", "5"} ) {
        std::string fn = "noids-emptybranchlength";
        fn += i;
        fn += ".tre";
        auto c = genericOTCParsingErrorTest(th, fn);
        if (c != '.') {
            r = c;
        }
    }
    return r;
}

int main(int argc, char *argv[]) {
    TestHarness th(argc, argv);
    TestsVec tests{TestFn("testSingleCharLabelPoly", testSingleCharLabelPoly)
                   , TestFn("testWordLabelPoly", testWordLabelPoly)
                   , TestFn("testBifurcating", testBifurcating)
                   , TestFn("testMonotypic", testMonotypic)
                   , TestFn("testUnderscores", testUnderscores)
                   , TestFn("testQuotedWordLabelPoly", testQuotedWordLabelPoly)
                   , TestFn("testCommentPoly", testCommentPoly)
                   , TestFn("testUnbalanced", testUnbalanced)
                   , TestFn("testUnbalancedToManyClose", testUnbalancedToManyClose)
                   , TestFn("testWhitespaceHandling", testWhitespaceHandling)
                   , TestFn("testBranchLengths", testBranchLengths)
                   , TestFn("testEmptyClade", testEmptyClade)
                   , TestFn("testEmptySib", testEmptySib)
                   , TestFn("testEmptyBranchLength", testEmptyBranchLength)

                  };
    return th.runTests(tests);
}


text:
<ion-item >

{{task.title}}

Due: {{task.dueDate | date}}

</ion-item>


text:
package net.jiyuu_ni.seiidex.jpa;

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;

/**
 * The persistent class for the item_flags database table.
 *
 */
@Entity
@Table(name="item_flags")
@NamedQuery(name="ItemFlag.findAll", query="SELECT i FROM ItemFlag i")
public class ItemFlag implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	private int id;

	private String identifier;

	//bi-directional many-to-many association to Item
	@ManyToMany
	@JoinTable(
		name="item_flag_map"
		, joinColumns={
			@JoinColumn(name="item_flag_id")
			}
		, inverseJoinColumns={
			@JoinColumn(name="item_id")
			}
		)
	private List<Item> items;

	//bi-directional many-to-one association to ItemFlagProse
	@OneToMany(mappedBy="itemFlag")
	private List<ItemFlagProse> itemFlagProses;

	public ItemFlag() {
	}

	public int getId() {
		return this.id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getIdentifier() {
		return this.identifier;
	}

	public void setIdentifier(String identifier) {
		this.identifier = identifier;
	}

	public List<Item> getItems() {
		return this.items;
	}

	public void setItems(List<Item> items) {
		this.items = items;
	}

	public List<ItemFlagProse> getItemFlagProses() {
		return this.itemFlagProses;
	}

	public void setItemFlagProses(List<ItemFlagProse> itemFlagProses) {
		this.itemFlagProses = itemFlagProses;
	}

	public ItemFlagProse addItemFlagPros(ItemFlagProse itemFlagPros) {
		getItemFlagProses().add(itemFlagPros);
		itemFlagPros.setItemFlag(this);

		return itemFlagPros;
	}

	public ItemFlagProse removeItemFlagPros(ItemFlagProse itemFlagPros) {
		getItemFlagProses().remove(itemFlagPros);
		itemFlagPros.setItemFlag(null);

		return itemFlagPros;
	}

}


text:
<?php
/**
 * Site index template.
 *
 * @package Born_Again
 * @since Born Again 1.0
 */
  get_header();

  if (have_posts()) {
    while (have_posts()) {
      the_post();
      get_template_part('_includes/content', get_post_type());
    }
  }

  get_sidebar();
  get_footer();


text:
<?php

/**
 * opTimeline
 *
 * @package    OpenPNE
 * @subpackage opTimelinePlugin
 */

class opTimeline
{

  /**
   * @var opTimelineUser
   */
  private $user;

  private $imageContentSize;
  private $baseUrl;

  public function __construct(opTimelineUser $user, array $params)
  {
    $this->user = $user;

    $this->imageContentSize = $params['image_size'];
    $this->baseUrl = $params['base_url'];
  }

  const COMMENT_DISPLAY_MAX = 10;
  const MINIMUM_IMAGE_WIDTH = 285;

  public function addPublicFlagByActivityDataForSearchAPIByActivityData(array $responseDataList, $activityDataList)
  {
    $publicFlags = array();
    foreach ($activityDataList as $activity)
    {
      $publicFlags[$activity->getId()] = $activity->getPublicFlag();
    }

    $publicStatusTextList = array(
        ActivityDataTable::PUBLIC_FLAG_OPEN => 'open',
        ActivityDataTable::PUBLIC_FLAG_SNS => 'sns',
        ActivityDataTable::PUBLIC_FLAG_FRIEND => 'friend',
        ActivityDataTable::PUBLIC_FLAG_PRIVATE => 'private'
    );

    foreach ($responseDataList as &$data)
    {
      $publicFlag = $publicFlags[$data['id']];
      $data['public_status'] = $publicStatusTextList[$publicFlag];
    }
    unset($data);

    return $responseDataList;
  }

  /**
   * メソッドを実行する前にopJsonApiをロードしておく必要がある
   */
  public function createActivityDataByActivityDataAndViewerMemberIdForSearchAPI($activityDataList, $viewerMemberId)
  {
    $activityIds = array();
    foreach ($activityDataList as $activity)
    {
      $activityIds[] = $activity->getId();
    }

    if (empty($activityIds))
    {
      return array();
    }

    $replyActivityDataList = $this->findReplyActivityDataByActivityIdsGroupByActivityId($activityIds);

    $memberIds = $this->extractionMemberIdByActivityDataAndReplyActivityDataRows(
                    $activityDataList, $replyActivityDataList);
    $memberDataList = $this->user->createMemberDataByViewerMemberIdAndMemberIdsForAPIResponse($viewerMemberId, $memberIds);

    $responseDataList = $this->createActivityDataByActivityDataAndMemberDataForSearchAPI($activityDataList, $memberDataList);

    foreach ($responseDataList as &$response)
    {
      $id = $response['id'];

      if (isset($replyActivityDataList[$id]))
      {
        $replies = $replyActivityDataList[$id];

        $response['replies'] = $this->createActivityDataByActivityDataRowsAndMemberDataForSearchAPI($replies['data'], $memberDataList);
        $response['replies_count'] = $replies['count'];
      }
      else
      {
        $response['replies'] = null;
        $response['replies_count'] = 0;
      }
      $response['body'] = htmlspecialchars($response['body'], ENT_QUOTES, 'UTF-8', false);
      $response['body_html'] = htmlspecialchars($response['body_html'], ENT_QUOTES, 'UTF-8', false);
    }
    unset($response);

    return $responseDataList;
  }

  private function extractionMemberIdByActivityDataAndReplyActivityDataRows($activities, $replyActivitiyRows)
  {
    $memberIds = array();
    foreach ($activities as $activity)
    {
      $memberIds[] = $activity->getMemberId();
    }

    foreach ($replyActivitiyRows as $activityDataList)
    {
      foreach ($activityDataList['data'] as $activityData)
      {
        $memberIds[] = $activityData['member_id'];
      }
    }

    $memberIds = array_unique($memberIds);

    return $memberIds;
  }

  private function createActivityDataByActivityDataAndMemberDataForSearchAPI($activityDataList, $memberData)
  {
    $activityIds = array();
    foreach ($activityDataList as $activity)
    {
      $activityIds[] = $activity->getId();
    }

    $activityImageUrls = $this->findActivityImageUrlsByActivityIds($activityIds);

    $responseDataList = array();
    foreach ($activityDataList as $activity)
    {
      if (isset($activityImageUrls[$activity->getId()]))
      {
        //@todo symfonyの形式に変更させる
        //$activityImageUrl = sf_image_path($activityImageUrls[$activity->getId()], array(), true);

        $activityImageUrl = $activityImageUrls[$activity->getId()];
      }
      else
      {
        $activityImageUrl = null;
      }

      $imageUrls = $this->getImageUrlInfoByImageUrl($activityImageUrl);

      $responseData['id'] = $activity->getId();
      $responseData['member'] = $memberData[$activity->getMemberId()];

      $responseData['body'] = preg_replace('/
/', '<br />', $activity->getBody());
      $responseData['body_html'] = op_activity_linkification(nl2br(op_api_force_escape($responseData['body'])));
      $responseData['uri'] = $activity->getUri();
      $responseData['source'] = $activity->getSource();
      $responseData['source_uri'] = $activity->getSourceUri();

      $responseData['image_url'] = $imageUrls['small'];
      $responseData['image_large_url'] = $imageUrls['large'];
      $responseData['created_at'] = date('r', strtotime($activity->getCreatedAt()));

      $responseDataList[] = $responseData;
    }

    return $responseDataList;
  }

  private function getImageUrlInfoByImageUrl($imageUrl)
  {
    if (is_null($imageUrl))
    {
      return array(
        'large' => null,
        'small' => null,
      );
    }

    $imagePath = $this->convertImageUrlToImagePath($imageUrl);

    if (!file_exists($imagePath))
    {
      return array(
        'large' => opTimelineImage::getNotImageUrl(),
        'small' => opTimelineImage::getNotImageUrl(),
      );
    }

    $minimumDirPath = opTimelineImage::findUploadDirPath($imagePath, self::MINIMUM_IMAGE_WIDTH);
    $imageName = pathinfo($imagePath, PATHINFO_BASENAME);
    $minimumImagePath = $minimumDirPath.'/'.$imageName;

    if (!file_exists($minimumImagePath))
    {
      return array(
        'large' => $imageUrl,
        'small' => $imageUrl,
      );
    }

    $minimumImageUrl = str_replace(sfConfig::get('sf_web_dir'), $this->baseUrl, $minimumImagePath);

    return array(
      'large' => $imageUrl,
      'small' => $minimumImageUrl,
    );
  }

  private function convertImageUrlToImagePath($imageUrl)
  {
    $match = array();
    preg_match("/(https?:\/\/.*)(\/cache)/", $imageUrl, $match);

    return str_replace($match[1], sfConfig::get('sf_web_dir'), $imageUrl);
  }

  private function createActivityDataByActivityDataRowsAndMemberDataForSearchAPI($activityDataRows, $memberDataList)
  {

    $responseDataList = array();
    foreach ($activityDataRows as $row)
    {
      $responseData['id'] = $row['id'];
      $responseData['member'] = $memberDataList[$row['member_id']];

      $responseData['body'] = htmlspecialchars($row['body'], ENT_QUOTES, 'UTF-8', false);
      $responseData['body_html'] = op_activity_linkification(nl2br(htmlspecialchars($row['body'], ENT_QUOTES, 'UTF-8', false)));
      $responseData['uri'] = $row['uri'];
      $responseData['source'] = $row['source'];
      $responseData['source_uri'] = $row['source_uri'];

      //コメントでは画像を投稿できない
      $responseData['image_url'] = null;
      $responseData['image_large_url'] = null;
      $responseData['created_at'] = date('r', strtotime($row['created_at']));

      $responseDataList[] = $responseData;
    }

    return $responseDataList;
  }

  public function findReplyActivityDataByActivityIdsGroupByActivityId(array $activityIds)
  {
    static $queryCacheHash;

    if (!$queryCacheHash)
    {
      $q = Doctrine_Query::create();
      $q->from('ActivityData');
      $q->whereIn('in_reply_to_activity_id', $activityIds);
      $q->orderBy('in_reply_to_activity_id, created_at DESC');
      $searchResult = $q->fetchArray();

      $queryCacheHash = $q->calculateQueryCacheHash();
    }
    else
    {
      $q->setCachedQueryCacheHash($queryCacheHash);
      $searchResult = $q->fetchArray();
    }

    $replies = array();
    foreach ($searchResult as $row)
    {
      $targetId = $row['in_reply_to_activity_id'];

      if (!isset($replies[$targetId]['data']) || count($replies[$targetId]['data']) < self::COMMENT_DISPLAY_MAX)
      {
        $replies[$targetId]['data'][] = $row;
      }

      if (isset($replies[$targetId]['count']))
      {
        $replies[$targetId]['count']++;
      }
      else
      {
        $replies[$targetId]['count'] = 1;
      }
    }

    return $replies;
  }

  public function searchActivityDataByAPIRequestDataAndMemberId($requestDataList, $memberId)
  {
    $builder = opActivityQueryBuilder::create()
                    ->setViewerId($memberId);

    if (isset($requestDataList['target']))
    {
      if ('friend' === $requestDataList['target'])
      {
        $builder->includeFriends($requestDataList['target_id'] ? $requestDataList['target_id'] : null);
      }

      if ('community' === $requestDataList['target'])
      {
        $builder
                ->includeSelf()
                ->includeFriends()
                ->includeSns()
                ->setCommunityId($requestDataList['target_id']);
      }
    }
    else
    {
      if (isset($requestDataList['member_id']))
      {
        $builder->includeMember($requestDataList['member_id']);
      }
      else
      {
        $builder
                ->includeSns()
                ->includeFriends()
                ->includeSelf();
      }
    }

    $query = $builder->buildQuery();

    if (isset($requestDataList['keyword']))
    {
      $query->andWhereLike('body', $requestDataList['keyword']);
    }

    $globalAPILimit = sfConfig::get('op_json_api_limit', 20);
    if (isset($requestDataList['count']) && (int) $requestDataList['count'] < $globalAPILimit)
    {
      $query->limit($requestDataList['count']);
    }
    else
    {
      $query->limit($globalAPILimit);
    }

    if (isset($requestDataList['max_id']))
    {
      $query->addWhere('id <= ?', $requestDataList['max_id']);
    }

    if (isset($requestDataList['since_id']))
    {
      $query->addWhere('id > ?', $requestDataList['since_id']);
    }

    if (isset($requestDataList['activity_id']))
    {
      $query->addWhere('id = ?', $requestDataList['activity_id']);
    }

    $query->andWhere('in_reply_to_activity_id IS NULL');

    return $query->execute();
  }

  public function findActivityImageUrlsByActivityIds(array $actvityIds)
  {
    $query = new opDoctrineQuery();
    $query->select('activity_data_id, uri');
    $query->from('ActivityImage');
    $query->andWhereIn('activity_data_id', $actvityIds);

    $searchResult = $query->fetchArray();

    $imageUrls = array();
    foreach ($searchResult as $row)
    {
      $imageUrls[$row['activity_data_id']] = $row['uri'];
    }

    return $imageUrls;
  }

  public function embedImageUrlToContentForSearchAPI(array $responseDataList)
  {
    $imageUrls = array();
    foreach ($responseDataList as $row)
    {
      if (!is_null($row['image_url']))
      {
        if ('large' === $this->imageContentSize)
        {
          $imageUrls[$row['id']] = $row['image_large_url'];
        }
        else
        {
          $imageUrls[$row['id']] = $row['image_url'];
        }
      }
    }

    foreach ($responseDataList as &$data)
    {
      $id = $data['id'];

      if (isset($imageUrls[$id]))
      {
        $data['body'] = $data['body'].' '.$imageUrls[$id];
        $data['body_html'] = $data['body_html'].'

';
      }
    }

    return $responseDataList;
  }

  public function createPostActivityFromAPIByApiDataAndMemberId($apiData, $memberId)
  {
    $body = (string) $apiData['body'];

    $options = array();

    if (isset($apiData['public_flag']))
    {
      $options['public_flag'] = $apiData['public_flag'];
    }

    if (isset($apiData['in_reply_to_activity_id']))
    {
      $options['in_reply_to_activity_id'] = $apiData['in_reply_to_activity_id'];
    }

    if (isset($apiData['uri']))
    {
      $options['uri'] = $apiData['uri'];
    }
    elseif (isset($apiData['url']))
    {
      $options['uri'] = $apiData['url'];
    }

    if (isset($apiData['target']) && 'community' === $apiData['target'])
    {
      $options['foreign_table'] = 'community';
      $options['foreign_id'] = $apiData['target_id'];
    }

    $options['source'] = 'API';

    return Doctrine::getTable('ActivityData')->updateActivity($memberId, $body, $options);
  }

  public function createActivityImageByFileInfoAndActivityId(array $fileInfo, $activityId)
  {
    $file = new File();
    $file->setOriginalFilename(basename($fileInfo['name']));
    $file->setType($fileInfo['type']);

    $fileFormat = $file->getImageFormat();
    if (is_null($fileFormat) || '' == $fileFormat)
    {
      $fileFormat = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
    }

    $fileBaseName = md5(time()).'_'.$fileFormat;
    $filename = 'ac_'.$fileInfo['member_id'].'_'.$fileBaseName;

    $file->setName($filename);
    $file->setFilesize($fileInfo['size']);
    $bin = new FileBin();
    $bin->setBin($fileInfo['binary']);
    $file->setFileBin($bin);
    $file->save();

    $activityImage = new ActivityImage();
    $activityImage->setActivityDataId($activityId);
    $activityImage->setFileId($file->getId());
    $activityImage->setUri($this->getActivityImageUriByfileInfoAndFilename($fileInfo, $filename));
    $activityImage->setMimeType($file->type);
    $activityImage->save();

    $this->createUploadImageFileByFileInfoAndSaveFileName($fileInfo, $filename);

    return $activityImage;
  }

  private function getActivityImageUriByfileInfoAndFilename($fileInfo, $filename)
  {
    //ファイルテーブルの名前だと拡張式がついていない
    $filename = opTimelineImage::addExtensionToBasenameForFileTable($filename);
    $uploadPath = opTimelineImage::findUploadDirPath($filename);
    $uploadBasePath = str_replace(sfConfig::get('sf_web_dir'), '', $uploadPath);

    return $fileInfo['web_base_path'].$uploadBasePath.'/'.$filename;
  }

  private function createUploadImageFileByFileInfoAndSaveFileName($fileInfo, $filename)
  {
    $filename = opTimelineImage::addExtensionToBasenameForFileTable($filename);
    $uploadDirPath = opTimelineImage::findUploadDirPath($fileInfo['name']);

    $fileSavePath = $uploadDirPath.'/'.$filename;

    opTimelineImage::copyByResourcePathAndTargetPath($fileInfo['tmp_name'], $fileSavePath);

    $imageSize = opTimelineImage::getImageSizeByPath($fileSavePath);
    //画像が縮小サイズより小さい場合は縮小した画像を作成しない
    if ($imageSize['width'] <= self::MINIMUM_IMAGE_WIDTH)
    {
      return true;
    }

    $minimumDirPath = opTimelineImage::findUploadDirPath($fileInfo['name'], self::MINIMUM_IMAGE_WIDTH);
    $minimumPath = $minimumDirPath.'/'.basename($fileSavePath);

    $paths = array(
        'resource' => $fileSavePath,
        'target' => $minimumPath,
    );

    opTimelineImage::createMinimumImageByWidthSizeAndPaths(self::MINIMUM_IMAGE_WIDTH, $paths);
  }

  public static function getViewPhoto()
  {
    $viewPhoto = Doctrine::getTable('SnsConfig')->get('op_timeline_plugin_view_photo', false);
    if (false !== $viewPhoto)
    {
      return $viewPhoto;
    }
    return 1;
  }
}


text:
using System.Globalization;
using Xunit;

namespace System.Drawing.PrimitivesTest
{
    public class RectangleTests
    {
        [Fact]
        public void DefaultConstructorTest()
        {
            Assert.Equal(Rectangle.Empty, new Rectangle());
        }

        [Theory]
        [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)]
        [InlineData(int.MaxValue, 0, int.MinValue, 0)]
        [InlineData(0, 0, 0, 0)]
        [InlineData(0, int.MinValue, 0, int.MaxValue)]
        public void NonDefaultConstructorTest(int x, int y, int width, int height)
        {
            Rectangle rect1 = new Rectangle(x, y, width, height);
            Rectangle rect2 = new Rectangle(new Point(x, y), new Size(width, height));

            Assert.Equal(rect1, rect2);
        }

        [Theory]
        [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)]
        [InlineData(int.MaxValue, 0, int.MinValue, 0)]
        [InlineData(0, 0, 0, 0)]
        [InlineData(0, int.MinValue, 0, int.MaxValue)]
        public void FromLTRBTest(int left, int top, int right, int bottom)
        {
            Rectangle rect1 = new Rectangle(left, top, right - left, bottom - top);
            Rectangle rect2 = Rectangle.FromLTRB(left, top, right, bottom);

            Assert.Equal(rect1, rect2);
        }

        [Fact]
        public void EmptyTest()
        {
            Assert.True(Rectangle.Empty.IsEmpty);
            Assert.True(new Rectangle(0, 0, 0, 0).IsEmpty);
            Assert.True(new Rectangle().IsEmpty);
        }

        [Theory]
        [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)]
        [InlineData(int.MaxValue, 0, int.MinValue, 0)]
        [InlineData(int.MinValue, int.MaxValue, int.MinValue, int.MaxValue)]
        [InlineData(0, int.MinValue, 0, int.MaxValue)]
        public void NonEmptyTest(int x, int y, int width, int height)
        {
            Assert.False(new Rectangle(x, y, width, height).IsEmpty);
        }

        [Theory]
        [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)]
        [InlineData(int.MaxValue, 0, int.MinValue, 0)]
        [InlineData(0, 0, 0, 0)]
        [InlineData(0, int.MinValue, 0, int.MaxValue)]
        [InlineData(int.MinValue, int.MaxValue, int.MinValue, int.MaxValue)]
        public void DimensionsTest(int x, int y, int width, int height)
        {
            Rectangle rect = new Rectangle(x, y, width, height);
            Assert.Equal(new Point(x, y), rect.Location);
            Assert.Equal(new Size(width, height), rect.Size);

            Assert.Equal(x, rect.X);
            Assert.Equal(y, rect.Y);
            Assert.Equal(width, rect.Width);
            Assert.Equal(height, rect.Height);
            Assert.Equal(x, rect.Left);
            Assert.Equal(y, rect.Top);
            Assert.Equal(x + width, rect.Right);
            Assert.Equal(y + height, rect.Bottom);

            Point p = new Point(width, height);
            Size s = new Size(x, y);
            rect.Location = p;
            rect.Size = s;

            Assert.Equal(p, rect.Location);
            Assert.Equal(s, rect.Size);

            Assert.Equal(width, rect.X);
            Assert.Equal(height, rect.Y);
            Assert.Equal(x, rect.Width);
            Assert.Equal(y, rect.Height);
            Assert.Equal(width, rect.Left);
            Assert.Equal(height, rect.Top);
            Assert.Equal(x + width, rect.Right);
            Assert.Equal(y + height, rect.Bottom);
        }

        [Theory]
        [InlineData(int.MaxValue, int.MinValue, int.MaxValue, int.MinValue)]
        [InlineData(int.MaxValue, 0, int.MinValue, 0)]
        [InlineData(0, int.MinValue, 0, int.MaxValue)]
        [InlineData(int.MinValue, int.MaxValue, int.MinValue, int.MaxValue)]
        public void EqualityTest(int x, int y, int width, int height)
        {
            Rectangle rect1 = new Rectangle(x, y, width, height);
            Rectangle rect2 = new Rectangle(width/2, height/2, x, y);

            Assert.True(rect1 != rect2);
            Assert.False(rect1 == rect2);
            Assert.False(rect1.Equals(rect2));
        }

        [Theory]
        [InlineData(float.MaxValue, float.MinValue, float.MaxValue, float.MinValue)]
        [InlineData(float.MinValue, float.MaxValue, float.MinValue, float.MaxValue)]
        [InlineData(0, 0, 0, 0)]
        public void RectangleFConversionTest(float x, float y, float width, float height)
        {
            RectangleF rect = new RectangleF(x, y, width, height);
            Rectangle rCeiling = new Rectangle((int)Math.Ceiling(x), (int)Math.Ceiling(y),
                (int)Math.Ceiling(width), (int)Math.Ceiling(height));
            Rectangle rTruncate = new Rectangle((int)x, (int)y, (int)width, (int)height);
            Rectangle rRound = new Rectangle((int)Math.Round(x), (int)Math.Round(y),
                (int)Math.Round(width), (int)Math.Round(height));

            Assert.Equal(rCeiling, Rectangle.Ceiling(rect));
            Assert.Equal(rTruncate, Rectangle.Truncate(rect));
            Assert.Equal(rRound, Rectangle.Round(rect));
        }

        [Theory]
        [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)]
        [InlineData(0, int.MinValue, int.MaxValue, 0)]
        public void ContainsTest(int x, int y, int width, int height)
        {
            Rectangle rect = new Rectangle(2*x-width, 2*y-height, width, height);
            Point p = new Point(x, y);
            Rectangle r = new Rectangle(x, y, width / 2, height / 2);

            Assert.False(rect.Contains(x, y));
            Assert.False(rect.Contains(p));
            Assert.False(rect.Contains(r));
        }

        [Theory]
        [InlineData(0, 0, 0, 0)]
        [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)]
        [InlineData(0, int.MinValue, int.MaxValue, 0)]
        public void InflateTest(int x, int y, int width, int height)
        {
            Rectangle rect = new Rectangle(x, y, width, height);
            Rectangle inflatedRect = new Rectangle(x - width, y - height, width + 2 * width, height + 2 * height);

            rect.Inflate(width, height);
            Assert.Equal(inflatedRect, rect);

            Size s = new Size(x, y);
            inflatedRect = new Rectangle(rect.X - x, rect.Y - y, rect.Width + 2 * x, rect.Height + 2 * y);

            rect.Inflate(s);
            Assert.Equal(inflatedRect, rect);
        }

        [Theory]
        [InlineData(0, 0, 0, 0)]
        [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)]
        [InlineData(0, int.MinValue, int.MaxValue, 0)]
        public void IntersectTest(int x, int y, int width, int height)
        {
            Rectangle rect = new Rectangle(x, y, width, height);
            Rectangle expectedRect = Rectangle.Intersect(rect, rect);
            rect.Intersect(rect);
            Assert.Equal(expectedRect, rect);
            Assert.False(rect.IntersectsWith(expectedRect));
        }

        [Theory]
        [InlineData(0, 0, 0, 0)]
        [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)]
        [InlineData(int.MaxValue, 0, 0, int.MaxValue)]
        [InlineData(0, int.MinValue, int.MaxValue, 0)]
        public void UnionTest(int x, int y, int width, int height)
        {
            Rectangle a = new Rectangle(x, y, width, height);
            Rectangle b = new Rectangle(width, height, x, y);

            int x1 = Math.Min(a.X, b.X);
            int x2 = Math.Max(a.X + a.Width, b.X + b.Width);
            int y1 = Math.Min(a.Y, b.Y);
            int y2 = Math.Max(a.Y + a.Height, b.Y + b.Height);

            Rectangle expectedRectangle = new Rectangle(x1, y1, x2 - x1, y2 - y1);

            Assert.Equal(expectedRectangle, Rectangle.Union(a, b));
        }

        [Theory]
        [InlineData(0, 0, 0, 0)]
        [InlineData(int.MaxValue, int.MinValue, int.MinValue, int.MaxValue)]
        [InlineData(int.MaxValue, 0, 0, int.MaxValue)]
        [InlineData(0, int.MinValue, int.MaxValue, 0)]
        public void OffsetTest(int x, int y, int width, int height)
        {
            Rectangle r1 = new Rectangle(x, y, width, height);
            Rectangle expectedRect = new Rectangle(x + width, y + height, width, height);
            Point p = new Point(width, height);

            r1.Offset(p);
            Assert.Equal(expectedRect, r1);

            expectedRect.Offset(p);
            r1.Offset(width, height);
            Assert.Equal(expectedRect, r1);
        }

        [Fact]
        public void ToStringTest()
        {
            string expected = "{X=0,Y=0,Width=0,Height=0}";
            Assert.Equal(expected, Rectangle.Empty.ToString());
        }
    }
}


text:
'''
jeeves.py
----------
Robot to suggest outfit based on the weather
    - Variables
    - Conditionals
----------
Python Demo Workshop, March 22nd 2017
'''
#### Declaring variables in Python
# Good news: No need to lock variable to a type!
# Bad news: No real implementation of constant variable types...

# Integer Data Type
LOW_THRESHOLD = 35
HIGH_THRESHOLD = 80
JACKET_THRESHOLD = 40
SHORTS_THRESHOLD = 65

print('It is your robots first day on the job, so please introduce yourself: ')

# Declare and initialize a variable from user input
# String Data Type
name = raw_input('> ')

print('Great! He will be with you now..')

# Format print statement with name as paramater
print('Good day {0}'.format(name)) # Will place name in first position (zero indexed)
print('My name is Jeeves, your personal robot butler. Shall we settle on an outfit for today?')

# Get current weather temperature and condition
temp = raw_input('Now what is the temperature outside today?\n > ')
temp = int(temp) # IMPORTANT: raw_input returns a string, need to type cast to an int

condition = raw_input('Now would you say it is clear, cloudy, or overcast?\n > ')

# Error Checking on condition
condition = condition.lower() # For the purposes of comparison
if condition != 'clear' and condition != 'cloudy' and condition != 'overcast':
    print('You are being ridiculous..\nI shall not work with someone with such rude manner!')

    exit(1) # !! IF WE GOT HERE WE MESSED UP !! *#

### Branch to determine what outfit to wear

# Report on current temperature
if temp > HIGH_THRESHOLD:
    print('Goodness me it is hot today!')

elif temp < LOW_THRESHOLD:
    print('Sounds like a cold day outside, better bundle up!')

else:
    print('Seems like a moderate day today')

# Decide on what to wear based on weather condition
# Boolean Data Type
good_weather = True

if condition != 'clear':
    good_weather = False

if good_weather: # Will execute if good_weather == True
    if temp >= SHORTS_THRESHOLD:
        print('Fabulous news! It is nice enough outside to wear shorts! Rock a clean tee and get outside!')

    elif temp <= JACKET_THRESHOLD:
        print('Better bundle up, if you have to go outside definitely bring a jacket')

    else:
        print('Your call, remember jeans and a sweater bring it together')

else: # Executes on good_weather == False
    if temp >= SHORTS_THRESHOLD:
        print('Tough spot...try wearing dri fit shorts with a light rain jacket')

    elif temp <= JACKET_THRESHOLD:
        print('Gonna be a tough go. Definitely go with a jacket, hat, and boots if need be')

    else:
        print('Try the layered look. Lightweight sweater under a rain jacket')

print('Hope you have a great day {0}!!!'.format(name))

'''
-- BONUS --
Obviously, having to enter your name every single time you run this
program is woefully ineffecient.

-> Try having the program save your name the first time you enter it
(say into a text file) and in subsequent uses just read the name
from the file

Working with files in Python: http://pymbook.readthedocs.io/en/latest/file.html

HINT: You can use a conditional to see if the name has been
recorded already. If so, read the name from the file. Else...
'''


text:
title: American Wants To Work
layout: default
modal-id: 11
date: 2014-07-10
img: american.jpg
thumbnail: american.jpg
alt: image-alt
project-date: April 2014
<!-- client: Start Bootstrap -->
category: Web Development
website: http://www.americawantstowork.org

---


text:
require 'regaliator/endpoint'

module Regaliator
  module V15
    class Transaction < Endpoint
      def list(params = {})
        request('/transactions', params).post
      end

      def pay(params = {})
        request('/transaction/pay', params).post
      end

      def reverse(params = {})
        request('/transaction/reverse', params).post
      end

      def cancel(params = {})
        request('/transaction/cancel', params).post
      end
    end
  end
end


text:
layout: post
title: "Bem-vindo ao Canvas #2"
image: "/assets/bem-vindo-canvas/cover2.jpg"
date:   2017-01-14 08:00:00 -0200
color_template: "canvas"
tags: html5 canvas javascript
resume: "Não podemos nos ater somente as formas, existem muitas coisas que podemos fazer no nosso palco. E hoje iremos falar das transformações. ;)"
topic: canvas
comments: true
---

Introdução

Fala pessoal, venho informar que é um prazer estar com vocês novamente, e que esse é o segundo post da série "Bem-vindo ao canvas", pra quem não viu o primeiro é só vir aqui. Lembrando que a intenção dessa série em 3 posts é nos introduzir aos princípios do canvas, e no final fazer um efeito de particulas muito maneiro.

Nesse post iremos falar sobre as principais transformações matriciais(translação, rotação e escala). No final novamente irá surgir algum desenho interesssante(eu acho), sem mais, vamos ao que interessa.

Se você não faz idéia do que é o canvas, no primeiro post tem uma explicação bem resumida dessa ótima ferramenta do HTML5.

Antes de tudo

Precismos da nossa tag <canvas></canvas> e inicializar nosso contexto

	index.html

<style>
   *{padding:0;margin:0;}
   // esse position é só ter uma barra de rolagem
   // overflow: hidden no body tb é blz XD
   #mycanvas{position:fixed;}
</style>
...
<canvas id="mycanvas" width="150" height="150"></canvas>
...

	index.js

window.onload = draw;

function draw(){
   // Obtendo nosso nó de referencia
   var canvas = document.getElementById("mycanvas");
   // ajustar as dimensões para ocupar a página inteira
   canvas.width = window.innerWidth;
   canvas.height = window.innerHeight;

   // inicializando o contexto em 2 dimensões
   var context = canvas.getContext("2d");
}

Continuamos usando as formas

Infelizmente, aprender algo novo não cancela algo antigo, pelo menos não nesse caso, aqui precisaremos usar os "caminhos"(paths), para demonstrar o que iremos fazer.

Como o desenho desse post ficará um pouco mais complexo, vamos abraçar toda a nossa peça em um objeto.

Mãos a obra, vamos fazer nosso desenho.

   index.js

window.onload = draw;

function draw(){
   var canvas = document.getElementById("mycanvas");
   canvas.width = window.innerWidth;
   canvas.height = window.innerHeight;

   // retiramos o contexto dessa função
   // e transferimos para o objeto sky
   sky.paint(canvas);
}

var sky = {
   canvas:null,
   ctx:null,
   paint:function(canvas){
      // setar as configurações iniciais
      this.canvas = canvas;
      // atribuindo o contexto a uma variavel
      // no nosso objeto
      this.ctx = this.canvas.getContext("2d");

      // vamos simplificar nosso código e usar
      // funções especificas para cada parte
      // do nosso desenho
      this.drawSky();
   },
   drawSky:function(){
      // função responsável por desenhar nosso céu
      // (oh really?)
      this.ctx.fillStyle = "#0c1644"; // fillStyle para escolher a cor
                                      // de preenchimento do nosso fundo

      // aqui o céu é desenhado para ocupar
      // o palco inteiro
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
   }
}

Até ai show, nada de novo a não ser o fillStyle, que não é nada tão complicado de entender, ele é semelhante ao strokeStyle, mas vai cuidar da cor do preenchimento das nossas formas.

Transformações

Consegui pensar em um exemplo muito legal, nós iremos em uma função, pra desenhar uma unica forma utilizar 3 das 4 transformações possíveis, rotação, translação e escala.

Infelizmente não da pra pular a parte teórica chatona, não para mim, então pra não confundir tudo, irei primeiro falar sobre cada transformação separadamente, e por fim vamos ao exemplo utilizando as 3

Translação

A transformação de translação, é realizada quando você quer mudar a posição de um objeto, demonstrado acima.

No nosso caso do canvas, nós não conseguimos criar objetos inteiros e move-los de forma sólida para outro ponto, dessa maneira, a transformação de translação no canvas serve para mudar a origem do nosso palco, demonstrado abaixo, e a partir dali iremos desenhar a forma que planejavamos translocar.

A função responsavel por isso no canvas é a .translate(x, y).

Escala

Como demonstrado na figura acima, a transformação de escala, é nada mais do que aumentar algum eixo proporcionalmente ao valor passado, lembrando que a escala inicial/padrão é sempre (1, 1), sendo assim na imagem vemos que a figura foi diminuida pela metade(ou 1/2 = 0.5), se quisesse dobrar o tamanho do desenho ele teria usado (2, 2).

A função que iremos utilizar será .scale(x, y).

Fato interessante: nós podemos espelhar nosso canvas utilizando uma transformação negativa (-1, 1), (1, -1) ou (-1, -1)

   espelhado.js

...
   // caso apliquemos
   context.scale(1, -1);
   // nosso sistema de coordenadas ficará
   // com a origem em baixo esquerda, como
   // um tradicional plano cartersiano :D
...

Rotação

Rotação a última das transformações mais utilizadas, ela também pode ser considerada a mais simples, responsável apenas por rotacionar um objeto no sentido horário.

Novamente, no canvas não controlamos as formas, só controlamos o palco, sendo assim o que acontece é que o nosso palco será rotacionado no sentido horário como demonstrado abaixo.

Utilizaremos .rotate(angulo) para aplicar essa transformação.

muito importante

Todas as transformações que fazemos no nosso contexto ficam salvas, então sempre é necessão chamar um .save() e .restore(), antes e depois de aplicar as transformações.

   indicado_fazer.js

...
   context.save(); // salvo o estado atual
   // faz as transformações
   context.restore(); // retorna ao estado salvo
...

Exemplo

Visto isso, vamos à continuação do nosso desenho.

   index.js

window.onload = draw;

function draw(){ ... } // o código é o mesmo de lá de cima
                       // só omiti ele para não ficar
                       // ocupando mt espaço na área de code

var sky = {
   canvas:null,
   ctx:null,
   paint:function(canvas){
      this.canvas = canvas;
      this.ctx = this.canvas.getContext("2d");

      this.drawSky();

      // manda desenhar a estrela do nosso céu
      this.drawStar();
   },
   drawSky:function(){ ... },
   drawStar:function(){
      // primeira coisa sempre é salvar o estado atual
      this.ctx.save();

      // nossa primeira transformação, mudamos a origem
      // para 100px distante em x e y
      this.ctx.translate(100, 100);

      // definindo o tamanho da nossa estrela
      // aqui definimos qual será a escala da nossa estrela
      // de 0 até 1.5
      var escala = Math.random()*1.5;
      // nossa segunda transformação, alteramos o tamanho
      // da escala para o valor da variavel calculada acima
      this.ctx.scale(escala, escala);

      // aqui definimos a distancia das pontas das nossas estrelas
      var raioMax = 20;
      // e aqui a distancia minima das nossas pontas
      var raioMin = 8;

      // iniciamos nosso caminho
      this.ctx.beginPath();

      // aplicamos uma rotação aleatória para a
      // estrela ficar um pouco inclinada
      this.ctx.rotate(Math.random());

      // movemos nossa ponta da caneta para a ponta mais distance
      this.ctx.moveTo(raioMax, 0);

      // e aqui vem o for do desenho que fica fazendo uma linha
      // para ponta distante e a interna
      for(var i = 0; i < 10; i++){
         // a cada loop nós adicionamos pi/5 a rotação anterior
         // isso ocorre porque não chamamos o método .restore()
         // se tivessemos chamado ele toda vez fariamos uma
         // linha na mesma direção.
         this.ctx.rotate(Math.PI/5);

         // condicional simples para verificar se é para desenhar
         // para a ponta externa ou para a interna
         if(i%2 == 0){
            this.ctx.lineTo(raioMin, 0)
         }else{
            this.ctx.lineTo(raioMax, 0)
         }
      }

      // fechar o caminho, MUITO IMPORTANTE
      this.ctx.closePath();

      // escolher a cor do preenchimento da nossa estrela
      this.ctx.fillStyle = "white";
      // preencher
      this.ctx.fill();

      // e retornar ao estado anterior, assim não atrapalharemos
      // nenhum desenho feito por outra função
      this.ctx.restore();
   }
}

Deixando interessante

Na introdução do post eu prometi que surgiria alguma coisa legal, até o momento só tem uma estrela no meio de um troço azul.

Pra deixar interessante vamos direto ao código, bora encher esse céu de estrelas.

   index.js

window.onload = draw;

function draw(){ ... }

var sky = {
   quantStars:70, // aqui setamos quantas estrelas queremos
                  // no nosso céu
   canvas:null,
   ctx:null,
   paint:function(canvas){
      this.canvas = canvas;
      this.ctx = this.canvas.getContext("2d");

      this.drawSky();

      this.populateSky(); // vamos popular o céu com estrelas !
   },
   drawSky:function(){ ... },
   populateSky:function(){
      // um loop simples que cuida de criar as
      // nossas estrelas
      for(var i=0; i < this.quantStars; i++;){
         // a estrela vai ser gerada em algum lugar aleatório
         // sem ultrapassar o tamanho da tela
         this.drawStar(Math.random()*this.canvas.width,
                       Math.random()*this.canvas.height);
      }
   },
   drawStar:function(posX, posY){ // só fizemos essa alteração aqui
      this.ctx.save();

      // pra poder criar a estrela no local que passarmos como parametro
      this.ctx.translate(posX, posY);

      var escala = Math.random()*1.5;
      this.ctx.scale(escala, escala);

      var raioMax = 20;
      var raioMin = 8;

      this.ctx.beginPath();
      this.ctx.rotate(Math.random());
      this.ctx.moveTo(raioMax, 0);
      for(var i = 0; i < 10; i++){
         this.ctx.rotate(Math.PI/5);
         if(i%2 == 0){
            this.ctx.lineTo(raioMin, 0)
         }else{
            this.ctx.lineTo(raioMax, 0)
         }
      }

      this.ctx.closePath();

      this.ctx.fillStyle = "white";
      this.ctx.fill();

      this.ctx.restore();
   }
}

Seguidos todos os passos corretamente, você provavelmente teve um resultado idêntico a esse !(só ta mudando toda vez que você recarrega a página :p)

See the Pen Céu estrelado by Matheus Mesquita (@mathmesquita) on CodePen.

Conclusão

Wow, esse post acabou conseguindo ser maior que o outro!! :O Mas é isso aí galera, conforme vai aumentando a complexidade os posts vão ficando maiores, esse talvez foi mais divertido que o outro pois teve um resultado que ja começa a traçar uma linha para o que queremos de particulas(se você mudar a estrela pra um circulo você acabou de gerar as particulas).

A série continua semana que vem(chegando ao seu final :[ ), mas relaxe que ja estou planejando mais coisas para brincar com o canvas !! Quem sabe uma série de canvas avançado ? ou fazendo um jogo na unha ? Enfim !!! muitas idéias e por hoje paramos aqui.

Qualquer dúvida, sugestão, elogio, xingamento convite para uma conversa, estarei nos comentários !! Espero que tenham gostado e até a próxima. õ7

Último post ja está disponível !


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

		<link rel="stylesheet" type="text/css" href="./stylesheets/blog-stylesheet.css">
		<title>PYu06 - Technical Blog</title>

The Enumerable#Map

Oct 12 '14

The Enumerable#map method takes the form: array.map{ |item| block }. Calling this method will create a new array that will do the code block to each item in the array.

A good time to use the .map method is when you want to create a new array after doing a block of code to the original array. Think of it as iterating each element and outputting into a new array.

For example:

	[1,2,3,4].map { |x| x*2 }
	# => [2,4,6,8]

Archive

Home


text:
export class Model {
    user: string;
    items: TodoItem[];

    constructor() {
        this.user = "Adam";
        this.items = [
            new TodoItem("Buy Flowers", false),
            new TodoItem("Get Shoes", false),
            new TodoItem("Collect Tickets", false),
            new TodoItem("Call Joe", false)
        ]
    }
}

export class TodoItem {
    action: string;
    done: boolean;

    constructor(action: string, done: boolean) {
        this.action = action;
        this.done = done;
    }
}


text:
using System;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Support.V4.App;

namespace Producer.Droid
{
	public static class NotificationExtensions
	{
		public static void InitNotificationChannels (this Context context)
		{
			if (Build.VERSION.SdkInt < BuildVersionCodes.O)
			{
				return;
			}

			//var notificationManager = NotificationManagerCompat.From (Context);

			var notificationManager = (NotificationManager) context.GetSystemService (Context.NotificationService);
			// The id of the channel.
			String id = NotificationChannels.ContentPublished.Id;
			// The user-visible name of the channel.
			var name = NotificationChannels.ContentPublished.Name;
			// The user-visible description of the channel.
			var description = NotificationChannels.ContentPublished.Description;

			var channel = new NotificationChannel (id, name, NotificationImportance.High);
			// Configure the notification channel.
			channel.Description = description;
			channel.EnableLights (true);
			// Sets the notification light color for notifications posted to this
			// channel, if the device supports this feature.
			channel.LightColor = Color.Red;
			channel.EnableVibration (true);
			channel.SetVibrationPattern (new long [] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });

			notificationManager.CreateNotificationChannel (channel);
		}

		public static Notification.Builder GetChannelNotification (this Context context, string channel, string title, string body)
		{
			//NotificationCompat.Builder 2 param constructor not available yet :(

			return new Notification.Builder (context, channel)
					.SetContentTitle (title)
					.SetContentText (body)
					.SetSmallIcon (Android.Resource.Drawable.StatNotifyMore)
					.SetAutoCancel (true);
		}

		public static NotificationCompat.Builder GetNotification (this Context context, string title, string body)
		{
			//NotificationCompat.Builder 2 param constructor not available yet :(

			return new NotificationCompat.Builder (context)
					.SetContentTitle (title)
					.SetContentText (body)
					.SetSmallIcon (Android.Resource.Drawable.StatNotifyMore)
					.SetAutoCancel (true);
		}

		public static Notification.Builder SetLaunchActivity (this Notification.Builder builder, Type activityType)
		{
			var intent = new Intent (Application.Context, activityType);
			//intent.putExtra (...); // add some extras here
			var pendingIntent = PendingIntent.GetActivity (Application.Context, builder.GetHashCode (), intent, PendingIntentFlags.UpdateCurrent);
			builder.SetContentIntent (pendingIntent);

			return builder;
		}

		public static NotificationCompat.Builder SetLaunchActivity (this NotificationCompat.Builder builder, Type activityType)
		{
			var intent = new Intent (Application.Context, activityType);
			//intent.putExtra (...); // add some extras here
			var pendingIntent = PendingIntent.GetActivity (Application.Context, builder.GetHashCode (), intent, PendingIntentFlags.UpdateCurrent);
			builder.SetContentIntent (pendingIntent);

			return builder;
		}

		public static void Send (this Notification.Builder builder)
		{
			var notification = builder.Build ();
			//var notificationId = Convert.ToInt32 (DateTime.Now.Ticks); //meh?  how unique does this need to be?

			//we want to use the same thing here we passed as request id, above
			var notificationId = builder.GetHashCode ();

			NotificationManagerCompat notificationManager = NotificationManagerCompat.From (Application.Context);
			notificationManager.Notify (notificationId, notification);
		}

		public static void Send (this NotificationCompat.Builder builder)
		{
			var notification = builder.Build ();
			//var notificationId = Convert.ToInt32 (DateTime.Now.Ticks); //meh?  how unique does this need to be?

			//we want to use the same thing here we passed as request id, above
			var notificationId = builder.GetHashCode ();

			NotificationManagerCompat notificationManager = NotificationManagerCompat.From (Application.Context);
			notificationManager.Notify (notificationId, notification);
		}
	}
}


text:
/**
 @file
 @author  Nicholas Gillian <ngillian@media.mit.edu>
 @version 1.0

 @brief The FFT class computes the Fourier transform of an N dimensional signal using a Fast Fourier Transform algorithm.

 The FFT class computes N independent FFTs, one for each dimension in the input signal.
 The FFT is computed using the previous M samples input to the FFT instance, where M is equal to the FFT Window Size parameter,
 which is set by the user when they initialize the FFT.
 The FFT Window Size parameter must be a power of two (16,32,64,128,256,512,1024,2048,4096,etc.). Note that, because of the symmetries
 within the FFT computation, the results of an FFT will be half the FFT Window Size. This means that if you create an FFT with a Window Size
 of 256, the resulting vectors that you will get (such as the magnitude and phase) will each have 128 elements in them.

 For each N dimensional input signal, the FFT will output:
 - An M dimensional vector containing the magnitude of each frequency component
 - An M dimensional vector containing the phase of each frequency component
 where M is equal to the FFTWindowSize / 2 . These values will be concatenated into one vector, in the order of
 { [magnitude dimension 1] [phase dimension 1] [magnitude dimension 2] [phase dimension 2] ... [magnitude dimension N] [phase dimension N] }.
 The size of this concatenated output vector will therefore be equal to N * M * 2 - where N is the number of input dimensions to the FFT, M is the FFTWindowSize/2,
 and 2 represents the magnitude and phase vectors. If you only really need the magnitude or phase of a signal, as opposed to both, then you can turn off the computation
 and concatenation of the element you do not need to save unnecessary computations and memory copies, this can either be done in the FFT's constructor or by using the
 setComputeMagnitude(bool computeMagnitude) and setComputePhase(bool computePhase) functions.

 @example FeatureExtractionModules/FFTExample/FFTExample.cpp
 */

/**
 GRT MIT License
 Copyright (c) <2012> <Nicholas Gillian, Media Lab, MIT>

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial
 portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
 LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef GRT_FFT_HEADER
#define GRT_FFT_HEADER

#include "../../CoreModules/FeatureExtraction.h"
#include "FastFourierTransform.h"

namespace GRT{

class FFT : public FeatureExtraction
{
public:
    /**
     Constructor, sets the fftWindowSize, hopSize, fftWindowFunction, if the magnitude and phase should be computed during the FFT and the number
     of dimensions in the input signal.

     @param UINT fftWindowSize: sets the size of the fft, this should be a power of two. Default fftWindowSize=512
     @param UINT hopSize: sets how often the fft should be computed. If the hopSize parameter is set to 1 then the FFT will be computed everytime
     the classes computeFeatures(...) or computeFFT(...) functions are called. You may not want to compute the FFT of the input signal for every
     sample however, if this is the case then set the hopSize parameter to N, in which case the FFT will only be computed every N samples on the previous M values, where M is equal to the fftWindowSize. Default hopSize=1
     @param UINT numDimensions: the dimensionality of the input data to the FFT.  Default numDimensions = 1
     @param UINT fftWindowFunction: sets the window function of the FFT. This should be one of the FFTWindowFunctionOptions enumeration values. Default windowFunction=RECTANGULAR_WINDOW
     @param bool computeMagnitude: sets if the magnitude (and power) of the spectrum should be computed on the results of the FFT. Default computeMagnitude=true
     @param bool computePhase: sets if the phase of the spectrum should be computed on the results of the FFT. Default computePhase=true
     */
	FFT(UINT fftWindowSize=512,UINT hopSize=1,UINT numDimensions=1,UINT fftWindowFunction=RECTANGULAR_WINDOW,bool computeMagnitude=true,bool computePhase=true);

    /**
     Copy Constructor, copies the FFT from the rhs instance to this instance

	 @param const FFT &rhs: another instance of the FFT class from which the data will be copied to this instance
     */
    FFT(const FFT &rhs);

    /**
     Default Destructor
     */
	virtual ~FFT(void);

    /**
     Sets the equals operator, copies the data from the rhs instance to this instance

	 @param const FFT &rhs: another instance of the FFT class from which the data will be copied to this instance
	 @return a reference to this instance of FFT
     */
    FFT& operator=(const FFT &rhs);

    /**
     Sets the FeatureExtraction deepCopyFrom function, overwriting the base FeatureExtraction function.
     This function is used to deep copy the values from the input pointer to this instance of the FeatureExtraction module.
     This function is called by the GestureRecognitionPipeline when the user adds a new FeatureExtraction module to the pipeline.

	 @param FeatureExtraction *featureExtraction: a pointer to another instance of an FFT, the values of that instance will be cloned to this instance
	 @return true if the deep copy was successful, false otherwise
     */
    virtual bool deepCopyFrom(const FeatureExtraction *featureExtraction);

    /**
     Sets the FeatureExtraction computeFeatures function, overwriting the base FeatureExtraction function.
     This function is called by the GestureRecognitionPipeline when any new input data needs to be processed (during the prediction phase for example).
     This function calls the FFT's computeFFT(...) function.

	 @param const VectorDouble &inputVector: the inputVector that should be processed.  Must have the same dimensionality as the FeatureExtraction module
	 @return true if the data was processed, false otherwise
     */
    virtual bool computeFeatures(const VectorDouble &inputVector);

    /**
     Sets the FeatureExtraction reset function, overwriting the base FeatureExtraction function.
     This function is called by the GestureRecognitionPipeline when the pipelines main reset() function is called.
     This function resets the FFT by re-initiliazing the instance.

	 @return true if the FFT was reset, false otherwise
     */
    virtual bool reset();

    /**
     This saves the feature extraction settings to a file.

     @param const string filename: the filename to save the settings to
     @return returns true if the settings were saved successfully, false otherwise
     */
    virtual bool saveModelToFile(string filename) const;

    /**
     This saves the feature extraction settings to a file.

     @param fstream &file: a reference to the file to save the settings to
     @return returns true if the settings were saved successfully, false otherwise
     */
    virtual bool loadModelFromFile(string filename);

    /**
     This saves the feature extraction settings to a file.
     This overrides the saveSettingsToFile function in the FeatureExtraction base class.

     @param fstream &file: a reference to the file to save the settings to
     @return returns true if the settings were saved successfully, false otherwise
     */
    virtual bool saveModelToFile(fstream &file) const;

    /**
     This loads the feature extraction settings from a file.
     This overrides the loadSettingsFromFile function in the FeatureExtraction base class.

     @param fstream &file: a reference to the file to load the settings from
     @return returns true if the settings were loaded successfully, false otherwise
     */
    virtual bool loadModelFromFile(fstream &file);

    /**
     Initializes the FFT.
     Should be called before calling the computeFFT(...) or computeFeatures(...) methods.
     This function is automatically called by the constructor.

     @param UINT fftWindowSize: sets the size of the fft, this must be a power of two
     @param UINT hopSize: sets how often the fft should be computed. If the hopSize parameter is set to 1 then the FFT will be computed everytime
     the classes computeFeatures(...) or computeFFT(...) functions are called. You may not want to compute the FFT of the input signal for every
     sample however, if this is the case then set the hopSize parameter to N, in which case the FFT will only be computed every N samples on the previous M values, where M is equal to the fftWindowSize
     @param UINT numDimensions: the dimensionality of the input data to the FFT
     @param UINT windowFunction: sets the window function of the FFT. This should be one of the WindowFunctionOptions enumeration values
     @param bool computeMagnitude: sets if the magnitude (and power) of the spectrum should be computed on the results of the FFT
     @param bool computePhase: sets if the phase of the spectrum should be computed on the results of the FFT
	 @return true if the FTT was initialized, false otherwise
     */
    bool init(UINT fftWindowSize,UINT hopSize,UINT numDimensions,UINT windowFunction,bool computeMagnitude,bool computePhase);

    /**
     Computes the FFT of the previous M input samples, where M is the size of the fft window set by the constructor.
     The FFT of the input will only be computed if the current hop counter value matches the hopSize.
     This function should only be used if the dimensionality of the FFT has been set to 1.

     @param const double x: the new sample, this will be added to a buffer and the FFT will be computed for the data in the buffer
	 @return true if the FTT was updated successfully, false otherwise
     */
    bool update(const double x);

    /**
     Computes the FFT of the previous M input samples, where M is the size of the fft window set by the constructor.
     The FFT of the input will only be computed if the current hop counter value matches the hopSize.
     The dimensionality of the input vector must match the number of dimensions for the FFT.

     @param const VectorDouble &x: the new N-dimensional sample, this will be added to a buffer and the FFT will be computed for the data in the buffer
	 @return true if the FTT was updated successfully, false otherwise
     */
    bool update(const VectorDouble &x);

    /**
     Returns the current hopSize.

	 @return returns the current hopSize value if the FFT has been initialized, otherwise zero will be returned
     */
    UINT getHopSize();

    /**
     Returns the current dataBufferSize, which is the same as the FFT window size.

	 @return returns the current dataBufferSize value if the FFT has been initialized, otherwise zero will be returned
     */
    UINT getDataBufferSize();

    /**
     Returns the FFT window size.

	 @return returns the current FFT window size value if the FFT has been initialized, otherwise zero will be returned
     */
    UINT getFFTWindowSize();

    /**
     Returns the current FFT window function enumeration value.

	 @return returns the current FFT window function value if the FFT has been initialized, otherwise zero will be returned
     */
    UINT getFFTWindowFunction();

    /**
     Returns the current hop counter value.

	 @return returns the current hop counter value if the FFT has been initialized, otherwise zero will be returned
     */
    UINT getHopCounter();

    /**
     Returns if the magnitude (and power) of the FFT spectrum is being computed.

	 @return true if the magnitude (and power) of the FFT spectrum is being computed and if the FFT has been initialized, otherwise false will be returned
     */
    bool getComputeMagnitude(){ if(initialized){ return computeMagnitude; } return false; }

    /**
     Returns if the phase of the FFT spectrum is being computed.

	 @return true if the phase of the FFT spectrum is being computed and if the FFT has been initialized, otherwise false will be returned
     */
    bool getComputePhase(){ if(initialized){ return computePhase; } return false; }

    /**
     Returns the FFT results computed from the last FFT of the input signal.

	 @return returns a vector of FastFourierTransform (where the size of the vector is equal to the number of input dimensions for the FFT).  An empty vector will be returned if the FFT was not computed
     */
    vector< FastFourierTransform > getFFTResults(){ return fft; }

    /**
     Returns a pointer to the FFT results computed from the last FFT of the input signal.

	 @return returns a pointer to the vector of FastFourierTransform (where the size of the vector is equal to the number of input dimensions for the FFT).  An empty vector will be returned if the FFT was not computed
     */
    vector< FastFourierTransform >& getFFTResultsPtr(){ return fft; }

    VectorDouble getFrequencyBins(const unsigned int sampleRate);

    /**
     Sets the hopSize parameter, this sets how often the fft should be computed.
     If the hopSize parameter is set to 1 then the FFT will be computed everytime the classes' computeFeatures(...) or computeFFT(...) functions are called.
     You may not want to compute the FFT of the input signal for every sample however, if this is the case then set the hopSize parameter to N, in which case the FFT will only be computed every N samples on the previous M values, where M is equal to the fftWindowSize.
     The hopSize must be greater than zero.
     Setting the hopSize will also reset the hop counter.

     @param UINT hopSize: the new hopSize parameter, must be greater than zero
	 @return returns true if the hopSize parameter was successfully updated, false otherwise
     */
    bool setHopSize(UINT hopSize);

    /**
     Sets the fftWindowSize parameter, this sets the size of the fft, this must be a power of two.
     Setting this value will also re-initialize the FFT.

     @param UINT fftWindowSize: the new fftWindowSize parameter, this must be a power of two.
	 @return returns true if the fftWindowSize parameter was successfully updated, false otherwise
     */
    bool setFFTWindowSize(UINT fftWindowSize);

    /**
     Sets the fftWindowFunction parameter, this should be one of the FFTWindowFunctionOptions enumeration values.

     @param UINT fftWindowFunction: the new fftWindowFunction parameter, must be one of the FFTWindowFunctionOptions enumeration values
	 @return returns true if the fftWindowFunction parameter was successfully updated, false otherwise
     */
    bool setFFTWindowFunction(UINT fftWindowFunction);

    /**
     Sets if the magnitude (and power) of the FFT spectrum should be computed.

     @param bool computeMagnitude: the new computeMagnitude parameter
	 @return returns true if the computeMagnitude parameter was successfully updated, false otherwise
     */
    bool setComputeMagnitude(bool computeMagnitude);

    /**
     Sets if the phase of the FFT spectrum should be computed.

     @param bool computePhase: the new computeMagnitude parameter
	 @return returns true if the computePhase parameter was successfully updated, false otherwise
     */
    bool setComputePhase(bool computePhase);

protected:
    bool isPowerOfTwo(UINT x);                                   ///< A helper function to compute if the input is a power of two
    bool validateFFTWindowFunction(UINT fftWindowFunction);

    UINT hopSize;                                               ///< The current hopSize, this sets how often the fft should be computed
    UINT dataBufferSize;                                        ///< Stores how much previous input data is stored in the dataBuffer
    UINT fftWindowSize;                                         ///< Stores the size of the fft (and also the dataBuffer)
    UINT fftWindowFunction;                                     ///< The current windowFunction used for the FFT
    UINT hopCounter;                                            ///< Keeps track of how many input samples the FFT has seen
    bool computeMagnitude;                                      ///< Tracks if the magnitude (and power) of the FFT need to be computed
    bool computePhase;                                          ///< Tracks if the phase of the FFT needs to be computed
    GRT::VectorDouble tempBuffer;                               ///< A temporary buffer used to store the input data for the FFT
    CircularBuffer< VectorDouble > dataBuffer;                  ///< A circular buffer used to store the previous M inputs
    vector< FastFourierTransform > fft;                         ///< A buffer used to store the FFT results
    std::map< unsigned int, unsigned int > windowSizeMap;       ///< A map to relate the FFTWindowSize enumerations to actual values

    static RegisterFeatureExtractionModule< FFT > registerModule;

public:
    enum FFTWindowFunctionOptions{RECTANGULAR_WINDOW=0,BARTLETT_WINDOW,HAMMING_WINDOW,HANNING_WINDOW};
};

} //End of namespace GRT

#endif //GRT_FFT_HEADER


text:
/*
Shared include files
by: Connor Douthat
10/2/2015
*/
#include "main/libs.h"
#include "main/def.h"

#include "util/stringHelp.h"
#include "util/prototypes.h"
#include "util/envHelp.h"

#include "crypto/cryptoHelp.h"
#include "crypto/PasswordCipher.h"

#include "vault/VaultEntry.h"
#include "vault/Vault.h"
#include "vault/VaultManager.h"
#include "vault/VaultEntry.cpp"

#include "gui/GenericUserInput.h"
#include "gui/MenuTree.h"

#include "main/globals.h"
#include "main/config.h"

#include "dialog/preferences.h"
#include "dialog/openVault.h"
#include "dialog/closeVault.h"
#include "dialog/closeAllVaults.h"
#include "dialog/exportVault.h"
#include "dialog/recallEntry.h"
#include "dialog/createEntry.h"
#include "dialog/changeEntry.h"
#include "dialog/changeVaultPass.h"
#include "dialog/removeEntry.h"
#include "dialog/quickRecall.h"

#include "main/menuActions.h"
#include "main/menu.h"


text:
<ion-nav-buttons side="right">
    <button class="button button-positive" ng-click="triggerBuild()">Run</button>
</ion-nav-buttons>
<ion-view title="{{ buildType | buildTypeName }}">
    <ion-content>
        <ion-list>
            <ng-include ng-repeat="build in builds" src="'templates/buildItems.html'"></ng-include>
        </ion-list>
    </ion-content>
</ion-view>


text:
<?xml version="1.0" encoding="UTF-8"?>
<Poll_Response xmlns="http://taxii.mitre.org/messages/taxii_xml_binding-1.1"
 collection_name="test-collection" in_response_to="1235" message_id="invalid4">
 <Message>This Poll_Response is invalid because Record_Count is missing while
  a Content_Block is present.</Message>
 <Content_Block>
  <Content_Binding binding_id="urn:foo"/>
  <Content>Gitcha' content here!</Content>
 </Content_Block>
</Poll_Response>