text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Add Child Class
 *
 * @author Colan
 */
class Add_child extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper('url');
        $this->load->library('session');
        $this->load->library('email');
        $this->load->helper('form');
        $this->load->helper('string');
        $this->load->library('form_validation');
        $this->load->model('auth_model');
        $this->load->model('dashboard_model');

        cipl_user_auth();
    }

    public function index() {

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $config = array(
                array(
                    'field' => 'uname',
                    'label' => 'Child\'s Name',
                    'rules' => 'trim|required'
                ),
                array(
                    'field' => 'age',
                    'label' => 'Child\'s Age',
                    'rules' => 'trim|required'
                )
            );

            //echo $this->input->post('password_required'); exit;

            if($this->input->post('password_required') != '') {
                $config[] = array(
                  'field' => 'password',
                  'label' => 'Password',
                  'rules' => 'trim|required'
                );

                $config[] = array(
                  'field' => 'retype_password',
                  'label' => 'Retype Password',
                  'rules' => 'trim|required|matches[password]'
                );
            }

            $this->form_validation->set_rules($config);

            if ($this->form_validation->run() != FALSE) {
                $parent_details = $this->session->userdata('user_details');
                $password = '';
                if($this->input->post('password_required') != '') {
                    $password = $this->input->post('password');
                }
                //$password = random_string('alnum', 16);
                $input_data = array(
                    "email_id" => '',
                    "password" => md5($password),
                    "gender" => $this->input->post('gender'),
                    "uname" => $this->input->post('uname'),
                    "profile_image" => '',
                    "user_role" => '3',
                    "age" => $this->input->post('age'),
                    "age_group" => $this->input->post('age_group_id'),
                    "parent_id" => $parent_details['user_id'],
                    "logged_in" => '0',
                    "status" => '0',
                    "created_on" => date('Y-m-d H:i:s'),
                    "child_mode" => 'false',
                    "parent_type" => 'active',
                    "child_allowed" => '0',
                    "password_autogenerated" => 'true',
                    "password_reset_key" => '',
                    "register_confirm_key" => ''
                );

                if($this->input->post('profile_img')!="")
                {

                    //echo "<img src='".$this->input->post('profile_img')."'>";
                    $parent_image = $this->input->post('profile_img');
                    $image_name = base64_encode($this->input->post('uname'));

                    $filename = $image_name.'_'.md5(rand(1000000,1000000000)).'.jpg';
                    $profile_image = 'assets/userImages/'.$filename;

                    $imgdata = $parent_image;

                    list($type, $imgdata) = explode(';', $imgdata);
                    list(, $imgdata)      = explode(',', $imgdata);
                    $imgdata = base64_decode($imgdata);
                    file_put_contents($profile_image, $imgdata);

                    $input_data['profile_image'] = $profile_image;

                }

                $result = $this->auth_model->add_child($input_data);
                // SEND EMAIL
                $this->email->from('admin@colanapps.in', 'Ummahstars.Com');
                $this->email->to($parent_details['email_id']);
                $this->email->subject('Ummahstars.com - Welcome');

                $mail_data["uname"] = $parent_details['uname'];
                $mail_data['child_name'] = $this->input->post('uname');
                $mail_data['child_age'] = $this->input->post('age');
                $mail_data['child_password'] = $password;

                $message = $this->load->view('front/email_templates/new_child', $mail_data, TRUE);
                $this->email->message($message);
                $this->email->send();

                if($this->input->post('more_child') != '') {
                    $this->session->set_flashdata('Success', 'New child added successfully.');
                }
                else
                {
                    redirect('dashboard', 'refresh');
                }
            }
        }
        $data['age_groups'] = $this->dashboard_model->get_all_age_groups();
        $this->load->view('front/common/header');
        $this->load->view('front/add_child/index', $data);
        $this->load->view('front/common/footer');
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>

Deleting all Unauthorized User Accounts

How to permanently delete all unauthorized user accounts using the User Accounts module.

Navigate to Admin >  User Accounts - OR - Go to a User Accounts module.

Optional. Click the Unauthorized link to view a list of unauthorized users before deleting them.

Click the Delete Unauthorized Users link at the base of the module. This displays the message "Are You Sure You Wish To Delete These Items?"

Click the Yes button to confirm deletion.

redpajama_set_name: RedPajamaGithub


text:
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace TestUtil
{
	class MasterTestInterface : public Master
	{
	public:
		static unordered_set<string> encoderGenome(const string & genome)
		{
			return Master::encoderGenome(genome);
		}
	};

	TEST_CLASS(MasterTest)
	{

	public:

		// encoderGenome
		TEST_METHOD(encoderGenome_Success)
		{
			// On extrait un ensemble de mot depuis un génome valide

			string genome = "ATCG;AAAA;CC;TT;GG";

			try {

				unordered_set<string> genomeSet = MasterTestInterface::encoderGenome(genome);

				Assert::IsTrue(genomeSet.size() == 5);

				Assert::IsTrue(genomeSet.find("ATCG") != genomeSet.end());
				Assert::IsTrue(genomeSet.find("AAAA") != genomeSet.end());
				Assert::IsTrue(genomeSet.find("CC") != genomeSet.end());
				Assert::IsTrue(genomeSet.find("TT") != genomeSet.end());
				Assert::IsTrue(genomeSet.find("GG") != genomeSet.end());

			}
			catch (exception const& e)
			{
				UNREFERENCE_PARAMETER(e);

				Assert::Fail();
			}

		}

		TEST_METHOD(encoderGenome_Fail)
		{
			// On extrait un ensemble de mot depuis un génome invalide
			// Une exception "invalid_argument" est alors levée

			string genome = "ATCG;XXXX;CC;TT;GG";

			bool invalidArgumentException = false;

			try {

				unordered_set<string> genomeSet = MasterTestInterface::encoderGenome(genome);

				Assert::Fail();
			}
			catch (invalid_argument const& e)
			{
				UNREFERENCE_PARAMETER(e);

				invalidArgumentException = true;
			}

			Assert::IsTrue(invalidArgumentException);

		}

	};
}


text:
<?php
namespace Account\Form;

use Zend\Form\Form;

class RegisterForm extends Form
{
    public function __construct()
    {
        parent::__construct('registerForm');

        $this->setAttributes(array(
            'method' => 'post',
            'class' => 'standardForm'
        ));

        $this->add(array(
            'name' => 'security',
            'type' => 'Zend\Form\Element\Csrf'
        ));

        $this->add(array(
            'name' => 'submit',
            'type' => 'submit'
        ));

        $this->setValidationGroup(array(
            'security',
            'account' => array(
                'username',
                'password',
                'email'
            )
        ));
    }
}


text:
RESOLUTION=0.1

# End-Effector Frame
FRAME = "end_effector_grasp"

# Object placement tolerance
EPSILON = 1e-4

########################
### Imported Modules ###
########################

# Import our planning packages
import aminopy as aa
import tmsmtpy as tm

import TMSMT

# Import python math package
from math import pi

# The Common Lisp runtime is also available
import CL as cl

#############
## Helpers ##
#############

def map_locations(function, scene):
    for frame in tm.collect_frame_type(scene,"surface"):
        name = frame['name']
        for geom in frame['geometry']:
            shape = geom['shape']
            if aa.shape_is_box(shape):
                d = shape['dimension']
                x_max = d[0] / 2
                y_max = d[1] / 2
                x = 0
                i = 0
                while x <= x_max:
                    y = 0
                    j = 0
                    while y <= y_max:
                        function(name,i,j)
                        if i > 0: function(name,-i,j)
                        if j > 0: function(name,i,-j)
                        if i > 0 and j > 0: function(name,-i,-j)
                        y += RESOLUTION
                        j+=1
                    x +=  RESOLUTION
                    i+=1

def location_table(parent,frame):
    parent_name = parent.name
    name = frame.name
    trans = aa.translation( aa.frame_fixed_tf(frame) )
    i = int(round( trans[0] / RESOLUTION))
    j = int(round( trans[1] / RESOLUTION))
    position = tm.mangle(parent_name,i,j)
    return (["ONTABLE", name, position], i, j)

############################
### Collision Constraint ###
############################

def collision_constraint(scene,op,objs):
    # TODO: stacking

    moveable = []
    def collect_moveable(frame_name):
        frame = scene[frame_name]
        if aa.frame_isa(frame,"moveable"):
            moveable.append(frame)
    map(collect_moveable, objs)

    conjunction = []

    def handle_moveable(frame):
        parent_name = frame.parent
        parent = scene[parent_name]
        if aa.frame_isa(parent, "surface"):
            (x, i, j) = location_table(parent,frame)
            conjunction.append(x)

    map(handle_moveable, moveable)

    return conjunction

##########################
## Scene State Function ##
##########################
## TODO: Does not work after an UNSTACK operatorion
## Problem is with the "Clear" predicate
def make_state(scene, configuration, is_goal):
    '''Map the scene graph `scene' to a task state expression'''

    ## terms in the expression
    conjunction = []
    occupied = {}
    moveable_frames = tm.collect_frame_type(scene,"moveable")

    ## Add object locations
    handempty = [True]

    def add_on(child,parent):
        if parent == FRAME:
            conjunction.append(["HOLDING", child])
            conjunction.append(["NOT", ["HANDEMPTY"]])
            handempty[0] = False
            occupied[child] = True
        else:
            conjunction.append(["ON", child, parent])
            occupied[parent] = True

    def handle_moveable(frame):
        name = frame.name
        parent_name = frame.parent

        try:
            # If parent frame is a placement surface, position is the
            # appropriate grid cell on the surface.
            parent_frame = scene[parent_name]
            if aa.frame_isa(parent_frame, "surface"):
                (x, i, j) = location_table(parent_frame,frame)
                conjunction.append(x)

                occupied[(parent_name,i,j)] = True
            else:
                add_on(name,parent_name)
        except NameError:
                add_on(name,parent_name)

    map(handle_moveable, moveable_frames)

    if handempty[0]:
        conjunction.append(["HANDEMPTY"])

    ## Clear things
    def clear_block(frame):
        name = frame.name
        if not name in occupied:
            conjunction.append(["CLEAR", name])

    def clear_location(name,i,j):
        if not (name,i,j) in occupied:
            conjunction.append(["CLEAR", tm.mangle(name,i,j)])

    if not is_goal:
        map(clear_block, moveable_frames)
        map_locations(clear_location,scene)

    return conjunction

def scene_state(scene,configuration):
    return make_state(scene, configuration, False)

def goal_state(scene,configuration):
    return make_state(scene, configuration, True)

############################
## Scene Objects Function ##
############################

def scene_objects(scene):
    '''Return the PDDL objects for `scene'.'''
    obj = []

    def type_names(thing):
        return [ f.name
                 for f in
                 tm.collect_frame_type(scene,thing) ]

    # Moveable objects are blocks
    moveable = type_names("moveable")
    moveable.insert(0, "BLOCK")

    # Draw grid on surfaces
    locations = ['LOCATION']
    def add_loc(name,i,j):
        locations.append(tm.mangle(name,i,j))

    map_locations(add_loc,scene)

    return [moveable, locations]

############################
### Operator Definitions ###
############################

def motion_plan(op, frame, goal):
    scene = op.final_scene
    sub_scenegraph = aa.scene_chain(scene, "", frame)
    return tm.op_motion( op, sub_scenegraph, goal )

