text:
//#include "StdAfx.h"
#include "sc_manager.h"
#include "winsrv_helper.hpp"
#include <boost/foreach.hpp>

namespace WinService
{

/************************************************************************
//  win_sc_manger
//  --------------------------------------------------------------------
//
************************************************************************/

win_sc_manger::win_sc_manger()
:hand_(NULL)
{
	//
}
win_sc_manger::~win_sc_manger()
{
	std::string igrone;
	close_scm(igrone);
}

bool	win_sc_manger::scm_has_open()const
{
	return !invalid_svc_handle(hand_);
}
int win_sc_manger::qry_service_list(SrvStatus stat,SrvType type,WinSvcList& lst,std::string& what_wrong )
{
	BOOL got=TRUE;
	int err=0;

	unsigned long bytes_need=0;
	unsigned long start_page=0;
	unsigned long got_pages=0;
	// check how many bytes needed.
	got=::EnumServicesStatusEx(hand_,SC_ENUM_PROCESS_INFO,type,stat,NULL,0,&bytes_need,&got_pages,&start_page,NULL);
	if(!got){
		err=::GetLastError();
		if(err != ERROR_MORE_DATA){
			what_wrong=get_sys_err_msg(err);
			return err;
		}else{
			// it not a error
			err=sc_success_code();
		}
	}
	buffer<unsigned char> svc_buf(bytes_need);

	// got those...
	bytes_need=0;start_page=0;got_pages=0;
	got=::EnumServicesStatusEx(hand_,SC_ENUM_PROCESS_INFO,type,stat,svc_buf.ptr(),svc_buf.count(),&bytes_need,&got_pages,&start_page,NULL);

	if(!got){
		err=::GetLastError();
		what_wrong=get_sys_err_msg(err);
		return err;
	}else{
		ENUM_SERVICE_STATUS_PROCESS* essp=(ENUM_SERVICE_STATUS_PROCESS*)(svc_buf.ptr()) ;
		for (unsigned long i=0;i<got_pages;++i){
			win_service svc(essp->lpServiceName,*this);
			srv_process_info::ssp_to_proc_info(&essp->ServiceStatusProcess,svc.proc_info());

			lst.push_back(svc);
			//
			++essp;
		}
		return err;
	}

}
int		win_sc_manger::qry_service(const std::string& svc_name,SrvStatus stat,SrvType type,win_service& svc_info,std::string& what_wrong )
{
	WinSvcList lst;
	int err = qry_service_list(stat,type,lst,what_wrong);
	if(err == sc_success_code()){
		WinSvcList::const_iterator it=lst.begin();
		WinSvcList::const_iterator it_end=lst.end();
		while(it != it_end){
			if(it->name() == svc_name){
				svc_info.copy_from(*it);
				return 0;
			}
			++it;
		}
	}
	err=ERROR_SERVICE_NOT_FOUND;
	what_wrong=get_sys_err_msg(err);
	return err;

}
int win_sc_manger::open_service(const std::string& svc_name,SC_HANDLE& svc,std::string& what_wrong)
{
	unsigned int err=0;
	svc= ::OpenService(hand_,svc_name.c_str(),SERVICE_ALL_ACCESS);
	if(invalid_svc_handle(svc)){
		err=::GetLastError();
		what_wrong=get_sys_err_msg(err);
	}
	return err;

}

int		win_sc_manger::open_scm(std::string& what_wrong)
{
	if(scm_has_open())
		return 0;
	unsigned int err=0;
	//SC_MANAGER_ALL_ACCESS (0xF003F)
	hand_=::OpenSCManager(NULL,SERVICES_ACTIVE_DATABASE,SC_MANAGER_ALL_ACCESS);
	if(invalid_svc_handle(hand_)){
		err=::GetLastError();
		what_wrong=get_sys_err_msg(err);
	}
	return err;
}
int		win_sc_manger::close_scm(std::string& what_wrong)
{
	int err=close_svc_handle(hand_,what_wrong);
	hand_=NULL;
	return err;
}

int		win_sc_manger::create_service( svc_create_parameter& para,std::string& what_wrong)
{
	int err=0;
	SC_HANDLE created=::CreateService(
		hand_,
		para.ServiceName.c_str(),
		para.DisplayName.c_str(),
		para.DesiredAccess,
		para.ServiceType,
		para.StartType,
		para.ErrorControl,
		para.BinaryPathName.c_str(),
		para.LoadOrderGroup.c_str(),
		(para.TagId== 0xFFFFFFFF) ? (NULL):(&para.TagId),
		para.Dependencies.c_str(),
		para.ServiceStartName.length()==0?NULL:para.ServiceStartName.c_str(),
		para.Password.c_str());
	if(invalid_svc_handle(created)){
		err=::GetLastError();
		what_wrong=get_sys_err_msg(err);
	}else{
		std::string igrone;
		close_svc_handle(hand_,igrone);
	}
	return err;
}
int		win_sc_manger::delete_service(const std::string& svc_name,std::string& what_wrong)
{

	SC_HANDLE svc_handle=NULL;
	int err=open_service(svc_name,svc_handle, what_wrong);
	if(err == sc_success_code()){
		if(!::DeleteService(svc_handle)){
			err = GetLastError();
			what_wrong=get_sys_err_msg(err);
		}

		std::string igrone;
		close_svc_handle(hand_,igrone);
	}
	return err;

}
int		win_sc_manger::start_service(const std::string& svc_name,const std::vector<std::string>& cmd_line,std::string& what_wrong)
{
	std::vector<const char*>	cmd_argv;
	unsigned long	argc_count=static_cast<unsigned long>(cmd_line.size());
	if(argc_count>0){
		// If there are no arguments, this parameter can be NULL. Otherwise, the first argument
		// is the name of the service
		cmd_argv.push_back(svc_name.c_str());
		BOOST_FOREACH(const std::string& val,cmd_line){
			cmd_argv.push_back(val.c_str());
		}
	}

	SC_HANDLE svc_handle=NULL;
	int err=open_service(svc_name,svc_handle, what_wrong);
	if(err == sc_success_code()){
		const char ** argv_list=(argc_count==0)?NULL:(&(cmd_argv[0]));
		if(!::StartService(svc_handle,argc_count,argv_list)){
			err = GetLastError();
			what_wrong=get_sys_err_msg(err);
		}

		std::string igrone;
		close_svc_handle(hand_,igrone);
	}
	return err;

}
int		win_sc_manger::stop_service(const std::string& svc_name,std::string& what_wrong)
{
	SC_HANDLE svc_handle=NULL;
	int err=open_service(svc_name,svc_handle, what_wrong);
	if(err == sc_success_code()){
		post_ctrl_msg(svc_handle,kSvcDoStop,NULL,what_wrong,err);
		std::string igrone;
		close_svc_handle(hand_,igrone);
	}
	return err;
}

int		win_sc_manger::pause_service(const std::string& svc_name,std::string& what_wrong)
{
	SC_HANDLE svc_handle=NULL;
	int err=open_service(svc_name,svc_handle, what_wrong);
	if(err == sc_success_code()){
		post_ctrl_msg(svc_handle,kSvcDoPause,NULL,what_wrong,err);
		std::string igrone;
		close_svc_handle(hand_,igrone);
	}
	return err;
}
int		win_sc_manger::resume_service(const std::string& svc_name,std::string& what_wrong)
{
	SC_HANDLE svc_handle=NULL;
	int err=open_service(svc_name,svc_handle, what_wrong);
	if(err == sc_success_code()){
		post_ctrl_msg(svc_handle,kSvcDoResume,NULL,what_wrong,err);
		std::string igrone;
		close_svc_handle(hand_,igrone);
	}
	return err;
}
bool		win_sc_manger::post_ctrl_msg(SC_HANDLE svc_handle,SvcCtrlCode ctrl_code,void* para_ptr,std::string& what_wrong,int & stat_code)
{
	::SetLastError(sc_success_code());
	BOOL call_ok=false;
#if ((_WIN32_WINNT>=0x0600)||(WINVER>=0x0600))
	call_ok=::ControlServiceEx(svc_handle,ctrl_code,SERVICE_CONTROL_STATUS_REASON_INFO,para_ptr);
#else
	SERVICE_STATUS	sstatus={0};
	call_ok=::ControlService(svc_handle,ctrl_code,&sstatus);
#endif

	stat_code = GetLastError();
	what_wrong=get_sys_err_msg(stat_code);
	return static_cast<bool>(call_ok);

}
}//WinService


text:
using System;

