text:
package com.fangzhou.manatee.web.rest;

import com.fangzhou.manatee.ManateeApp;
import com.fangzhou.manatee.domain.Staff;
import com.fangzhou.manatee.repository.StaffRepository;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.Matchers.hasItem;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
 * Test class for the StaffResource REST controller.
 *
 * @see StaffResource
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ManateeApp.class)
@WebAppConfiguration
@IntegrationTest
public class StaffResourceIntTest {

    private static final String DEFAULT_NAME = "AAAAA";
    private static final String UPDATED_NAME = "BBBBB";
    private static final String DEFAULT_ROLE = "AAAAA";
    private static final String UPDATED_ROLE = "BBBBB";

    @Inject
    private StaffRepository staffRepository;

    @Inject
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Inject
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    private MockMvc restStaffMockMvc;

    private Staff staff;

    @PostConstruct
    public void setup() {
        MockitoAnnotations.initMocks(this);
        StaffResource staffResource = new StaffResource();
        ReflectionTestUtils.setField(staffResource, "staffRepository", staffRepository);
        this.restStaffMockMvc = MockMvcBuilders.standaloneSetup(staffResource)
            .setCustomArgumentResolvers(pageableArgumentResolver)
            .setMessageConverters(jacksonMessageConverter).build();
    }

    @Before
    public void initTest() {
        staff = new Staff();
        staff.setName(DEFAULT_NAME);
        staff.setRole(DEFAULT_ROLE);
    }

    @Test
    @Transactional
    public void createStaff() throws Exception {
        int databaseSizeBeforeCreate = staffRepository.findAll().size();

        // Create the Staff

        restStaffMockMvc.perform(post("/api/staff")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(staff)))
                .andExpect(status().isCreated());

        // Validate the Staff in the database
        List<Staff> staff = staffRepository.findAll();
        assertThat(staff).hasSize(databaseSizeBeforeCreate + 1);
        Staff testStaff = staff.get(staff.size() - 1);
        assertThat(testStaff.getName()).isEqualTo(DEFAULT_NAME);
        assertThat(testStaff.getRole()).isEqualTo(DEFAULT_ROLE);
    }

    @Test
    @Transactional
    public void getAllStaff() throws Exception {
        // Initialize the database
        staffRepository.saveAndFlush(staff);

        // Get all the staff
        restStaffMockMvc.perform(get("/api/staff?sort=id,desc"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.[*].id").value(hasItem(staff.getId().intValue())))
                .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
                .andExpect(jsonPath("$.[*].role").value(hasItem(DEFAULT_ROLE.toString())));
    }

    @Test
    @Transactional
    public void getStaff() throws Exception {
        // Initialize the database
        staffRepository.saveAndFlush(staff);

        // Get the staff
        restStaffMockMvc.perform(get("/api/staff/{id}", staff.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.id").value(staff.getId().intValue()))
            .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()))
            .andExpect(jsonPath("$.role").value(DEFAULT_ROLE.toString()));
    }

    @Test
    @Transactional
    public void getNonExistingStaff() throws Exception {
        // Get the staff
        restStaffMockMvc.perform(get("/api/staff/{id}", Long.MAX_VALUE))
                .andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    public void updateStaff() throws Exception {
        // Initialize the database
        staffRepository.saveAndFlush(staff);
        int databaseSizeBeforeUpdate = staffRepository.findAll().size();

        // Update the staff
        Staff updatedStaff = new Staff();
        updatedStaff.setId(staff.getId());
        updatedStaff.setName(UPDATED_NAME);
        updatedStaff.setRole(UPDATED_ROLE);

        restStaffMockMvc.perform(put("/api/staff")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(updatedStaff)))
                .andExpect(status().isOk());

        // Validate the Staff in the database
        List<Staff> staff = staffRepository.findAll();
        assertThat(staff).hasSize(databaseSizeBeforeUpdate);
        Staff testStaff = staff.get(staff.size() - 1);
        assertThat(testStaff.getName()).isEqualTo(UPDATED_NAME);
        assertThat(testStaff.getRole()).isEqualTo(UPDATED_ROLE);
    }

    @Test
    @Transactional
    public void deleteStaff() throws Exception {
        // Initialize the database
        staffRepository.saveAndFlush(staff);
        int databaseSizeBeforeDelete = staffRepository.findAll().size();

        // Get the staff
        restStaffMockMvc.perform(delete("/api/staff/{id}", staff.getId())
                .accept(TestUtil.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk());

        // Validate the database is empty
        List<Staff> staff = staffRepository.findAll();
        assertThat(staff).hasSize(databaseSizeBeforeDelete - 1);
    }
}


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

    angular
        .module('editor')
        .factory('menu', menu);

    menu.$inject = ['canvas', 'presentation'];

    function menu(canvas, presentation) {

        var service = {
            addText: addText,
            addIframe: addIframe,
            addSlide: addSlide,
            getSlides: getSlides,
            getSelectedElement: getSelectedElement,
            setTextAlign: setTextAlign,
            removeSlide: removeSlide,
            removeElement: removeElement
        };

        return service;

        function removeElement(){
            presentation.removeElement(canvas.getSelectedElement());
            canvas.removeSelectedElement();
        }

        function addIframe(){
            presentation.addIframe();
        }

        function addText() {
            presentation.addText();

        }

        function getSelectedElement() {
            return canvas.getSelectedElement();
        }

        function getSlides(){
            return presentation.getSlides();
        }

        function addSlide(){
            presentation.addSlide();
        }

        function removeSlide(){
            presentation.removeSlide();
        }

        function setTextAlign(align, selectedElement){
            presentation.setTextAlign(align, selectedElement);
        }
    }
})();

redpajama_set_name: RedPajamaGithub