# def pick(op, obj):
#     mp = motion_plan(op, FRAME, tm.op_tf_abs(op,obj))
#     return tm.op_reparent(mp, FRAME, obj)

def place_tf(op, obj, dst_frame, g_tf_o ):
    mp =  motion_plan(op, obj, g_tf_o)
    return tm.op_reparent(mp, dst_frame, obj)

def place_height(scene,name):
    g = scene[name].collision
    s = g[0].shape
    if aa.shape_is_box(s):
        return s.dimension[2] / 2

# def place(op, obj, dst, i, j):
#     scene = op['final_scene']
#     x = i*RESOLUTION
#     y = j*RESOLUTION
#     z = place_height(scene,obj) + place_height(scene,dst) + EPSILON
#     d_tf_o = aa.tf2( 1, [x,y,z] )
#     g_tf_d = tm.op_tf_abs(op,dst)
#     g_tf_o = aa.mul(g_tf_d, d_tf_o );
#     return place_tf(op, obj, dst, g_tf_o)

# def stack(op, obj, dst ):
#     scene = op['final_scene']
#     config = op['final_config']
#     g_tf_d = tm.op_tf_abs(op,dst)
#     d_tf_o = aa.tf2(1, [0,0, place_height(scene,obj) + place_height(scene,dst) + EPSILON])
#     g_tf_o = aa.mul(g_tf_d, d_tf_o)
#     return place_tf(op, obj, dst, g_tf_o)

def op_pick_up(scene, config, op):
    #(a, obj, src, i, j) = op
    obj = op[1]
    nop = tm.op_nop(scene,config)
    mp = motion_plan(nop, FRAME, tm.op_tf_abs(nop,obj))
    return tm.op_reparent(mp, FRAME, obj)

def op_put_down(scene, config, op):
    (a, obj, dst, i, j) = op
    nop = tm.op_nop(scene,config)
    x = i*RESOLUTION
    y = j*RESOLUTION
    z = place_height(scene,obj) + place_height(scene,dst) + EPSILON
    d_tf_o = aa.tf2( 1, [x,y,z] )
    g_tf_d = tm.op_tf_abs(nop,dst)
    g_tf_o = aa.mul(g_tf_d, d_tf_o );
    return place_tf(nop, obj, dst, g_tf_o)

def op_stack(scene, config, op):
    (act,obj,dst) = op
    nop = tm.op_nop(scene,config)
    g_tf_d = tm.op_tf_abs(nop,dst)
    d_tf_o = aa.tf2(1, [0,0, place_height(scene,obj) + place_height(scene,dst) + EPSILON])
    g_tf_o = aa.mul(g_tf_d, d_tf_o)
    return place_tf(nop, obj, dst, g_tf_o)

def op_unstack(scene, config, op):
    return op_pick_up(scene,config,op)

##########################
### Register functions ###
##########################

tm.bind_scene_state(scene_state)
tm.bind_goal_state(goal_state)
tm.bind_scene_objects(scene_objects)
tm.bind_refine_operator(op_pick_up, "PICK-UP")
tm.bind_refine_operator(op_put_down, "PUT-DOWN")
tm.bind_refine_operator(op_stack, "STACK")
tm.bind_refine_operator(op_unstack, "UNSTACK")

tm.bind_collision_constraint(collision_constraint)


text:
/**
* Using .exist as a property instead of a function makes jshint unhappy!
*/
/*jshint -W030 */
var chai = require('chai');
chai.config.includeStack = true;
require('chai').should();
var expect = require('chai').expect;

describe('GeoManager', function() {

  describe('Add', function() {
    var GeoManager;

    beforeEach(function() {
      GeoManager = require('../index').create({
        lat: 35.73265,
        lon: -78.85029,
        minDistance: 50
      });
    });

    it('should throw error if no lat/lon provided', function() {
      expect(function() {
        GeoManager.add();
      }).to.throw();
    });

    it('should allow adding to the managed list', function() {
      var item = {
        lat: 35.73,
        lon: -78.85,
        data: 'Austin'
      };

      GeoManager.add(item);

      var managed = GeoManager.getManagedList();

      var expectedDistance = 0.1838296891494826;

      expect(managed.length).to.equal(1);
      expect(managed[0].distance).to.equal(expectedDistance);
      expect(managed[0].data.length).to.equal(1);

      expect(managed[0].data[0].distance).to.equal(expectedDistance);
      expect(managed[0].data[0].lat).to.equal(item.lat);
      expect(managed[0].data[0].lon).to.equal(item.lon);
      expect(managed[0].data[0].data).to.equal(item.data);
    });
  });

  describe('Find Closest', function() {
    var GeoManager;
    var addedItem = {
      lat: 35.73,
      lon: -78.85,
      data: 'Austin'
    };

    beforeEach(function() {
      GeoManager = require('../index').create({
        lat: 35.73265,
        lon: -78.85029,
        minDistance: 50
      });

      GeoManager.add(addedItem);
    });

    it('should throw error if no lat/lon provided', function() {
      expect(function() {
        GeoManager.findClosest();
      }).to.throw();
    });

    it('should find closest managed geo locations', function() {
      var closest = GeoManager.findClosest({
        lat: 35.7,
        lon: -78.8
      });

      expect(closest.distance).to.equal(0.1838296891494826);
      expect(closest.data[0].lat).to.equal(addedItem.lat);
      expect(closest.data[0].lon).to.equal(addedItem.lon);
      expect(closest.data[0].data).to.equal(addedItem.data);
    });

    it('should find closest managed geo locations when different distance lists exist', function() {
      GeoManager.add({
        lat: 42.1,
        lon: 97.6
      });

      var closest = GeoManager.findClosest({
        lat: 35.7,
        lon: -78.8
      });

      expect(closest.distance).to.equal(0.1838296891494826);
      expect(closest.data.length).to.equal(1);
      expect(closest.data[0].lat).to.equal(addedItem.lat);
      expect(closest.data[0].lon).to.equal(addedItem.lon);
      expect(closest.data[0].data).to.equal(addedItem.data);
    });

    it('should find closest not in range if ignoreMin flag included', function() {
      var closest = GeoManager.findClosest({
        lat: 23.2,
        lon: 70.4
      });

      expect(closest).to.equal(null);
    });

    it('should find closest not in range if ignoreMin flag included', function() {
      var closest = GeoManager.findClosest({
        lat: 23.2,
        lon: 70.4,
        ignoreMin: true
      });

      expect(closest).to.exist;
    });
  });

  describe('Delete', function() {
    var GeoManager;
    var addedItem = {
      lat: 35.73,
      lon: -78.85,
      data: 'Austin'
    };

    beforeEach(function() {
      GeoManager = require('../index').create({
        lat: 35.73265,
        lon: -78.85029,
        minDistance: 50
      });

      GeoManager.add(addedItem);
    });

    it('should throw error if no lat/lon provided', function() {
      expect(function() {
        GeoManager.delete();
      }).to.throw();
    });

    it('should allow deletion of existing geo location', function() {
      var managed = GeoManager.getManagedList();

      expect(managed.length).to.equal(1);

      GeoManager.delete({
        lat: addedItem.lat,
        lon: addedItem.lon
      });

      managed = GeoManager.getManagedList();
      expect(managed.length).to.equal(0);
    });

    it('should allow deletion of existing geo location when multiple in same list', function() {
      var managed = GeoManager.getManagedList();

      expect(managed.length).to.equal(1);

      var secondItem = {
        lat: 35.7,
        lon: -78.8,
        data: 'Test'
      };

      GeoManager.add(secondItem);

      managed = GeoManager.getManagedList();

      expect(managed[0].data.length).to.equal(2);

      GeoManager.delete({
        lat: addedItem.lat,
        lon: addedItem.lon
      });

      managed = GeoManager.getManagedList();
      expect(managed.length).to.equal(1);

      expect(managed[0].data[0].lat).to.equal(secondItem.lat);
      expect(managed[0].data[0].lon).to.equal(secondItem.lon);
      expect(managed[0].data[0].data).to.equal(secondItem.data);
    });

    it('should not delete any not within range', function() {
      var managed = GeoManager.getManagedList();

      expect(managed.length).to.equal(1);

      GeoManager.delete({
        lat: 23.2,
        lon: 70.4
      });

      managed = GeoManager.getManagedList();
      expect(managed.length).to.equal(1);
    });

    it('should not delete items with same lat/lon but different data', function() {
      GeoManager.delete({
        lat: addedItem.lat,
        lon: addedItem.lon,
        data: 'random data!'
      });

      var managed = GeoManager.getManagedList();
      expect(managed.length).to.equal(1);
    });

    it('should only delete the item with exact data if data specified in delete', function() {
      var secondItem = {
        lat: addedItem.lat,
        lon: addedItem.lon,
        data: 'Test'
      };

      GeoManager.add(secondItem);

      GeoManager.delete({
        lat: addedItem.lat,
        lon: addedItem.lon,
        data: 'Test'
      });

      var managed = GeoManager.getManagedList();
      expect(managed[0].data[0].data).to.equal(addedItem.data);
    });
  });
});


text:
__author__ = 'luyangsheng'
from flask import Flask
from flask import request, g
from flask.sessions import SessionInterface
from beaker.middleware import SessionMiddleware
import logging

# global server envrionment options
debug = True

# database settings
_DB_URL_FORMAT = "mysql://%(user)s:%(password)s@%(host)s:%(port)s/%(database)s"
_db_config = {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "root",
    "database": "db_sys",
}

# other sever options
options = {
    # use md5sum of my name as cookie_secret
    "SECRET_KEY": "3087c29ddaaed0a7671093b3eb00ad4a",
    "DEBUG": debug
}
session_opts = {
    "session.type": "ext:database",
    "session.url": _DB_URL_FORMAT % _db_config,
    "session.lock_dir": "./lock",
}
# 把自己伪装成php。。。这个有点邪恶
session_setting = {
    "key": "PHPSESSIONID",
}

app = Flask(__name__, static_url_path="")
app.config.update(**options)

# logging config
_log_config = {
    "level": logging.DEBUG,
    "format": "[%(asctime)s][%(levelname)s]--%(name)s--:%(message)s",
}
if not debug:
    _log_config['file'] = "hsp_sys.log"
logging.basicConfig(**_log_config)

class BeakerSessionInterface(SessionInterface):

    def open_session(self, _app, _request):
        _session = request.environ['beaker.session']
        return _session

    def save_session(self, _app, _session, response):
        _session.save()

# initial database session before request
@app.before_request
def before_request():
    pass

# close database session after request
@app.teardown_request
def teardnow_request(exception):
    pass

app.wsgi_app = SessionMiddleware(
    app.wsgi_app,
    session_opts,
    **session_setting
)
app.session_interface = BeakerSessionInterface()

from controller import *


text:
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <title>Css Star Rating</title>

  <meta name="description" content=""/>
  <meta name="generator" content="kss-node"/>
  <meta name="viewport" content="width=device-width"/>

  <link rel="stylesheet" href="kss-assets/kss.css"/>
  <link rel="stylesheet" href="assets/css/star-rating.css"/>
<link rel="stylesheet" href="assets/css/fontawesome-all.min.css"/>