namespace DriversLicense
{
    class Program
    {
        static void Main(string[] args)
        {
            string State = "";
            bool repeat = true;
            string convertedName = "";
            while (repeat)
            {
                Console.WriteLine("What is your state? (IL/WI/FL)");
                State = Console.ReadLine();

                Console.WriteLine("What is your first name?");
                string firstname = Console.ReadLine();
                string firstinitial = firstname.Substring(0, 1);
                Console.WriteLine("What is your middle initial?");
                string middleinitial = Console.ReadLine();

                convertedName = FirstName.NameConvert(State, firstname, firstinitial, middleinitial);
                if (State == "IL") License.Illinois = License.Illinois.Replace("CCC", convertedName);
                else if (State == "WI") License.Wisconsin = License.Wisconsin.Replace("CCC", convertedName);
                else if (State == "FL") License.Florida = License.Florida.Replace("CCC", convertedName);

                Console.WriteLine("What is your last name?");
                string LastName = Console.ReadLine();
                LastName = Soundex.Compute(LastName);
                if (State == "IL") License.Illinois = License.Illinois.Replace("BBBB", LastName);
                else if (State == "FL") License.Florida = License.Florida.Replace("BBBB", LastName);
                else if (State == "WI") License.Wisconsin = License.Wisconsin.Replace("BBBB", LastName);

                Console.WriteLine("What is your birthdate? (MM/DD/YYYY)(include all zeros and slashes)");
                bool birthunident = true;
                string Birthday = "";
                while (birthunident)
                {
                    Birthday = Console.ReadLine();
                    if (Birthday.Length < 10 || Birthday.Length > 10)
                    {
                        Console.WriteLine("You did not enter a valid birthday. Please type it again. ");
                        birthunident = true;
                    }
                    else birthunident = false;

                }
                string X = Birthday.Substring(8, 1);
                string Y = Birthday.Substring(9, 1);
                if (State == "IL")
                {
                    License.Illinois = License.Illinois.Replace("X", X);
                    License.Illinois = License.Illinois.Replace("Y", Y);
                }
                else if (State == "WI")
                {
                    License.Wisconsin = License.Wisconsin.Replace("X", X);
                    License.Wisconsin = License.Wisconsin.Replace("Y", Y);
                }
                else if (State == "FL")
                {
                    License.Florida = License.Florida.Replace("X", X);
                    License.Florida = License.Florida.Replace("Y", Y);
                }
                string birth_month = Birthday.Substring(0, 2);
                string birth_day = Birthday.Substring(3, 2);

                Console.WriteLine("What is your gender? Male/Female");
                bool genunident = true;
                int il_gender = 0;
                int fl_gender = 0;
                int wi_gender = 0;
                while (genunident)
                {
                    var Gender = Console.ReadLine();
                    if (State == "IL")
                    {
                        switch (Gender)
                        {
                            case "Male":
                                il_gender = 0;
                                genunident = false;
                                break;
                            case "Female":
                                il_gender = 600;
                                genunident = false;
                                break;
                            default:
                                Console.WriteLine("Your gender was not valid. Please type it again.");
                                genunident = true;
                                break;
                        }
                    }
                    else if (State == "WI")
                    {
                        switch (Gender)
                        {
                            case "Male":
                                wi_gender = 0;
                                genunident = false;
                                break;
                            case "Female":
                                wi_gender = 500;
                                genunident = false;
                                break;
                            default:
                                Console.WriteLine("Your gender was not valid. Please type it again.");
                                genunident = true;
                                break;
                        }
                    }
                    else if (State == "FL")
                    {
                        switch (Gender)
                        {
                            case "Male":
                                fl_gender = 0;
                                genunident = false;
                                break;
                            case "Female":
                                fl_gender = 500;
                                genunident = false;
                                break;
                            default:
                                Console.WriteLine("Your gender was not valid. Please type it again.");
                                genunident = true;
                                break;
                        }
                    }
                }
                int birthMonth = Convert.ToInt32(birth_month);
                int birthDay = Convert.ToInt32(birth_day);

                int il_birth_equ = (birthMonth - 1) * 31 + birthDay + il_gender;
                int fl_birth_equ = (birthMonth - 1) * 40 + birthDay + fl_gender;
                int wi_birth_equ = (birthMonth - 1) * 40 + birthDay + wi_gender;
                string birthEquIL = il_birth_equ.ToString();
                string birthEquWI = wi_birth_equ.ToString();
                string birthEquFL = fl_birth_equ.ToString();

                if (birthEquIL.Length < 3) birthEquIL = birthEquIL.PadLeft(3, '0');
                if (birthEquWI.Length < 3) birthEquWI = birthEquWI.PadLeft(3, '0');
                if (birthEquFL.Length < 3) birthEquFL = birthEquFL.PadLeft(3, '0');

                if (State == "IL")
                {
                    License.Illinois = License.Illinois.Replace("EEE", birthEquIL);
                    Console.WriteLine("Your Illinois license number is " + License.Illinois);
                }
                else if (State == "FL")
                {
                    License.Florida = License.Florida.Replace("EEE", birthEquFL);
                    Console.WriteLine("Your Florida license number is " + License.Florida + ". The overflow (the ? at the end) can not be determined.");
                }
                else if (State == "WI")
                {
                    License.Wisconsin = License.Wisconsin.Replace("EEE", birthEquWI);
                    Console.WriteLine("Your Wisconsin license number is " + License.Wisconsin + ". The overflow (the ?? at the end) can not be determined.");
                }

                Console.WriteLine("Try again? y/n");
                bool unident = true;
                while (unident)
                {
                    string Again = Console.ReadLine();
                    if (Again == "y")
                    {
                        unident = false;
                        repeat = true;
                        License.Illinois = "BBBB-CCCX-YEEE";
                        License.Wisconsin = "BBBB-CCCX-YEEE-??";
                        License.Florida = "BBBB-CCC-XY-EEE-?";
                    }
                    else if (Again == "n")
                    {
                        unident = false;
                        repeat = false;
                    }
                    else
                    {
                        Console.WriteLine("You did not enter 'y' or 'n'. Please type your choice in again.");
                        unident = true;
                    }
                }
            }
        }
    }

    public static class License
    {
        public static string Illinois = "BBBB-CCCX-YEEE";
        public static string Wisconsin = "BBBB-CCCX-YEEE-??";
        public static string Florida = "BBBB-CCC-XY-EEE-?";
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.keyspaces.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The point-in-time recovery status of the specified table.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PointInTimeRecoverySummary implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * Shows if point-in-time recovery is enabled or disabled for the specified table.
     *

     */
    private String status;
    /**
     *

     * Specifies the earliest possible restore point of the table in ISO 8601 format.
     *

     */
    private java.util.Date earliestRestorableTimestamp;

    /**
     *

     * Shows if point-in-time recovery is enabled or disabled for the specified table.
     *

     *
     * @param status
     *        Shows if point-in-time recovery is enabled or disabled for the specified table.
     * @see PointInTimeRecoveryStatus
     */

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     *

     * Shows if point-in-time recovery is enabled or disabled for the specified table.
     *

     *
     * @return Shows if point-in-time recovery is enabled or disabled for the specified table.
     * @see PointInTimeRecoveryStatus
     */

    public String getStatus() {
        return this.status;
    }

    /**
     *

     * Shows if point-in-time recovery is enabled or disabled for the specified table.
     *

     *
     * @param status
     *        Shows if point-in-time recovery is enabled or disabled for the specified table.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see PointInTimeRecoveryStatus
     */

    public PointInTimeRecoverySummary withStatus(String status) {
        setStatus(status);
        return this;
    }

    /**
     *

     * Shows if point-in-time recovery is enabled or disabled for the specified table.
     *

     *
     * @param status
     *        Shows if point-in-time recovery is enabled or disabled for the specified table.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see PointInTimeRecoveryStatus
     */

    public PointInTimeRecoverySummary withStatus(PointInTimeRecoveryStatus status) {
        this.status = status.toString();
        return this;
    }

    /**
     *

     * Specifies the earliest possible restore point of the table in ISO 8601 format.
     *

     *
     * @param earliestRestorableTimestamp
     *        Specifies the earliest possible restore point of the table in ISO 8601 format.
     */

    public void setEarliestRestorableTimestamp(java.util.Date earliestRestorableTimestamp) {
        this.earliestRestorableTimestamp = earliestRestorableTimestamp;
    }

    /**
     *

     * Specifies the earliest possible restore point of the table in ISO 8601 format.
     *

     *
     * @return Specifies the earliest possible restore point of the table in ISO 8601 format.
     */

    public java.util.Date getEarliestRestorableTimestamp() {
        return this.earliestRestorableTimestamp;
    }

    /**
     *

     * Specifies the earliest possible restore point of the table in ISO 8601 format.
     *

     *
     * @param earliestRestorableTimestamp
     *        Specifies the earliest possible restore point of the table in ISO 8601 format.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PointInTimeRecoverySummary withEarliestRestorableTimestamp(java.util.Date earliestRestorableTimestamp) {
        setEarliestRestorableTimestamp(earliestRestorableTimestamp);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getStatus() != null)
            sb.append("Status: ").append(getStatus()).append(",");
        if (getEarliestRestorableTimestamp() != null)
            sb.append("EarliestRestorableTimestamp: ").append(getEarliestRestorableTimestamp());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof PointInTimeRecoverySummary == false)
            return false;
        PointInTimeRecoverySummary other = (PointInTimeRecoverySummary) obj;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
            return false;
        if (other.getEarliestRestorableTimestamp() == null ^ this.getEarliestRestorableTimestamp() == null)
            return false;
        if (other.getEarliestRestorableTimestamp() != null && other.getEarliestRestorableTimestamp().equals(this.getEarliestRestorableTimestamp()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
        hashCode = prime * hashCode + ((getEarliestRestorableTimestamp() == null) ? 0 : getEarliestRestorableTimestamp().hashCode());
        return hashCode;
    }

    @Override
    public PointInTimeRecoverySummary clone() {
        try {
            return (PointInTimeRecoverySummary) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.keyspaces.model.transform.PointInTimeRecoverySummaryMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
export interface BootInput {
    custom_launcher_selector?: string;
    user_id?: string;
    email?: string;
    /**
     * If no app_id is passed, the value on config will be used
     */
    app_id?: string;
    [propName: string]: any;
}


text:
<resources>
    <!-- Main Activity -->
    <dimen name="main_tab_height">32dp</dimen>
    <dimen name="main_tab_size">18sp</dimen>

    <!-- Map Fragment-->
    <dimen name="map_zoom_right">10dp</dimen>
    <dimen name="map_zoom_bottom">20dp</dimen>
    <dimen name="map_zoom_button_size">40dp</dimen>
    <dimen name="map_button_margin">10dp</dimen>

    <!-- Book Fragmeng-->
    <dimen name="book_icon_marginTop">4dp</dimen>
    <dimen name="book_icon_marginLeft">16dp</dimen>
    <dimen name="book_icon_width">18dp</dimen>
    <dimen name="book_icon_height">24dp</dimen>
    <dimen name="book_title_margin_left">8dp</dimen>
    <dimen name="book_title_margin_top">10dp</dimen>
    <dimen name="book_title_text_size">14sp</dimen>
    <dimen name="book_distance_marginRight">22dp</dimen>
    <dimen name="book_name_marginTop">20dp</dimen>
    <dimen name="book_name_text_size">12sp</dimen>
    <dimen name="book_rating_marginTop">10dp</dimen>
    <dimen name="book_rating_maginLeft">4dp</dimen>
    <dimen name="book_expand_paddingLeft">40dp</dimen>
    <dimen name="book_expand_marginTop">20dp</dimen>

    <dimen name="book_expand_head_valid_marginLeft">90dp</dimen>
    <dimen name="book_expand_head_image_width">14dp</dimen>
    <dimen name="book_expand_head_image_height">10dp</dimen>
    <dimen name="book_expand_head_image_marginRight">16dp</dimen>

    <dimen name="book_expand_content_phone_icon_width">28dp</dimen>
    <dimen name="book_expand_content_phone_icon_height">28dp</dimen>
    <dimen name="book_expand_content_phone_icon_marginTop">4dp</dimen>
    <dimen name="book_expand_content_phone_num_marginTop">12dp</dimen>
    <dimen name="book_expand_content_phone_num_marginLeft">8dp</dimen>

    <dimen name="book_expand_content_count_title_marginLeft">126dp</dimen>
    <dimen name="book_expand_content_count_marginTop">10dp</dimen>

    <dimen name="book_btn_text_size">14sp</dimen>
    <dimen name="book_btn_height">40dp</dimen>

    <!--all page  set-->
    <dimen name="all_page_title_text_size">20sp</dimen>
    <dimen name="all_page_sub_text_size">18sp</dimen>

    <!--person page info setting-->
    <dimen name="person_info_group_container_margin_left">10dp</dimen>
    <dimen name="person_info_group_container_margin_right">10dp</dimen>

    <dimen name="person_info_framelayout_image_h">82dp</dimen>
    <dimen name="person_info_framelayout_image_w">82dp</dimen>
    <dimen name="person_info_framelayout_text_h">50dp</dimen>
    <dimen name="person_info_framelayout_text_w">50dp</dimen>
    <dimen name="person_info_framelayout_turn_h">20dp</dimen>
    <dimen name="person_info_framelayout_turn_w">20dp</dimen>