text:
1. IDE like *Eclipse* or *Android Studio*
2. Download [Android SDK](http://developer.android.com/sdk/installing/adding-packages.html)

#### Steps to build from source using Eclipse
1. Download *No Root Dpad* source code (either by [cloning](https://help.github.com/articles/fetching-a-remote/#clone) or by [downloading source files](https://github.com/annelagang/No-Root-Dpad/archive/master.zip))
2. From the *dependencies* folder, unzip locale-api.
3. Import *locale-api* (from the locale-api zip file in dependencies folder) as Android project.
4. Import *No Root Dpad* as Android project.
5. To reference to *locale-api* library:
    1. Right click *No Root Dpad* project.
    2. Choose *Properties* > *Android*.
    3. Under *Library*, add *locale-api* the click *Apply*.
    4. Click *Ok* to close Properties dialog.

**Note:** Android Studio steps to follow


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

namespace BookLibrary
{
    class Library
    {
        public string name { get; set; }
        public List<Book> books { get; set; }

    }
}


text:
package com.google.security.zynamics.reil.translators.arm;

import com.google.security.zynamics.reil.ReilHelpers;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.translators.IInstructionTranslator;
import com.google.security.zynamics.reil.translators.ITranslationEnvironment;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.TranslationHelpers;
import com.google.security.zynamics.zylib.disassembly.IInstruction;

import java.util.List;

public class ARMBxjTranslator implements IInstructionTranslator {
  /**
   * BXJ{<cond>} <Rm>
   *
   * if ConditionPassed(cond) then if (JE bit of Main Configuration register) == 0 then T Flag =
   * Rm[0] PC = Rm AND 0xFFFFFFFE else jpc = SUB-ARCHITECTURE DEFINED value invalidhandler =
   * SUB-ARCHITECTURE DEFINED value if (Jazelle Extension accepts opcode at jpc) then if (CV bit of
   * Jazelle OS Control register) == 0 then PC = invalidhandler else J Flag = 1 Start opcode
   * execution at jpc else if ((CV bit of Jazelle OS Control register) == 0) AND (IMPLEMENTATION
   * DEFINED CONDITION) then PC = invalidhandler else // Subject to SUB-ARCHITECTURE DEFINED
   * restrictions on Rm: T Flag = Rm[0] PC = Rm AND 0xFFFFFFFE
   */
  @Override
  public void translate(final ITranslationEnvironment environment, final IInstruction instruction,
      final List<ReilInstruction> instructions) throws InternalTranslationException {
    TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "BXJ");

    final long baseOffset = ReilHelpers.nextReilAddress(instruction, instructions);

    instructions.add(ReilHelpers.createUnknown(baseOffset));
  }
}


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * @see BxDolMenu
 */
class BxTemplMenu extends BxBaseMenu
{
    public function __construct ($aObject, $oTemplate = false)
    {
        parent::__construct ($aObject, $oTemplate);
    }
}

/** @} */


text:
import React from 'react';
global.React = React;

import _ from 'lodash';
global._ = _;

import $ from 'jquery';
global.$ = $;

import classNames from 'classnames';
global.classNames = classNames;

import sinon from 'sinon';
global.sinon = sinon;

const Hound = window.Hound = global.Hound = {
  settings: {
    placeholder: "placeholder"
  }
};

// Make Enzyme functions available in all test files without importing
import Enzyme, { shallow, render, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

global.shallow = shallow;
global.render = render;
global.mount = mount;

// Define window alert because jsdom no longer defines it
window.alert = _.noop;


text:
<!DOCTYPE html>

		<title>Victoria Sardelli</title>
		<link href="css/personal_head_foot1.css" type="text/css" rel="stylesheet" />
		<link href="css/personal_about_gen1.css" type="text/css" rel="stylesheet" />

Victoria Sardelli

Education

Work Experience

Projects

vlsardelli@outlook.com

Hey there! I'm Tori, and I am pursuing a Computer Science Major and Japanese language Minor at Rochester Institute of Technology.
				   I have a wide range of interests, but I'm currently focusing on language science, Japanese, and self-studying Haskell.

				<fieldset>
					<legend>Quick Facts</legend>

							Full Name:
							Victoria Lauren Millare Sardelli

							College:
							Rochester Institute of Technology

							Major:
							Computer Science

							Minor:
							Japanese

							Language Experience:
							C, Java, Python, html/css

				</fieldset>

Education

					School
					Graduation Year
					GPA
					Misc.

					Rochester Institute of Techonology
					2018/19 (tentative)
					3.76 (tentative)
					Dean's List (1st year: 1st and 2nd semester)

					West Babylon Senior High School
					2014
					104.2/100.00 (weighted)
					Diploma with Advanced Regents with Honors

					   Class Rank: 7/362

Work Experience

					Organization
					Title
					Duties
					Dates of Employment

					West Babylon Public Library
					Page
					Shelving books/DVDs, setting up program rooms, making reminder calls, and completing check-ins
					    for programs
					August 2013 - October 2013

					Town of Babylon Town Hall
					Citizen Services Dept. Intern
					Answered constituent complaint calls for the Citizen Services Department of Town Hall and entered them into the database.
					    Filing for the town government's health benefits department.
					June 2013 - August 2013

Projects

			<fieldset>
				<legend>Flashcard Program</legend>

Description: a basic flashcard program using python and tkinter.

Why I made it: I wanted to create online flashcards to review my Japanese vocab! Of course,
				      I could've used an already-made, more sophisticated app...but that's not as much fun! :)
				      Check it out here:
				      Flashcards

			</fieldset>

For the most current info on my projects, please feel free to check out
			   my Github page!

Let's be social!

Email: vlsardelli@outlook.com


text:
<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:icon="@android:drawable/ic_menu_camera" android:title="@string/TakePicture" android:id="@+id/TakePicture_id"></item>
<!--     <item android:icon="@android:drawable/ic_menu_video" android:title="@string/TakeVideo" android:id="@+id/TakeVideo_id"></item> -->
</menu>


text:
package org.jetbrains.annotations;

import com.intellij.util.concurrency.annotations.RequiresBackgroundThread;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Used to indicate that a method should be called in background thread
 * @deprecated Use {@link RequiresBackgroundThread}.
 */
@Deprecated(forRemoval = true)
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
public @interface CalledInBackground {
  boolean instrument() default true;
}


text:
module ApiUtil
  def get_and_parse(url, params)
    parse_result RestClient.get url, :params => params
  end
  module_function :get_and_parse

  def post_and_parse(url, params)
    parse_result RestClient.post url, params
  end
  module_function :post_and_parse

  def post_json(url, params)
    parse_result RestClient.post url, params.to_json, content_type: :json
  end
  module_function :post_json

  def parse_result(result)
    underscore_keys_recursive JSON.parse result
  end
  module_function :parse_result

  def underscore_keys_recursive(obj)
    if obj.is_a?(Hash)
      out = {}
      obj.each do |k, v|
        out[k.to_s.underscore.to_sym] = underscore_keys_recursive v
      end
      out
    elsif obj.is_a?(Array)
      out = []
      obj.each do |v|
        out.push underscore_keys_recursive v
      end
      out
    else
      obj
    end
  end
  module_function :underscore_keys_recursive
end


text:
package store

import (
	"sync"
	"sync/atomic"
	"time"

	"github.com/cloudfoundry/gosigar"
	"github.com/ricochet2200/go-disk-usage/du"
	"go.uber.org/zap"
)

type groupWatcherState struct {
	interval                   int
	diskFreeDisableThreshold   uint64
	diskFreeReenableThreshold  uint64
	diskUsageDisableThreshold  float64
	diskUsageReenableThreshold float64
	diskFree                   uint64
	diskUsed                   uint64
	diskSize                   uint64
	diskFreeTOC                uint64
	diskUsedTOC                uint64
	diskSizeTOC                uint64
	memFreeDisableThreshold    uint64
	memFreeReenableThreshold   uint64
	memUsageDisableThreshold   float64
	memUsageReenableThreshold  float64
	memFree                    uint64
	memUsed                    uint64
	memSize                    uint64

	startupShutdownLock sync.Mutex
	notifyChan          chan *bgNotification
}

func (store *defaultGroupStore) watcherConfig(cfg *GroupStoreConfig) {
	store.watcherState.interval = 60
	store.watcherState.diskFreeDisableThreshold = cfg.DiskFreeDisableThreshold
	store.watcherState.diskFreeReenableThreshold = cfg.DiskFreeReenableThreshold
	store.watcherState.diskUsageDisableThreshold = cfg.DiskUsageDisableThreshold
	store.watcherState.diskUsageReenableThreshold = cfg.DiskUsageReenableThreshold
	store.watcherState.memFreeDisableThreshold = cfg.MemFreeDisableThreshold
	store.watcherState.memFreeReenableThreshold = cfg.MemFreeReenableThreshold
	store.watcherState.memUsageDisableThreshold = cfg.MemUsageDisableThreshold
	store.watcherState.memUsageReenableThreshold = cfg.MemUsageReenableThreshold
}

func (store *defaultGroupStore) watcherStartup() {
	store.watcherState.startupShutdownLock.Lock()
	if store.watcherState.notifyChan == nil {
		store.watcherState.notifyChan = make(chan *bgNotification, 1)
		go store.watcherLauncher(store.watcherState.notifyChan)
	}
	store.watcherState.startupShutdownLock.Unlock()
}

func (store *defaultGroupStore) watcherShutdown() {
	store.watcherState.startupShutdownLock.Lock()
	if store.watcherState.notifyChan != nil {
		c := make(chan struct{}, 1)
		store.watcherState.notifyChan <- &bgNotification{
			action:   _BG_DISABLE,
			doneChan: c,
		}
		<-c
		store.watcherState.notifyChan = nil
	}
	store.watcherState.startupShutdownLock.Unlock()
}

func (store *defaultGroupStore) watcherLauncher(notifyChan chan *bgNotification) {
	interval := float64(store.watcherState.interval) * float64(time.Second)
	store.randMutex.Lock()
	nextRun := time.Now().Add(time.Duration(interval + interval*store.rand.NormFloat64()*0.1))
	store.randMutex.Unlock()
	disabled := false
	running := true
	for running {
		var notification *bgNotification
		sleep := nextRun.Sub(time.Now())
		if sleep > 0 {
			select {
			case notification = <-notifyChan:
			case <-time.After(sleep):
			}
		} else {
			select {
			case notification = <-notifyChan:
			default:
			}
		}
		store.randMutex.Lock()
		nextRun = time.Now().Add(time.Duration(interval + interval*store.rand.NormFloat64()*0.1))
		store.randMutex.Unlock()
		if notification != nil {
			if notification.action == _BG_DISABLE {
				running = false
			} else {
				store.logger.Error("invalid action requested", zap.String("name", store.loggerPrefix+"watcher"), zap.Int("action", int(notification.action)))
			}
			notification.doneChan <- struct{}{}
			continue
		}
		u := du.NewDiskUsage(store.path)
		utoc := u
		if store.pathtoc != store.path {
			utoc = du.NewDiskUsage(store.pathtoc)
		}
		diskFree := u.Free()
		diskUsed := u.Used()
		diskSize := u.Size()
		diskUsage := float64(u.Usage())
		diskFreeTOC := utoc.Free()
		diskUsedTOC := utoc.Used()
		diskSizeTOC := utoc.Size()
		diskUsageTOC := float64(utoc.Usage())
		atomic.StoreUint64(&store.watcherState.diskFree, diskFree)
		atomic.StoreUint64(&store.watcherState.diskUsed, diskUsed)
		atomic.StoreUint64(&store.watcherState.diskSize, diskSize)
		atomic.StoreUint64(&store.watcherState.diskFreeTOC, diskFreeTOC)
		atomic.StoreUint64(&store.watcherState.diskUsedTOC, diskUsedTOC)
		atomic.StoreUint64(&store.watcherState.diskSizeTOC, diskSizeTOC)
		store.logger.Debug("diskStat", zap.String("name", store.loggerPrefix+"watcher"), zap.Uint64("diskFree", diskFree), zap.Uint64("diskUsed", diskUsed), zap.Uint64("diskSize", diskSize), zap.Float64("diskUsage", float64(diskUsage)*100), zap.Uint64("diskFreeTOC", diskFreeTOC), zap.Uint64("diskUsedTOC", diskUsedTOC), zap.Uint64("diskSizeTOC", diskSizeTOC), zap.Float64("diskUsageTOC", float64(diskUsageTOC)*100))
		m := &sigar.Mem{}
		var memUsage float64
		if err := m.Get(); err != nil {
			m = nil
			store.logger.Debug("could not stat memory", zap.String("name", store.loggerPrefix+"watcher"), zap.Error(err))
		} else {
			memUsage = float64(m.ActualUsed) / float64(m.Total)
			atomic.StoreUint64(&store.watcherState.memFree, m.ActualFree)
			atomic.StoreUint64(&store.watcherState.memUsed, m.ActualUsed)
			atomic.StoreUint64(&store.watcherState.memSize, m.Total)
			store.logger.Debug("memStat", zap.String("name", store.loggerPrefix+"watcher"), zap.Uint64("actualFree", m.ActualFree), zap.Uint64("actualUsed", m.ActualUsed), zap.Uint64("total", m.Total), zap.Float64("usage", memUsage*100))
		}
		var wantToDisable string
		var wantToReenable string
		if store.watcherState.diskFreeDisableThreshold > 1 && (diskFree <= store.watcherState.diskFreeDisableThreshold || diskFreeTOC <= store.watcherState.diskFreeDisableThreshold) {
			wantToDisable = "passed the disk free threshold for automatic disabling"
		}
		if store.watcherState.diskUsageDisableThreshold > 0 && (diskUsage >= store.watcherState.diskUsageDisableThreshold || diskUsageTOC >= store.watcherState.diskUsageDisableThreshold) {
			wantToDisable = "passed the disk usage threshold for automatic disabling"
		}
		if store.watcherState.memFreeDisableThreshold > 1 && m != nil && m.ActualFree <= store.watcherState.memFreeDisableThreshold {
			wantToDisable = "passed the mem free threshold for automatic disabling"
		}
		if store.watcherState.memUsageDisableThreshold > 0 && m != nil && memUsage >= store.watcherState.memUsageDisableThreshold {
			wantToDisable = "passed the mem usage threshold for automatic disabling"
		}
		if store.watcherState.diskFreeReenableThreshold > 1 && diskFree >= store.watcherState.diskFreeReenableThreshold && diskFreeTOC >= store.watcherState.diskFreeReenableThreshold {
			wantToReenable = "passed the disk free threshold for automatic re-enabling"
		}
		if store.watcherState.diskUsageReenableThreshold > 0 && diskUsage <= store.watcherState.diskUsageReenableThreshold && diskUsageTOC <= store.watcherState.diskUsageReenableThreshold {
			wantToReenable = "passed the disk usage threshold for automatic re-enabling"
		}
		if store.watcherState.memFreeReenableThreshold > 1 && m != nil && m.ActualFree >= store.watcherState.memFreeReenableThreshold {
			wantToReenable = "passed the mem free threshold for automatic re-enabling"
		}
		if store.watcherState.memUsageReenableThreshold > 0 && m != nil && memUsage <= store.watcherState.memUsageReenableThreshold {
			wantToReenable = "passed the mem usage threshold for automatic re-enabling"
		}
		if wantToDisable != "" {
			if !disabled {
				store.logger.Error(wantToDisable, zap.String("name", store.loggerPrefix+"watcher"))
				store.disableWrites(false) // false indicates non-user call
				disabled = true
			}
		} else if wantToReenable != "" {
			if disabled {
				store.logger.Error(wantToReenable, zap.String("name", store.loggerPrefix+"watcher"))
				store.enableWrites(false)
				disabled = false
			}
		}
	}
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.resthub.web.support Class Hierarchy (RESThub Spring stack 2.2.0-SNAPSHOT API)</title>
<meta name="date" content="2014-09-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.resthub.web.support

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.ning.http.client.AsyncCompletionHandler<T> (implements com.ning.http.client.AsyncHandler<T>, com.ning.http.client.ProgressAsyncHandler<T>)

org.resthub.web.support.AsyncEntityHandler

org.resthub.web.support.JsonBodyReader (implements org.resthub.web.support.BodyReader)

org.resthub.web.support.JsonBodyWriter (implements org.resthub.web.support.BodyWriter)

org.resthub.web.support.XmlBodyReader (implements org.resthub.web.support.BodyReader)

org.resthub.web.support.XmlBodyWriter (implements org.resthub.web.support.BodyWriter)

Interface Hierarchy

org.resthub.web.support.BodyReader

org.resthub.web.support.BodyWriter

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2009–2014. All rights reserved.


text:
package org.apache.isis.viewer.wicket.model.mementos;

import java.io.Serializable;

import org.apache.isis.core.metamodel.spec.ObjectSpecId;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.metamodel.spec.feature.OneToManyAssociation;
import org.apache.isis.core.metamodel.specloader.SpecificationLoader;
import org.apache.isis.core.runtime.system.session.IsisSessionFactory;

/**
 * {@link Serializable} representation of a {@link OneToManyAssociation} (a
 * parented collection of entities).
 */
public class CollectionMemento implements Serializable {

    private static final long serialVersionUID = 1L;

    private static ObjectSpecification owningSpecFor(
            final OneToManyAssociation association,
            final IsisSessionFactory isisSessionFactory) {
        final SpecificationLoader specificationLoader = isisSessionFactory.getSpecificationLoader();
        return specificationLoader.loadSpecification(association.getIdentifier().toClassIdentityString());
    }

    private final ObjectSpecId owningType;
    private final String id;

    private transient OneToManyAssociation collection;

    public CollectionMemento(
            final ObjectSpecId owningType,
            final String id, final SpecificationLoader specificationLoader) {
        this(owningType, id, collectionFor(owningType, id, specificationLoader));
    }

    public CollectionMemento(final OneToManyAssociation collection, final IsisSessionFactory isisSessionFactory) {
        this(owningSpecFor(collection, isisSessionFactory).getSpecId(), collection.getIdentifier().toNameIdentityString(), collection);
    }

    private CollectionMemento(final ObjectSpecId owningType, final String id, final OneToManyAssociation collection) {
        this.owningType = owningType;
        this.id = id;
        this.collection = collection;
    }

    public ObjectSpecId getOwningType() {
        return owningType;
    }

    /**
     * Only applies to parented collections, being the id of the collection in
     * the parent (eg <tt>lineItems</tt>).
     *
     * <p>
     * Will return <tt>null</tt> otherwise.
     */
    public String getId() {
        return id;
    }

    public String getName(final SpecificationLoader specificationLoader) {
        return getCollection(specificationLoader).getName();
    }

    public OneToManyAssociation getCollection(final SpecificationLoader specificationLoader) {
        if (collection == null) {
            collection = collectionFor(owningType, id, specificationLoader);
        }
        return collection;
    }

    private static OneToManyAssociation collectionFor(
            ObjectSpecId owningType,
            String id,
            final SpecificationLoader specificationLoader) {
        return (OneToManyAssociation) SpecUtils.getSpecificationFor(owningType, specificationLoader).getAssociation(id);
    }

}


text:
Configuration files for my openHAB2 installation. Including Modbus communication with Nilan(R) heatpump and Astro bindings.

## Installed Bindings

### Astro

* [org.openhab.binding.astro](https://github.com/openhab/openHAB2-addons/tree/master/addons/binding/org.openhab.binding.astro)

### Modbus - Nilan(R) heatpump Comfort 300 Top (cts-602 control board)

* [Product documentation](http://www.nilan.de/startseite/losungen/wohnungslosungen/luftung/comfort-serien/comfort-300-top)
* [Modbus documentation](http://reader.livedition.dk/nilan/272/)

### Harmony Hub Binding

* [Harmony Hub Binding documentation](https://www.openhab.org/addons/bindings/harmonyhub/)

### GPIO Binding

* [GPIO Binding documentation](https://www.openhab.org/addons/bindings/gpio1/)

### Kodi Binding

* [Kodi Binding documentation](https://www.openhab.org/addons/bindings/kodi/)

## Installed Persistence

* [RRD4j Persistence](http://docs.openhab.org/addons/persistence/rrd4j/readme.html)

## Installed Transformations

* [Map Transformation](https://github.com/openhab/openhab1-addons/wiki/Transformations)
* [Javascript Transformation](https://github.com/openhab/openhab1-addons/wiki/Transformations)

## Installed UIs

* Basic UI
* HABot
* HABPanel
* Home Builder
* Paper UI

## Quick Setup

Copy config files from openhab2 folder into your openHAB2 installation (i.e. /etc/openhab2)

## Details

Some details how I created my config-files.

* Create nilan heatpump modbus items out of csv file / nilan documentation
```sh
$ cd /etc/openHAB2/scripts
$ python createNilanItems.py > ../items/nilan.items
```
* Add modbus address binding according to nilan address-specifications and the configuration in services/modbus.cfg
* Add Items into your main.sitemap file.

## Some issues due to early adopting modbus plugin 1.10.0-SNAPSHOT

If modbus plugin not already >= v1.10.0.201704100111 (build #1457 or greater) [download](https://openhab.ci.cloudbees.com/job/openHAB1-Addons/lastSuccessfulBuild/artifact/bundles/binding/org.openhab.binding.modbus/target) and copy plugin to /usr/share/openhab2/addons

If modbus communication isn't working see [issue](https://github.com/openhab/openhab2-addons/pull/362/#issuecomment-173125977).

```openhab2-console
feature:install openhab-transport-serial
```

## Other useful links

* <https://github.com/nickma82/nilan_communication_bringup>
* <https://community.openhab.org/t/openhab1-nilan-heatpump/23538>
* <https://github.com/roggmaeh/nilan-openhab>
* <https://github.com/openhab/openhab1-addons/wiki/Samples-Binding-Config#serial-modbus-nilan-heatpump-configuration>


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <sys/types.h>

#ifdef DG_DIAGNOSE
#include "diagnose/dg.h"
#endif

#include "n_srm.h"
#include "srm2api.h"
#include "srm_soap27.h"

#include "constants.h"
#include "i18.h"
#include "sysdep.h"             /* BOOL, STD_BUF, ... */

#include "free.h"               /* FREE(), DELETE() */
#include "str.h"		/* dq_param() */

#include <iostream>             /* std::string, cout, endl, ... */
#include <sstream>              /* ostringstream */

using namespace std;

/*
 * srmGetRequestSummary request constuctor
 */
srmGetRequestSummary::srmGetRequestSummary()
{
  init();
}

/*
 * Initialise srmGetRequestSummary request
 */
void
srmGetRequestSummary::init()
{
  /* request (parser/API) */

  /* response (parser) */
  requestSummary = NULL;
}

/*
 * srmGetRequestSummary request copy constuctor
 */
srmGetRequestSummary::srmGetRequestSummary(Node &node)
{
  init();
  Node::init(node);
}

/*
 * srmGetRequestSummary request destructor
 */
srmGetRequestSummary::~srmGetRequestSummary()
{
  DM_DBG_I;

  /* request (parser/API) */
  DELETE_VEC(requestToken);

  /* response (parser) */
  DELETE(requestSummary);

  DM_DBG_O;
}

/*
 * Free process-related structures.
 */
void
srmGetRequestSummary::finish(Process *proc)
{
  DM_DBG_I;

  FREE_SRM_RET(GetRequestSummary);
}

int
srmGetRequestSummary::exec(Process *proc)
{
  DM_DBG_I;

  std::vector <std::string *> requestToken = proc->eval_vec_str(srmGetRequestSummary::requestToken);

#ifdef SRM2_CALL
  NEW_SRM_RET(GetRequestSummary);

  GetRequestSummary(
    soap,
    EVAL2CSTR(srm_endpoint),
    EVAL2CSTR(authorizationID),
    requestToken,
    resp
  );
#endif

  DELETE_VEC(requestToken);

  /* matching */
  if(!resp || !resp->srmGetRequestSummaryResponse) {
    DM_LOG(DM_N(1), "no SRM response\n");
    RETURN(ERR_ERR);
  }

  /* arrayOfRequestDetails */
  EAT_MATCH(requestSummary, arrayOfRequestDetailsToString(proc, FALSE, FALSE).c_str());

  RETURN(matchReturnStatus(resp->srmGetRequestSummaryResponse->returnStatus, proc));
}

std::string
srmGetRequestSummary::toString(Process *proc)
{
  DM_DBG_I;

  GET_SRM_RESP(GetRequestSummary);
  BOOL quote = TRUE;
  std::stringstream ss;

  std::vector <std::string *> requestToken =
    proc? proc->eval_vec_str(srmGetRequestSummary::requestToken):
          srmGetRequestSummary::requestToken;

  /* request */
  SS_SRM("srmGetRequestSummary");
  SS_P_DQ(authorizationID);
  SS_VEC_DEL(requestToken);

  /* response (parser) */
  SS_P_DQ(requestSummary);
  SS_P_DQ(returnStatus.explanation);
  SS_P_DQ(returnStatus.statusCode);

  /* response (API) */
  if(!resp || !resp->srmGetRequestSummaryResponse) RETURN(ss.str());

  ss << arrayOfRequestDetailsToString(proc, TRUE, quote);

  SS_P_SRM_RETSTAT(resp->srmGetRequestSummaryResponse);

  RETURN(ss.str());
}

std::string
srmGetRequestSummary::arrayOfRequestDetailsToString(Process *proc, BOOL space, BOOL quote) const
{
  DM_DBG_I;

  GET_SRM_RESP(GetRequestSummary);
  std::stringstream ss;

  if(!resp || !resp->srmGetRequestSummaryResponse) RETURN(ss.str());

  if(resp->srmGetRequestSummaryResponse->arrayOfRequestSummaries) {
    BOOL print_space = FALSE;
    std::vector<srm__TRequestSummary *> v = resp->srmGetRequestSummaryResponse->arrayOfRequestSummaries->summaryArray;
    for(uint u = 0; u < v.size(); u++) {
      SS_P_VEC_PAR(requestToken);
      SS_P_VEC_SRM_RETSTAT(status);
      SS_P_VEC_DPAR_SOAP(RequestType,requestType);
      SS_P_VEC_DPAR(totalNumFilesInRequest);
      SS_P_VEC_DPAR(numOfCompletedFiles);
      SS_P_VEC_DPAR(numOfWaitingFiles);
      SS_P_VEC_DPAR(numOfFailedFiles);
    }
  }

  RETURN(ss.str());
}


text:
App.Video = DS.Model.extend({
    videoURL: DS.attr('string')
});


text:
/** Automatically generated file. DO NOT MODIFY */
package com.adhamenaya;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
* **Cargo:** Desenvolvedor Front End Junior
* **Empresa** Jota Teles
* **Cidade:** São Paulo
* **Salário:** Não informado
* **Tipo de contrato:** CLT - Empregado
* **Aberto em:** 28/07/2015 13:46:40
* **Conhecimentos necessários:** css
* **Descrição:** nada
* **Como aplicar?** Mande email para exemplo@gmail.com


text:
#ifndef __G_SIMPLE_ACTION_H__
#define __G_SIMPLE_ACTION_H__

#if !defined (__GIO_GIO_H_INSIDE__) && !defined (GIO_COMPILATION)
#error "Only <gio/gio.h> can be included directly."
#endif

#include <gio/giotypes.h>

G_BEGIN_DECLS

#define G_TYPE_SIMPLE_ACTION                                (g_simple_action_get_type ())
#define G_SIMPLE_ACTION(inst)                               (G_TYPE_CHECK_INSTANCE_CAST ((inst),                     \
                                                             G_TYPE_SIMPLE_ACTION, GSimpleAction))
#define G_IS_SIMPLE_ACTION(inst)                            (G_TYPE_CHECK_INSTANCE_TYPE ((inst),                     \
                                                             G_TYPE_SIMPLE_ACTION))

GLIB_AVAILABLE_IN_ALL
GType                   g_simple_action_get_type                        (void) G_GNUC_CONST;

GLIB_AVAILABLE_IN_ALL
GSimpleAction *         g_simple_action_new                             (const gchar        *name,
                                                                         const GVariantType *parameter_type);

GLIB_AVAILABLE_IN_ALL
GSimpleAction *         g_simple_action_new_stateful                    (const gchar        *name,
                                                                         const GVariantType *parameter_type,
                                                                         GVariant           *state);

GLIB_AVAILABLE_IN_ALL
void                    g_simple_action_set_enabled                     (GSimpleAction      *simple,
                                                                         gboolean            enabled);

GLIB_AVAILABLE_IN_2_30
void                    g_simple_action_set_state                       (GSimpleAction      *simple,
                                                                         GVariant           *value);

G_END_DECLS

#endif /* __G_SIMPLE_ACTION_H__ */


text:
[![CircleCI](https://circleci.com/gh/segment-integrations/integration-intercom.svg?style=shield&circle-token=e243225f78f3fe8673bdefa621614a63b881ddb2)](https://circleci.com/gh/segment-integrations/integration-intercom)

Intercom server-side integration for [Segment](https://segment.com).


text:
{% extends "../../layout.html" %}

{% block page_title %}
  Legal - Search Results
{% endblock %}

{% block content %}

{% set serviceName = 'Find a career' %}
{% set bannerStyle = 'BETA-style' %}

    {% include "../../includes/breadcrumb_searchresults.html" %}

Careers that have similar duties

 7 Filters are currently selected  Add or remove duties to change your results

3 careers found

Prison officer

 Prison guard

Prison officers supervise inmates in prisons, remand centres and young offenders' institutions.

Salary: £20,750 to £38,000

Found in:  Administration ,  Emergency and uniform services

Border Force officer

Border Force officers protect UK border entry points like ports and airports, by enforcing immigration and customs regulations

Salary: £33,800 to £39,000r

Found in:  Administration ,Government services,  Emergency and uniform services,

Police officer

Policeman, policewoman, police constable

Police officers keep law and order, investigate crime, and support crime prevention.

Salary: £20,000 to £60,000

Found in: Government services,  Emergency and uniform services

{% endblock %}


text:
title: Subventions régionales
category: Appels
subCategory: Afrique 2015
description: Subventions régionales dans le programme BID cherchent à établir ou à renforcer des collaborations internationales qui augmentent la mobilisation des données sur la biodiversité.
---
# Subventions régionales

_Afrique subsaharienne, 2015_

**NOTE: Cet appel est maintenant terminé**

Les subventions régionales dans le programme BID cherchent à établir ou à renforcer des collaborations internationales qui augmentent la mobilisation des données sur la biodiversité.

-----------

## Procédure de soumission

La date limite pour les notes conceptuelles initiales d'Afrique subsaharienne était le 20 novembre 2015. Le GBIF et la commission d'évaluation ont fourni des commentaires et des recommandations aux candidats invités à préparer des propositions complètes.

**Les demandes doivent être envoyées en anglais en utilisant le modèle correspondant**.

Veuillez noter que les demandes reçues en retard ou incomplètes ne seront pas prises en compte par la commission d'évaluation.

-----------

## Objectifs

Les objectifs spécifiques des subventions régionales pour la mobilisation de données sur la biodiversité sont :

+ Établir ou renforcer les collaborations internationales afin de mobiliser les données sur la biodiversité
+ Accroître le nombre de données disponibles sur la biodiversité, pendant la période de subvention et au-delà
+ Utiliser les données sur la biodiversité pour répondre aux priorités de conservation

Le programme BID vise deux résultats principaux :

1. Une capacité accrue pour la mobilisation et l'utilisation efficaces des informations sur la biodiversité
2. Une disponibilité accrue des ressources d'information et des guides des meilleures pratiques pour la mobilisation et l'utilisation de l'information sur la biodiversité afin de répondre aux besoins des principaux enjeux politiques

-----------

## Documents essentiels

+ [BID Regional Grant Proposal template](https://www.gbif.org/sites/default/files/gbif_project/files/BID-Regional-Grant-Proposal-Template.doc) (*en anglais*)
+ [Premier appel 2015 á propositions de projets pour l'Afrique](https://www.gbif.org/sites/default/files/gbif_project/files/Appel_2015_a_propositions_de_projets_pour_l_Afrique_0.pdf)
+ [Annexe A de le premier appel 2015 á propositions de projets pour l'Afrique](https://www.gbif.org/sites/default/files/gbif_project/files/Annexe_A_de_l_appel-2015_a_propositions_de_projets_pour_l_Afrique_du_programme_BID_0.pdf)
+ [« Africa Rising » : Mobilisation des Données de Biodiversité pour un Développement Durable](https://www.gbif.org/sites/default/files/gbif_event/files/AfricaRising-Declaration-FR.pdf)

-----------

## Critères d'évaluation

Les propositions seront évaluées selon les critères suivants :

1. Alignement du projet sur les objectifs et priorités de BID.
2. Alignement du projet sur les besoins clairement exprimés dans la proposition en matière d'informations et de renforcement des capacités de biodiversité.
3. Contributions supplémentaires du projet aux besoins régionaux en données, y compris ceux définis dans la [déclaration et le plan d'action d' « Africa Rising »](https://www.gbif.org/sites/default/files/gbif_event/files/AfricaRising-Declaration-FR.pdf).
4. Succès et expérience avérés dans l'exécution de projets similaires.
5. Capacité du projet à servir d'exemple en matière de meilleures pratiques dans l'utilisation des informations sur la biodiversité pour la prise de décision.
6. Quantité, qualité et pertinence des données sur la biodiversité proposées pour la mobilisation, avec une préférence accordée aux projets qui mobilisent des données sur la biodiversité liées aux zones protégées, aux espèces menacées et aux espèces exotiques envahissantes.
7. Solidité des plans de développement et de durabilité des capacités institutionnelles au-delà des actions du projet.
8. Niveau de soutien institutionnel et rapport coût-efficacité des actions proposées ; équilibre entre le niveau de subvention demandé à BID et le cofinancement par les partenaires du consortium.
9. Valeur anticipée des éléments livrables du projet sur le plan national et régional, et pour l'ensemble de la communauté GBIF.
10. Choix et complémentarité des partenaires du consortium.
11. Qualité de la conception du projet et de l'évaluation des risques. Les plans de suivi et d'évaluation seront évalués dans les propositions complètes.

-----------

## Durée du projet

Les projets sélectionnés pourront amorcer leurs activités en juin 2016 pour une durée maximale de deux ans (s'achevant en juin 2018), suivie d'une période de six mois d'élaboration de rapports et d'évaluation (s'achevant en décembre 2018). Tous les projets doivent s'achever d'ici au 31 décembre 2018.

-----------

## Montant de subvention disponsible

Un minimum de trois partenaires, originaires de pays ACP africains différents, doit former un consortium. Chaque partenaire pourra recevoir jusqu'à 20 000 €, et un coordinateur de consortium pourra recevoir en plus jusqu'à 10 000 € de financement supplémentaire pour coordonner les activités de ses partenaires. Au cours du programme BID, chaque candidat peut recevoir un maximum de 60 000 € de financement pour des projets.

-----------

## Types d'activité des subventions régionales

Les subventions régionales doivent comprendre au moins une activité qui contribue à chacune des trois catégories ci-dessous. Chaque catégorie présentée ci-dessous comprend une liste non exhaustive des types d'activité possibles :

1. Mise en place ou renforcement des réseaux afin de soutenir à long terme la mobilisation des données et le partage interinstitutionnel des données:
+ Évaluation des besoins des détenteurs et des utilisateurs de données par le biais d'un sondage ou d'une étude afin de développer une stratégie pour le consortium.
+ Organisation d'ateliers régionaux pour la promotion de la collaboration interinstitutionnelle.
+ Officialisation des partenariats par le biais d'accords institutionnels, de politiques de partage des données et d'approbation par les pouvoirs publics des stratégies de mobilisation des données.
+ Adoption d'un processus de publication des données, qui peut éventuellement comprendre l'installation d'outils informatiques de publication des données. (p.ex. Outil de publication intégré [« GBIF Integrated Publishing Toolkit »](https://www.gbif.org/ipt) (*en anglais*)).
+ Formation des responsables de données et du personnel gérant les collections au sein des institutions principales détentrices de données à la mobilisation et à la gestion des données, par exemple par le biais d'ateliers permettant de partager les connaissances acquises lors de la participation aux ateliers BID de renforcement des capacités.

2. Activités permettant de mobiliser les données sur la biodiversité liées aux zones protégées, aux espèces exotiques envahissantes et/ou aux espèces menacées :
+ Compilation des inventaires des détenteurs de données sur la biodiversité (par exemple création de catalogues de métadonnées).
+ Numérisation et publication des collections d'histoire naturelle et des informations sur la biodiversité provenant de la littérature scientifique.
+ Mobilisation des occurrences d'espèces et des données d'échantillonnage provenant des réseaux d'observation et des systèmes de suivi, tels que les espèces exotiques envahissantes, les espèces menacées ou les espèces endémiques.
+ Validation et publication des listes taxonomiques d'espèces nationales, régionales et locales, des listes d'espèces envahissantes et des listes d'espèces menacées.
+ Préparation de [« data papers »](https://www.gbif.org/publishing-data/data-papers) visant à améliorer la réutilisation des données mobilisées sur la biodiversité.

3. Intégration des informations sur la biodiversité dans les processus politiques et de prise de décision :
+ Sondages ou ateliers permettant de comprendre les exigences en matière de données sur la biodiversité pour les cas d'utilisation spécifiques
+ Mise en place de groupes d'utilisateurs pour orienter la mise en oeuvre des projets sur des sujets prioritaires identifiés, tels que l'agrobiodiversité, la biodiversité urbaine et les zones protégées
+ Organisation d'ateliers et d'actions de sensibilisation pour promouvoir l'utilisation des données en libre accès, par exemple, dans les rapports sur la biodiversité à l'échelle nationale.
+ Organisation d'ateliers sur les techniques d'analyse de données
+ Utilisation des données sur la biodiversité dans les processus de prise de décision
+ Documentation des cas d'utilisation et partage de ces cas avec les partenaires de la région

------

```styledYaml
templates:
- path: eufund_fr.html
```


text:
import { Grid } from '../core';
import { IDataModel, IGridDataChange, IGridDataResult } from '../data-model';
import makeDirtyClean from '../dirty-clean';
import { ISimpleGrid } from '../simple-grid';

export interface ISimpleDataModel extends IDataModel {
  setHeader(virtualRow: number, virtualCol: number, datum: string[]): void;
}

export function create(_grid: Grid) {
  const grid = _grid as ISimpleGrid;
  type InternalData = Pick<IGridDataResult<string[]>, 'value'>;
  type DataRow = InternalData[];
  const cellData: DataRow[] = [];
  const headerData: DataRow[] = [];
  let sortedCol: number | undefined;
  let ascending = false;
  const dirtyClean = makeDirtyClean(grid);
  const internalSet = (data: DataRow[], r: number, c: number, datum: string[]) => {
    if (!data[r]) {
      data[r] = [];
    }
    data[r][c] = {
      value: datum
    };
    dirtyClean.setDirty();
  };

  const api: ISimpleDataModel = {
    isDirty: dirtyClean.isDirty,
    setDirty: dirtyClean.setDirty,
    handleCachedDataChange: dirtyClean.setDirty,
    set(rowOrData: number | Array<IGridDataChange<any>>, c?: number, datum?: string | string[]) {
      let data: Array<IGridDataChange<any>>;
      if (!Array.isArray(rowOrData)) {
        if (typeof datum === 'string') {
          datum = datum.replace('[rR]', '').replace('[cC]', '').split(' ');
        }
        data = [{
          row: rowOrData,
          col: c as number,
          value: datum

        }];
      } else {
        data = rowOrData;
      }
      data.forEach((change) => {
        internalSet(cellData, change.row, change.col, change.value);
      });
    },
    setHeader(r: number, c: number, datum: string[]) {
      internalSet(headerData, r, c, datum);
    },
    get(r: number, c: number, _isCopy?: boolean) {
      const rowDescriptor = grid.rowModel.row(r);
      if (!rowDescriptor) {
        return {
          value: undefined,
          formatted: ''
        };
      }
      const dataRow = cellData[rowDescriptor.dataRow];
      const datum = dataRow && dataRow[grid.colModel.col(c).dataCol];
      const value = datum && datum.value;
      const formatted = !Array.isArray(value) ?
        value :
        (rowDescriptor.dataLayer ? ' s' + rowDescriptor.dataLayer + ' ' : '') + 'r' + value[0] + ' c' + value[1]
        ;

      return {
        value,
        formatted: formatted || ''
      };
    },
    getHeader(r: number, c: number) {
      const dataRow = headerData[grid.rowModel.get(r).dataRow];

      const datum = dataRow && dataRow[grid.colModel.get(c).dataCol];
      const value = datum && datum.value;
      return {
        value,
        formatted: value && 'hr' + value[0] + ' hc' + value[1] || ''
      };
    },

    toggleSort(c: number) {
      let retVal = -1;
      const compareMethod = (val1: string, val2: string) => {
        return val1 < (val2) ? retVal : -1 * retVal;
      };
      if (c === sortedCol) {
        if (ascending) {
          retVal = 1;
        }
        ascending = !ascending;
      } else {
        sortedCol = c;
        ascending = true;
      }
      cellData.sort((dataRow1, dataRow2) => {
        if (!dataRow1 || !dataRow1[c]) {
          return retVal;
        }
        if (!dataRow2 || !dataRow2[c]) {
          return retVal * -1;
        }
        return compareMethod(dataRow1[c].value[1], dataRow2[c].value[1]);
      });
      dirtyClean.setDirty();
    }
  };

  return api;
}

export default create;


text:
.. raw:: pdf

   PageBreak

HowTo Notes
===========

.. index:: HowTo: Create an XFS disk partition

.. _create-the-XFS-partition:

HowTo: Create an XFS disk partition
-----------------------------------

In most cases, Fuel creates the XFS partition for you.  If for some reason you
need to create it yourself, use this procedure:

.. note:: Replace ``/dev/sdb`` with the appropriate block device you wish to
  configure.

1. Create the partition itself
   ::

     fdisk /dev/sdb
       n(for new)
       p(for partition)
       <enter> (to accept the defaults)
       <enter> (to accept the defaults)
       w(to save changes)

2. Initialize the XFS partition
   ::

     mkfs.xfs -i size=1024 -f /dev/sdb1

3. For a standard swift install, all data drives are mounted directly under
   /srv/node, so first create the mount point
   ::

     mkdir -p /srv/node/sdb1

4. Finally, add the new partition to fstab so it mounts automatically, then
   mount all current partitions
   ::

     echo "/dev/sdb1 /srv/node/sdb1 xfs
     noatime,nodiratime,nobarrier,logbufs=8 0 0" >> /etc/fstab
     mount -a

.. index:: HowTo: Redeploy a node from scratch

.. _Redeploy_node_from_scratch:

HowTo: Redeploy a node from scratch
------------------------------------

Compute and Cinder nodes can be redeployed in both multinode and multinode HA
configurations. However, controllers cannot be redeployed without compeltely
redeploying the environment. To do so, follow these steps:

1. Remove the node from your environment in the Fuel UI
2. Deploy Changes
3. Wait for the host to become available as an unallocated node
4. Add the node to the environment with the same role as before
5. Deploy Changes

.. _Enable_Disable_Galera_autorebuild:

.. index:: HowTo: Galera Cluster Autorebuild

HowTo: Enable/Disable Galera Cluster Autorebuild Mechanism
----------------------------------------------------------

By default Fuel reassembles Galera cluster automatically without need for any
user interaction. The OCF script looks for existense of `mysqlprimaryinit`
variable and tries to assemble the cluster in a following way:

  - script checks for variable above and for temporary config file created
    explicitly on deployment stage - if first is present and second missing,
    then script enters autorebuild phase, otherwise it is skipped;

  - script checks for the status of the current node - if it is syncronized
    with quorum, procedure stops, otherwise latest epoch takes place as a
    corosync variable parameter for selected node;

  - sleep for five minutes come in place allowing other nodes to join
    corosync quorum and push their epochs too;

  - for every node in quorum script does comparison of epochs and if there is
    at least one node with higher epoch, skips the rest and starts standalone
    service which will join newly formed cluster later; if there is no higher
    epochs script checks for temporary `mysqlmaster` flag and neither sets it if
    flag does not exists nor falls back to the standalong mode;

  - mysql process launches with empty `gcomm://` string forming a new quorum
    and `mysqlmaster` deletes immediately, other nodes joins in a very short time.

To prevent `autorebuild feature` you should do::

  crm_attribute -t crm_config --name mysqlprimaryinit --delete

To re-enable `autorebuild feature` you should do::

  crm_attribute -t crm_config --name mysqlprimaryinit --update done

To try an automated reassemble without reboot if cluster is broken just issue::

  crm resource restart clone_p_mysql

.. index:: HowTo: Troubleshoot Corosync/Pacemaker

How To Troubleshoot Corosync/Pacemaker
--------------------------------------

Pacemaker and Corosync come with several CLI utilities that can help you
troubleshoot and understand what is going on.

crm - Cluster Resource Manager
++++++++++++++++++++++++++++++

This is the main pacemaker utility it shows you state of pacemaker cluster.
Several most popular commands that you can use to understand whether your
cluster is consistent:

**crm status**

This command shows you the main information about pacemaker cluster and state of
resources being managed::

  crm(live)# status
  ============
  Last updated: Tue May 14 15:13:47 2013
  Last change: Mon May 13 18:36:56 2013 via cibadmin on fuel-controller-01
  Stack: openais
  Current DC: fuel-controller-01 - partition with quorum
  Version: 1.1.6-9971ebba4494012a93c03b40a2c58ec0eb60f50c
  5 Nodes configured, 5 expected votes
  3 Resources configured.
  ============

  Online: [ fuel-controller-01 fuel-controller-02 fuel-controller-03
  fuel-controller-04 fuel-controller-05 ]

  p_quantum-plugin-openvswitch-agent (ocf::pacemaker:quantum-agent-ovs): Started fuel-controller-01
  p_quantum-dhcp-agent (ocf::pacemaker:quantum-agent-dhcp): Started fuel-controller-01
  p_quantum-l3-agent (ocf::pacemaker:quantum-agent-l3): Started fuel-controller-01

**crm(live)# resource**

Here you can enter resource-specific commands::

  crm(live)resource#  status`

  p_quantum-plugin-openvswitch-agent  (ocf::pacemaker:quantum-agent-ovs) Started
  p_quantum-dhcp-agent   (ocf::pacemaker:quantum-agent-dhcp) Started
  p_quantum-l3-agent     (ocf::pacemaker:quantum-agent-l3) Started

**crm(live)resource#  start|restart|stop|cleanup <resource_name>**

These commands allow you to respectively start, stop, and restart resources.

**cleanup**

The pacemaker cleanup command resets a resource's state on the node if it is
currently in a failed state or due to some unexpected operation, such as some
side effects of a SysVInit operation on the resource. In such an event,
pacemaker will manage it by itself, deciding which node will run the resource.

Example::

  3 Nodes configured, 3 expected votes
  3 Resources configured.
  ============

  3 Nodes configured, 3 expected votes
  16 Resources configured.

  Online: [ controller-01 controller-02 controller-03 ]

   vip__management_old	(ocf::heartbeat:IPaddr2):   	Started controller-01
   vip__public_old    	(ocf::heartbeat:IPaddr2):   	Started controller-02
   Clone Set: clone_p_haproxy [p_haproxy]
    Started: [ controller-01 controller-02 controller-03 ]
   Clone Set: clone_p_mysql [p_mysql]
    Started: [ controller-01 controller-02 controller-03 ]
   Clone Set: clone_p_quantum-openvswitch-agent [p_quantum-openvswitch-agent]
    Started: [ controller-01 controller-02 controller-03 ]
   Clone Set: clone_p_quantum-metadata-agent [p_quantum-metadata-agent]
    Started: [ controller-01 controller-02 controller-03 ]
   p_quantum-dhcp-agent   (ocf::mirantis:quantum-agent-dhcp): 	Started controller-01
   p_quantum-l3-agent 	(ocf::mirantis:quantum-agent-l3):   	Started controller-03

In this case there were residual OpenStack agent processes that were started by
pacemaker in case of network failure and cluster partitioning. After the
restoration of connectivity pacemaker saw these duplicate resources running on
different nodes. You can let it clean up this situation automatically or, if you
do not want to wait, cleanup them manually.

.. seealso::

  crm interactive help and documentation resources for Pacemaker
  (e.g. http://doc.opensuse.org/products/draft/SLE-HA/SLE-ha-guide_sd_draft/cha.ha.manual_config.html).

In some network scenarios one can get cluster split into several parts and
``crm status`` showing something like this::

  On ctrl1
  ============
  ….
  Online: [ ctrl1 ]

  On ctrl2
  ============
  ….
  Online: [ ctrl2 ]

  On ctrl3
  ============
  ….
  Online: [ ctrl3 ]

You can troubleshoot this by checking corosync connectivity between nodes.
There are several points:

1) Multicast should be enabled in the network, IP address configured as
   multicast should not be filtered. The mcast port, a single udp port should
   be accepted on the management network among all controllers

2) Corosync should start after network interfaces are activated.

3) `bindnetaddr` should be located in the management network or at least in
   the same multicast reachable segment

You can check this in output of ``ip maddr show``:

.. code-block:: none
   :emphasize-lines: 1,8

   5:  br-mgmt
      link  33:33:00:00:00:01
      link  01:00:5e:00:00:01
      link  33:33:ff:a3:e2:57
      link  01:00:5e:01:01:02
      link  01:00:5e:00:00:12
      inet  224.0.0.18
      inet  239.1.1.2
      inet  224.0.0.1
      inet6 ff02::1:ffa3:e257
      inet6 ff02::1

**corosync-objctl**

This command is used to get/set runtime corosync configuration values including
status of corosync redundant ring members::

  runtime.totem.pg.mrp.srp.members.134245130.ip=r(0) ip(10.107.0.8)
  runtime.totem.pg.mrp.srp.members.134245130.join_count=1
  ...
  runtime.totem.pg.mrp.srp.members.201353994.ip=r(0) ip(10.107.0.12)
  runtime.totem.pg.mrp.srp.members.201353994.join_count=1
  runtime.totem.pg.mrp.srp.members.201353994.status=joined

If IP of the node is 127.0.0.1 it means that corosync started when only loopback
interfaces was available and bound to it.

If there is only one IP in members list that means there is corosync connectivity
issue because the node does not see the other ones. The same stays for the case
when members list is incomplete.

.. index:: HowTo: Smoke Test HA

How To Smoke Test HA
--------------------

To test if NeutrnoHA is working, simply shut down the node hosting, e.g.
Neutron agents (either gracefully or hardly). You should see agents start on
the other node::

  # crm status

  Online: [ fuel-controller-02 fuel-controller-03 fuel-controller-04 fuel-controller-05 ]
  OFFLINE: [ fuel-controller-01 ]

  p_quantum-plugin-openvswitch-agent (ocf::pacemaker:quantum-agent-ovs): Started fuel-controller-02
  p_quantum-dhcp-agent (ocf::pacemaker:quantum-agent-dhcp): Started fuel-controller-02
  p_quantum-l3-agent (ocf::pacemaker:quantum-agent-l3): Started fuel-controller-02

and see corresponding Neutron interfaces on the new Neutron node::

  # ip link show

  11: tap7b4ded0e-cb: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc
  12: qr-829736b7-34: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc
  13: qg-814b8c84-8f: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc

You can also check ``ovs-vsctl show output`` to see that all corresponding
tunnels/bridges/interfaces are created and connected properly::

  ce754a73-a1c4-4099-b51b-8b839f10291c
    Bridge br-mgmt
        Port br-mgmt
            Interface br-mgmt
                type: internal
        Port "eth1"
            Interface "eth1"
    Bridge br-ex
        Port br-ex
            Interface br-ex
                type: internal
        Port "eth0"
            Interface "eth0"
        Port "qg-814b8c84-8f"
            Interface "qg-814b8c84-8f"
                type: internal
    Bridge br-int
        Port patch-tun
            Interface patch-tun
                type: patch
                options: {peer=patch-int}
        Port br-int
            Interface br-int
                type: internal
        Port "tap7b4ded0e-cb"
            tag: 1
            Interface "tap7b4ded0e-cb"
                type: internal
        Port "qr-829736b7-34"
            tag: 1
            Interface "qr-829736b7-34"
                type: internal
    Bridge br-tun
        Port "gre-1"
            Interface "gre-1"
                type: gre
                options: {in_key=flow, out_key=flow, remote_ip="10.107.0.8"}
        Port "gre-2"
            Interface "gre-2"
                type: gre
                options: {in_key=flow, out_key=flow, remote_ip="10.107.0.5"}
        Port patch-int
            Interface patch-int
                type: patch
                options: {peer=patch-tun}
        Port "gre-3"
            Interface "gre-3"
                type: gre
                options: {in_key=flow, out_key=flow, remote_ip="10.107.0.6"}
        Port "gre-4"
            Interface "gre-4"
                type: gre
                options: {in_key=flow, out_key=flow, remote_ip="10.107.0.7"}
        Port br-tun
            Interface br-tun
                type: internal
    ovs_version: "1.4.0+build0"


text:
import json

import keystoneclient.auth.identity.v3
import keystoneclient.session
import cinderclient.client

import local_settings

auth = keystoneclient.auth.identity.v3.Password(auth_url=local_settings.auth_url_v3,
                                                username=local_settings.username,
                                                password=local_settings.password,
                                                user_domain_name='Default',
                                                project_domain_name='Default',
                                                project_name=local_settings.tenant_name)
session = keystoneclient.session.Session(auth=auth)
cinder = cinderclient.client.Client('2', session=session)

q = cinder.backups.list()
print type(q[0]), dir(q[0])
print json.dumps([i.to_dict() for i in q])


text:
echo "> creating app directories"
mkdir -p \
  /var/lib/piwik/archive \
  /var/lib/piwik/plugins \
  /var/lib/piwik/config


text:
""" cluster.py

Cluster functionality
"""

#!/usr/bin/env python
# -*- coding: utf-8 -*-

__copyright__ = 'Copyright 2013 Vanderbilt University. All Rights Reserved'

import os
import time
import logging
import subprocess
from datetime import datetime
from subprocess import CalledProcessError
from dax_settings import DAX_Settings
DAX_SETTINGS = DAX_Settings()
DEFAULT_EMAIL_OPTS = DAX_SETTINGS.get_email_opts()
JOB_TEMPLATE = DAX_SETTINGS.get_job_template()
CMD_SUBMIT = DAX_SETTINGS.get_cmd_submit()
CMD_COUNT_NB_JOBS = DAX_SETTINGS.get_cmd_count_nb_jobs()
CMD_GET_JOB_STATUS = DAX_SETTINGS.get_cmd_get_job_status()
CMD_GET_JOB_WALLTIME = DAX_SETTINGS.get_cmd_get_job_walltime()
CMD_GET_JOB_MEMORY = DAX_SETTINGS.get_cmd_get_job_memory()
CMD_GET_JOB_NODE = DAX_SETTINGS.get_cmd_get_job_node()
RUNNING_STATUS = DAX_SETTINGS.get_running_status()
QUEUE_STATUS = DAX_SETTINGS.get_queue_status()
COMPLETE_STATUS = DAX_SETTINGS.get_complete_status()
PREFIX_JOBID = DAX_SETTINGS.get_prefix_jobid()
SUFFIX_JOBID = DAX_SETTINGS.get_suffix_jobid()
MAX_TRACE_DAYS = 30

#Logger to print logs
LOGGER = logging.getLogger('dax')

def c_output(output):
    """
    Check if the output value is an integer

    :param output: variable to check
    :return: True if output is not an integer, False otherwise.
    """
    try:
        int(output)
        error = False
    except (CalledProcessError, ValueError) as err:
        error = True
        LOGGER.error(err)
    return error

def count_jobs():
    """
    Count the number of jobs in the queue on the cluster

    :return: number of jobs in the queue
    """
    cmd = CMD_COUNT_NB_JOBS
    output = subprocess.check_output(cmd, shell=True)
    error = c_output(output)
    while error:
        LOGGER.info('     try again to access number of jobs in 2 seconds.')
        time.sleep(2)
        output = subprocess.check_output(cmd, shell=True)
        error = c_output(output)
    if int(output) < 0:
        return 0
    else:
        return int(output)

def job_status(jobid):
    """
    Get the status for a job on the cluster

    :param jobid: job id to check
    :return: job status

    """
    cmd = CMD_GET_JOB_STATUS.safe_substitute({'jobid':jobid})
    try:
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        output = output.strip()
        if output == RUNNING_STATUS:
            return 'R'
        elif output == QUEUE_STATUS:
            return 'Q'
        elif output == COMPLETE_STATUS or len(output) == 0:
            return 'C'
        else:
            return None
    except CalledProcessError:
        return None

def is_traceable_date(jobdate):
    """
    Check if the job is traceable on the cluster

    :param jobdate: launching date of the job
    :return: True if traceable, False otherwise.
    """
    try:
        trace_date = datetime.strptime(jobdate, "%Y-%m-%d")
        diff_days = (datetime.today() - trace_date).days
        return diff_days <= MAX_TRACE_DAYS
    except ValueError:
        return False

def tracejob_info(jobid, jobdate):
    """
    Trace the job information from the cluster

    :param jobid: job id to check
    :param jobdate: launching date of the job
    :return: dictionary object with 'mem_used', 'walltime_used', 'jobnode'
    """
    time_s = datetime.strptime(jobdate, "%Y-%m-%d")
    diff_days = (datetime.today()-time_s).days+1
    jobinfo = dict()
    jobinfo['mem_used'] = get_job_mem_used(jobid, diff_days)
    jobinfo['walltime_used'] = get_job_walltime_used(jobid, diff_days)
    jobinfo['jobnode'] = get_job_node(jobid, diff_days)

    return jobinfo

def get_job_mem_used(jobid, diff_days):
    """
    Get the memory used for the task from cluster

    :param jobid: job id to check
    :param diff_days: difference of days between starting date and now
    :return: string with the memory usage, empty string if error
    """
    mem = ''
    # Check for blank jobid
    if not jobid:
        return mem

    cmd = CMD_GET_JOB_MEMORY.safe_substitute({'numberofdays':diff_days, 'jobid':jobid})
    try:
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        if output:
            mem = output.strip()

    except CalledProcessError:
        pass

    return mem

def get_job_walltime_used(jobid, diff_days):
    """
    Get the walltime used for the task from cluster

    :param jobid: job id to check
    :param diff_days: difference of days between starting date and now
    :return: string with the walltime used, empty string if error
    """
    walltime = ''
    # Check for blank jobid
    if not jobid:
        return walltime

    cmd = CMD_GET_JOB_WALLTIME.safe_substitute({'numberofdays':diff_days, 'jobid':jobid})
    try:
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        if output:
            walltime = output.strip()

    except CalledProcessError:
        pass

    if not walltime and diff_days > 3:
        walltime = 'NotFound'

    return walltime

def get_job_node(jobid, diff_days):
    """
    Get the node where the job was running on the cluster

    :param jobid: job id to check
    :param diff_days: difference of days between starting date and now
    :return: string with the node, empty string if error
    """
    jobnode = ''
    # Check for blank jobid
    if not jobid:
        return jobnode

    cmd = CMD_GET_JOB_NODE.safe_substitute({'numberofdays':diff_days, 'jobid':jobid})
    try:
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        if output:
            jobnode = output.strip()

    except CalledProcessError:
        pass

    return jobnode

def get_specific_str(big_str, prefix, suffix):
    """
    Extract a specific length out of a string

    :param big_str: string to reduce
    :param prefix: prefix to remove
    :param suffix: suffix to remove
    :return: string reduced, return empty string if prefix and suffix not present
    """
    specific_str = big_str
    if prefix and len(specific_str.split(prefix)) > 1:
        specific_str = specific_str.split(prefix)[1]
    if suffix and len(specific_str.split(suffix)) > 1:
        specific_str = specific_str.split(suffix)[0]
    if specific_str != big_str:
        return specific_str
    else:
        return ''

class PBS:   #The script file generator class
    """ PBS class to generate/submit the cluster file to run a task """
    def __init__(self, filename, outfile, cmds, walltime_str, mem_mb=2048,
                 ppn=1, email=None, email_options=DEFAULT_EMAIL_OPTS, xnat_host=None):
        """
        Entry point for the PBS class

        :param filename: filename for the script
        :param outfile: filepath for the outlogs
        :param cmds: commands to run in the script
        :param walltime_str: walltime to set for the script
        :param mem_mb: memory in mb to set for the script
        :param ppn: number of processor to set for the script
        :param email: email address to set for the script
        :param email_options: email options to set for the script
        :param xnat_host: set the XNAT_HOST for the job (export)
        :return: None
        """
        self.filename = filename
        self.outfile = outfile
        self.cmds = cmds
        self.walltime_str = walltime_str
        self.mem_mb = mem_mb
        self.email = email
        self.email_options = email_options
        self.ppn = ppn
        if xnat_host:
            self.xnat_host = xnat_host
        else:
            self.xnat_host = os.environ['XNAT_HOST']

    def write(self):
        """
        Write the file

        :return: None
        """
        #pbs_dir
        job_dir = os.path.dirname(self.filename)
        if not os.path.exists(job_dir):
            os.makedirs(job_dir)
        # Write the Bedpost script (default value)
        job_data = {'job_email':self.email,
                    'job_email_options':self.email_options,
                    'job_ppn':str(self.ppn),
                    'job_walltime':str(self.walltime_str),
                    'job_memory':str(self.mem_mb),
                    'job_output_file':self.outfile,
                    'job_output_file_options':'oe',
                    'job_cmds':'\n'.join(self.cmds),
                    'xnat_host':self.xnat_host}
        with open(self.filename, 'w') as f_obj:
            f_obj.write(JOB_TEMPLATE.safe_substitute(job_data))

    def submit(self):
        """
        Submit the file to the cluster

        :return: None
        """
        try:
            cmd = CMD_SUBMIT +' '+ self.filename
            proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            output, error = proc.communicate()
            if output:
                LOGGER.info('    '+output)
            if error:
                LOGGER.error(error)
            #output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
            jobid = get_specific_str(output, PREFIX_JOBID, SUFFIX_JOBID)
        except CalledProcessError as err:
            LOGGER.error(err)
            jobid = '0'

        return jobid.strip()

class ClusterLaunchException(Exception):
    """Custom exception raised when launch on the grid failed"""
    def __init__(self):
        Exception.__init__(self, 'ERROR: Failed to launch job on the grid.')

class ClusterCountJobsException(Exception):
    """Custom exception raised when attempting to get the number of
    jobs fails"""
    def __init__(self):
        Exception.__init__(self, 'ERROR: Failed to fetch number of '
                                 'jobs from the grid.')

class ClusterJobIDException(Exception):
    """Custom exception raised when attempting to get the job id failed"""
    def __init__(self):
        Exception.__init__(self, 'ERROR: Failed to get job id.')