Css Star Rating

          0Overview

          1Star Rating

              1.2.1.3

                  #permalink

            Star sizes

              Toggle example guides
              <svg focusable="false" aria-hidden="true" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" viewBox="0 0 64 64">
                <rect class="kss-toolbar__icon-fill" x="5" y="35" width="5" height="9"/>
                <rect class="kss-toolbar__icon-fill" x="54" y="21" width="5" height="9"/>
                <rect class="kss-toolbar__icon-fill" x="54" y="35" width="5" height="9"/>
                <rect class="kss-toolbar__icon-fill" x="5" y="21" width="5" height="9"/>
                <rect class="kss-toolbar__icon-fill" x="5" y="0" width="5" height="15"/>
                <rect class="kss-toolbar__icon-fill" x="35" y="5" width="9" height="5"/>
                <rect class="kss-toolbar__icon-fill" x="20" y="5" width="9" height="5"/>
                <rect class="kss-toolbar__icon-fill" x="0" y="5" width="15" height="5"/>
                <rect class="kss-toolbar__icon-fill" x="54" y="0" width="5" height="15"/>
                <rect class="kss-toolbar__icon-fill" x="49" y="5" width="15" height="5"/>
                <rect class="kss-toolbar__icon-fill" x="54" y="49" width="5" height="15"/>
                <rect class="kss-toolbar__icon-fill" x="49" y="54" width="15" height="5"/>
                <rect class="kss-toolbar__icon-fill" x="5" y="49" width="5" height="15"/>
                <rect class="kss-toolbar__icon-fill" x="0" y="54" width="15" height="5"/>
                <rect class="kss-toolbar__icon-fill" x="35" y="54" width="9" height="5"/>
                <rect class="kss-toolbar__icon-fill" x="20" y="54" width="9" height="5"/>
              </svg>

              Toggle HTML markup
              <svg focusable="false" aria-hidden="true" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" viewBox="0 0 64 64">
                <path class="kss-toolbar__icon-fill" d="M37.555,46.239l6.103,6.103l20.342,-20.342l-20.342,-20.342l-6.103,6.103l14.24,14.239l-14.24,14.239Z"/>
                <path class="kss-toolbar__icon-fill" d="M26.445,17.761l-6.103,-6.103l-20.342,20.342l20.342,20.342l6.103,-6.103l-14.24,-14.239l14.24,-14.239Z"/>
              </svg>

The Star sizes.

            Examples

              Default styling

  <svg class="star-empty">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-empty"></use>
  </svg>
  <svg class="star-half">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-half"></use>
  </svg>
  <svg class="star-filled">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-filled"></use>
  </svg>

              .small

              displays star in small size

  <svg class="star-empty">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-empty"></use>
  </svg>
  <svg class="star-half">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-half"></use>
  </svg>
  <svg class="star-filled">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-filled"></use>
  </svg>

              .medium

              displays star in medium size

  <svg class="star-empty">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-empty"></use>
  </svg>
  <svg class="star-half">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-half"></use>
  </svg>
  <svg class="star-filled">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-filled"></use>
  </svg>

              .large

              displays star in large size

  <svg class="star-empty">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-empty"></use>
  </svg>
  <svg class="star-half">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-half"></use>
  </svg>
  <svg class="star-filled">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-filled"></use>
  </svg>

                Markup

<div class="star [modifier class]">
  <svg class="star-empty">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-empty"></use>
  </svg>
  <svg class="star-half">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-half"></use>
  </svg>
  <svg class="star-filled">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="assets/images/star-rating.icons.svg#star-filled"></use>
  </svg>
</div>

          Source: src/kss-documentation/elements.kss.scss, line 218


text:
package flounder.space;

import flounder.physics.*;

/**
 * Represents an object that has some notion of space, and can be stored in a {@link ISpatialStructure}.
 */
public interface ISpatialObject {
	/**
	 * @return Returns a shape fully enclosing the object.
	 */
	Collider getCollider();
}


text:
package org.telegram.telegrambots.api.methods;

import javax.ws.rs.Path;

import org.telegram.telegrambots.api.methods.send.ApiMethod;

import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

/**
 *
 * @author Lev Nadeinsky
 * @author Ruben Bermudez
 * @brief Use this method to get basic info about a file and prepare it for downloading.
 * For the moment, bots can download files of up to 20MB in size.
 * On success, a File object is returned.
 * The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>,
 * where <file_path> is taken from the response.
 * It is guaranteed that the link will be valid for at least 1 hour.
 * When the link expires, a new one can be requested by calling getFile again.
 * @date	2016-11-21
 */
@Data
@ToString
@EqualsAndHashCode(callSuper=false)
@Path("getFile")
public class GetFile extends ApiMethod {

	/**
	 * File identifier to get info about
	 */
    @JsonProperty("file_id") String fileId;
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;

using ManagedIrbis.Client;
using ManagedIrbis.Morphology;

namespace UnitTests.ManagedIrbis.Morphology
{
    [TestClass]
    public class SynonymEngineTest
        : Common.CommonUnitTest
    {
        [TestMethod]
        public void SynonymEngine_Construction_1()
        {
            using (IrbisProvider provider = GetProvider())
            {
                SynonymEngine engine = new SynonymEngine(provider);
                Assert.AreSame(provider, engine.Provider);
                Assert.AreEqual(SynonymEngine.DefaultDatabase, engine.Database.Value);
                Assert.AreEqual(SynonymEngine.DefaultPrefix, engine.Prefix.Value);
            }
        }

        [TestMethod]
        public void SynonymEngine_GetSynonyms_1()
        {
            using (IrbisProvider provider = GetProvider())
            {
                SynonymEngine engine = new SynonymEngine(provider);
                string[] synonyms = engine.GetSynonyms("абориген");
                Assert.AreEqual(2, synonyms.Length);

                synonyms = engine.GetSynonyms("неттакогослова");
                Assert.AreEqual(0, synonyms.Length);
            }
        }
    }
}


text:
from unittest import TestCase

class TestIsLeapYear(TestCase):

    def _call_fut(self, year):
        from awstatic.utils import is_leap_year
        return is_leap_year(year)

    def test_basics(self):
        self.assertTrue(self._call_fut(2012))
        self.assertFalse(self._call_fut(2011))
        self.assertTrue(self._call_fut(1600))
        self.assertFalse(self._call_fut(1700))

class TestNumberOfDays(TestCase):

    def _call_fut(self, yyyymm):
        from awstatic.utils import get_number_of_days
        return get_number_of_days(yyyymm)

    def test_basics(self):
        self.assertEqual(self._call_fut('201101'), 31)
        self.assertEqual(self._call_fut('201102'), 28)
        self.assertEqual(self._call_fut('201202'), 29)
        self.assertEqual(self._call_fut('201204'), 30)
        self.assertEqual(self._call_fut('201212'), 31)

class TestInterpolate(TestCase):

    def _call_fut(self, s, **bindings):
        from awstatic.utils import interpolate
        return interpolate(s, **bindings)

    def test_basics(self):
        self.assertEqual(self._call_fut('foo'), 'foo')
        self.assertEqual(self._call_fut('foo', foo='1'), 'foo')
        self.assertEqual(self._call_fut('${foo}'), '${foo}')
        self.assertEqual(self._call_fut('${foo}', bar='1'), '${foo}')
        self.assertEqual(self._call_fut('Value is: ${foo}', foo='1'),
                         'Value is: 1')


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview A confirmation dialog allowing the user to delete various types
 * of certificates.
 */
import '../../cr_elements/cr_button/cr_button.m.js';
import '../../cr_elements/cr_dialog/cr_dialog.m.js';
import './certificate_shared_css.js';

import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {CrDialogElement} from '../../cr_elements/cr_dialog/cr_dialog.m.js';
import {assertNotReached} from '../../js/assert.m.js';
import {I18nMixin} from '../../js/i18n_mixin.js';
import {loadTimeData} from '../../js/load_time_data.m.js';

import {CertificatesBrowserProxy, CertificatesBrowserProxyImpl, CertificateSubnode, CertificateType} from './certificates_browser_proxy.js';

export interface CertificateDeleteConfirmationDialogElement {
  $: {
    dialog: CrDialogElement,
  };
}

const CertificateDeleteConfirmationDialogElementBase =
    I18nMixin(PolymerElement);

export class CertificateDeleteConfirmationDialogElement extends
    CertificateDeleteConfirmationDialogElementBase {
  static get is() {
    return 'certificate-delete-confirmation-dialog';
  }

  static get template() {
    return html`{__html_template__}`;
  }

  static get properties() {
    return {
      model: Object,
      certificateType: String,
    };
  }

  model: CertificateSubnode;
  certificateType: CertificateType;

  connectedCallback() {
    super.connectedCallback();
    this.$.dialog.showModal();
  }

  private getTitleText_(): string {
    const getString = (localizedMessageId: string) =>
        loadTimeData.getStringF(localizedMessageId, this.model.name);

    switch (this.certificateType) {
      case CertificateType.PERSONAL:
        return getString('certificateManagerDeleteUserTitle');
      case CertificateType.SERVER:
        return getString('certificateManagerDeleteServerTitle');
      case CertificateType.CA:
        return getString('certificateManagerDeleteCaTitle');
      case CertificateType.OTHER:
        return getString('certificateManagerDeleteOtherTitle');
    }
    assertNotReached();
    return '';
  }

  private getDescriptionText_(): string {
    const getString = loadTimeData.getString.bind(loadTimeData);
    switch (this.certificateType) {
      case CertificateType.PERSONAL:
        return getString('certificateManagerDeleteUserDescription');
      case CertificateType.SERVER:
        return getString('certificateManagerDeleteServerDescription');
      case CertificateType.CA:
        return getString('certificateManagerDeleteCaDescription');
      case CertificateType.OTHER:
        return '';
    }
    assertNotReached();
    return '';
  }

  private onCancelTap_() {
    this.$.dialog.close();
  }

  private onOkTap_() {
    CertificatesBrowserProxyImpl.getInstance()
        .deleteCertificate(this.model.id)
        .then(
            () => {
              this.$.dialog.close();
            },
            error => {
              this.$.dialog.close();
              this.dispatchEvent(new CustomEvent('certificates-error', {
                bubbles: true,
                composed: true,
                detail: {error: error, anchor: null},
              }));
            });
  }
}

customElements.define(
    CertificateDeleteConfirmationDialogElement.is,
    CertificateDeleteConfirmationDialogElement);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Portfolio Laura Morales- Prototype 2</title>

    <link rel="stylesheet" href="bower_components/aos/dist/aos.css" />

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Dancing+Script|Raleway|Raleway+Dots|Oxygen" rel="stylesheet">

    <link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="vendor/simple-line-icons/css/simple-line-icons.css">
    <link rel="stylesheet" href="vendor/device-mockups/iphone6-flat-mockup.css">

    <link href="css/new-age.min.css" rel="stylesheet">
    <link href="less/new-age.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Lm

                        Mes réalisations

                        Mes talents

                        Mon expérience

                        Contact

Laura Morales

Développeuse Front-End

                            Connaître mon histoire!

Bonjour, je m'appelle Laura Morales.

Je suis une prof. de langues qui a décidé de retourner à l'école pour apprendre une quatrième: la programmation :)

J'étudie au Cégep Limoilou actuellement et après 12 mois d'éxploration du code, je me lance à la recherche de mon premier stage comme Développeuse web...

Jete un coup d'oeil à mon cahier d'exercices!

J'ai joué plusieurs rôles dans le processus de production web, en voici deux exemples.