    <!--order page-->
    <dimen name="order_charge_line_w">100dp</dimen>
    <dimen name="order_charge_line_h">22dp</dimen>
    <dimen name="order_charge_line_edit_w">240dp</dimen>
    <dimen name="order_charge_line_edit_h">44dp</dimen>

     <!--myinfo set-->
    <dimen name="myinfo_main_h">120dp</dimen>
    <dimen name="myinfo_radioButton_w">80dp</dimen>
    <dimen name="myinfo_radioButton_h">44dp</dimen>
    <dimen name="myinfo_radioButton_text_size">18sp</dimen>

<!--my  car-->
    <dimen name="mycar_image_h">90dp</dimen>

    <!--my charge-->
    <dimen name="mycharge_laber_w">120dp</dimen>
    <dimen name="mycharg_edittext_w">240dp</dimen>

    <!--my share-->
    <dimen name="myshare_select_w">40dp</dimen>
    <dimen name="myshare_select_h">50dp</dimen>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>


text:
Apache-WriteConfig
==================

Write Apache Configuration Files


text:
package de.iritgo.aktera.base.group;

import de.iritgo.aktera.authentication.defaultauth.entity.AkteraGroupEntry;
import de.iritgo.aktera.authentication.defaultauth.entity.UserDAO;
import de.iritgo.aktera.ui.UIControllerException;
import de.iritgo.aktera.ui.UIRequest;
import de.iritgo.aktera.ui.UIResponse;
import de.iritgo.aktera.ui.ng.listing.AbstractListCommandUIController;
import de.iritgo.simplelife.math.NumberTools;

/**
 * Move an aktera group entry one position down.
 */
public class DownAkteraGroupEntry extends AbstractListCommandUIController
{
	private UserDAO userDAO;

	public void setUserDAO(UserDAO userDAO)
	{
		this.userDAO = userDAO;
	}

	public DownAkteraGroupEntry()
	{
		super("entryId");
	}