                    <button type="button" class="btn btn-modal btn-xl" data-toggle="modal" data-target="#modalWeb">
                        Projet Web
                    </button>

                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Metierdart.com

Dans le cadre de notre premier projet client, j'ai eu la chance de travailler avec l'équipe de refonte du site web pour le Centre de formation et de consultation en métiers d'art du Cégep Limoilou. J'y ai joué le rôle de chargée de projet et je me suis aussi occupée en grande partie de la procédure de mise en ligne. Grâce à ce rôle, j'ai beaucoup apris sur l'utilisation des differents outils de gestion ainsi que sur l'hébérgement et les transfers via FTP.

                                     Voir site

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>

                    <button type="button" class="btn btn-modal btn-xl" data-toggle="modal" data-target="#modalApp">
                        Projet Mobile
                    </button>

                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Samsara

Samsara, est le premier projet d'application web conçu entièrement par moi. Dans le processus de conception, j'ai expérimenté toutes les étapes commençant par l'idéation, et passant par le maquettage et la definition de la clientèle cible. Pour l'instant elle est en phase 1, et le prototype semi-fonctionnel que j'ai dévéloppé à merité la création d'une équipe de collègues qui travailleront avec moi pour la pousser plus loin.

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>

Formation polyvalante, Intérêts multiples

Voici les outils que j'aime utiliser le plus!

Conception

J'aime imaginer des applications et des solutions multiples à toute sorte de problematiques pouvant être mieux dressés par des outils web.

Langages

Pour bien presenter mon contenu j'utilise HTML5 et CSS3! Ensuite, pour le rendre dynamique et intéressant j'utilise l'aide de JavaScript et Jquery.

Logiciels

Toujours étant une mordue de l'audiovisuel, j'ai beaucoup profité de l'initiation aux logiciels d'édition tels que Adobe Premiere, Audition et Photoshop. Un coup de coeur

Partage

Une des choses que j'aime le plus du monde du web, c'est l'esprit de communauté, de partage et d'entraide. C'est pour ça que je met l'accent sur l'utilisation des plateformes comme github et l'apprentissage des systèmes d'exploitation open source m'intéresse davantage.

Mon expérience

Étant née dans le sud du continent, j'ai eu la chance de travailler ici et là. Donc je peux compter dans mon expérience des passages par des environements très variés et dans 3 villes complètement différents. Mes expériences qui vont de l'école bilangue la plus reputée de Medellin à une des entreprises phare dans le domaine des télécommunications au Québec, m'ont beaucoup fait grandir et apprendre.

Intéressé(e)?
Contactez-moi.

                M'écrire!

                <button type="button" class="btn btn-modal btn-xl" data-toggle="modal" data-target="#modalForm">
                    Projet Mobile
                </button>

                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Samsara

                                <form role="form" id="contact-form" class="contact-form">

                                                <input type="text" class="form-control" name="Name" autocomplete="off" id="Name" placeholder="Name">

                                                <input type="email" class="form-control" name="email" autocomplete="off" id="email" placeholder="E-mail">

                                                <textarea class="form-control textarea" rows="3" name="Message" id="Message" placeholder="Message"></textarea>

                                            <button type="submit" class="btn main-btn pull-right">Send a message</button>

                                </form>

                        <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>

J' les réseaux sociaux aussi!

© 2016 Laura Morales.


text:
Uploader::Engine.routes.draw do
  resources :attachments, only: [:index, :create, :update, :destroy]
end


text:
module LocalName
  def local_name( lang = Locale.base_language )
    cat_alias = aliases.local(lang) if not lang.nil?
    if cat_alias.nil? or cat_alias.empty?
      cat_alias = aliases.local( Locale.base_language )
    end
    if cat_alias.first.nil?
      logger.info "Object #{self.class} with id #{id} has no aliases"
      if not self['name'].nil?
        return self['name']
      else
        return ""
      end
    end
    cat_alias.first.name
  end

  def name
    local_name Locale.base_language
  end

  def aliases
    name_aliases
  end

  def local_aliases( lang )
    aliases.local( lang )
  end

  def official_translation( lang )
    self.aliases.find(:all, :conditions => [ "official_translation = ? AND language_id = ?", 1, lang.id ] )
  end

  def non_official_aliases( lang )
    aliases - official_translation( lang )
  end

  def non_official_translations( lang )
    self.aliases.find(:all, :conditions => [ "official_translation = ? AND (language_id = ? OR language_id = ?) ", 0, lang.id, Language.independent_language.id ] )
  end

  def no_official_translation( lang )
    self.official_translation( lang ).each do |a|
      a.official_translation = false
      a.save
    end
  end

  # problem - sporadic MemCache Error: undefined class/module NameAlias errors
  # TODO expire cached objects when aliases change
  # TODO caches_method :aliases_by_language generiert caching wrapper
  # automatisch
  def aliases_by_language
 #   key = "aliases_by_language_#{self.class.base_class}_#{self.id}"
 #   unless aliases = Cache.get(key)
      aliases = {}
      NameAlias.find(:all, :conditions => "related_object_type = '#{self.class.base_class}' and related_object_id = #{self.id}").each { |a|
        aliases[a.language] ||= []
        aliases[a.language] << a
      }
#      Cache.put key, aliases
#    end
    aliases
  end

  # Return aliases in a slimed down version of aliases_by_language (needed for
  # indexing)
  #
  # >> Movie.find(11).alias_names_by_language
  # => {"de"=>["Der Herr der Ringe"]}
  def alias_names_by_language
    returning aliases = {} do
      aliases_by_language.each do |lang, as|
        aliases[lang.code] = as.collect{ |a| a.name }
      end
    end
  end
end


text:
class User < ActiveRecord::Base
  has_many :teams, through: :users_teams, class_name: 'Team'
  has_many :users_teams, class_name: 'UsersTeams'

  validates :name, :email, presence: true
  validates :email, uniqueness: true
  validates :password, length: { minimum: 4 }, on: :create

  has_secure_password
end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Newtonsoft.Json;
using NsqSharp.Api;
using NsqSharp.Bus;
using NsqSharp.Bus.Configuration;
using NsqSharp.Bus.Configuration.BuiltIn;
using NsqSharp.Tests.Bus.TestFakes;
using NsqSharp.Utils.Extensions;
using NUnit.Framework;
using StructureMap;

namespace NsqSharp.Tests.Bus
{
#if !RUN_INTEGRATION_TESTS
    [TestFixture(IgnoreReason = "NSQD Integration Test")]
#else
    [TestFixture]
#endif
    public class TouchTest
    {
        private static readonly NsqdHttpClient _nsqdHttpClient;
        private static readonly NsqLookupdHttpClient _nsqLookupdHttpClient;

        static TouchTest()
        {
            _nsqdHttpClient = new NsqdHttpClient("127.0.0.1:4151", TimeSpan.FromSeconds(5));
            _nsqLookupdHttpClient = new NsqLookupdHttpClient("127.0.0.1:4161", TimeSpan.FromSeconds(5));
        }

        [Test]
        public void Given_A_Timeout_Of_3_Seconds_When_Touch_Not_Executed_Then_Nsqd_Should_Requeue()
        {
            string topicName = string.Format("test_touch_{0}", DateTime.Now.UnixNano());
            const string channelName = "test_touch";

            var container = new Container();

            _nsqdHttpClient.CreateTopic(topicName);
            _nsqLookupdHttpClient.CreateTopic(topicName);

            try
            {
                BusService.Start(new BusConfiguration(
                    new StructureMapObjectBuilder(container),
                    new NewtonsoftJsonSerializer(typeof(JsonConverter).Assembly),
                    new MessageAuditorStub(),
                    new MessageTypeToTopicDictionary(new Dictionary<Type, string> {
                        { typeof(TouchTestMessage), topicName }
                    }),
                    new HandlerTypeToChannelDictionary(new Dictionary<Type, string> {
                        { typeof(BlockingNoTouchTestHandler), channelName }
                    }),
                    defaultNsqLookupdHttpEndpoints: new[] { "127.0.0.1:4161" },
                    defaultThreadsPerHandler: 1,
                    nsqConfig: new Config
                    {
                        MessageTimeout = TimeSpan.FromSeconds(3.5),
                        MaxRequeueDelay = TimeSpan.Zero,
                        LookupdPollJitter = 0,
                        LookupdPollInterval = TimeSpan.FromSeconds(1)
                    },
                    preCreateTopicsAndChannels: true
                ));

                BlockingNoTouchTestHandler.Reset();

                var bus = container.GetInstance<IBus>();

                // send our message which will get timed out
                bus.Send(new TouchTestMessage());
                var signaled = BlockingNoTouchTestHandler.Wait(TimeSpan.FromSeconds(10));

                Assert.IsTrue(signaled, "signaled");

                int count = BlockingNoTouchTestHandler.GetCount();
                Assert.AreEqual(2, count, "first count check");

                // give it a chance to possibly requeue/reprocess again
                Thread.Sleep(100);

                count = BlockingNoTouchTestHandler.GetCount();
                Assert.AreEqual(2, count, "second count check");

                // checks stats from http server
                var stats = _nsqdHttpClient.GetStats();
                var topic = stats.Topics.Single(p => p.TopicName == topicName);
                var channel = topic.Channels.Single(p => p.ChannelName == channelName);

                Assert.AreEqual(1, topic.MessageCount, "topic.MessageCount");
                Assert.AreEqual(0, topic.Depth, "topic.Depth");
                Assert.AreEqual(0, topic.BackendDepth, "topic.BackendDepth");

                Assert.AreEqual(1, channel.MessageCount, "channel.MessageCount");
                Assert.AreEqual(0, channel.DeferredCount, "channel.DeferredCount");
                Assert.AreEqual(0, channel.Depth, "channel.Depth");
                Assert.AreEqual(0, channel.BackendDepth, "channel.BackendDepth");
                Assert.AreEqual(0, channel.InFlightCount, "channel.InFlightCount");
                Assert.AreEqual(1, channel.TimeoutCount, "channel.TimeoutCount"); // 1 timeout
                Assert.AreEqual(1, channel.RequeueCount, "channel.RequeueCount"); // 1 requeue
            }
            finally
            {
                BusService.Stop();
                _nsqdHttpClient.DeleteTopic(topicName);
                _nsqLookupdHttpClient.DeleteTopic(topicName);
            }
        }

        [Test]
        public void Given_A_Timeout_Of_3_Seconds_When_Touch_Executed_Then_Nsqd_Should_Not_Requeue()
        {
            string topicName = string.Format("test_touch_{0}", DateTime.Now.UnixNano());
            const string channelName = "test_touch";

            var container = new Container();

            _nsqdHttpClient.CreateTopic(topicName);
            _nsqLookupdHttpClient.CreateTopic(topicName);

            try
            {
                BusService.Start(new BusConfiguration(
                    new StructureMapObjectBuilder(container),
                    new NewtonsoftJsonSerializer(typeof(JsonConverter).Assembly),
                    new MessageAuditorStub(),
                    new MessageTypeToTopicDictionary(new Dictionary<Type, string> {
                        { typeof(TouchTestMessage), topicName }
                    }),
                    new HandlerTypeToChannelDictionary(new Dictionary<Type, string> {
                        { typeof(BlockingTouchTestHandler), channelName }
                    }),
                    defaultNsqLookupdHttpEndpoints: new[] { "127.0.0.1:4161" },
                    defaultThreadsPerHandler: 1,
                    nsqConfig: new Config
                    {
                        MessageTimeout = TimeSpan.FromSeconds(3),
                        MaxRequeueDelay = TimeSpan.Zero,
                        LookupdPollJitter = 0,
                        LookupdPollInterval = TimeSpan.FromSeconds(1)
                    },
                    preCreateTopicsAndChannels: true
                ));

                BlockingTouchTestHandler.Reset();

                var bus = container.GetInstance<IBus>();

                // send our message which will get timed out
                bus.Send(new TouchTestMessage());
                var signaled = BlockingTouchTestHandler.Wait(TimeSpan.FromSeconds(10));

                Assert.IsTrue(signaled, "signaled");

                int count = BlockingTouchTestHandler.GetCount();
                Assert.AreEqual(1, count);

                // give it a chance to possibly requeue/reprocess again
                Thread.Sleep(100);

                count = BlockingTouchTestHandler.GetCount();
                Assert.AreEqual(1, count);

                // checks stats from http server
                var stats = _nsqdHttpClient.GetStats();
                var topic = stats.Topics.Single(p => p.TopicName == topicName);
                var channel = topic.Channels.Single(p => p.ChannelName == channelName);

                Assert.AreEqual(1, topic.MessageCount, "topic.MessageCount");
                Assert.AreEqual(0, topic.Depth, "topic.Depth");
                Assert.AreEqual(0, topic.BackendDepth, "topic.BackendDepth");

                Assert.AreEqual(1, channel.MessageCount, "channel.MessageCount");
                Assert.AreEqual(0, channel.DeferredCount, "channel.DeferredCount");
                Assert.AreEqual(0, channel.Depth, "channel.Depth");
                Assert.AreEqual(0, channel.BackendDepth, "channel.BackendDepth");
                Assert.AreEqual(0, channel.InFlightCount, "channel.InFlightCount");
                Assert.AreEqual(0, channel.TimeoutCount, "channel.TimeoutCount"); // 0 timeout
                Assert.AreEqual(0, channel.RequeueCount, "channel.RequeueCount"); // 0 requeue
            }
            finally
            {
                BusService.Stop();
                _nsqdHttpClient.DeleteTopic(topicName);
                _nsqLookupdHttpClient.DeleteTopic(topicName);
            }
        }

        private class TouchTestMessage
        {
        }

        private class BlockingNoTouchTestHandler : IHandleMessages<TouchTestMessage>
        {
            private static int _count;
            private static readonly AutoResetEvent _wait = new AutoResetEvent(initialState: false);

            public void Handle(TouchTestMessage message)
            {
                int value = Interlocked.Increment(ref _count);
                if (value == 1)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(6));
                }
                else if (value == 2)
                {
                    _wait.Set();
                }
            }

            public static int GetCount()
            {
                return _count;
            }

            public static void Reset()
            {
                Interlocked.Exchange(ref _count, 0);
                _wait.Reset();
            }

            public static bool Wait(TimeSpan timeout)
            {
                return _wait.WaitOne(timeout);
            }
        }

        private class BlockingTouchTestHandler : IHandleMessages<TouchTestMessage>
        {
            private static int _count;
            private static readonly AutoResetEvent _wait = new AutoResetEvent(initialState: false);

            private readonly IBus _bus;

            public BlockingTouchTestHandler(IBus bus)
            {
                _bus = bus;
            }

            public void Handle(TouchTestMessage message)
            {
                Interlocked.Increment(ref _count);

                var stopwatch = Stopwatch.StartNew();
                while (stopwatch.Elapsed < TimeSpan.FromSeconds(7))
                {
                    Thread.Sleep(50);
                    _bus.CurrentThreadMessage.Touch();
                }

                _wait.Set();
            }

            public static int GetCount()
            {
                return _count;
            }

            public static void Reset()
            {
                Interlocked.Exchange(ref _count, 0);
                _wait.Reset();
            }

            public static bool Wait(TimeSpan timeout)
            {
                return _wait.WaitOne(timeout);
            }
        }
    }
}


text:
module Faker
  class Games
    class DnD < Base
      class << self
        ##
        # Produces the name of an alignment from Dungeons and Dragons.
        #
        # @return [String]
        #
        # @example
        #   Faker::Games::DnD.alignment #=> "Lawful Neutral"
        #
        # @faker.version 2.13.0
        def alignment
          fetch('dnd.alignments')
        end

        ##
        # Produces the name of a background from Dungeons and Dragons (PHB).
        #
        # @return [String]
        #
        # @example
        #   Faker::Games::DnD.background #=> "Urchin"
        #
        # @faker.version 2.13.0
        def background
          fetch('dnd.backgrounds')
        end

        ##
        # Produces the name of a city from Dungeons and Dragons.
        #
        # @return [String]
        #
        # @example
        #   Faker::Games::DnD.city #=> "Earthfast"
        #
        # @faker.version 2.14.0
        def city
          fetch('dnd.cities')
        end

        ##
        # Produces the name of a class from Dungeons and Dragons (PHB).
        #
        # @return [String]
        #
        # @example
        #   Faker::Games::DnD.klass #=> "Warlock"
        #
        # @faker.version 2.13.0
        def klass
          fetch('dnd.klasses')
        end

        ##
        # Produces the name of a language from Dungeons and Dragons.
        #
        # @return [String]
        #
        # @example
        #   Faker::Games::DnD.language #=> "Gnomish"
        #
        # @faker.version 2.14.0
        def language
          fetch('dnd.languages')
        end

        ##
        # Produces the name of a melee weapon from Dungeons and Dragons.
        #
        # @return [String]
        #
        # @example
        #   Faker::Games::DnD.melee_weapon #=> "Handaxe"
        #
        # @faker.version 2.14.0
        def melee_weapon
          fetch('dnd.melee_weapons')
        end

        ##
        # Produces the name of a monster from Dungeons and Dragons.
        #
        # @return [String]
        #
        # @example
        #   Faker::Games::DnD.monster #=> "Manticore"
        #
        # @faker.version 2.14.0
        def monster
          fetch('dnd.monsters')
        end

        ##
        # Produces the name of a race from Dungeons and Dragons (PHB).
        #
        # @return [String]
        #
        # @example
        #   Faker::Games::DnD.races #=> "Dwarf"
        #
        # @faker.version 2.14.0
        def race
          fetch('dnd.races')
        end

        ##
        # Produces the name of a ranged weapon from Dungeons and Dragons.
        #
        # @return [String]
        #
        # @example
        #   Faker::Games::DnD.ranged_weapon #=> "Shortbow"
        #
        # @faker.version 2.14.0
        def ranged_weapon
          fetch('dnd.ranged_weapons')
        end

        # This method is deprecated. The implementation will be removed in a near future release.
        # Use `DnD.race` instead.
        #
        # @deprecated Use {#race} instead.
        def species
          warn '`DnD.species` is deprecated. Use `DnD.race` instead.'

          super
        end
      end
    end
  end
end


text:
import { getContentSection, getTranslatedContent } from '../content';

describe('getContentSection', function fnDescribe() {
    it('should return a config', function fnIt() {
        expect(
            getContentSection({
                head: {
                    foo: 'bar'
                }
            })('head')
        ).toEqual({ foo: 'bar' });
    });
});

describe('getTranslatedContent', function fnDescribe() {
    it('should return a translated config', function fnIt() {
        const translatedContent = getTranslatedContent(
            'en-EN',
            {
                content: {
                    data: {
                        foo: 'intl-test-1',
                        bar: ['intl-test-2'],
                        foobar: 1,
                        barfoo: 'no-translation-available'
                    }
                },
                'en-en': {
                    data: {
                        'intl-test-1': 'test-1',
                        'intl-test-2': 'test-2'
                    }
                }
            },
            'data'
        );
        expect(translatedContent).toEqual({
            foo: 'test-1',
            bar: ['test-2'],
            foobar: 1,
            barfoo: 'no-translation-available'
        });
    });
});


text:
import os
import sys
import logging
from unittest import TestCase
from nose.tools import ok_, eq_

from checker import *

class OFPTest(TestCase):

    def setUp(self):
        # add cleanup func.
        self.addCleanup(self.cleanups)

        checker_setup(self)
        self.opts = checker_get_opts(self)

        # start
        checker_start_lagopus(self)
        checker_start_datastore(self)
        self.setup_ds()
        checker_start_ofp(self)

    def cleanups(self):
        # stop
        checker_stop_ofp(self)
        checker_stop_datastore(self)
        checker_stop_lagopus(self)

        checker_teardown(self)

    def setup_ds(self):
        e_res = '{"ret":"OK"}'
        dpid = self.opts["switches"]["target"]["dpid"]

        # TODO: type = ethernet-dpdk-phy
        cmds = ["channel channel01 create -dst-addr 127.0.0.1 -protocol tcp",
                "controller controller01 create -channel channel01",
                "interface interface01 create -type ethernet-dpdk-phy "
                "-port-number 0",
                "interface interface02 create -type ethernet-dpdk-phy "
                "-port-number 1",
                "interface interface03 create -type ethernet-dpdk-phy "
                "-port-number 2",
                "port port01 create -interface interface01",
                "port port02 create -interface interface02",
                "port port03 create -interface interface03",
                "bridge bridge01 create -controller controller01 "
                "-port port01 1 -port port02 2 -port port03 3 -dpid 0x1",
                "bridge bridge01 enable"]
        for cmd in cmds:
            datastore_checker_cmd(dpid, cmd, e_res)

    def test_flow(self):
        dpid = self.opts["switches"]["target"]["dpid"]
        dp = ofp_checker_get_dp(dpid)
        ofp = dp.ofproto
        ofp_parser = dp.ofproto_parser

        # send FlowMod.
        match = ofp_parser.OFPMatch(in_port=1, eth_dst="ff:ff:ff:ff:ff:ff")
        actions = [ofp_parser.OFPActionOutput(ofp.OFPP_NORMAL, 0)]
        inst = [ofp_parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS,
                                                 actions)]
        sm = ofp_parser.OFPFlowMod(dp, cookie=0,
                                   cookie_mask=0,
                                   table_id=0,
                                   command=ofp.OFPFC_ADD,
                                   idle_timeout=0,
                                   hard_timeout=0,
                                   priority=10,
                                   buffer_id=ofp.OFP_NO_BUFFER,
                                   out_port=0,
                                   out_group=0,
                                   flags=0,
                                   match=match,
                                   instructions=inst)
        sm = ofp_checker_send_msg(dpid, sm)

        # send FlowStatsRequest.
        sm = ofp_parser.OFPFlowStatsRequest(dp, flags=0,
                                            table_id=ofp.OFPTT_ALL,
                                            out_port=ofp.OFPP_ANY,
                                            out_group=ofp.OFPG_ANY,
                                            cookie=0,
                                            cookie_mask=0,
                                            match=match)
        sm = ofp_checker_send_msg(dpid, sm)

        # recv FlowStatsReply.
        # create expected_msg.
        st = ofp_parser.OFPFlowStats(table_id=0, duration_sec=0,
                                     duration_nsec=0, priority=10,
                                     idle_timeout=0, hard_timeout=0, flags=0,
                                     cookie=0, packet_count=0, byte_count=0,
                                     match=match, instructions=inst)
        st.length = 96
        st._set_targets(["length", "table_id", "priority",
                         "idle_timeout", "hard_timeout", "flags",
                         "cookie", "packet_count", "byte_count",
                         "match", "instructions"])
        em = ofp_parser.OFPFlowStatsReply(dp, body=[st],
                                          flags=0)
        em.type = ofp.OFPMP_FLOW
        em, rm = ofp_checker_recv_msg(dpid, em, None,
                                      sm.xid, 112)

        # send/rcv flow datastore cmd.
        e_res = '''
        {"ret":"OK",
        "data":[{"name":":bridge01",
        "tables":[{
        "flows":[{
        "actions":[{
        "apply_actions":[{"output":"normal"}]}],
        "cookie":0,
        "dl_dst":"ff:ff:ff:ff:ff:ff",
        "hard_timeout":0,
        "idle_timeout":0,
        "in_port":1,
        "priority":10}],
        "table":0}]}]}
        '''
        datastore_checker_cmd(0x01, "flow", e_res)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Contentful.Core.Models
{
    /// <summary>
    /// Represents a single asset of a <see cref="Space"/>.
    /// </summary>
    public class Asset : IContentfulResource, IContent
    {
        /// <summary>
        /// Common system managed metadata properties.
        /// </summary>
        [JsonProperty("sys")]
        public SystemProperties SystemProperties { get; set; }

        /// <summary>
        /// The description of the asset.
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// The title of the asset.
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Encapsulates information about the binary file of the asset.
        /// </summary>
        public File File { get; set; }

        /// <summary>
        /// The titles of the asset per locale.
        /// </summary>
        public Dictionary<string, string> TitleLocalized { get; set; }

        /// <summary>
        /// The descriptions of the asset per locale.
        /// </summary>
        public Dictionary<string, string> DescriptionLocalized { get; set; }

        /// <summary>
        /// Information about the file in respective language.
        /// </summary>
        public Dictionary<string, File> FilesLocalized { get; set; }

        /// <summary>
        /// The system managed metadata of an entry.
        /// </summary>
        public ContentfulMetadata Metadata { get; set; }
    }
}