	@Override
	protected void execute(UIRequest request, UIResponse response, String id) throws UIControllerException
	{
		AkteraGroupEntry entry = userDAO.findAkteraGroupEntryById(NumberTools.toInt(id, - 1));
		userDAO.moveDownAkteraGroupEntry(entry);
	}
}


text:
package minefantasy.mf2.client.render;

import minefantasy.mf2.entity.EntityBomb;
import minefantasy.mf2.item.list.ToolListMF;
import minefantasy.mf2.util.MFLogUtil;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.entity.Entity;
import net.minecraft.util.IIcon;
import net.minecraft.util.ResourceLocation;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public class RenderBombIcon extends Render
{
    public RenderBombIcon()
    {
    }
    /**
     * Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
     * handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic
     * (Render<T extends Entity) and this method has signature public void func_76986_a(T entity, double d, double d1,
     * double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
     */
    @Override
    public void doRender(Entity entity, double x, double y, double z, float f, float f1)
    {
    	doRender((EntityBomb)entity, x, y, z, f, f1);
    }
    public void doRender(EntityBomb bomb, double x, double y, double z, float f, float f1)
    {
    	byte casing = bomb.getCasing();
        IIcon iicon = ToolListMF.bomb_custom.getIcon(casing);

        if (iicon != null)
        {
            GL11.glPushMatrix();
            GL11.glTranslatef((float)x, (float)y, (float)z);
            GL11.glEnable(GL12.GL_RESCALE_NORMAL);
            GL11.glScalef(0.5F, 0.5F, 0.5F);
            this.bindEntityTexture(bomb);
            Tessellator tessellator = Tessellator.instance;

            this.func_77026_a(tessellator, iicon);
            GL11.glDisable(GL12.GL_RESCALE_NORMAL);
            GL11.glPopMatrix();
        }
    }

	/**
     * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture.
     */
    @Override
	protected ResourceLocation getEntityTexture(Entity p_110775_1_)
    {
        return TextureMap.locationItemsTexture;
    }

    private void func_77026_a(Tessellator p_77026_1_, IIcon p_77026_2_)
    {
        float f = p_77026_2_.getMinU();
        float f1 = p_77026_2_.getMaxU();
        float f2 = p_77026_2_.getMinV();
        float f3 = p_77026_2_.getMaxV();
        float f4 = 1.0F;
        float f5 = 0.5F;
        float f6 = 0.25F;
        GL11.glRotatef(180.0F - this.renderManager.playerViewY, 0.0F, 1.0F, 0.0F);
        GL11.glRotatef(-this.renderManager.playerViewX, 1.0F, 0.0F, 0.0F);
        p_77026_1_.startDrawingQuads();
        p_77026_1_.setNormal(0.0F, 1.0F, 0.0F);
        p_77026_1_.addVertexWithUV(0.0F - f5, 0.0F - f6, 0.0D, f, f3);
        p_77026_1_.addVertexWithUV(f4 - f5, 0.0F - f6, 0.0D, f1, f3);
        p_77026_1_.addVertexWithUV(f4 - f5, f4 - f6, 0.0D, f1, f2);
        p_77026_1_.addVertexWithUV(0.0F - f5, f4 - f6, 0.0D, f, f2);
        p_77026_1_.draw();
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@drawable/background"
    tools:context="com.analisis.numericsapp.app.OneVarEquation.IncrementalSearch">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="X value"
        android:id="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="75dp"
        android:textColor="#ffffffff" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText2"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true"
        android:textColor="#ff000000" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Delta"
        android:id="@+id/textView3"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:textColor="#ffffffff" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText3"
        android:layout_alignStart="@+id/editText2"
        android:layout_below="@+id/textView3"
        android:layout_centerHorizontal="true"
        android:textColor="#ff000000" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Iterations"
        android:id="@+id/textView4"
        android:layout_below="@+id/editText3"
        android:layout_centerHorizontal="true"
        android:textColor="#ffffffff" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText4"
        android:layout_alignStart="@+id/editText3"
        android:layout_below="@+id/textView4"
        android:layout_centerHorizontal="true"
        android:textColor="#ff000000" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculate"
        android:id="@+id/calculateIncrementalSearch"
        android:onClick="CalculateIncrementalSearch"
        android:layout_toStartOf="@+id/textView3"
        android:layout_alignTop="@+id/TableButton"
        android:layout_toLeftOf="@+id/textView3" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textView5"
        android:layout_below="@+id/editText4"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="76dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Table"
        android:id="@+id/TableButton"
        android:layout_toEndOf="@+id/textView2"
        android:layout_below="@+id/textView5"
        android:layout_toRightOf="@+id/textView2"
        android:layout_marginTop="37dp" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Help"
        android:id="@+id/helpIS"
        android:onClick="helpbi"
        android:layout_toEndOf="@+id/TableButton"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toRightOf="@+id/TableButton" />

</RelativeLayout>


text:
package me.flibio.jobslite.data;

import org.spongepowered.api.data.DataHolder;
import org.spongepowered.api.data.DataView;
import org.spongepowered.api.data.manipulator.DataManipulatorBuilder;
import org.spongepowered.api.data.persistence.InvalidDataException;

import java.util.Optional;

@Deprecated
public class JobDataManipulatorBuilder implements DataManipulatorBuilder<JobData, ImmutableJobData> {

    private int level;
    private int exp;
    private String jobName;

    @Override
    public Optional<JobData> build(DataView container) throws InvalidDataException {
        if (container.contains(LiteKeys.JOB_NAME.getQuery(), LiteKeys.LEVEL.getQuery(), LiteKeys.EXP.getQuery())) {
            final String jobName = container.getString(LiteKeys.JOB_NAME.getQuery()).get();
            final int level = container.getInt(LiteKeys.LEVEL.getQuery()).get();
            final int exp = container.getInt(LiteKeys.EXP.getQuery()).get();
            return Optional.of(new JobData(jobName, level, exp));
        }
        return Optional.empty();
    }

    public JobDataManipulatorBuilder setJobInfo(String jobName, int level, int exp) {
        this.jobName = jobName;
        this.level = level;
        this.exp = exp;
        return this;
    }

    @Override
    public JobData create() {
        if (level < 0) {
            level = 0;
        }
        if (exp < 0) {
            exp = 0;
        }
        if (jobName == null) {
            jobName = "";
        }
        return new JobData(jobName, level, exp);
    }

    @Override
    public Optional<JobData> createFrom(DataHolder dataHolder) {
        return Optional.of(dataHolder.get(JobData.class).orElse(new JobData("", 0, 0)));
    }

}


text:
function ConvertTo-ESRole {
	<#
		.SYNOPSIS
			Converts JSON to esREST.Role objects
		.DESCRIPTION
			Helper function to convert PSCustomObject converted from JSON from the ElasticSearch REST API to esREST.Role objects
		.PARAMETER InputObject
			A PSCustomObject object to be converted to an esREST.Role object
		.LINK
			https://www.elastic.co/guide/en/shield/current/shield-rest.html#shield-roles-rest
			ConvertFrom-ESRole
			Get-ESRole
			New-ESRole
			Set-ESRole
	#>
	Param (
		[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
		[PSCustomObject[]]$InputObject
	)
	Begin {
		# Get the list of roles in the returned object
		$roleNames = ( $InputObject | Get-Member -MemberType NoteProperty ).Name
		Write-Verbose "Found $($roleNames.Count) roles to process"
	}
	Process {
		foreach ( $role in $roleNames ) {
			Write-Verbose "Processing role: $role"

			# Make the current role easier to reference
			$roleObj = $InputObject."$role"

			# Start a hashtable for properties to pass to New-Object
			$roleProps = @{ Name = $role }

			# Process the ClusterPrivileges
			$roleProps.ClusterPrivilege = $roleObj.cluster

			# Process the IndexPrivilegeGroups
			$roleProps.IndexPrivilegeGroup = @()
			foreach ( $privGroup in $roleObj.indices ) {
				$roleProps.IndexPrivilegeGroup += New-Object esREST.IndexPrivilegeGroup -Property @{ Index = $privGroup.names ; Privilege = $privGroup.privileges ; Field = $privGroup.fields }
			}

			# Process the RunAs items
			$roleProps.RunAs = $roleObj.run_as

			# Generate the Role object
			$result = New-Object esREST.Role -Property $roleProps

			Write-Output $result
		}
	}
}


text:
.class Lorg/holoeverywhere/widget/Spinner$DialogPopup;
.super Ljava/lang/Object;
.source "Spinner.java"

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;
.implements Lorg/holoeverywhere/widget/Spinner$SpinnerPopup;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lorg/holoeverywhere/widget/Spinner;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "DialogPopup"
.end annotation

# instance fields
.field private mListAdapter:Landroid/widget/ListAdapter;

.field private mPopup:Lorg/holoeverywhere/app/AlertDialog;

.field private mPrompt:Ljava/lang/CharSequence;

.field final synthetic this$0:Lorg/holoeverywhere/widget/Spinner;

# direct methods
.method private constructor <init>(Lorg/holoeverywhere/widget/Spinner;)V
    .locals 0

    .prologue
    .line 27
    iput-object p1, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->this$0:Lorg/holoeverywhere/widget/Spinner;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lorg/holoeverywhere/widget/Spinner;Lorg/holoeverywhere/widget/Spinner$1;)V
    .locals 0
    .param p1, "x0"    # Lorg/holoeverywhere/widget/Spinner;
    .param p2, "x1"    # Lorg/holoeverywhere/widget/Spinner$1;

    .prologue
    .line 27
    invoke-direct {p0, p1}, Lorg/holoeverywhere/widget/Spinner$DialogPopup;-><init>(Lorg/holoeverywhere/widget/Spinner;)V

    return-void
.end method

# virtual methods
.method public dismiss()V
    .locals 1

    .prologue
    .line 35
    iget-object v0, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mPopup:Lorg/holoeverywhere/app/AlertDialog;

    invoke-virtual {v0}, Lorg/holoeverywhere/app/AlertDialog;->dismiss()V

    .line 36
    const/4 v0, 0x0

    iput-object v0, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mPopup:Lorg/holoeverywhere/app/AlertDialog;

    .line 37
    return-void
.end method

.method public getBackground()Landroid/graphics/drawable/Drawable;
    .locals 1

    .prologue
    .line 41
    const/4 v0, 0x0

    return-object v0
.end method

.method public getHintText()Ljava/lang/CharSequence;
    .locals 1

    .prologue
    .line 46
    iget-object v0, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mPrompt:Ljava/lang/CharSequence;

    return-object v0
.end method

.method public getHorizontalOffset()I
    .locals 1

    .prologue
    .line 51
    const/4 v0, 0x0

    return v0
.end method

.method public getVerticalOffset()I
    .locals 1

    .prologue
    .line 56
    const/4 v0, 0x0

    return v0
.end method

.method public isShowing()Z
    .locals 1

    .prologue
    .line 61
    iget-object v0, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mPopup:Lorg/holoeverywhere/app/AlertDialog;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mPopup:Lorg/holoeverywhere/app/AlertDialog;

    invoke-virtual {v0}, Lorg/holoeverywhere/app/AlertDialog;->isShowing()Z

    move-result v0

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public onClick(Landroid/content/DialogInterface;I)V
    .locals 4
    .param p1, "dialog"    # Landroid/content/DialogInterface;
    .param p2, "which"    # I

    .prologue
    .line 66
    iget-object v0, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->this$0:Lorg/holoeverywhere/widget/Spinner;

    invoke-virtual {v0, p2}, Lorg/holoeverywhere/widget/Spinner;->setSelection(I)V

    .line 67
    iget-object v0, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->this$0:Lorg/holoeverywhere/widget/Spinner;

    iget-object v0, v0, Lorg/holoeverywhere/widget/Spinner;->mOnItemClickListener:Lorg/holoeverywhere/widget/AdapterView$OnItemClickListener;

    if-eqz v0, :cond_0

    .line 68
    iget-object v0, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->this$0:Lorg/holoeverywhere/widget/Spinner;

    const/4 v1, 0x0

    iget-object v2, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mListAdapter:Landroid/widget/ListAdapter;

    invoke-interface {v2, p2}, Landroid/widget/ListAdapter;->getItemId(I)J

    move-result-wide v2

    invoke-virtual {v0, v1, p2, v2, v3}, Lorg/holoeverywhere/widget/Spinner;->performItemClick(Landroid/view/View;IJ)Z

    .line 70
    :cond_0
    invoke-virtual {p0}, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->dismiss()V

    .line 71
    return-void
.end method

.method public setAdapter(Landroid/widget/ListAdapter;)V
    .locals 0
    .param p1, "adapter"    # Landroid/widget/ListAdapter;

    .prologue
    .line 75
    iput-object p1, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mListAdapter:Landroid/widget/ListAdapter;

    .line 76
    return-void
.end method

.method public setBackgroundDrawable(Landroid/graphics/drawable/Drawable;)V
    .locals 2
    .param p1, "bg"    # Landroid/graphics/drawable/Drawable;

    .prologue
    .line 80
    const-string v0, "Spinner"

    const-string v1, "Cannot set popup background for MODE_DIALOG, ignoring"

    invoke-static {v0, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 82
    return-void
.end method

.method public setHorizontalOffset(I)V
    .locals 2
    .param p1, "px"    # I

    .prologue
    .line 86
    const-string v0, "Spinner"

    const-string v1, "Cannot set horizontal offset for MODE_DIALOG, ignoring"

    invoke-static {v0, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 88
    return-void
.end method

.method public setPromptText(Ljava/lang/CharSequence;)V
    .locals 0
    .param p1, "hintText"    # Ljava/lang/CharSequence;

    .prologue
    .line 92
    iput-object p1, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mPrompt:Ljava/lang/CharSequence;

    .line 93
    return-void
.end method

.method public setVerticalOffset(I)V
    .locals 2
    .param p1, "px"    # I

    .prologue
    .line 97
    const-string v0, "Spinner"

    const-string v1, "Cannot set vertical offset for MODE_DIALOG, ignoring"

    invoke-static {v0, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 99
    return-void
.end method

.method public show()V
    .locals 3

    .prologue
    .line 103
    new-instance v0, Lorg/holoeverywhere/app/AlertDialog$Builder;

    iget-object v1, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->this$0:Lorg/holoeverywhere/widget/Spinner;

    invoke-virtual {v1}, Lorg/holoeverywhere/widget/Spinner;->getContext()Landroid/content/Context;

    move-result-object v1

    invoke-direct {v0, v1}, Lorg/holoeverywhere/app/AlertDialog$Builder;-><init>(Landroid/content/Context;)V

    .line 104
    .local v0, "builder":Lorg/holoeverywhere/app/AlertDialog$Builder;
    iget-object v1, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mPrompt:Ljava/lang/CharSequence;

    if-eqz v1, :cond_0

    .line 105
    iget-object v1, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mPrompt:Ljava/lang/CharSequence;

    invoke-virtual {v0, v1}, Lorg/holoeverywhere/app/AlertDialog$Builder;->setTitle(Ljava/lang/CharSequence;)Lorg/holoeverywhere/app/AlertDialog$Builder;

    .line 107
    :cond_0
    iget-object v1, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mListAdapter:Landroid/widget/ListAdapter;

    iget-object v2, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->this$0:Lorg/holoeverywhere/widget/Spinner;

    invoke-virtual {v2}, Lorg/holoeverywhere/widget/Spinner;->getSelectedItemPosition()I

    move-result v2

    invoke-virtual {v0, v1, v2, p0}, Lorg/holoeverywhere/app/AlertDialog$Builder;->setSingleChoiceItems(Landroid/widget/ListAdapter;ILandroid/content/DialogInterface$OnClickListener;)Lorg/holoeverywhere/app/AlertDialog$Builder;

    move-result-object v1

    invoke-virtual {v1}, Lorg/holoeverywhere/app/AlertDialog$Builder;->show()Lorg/holoeverywhere/app/AlertDialog;

    move-result-object v1

    iput-object v1, p0, Lorg/holoeverywhere/widget/Spinner$DialogPopup;->mPopup:Lorg/holoeverywhere/app/AlertDialog;

    .line 109
    return-void
.end method


text:
/**
 * Created by Jian Chen
 * @since  2016.05.24
 * @author Jian Chen <admin@chensoft.com>
 * @link   http://chensoft.com
 */
#pragma once

#include <unordered_map>
#include <vector>
#include <map>

namespace chen
{
    class map
    {
    public:
        /**
         * Test if the key is in a map
         */
        template <typename M>
        static bool exist(const M &m, const typename M::key_type &k)
        {
            return m.find(k) != m.end();
        }

        /**
         * Find value in map
         */
        template <typename M>
        static typename M::mapped_type find(const M &m, const typename M::key_type &k)
        {
            auto it = m.find(k);
            return it != m.end() ? it->second : typename M::mapped_type();
        }

        template <typename M, typename R>
        static R find(const M &m, const typename M::key_type &k, R def)
        {
            auto it = m.find(k);
            return it != m.end() ? static_cast<R>(it->second) : def;
        }

        /**
         * Write value if find
         */
        template <typename M, typename O>
        static void write(const M &m, const typename M::key_type &k, O &o)
        {
            auto it = m.find(k);
            if (it != m.end())
                o = static_cast<O>(it->second);
        }

        /**
         * The keys of a map
         */
        template <typename M>
        static std::vector<typename M::key_type> keys(const M &m)
        {
            std::vector<typename M::key_type> ret;
            for (auto &pair : m)
                ret.emplace_back(pair.first);
            return ret;
        }

        /**
         * The values of a map
         */
        template <typename M>
        static std::vector<typename M::mapped_type> values(const M &m)
        {
            std::vector<typename M::mapped_type> ret;
            for (auto &pair : m)
                ret.emplace_back(pair.second);
            return ret;
        }

        /**
         * Invert the map, user should make sure the values are unique
         * otherwise the same keys will be override
         */
        template <typename M>
        static M flip(const M &m)
        {
            M ret;
            for (auto &pair : m)
                ret[pair.second] = pair.first;
            return ret;
        }
    };
}


text:
#include <folly/synchronization/detail/Sleeper.h>

namespace folly {
namespace detail {

constexpr std::chrono::nanoseconds Sleeper::kMinYieldingSleep;
}
} // namespace folly


text:
using System;
using System.Threading.Tasks;

namespace Discord.Commands
{
    /// <summary>
    ///     Requires the bot to have a specific permission in the channel a command is invoked in.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class RequireBotPermissionAttribute : PreconditionAttribute
    {
        /// <summary>
        ///     Gets the specified <see cref="Discord.GuildPermission" /> of the precondition.
        /// </summary>
        public GuildPermission? GuildPermission { get; }
        /// <summary>
        ///     Gets the specified <see cref="Discord.ChannelPermission" /> of the precondition.
        /// </summary>
        public ChannelPermission? ChannelPermission { get; }
        /// <inheritdoc />
        public override string ErrorMessage { get; set; }
        /// <summary>
        ///     Gets or sets the error message if the precondition
        ///     fails due to being run outside of a Guild channel.
        /// </summary>
        public string NotAGuildErrorMessage { get; set; }

        /// <summary>
        ///     Requires the bot account to have a specific <see cref="Discord.GuildPermission"/>.
        /// </summary>
        /// <remarks>
        ///     This precondition will always fail if the command is being invoked in a <see cref="IPrivateChannel"/>.
        /// </remarks>
        /// <param name="permission">
        ///     The <see cref="Discord.GuildPermission"/> that the bot must have. Multiple permissions can be specified
        ///     by ORing the permissions together.
        /// </param>
        public RequireBotPermissionAttribute(GuildPermission permission)
        {
            GuildPermission = permission;
            ChannelPermission = null;
        }
        /// <summary>
        ///     Requires that the bot account to have a specific <see cref="Discord.ChannelPermission"/>.
        /// </summary>
        /// <param name="permission">
        ///     The <see cref="Discord.ChannelPermission"/> that the bot must have. Multiple permissions can be
        ///     specified by ORing the permissions together.
        /// </param>
        public RequireBotPermissionAttribute(ChannelPermission permission)
        {
            ChannelPermission = permission;
            GuildPermission = null;
        }

        /// <inheritdoc />
        public override async Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            IGuildUser guildUser = null;
            if (context.Guild != null)
                guildUser = await context.Guild.GetCurrentUserAsync().ConfigureAwait(false);

            if (GuildPermission.HasValue)
            {
                if (guildUser == null)
                    return PreconditionResult.FromError(NotAGuildErrorMessage ?? "Command must be used in a guild channel.");
                if (!guildUser.GuildPermissions.Has(GuildPermission.Value))
                    return PreconditionResult.FromError(ErrorMessage ?? $"Bot requires guild permission {GuildPermission.Value}.");
            }

            if (ChannelPermission.HasValue)
            {
                ChannelPermissions perms;
                if (context.Channel is IGuildChannel guildChannel)
                    perms = guildUser.GetPermissions(guildChannel);
                else
                    perms = ChannelPermissions.All(context.Channel);

                if (!perms.Has(ChannelPermission.Value))
                    return PreconditionResult.FromError(ErrorMessage ?? $"Bot requires channel permission {ChannelPermission.Value}.");
            }

            return PreconditionResult.FromSuccess();
        }
    }
}


text:
<?php

use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\dynagrid\DynaGrid;
use app\models\User;
/* @var $this yii\web\View */
/* @var $searchModel app\models\NotificationSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Notifications';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

<?php
     $toolbars = [
        ['content' =>
            Html::a('', ['notification/create'], ['type' => 'button', 'title' => 'Add ' . $this->title, 'class' => 'btn btn-success']) . ' ' .
            Html::a('', ['notification/parsing'], ['type' => 'button', 'title' => 'Parsing Excel ' . $this->title, 'class' => 'btn btn-danger']) . ' ' .
            Html::a('', ['notification/index','p_reset'=>true], ['data-pjax' => 0, 'class' => 'btn btn-default', 'title' => 'Reset Grid']). ' '

        ],
        ['content' => '{dynagridFilter}{dynagridSort}{dynagrid}'],
        '{export}',
    ];
    $panels = [
        'heading' => '
  ' . $this->title . '
',
        'before' => '
* The table at the right you can pull reports & personalize
',
    ];
    $columns = [
        ['class' => 'kartik\grid\SerialColumn', 'order' => DynaGrid::ORDER_FIX_LEFT],
                    'id',
            'title',
            'message:ntext',
            'url:url',
            'params:ntext',
            [
            'attribute' => 'userUpdate',
            'format' => 'html',
            'filter' => User::dropdown(),
            'value' => function($data) {
                return $data->userUpdateLabel;
            },
            ],

                    ['attribute' => 'userCreate','format' => 'html','filter' => User::dropdown(),
            'value' => function($data) {
                return $data->userCreateLabel;
            },
        ],
                    [
            'attribute' => 'updateDate',
            'filterType' => GridView::FILTER_DATE,
            'format' => 'raw',
            'width' => '170px',
            'filterWidgetOptions' => [
                'pluginOptions' => ['format' => 'yyyy-mm-dd']
            ],
        ],

                    [
            'attribute' => 'createDate',
            'filterType' => GridView::FILTER_DATE,
            'format' => 'raw',
            'width' => '170px',
            'filterWidgetOptions' => [
                'pluginOptions' => ['format' => 'yyyy-mm-dd']
            ],
            ],

                [
            'class' => 'kartik\grid\ActionColumn',
            'dropdown' => false,
            'vAlign' => 'middle',
            'viewOptions' => ['title' => 'view', 'data-toggle' => 'tooltip'],
            'updateOptions' => ['title' => 'update', 'data-toggle' => 'tooltip'],
            'deleteOptions' => ['title' => 'delete', 'data-toggle' => 'tooltip'],
        ],
        [
            'class' => 'kartik\grid\CheckboxColumn',
        ],
    ];

    $dynagrid = DynaGrid::begin([
                'id' => 'user-grid',
                'columns' => $columns,
                'theme' => 'panel-primary',
                'showPersonalize' => true,
                'storage' => 'db',
                //'maxPageSize' =>500,
                'allowSortSetting' => true,
                'gridOptions' => [
                    'dataProvider' => $dataProvider,
                    'filterModel' => $searchModel,
                    'showPageSummary' => true,
                    'floatHeader' => true,
                    'pjax' => true,
                    'panel' => $panels,
                    'toolbar' => $toolbars,
                ],
                'options' => ['id' => 'Notification'.Yii::$app->user->identity->id] // a unique identifier is important
    ]);

    DynaGrid::end();
?>


text:
#include <aws/discovery/model/StartExportTaskRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::ApplicationDiscoveryService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

StartExportTaskRequest::StartExportTaskRequest() :
    m_exportDataFormatHasBeenSet(false),
    m_filtersHasBeenSet(false),
    m_startTimeHasBeenSet(false),
    m_endTimeHasBeenSet(false)
{
}

Aws::String StartExportTaskRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_exportDataFormatHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> exportDataFormatJsonList(m_exportDataFormat.size());
   for(unsigned exportDataFormatIndex = 0; exportDataFormatIndex < exportDataFormatJsonList.GetLength(); ++exportDataFormatIndex)
   {
     exportDataFormatJsonList[exportDataFormatIndex].AsString(ExportDataFormatMapper::GetNameForExportDataFormat(m_exportDataFormat[exportDataFormatIndex]));
   }
   payload.WithArray("exportDataFormat", std::move(exportDataFormatJsonList));

  }

  if(m_filtersHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> filtersJsonList(m_filters.size());
   for(unsigned filtersIndex = 0; filtersIndex < filtersJsonList.GetLength(); ++filtersIndex)
   {
     filtersJsonList[filtersIndex].AsObject(m_filters[filtersIndex].Jsonize());
   }
   payload.WithArray("filters", std::move(filtersJsonList));

  }

  if(m_startTimeHasBeenSet)
  {
   payload.WithDouble("startTime", m_startTime.SecondsWithMSPrecision());
  }

  if(m_endTimeHasBeenSet)
  {
   payload.WithDouble("endTime", m_endTime.SecondsWithMSPrecision());
  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection StartExportTaskRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSPoseidonService_V2015_11_01.StartExportTask"));
  return headers;

}


text:
import fs = require('fs');
import mockanswer = require('azure-pipelines-task-lib/mock-answer');
import mockrun = require('azure-pipelines-task-lib/mock-run');
import path = require('path');

let taskPath = path.join(__dirname, '..', 'copyfiles.js');
let runner: mockrun.TaskMockRunner = new mockrun.TaskMockRunner(taskPath);
runner.setInput('Contents', '**');
runner.setInput('SourceFolder', path.normalize('/srcDir'));
runner.setInput('TargetFolder', path.normalize('/destDir'));
runner.setInput('CleanTargetFolder', 'false');
runner.setInput('Overwrite', 'false');
let answers = <mockanswer.TaskLibAnswers> {
    checkPath: { },
    find: { },
};
answers.checkPath[path.normalize('/srcDir')] = true;
answers.find[path.normalize('/srcDir')] = [
    path.normalize('/srcDir'),
    path.normalize('/srcDir/someOtherDir'),
    path.normalize('/srcDir/someOtherDir/file1.file'),
    path.normalize('/srcDir/someOtherDir/file2.file'),
    path.normalize('/srcDir/someOtherDir2'),
    path.normalize('/srcDir/someOtherDir2/file1.file'),
    path.normalize('/srcDir/someOtherDir2/file2.file'),
    path.normalize('/srcDir/someOtherDir2/file3.file'),
    path.normalize('/srcDir/someOtherDir3'),
];
runner.setAnswers(answers);

fs.existsSync = (itemPath: string) => {
    switch (itemPath) {
        case path.normalize('/srcDir'):
        case path.normalize('/srcDir/someOtherDir'):
        case path.normalize('/srcDir/someOtherDir/file1.file'):
        case path.normalize('/srcDir/someOtherDir/file2.file'):
        case path.normalize('/srcDir/someOtherDir2'):
        case path.normalize('/srcDir/someOtherDir2/file1.file'):
        case path.normalize('/srcDir/someOtherDir2/file2.file'):
        case path.normalize('/srcDir/someOtherDir2/file3.file'):
        case path.normalize('/srcDir/someOtherDir3'):
            return true;
        default:
            return false;
    }
}

fs.statSync = (itemPath: string) => {
    const itemStats: fs.Stats = new fs.Stats();
    switch (itemPath) {
        case path.normalize('/srcDir/someOtherDir'):
        case path.normalize('/srcDir/someOtherDir2'):
        case path.normalize('/srcDir/someOtherDir3'):
            itemStats.isDirectory = () => true;
            break;
        case path.normalize('/srcDir/someOtherDir/file1.file'):
        case path.normalize('/srcDir/someOtherDir/file2.file'):
        case path.normalize('/srcDir/someOtherDir2/file1.file'):
        case path.normalize('/srcDir/someOtherDir2/file2.file'):
        case path.normalize('/srcDir/someOtherDir2/file3.file'):
            itemStats.isDirectory = () => false;
            break;
        default:
            throw { code: 'ENOENT' };
    }
    return itemStats;
}

// as a precaution, disable fs.chmodSync. it should not be called during this scenario.
fs.chmodSync = null;
runner.registerMock('fs', fs);

runner.run();


text:
package co.aurasphere.botmill.core.base;

import java.io.IOException;
import java.io.Reader;
import javax.servlet.http.HttpServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import co.aurasphere.botmill.core.BotDefinition;
import co.aurasphere.botmill.core.internal.util.ConfigurationUtils;

/**
 * Base BotMill servlet with shared behavior.
 *
 * @author Donato Rimenti
 */
public class BotMillServlet extends HttpServlet {

	/**
	 * The logger.
	 */
	protected static final Logger logger = LoggerFactory
			.getLogger(BotMillServlet.class);

	/**
	 * The serial version UID.
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Initializes the BotMill servlet. The initialization will try to load the
	 * classes implementing {@link BotDefinition} in the classpath. If the
	 * classes are found and correctly loaded, the method
	 * {@link BotDefinition#defineBehaviour()} is called for each configuration.
	 */
	@Override
	public void init() {
		ConfigurationUtils.loadEncryptedConfigurationProperties();
		ConfigurationUtils.loadConfigurationFile();
		ConfigurationUtils.loadBotConfig();
		ConfigurationUtils.loadBotDefinitions();
		logger.info("BotMill servlet started.");
	}

	/**
	 * Utility method that converts a Reader to a String.
	 *
	 * @param reader
	 *            the reader to convert.
	 * @return a String with the content of the reader.
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	protected static String readerToString(Reader reader) throws IOException {
		char[] arr = new char[8 * 1024];
		StringBuilder buffer = new StringBuilder();
		int numCharsRead;
		while ((numCharsRead = reader.read(arr, 0, arr.length)) != -1) {
			buffer.append(arr, 0, numCharsRead);
		}
		return buffer.toString();
	}

}


text:
package org.tiatus.service;

import org.tiatus.entity.Club;

import java.util.List;

/**
 * Created by johnreynolds on 25/06/2016.
 */
public interface ClubService {
    /**
     * Add club
     * @param club to create
     * @return created club
     * @throws ServiceException on error
     */
    Club addClub(Club club, String sessionId) throws ServiceException;

    /**
     * Remove a club
     * @param club to remove
     * @throws ServiceException on error
     */
    void deleteClub(Club club, String sessionId) throws ServiceException;

    /**
     * update club
     * @param club to update
     * @throws ServiceException on error
     */
    void updateClub(Club club, String sessionId) throws ServiceException;

    Club getClubForId(Long id);

    /**
     * Get clubs
     * @return list of clubs
     */
    List<Club> getClubs();
}


text:
package upcloud

import (
	"encoding/xml"
	"time"
)

// Constants
const (
	StorageTypeBackup   = "backup"
	StorageTypeCDROM    = "cdrom"
	StorageTypeDisk     = "disk"
	StorageTypeNormal   = "normal"
	StorageTypeTemplate = "template"

	StorageTierHDD     = "hdd"
	StorageTierMaxIOPS = "maxiops"

	StorageAccessPublic  = "public"
	StorageAccessPrivate = "private"

	StorageStateOnline      = "online"
	StorageStateMaintenance = "maintenance"
	StorageStateCloning     = "cloning"
	StorageStateBackuping   = "backuping"
	StorageStateError       = "error"

	BackupRuleIntervalDaily     = "daily"
	BackupRuleIntervalMonday    = "mon"
	BackupRuleIntervalTuesday   = "tue"
	BackupRuleIntervalWednesday = "wed"
	BackupRuleIntervalThursday  = "thu"
	BackupRuleIntervalFriday    = "fri"
	BackupRuleIntervalSaturday  = "sat"
	BackupRuleIntervalSunday    = "sun"

	CreateServerStorageDeviceActionCreate = "create"
	CreateServerStorageDeviceActionClone  = "clone"
	CreateServerStorageDeviceActionAttach = "attach"
)

// Storages represents a /storage response
type Storages struct {
	Storages []Storage `xml:"storage"`
}

// Storage represents a storage device
type Storage struct {
	Access  string  `xml:"access"`
	License float64 `xml:"license"`
	// TODO: Convert to boolean
	PartOfPlan string `xml:"part_of_plan"`
	Size       int    `xml:"size"`
	State      string `xml:"state"`
	Tier       string `xml:"tier"`
	Title      string `xml:"title"`
	Type       string `xml:"type"`
	UUID       string `xml:"uuid"`
	Zone       string `xml:"zone"`
	// Only for type "backup":
	Origin  string    `xml:"origin"`
	Created time.Time `xml:"created"`
}

// StorageDetails represents detailed information about a piece of storage
type StorageDetails struct {
	Storage

	BackupRule  *BackupRule `xml:"backup_rule"`
	BackupUUIDs []string    `xml:"backups>backup"`
	ServerUUIDs []string    `xml:"servers>server"`
}

// BackupRule represents a backup rule
type BackupRule struct {
	XMLName  xml.Name `xml:"backup_rule"`
	Interval string   `xml:"interval"`
	// Time should be in the format "hhmm", e.g. "0430"
	Time      string `xml:"time"`
	Retention int    `xml:"retention"`
}

// ServerStorageDevice represents a storage device in the context of server requests or server details
type ServerStorageDevice struct {
	XMLName xml.Name `xml:"storage_device"`

	Address string `xml:"address"`
	// TODO: Convert to boolean
	PartOfPlan string `xml:"part_of_plan"`
	UUID       string `xml:"storage"`
	Size       int    `xml:"storage_size"`
	Title      string `xml:"storage_title"`
	Type       string `xml:"type"`
}

// CreateServerStorageDevice represents a storage device for a CreateServerRequest
type CreateServerStorageDevice struct {
	XMLName xml.Name `xml:"storage_device"`

	Action  string `xml:"action"`
	Address string `xml:"address,omitempty"`
	Storage string `xml:"storage"`
	Title   string `xml:"title,omitempty"`
	// Storage size in gigabytes
	Size int    `xml:"size"`
	Tier string `xml:"tier,omitempty"`
	Type string `xml:"type,omitempty"`
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. natn. Acad. Sci. India, Sect. B, Biol. Sci. 36(3): 289 (1966)

#### Original name
Cercospora garugae G.P. Agarwal & Hasija

### Remarks
null


text:
[DLP API][Product Documentation]: The Google Data Loss Prevention API provides methods for detection of privacy-sensitive fragments in text, images, and Google Cloud Platform storage repositories.
- [Client Library Documentation][]
- [Product Documentation][]

## Quick Start
In order to use this library, you first need to go through the following steps:

1. [Select or create a Cloud Platform project.](https://console.cloud.google.com/project)
2. [Enable the DLP API.](https://console.cloud.google.com/apis/api/dlp)
3. [Setup Authentication.](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud/master/guides/authentication)

### Installation
```
$ gem install google-cloud-dlp
```

### Preview
#### DlpServiceClient
```rb
require "google/cloud/dlp"

dlp_service_client = Google::Cloud::Dlp.new
min_likelihood = :POSSIBLE
inspect_config = { min_likelihood: min_likelihood }
type = "text/plain"
value = "my phone number is 215-512-1212"
items_element = { type: type, value: value }
items = [items_element]
response = dlp_service_client.inspect_content(inspect_config, items)
```

### Next Steps
- Read the [Client Library Documentation][] for DLP API to see other available methods on the client.
- Read the [DLP API Product documentation][Product Documentation] to learn more about the product and see How-to Guides.
- View this [repository's main README](https://github.com/GoogleCloudPlatform/google-cloud-ruby/blob/master/README.md) to see the full list of Cloud APIs that we cover.

[Client Library Documentation]: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-dlp/latest/google/privacy/dlp/v2beta1
[Product Documentation]: https://cloud.google.com/dlp


text:
package com.sdw.soft.common.sys.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.sdw.soft.common.sys.dao.CalendarDao;
import com.sdw.soft.common.sys.entity.Calendar;
import com.sdw.soft.core.dao.BaseDao;
import com.sdw.soft.core.service.BaseService;

@Service
@Transactional
public class CalendarService extends BaseService<Calendar, String> {

	private static final Logger logger = LoggerFactory.getLogger(CalendarService.class);

	@Autowired
	private CalendarDao calendarDao ;

	@Override
	protected BaseDao<Calendar, String> getEntityDao() {
		return calendarDao;
	}

	public List<Calendar> findAllWithNoPageNoSort() {

		return Lists.newArrayList(calendarDao.findAllCached());
	}

}


text:
Law perform continuous archiving of PostgreSQL WAL files along with taking
and restoring base backups.

## Installation

Download and install :

```
$ go get github.com/cyberdelia/law
```

## Usage

Law make use of environment-variable, the base one are:

 - ``STORAGE_URL``: URL indicating where files are stored.
   * For file storage: ``file:///tmp/``
   * For S3 storage: ``s3://s3.amazonaws.com/bucket_name``
 - ``DATABASE_URL``: URL to database.
   * For online backup: ``postgres://locahost:5432/`` or ``postgres:///tmp/.s.PGSQL.5432``
   * For offline backup: ``file:///usr/local/var/postgres``

S3 storage might requires one or more of theses variables:

 - ``AWS_ACCESS_KEY_ID``: An AWS access key.
 - ``AWS_SECRET_ACCESS_KEY``: An AWS secret key.
 - ``AWS_SECURITY_TOKEN``: An AWS STS Token.

Law has 4 subcommands :

 - ``wal-push``: Push wal archive to storage.

  Example: ``law wal-push -segment %p``

 - ``wal-fetch``: Fetch wal archive from storage.

   Example: ``law wal-fetch -segment %p -destination %p``

 - ``backup-push``: Push a backup to storage.

   Example: ``law backup-push -cluster /var/lib/database``

 - ``backup-fetch``: Fetch a backup from storage.

   Example: ``law backup-fetch -cluster /var/lib/database``

## PostgreSQL configuration

In order for law to work you'll need to setup PostgreSQL like so:

```
wal_level = archive
archive_mode = on
archive_command = 'law -storage <ssn> wal-push -segment %p'
archive_timeout = 60
restore_command = 'law -storage <ssn> wal-fetch -destination "%f" -segment "%p"'
```

## Limitations

This is alpha software, don't use it for anything serious.


text:
package org.switchyard.quickstarts.camel.sap.binding;

import org.switchyard.quickstarts.camel.sap.binding.jaxb.BookFlightRequest;
import org.switchyard.quickstarts.camel.sap.binding.jaxb.BookFlightResponse;

public interface FlightBookingService {
    BookFlightResponse bookFlight(BookFlightRequest request);
}


text:
date: 2016-09-12 09:56:41+00:00
layout: versioned
menu:
  main:
    identifier: safire-policy-participation
    parent: safire-policy
    weight: 2
slug: participation
tags:
  - participation
title: Participation Agreement
url: /safire/policy/participation/
---

This page documents the history of SAFIRE's Participation Agreement and will display the most recent version. You should always reference this page when linking to the Participation Agreement, unless you intend to link to a specific, versioned document.

Changes to the Participation Agreement are approved by TENET's Board of Directors on recommendation from the SAFIRE Steering Committee.


text:
import sys, psutil, os, stat, tempfile, argparse, time, datetime
sys.path.extend(['.','..','../..','py'])
import h2o_sandbox

# Stripped down, similar to h2o.py has for these functions
# Possible to do this in bash, but the code becomes cryptic.
# You can execute this as sh2junit.py <bash command string>

# sh2junit runs the cmd_string as a subprocess, with stdout/stderr going to files in sandbox
# and stdout to python stdout too.
# When it completes, check the sandbox for errors (using h2o_sandbox.py
# prints interesting things to stdout. Creates the result xml in the current dire
# with name "sh2junit_<name>.xml"

def sandbox_tmp_file(prefix='', suffix=''):
    # this gives absolute path, good!
    dirname = './sandbox'
    if not os.path.exists(dirname):
        print "no ./sandbox. Creating"
        os.makedirs(dirname)

    fd, path = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=dirname)
    # make sure the file now exists
    # os.open(path, 'a').close()
    # give everyone permission to read it (jenkins running as
    # 0xcustomer needs to archive as jenkins
    #permissions = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
    os.chmod(path, 0644) #'644')  #permissions)
    return (fd, path)

#**************************************************************************
# Example junit xml
#<?xml version="1.0" encoding="UTF-8"?>
#<testsuites disabled="" errors="" failures="" name="" tests="" time="">
#    <testsuite disabled="" errors="" failures="" hostname="" id="" name="" package="" skipped="" tests="" time="" timestamp="">
#        <properties>
#            <property name="" value=""/>
#        </properties>
#        <testcase assertions="" classname="" name="" status="" time="">
#            <skipped/>
#            <error message="" type=""/>
#            <failure message="" type=""/>
#            <system-out/>
#            <system-err/>
#        </testcase>
#        <system-out/>
#        <system-err/>
#    </testsuite>
#</testsuites>
def create_junit_xml(name, out, err, sandboxErrorMessage, errors=0, elapsed=0):
    # http://junitpdfreport.sourceforge.net/managedcontent/PdfTranslation

    # not really nosetests..just trying to mimic the python xml
    content  = '<?xml version="1.0" encoding="UTF-8" ?>\n'
    content += '    <testsuite name="nosetests" tests="1" errors="%s" failures="0" skip="0">\n' % (errors)
    content += '        <testcase classname="%s" name="%s" time="%0.4f">\n' % (name, name, elapsed)
    if errors != 0 and not sandboxErrorMessage:
        content += '            <error type="Non-zero R exit code" message="Non-zero R exit code"></error>\n'
    # may or may not be 2 errors (R exit code plus log error
    if errors != 0 and sandboxErrorMessage:
        content += '            <error type="Error in h2o logs" message="Error in h2o logs"></error>\n'
    content += '            <system-out>\n'
    content += '<![CDATA[\n'
    content += 'spawn stdout' + str(datetime.datetime.now()) + '**********************************************************\n'
    content += out
    content += ']]>\n'
    content += '            </system-out>\n'

    content += '            <system-err>\n'
    content += '<![CDATA[\n'
    content += 'spawn stderr' + str(datetime.datetime.now()) + '**********************************************************\n'
    content += err
    if sandboxErrorMessage:
        content += 'spawn errors from sandbox log parsing*********************************\n'
        # maybe could split this into a 2nd stdout or stder ..see above
        content += sandboxErrorMessage
    content += ']]>\n'
    content += '            </system-err>\n'

    content += '        </testcase>\n'
    content += '    </testsuite>\n'

    # see if adding nosetests makes michal's stuff pick it up??
    # and "test_" prefix"
    x = './test_' + os.path.basename(name) + '.nosetests.xml'
    with open(x, 'wb') as f:
        f.write(content)
    #f = open(x, 'w')
    #f.write(content)
    #f.close()

#**************************************************************************
# belt and suspenders. Do we really need to worry about this?
def terminate_process_tree(pid, including_parent=True):
    parent = psutil.Process(pid)
    for child in parent.get_children(recursive=True):
        try:
            child.terminate()
        except psutil.NoSuchProcess:
            print "terminate_process_tree:", "NoSuchProcess. couldn't terminate child process with pid %s" % child.pid()
        except psutil.AccessDenied:
            print "terminate_process_tree:", "couldn't terminate child process with pid %s" % child.pid()
        else:
            child.wait(timeout=3)

    if including_parent:
        try:
            parent.terminate()
        except psutil.NoSuchProcess:
            print "terminate_process_tree:", "NoSuchProcess. couldn't terminate parent process with pid %s" % parent.pid()
            pass
        except psutil.AccessDenied:
            print "terminate_process_tree:", "AccessDenied. couldn't terminate parent process with pid %s" % parent.pid()
        else:
            parent.wait(timeout=3)

def terminate_child_processes():
    me = os.getpid()
    terminate_process_tree(me, including_parent=False)

#**************************************************************************
def rc_if_exists_and_done(ps):
    try:
        rc = ps.wait(0)
    except psutil.TimeoutExpired:
        # not sure why I'm getting this
        print "Got TimeoutExpired on the R subprocess, may be legal"
        rc = None
    except psutil.NoSuchProcess:
        raise Exception("The R subprocess disappeared when we thought it should still be there")
    except psutil.AccessDenied:
        raise Exception("The R subprocess gave us AccessDenied")

    # rc = None means it already completed?
    # FIX! Is it none if we get a timeout exception on this python ..how is that captured?
    if rc:
        # increment the global errors count if we get a non-zero rc. non-zero rc should only happen once?
        error = 1
        print "rc_if_exists_and_done: got non-zero rc: %s" % rc
    else:
        error = 0
    return (rc, error)

#**************************************************************************
def sh2junit(name='NoName', cmd_string='/bin/ls', timeout=300, shdir=None, **kwargs):
    # split by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed)
    print "cmd_string:", cmd_string
    cmdList = cmd_string.split()
    # these are absolute paths
    outfd, outpath = sandbox_tmp_file(prefix=name + '.stdout.', suffix='.log')
    errfd, errpath = sandbox_tmp_file(prefix=name + '.stderr.', suffix='.log')

    # make outpath and errpath full paths, so we can redirect
    print "outpath:", outpath
    print "errpath:", errpath

    start = time.time()
    print "psutil.Popen:", cmdList, outpath, errpath
    import subprocess
    # start the process in the target dir, if desired
    if shdir:
        currentDir = os.getcwd()
        os.chdir(shdir)
    ps = psutil.Popen(cmdList, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
    if shdir:
        os.chdir(currentDir)

    comment = 'PID %d, stdout %s, stderr %s' % (
        ps.pid, os.path.basename(outpath), os.path.basename(errpath))
    print "spawn_cmd", cmd_string, comment

    # Reads the subprocess stdout until it is closed and
    # ...echo it our python stdout and also the R stdout file in sandbox
    # Then wait for the program to exit.
    # Read before wait so that you don't risk the pipe filling up and hanging the program.
    # You wait after read for the final program exit and return code.
    # If you don't wait, you'll get a zombie process (at least on linux)

    # this might not do what we want..see:
    # http://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line
    # I suppose we'll stop early?

    # shouldn't need a delay before checking this?
    if not ps.is_running():
        raise Exception("sh2junit: not immediate ps.is_running after start")

    # Until we get the rc, it can be a zombie process.
    # A zombie process is not a real process.
    # it's just a remaining entry in the process table until the parent process requests the child's return code.
    # The actual process has ended and requires no other resources but said process table entry.
    linesMayExist = True
    errors = 0
    timeoutError = False
    while linesMayExist:
        # get whatever accumulated, up to nothing returned
        # only do up to 20 lines before we check timeout again
        # why was R processes not completing on centos?
        # linesMayExist = ps.is_running() and not ps.status() == psutil.STATUS_ZOMBIE
        linesMayExist = ps.is_running()
        lineBurstCnt = 0
        # stdout from subprocess
        line = ps.stdout.readline()

        # R apparently uses stderr a lot, so want to mix that in. We don't grab it until we hit a stall in R stdout though.
        while line:
            lineBurstCnt += 1
            # maybe I should use p.communicate() instead. have to keep it to stdout? or do stdout+stderr here
            sys.stdout.write("R->" + line) # to our python stdout, with a prefix so it's obviously from R
            os.write(outfd, line) # to sandbox R stdout
            elapsed = time.time() - start
            if elapsed > timeout:
                timeoutError = True
                errors += 1
                print "ERROR: sh2junit: elapsed: %0.2f timeout: %s (secs) while echoing subprocess stdout" % (elapsed, timeout)
                #kill R subprocess but don't kill me
                terminate_process_tree(ps.pid, including_parent=False)
                break
            line = ps.stdout.readline()
        if timeoutError:
            print "\n\n\nERROR: timeout"
            break
        # stderr from subprocess
        line = ps.stderr.readline()
        while line:
            lineBurstCnt += 1
            sys.stdout.write("Re->" + line) # to our python stdout, with a prefix so it's obviously from R stderr
            os.write(errfd, line) # to sandbox R stderr
            line = ps.stderr.readline()
        print "lineBurstCnt:", lineBurstCnt

        # Check. may have flipped to not running, and we just got the last bit.
        # shouldn't be a race on a transition here, if ps.wait(0) completion syncs the transition
        if linesMayExist:
            print "ps.is_running():", ps.is_running(), ps.pid, ps.name, ps.status, ps.create_time
            # unload the return code without waiting..so we don't have a zombie!

        (lastrc, error) = rc_if_exists_and_done(ps)
        errors += error

        elapsed = time.time() - start
        # forever if timeout is None
        #if timeout and elapsed > timeout:
        if elapsed > timeout:
            timeoutError = True
            errors += 1
            # we don't want to exception here, because we're going to print the xml that says there's an error
            # I guess we'll end up terminating the R process down below
            # could we have lines in stdout we didn't catch up on? maybe, but do we care?
            print "ERROR: sh2junit: elapsed: %0.2f timeout: %s (secs) while echoing subprocess stdout" % (elapsed, timeout)
            #kill R subprocess but don't kill me
            #terminate_process_tree(ps.pid, including_parent=False)
            break
        # wait for some more output to accumulate
        time.sleep(0.25)

    # It shouldn't be running now?

    # timeout=None waits forever. timeout=0 returns immediately.
    # default above is 5 minutes
    # Wait for process termination. Since child:  return the exit code.
    # If the process is already terminated does not raise NoSuchProcess exception
    # but just return None immediately.
    # If timeout is specified and process is still alive raises psutil.TimeoutExpired() exception.
    # old
    # rc = ps.wait(timeout)
    (lastrc, error) = rc_if_exists_and_done(ps)
    errors += error
    elapsed = time.time() - start

    # Prune h2o logs to interesting lines and detect errors.
    # Error lines are returned. warning/info are printed to our (python stdout)
    # so that's always printed/saved?
    # None if no error
    sandboxErrorMessage = h2o_sandbox.check_sandbox_for_errors(
        LOG_DIR='./sandbox',
        python_test_name=name,
        cloudShutdownIsError=True,
        sandboxIgnoreErrors=True) # don't take exception on error

    if sandboxErrorMessage:
        errors += 1

    out = file(outpath).read()
    err = file(errpath).read()
    create_junit_xml(name, out, err, sandboxErrorMessage, errors=errors, elapsed=elapsed)

    if not errors:
        return (errors, outpath, errpath)
    else:
        # dump all the info as part of the exception? maybe too much
        # is this bad to do in all cases? do we need it?
        hline = "\n===========================================BEGIN DUMP=============================================================\n"
        hhline = "\n===========================================END DUMP=============================================================\n"
        out = '[stdout->err]: '.join(out.splitlines(True))
        err = '[sterr->err]: '.join(err.splitlines(True))
        if ps.is_running():
            print "Before terminate:", ps.pid, ps.is_running()
            terminate_process_tree(ps.pid, including_parent=True)
        if sandboxErrorMessage:
            print "\n\n\nError in Sandbox. Ending test. Dumping sub-process output.\n"
            print hline
            raise Exception("%s %s \n\tlastrc:%s \n\terrors:%s \n\tErrors found in ./sandbox log files?.\nR stdout:\n%s\n\nR stderr:\n%s\n%s" %
                (name, cmd_string, lastrc, errors, out, err, hhline))
        # could have already terminated?
        elif timeoutError:
            print "\n\n\nTimeout Error. Ending test. Dumping sub-process output.\n"
            print hline
            raise Exception("%s %s \n\tlastrc:%s \n\terrors:%s \n\ttimed out after %d secs. \nR stdout:\n%s\n\nR stderr:\n%s\n%s" %
                (name, cmd_string, lastrc, errors, timeout or 0, out, err, hhline))
        else:
            print "\n\n\nCaught exception. Ending test. Dumping sub-process output.\n"
            print hline
            raise Exception("%s %s \n\tlastrc:%s \n\terrors:%s \n\tLikely non-zero exit code from R.\nR stdout:\n%s\n\nR stderr:\n%s\n%s" %
                (name, cmd_string, lastrc, errors, out, err, hhline))

#**************************************************************************
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-shdir', type=str, default=None, help='executes the $cmd in the target dir, but the logs stay in sandbox here')
    parser.add_argument('-name', type=str, default='NoName', help='used to help name the xml/stdout/stderr logs created')
    parser.add_argument('-timeout', type=int, default=5, help='secs timeout for the shell subprocess. Fail if timeout')
    parser.add_argument('-cmd', '--cmd_string', type=str, default=None, help="cmd string to pass to shell subprocess. Better to just use'--' to start the cmd (everything after that is sucked in)")
    parser.add_argument('Rargs', nargs=argparse.REMAINDER)
    args = parser.parse_args()

    if args.cmd_string:
        cmd_string = args.cmd_string
    else:
        # easiest way to handle multiple tokens for command
        # end with -- and this grabs the rest
        # drop the leading '--' if we stopped parsing the rest that way
        if args.Rargs:
            print "args.Rargs:", args.Rargs
            if args.Rargs[0]=='--':
                args.Rargs[0] = ''
            cmd_string = ' '.join(args.Rargs)
        else:
            # placeholder for test
            cmd_string = '/bin/ls'

    sh2junit(name=args.name, cmd_string=cmd_string, timeout=args.timeout, shdir=args.shdir)


text:
class Test
end


text:
package smtp

import (
	"crypto/tls"
	"fmt"
	"net/smtp"

	"github.com/pkg/errors"
)

// Config contains configuration for SMTP authentication.
//
// ⚠ WARNING: Change to the field name must preserve the INI key name for backward compatibility.
type Config struct {
	Auth           string
	Host           string
	Port           int
	AllowedDomains string
	TLS            bool `ini:"tls"`
	SkipVerify     bool
}

func (c *Config) doAuth(auth smtp.Auth) error {
	client, err := smtp.Dial(fmt.Sprintf("%s:%d", c.Host, c.Port))
	if err != nil {
		return err
	}
	defer client.Close()

	if err = client.Hello("gogs"); err != nil {
		return err
	}

	if c.TLS {
		if ok, _ := client.Extension("STARTTLS"); ok {
			if err = client.StartTLS(&tls.Config{
				InsecureSkipVerify: c.SkipVerify,
				ServerName:         c.Host,
			}); err != nil {
				return err
			}
		} else {
			return errors.New("SMTP server does not support TLS")
		}
	}

	if ok, _ := client.Extension("AUTH"); ok {
		if err = client.Auth(auth); err != nil {
			return err
		}
		return nil
	}
	return errors.New("unsupported SMTP authentication method")
}


text:
For a simple local development environment, you will need:

* [A supported version of PHP](http://php.net/supported-versions.php)
* `php5-json`
* `php5-curl`

Then inside the project directory, run `php -S localhost:8000 router.php`. Next, just navigate to [localhost:8000](http://localhost:8000/) to view the site.

## Nginx Web Server

For a full web-server environment, which includes more redirect and permissions you may find useful, you will need:

* [A supported version of PHP](http://php.net/supported-versions.php)
* `php5-json`
* `php5-curl`
* The latest stable version of [Nginx](http://nginx.org)

Then, we need to configure Nginx. To start, open up a configuration file in Nano.

```bash
sudo nano /etc/nginx/sites-enabled/mvp.conf
```

Then, paste in required configuration in, modifying the root, include and error_log paths.

```
server {
    listen 80;
    server_name mvp.localtest.me;
    root /path/to/mvp;
    include /path/to/mvp/nginx.conf;
    error_log /path/to/error.log;
}
```

You can test the configuration with Nginx.

```bash
sudo nginx -t
```

Now we just need to restart the service.

```bash
sudo service nginx restart
```

Finally, navigate to [mvp.localtest.me](http://mvp.localtest.me)

# Code Style

 - Four space indentation
 - Remove trailing whitespaces and add an empty line at the end of each file
 - IE 9+ Compatibility

## PHP
 - `include` templates, not `require` or `_once`
 - Use full PHP tags, not short ones
 - Don't close PHP tags on PHP only files
 - Correctly format assignments for readability

```php
<?php
    include '_templates/sitewide.php';
    $page['title'] = 'HTML Safe Title';
    include '_templates/header.php';

    $foo        = bar($para, $param);
    $second_foo = 42;
    $third_foo  = 'hey';
?>
```

## HTML
 - Include `alt` attribute for all images
 - Include `title` attribute for all links
 - Close all your tags properly

## CSS
 - Try to use classes instead of IDs unless things are absolutely unique
 - One selector per line
 - Care with fallbacks and browsers compatibilities
```css
.class {
    color: #fefe89;
    font-size: 1.1em;
}

.second-class,
.third-class {
    backgound-color: white;
}
```

# Contributing

## Make a new branch and push it to GitHub.
```bash
git checkout -b feature_branch_name
git push -u origin feature_branch_name
```
## Updating from Master
```bash
git pull origin master
```
## Merge from master
```bash
git checkout feature_branch_name
git merge master
```
## Fix Merge Conflicts
TODO


text:
/**
 *
 */
package roslab.model.general;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import roslab.processors.electronics.EagleSchematic;
import roslab.processors.general.LibraryParser;

/**
 * @author Peter Gebhard
 */
public class Library {

    String name;
    List<Node> nodes;

    /**
     *
     */
    public Library() {
        this(null, null);
    }

    /**
     * @param nodes
     */
    public Library(List<Node> nodes) {
        this(null, nodes);
    }

    /**
     * @param name
     */
    public Library(String name) {
        this(name, null);
    }

    /**
     * @param name
     * @param nodes
     */
    public Library(String name, List<Node> nodes) {
        if (name == null) {
            this.name = "Default";
        }
        else {
            this.name = name;
        }
        if (nodes == null) {
            this.nodes = new ArrayList<Node>();
        }
        else {
            this.nodes = nodes;
        }
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the nodes
     */
    public List<Node> getNodes() {
        return nodes;
    }

    /**
     * @return the specified node
     */
    public Node getNode(String name) {
        for (Node n : nodes) {
            if (n.getName().equals(name)) {
                return n;
            }
        }
        return null;
    }

    /**
     * @return the nodes
     */
    public List<Node> getNodesOfClass(Class<?> clazz) {
        List<Node> subset = new ArrayList<Node>();
        for (Node n : nodes) {
            if (n.getClass().equals(clazz)) {
                subset.add(n);
            }
        }
        return subset;
    }

    /**
     * @param nodes
     *            the nodes to set
     */
    public void setNodes(List<Node> nodes) {
        this.nodes = nodes;
    }

    /**
     * @param n
     *            the node to add
     * @return
     */
    public boolean addNode(Node n) {
        if (!nodes.contains(n)) {
            return nodes.add(n);
        }
        return false;
    }

    /**
     * @param n
     *            the node to remove
     * @return
     */
    public boolean removeNode(Node n) {
        return nodes.remove(n);
    }

    public static Library loadBaseElectronicsLibrary() {
        Library lib = new Library("Base");
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("resources", "electronics_lib"))) {
            for (Path entry : stream) {
                if (entry.getFileName().toString().endsWith(".sch")) {
                    lib.addNode(EagleSchematic.buildCircuitFromSchematic(entry));
                }
            }
        }
        catch (IOException x) {
            // IOException can never be thrown by the iteration.
            // In this snippet, it can only be thrown by newDirectoryStream.
            System.err.println(x);
        }
        return lib;
    }

    /**
     * Clear the library contents and load nodes from input Library file.
     *
     * @param libraryFile
     *            the name of the Library file to load
     */
    public void loadLibrary(Path libraryPath) {
        Library lib = LibraryParser.parseLibraryYAML(libraryPath);
        this.name = lib.name;
        this.nodes.clear();
        for (Node n : lib.nodes) {
            addNode(n);
        }
    }
}


text:
//    This file is part of Gusty's Serpents
//    Copyright (C) 2009  Augustin Preda (thegusty999@gmail.com)
//
//    Gusty's Serpents is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//    Implementation of the base serpent.

#include "SerpentBase.h"
#include "GBaseEngine.h"
#include "VisualBodyPart.h"
#include "GBaseSetting.h"
#include <Ogre.h>

namespace Serpents
{
	class VisualSerpent :
		public SerpentBase
	{
	protected:
		Ogre::SceneManager * sceneManager;
		GBase::GBaseEngine * engine;

		virtual VisualBodyPart * createHeadBodyPart();
		virtual VisualBodyPart * createBodyBodyPart();

		GBase::VisibleEntityConfig srphead;
		GBase::VisibleEntityConfig srpbody;
	public:
		VisualSerpent( Ogre::SceneManager * sceneManager, GBase::GBaseEngine * someEngine );
		virtual ~VisualSerpent();
		virtual BodyPartBase* createBodyPart(int partType=0);
		virtual void setHeadConfig( GBase::VisibleEntityConfig cfg );
		virtual void setBodyConfig( GBase::VisibleEntityConfig cfg );
	};
}


text:
public class Person
{
	private String title;
	private String forename;
	private String surname;

	// ...

	public int hashcode() {  // The method is named 'hashcode'.
		int hash = 23 * title.hashCode();
		hash ^= 13 * forename.hashCode();
		return hash ^ surname.hashCode();
	}
}