text:
#include "post.h"

extern char *globNuDir;

void pl_add_post(post_list *in, post *postAdd) { /* set up the new post_list_elem to add */
    post_list_elem *toAdd = malloc(sizeof(post_list_elem));
    toAdd->me = postAdd;
    toAdd->next = NULL; /* check if this is the first post_list_elem in the dictionary */
    if (in->head == NULL) {
        in->head = toAdd;
        in->tail = toAdd;
    } else { /* not the first one */
        (in->tail)->next = toAdd;
        in->tail = toAdd;
    } /* incr length */
    in->length++;
}

post *post_create(const char *in_fpath) {
    const char *temp;
    char *timestamp;
    struct stat inattr, outattr;
    time_t inTime, outTime, tmpTime;
    struct tm *inTime_tm, *createTime;
    post *to = malloc(sizeof(post));

    /* in_fn -- make sure to get the right part */
    to->in_fn = strdup(fileName(in_fpath) + 1);

	/* last modified time and date */
    stat(in_fpath, &inattr);
	inTime = inattr.st_mtime;
	inTime_tm = localtime(&inTime);
	strftime(to->mtime, 11, "%H:%M:%S", inTime_tm);
    strftime(to->mdate, 50, "%B %d, %Y", inTime_tm);

	/* out_loc and is_special */
    to->out_loc = getOutputFileName(to->in_fn, globNuDir, &(to->is_special));
    makeFnSafe(to->out_loc);

    /* delta_time */
	if (stat(to->out_loc, &outattr) != 0) {
	    to->delta_time = 100;
	} else {
	    outTime = outattr.st_mtime;
        to->delta_time = difftime(inTime, outTime);
	}

	/* TODO: Check if output file exists and the LM date of the output
	   if it's more recent compared to this, then don't rebuild it */

	parseFile(in_fpath, to);

	if (to->contents == NULL) {
	    return NULL;
	}

    temp = to->in_fn;
    to->raw_link = strutil_append_no_mutate("raw/", temp);

    if (to->is_special) {
    } else {
        /* timestamp is temp and 10 chars past */
        timestamp = strndup(temp, 10);

        /* creation date */
        time(&tmpTime);
        createTime = localtime(&tmpTime);
        if (strptime(timestamp, "%Y-%m-%d", createTime) != NULL) {
            strftime(to->cdate, 50, "%B %d, %Y", createTime);
        } else {
            fprintf(stderr, "["KRED"ERR"RESET"] Error while parsing time. This should not happen!!\n");
            return NULL;
        }
        free(timestamp);
    }

#ifdef __DEBUG
    printf("Made a new post!\nattr are:\n");
    printf("\tName: %s\n\tRaw link: %s\n\tis special:%d\n\tin fn:%s\n", to->name, to->raw_link, to->is_special, to->in_fn);
/*    printf("\tContents:\n%s", to->contents);*/
#endif
    return to;
}

void post_free(post *in) {
    free(in->name);
    free(in->raw_link);
    string_free(in->contents);
    free(in->in_fn);
    free(in->out_loc);
    free(in);
}

void pl_clean(post_list *in) {
    /* get the first element */
    post_list_elem *curr = in->head;
    post_list_elem *next;

#ifdef __DEBUG
    printf("my size: %d\n", in->length);
#endif

    /* loop through the entire list */
    while (curr != NULL) {
        next = curr->next;
        if (curr->me == NULL) {printf("wtf?...\n"); break;}
        post_free(curr->me);
        free(curr);
        curr = next;
    }

    free(in);
}

post_list *pl_new() {
    /* create a new empty post_list with the right values set
       so that it is ready to be used with other td_ functions */
    post_list *toCreate = malloc(sizeof(post_list));
    toCreate->head = NULL;
    toCreate->tail = NULL;
    toCreate->length = 0;
    return toCreate;
}

int _pl_cmp(const void *one, const void *two) {
    /* returns number > 0 if one is earlier than two */
    char *one_name = (((const post_list_elem *)one)->me)->in_fn;
    char *two_name = (((const post_list_elem *)two)->me)->in_fn;

    while (*one_name != '\0') {
        if (*one_name > *two_name) {
            return -1;
        } else if (*two_name > *one_name) {
            return 1;
        }
        /* they are equal so far, keep going */
        one_name++;
        two_name++;
    }

    if (*two_name != '\0') {
        /* two_name is longer than one_name */
        return 1;
    }

    return 0;
}

post_list_elem *_pl_make_array(post_list *in) {
    post_list_elem *arr, *tmp, *curr, *tmpref;

    arr = malloc(sizeof(post_list_elem) * (in->length));
    curr = in->head;
    tmp = arr;

    while (curr != NULL) {
        tmp->me = curr->me;
        tmpref = curr->next;
        free(curr);
        curr = tmpref;
        tmp++;
    }

    return arr;
}

post_list *_pl_from_array(post_list_elem *in, unsigned int length) {
    post_list_elem *created, *curr;
    post_list *lst;
    unsigned int i;

    lst = pl_new();
    curr = lst->head;

    for (i = 0; i < length; i++) {
        created = malloc(sizeof(post_list_elem));
        created->me = in[i].me;

        if (curr == NULL) {
            lst->head = created;
        } else {
            curr->next = created;
        }
        curr = created;
    }

    lst->tail = created;
    lst->length = length;
    if (created) created->next = NULL;

    free(in);
    return lst;
}

void pl_sort(post_list **in) {
    post_list_elem *arr;
    int length = (*in)->length;

    /* convert the post list to an array, then quicksort it, then convert it
     * back into a list
     */
    arr = _pl_make_array(*in);

    qsort((void*)arr, length, sizeof(post_list_elem), _pl_cmp);

    free(*in);
    *in = _pl_from_array(arr, length);
}


text:
import os

import IECore

import Gaffer
import GafferUI

class ImageReaderPathPreview( GafferUI.DeferredPathPreview ) :

	def __init__( self, path ) :

		self.__renderableGadget = GafferUI.RenderableGadget( None )
		self.__gadgetWidget = GafferUI.GadgetWidget(
			self.__renderableGadget,
			bufferOptions = set( (
				GafferUI.GLWidget.BufferOptions.Depth,
				GafferUI.GLWidget.BufferOptions.Double,
			) ),
		)

		GafferUI.DeferredPathPreview.__init__( self, self.__gadgetWidget, path )

		self._updateFromPath()

	def isValid( self ) :

		if not isinstance( self.getPath(), Gaffer.FileSystemPath ) :
			return False

		ext = os.path.splitext( str( self.getPath() ) )[1]
		if not ext :
			return False

		return ext[1:].lower() in IECore.Reader.supportedExtensions( IECore.TypeId.ImageReader )

	def _load( self ) :

		reader = None
		with IECore.IgnoredExceptions( RuntimeError ) :
			reader = IECore.ImageReader.create( str( self.getPath() ) )

		if reader is None :
			return None

		o = None
		with IECore.IgnoredExceptions( RuntimeError ) :
			o = reader.read()

		if not isinstance( o, IECore.VisibleRenderable ) :
			return None

		if isinstance( o, IECore.ImagePrimitive ) :
			## \todo Deal with colorspace uniformly everywhere, doing the
			# transformations in the viewers themselves.
			IECore.LinearToSRGBOp()( input=o, copyInput=False )

		return o

	def _deferredUpdate( self, o ) :

		self.__renderableGadget.setRenderable( o )

		if isinstance( o, IECore.ImagePrimitive ) :
			camera = IECore.Camera( parameters = { "projection" : "orthographic" } )
		else :
			camera = IECore.Camera( parameters = { "projection" : "perspective" } )

		self.__gadgetWidget.getViewportGadget().setCamera( camera )
		self.__gadgetWidget.getViewportGadget().frame( o.bound(), IECore.V3f( 0, 0, -1 ) )

GafferUI.PathPreviewWidget.registerType( "Preview", ImageReaderPathPreview )


text:
% v2-acmsmall-sample.tex, dated March 6 2012
% This is a sample file for ACM small trim journals
%
% Compilation using 'acmsmall.cls' - version 1.3 (March 2012), Aptara Inc.
% (c) 2010 Association for Computing Machinery (ACM)
%
% Questions/Suggestions/Feedback should be addressed to => "acmtexsupport@aptaracorp.com".
% Users can also go through the FAQs available on the journal's submission webpage.
%
% Steps to compile: latex, bibtex, latex latex
%
% For tracking purposes => this is v1.3 - March 2012

\documentclass[prodmode,acmtecs]{acmsmall} % Aptara syntax

% Package to generate and customize Algorithm as per ACM style
\usepackage[ruled]{algorithm2e}
\renewcommand{\algorithmcfname}{ALGORITHM}
\SetAlFnt{\small}
\SetAlCapFnt{\small}
\SetAlCapNameFnt{\small}
\SetAlCapHSkip{0pt}
\IncMargin{-\parindent}

% Metadata Information
\acmVolume{9}
\acmNumber{4}
\acmArticle{39}
\acmYear{2010}
\acmMonth{3}

% Copyright
\setcopyright{rightsretained}

% DOI
\doi{0000001.0000001}

%ISSN
\issn{1234-56789}

% Document starts
\begin{document}

% Page heads
\markboth{G. Zhou et al.}{A Multifrequency MAC Specially Designed for WSN Applications}

% Title portion
\title{A Multifrequency MAC Specially Designed for Wireless Sensor Network Applications}
\author{GANG ZHOU
\affil{College of William and Mary}
YAFENG WU
\affil{University of Virginia}
TING YAN
\affil{Eaton Innovation Center}
TIAN HE
\affil{University of Minnesota}
CHENGDU HUANG
\affil{Google}
JOHN A. STANKOVIC
\affil{University of Virginia}
TAREK F. ABDELZAHER
\affil{University of Illinois at Urbana-Champaign}}
% NOTE! Affiliations placed here should be for the institution where the
%       BULK of the research was done. If the author has gone to a new
%       institution, before publication, the (above) affiliation should NOT be changed.
%       The authors 'current' address may be given in the "Author's addresses:" block (below).
%       So for example, Mr. Abdelzaher, the bulk of the research was done at UIUC, and he is
%       currently affiliated with NASA.

\begin{abstract}
Multifrequency media access control has been well understood in
general wireless ad hoc networks, while in wireless sensor networks,
researchers still focus on single frequency solutions. In wireless
sensor networks, each device is typically equipped with a single
radio transceiver and applications adopt much smaller packet sizes
compared to those in general wireless ad hoc networks. Hence, the
multifrequency MAC protocols proposed for general wireless ad hoc
networks are not suitable for wireless sensor network applications,
which we further demonstrate through our simulation experiments. In
this article, we propose MMSN, which takes advantage of
multifrequency availability while, at the same time, takes into
consideration the restrictions of wireless sensor networks. Through
extensive experiments, MMSN exhibits the prominent ability to utilize
parallel transmissions among neighboring nodes. When multiple physical
frequencies are available, it also achieves increased energy
efficiency, demonstrating the ability to work against radio
interference and the tolerance to a wide range of measured time
synchronization errors.
\end{abstract}

%
% The code below should be generated by the tool at
% http://dl.acm.org/ccs.cfm
% Please copy and paste the code instead of the example below.
%
\begin{CCSXML}
<ccs2012>
 <concept>
  <concept_id>10010520.10010553.10010562</concept_id>
  <concept_desc>Computer systems organization~Embedded systems</concept_desc>
  <concept_significance>500</concept_significance>
 </concept>
 <concept>
  <concept_id>10010520.10010575.10010755</concept_id>
  <concept_desc>Computer systems organization~Redundancy</concept_desc>
  <concept_significance>300</concept_significance>
 </concept>
 <concept>
  <concept_id>10010520.10010553.10010554</concept_id>
  <concept_desc>Computer systems organization~Robotics</concept_desc>
  <concept_significance>100</concept_significance>
 </concept>
 <concept>
  <concept_id>10003033.10003083.10003095</concept_id>
  <concept_desc>Networks~Network reliability</concept_desc>
  <concept_significance>100</concept_significance>
 </concept>
</ccs2012>
\end{CCSXML}

\ccsdesc[500]{Computer systems organization~Embedded systems}
\ccsdesc[300]{Computer systems organization~Redundancy}
\ccsdesc{Computer systems organization~Robotics}
\ccsdesc[100]{Networks~Network reliability}

%
% End generated code
%

\terms{Design, Algorithms, Performance}

\keywords{Wireless sensor networks, media access control,
multi-channel, radio interference, time synchronization}

\acmformat{Gang Zhou, Yafeng Wu, Ting Yan, Tian He, Chengdu Huang, John A. Stankovic,
and Tarek F. Abdelzaher, 2010. A multifrequency MAC specially
designed for  wireless sensor network applications.}
% At a minimum you need to supply the author names, year and a title.
% IMPORTANT:
% Full first names whenever they are known, surname last, followed by a period.
% In the case of two authors, 'and' is placed between them.
% In the case of three or more authors, the serial comma is used, that is, all author names
% except the last one but including the penultimate author's name are followed by a comma,
% and then 'and' is placed before the final author's name.
% If only first and middle initials are known, then each initial
% is followed by a period and they are separated by a space.
% The remaining information (journal title, volume, article number, date, etc.) is 'auto-generated'.

\begin{bottomstuff}
This work is supported by the National Science Foundation, under
grant CNS-0435060, grant CCR-0325197 and grant EN-CS-0329609.

Author's addresses: G. Zhou, Computer Science Department,
College of William and Mary; Y. Wu  {and} J. A. Stankovic,
Computer Science Department, University of Virginia; T. Yan,
Eaton Innovation Center; T. He, Computer Science Department,
University of Minnesota; C. Huang, Google; T. F. Abdelzaher,
(Current address) NASA Ames Research Center, Moffett Field, California 94035.
\end{bottomstuff}

\maketitle

\section{Introduction}

As a new technology, Wireless Sensor Networks (WSNs) has a wide
range of applications [Culler 2001,Bahl 2002,Akyildiz 2001], including
environment monitoring, smart buildings, medical care, industrial and
military applications. Among them, a recent trend is to develop
commercial sensor networks that require pervasive sensing of both
environment and human beings, for example, assisted living
[Akyildiz 2002,Harvard 2001,CROSSBOW] and smart homes
[Harvard 2001,Adya 2001,CROSSBOW].
% quote
\begin{quote}
``For these applications, sensor devices are incorporated into human
cloths [Natarajan 2001,Zhou 2006,Bahl 2002,Adya 2001] for monitoring
health related information like EKG readings, fall detection, and voice recognition".
\end{quote}
While collecting all these multimedia information
[Akyildiz 2002] requires a high network throughput, off-the-shelf
sensor devices only provide very limited bandwidth in a single
channel: 19.2Kbps in MICA2 [Bahl 2002] and 250Kbps in MICAz.

In this article, we propose MMSN, abbreviation for Multifrequency
Media access control for wireless Sensor Networks. The main
contributions of this work can be summarized as follows.
% itemize
\begin{itemize}
\item To the best of our knowledge, the MMSN protocol is the first
multifrequency MAC protocol especially designed for WSNs, in which
each device is equipped with a single radio transceiver and
the MAC layer packet size is very small.
\item Instead of using pairwise RTS/CTS frequency negotiation
[Adya 2001,Culler 2001; Tzamaloukas 2001; Zhou 2006],
we propose lightweight frequency assignments, which are good choices
for many deployed comparatively static WSNs.
\item We develop new toggle transmission and snooping techniques to
enable a single radio transceiver in a sensor device to achieve
scalable performance, avoiding the nonscalable ``one
control channel + multiple data channels'' design [Natarajan 2001].
\end{itemize}

% Head 1
\section{MMSN Protocol}

% Head 2
\subsection{Frequency Assignment}

We propose a suboptimal distribution to be used by each node, which is
easy to compute and does not depend on the number of competing
nodes. A natural candidate is an increasing geometric sequence, in
which
% Numbered Equation
\begin{equation}
\label{eqn:01}
P(t)=\frac{b^{\frac{t+1}{T+1}}-b^{\frac{t}{T+1}}}{b-1},
\end{equation}
where $t=0,{\ldots}\,,T$, and $b$ is a number greater than $1$.

In our algorithm, we use the suboptimal approach for simplicity and
generality. We need to make the distribution of the selected back-off
time slice at each node conform to what is shown in Equation
(\ref{eqn:01}). It is implemented as follows: First, a random
variable $\alpha$ with a uniform distribution within the interval
$(0, 1)$ is generated on each node, then time slice $i$ is selected
according to the following equation:
% Unnumbered Equation
\[
i=\lfloor(T+1)\log_b[\alpha(b-1)+1]\rfloor.
\]
It can be easily proven that the distribution of $i$ conforms to Equation
(\ref{eqn:01}).

So protocols [Bahl 2002,Culler 2001,Zhou 2006,Adya 2001,Culler 2001;
Tzamaloukas-01; Akyildiz-01] that use RTS/CTS
controls\footnote{RTS/CTS controls are required to be implemented by
802.11-compliant devices. They can be used as an optional mechanism
to avoid Hidden Terminal Problems in the 802.11 standard and
protocols based on those similar to [Akyildiz 2001] and
[Adya 2001].} for frequency negotiation and reservation are not
suitable for WSN applications, even though they exhibit good
performance in general wireless ad hoc
networks.

% Head 3
\subsubsection{Exclusive Frequency Assignment}

In exclusive frequency assignment, nodes first exchange their IDs
among two communication hops so that each node knows its two-hop
neighbors' IDs. In the second broadcast, each node beacons all
neighbors' IDs it has collected during the first broadcast period.

% Head 4
\paragraph{Eavesdropping}

Even though the even selection scheme leads to even sharing of
available frequencies among any two-hop neighborhood, it involves a
number of two-hop broadcasts. To reduce the communication cost, we
propose a lightweight eavesdropping scheme.

\subsection{Basic Notations}

As Algorithm~\ref{alg:one} states, for each frequency
number, each node calculates a random number (${\textit{Rnd}}_{\alpha}$) for
itself and a random number (${\textit{Rnd}}_{\beta}$) for each of its two-hop
neighbors with the same pseudorandom number generator.
% Algorithm
\begin{algorithm}[t]
\SetAlgoNoLine
\KwIn{Node $\alpha$'s ID ($ID_{\alpha}$), and node $\alpha$'s
neighbors' IDs within two communication hops.}
\KwOut{The frequency number ($FreNum_{\alpha}$) node $\alpha$ gets assigned.}
$index$ = 0; $FreNum_{\alpha}$ = -1\;
\Repeat{$FreNum_{\alpha} > -1$}{
        $Rnd_{\alpha}$ = Random($ID_{\alpha}$, $index$)\;
        $Found$ = $TRUE$\;
        \For{each node $\beta$ in $\alpha$'s two communication hops
    }{
      $Rnd_{\beta}$ = Random($ID_{\beta}$, $index$)\;
      \If{($Rnd_{\alpha} < Rnd_{\beta}$) \text{or} ($Rnd_{\alpha}$ ==
          $Rnd_{\beta}$ \text{and} $ID_{\alpha} < ID_{\beta}$)\;
      }{
        $Found$ = $FALSE$; break\;
      }
        }
     \eIf{$Found$}{
           $FreNum_{\alpha}$ = $index$\;
         }{
           $index$ ++\;
     }
      }
\caption{Frequency Number Computation}
\label{alg:one}
\end{algorithm}

Bus masters are divided into two disjoint sets, $\mathcal{M}_{RT}$
and $\mathcal{M}_{NRT}$.
% description
\begin{description}
\item[RT Masters]
$\mathcal{M}_{RT}=\{ \vec{m}_{1},\dots,\vec{m}_{n}\}$ denotes the
$n$ RT masters issuing real-time constrained requests. To model the
current request issued by an $\vec{m}_{i}$ in $\mathcal{M}_{RT}$,
three parameters---the recurrence time $(r_i)$, the service cycle
$(c_i)$, and the relative deadline $(d_i)$---are used, with their
relationships.
\item[NRT Masters]
$\mathcal{M}_{NRT}=\{ \vec{m}_{n+1},\dots,\vec{m}_{n+m}\}$ is a set
of $m$ masters issuing nonreal-time constrained requests. In our
model, each $\vec{m}_{j}$ in $\mathcal{M}_{NRT}$ needs only one
parameter, the service cycle, to model the current request it
issues.
\end{description}

Here, a question may arise, since each node has a global ID. Why
don't we just map nodes' IDs within two hops into a group of
frequency numbers and assign those numbers to all nodes within two
hops?

\section{Simulator}
\label{sec:sim}

If the model checker requests successors of a state which are not
created yet, the state space uses the simulator to create the
successors on-the-fly. To create successor states the simulator
conducts the following steps.
% enumerate
\begin{enumerate}
\item Load state into microcontroller model.
\item Determine assignments needed for resolving nondeterminism.
\item For each assignment.
      \begin{enumerate}
      \item either call interrupt handler or simulate effect of next instruction, or
      \item evaluate truth values of atomic propositions.
      \end{enumerate}
\item Return resulting states.
\end{enumerate}
Figure~\ref{fig:one} shows a typical microcontroller C program that
controls an automotive power window lift. The program is one of the
programs used in the case study described in Section~\ref{sec:sim}.
At first sight, the programs looks like an ANSI~C program. It
contains function calls, assignments, if clauses, and while loops.
% Figure
\begin{figure}
\centerline{\includegraphics{acmsmall-mouse}}
\caption{Code before preprocessing.}
\label{fig:one}
\end{figure}

\subsection{Problem Formulation}

The objective of variable coalescence-based offset assignment is to find
both the coalescence scheme and the MWPC on the coalesced graph. We start
with a few definitions and lemmas for variable coalescence.

% Enunciations
\begin{definition}[Coalesced Node (C-Node)]A C-node is a set of
live ranges (webs) in the AG or IG that are coalesced. Nodes within the same
C-node cannot interfere with each other on the IG. Before any coalescing is
done, each live range is a C-node by itself.
\end{definition}

\begin{definition}[C-AG (Coalesced Access Graph)]The C-AG is the access
graph after node coalescence, which is composed of all C-nodes and C-edges.
\end{definition}

\begin{lemma}
The C-MWPC problem is NP-complete.
\end{lemma}
\begin{proof} C-MWPC can be easily reduced to the MWPC problem assuming a
coalescence graph without any edge or a fully connected interference graph.
Therefore, each C-node is an uncoalesced live range after value separation
and C-PC is equivalent to PC. A fully connected interference graph is made
possible when all live ranges interfere with each other. Thus, the C-MWPC
problem is NP-complete.
\end{proof}

\begin{lemma}[Lemma Subhead]The solution to the C-MWPC problem is no
worse than the solution to the MWPC.
\end{lemma}
\begin{proof}
Simply, any solution to the MWPC is also a solution to the
C-MWPC. But some solutions to C-MWPC may not apply to the MWPC (if any
coalescing were made).
\end{proof}

\section{Performance Evaluation}

During all the experiments, the Geographic Forwarding (GF)
[Akyildiz 2001] routing protocol is used. GF exploits geographic
information of nodes and conducts local data-forwarding to achieve
end-to-end routing. Our simulation is
configured according to the settings in
Table~\ref{tab:one}. Each run lasts for 2 minutes and
repeated 100 times. For each data value we present in the results,
we also give its 90\% confidence interval.
% Table
\begin{table}%
\tbl{Simulation Configuration\label{tab:one}}{%
\begin{tabular}{|l|l|}
\hline
TERRAIN{$^a$}   & (200m$\times$200m) Square\\\hline
Node Number     & 289\\\hline
Node Placement  & Uniform\\\hline
Application     & Many-to-Many/Gossip CBR Streams\\\hline
Payload Size    & 32 bytes\\\hline
Routing Layer   & GF\\\hline
MAC Layer       & CSMA/MMSN\\\hline
Radio Layer     & RADIO-ACCNOISE\\\hline
Radio Bandwidth & 250Kbps\\\hline
Radio Range     & 20m--45m\\\hline
\end{tabular}}
\begin{tabnote}%
\Note{Source:}{This is a table
sourcenote. This is a table sourcenote. This is a table
sourcenote.}
\vskip2pt
\Note{Note:}{This is a table footnote.}
\tabnoteentry{$^a$}{This is a table footnote. This is a
table footnote. This is a table footnote.}
\end{tabnote}%
\end{table}%

\section{Conclusions}

In this article, we develop the first multifrequency MAC protocol for
WSN applications in which each device adopts a
single radio transceiver. The different MAC design requirements for
WSNs and general wireless ad-hoc networks are
compared, and a complete WSN multifrequency MAC design (MMSN) is
put forth. During the MMSN design, we analyze and evaluate different
choices for frequency assignments and also discuss the nonuniform
back-off algorithms for the slotted media access design.

% Start of "Sample References" section

\section{Typical references in new ACM Reference Format}
A paginated journal article \cite{Abril07}, an enumerated
journal article \cite{Cohen07}, a reference to an entire issue \cite{JCohen96},
a monograph (whole book) \cite{Kosiur01}, a monograph/whole book in a series (see 2a in spec. document)
\cite{Harel79}, a divisible-book such as an anthology or compilation \cite{Editor00}
followed by the same example, however we only output the series if the volume number is given
\cite{Editor00a} (so Editor00a's series should NOT be present since it has no vol. no.),
a chapter in a divisible book \cite{Spector90}, a chapter in a divisible book
in a series \cite{Douglass98}, a multi-volume work as book \cite{Knuth97},
an article in a proceedings (of a conference, symposium, workshop for example)
(paginated proceedings article) \cite{Andler79}, a proceedings article
with all possible elements \cite{Smith10}, an example of an enumerated
proceedings article \cite{VanGundy07},
an informally published work \cite{Harel78}, a doctoral dissertation \cite{Clarkson85},
a master's thesis: \cite{anisi03}, an online document / world wide web resource \cite{Thornburg01}, \cite{Ablamowicz07},
\cite{Poker06}, a video game (Case 1) \cite{Obama08} and (Case 2) \cite{Novak03}
and \cite{Lee05} and (Case 3) a patent \cite{JoeScientist001},
work accepted for publication \cite{rous08}, 'YYYYb'-test for prolific author
\cite{SaeediMEJ10} and \cite{SaeediJETC10}. Other cites might contain
'duplicate' DOI and URLs (some SIAM articles) \cite{Kirschmer:2010:AEI:1958016.1958018}.
Boris / Barbara Beeton: multi-volume works as books
\cite{MR781536} and \cite{MR781537}.

% Appendix
\appendix
\section*{APPENDIX}
\setcounter{section}{1}
In this appendix, we measure
the channel switching time of Micaz [CROSSBOW] sensor devices.
In our experiments, one mote alternatingly switches between Channels
11 and 12. Every time after the node switches to a channel, it sends
out a packet immediately and then changes to a new channel as soon
as the transmission is finished. We measure the
number of packets the test mote can send in 10 seconds, denoted as
$N_{1}$. In contrast, we also measure the same value of the test
mote without switching channels, denoted as $N_{2}$. We calculate
the channel-switching time $s$ as
\begin{eqnarray}%
s=\frac{10}{N_{1}}-\frac{10}{N_{2}}. \nonumber
\end{eqnarray}%
By repeating the experiments 100 times, we get the average
channel-switching time of Micaz motes: 24.3$\mu$s.

\appendixhead{ZHOU}

% Acknowledgments
\begin{acks}
The authors would like to thank Dr. Maura Turolla of Telecom
Italia for providing specifications about the application scenario.
\end{acks}

% Bibliography
\bibliographystyle{ACM-Reference-Format-Journals}
\bibliography{acmsmall-sample-bibfile}
                             % Sample .bib file with references that match those in
                             % the 'Specifications Document (V1.5)' as well containing
                             % 'legacy' bibs and bibs with 'alternate codings'.
                             % Gerry Murray - March 2012

% History dates
\received{February 2007}{March 2009}{June 2009}

% Electronic Appendix
\elecappendix

\medskip

\section{This is an example of Appendix section head}

Channel-switching time is measured as the time length it takes for
motes to successfully switch from one channel to another. This
parameter impacts the maximum network throughput, because motes
cannot receive or send any packet during this period of time, and it
also affects the efficiency of toggle snooping in MMSN, where motes
need to sense through channels rapidly.

By repeating experiments 100 times, we get the average
channel-switching time of Micaz motes: 24.3 $\mu$s. We then conduct
the same experiments with different Micaz motes, as well as
experiments with the transmitter switching from Channel 11 to other
channels. In both scenarios, the channel-switching time does not have
obvious changes. (In our experiments, all values are in the range of
23.6 $\mu$s to 24.9 $\mu$s.)

\section{Appendix section head}

The primary consumer of energy in WSNs is idle listening. The key to
reduce idle listening is executing low duty-cycle on nodes. Two
primary approaches are considered in controlling duty-cycles in the
MAC layer.

\end{document}
% End of v2-acmsmall-sample.tex (March 2012) - Gerry Murray, ACM


text:
package com.hazelcast.cache.impl.journal;

import com.hazelcast.config.CacheSimpleConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.EventJournalConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.internal.journal.EventJournalReader;
import com.hazelcast.journal.AbstractEventJournalBounceTest;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.SlowTest;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import javax.cache.Cache;

/**
 * Cache event journal read bouncing test
 */
@RunWith(HazelcastSerialClassRunner.class)
@Category(SlowTest.class)
public class CacheEventJournalBounceTest extends AbstractEventJournalBounceTest {
    private static final String TEST_CACHE_NAME = "eventJournalTestCache";
    private static final int COUNT_ENTRIES = 100000;

    @Override
    protected void fillDataStructure(HazelcastInstance instance) {
        final Cache<String, Integer> cache = instance.getCacheManager().getCache(TEST_CACHE_NAME);

        for (int i = 0; i < COUNT_ENTRIES; i++) {
            cache.put("name" + i, i);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected <T> EventJournalReader<T> getEventJournalReader(HazelcastInstance instance) {
        return (EventJournalReader<T>) instance.getCacheManager().getCache(TEST_CACHE_NAME);
    }

    @Override
    protected Config getConfig() {
        final CacheSimpleConfig cacheConfig = new CacheSimpleConfig()
                .setName(TEST_CACHE_NAME);
        cacheConfig.getEvictionConfig().setSize(Integer.MAX_VALUE);
        Config config = super.getConfig()
                             .addCacheConfig(cacheConfig);

        config.getCacheConfig(TEST_CACHE_NAME)
              .setEventJournalConfig(new EventJournalConfig().setEnabled(true)
                                                             .setCapacity(10000));
        return config;
    }
}


text:
import reducer from './reducer'
import * as actions from './actions'

export { reducer, actions };


text:
> see https://aka.ms/autorest

This is the AutoRest configuration file for IotHub.

---
## Getting Started
To build the SDK for IotHub, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`
---

## Configuration

### Basic Information
These are the global settings for the IotHub API.

``` yaml
openapi-type: arm
tag: package-2017-07
```

### Tag: package-2017-07

These settings apply only when `--tag=package-2017-07` is specified on the command line.

``` yaml $(tag) == 'package-2017-07'
input-file:
- Microsoft.Devices/2017-07-01/iothub.json
```

### Tag: package-2017-01

These settings apply only when `--tag=package-2017-01` is specified on the command line.

``` yaml $(tag) == 'package-2017-01'
input-file:
- Microsoft.Devices/2017-01-19/iothub.json
```

### Tag: package-2016-02

These settings apply only when `--tag=package-2016-02` is specified on the command line.

``` yaml $(tag) == 'package-2016-02'
input-file:
- Microsoft.Devices/2016-02-03/iothub.json
```

---
# Code Generation

## C#

These settings apply only when `--csharp` is specified on the command line.
Please also specify `--csharp-sdks-folder=<path to "SDKs" directory of your azure-sdk-for-net clone>`.

``` yaml $(csharp)
csharp:
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: Microsoft.Azure.Management.IotHub
  output-folder: $(csharp-sdks-folder)/IotHub/Management.IotHub/Generated
  clear-output-folder: true
```