text:
package controlador;

import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.Pagination;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import modelo.CheckEquipo;
import modelo.ExportExcelBaseDiagnosticos;
import controlador.ControladorErrores;

public class ControladorDiagnosticoEquipo implements Initializable {

	private CheckEquipo ch;

	@FXML TableColumn<CheckEquipo, String> tcEquipo, tcSistemaE, tcSistemaO, tcDanios, tcFallas,tcDiagnostico;
	@FXML TextArea txtDanios, txtFallas, txtDiagnostico;
	@FXML TableView<CheckEquipo> tvDiagnostico;
	@FXML TextField txtTipoEquipo,txtId,txtSistemaEquipo, txtSistemaOpe, txtBuscador;
	@FXML Label lblMensaje;
	@FXML Button guardar, btnRestaurar, btnAbrirexcel;
	@FXML CheckBox ckbInactivos;
	@FXML ToggleButton tbtnCambiar;

	private int filasXPagina, registros;
	private ControladorErrores ce;
	private ObservableList<CheckEquipo> datos;
	private FilteredList<CheckEquipo> datosBusqueda;

	@FXML Pagination paginador;

	public ControladorDiagnosticoEquipo() {
		// TODO Auto-generated constructor stub
		ch = new CheckEquipo();
		filasXPagina=10;
		datos = FXCollections.observableArrayList();
	}

	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		tcEquipo.setCellValueFactory(new PropertyValueFactory<CheckEquipo, String>("tipo_equipo"));
	    tcSistemaE.setCellValueFactory(new PropertyValueFactory<CheckEquipo, String>("sistema_equipo"));
	    tcSistemaO.setCellValueFactory(new PropertyValueFactory<CheckEquipo, String>("sistema_operativo"));
	    tcDanios.setCellValueFactory(new PropertyValueFactory<CheckEquipo, String>("danios_presentados"));
	    tcFallas.setCellValueFactory(new PropertyValueFactory<CheckEquipo, String>("falla_detectada"));
	    tcDiagnostico.setCellValueFactory(new PropertyValueFactory<CheckEquipo, String>("diagnostico"));
		//tvFilm.setItems(f.getFilms());

		// llenar table view

		llenarTableView(true);;
}

	// #regionmetodos paginacion

	private Node createPage(int pageIndex){
		int fromIndex = pageIndex * filasXPagina;
		int toIndex = Math.min(fromIndex + filasXPagina, datosBusqueda.size());
		tvDiagnostico.setItems(FXCollections.observableArrayList(
				datosBusqueda.subList(fromIndex, toIndex)));
		return new BorderPane(tvDiagnostico);
	}

	public void llenarTableView(Boolean estatus){
		try {
			//Refrescar y volver a cargar los datos en el TableView
			datos=ch.getCheckEquipos();
			datosBusqueda = new FilteredList<>(datos);
			paginador.setPageCount((int)(Math.ceil((double)datosBusqueda.size()/filasXPagina)));
			paginador.setPageFactory((Integer pagina) -> createPage(pagina));
			lblMensaje.setText(datos.size() + " registros encontrados.");
		} catch (Exception ex) {
			ce.printlog(ex.getMessage(), this.getClass().toString());
			lblMensaje.setText("Se ha producido un error al recuperar los datos.");
		}

	}

	@FXML public void click_TableView(){

		if(tvDiagnostico.getSelectionModel().getSelectedItem()!=null){
			ch = tvDiagnostico.getSelectionModel().getSelectedItem();

			txtId.setText(ch.getId_check_equipo().toString());
			txtTipoEquipo.setText(ch.getTipo_equipo().toString());
			txtSistemaEquipo.setText(ch.getSistema_equipo().toString());
			txtSistemaOpe.setText(ch.getSistema_operativo().toString());
			txtDanios.setText(ch.getDanios_presentados().toString());
			txtFallas.setText(ch.getFalla_detectada().toString());
			txtDiagnostico.setText(ch.getDiagnostico().toString());

			txtId.setDisable(true);
		}

	}

	@FXML public void click_insertar(){
		System.out.println("****************************");
		try{
			if(txtTipoEquipo.getText().trim().isEmpty() ||
					txtSistemaEquipo.getText().trim().isEmpty()||
					txtSistemaOpe.getText().trim().isEmpty()||
					txtDanios.getText().trim().isEmpty()||
					txtFallas.getText().trim().isEmpty()||
					txtDiagnostico.getText().trim().isEmpty()){
				lblMensaje.setText("Faltan datos por ingresar.");
				System.out.println("****************************");
			}
			else{
				ch = new CheckEquipo();
				ch.setTipo_equipo(new SimpleStringProperty(txtTipoEquipo.getText()));
				ch.setSistema_equipo(new SimpleStringProperty(txtSistemaEquipo.getText()));
				ch.setSistema_operativo(new SimpleStringProperty(txtSistemaOpe.getText()));
				ch.setDanios_presentados(new SimpleStringProperty(txtDanios.getText()));
				ch.setFalla_detectada(new SimpleStringProperty(txtFallas.getText()));
				ch.setDiagnostico(new SimpleStringProperty(txtDiagnostico.getText()));
				boolean yes = ch.insertar();
				if(yes){
					lblMensaje.setText("Datos insertados satisfactoriamente.");
					llenarTableView(true);
					limpiar();
				}
				else{
					lblMensaje.setText("Se ha producido un error en el servidor");
				}
			}
		}catch(Exception ex){
			ce.printlog(ex.getMessage(), this.getClass().toString());
			lblMensaje.setText("Se ha producido un error en el servidor");
		}
	}

	public void limpiar(){
		txtId.clear();
		txtTipoEquipo.clear();
		txtSistemaEquipo.clear();
		txtSistemaOpe.clear();
		txtDanios.clear();
		txtFallas.clear();
		txtDiagnostico.clear();

	}

	//Método para actualizar un registro en el TableView
		@FXML public void click_actualizar(){
			try {
				if(txtId.getText().isEmpty() ||
						txtTipoEquipo.getText().isEmpty() ||
						txtSistemaEquipo.getText().trim().isEmpty() ||
						txtSistemaOpe.getText().trim().isEmpty() ||
						txtDanios.getText().trim().isEmpty() ||
						txtFallas.getText().trim().isEmpty() ||
						txtDiagnostico.getText().trim().isEmpty()){
					lblMensaje.setText("Faltan datos por llenar");
				}
				else{
					ch = new CheckEquipo ();
					ch.setId_check_equipo(new SimpleIntegerProperty(Integer.valueOf(txtId.getText())));
					ch.setTipo_equipo(new SimpleStringProperty(txtTipoEquipo.getText()));
					ch.setSistema_equipo(new SimpleStringProperty(txtSistemaEquipo.getText()));
					ch.setSistema_operativo(new SimpleStringProperty(txtSistemaOpe.getText()));
					ch.setDanios_presentados(new SimpleStringProperty(txtDanios.getText()));
					ch.setFalla_detectada(new SimpleStringProperty(txtFallas.getText()));
					ch.setDiagnostico(new SimpleStringProperty(txtDiagnostico.getText()));
					boolean yes = ch.actualizar();
					if(yes){
						lblMensaje.setText("Datos actualizados satisfactoriamente.");
						llenarTableView(true);
						limpiar();
					}
					else{
						lblMensaje.setText("Se ha producido un error en el servidor");
					}
				}
			}catch(Exception ex){
				ce.printlog(ex.getMessage(), this.getClass().toString());
				lblMensaje.setText("Se ha producido un error en el servidor");
			}
		}
 /*
		public void CheckTabla(){
			try {
				// llenar table view
				datos= ch.getCheckEquipos(false);
				datosBusqueda =new FilteredList<>(datos);
				paginador.setPageCount(datosBusqueda.size()/filasXPagina);
				paginador.setPageFactory((Integer pagina)->createPage(pagina));
				registros = datosBusqueda.size();
				lblMensaje.setText( registros + " Registros encontrados");
				txtId.setDisable(false);
			} catch (Exception ex) {
				ce.printlog(ex.getMessage(), this.getClass().toString());
				lblMensaje.setText("Se ha producido un error al recuperar los datos.");
			}
		}
	/*
		@FXML public void cambiarClientes(){
			if(tbtnCambiar.isSelected()){

				try {
					datos= cl.getClientesDeleted();
					btnRestaurar.setDisable(false);
				} catch (SQLException ex) {
					// TODO Auto-generated catch block
					ce.printlog(ex.getMessage(), this.getClass().toString());
				}
			}
			else{
				try {
					btnRestaurar.setDisable(true);
					datos= cl.getClientes(false);
				} catch (SQLException ex) {
					// TODO Auto-generated catch block
					ce.printlog(ex.getMessage(), this.getClass().toString());
				}
			}
			try {
				// llenar table view
				datosBusqueda =new FilteredList<>(datos);
				paginador.setPageCount(datosBusqueda.size()/filasXPagina);
				paginador.setPageFactory((Integer pagina)->createPage(pagina));
				registros = datosBusqueda.size();
				lblMensaje.setText( registros + " Registros encontrados");
				txtId.setDisable(false);
			} catch (Exception ex) {
				ce.printlog(ex.getMessage(), this.getClass().toString());
				lblMensaje.setText("Se ha producido un error al recuperar los datos.");
			}
		}

		@FXML public void restaurar(){
			if(cl != null){
				if(cl.restaurar()){
					cambiarClientes();
					limpiar();
					lblMensaje.setText("Registro restaurado.");
				}
				else{
					lblMensaje.setText("Se ha producido un error al recuperar los datos.");
				}
			}
			else{
				lblMensaje.setText("No se ha seleccionado un registro.");
			}
		}

*/

		//Método para mostrar los registros dados de baja
		@FXML public void click_inactivos(){
			if(ckbInactivos.isSelected())
				llenarTableView(false);
			else
				llenarTableView(true);
		}

		//Método para incorporar otro lenguaje.
		//@FXML public void clickLanguage(){
		//	try {
		//		ventanas.modal("../view/fxml/Language.fxml","Lenguaje");
		//		cbLanguage.setItems(l.getLanguage());
		//	} catch (SQLException ex) {
		//		// TODO Auto-generated catch block
		//		ce.printlog(ex.getMessage(), this.getClass().toString());
		//	}
		//}

		@FXML
	 	public void Abrirexcel() {
	        new ExportExcelBaseDiagnosticos().WriteExcel();
	        String File = new String("src/archivos/Diagnosticos.xls");

			 try{
			   //definiendo la ruta en la propiedad file
			   Runtime.getRuntime().exec("cmd /c start "+File);

			   }catch(IOException ex){
				  ce.printlog(ex.getMessage(), this.getClass().toString());
			   }
		}

		// #region Buscador
	 	@FXML public void buscarTexto(){
	 		if(txtBuscador.getText().trim().isEmpty()){
	 			//Llenar TableView
	 			datosBusqueda= new FilteredList<>(datos);
	 			filasXPagina=10;
				paginador.setPageCount(datosBusqueda.size()/filasXPagina);
				paginador.setPageFactory((Integer pagina) -> createPage(pagina));
				lblMensaje.setText(datosBusqueda.size() + " registros encontrados en la Base de Datos.");
	 		}
	 		else{
	 			try{
		 			datosBusqueda.setPredicate(CheckEquipo->CheckEquipo.getTipo_equipo().toLowerCase().
		 					contains(txtBuscador.getText().toLowerCase()));
		 			if(datosBusqueda.size()<10)
		 				filasXPagina= datosBusqueda.size();
		 			else
		 				filasXPagina=10;
		 			paginador.setPageCount(datosBusqueda.size()/filasXPagina);
					paginador.setPageFactory((Integer pagina) -> createPage(pagina));
					lblMensaje.setText("Se encontraron " + datosBusqueda.size() + " coincidencias.");
	 			}
	 			catch(Exception ex){
	 				//Enviar mensaje
	 				ce.printlog(ex.getMessage(), this.getClass().toString());
	 				lblMensaje.setText("No se encontraron resultados");
	 				filasXPagina=0;
	 				paginador.setPageCount(filasXPagina);
					paginador.setPageFactory((Integer pagina) -> createPage(pagina));
	 			}
	 		}

	 	}
	 	// #endregion

	}


text:
require 'java'
require "java_to_base64/version"
require 'i_can_has_java_class'

unless ::ICanHasJavaClass.java_class_defined?("org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString")
  require 'java_to_base64/jars/commons-codec-1.9.jar'
end

module JavaToBase64
  def self.included(klass)
    unless java_instance_of?(klass, ::Java::JavaIo::Serializable)
      warn <<-SERIALIZABLE
        To include JavaToBase64 in a Java class you must implement java.io.Serializable
      SERIALIZABLE
    end

    klass.class_eval do
      include ::JavaToBase64::InstanceMethods
      extend ::JavaToBase64::ClassMethods
    end
  end

  def self.java_instance_of?(klass, klass_or_module)
    return klass.kind_of?(klass_or_module) || klass.included_modules.include?(klass_or_module)
  end

  module InstanceMethods
    def to_base64
      byte_array_output_stream = java.io.ByteArrayOutputStream.new
      object_output_stream = java.io.ObjectOutputStream.new(byte_array_output_stream)
      object_output_stream.write_object(self)
      bytes = byte_array_output_stream.to_byte_array

      return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(bytes)
    end
  end

  module ClassMethods
    def from_base64(base64_string)
      decoded_form = org.apache.commons.codec.binary.Base64.decodeBase64(base64_string)
      byte_array_input_stream = java.io.ByteArrayInputStream.new(decoded_form)
      # NOTE: JRuby ObjectInputStream https://github.com/ribrdb/jruby/commit/8ab064f4fffc86f89d5ceca1cbf29a6783b83802
      # Overrides the class loader to allow for JRuby objects to be deserialized correctly
      jruby_input_stream = org.jruby.util.JRubyObjectInputStream.new(::JRuby.runtime, byte_array_input_stream)

      return jruby_input_stream.read_object
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
chocolatey-packages
===================
Repo housing the Chocolatey packages that I maintain.

https://chocolatey.org/profiles/Spinarooni


text:
package hr.fer.zemris.jcms.web.actions2.course.market;

import hr.fer.zemris.jcms.service2.course.market.MarketBrowserService;
import hr.fer.zemris.jcms.web.actions.Ext2ActionSupport;
import hr.fer.zemris.jcms.web.actions.annotations.WebClass;
import hr.fer.zemris.jcms.web.actions.annotations.WebMethodInfo;
import hr.fer.zemris.jcms.web.actions.data.MPGroupsListData;

@WebClass(dataClass=MPGroupsListData.class)
public class MPGroupsList extends Ext2ActionSupport<MPGroupsListData> {

	private static final long serialVersionUID = 2L;

	@WebMethodInfo
    public String execute() throws Exception {
		MarketBrowserService.getMarketPlacesListForCourseInstance(getEntityManager(), data);
        return null;
    }

    public String getCourseInstanceID() {
		return data.getCourseInstanceID();
	}
    public void setCourseInstanceID(String courseInstanceID) {
		data.setCourseInstanceID(courseInstanceID);
	}
}


text:
namespace WindsorWebApi.Model
{
    public class ErrorInfo
    {
        public string Type { get; set; }
        public string Message { get; set; }
    }
}


text:
#import "SCAuthService.h"
#import "SCBackendService.h"
#import "SCCache.h"
#import "SCConfigService.h"
#import "SCDataService.h"
#import "SCFileUtils.h"
#import "SCGeoJSON.h"
#import "SCJavascriptCommands.h"
#import "SCLineString.h"
#import "SCRasterStore.h"
#import "SCSensorService.h"
#import "SCService.h"
#import "SCServiceGraph.h"
#import "SCSimplePoint.h"
#import "SCSpatialStore.h"
#import "SCSpatialStore.h"
#import "SCStoreStatusEvent.h"
#import "WebViewJavascriptBridge.h"
#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>

@interface SpatialConnect : NSObject

@property(readonly) SCSensorService *sensorService;
@property(readonly) SCDataService *dataService;
@property(readonly) SCConfigService *configService;
@property(readonly) SCAuthService *authService;
@property(readonly) SCBackendService *backendService;

@property(readonly, strong) SCCache *cache;

/*!
 @description This singleton of SpatialConnect is shared across your app.

 @return instance of SpatialConnect
 */
+ (id)sharedInstance;

/*!
 @discussion This starts all the services in the order they were added. Data,
 Sensor, Config, and Auth are all started. Backend Service waits for the Config
 service to find a remote backend.

 @brief Starts all the services
 */
- (void)startAllServices;

/*!
 @discussion Stops all the services in the order they were added to the services
 dictionary.

 @brief Stops the services
 */
- (void)stopAllServices;

/*!
 @description Stops all the services and then restarts them in the order they
 are added to the dictionary.

 @brief Restarts the services
 */
- (void)restartAllServices;

/*!
 @description Adds an instantiated instance of Service that extends the
 SCService class. The 'service' must extend the SCService class.

 @brief Adds a service to the SpatialConnect instance

 @param service instance of SCService class
 */
- (void)addService:(SCService *)service;

/*!
 @description This stops and removes a service from the SpatialConnect instance.

 @brief Removes a service from the SpatialConnect instance

 @param serviceId Service's unique identifier
 */
- (void)removeService:(NSString *)serviceId;

/*!
 @discussion This is the preferred way to start a service.

 @warning Do not call service start on the service instance. Use this method to
 start a service.

 @brief Starts a single service

 @param serviceId the unique id of the service.
 */
- (void)startService:(NSString *)serviceId;

/*!
 @discussion This is the preferred way to stop a service.

 @warning Do not call service stop on the service instance. Use this method to
 stop a service.

 @brief Stops a single service

 @param serviceId the unique id of the service.
 */
- (void)stopService:(NSString *)serviceId;

/*!
 @discussion This is the preferred way to restart a service.

 @warning Do not call service restart on the service instance. Use this method
 to start a service.

 @brief Restarts a single service

 @param serviceId the unique id of the service.
 */
- (void)restartService:(NSString *)serviceId;

/*!
 @discussion If you have an instance of SpatialConnect Server, this is how you
 would register it. Passing in a remote configuration object will use the info
 to start the connection to the backend.

 @brief Connects to SpatialConnect Server

 @param r remote configuration
 */
- (void)connectBackend:(SCRemoteConfig *)r;

/*

 */
- (void)connectAuth:(id<SCAuthProtocol>)ap;

- (void)updateDeviceToken:(NSString *)token;

/*!
 @discussion this is the unique identifier that is App Store compliant and used
 to uniquely identify the installation id which is unique per install on a
 device. ID's tied to the hardware are not allowed to be used by the app store

 @brief unique identifier

 @return UUID string of the install id.
 */
- (NSString *)deviceIdentifier;

/*!
 @description emits an SCServiceStatusEvent when the service is running. If the
 service isn't started, this will wait until it is started. This can be used by
 your
 app to start wiring up functionality waiting for it to occur. This is the best
 way to know if a service is started. If the service is already started, it will
 return an event immediately. You can also receive errors in the subscribe's
 error block. The observable will complete when the store is confirmed to have
 started.

 @brief An observable to listen for store start

 @param serviceId a services unique id

 @return RACSignal that emits when the service is running
 */
- (RACSignal *)serviceRunning:(NSString *)serviceId;

- (SCService *)serviceById:(NSString *)serviceId;

- (SCDataService *)dataService;
- (SCConfigService *)configService;
- (SCAuthService *)authService;
- (SCBackendService *)backendService;
- (SCSensorService *)sensorService;

@end


text:
//
//  WYNavHeaderView.h
//  NavDemo
//
//  Created by lwy1218 on 2017/8/9.
//  Copyright © 2017年 lwy1218. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "WYPageConfig.h"
@class WYPageTitleView;

@protocol WYPageTitleViewDataSource <NSObject>

@required

/**
 自定义指示器view 在自定义指示器的时候需要实现该代理方法

 @param pageTitleView self
 @return 自定义view 如果没有frame 则会按照'config'的
 */
- (UIView *)customIndicatorViewForPageTitleView:(WYPageTitleView  *)pageTitleView;

@optional

/**
 自定义指示器view的滚动效果

 @param indicatorView 指示器view
 @param progress 进度
 @param sourceIndex sourceIndex
 @param targetIndex targetIndex
 */
- (void)setCustomIndicatorViewScrollAnimation:(UIView *)indicatorView
                                     progress:(double)progress
                                  sourceIndex:(NSInteger)sourceIndex
                                  targetIndex:(NSInteger)targetIndex;

@end
@protocol WYPageTitleViewDelegate <NSObject>

/**
 按钮点击事件的代理

 @param pageTitleView pageTitleView
 @param selectdIndex 当前按钮下标
 @param oldIndex 上一次点击的按钮下标
 */
- (void)pageTitleView:(WYPageTitleView *)pageTitleView
     selectdIndexItem:(NSInteger)selectdIndex
             oldIndex:(NSInteger)oldIndex;

@end
@interface WYPageTitleView : UIView

@property (nonatomic , weak) id<WYPageTitleViewDelegate>delegate;

/** 自定义指示器的时候的数据源 */
@property (nonatomic , weak) id<WYPageTitleViewDataSource>dataSource;

/**
 指示器类型
 */
@property (nonatomic , assign) WYPageTitleIndicatorViewStyle indicatorStyle;

/** 指示器view */
@property (nonatomic , strong, readonly) UIView *indicatorView;
/**
 初始化

 @param frame frame
 @param titles 标题数组
 @param config config
 @param dataSource 数据源
 @return self
 */
- (instancetype)initWithFrame:(CGRect)frame
                       titles:(NSArray <NSString *>*)titles
                       config:(WYPageConfig *)config
                   dataSource:(id<WYPageTitleViewDataSource>)dataSource;

/**
 初始化

 @param frame frame
 @param titles 标题数组
 @param config config
 @return self
 */
- (instancetype)initWithFrame:(CGRect)frame
                       titles:(NSArray<NSString *> *)titles
                       config:(WYPageConfig *)config;

/**
 设置item的title

 @param progress 翻页进度
 @param sourceIndex 源index
 @param targetIndex 目标index
 */
- (void)setTitleWithProgress:(double)progress
                 sourceIndex:(NSInteger)sourceIndex
                 targetIndex:(NSInteger)targetIndex;

/**
 设置mainView的偏移量 contentView滚动结束后调用

 @param currentIndex 下标
 */
- (void)setHeaderContentOffsetWithCurrentIndex:(NSInteger)currentIndex;

/**
 设置对应下标的选中效果

 @param currentIndex 下标
 */
- (void)setupSelectedIndex:(NSInteger)currentIndex;

/**
 获取对应下标位置的按钮

 @param index 下标
 @return 按钮
 */
- (UIButton *)getItemWithIndex:(NSInteger)index;

/**
 刷新标题

 @param titles 标题组
 */
- (void)reloadTitles:(NSArray *)titles;

@end


text:
* cooluri.war

## Required

* Java 8
* Tomcat

## Development Hints

The code was developed in `NetBeans IDE 8.1`, using `Java EE 7 Web`, `JDK 1.8` and `Maven 4.0`.

## Idea

* cool URI via: `http://localhost:8084/id/*`
* document representaion via: `http://localhost:8084/data/*`

## Configuration

Copy the `config.properties.template` to `config.properties`.

`cp /cooluri/src/main/resources/config.properties.template /cooluri/src/main/resources/config.properties`.

Set `API_HOST` to e.g. `API_HOST=http://localhost:8084/data/*` if the host ist your localhost.

## Example

URI of a Ressource `http://localhost:8084/id/*` like `http://localhost:8084/id/items/xyz*` will be redirected including the header params via "303 See Other" to `http://localhost:8084/data/*` like `http://localhost:8084/data/items/xyz*`.

## Credits / Developers

`Florian Thiery M.Sc.`


text:
package test.java;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import main.java.InvalidPositionException;
import main.java.Position;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PositionTest
{
    final Logger logger = LoggerFactory.getLogger(PositionTest.class);

    @Test()
    public void testErrorThrownIfPositionIsCreatedOutsideOfGrid()
    {
        int numExceptions = 0;

        /*Try to create positions above and below the grid*/
        for (int column = -1; column <= 8; column++)
        {
            try
            {
                Position position = new Position(-1, column);
            } catch (InvalidPositionException ex)
            {
                numExceptions += 1;
            }
            try
            {
                Position position = new Position(8, column);
            } catch (InvalidPositionException ex)
            {
                numExceptions += 1;
            }
        }

        /*Try to create positions to the right and left of the grid*/
        for (int row = 0; row <= 7; row++)
        {
            try
            {
                Position position = new Position(row, -1);
            } catch (InvalidPositionException ex)
            {
                numExceptions += 1;
            }
            try
            {
                Position position = new Position(row, 8);
            } catch (InvalidPositionException ex)
            {
                numExceptions += 1;
            }
        }
        /*36 b/c there are 36 positions outlining the board that were tested*/
        assertEquals(numExceptions, 36);
    }

    @Test()
    public void testNoErrorThrownIfPositionIsCreatedInsideGrid()
    {
        for (int row = 0; row < 8; row++)
        {
            for (int column = 0; column < 8; column++)
            {
                try
                {
                    Position position = new Position(row, column);
                } catch (InvalidPositionException ex)
                {
                    logger.error(ex.getMessage());
                    System.exit(1);
                }
            }
        }
    }

    @Test()
    public void testEquals()
    {
        try
        {
            Position position1 = new Position(0, 0);
            Position position2 = new Position(0, 0);
            Position position3 = new Position(0, 1);
            Position position4 = new Position(1, 0);
            Position position5 = new Position(1, 1);

            assertTrue(position1.equals(position2));

            assertFalse(position2.equals(position3));
            assertFalse(position3.equals(position4));
            assertFalse(position4.equals(position5));
        } catch (InvalidPositionException ex)
        {
            logger.error(ex.getMessage());
            System.exit(1);
        }
    }
}


text:
package org.openuap.cms.publish.config.action;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openuap.base.util.ControllerHelper;
import org.openuap.cms.config.CMSConfig;
import org.openuap.cms.core.action.AdminAction;
import org.springframework.web.servlet.ModelAndView;

/**
 *

 * 内容发布配置
 *

 *
 *

 * $Id: PublishConfigAction.java 4026 2011-03-22 14:58:42Z orangeforjava $
 *

 *
 * @author Joseph
 * @version 1.0
 */
public class PublishConfigAction extends AdminAction {

	private String defaultViewName;

	private String defaultScreensPath;

	public PublishConfigAction() {
		initDefaultViewName();
	}

	protected void initDefaultViewName() {
		defaultScreensPath = "/plugin/cms/base/screens/publish/config/";
		defaultViewName = defaultScreensPath + "config.html";
	}
	/**
	 *
	 * @param request
	 *
	 * @param response
	 *
	 * @param helper
	 *
	 * @param model
	 *
	 * @return
	 */
	public ModelAndView perform(HttpServletRequest request,
			HttpServletResponse response, ControllerHelper helper, Map model) {
		ModelAndView mv = new ModelAndView(defaultViewName, model);
		CMSConfig config = CMSConfig.getInstance();
		model.put("config", config);
		return mv;
	}
	/**
	 *
	 * @param request
	 * @param response
	 * @param helper
	 * @param model
	 * @return
	 */
	public ModelAndView doChange(HttpServletRequest request,
			HttpServletResponse response, ControllerHelper helper, Map model) {

		try {

			//
			Iterator iter = helper.toMap().keySet().iterator();
			//

			while (iter.hasNext()) {
				String key = (String) iter.next();
				if (key.indexOf(".") >= 0) {
					this.config.setProperty(key, helper.getString(key, ""));
				}
			}
			this.config.save();
			CMSConfig.getInstance().refresh();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		ModelAndView mv = new ModelAndView(defaultViewName, model);
		CMSConfig config = CMSConfig.getInstance();
		model.put("config", config);
		return mv;
	}

	public void setDefaultViewName(String defaultViewName) {
		this.defaultViewName = defaultViewName;
	}

	public void setDefaultScreensPath(String defaultScreensPath) {
		this.defaultScreensPath = defaultScreensPath;
	}
}


text:
using namespace std;
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>

// wrap up the window, renderer in a class

struct sdlViewport {

	// Window and Renderer.
	SDL_Window* window;
	SDL_Renderer* renderer;

	SDL_GLContext glcontext;

	int width;
	int height;

	bool gl_active;

	sdlViewport(int w, int h,const string &s,bool useGL);
	void info();
	~sdlViewport();

	SDL_Texture *CreateTexture( Uint32 format, int access, int w, int h) { return SDL_CreateTexture(renderer,format,access,w,h); };
	SDL_Texture *CreateTextureFromSurface(SDL_Surface * surface) { return SDL_CreateTextureFromSurface(renderer, surface); };

	SDL_bool TargetSupported() {return SDL_RenderTargetSupported(renderer);};
	int SetTarget(SDL_Texture *texture) {return SDL_SetRenderTarget(renderer,texture);};
	SDL_Texture * GetTarget() {return SDL_GetRenderTarget(renderer);};

	int SetLogicalSize(int w, int h) {return SDL_RenderSetLogicalSize(renderer,w,h);};
	void GetLogicalSize(int *w, int *h) {SDL_RenderGetLogicalSize(renderer,w,h);};
	int SetViewport(const SDL_Rect * rect) {return SDL_RenderSetViewport(renderer,rect);};
	void GetViewport(SDL_Rect * rect) {SDL_RenderGetViewport(renderer,rect);};
	int SetClipRect(const SDL_Rect * rect) {return SDL_RenderSetClipRect(renderer,rect);};
	void GetClipRect(SDL_Rect * rect) {SDL_RenderGetClipRect(renderer,rect);};
	int SetScale(float scaleX, float scaleY) {return SDL_RenderSetScale(renderer,scaleX,scaleY);};
	void GetScale(float *scaleX, float *scaleY) {SDL_RenderGetScale(renderer,scaleX,scaleY);};

	int SetDrawColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {return SDL_SetRenderDrawColor(renderer,r,g,b,a);};
	int GetDrawColor(Uint8 * r, Uint8 * g, Uint8 * b, Uint8 * a) {return SDL_GetRenderDrawColor(renderer,r,g,b,a);};
	int SetDrawBlendMode(SDL_BlendMode blendMode) {return SDL_SetRenderDrawBlendMode(renderer,blendMode);};
	int GetDrawBlendMode(SDL_BlendMode *blendMode) {return SDL_GetRenderDrawBlendMode(renderer,blendMode);};

	int DrawPoint(int x, int y) {return SDL_RenderDrawPoint(renderer,x,y);};
	int DrawPoints(const SDL_Point * points, int count) {return SDL_RenderDrawPoints(renderer,points,count);};
	int DrawLine(int x1, int y1, int x2, int y2) {return SDL_RenderDrawLine(renderer,x1,y1,x2,y2);};
	int DrawLines(const SDL_Point * points, int count) {return SDL_RenderDrawLines(renderer,points,count);};
	int DrawRect(const SDL_Rect * rect) {return SDL_RenderDrawRect(renderer,rect);};
	int DrawRects(const SDL_Rect * rects, int count) {return SDL_RenderDrawRects(renderer,rects,count);};

	int DrawPolygon(const vector<SDL_Point *> &verts,const  int XOffset,const  int YOffset);

	int FillRect(const SDL_Rect * rect) {return SDL_RenderFillRect(renderer,rect);};
	int FillRects(const SDL_Rect * rects, int count) {return SDL_RenderFillRects(renderer,rects,count);};

	int Copy(SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_Rect * dstrect) { return SDL_RenderCopy(renderer,texture,srcrect,dstrect);};
	int CopyEx(SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_Rect * dstrect, const double angle, const SDL_Point *center, const SDL_RendererFlip flip) { return SDL_RenderCopyEx(renderer,texture,srcrect,dstrect,angle,center,flip); };

	int ReadPixels(const SDL_Rect * rect, Uint32 format, void *pixels, int pitch) {return SDL_RenderReadPixels(renderer,rect,format,pixels,pitch);};

	void Present() {
		if(gl_active)
			SDL_GL_SwapWindow(window);
		else
			SDL_RenderPresent(renderer);
	};
	void Clear() {SDL_RenderClear(renderer); };

};

class sdlViewportEx {
	private:
		string msg;
	public:
		sdlViewportEx(const char* f, ... );
		string getMsg() { return msg; }
};

#endif


text:
package com.intellij.codeInsight.daemon;

import com.intellij.ide.PowerSaveMode;
import com.intellij.openapi.editor.HectorComponentPanel;
import com.intellij.openapi.editor.HectorComponentPanelsProvider;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author yole
 */
public class PowerSaveHectorProvider implements HectorComponentPanelsProvider {
  @Override
  public HectorComponentPanel createConfigurable(@NotNull PsiFile file) {
    return new HectorComponentPanel() {
      private final JCheckBox myCheckBox = new JCheckBox("Power Save Mode");

      @Override
      public JComponent createComponent() {
        return myCheckBox;
      }

      @Override
      public boolean isModified() {
        return myCheckBox.isSelected() != PowerSaveMode.isEnabled();
      }

      @Override
      public void apply() {
        PowerSaveMode.setEnabled(myCheckBox.isSelected());
      }

      @Override
      public void reset() {
        myCheckBox.setSelected(PowerSaveMode.isEnabled());
      }
    };
  }
}


text:
from collections import (
    namedtuple,
)

from . import channel_ids
from . import messages
from .channel_ids import (
    ChannelID,
)
from .messages import (
    Message,
)

__all__ = (
    'Datagram',
    'decode',
    'encode',
)

class Datagram(namedtuple('Datagram', ('channel_id', 'messages'))):
    """A sequence of messages that is offered as a unit to the
    underlying transport protocol (UDP, etc.) prefixed by channel ID.
    The datagram is PPSPP's Protocol Data Unit (PDU).

    .. seealso::

        - :rfc:`7574#section-1.3` (:rfc:`page 6 <7574#page-6>`)
    """
    __slots__ = ()

    def __new__(cls, channel_id, messages):
        assert all(isinstance(message, Message) for message in messages)
        return super().__new__(cls, ChannelID(channel_id), tuple(messages))

def decode(data):
    """Decodes bytes into datagram instance.

    :param memoryview data: Binary data
    :rtype: :class:`Datagram`
    """
    channel_id, rest = channel_ids.decode(data)
    return Datagram(channel_id, messages.decode(rest))

def encode(datagram):
    """Encodes datagram instance into bytes.

    :param Datagram datagram: Datagram instance
    :rtype: bytes
    """
    data = bytearray()
    data.extend(channel_ids.encode(datagram.channel_id))
    data.extend(messages.encode(datagram.messages))
    return bytes(data)


text:
using ::testing::_;
using ::testing::DoAll;
using ::testing::SaveArg;
using media::BindToCurrentLoop;

namespace content {

ACTION_P(RunClosure, closure) {
  closure.Run();
}

class MockVideoCaptureImpl : public VideoCaptureImpl {
 public:
  MockVideoCaptureImpl(media::VideoCaptureSessionId session_id,
                       VideoCaptureMessageFilter* filter,
                       base::Closure destruct_callback)
      : VideoCaptureImpl(session_id, filter),
        destruct_callback_(destruct_callback) {
  }

  ~MockVideoCaptureImpl() override { destruct_callback_.Run(); }

 private:
  base::Closure destruct_callback_;

  DISALLOW_COPY_AND_ASSIGN(MockVideoCaptureImpl);
};

class MockVideoCaptureImplManager : public VideoCaptureImplManager {
 public:
  explicit MockVideoCaptureImplManager(
      base::Closure destruct_video_capture_callback)
      : destruct_video_capture_callback_(
          destruct_video_capture_callback) {}
  ~MockVideoCaptureImplManager() override {}

 protected:
  VideoCaptureImpl* CreateVideoCaptureImplForTesting(
      media::VideoCaptureSessionId id,
      VideoCaptureMessageFilter* filter) const override {
    return new MockVideoCaptureImpl(id,
                                    filter,
                                    destruct_video_capture_callback_);
  }

 private:
  base::Closure destruct_video_capture_callback_;

  DISALLOW_COPY_AND_ASSIGN(MockVideoCaptureImplManager);
};

class VideoCaptureImplManagerTest : public ::testing::Test {
 public:
  VideoCaptureImplManagerTest()
      : manager_(new MockVideoCaptureImplManager(
          BindToCurrentLoop(cleanup_run_loop_.QuitClosure()))) {
    params_.requested_format = media::VideoCaptureFormat(
        gfx::Size(176, 144), 30, media::VIDEO_CAPTURE_PIXEL_FORMAT_I420);
    child_process_.reset(new ChildProcess());
  }

  void FakeChannelSetup() {
    scoped_refptr<base::SingleThreadTaskRunner> task_runner =
        child_process_->io_task_runner();
    if (!task_runner->BelongsToCurrentThread()) {
      task_runner->PostTask(
          FROM_HERE, base::Bind(&VideoCaptureImplManagerTest::FakeChannelSetup,
                                base::Unretained(this)));
      return;
    }
    manager_->video_capture_message_filter()->OnFilterAdded(NULL);
  }

 protected:
  MOCK_METHOD2(OnFrameReady,
               void(const scoped_refptr<media::VideoFrame>&,
                    const base::TimeTicks& estimated_capture_time));
  MOCK_METHOD0(OnStarted, void());
  MOCK_METHOD0(OnStopped, void());

  void OnStateUpdate(VideoCaptureState state) {
    switch (state) {
      case VIDEO_CAPTURE_STATE_STARTED:
        OnStarted();
        break;
      case VIDEO_CAPTURE_STATE_STOPPED:
        OnStopped();
        break;
      default:
        NOTREACHED();
    }
  }

  base::Closure StartCapture(const media::VideoCaptureSessionId id,
                             const media::VideoCaptureParams& params) {
    return manager_->StartCapture(
        id, params, base::Bind(&VideoCaptureImplManagerTest::OnStateUpdate,
                               base::Unretained(this)),
        base::Bind(&VideoCaptureImplManagerTest::OnFrameReady,
                   base::Unretained(this)));
  }

  base::MessageLoop message_loop_;
  scoped_ptr<ChildProcess> child_process_;
  media::VideoCaptureParams params_;
  base::RunLoop cleanup_run_loop_;
  scoped_ptr<MockVideoCaptureImplManager> manager_;

 private:
  DISALLOW_COPY_AND_ASSIGN(VideoCaptureImplManagerTest);
};

TEST_F(VideoCaptureImplManagerTest, MultipleImpls) {
  base::Closure release_cb1 = manager_->UseDevice(0);
  base::Closure release_cb2 = manager_->UseDevice(1);
  base::Closure stop_cb1, stop_cb2;
  {
    base::RunLoop run_loop;
    base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure());
    EXPECT_CALL(*this, OnStarted()).WillOnce(RunClosure(quit_closure));
    EXPECT_CALL(*this, OnStarted()).RetiresOnSaturation();
    stop_cb1 = StartCapture(0, params_);
    stop_cb2 = StartCapture(1, params_);
    FakeChannelSetup();
    run_loop.Run();
  }

  {
    base::RunLoop run_loop;
    base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure());
    EXPECT_CALL(*this, OnStopped()).WillOnce(RunClosure(quit_closure));
    EXPECT_CALL(*this, OnStopped()).RetiresOnSaturation();
    stop_cb1.Run();
    stop_cb2.Run();
    run_loop.Run();
  }

  release_cb1.Run();
  release_cb2.Run();
  cleanup_run_loop_.Run();
}

TEST_F(VideoCaptureImplManagerTest, RefusesMultipleClients) {
  // TODO(ajose): EXPECT_DEATH is unsafe in a threaded context - what to use
  // instead?
  base::Closure release_cb1 = manager_->UseDevice(0);
  EXPECT_DEATH(base::Closure release_cb2 = manager_->UseDevice(0), "");
}

TEST_F(VideoCaptureImplManagerTest, NoLeak) {
  manager_->UseDevice(0).Reset();
  manager_.reset();
  cleanup_run_loop_.Run();
}

}  // namespace content


text:
/* Meteor Falls v0.10 Scripts.
    By: [VP]Blade, TheUnknownOne, Ethan
    Credit to: Max, Lutra
*/

Config = {
    // Configuration for the script.
    servername: "CaloTown",

    maintainers: ['Binix'],

    // Repo to load plugins from.
    repourl: "https://github.com/Binix/Scripts",
    // Repo to load data (announcement/description + tiers) from.
    dataurl: "http://meteor-falls.github.io/Server-Shit/",
    emotesurl: 'http://meteor-falls.github.io/Emotes/emotes.json',

    // Plugin directory.
    plugindir: "plugins/",
    datadir: "data/",

    // Do not touch unless you are adding a new plugin.
    // Plugins to load on script load.
    plugins: ['bot', 'reg', 'ranks', 'utils', 'rtd', 'yeolde', 'channeldata', 'emotes', 'lists', 'init', 'feedmon', 'tours', 'commands', 'highlanders', 'events'],
    data: ['emoji'],

    // Whether or not to load plugins from repourl. If set to false, they will load locally.
    load_from_web: true,
    // If HTML should be stripped from channel messages outputted onto the server window.
    stripHtmlFromChannelMessages: true,
    // If emotes are enabled.
    emotesEnabled: true,
    // If custom channels are enabled
    channelsEnabled: true,
    // Character limit in messages.
    characterLimit: 600
};

(function() {
    var dir = Config.plugindir,
        datadir = Config.datadir;
    sys.makeDir(dir);
    sys.makeDir(datadir);

    require = function require(name, webcall, noCache) {
        if ((name in require.cache) && !webcall && !noCache) {
            return require.cache[name];
        }

        var __fileContent,
            __fname = dir + name + ".js",
            module, __resp;

        if (webcall) {
            __resp = sys.synchronousWebCall(Config.repourl + "plugins/" + name + ".js");
            if (!__resp || __resp.substr(0, 9) === "<!DOCTYPE") {
                throw new Error("Failed to load plugin " + name + " from " + Config.repourl + "plugins/" + name + ".js");
            }
            sys.writeToFile(__fname, __resp);
        }

        if (!sys.fileExists(__fname)) {
            throw {name: "NoFileError", toString: function () { return "Couldn't find file " + (__fname) + "."; }};
        }

        __fileContent = sys.getFileContent(__fname);

        module = {
            exports: {},
            reload: function () { return false; },
            name: name
        };

        if (name in require.cache) {
            if (require.meta[name].onUnload) {
                require.meta[name].onUnload();
            }
        }

        try {
            sys.eval("(function (module, exports) { " + __fileContent + " }(module, module.exports));", __fname);
        } catch (e) {
            sys.sendAll("Error loading module " + name + ": " + e + " on line " + e.lineNumber);
            print(e.backtracetext);
            throw e;
        }

        print("Loaded module " + name);

        require.cache[name] = module.exports;
        require.meta[name] = module;
        return module.exports;
    };

    require.reload = function require_reload(name) {
        require(name, false, false);
        return require.meta[name].reload();
    };

    if (!require.cache || (typeof FULLRELOAD === 'boolean' && FULLRELOAD === true)) {
        require.cache = {};
        require.meta  = {};
    }

    FULLRELOAD = false;

    require.callPlugins = function require_callPlugins(event) {
        var args = Array.prototype.slice.call(arguments, 1),
            plugins = this.meta,
            exports, plugin;

        for (plugin in plugins) {
            exports = plugins[plugin].exports;
            if (event in exports) {
                try {
                    exports[event].apply(exports, args);
                } catch (e) {
                    print("Plugin error (" + plugins[plugin].name + ") on line " + e.lineNumber + ": " + e);
                    print(e.backtracetext);
                }
            }
        }
    };

    var plugin, data, resp, i;

    for (i = 0; i < Config.plugins.length; i += 1) {
        plugin = Config.plugins[i];
        require(plugin, Config.load_from_web);
    }

    for (i = 0; i < Config.data.length; i += 1) {
        data = Config.data[i] + ".json";

        if (!sys.fileExists(datadir + data)) {
            resp = sys.synchronousWebCall(Config.repourl + "data/" + data);
            sys.writeToFile(datadir + data, resp);
        }
    }
}());

function poUser(id) {
    var ip = sys.ip(id);

    this.id = id;
    this.ip = ip;
    this.floodCount = 0;
    this.teamChanges = 0;
    this.caps = 0;
    this.muted = false;
    this.semuted = false;

    this.originalName = sys.name(id);
    this.loginTime = sys.time();

    // This is an array so we can track multiple emotes in their last message.
    this.lastEmote = [];
    this.lastMessage = {message: "", time: 0};
}

function poChannel(chanId) {
    this.id   = chanId;
    this.name = sys.channel(chanId);

    this.creator = '';
    this.topic   = '';
    this.setBy   = '';

    this.members = {};
    this.auth    = {};
    this.mutes   = {};
    this.bans    = {};

    this.bots     = true;
    this.isPublic = true;
}

try {
    ChannelManager = require('channeldata').manager;
} catch (ex) {
    ChannelManager = {};
    sys.sendAll("Couldn't load ChannelManager: " + ex);
}

SESSION.identifyScriptAs("Meteor Falls Script v0.10.1");
SESSION.registerUserFactory(poUser);
SESSION.registerChannelFactory(poChannel);
SESSION.refill();

var poScript;
poScript = ({
    serverStartUp: function serverStartUp() {
        startUpTime = sys.time();
        script.init();
    },
    serverShutDown: function serverShutDown() {
        Reg.saveData();
        require.callPlugins("serverShutDown");
    },
    init: function init() {
        require.reload('utils');

        require.reload('reg');
        require.reload('ranks');
        require.reload('bot');

        require.reload('yeolde');
        require.reload('rtd');

        require.reload('feedmon');
        require.reload('tours');

        require.reload('init');

        require.reload('emotes');
        require.reload('lists');

        sys.resetProfiling();
    },
    step: function step() {
        require.callPlugins("step");
    },
    warning: function warning(func, message, backtrace) {
        require.callPlugins("warning", func, message, backtrace);
    },
    beforeNewMessage: function beforeNewMessage(message) {
        require.callPlugins("beforeNewMessage", message);
    },
    afterNewMessage: function afterNewMessage(message) {
        require.callPlugins("afterNewMessage", message);
    },
    beforeServerMessage: function (message) {
        require.callPlugins("beforeServerMessage", message);
    },
    beforeChannelJoin: function beforeChannelJoin(src, channel) {
        require.callPlugins("beforeChannelJoin", src, channel);
    },
    beforeChannelDestroyed: function beforeChannelDestroyed(channel) {
        require.callPlugins("beforeChannelDestroyed", channel);
    },
    afterChannelCreated: function afterChannelCreated(chan, name, src) {
        require.callPlugins("afterChannelCreated", chan, name, src);
    },
    afterChannelJoin: function afterChannelJoin(src, chan) {
        require.callPlugins("afterChannelJoin", src, chan);
    },
    beforeLogIn: function beforeLogIn(src) {
        require.callPlugins("beforeLogIn", src);
    },
    afterLogIn: function afterLogIn(src, defaultChan) {
        require.callPlugins("afterLogIn", src, defaultChan);
    },
    beforeChangeTier: function(src, team, oldtier, newtier) {
        require.callPlugins("beforeChangeTier", src, team, oldtier, newtier);
    },
    beforeChangeTeam: function beforeChangeTeam(src) {
        require.callPlugins("beforeChangeTeam", src);
    },
    beforeChatMessage: function beforeChatMessage(src, message, chan) {
        require.callPlugins("beforeChatMessage", src, message, chan);
    },
    beforeLogOut: function beforeLogOut(src) {
        require.callPlugins("beforeLogOut", src);
    },
    afterChangeTeam: function afterChangeTeam(src) {
        require.callPlugins("afterChangeTeam", src);
    },
    beforePlayerKick: function beforePlayerKick(src, bpl) {
        require.callPlugins("beforePlayerKick", src, bpl);
    },
    beforePlayerBan: function beforePlayerBan(src, bpl, time) {
        require.callPlugins("beforePlayerBan", src, bpl, time);
    },
    beforeChallengeIssued: function beforeChallengeIssued(src, dest) {
        require.callPlugins("beforeChallengeIssued", src, dest);
    },
    /*afterPlayerAway: function afterPlayerAway(src, mode) {
    },*/
    beforeBattleMatchup: function beforeBattleMatchup(src, dest, clauses, rated, mode, team1, team2) {
        require.callPlugins("beforeBattleMatchup", src, dest, clauses, rated, mode, team1, team2);
    },
    afterBattleStarted: function afterBattleStarted(src, dest, info, id, t1, t2) {
        require.callPlugins("afterBattleStarted", src, dest, info, id, t1, t2);
    },
    afterBattleEnded: function afterBattleEnded(src, dest, desc) {
        require.callPlugins("afterBattleEnded", src, dest, desc);
    },
    afterChatMessage: function afterChatMessage(src, message, chan) {
        require.callPlugins("afterChatMessage", src, message, chan);
    },
    beforePlayerRegister: function (src) {
        Utils.watch.notify(Utils.nameIp(src) + " registered.");
    },
    battleConnectionLost: function() {
        Utils.watch.notify("Connection to the battle server has been lost.");
    }
});


text:
<?php
declare(strict_types=1);
namespace Viserio\Component\Encryption;

use Viserio\Component\Contract\Encryption\Exception\CannotCloneKeyException;
use Viserio\Component\Contract\Encryption\Exception\CannotSerializeKeyException;
use Viserio\Component\Contract\Encryption\Exception\InvalidKeyException;
use Viserio\Component\Contract\Encryption\HiddenString as HiddenStringContract;

final class Key
{
    /**
     * @var string
     */
    private $keyMaterial;

    /**
     * You probably should not be using this directly.
     *
     * @param \Viserio\Component\Contract\Encryption\HiddenString $keyMaterial - The actual key data
     *
     * @throws \Viserio\Component\Contract\Encryption\Exception\InvalidKeyException
     */
    public function __construct(HiddenStringContract $keyMaterial)
    {
        $key = safe_str_cpy($keyMaterial->getString());

        if (\mb_strlen($key, '8bit') !== SODIUM_CRYPTO_STREAM_KEYBYTES) {
            throw new InvalidKeyException('Encryption key must be \SODIUM_CRYPTO_STREAM_KEYBYTES bytes long.');
        }

        $this->keyMaterial = $key;
    }

    /**
     * Make sure you wipe the key from memory on destruction.
     */
    public function __destruct()
    {
        \sodium_memzero($this->keyMaterial);

        $this->keyMaterial = null;
    }

    /**
     * Don't let this ever succeed.
     *
     * @throws \Viserio\Component\Contract\Encryption\Exception\CannotCloneKeyException
     */
    public function __clone()
    {
        throw new CannotCloneKeyException();
    }

    /**
     * Don't allow this object to ever be serialized.
     *
     * @throws \Viserio\Component\Contract\Encryption\Exception\CannotSerializeKeyException
     *
     * @return void
     */
    public function __sleep(): void
    {
        throw new CannotSerializeKeyException();
    }

    /**
     * Don't allow this object to ever be unserialized.
     *
     * @throws \Viserio\Component\Contract\Encryption\Exception\CannotSerializeKeyException
     *
     * @return void
     */
    public function __wakeup(): void
    {
        throw new CannotSerializeKeyException();
    }

    /**
     * Get the actual key material.
     *
     * @return string
     */
    public function getRawKeyMaterial(): string
    {
        return safe_str_cpy($this->keyMaterial);
    }
}


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

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.micromobs.android.floatlabel.FloatLabelEditText
        android:id="@id/name_widget_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/padding_16"
        app:hint="@string/placeholder_title"
        app:textColorHintFocused="@color/hint_focused"
        app:textColorHintUnFocused="@color/hint_unfocused"
        app:textSize="@dimen/font_16"/>

    <com.micromobs.android.floatlabel.FloatLabelEditText
        android:id="@id/name_widget_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/name_widget_title"
        android:paddingTop="@dimen/padding_16"
        app:hint="@string/hint_name"
        app:textColorHintFocused="@color/hint_focused"
        app:textColorHintUnFocused="@color/hint_unfocused"
        app:textSize="@dimen/font_16"/>

</RelativeLayout>


text:
// Module for cryptography

#include <c_errno.h>
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "c_types.h"
#include "c_stdlib.h"
#include "flash_fs.h"
#include "../crypto/digests.h"
#include "../crypto/mech.h"

#include "user_interface.h"

#include "rom.h"

/**
  * hash = crypto.sha1(input)
  *
  *	Calculates raw SHA1 hash of input string.
  * Input is arbitrary string, output is raw 20-byte hash as string.
  */
static int crypto_sha1( lua_State* L )
{
  SHA1_CTX ctx;
  uint8_t digest[20];
  // Read the string from lua (with length)
  int len;
  const char* msg = luaL_checklstring(L, 1, &len);
  // Use the SHA* functions in the rom
  SHA1Init(&ctx);
  SHA1Update(&ctx, msg, len);
  SHA1Final(digest, &ctx);

  // Push the result as a lua string
  lua_pushlstring(L, digest, 20);
  return 1;
}

#ifdef LUA_USE_MODULES_ENCODER
static int call_encoder( lua_State* L, const char *function ) {
  if (lua_gettop(L) != 1) {
    luaL_error(L, "%s must have one argument", function);
  }
  lua_getfield(L, LUA_GLOBALSINDEX, "encoder");
  if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) { // also need table just in case encoder has been overloaded
    luaL_error(L, "Cannot find encoder.%s", function);
  }
  lua_getfield(L, -1, function);
  lua_insert(L, 1);    //move function below the argument
  lua_pop(L, 1);       //and dump the encoder rotable from stack.
  lua_call(L,1,1);     // call encoder.xxx(string)
  return 1;
}

static int crypto_base64_encode (lua_State* L) {
  return call_encoder(L, "toBase64");
}
static int crypto_hex_encode (lua_State* L) {
  return call_encoder(L, "toHex");
}
#else
static const char* bytes64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
  * encoded = crypto.toBase64(raw)
  *
  * Encodes raw binary string as base64 string.
  */
static int crypto_base64_encode( lua_State* L )
{
  int len;
  const char* msg = luaL_checklstring(L, 1, &len);
  int blen = (len + 2) / 3 * 4;
  char* out = (char*)c_malloc(blen);
  int j = 0, i;
  for (i = 0; i < len; i += 3) {
    int a = msg[i];
    int b = (i + 1 < len) ? msg[i + 1] : 0;
    int c = (i + 2 < len) ? msg[i + 2] : 0;
    out[j++] = bytes64[a >> 2];
    out[j++] = bytes64[((a & 3) << 4) | (b >> 4)];
    out[j++] = (i + 1 < len) ? bytes64[((b & 15) << 2) | (c >> 6)] : 61;
    out[j++] = (i + 2 < len) ? bytes64[(c & 63)] : 61;
  }
  lua_pushlstring(L, out, j);
  c_free(out);
  return 1;
}

/**
  * encoded = crypto.toHex(raw)
  *
  *	Encodes raw binary string as hex string.
  */
static int crypto_hex_encode( lua_State* L)
{
  int len;
  const char* msg = luaL_checklstring(L, 1, &len);
  char* out = (char*)c_malloc(len * 2);
  int i, j = 0;
  for (i = 0; i < len; i++) {
    out[j++] = crypto_hexbytes[msg[i] >> 4];
    out[j++] = crypto_hexbytes[msg[i] & 0xf];
  }
  lua_pushlstring(L, out, len*2);
  c_free(out);
  return 1;
}
#endif
/**
  * masked = crypto.mask(message, mask)
  *
  * Apply a mask (repeated if shorter than message) as XOR to each byte.
  */
static int crypto_mask( lua_State* L )
{
  int len, mask_len;
  const char* msg = luaL_checklstring(L, 1, &len);
  const char* mask = luaL_checklstring(L, 2, &mask_len);
  int i;
  char* copy = (char*)c_malloc(len);
  for (i = 0; i < len; i++) {
    copy[i] = msg[i] ^ mask[i % 4];
  }
  lua_pushlstring(L, copy, len);
  c_free(copy);
  return 1;
}

static inline int bad_mech (lua_State *L) { return luaL_error (L, "unknown hash mech"); }
static inline int bad_mem  (lua_State *L) { return luaL_error (L, "insufficient memory"); }
static inline int bad_file (lua_State *L) { return luaL_error (L, "file does not exist"); }

/* rawdigest = crypto.hash("MD5", str)
 * strdigest = crypto.toHex(rawdigest)
 */
static int crypto_lhash (lua_State *L)
{
  const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  if (!mi)
    return bad_mech (L);
  size_t len = 0;
  const char *data = luaL_checklstring (L, 2, &len);

  uint8_t digest[mi->digest_size];
  if (crypto_hash (mi, data, len, digest) != 0)
    return bad_mem (L);

  lua_pushlstring (L, digest, sizeof (digest));
  return 1;
}

typedef struct digest_user_datum_t  {
	const digest_mech_info_t *mech_info;
	void *ctx;
} digest_user_datum_t;

/* General Usage for extensible hash functions:
 * sha = crypto.new_hash("MD5")
 * sha.update("Data")
 * sha.update("Data2")
 * strdigest = crypto.toHex(sha.finalize())
 */

/* crypto.new_hash("MECHTYPE") */
static int crypto_new_hash (lua_State *L)
{
  const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  if (!mi)
    return bad_mech (L);

  void *ctx = os_malloc (mi->ctx_size);
  if (ctx==NULL)
    return bad_mem (L);

  mi->create (ctx);

  // create a userdataum with specific metatable
  digest_user_datum_t *dudat = (digest_user_datum_t *)lua_newuserdata(L, sizeof(digest_user_datum_t));
  luaL_getmetatable(L, "crypto.hash");
  lua_setmetatable(L, -2);

  // Set pointers to the mechanics and CTX
  dudat->mech_info = mi;
  dudat->ctx       = ctx;

  return 1; // Pass userdata object back
}

/* Called as object, params:
   1 - userdata "this"
   2 - new string to add to the hash state  */
static int crypto_hash_update (lua_State *L)
{
  NODE_DBG("enter crypto_hash_update.\n");
  digest_user_datum_t *dudat;
  size_t sl;

  dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  luaL_argcheck(L, dudat, 1, "crypto.hash expected");

  const digest_mech_info_t *mi = dudat->mech_info;

  size_t len = 0;
  const char *data = luaL_checklstring (L, 2, &len);

  mi->update (dudat->ctx, data, len);

  return 0;  // No return value
}

/* Called as object, no params. Returns digest of default size. */
static int crypto_hash_finalize (lua_State *L)
{
  NODE_DBG("enter crypto_hash_update.\n");
  digest_user_datum_t *dudat;
  size_t sl;

  dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  luaL_argcheck(L, dudat, 1, "crypto.hash expected");

  const digest_mech_info_t *mi = dudat->mech_info;

  uint8_t digest[mi->digest_size]; // Allocate as local
  mi->finalize (digest, dudat->ctx);

  lua_pushlstring (L, digest, sizeof (digest));
  return 1;
}

/* Frees memory for the user datum and CTX hash state */
static int crypto_hash_gcdelete (lua_State *L)
{
  NODE_DBG("enter crypto_hash_delete.\n");
  digest_user_datum_t *dudat;

  dudat = (digest_user_datum_t *)luaL_checkudata(L, 1, "crypto.hash");
  luaL_argcheck(L, dudat, 1, "crypto.hash expected");

  os_free(dudat->ctx);
  os_free(dudat);

  return 0;
}

/* rawdigest = crypto.hash("MD5", filename)
 * strdigest = crypto.toHex(rawdigest)
 */
static int crypto_flhash (lua_State *L)
{
  const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  if (!mi)
    return bad_mech (L);
  const char *filename = luaL_checkstring (L, 2);

  // Open the file
  int file_fd = fs_open (filename, FS_RDONLY);
  if(file_fd < FS_OPEN_OK) {
    return bad_file(L);
  }

  // Compute hash
  uint8_t digest[mi->digest_size];
  int returncode = crypto_fhash (mi, &fs_read, file_fd, digest);

  // Finish up
  fs_close(file_fd);

  if (returncode == ENOMEM)
    return bad_mem (L);
  else if (returncode == EINVAL)
    return bad_mech(L);
  else
    lua_pushlstring (L, digest, sizeof (digest));

  return 1;
}

/* rawsignature = crypto.hmac("SHA1", str, key)
 * strsignature = crypto.toHex(rawsignature)
 */
static int crypto_lhmac (lua_State *L)
{
  const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
  if (!mi)
    return bad_mech (L);
  size_t len = 0;
  const char *data = luaL_checklstring (L, 2, &len);
  size_t klen = 0;
  const char *key = luaL_checklstring (L, 3, &klen);

  uint8_t digest[mi->digest_size];
  if (crypto_hmac (mi, data, len, key, klen, digest) != 0)
    return bad_mem (L);

  lua_pushlstring (L, digest, sizeof (digest));
  return 1;
}

static const crypto_mech_t *get_mech (lua_State *L, int idx)
{
  const char *name = luaL_checkstring (L, idx);

  const crypto_mech_t *mech = crypto_encryption_mech (name);
  if (mech)
    return mech;

  luaL_error (L, "unknown cipher: %s", name);
  __builtin_unreachable ();
}

static int crypto_encdec (lua_State *L, bool enc)
{
  const crypto_mech_t *mech = get_mech (L, 1);
  size_t klen;
  const char *key = luaL_checklstring (L, 2, &klen);
  size_t dlen;
  const char *data = luaL_checklstring (L, 3, &dlen);

  size_t ivlen;
  const char *iv = luaL_optlstring (L, 4, "", &ivlen);

  size_t bs = mech->block_size;
  size_t outlen = ((dlen + bs -1) / bs) * bs;
  char *buf = (char *)os_zalloc (outlen);
  if (!buf)
    return luaL_error (L, "crypto init failed");

  crypto_op_t op =
  {
    key, klen,
    iv, ivlen,
    data, dlen,
    buf, outlen,
    enc ? OP_ENCRYPT : OP_DECRYPT
  };
  if (!mech->run (&op))
  {
    os_free (buf);
    return luaL_error (L, "crypto op failed");
  }
  else
  {
    lua_pushlstring (L, buf, outlen);
    // note: if lua_pushlstring runs out of memory, we leak buf :(
    os_free (buf);
    return 1;
  }
}

static int lcrypto_encrypt (lua_State *L)
{
  return crypto_encdec (L, true);
}

static int lcrypto_decrypt (lua_State *L)
{
  return crypto_encdec (L, false);
}

// Hash function map
static const LUA_REG_TYPE crypto_hash_map[] = {
  { LSTRKEY( "update" ),  LFUNCVAL( crypto_hash_update ) },
  { LSTRKEY( "finalize" ),   LFUNCVAL( crypto_hash_finalize ) },
  { LSTRKEY( "__gc" ),    LFUNCVAL( crypto_hash_gcdelete ) },
  { LSTRKEY( "__index" ), LROVAL( crypto_hash_map ) },
  { LNILKEY, LNILVAL }
};

// Module function map
static const LUA_REG_TYPE crypto_map[] = {
  { LSTRKEY( "sha1" ),     LFUNCVAL( crypto_sha1 ) },
  { LSTRKEY( "toBase64" ), LFUNCVAL( crypto_base64_encode ) },
  { LSTRKEY( "toHex" ),    LFUNCVAL( crypto_hex_encode ) },
  { LSTRKEY( "mask" ),     LFUNCVAL( crypto_mask ) },
  { LSTRKEY( "hash"   ),   LFUNCVAL( crypto_lhash ) },
  { LSTRKEY( "fhash"  ),   LFUNCVAL( crypto_flhash ) },
  { LSTRKEY( "new_hash"   ),   LFUNCVAL( crypto_new_hash ) },
  { LSTRKEY( "hmac"   ),   LFUNCVAL( crypto_lhmac ) },
  { LSTRKEY( "encrypt" ),  LFUNCVAL( lcrypto_encrypt ) },
  { LSTRKEY( "decrypt" ),  LFUNCVAL( lcrypto_decrypt ) },
  { LNILKEY, LNILVAL }
};

int luaopen_crypto ( lua_State *L )
{
  luaL_rometatable(L, "crypto.hash", (void *)crypto_hash_map);  // create metatable for crypto.hash
  return 0;
}

NODEMCU_MODULE(CRYPTO, "crypto", crypto_map, luaopen_crypto);


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

#include "ray/object_manager/spilled_object_reader.h"

#include <fstream>
#include <regex>

#include "ray/util/logging.h"

namespace ray {
namespace {
const size_t UINT64_size = sizeof(uint64_t);
}

/* static */ absl::optional<SpilledObjectReader>
SpilledObjectReader::CreateSpilledObjectReader(const std::string &object_url) {
  std::string file_path;
  uint64_t object_offset = 0;
  uint64_t object_size = 0;

  if (!SpilledObjectReader::ParseObjectURL(
          object_url, file_path, object_offset, object_size)) {
    RAY_LOG(WARNING) << "Failed to parse spilled object url: " << object_url;
    return absl::optional<SpilledObjectReader>();
  }

  uint64_t data_offset = 0;
  uint64_t data_size = 0;
  uint64_t metadata_offset = 0;
  uint64_t metadata_size = 0;
  rpc::Address owner_address;

  std::ifstream is(file_path, std::ios::binary);
  if (!is || !SpilledObjectReader::ParseObjectHeader(is,
                                                     object_offset,
                                                     data_offset,
                                                     data_size,
                                                     metadata_offset,
                                                     metadata_size,
                                                     owner_address)) {
    RAY_LOG(WARNING) << "Failed to parse object header for spilled object " << object_url;
    return absl::optional<SpilledObjectReader>();
  }

  return absl::optional<SpilledObjectReader>(
      SpilledObjectReader(std::move(file_path),
                          object_size,
                          data_offset,
                          data_size,
                          metadata_offset,
                          metadata_size,
                          std::move(owner_address)));
}

uint64_t SpilledObjectReader::GetDataSize() const { return data_size_; }

uint64_t SpilledObjectReader::GetMetadataSize() const { return metadata_size_; }

const rpc::Address &SpilledObjectReader::GetOwnerAddress() const {
  return owner_address_;
}

SpilledObjectReader::SpilledObjectReader(std::string file_path,
                                         uint64_t object_size,
                                         uint64_t data_offset,
                                         uint64_t data_size,
                                         uint64_t metadata_offset,
                                         uint64_t metadata_size,
                                         rpc::Address owner_address)
    : file_path_(std::move(file_path)),
      object_size_(object_size),
      data_offset_(data_offset),
      data_size_(data_size),
      metadata_offset_(metadata_offset),
      metadata_size_(metadata_size),
      owner_address_(std::move(owner_address)) {}

/* static */ bool SpilledObjectReader::ParseObjectURL(const std::string &object_url,
                                                      std::string &file_path,
                                                      uint64_t &object_offset,
                                                      uint64_t &object_size) {
  static const std::regex object_url_pattern("^(.*)\\?offset=(\\d+)&size=(\\d+)$");
  std::smatch match_groups;
  if (!std::regex_match(object_url, match_groups, object_url_pattern) ||
      match_groups.size() != 4) {
    return false;
  }
  file_path = match_groups[1].str();
  try {
    auto offset = std::stoll(match_groups[2].str());
    auto size = std::stoll(match_groups[3].str());
    if (offset < 0 || size < 0) {
      RAY_LOG(ERROR) << "Offset and size can't be negative. offset: " << offset
                     << ", size: " << size;
      return false;
    }
    object_offset = offset;
    object_size = size;
  } catch (...) {
    RAY_LOG(ERROR) << "Failed to parse offset: " << match_groups[2].str()
                   << " and size: " << match_groups[3].str();
    return false;
  }
  return true;
}

/* static */
bool SpilledObjectReader::ParseObjectHeader(std::istream &is,
                                            uint64_t object_offset,
                                            uint64_t &data_offset,
                                            uint64_t &data_size,
                                            uint64_t &metadata_offset,
                                            uint64_t &metadata_size,
                                            rpc::Address &owner_address) {
  if (!is.seekg(object_offset)) {
    return false;
  }

  uint64_t address_size = 0;
  if (!ReadUINT64(is, address_size) || !ReadUINT64(is, metadata_size) ||
      !ReadUINT64(is, data_size)) {
    return false;
  }

  std::string address_str(address_size, '\0');
  if (!is.read(&address_str[0], address_size) ||
      !owner_address.ParseFromString(address_str)) {
    return false;
  }

  metadata_offset = object_offset + UINT64_size * 3 + address_size;
  data_offset = metadata_offset + metadata_size;
  return true;
}

/* static */
bool SpilledObjectReader::ReadUINT64(std::istream &is, uint64_t &output) {
  std::string buff(UINT64_size, '\0');
  if (!is.read(&buff[0], UINT64_size)) {
    return false;
  }
  output = SpilledObjectReader::ToUINT64(buff);
  return true;
}

/* static */
uint64_t SpilledObjectReader::ToUINT64(const std::string &s) {
  RAY_CHECK(s.size() == UINT64_size);
  uint64_t result = 0;
  for (size_t i = 0; i < s.size(); i++) {
    result = result << 8;
    result += static_cast<unsigned char>(s.at(s.size() - i - 1));
  }
  return result;
}

bool SpilledObjectReader::ReadFromDataSection(uint64_t offset,
                                              uint64_t size,
                                              char *output) const {
  std::ifstream is(file_path_, std::ios::binary);
  return is.seekg(data_offset_ + offset) && is.read(output, size);
}

bool SpilledObjectReader::ReadFromMetadataSection(uint64_t offset,
                                                  uint64_t size,
                                                  char *output) const {
  std::ifstream is(file_path_, std::ios::binary);
  return is.seekg(metadata_offset_ + offset) && is.read(output, size);
}
}  // namespace ray


text:
import {
  findExistsPageIndex
} from 'uni-helpers/index'

export default {
  name (fromArgs) {
    if (fromArgs.exists === 'back' && fromArgs.delta) {
      return 'navigateBack'
    }
    return 'redirectTo'
  },
  args (fromArgs) {
    if (fromArgs.exists === 'back' && fromArgs.url) {
      const existsPageIndex = findExistsPageIndex(fromArgs.url)
      if (existsPageIndex !== -1) {
        const delta = getCurrentPages().length - 1 - existsPageIndex
        if (delta > 0) {
          fromArgs.delta = delta
        }
      }
    }
  }
}


text:
require 'spec_helper'

describe GitGrabber::Api do
  before(:each) do
    @api = GitGrabber::Api.new 'my-funky-token'

    stub_request(
      :get, "https://api.github.com/user/repos"
      ).with(
        :headers => {
          'Accept'=>'application/vnd.github.beta+json',
          'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
          'Authorization'=>'token my-funky-token',
          'User-Agent'=>'Octokit Ruby Gem 2.7.2'
        }
      ).to_return(
        :status => 200,
        :body => "fake repo return body thing",
        :headers => {}
      )
  end

  it "fetches all user repositories" do
    repos = @api.fetch_all
    expect(repos).to eq('fake repo return body thing')
  end
end


text:
//// TODO:
//// [O] Contracts
//// [O] Documentation

namespace Splunk.Client
{
    using System;

    /// <summary>
    /// Provides an object representation of the settings of a Splunk server.
    /// </summary>
    /// <seealso cref="T:Splunk.Client.Resource"/>
    /// <seealso cref="T:Splunk.Client.IServerSettings"/>
    public class ServerSettings : Resource, IServerSettings
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ServerSettings"/> class.
        /// </summary>
        /// <param name="entry">
        /// An object representing a Splunk atom entry response.
        /// </param>
        /// <param name="generatorVersion">
        /// The version of the generator producing the <see cref="AtomFeed"/>
        /// feed containing <paramref name="entry"/>.
        /// </param>
        protected internal ServerSettings(AtomEntry entry, Version generatorVersion)
            : base(entry, generatorVersion)
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref="ServerSettings"/> class.
        /// </summary>
        /// <param name="feed">
        /// An object representing a Splunk atom feed response.
        /// </param>
        protected internal ServerSettings(AtomFeed feed)
        {
            this.Initialize(feed);
        }

        /// <summary>
        /// Infrastructure. Initializes a new instance of the
        /// <see cref= "ServerSettings"/> class.
        /// </summary>
        /// <remarks>
        /// This API supports the Splunk client infrastructure and is not intended to
        /// be used directly from your code. Use one of these methods to obtain a
        /// <see cref="ServerSettings"/> instance:
        /// <list type="table">
        /// <listheader>
        ///   <term>Method</term>
        ///   <description>Description</description>
        /// </listheader>
        /// <item>
        ///   <term><see cref="Server.GetSettingsAsync"/></term>
        ///   <description>
        ///   Asynchronously retrieves <see cref="ServerSettings"/> from the Splunk
        ///   server represented by the current instance.
        ///   </description>
        /// </item>
        /// <item>
        ///   <term><see cref="Server.UpdateSettingsAsync"/></term>
        ///   <description>
        ///   Asynchronously updates <see cref="ServerSettings"/> on the Splunk
        ///   server represented by the current instance.
        ///   </description>
        /// </item>
        /// </list>
        /// </remarks>
        public ServerSettings()
        { }

        #endregion

        #region Properties

        /// <inheritdoc/>
        public virtual Eai Eai
        {
            get { return this.Content.GetValue("Eai", Eai.Converter.Instance); }
        }

        /// <inheritdoc/>
        public virtual string SplunkDB
        {
            get { return this.Content.GetValue("SPLUNKDB", StringConverter.Instance); }
        }

        /// <inheritdoc/>
        public virtual string SplunkHome
        {
            get { return this.Content.GetValue("SPLUNKHOME", StringConverter.Instance); }
        }

        /// <inheritdoc/>
        public virtual bool EnableSplunkWebSsl
        {
            get { return this.Content.GetValue("EnableSplunkWebSSL", BooleanConverter.Instance); }
        }

        /// <inheritdoc/>
        public virtual string Host
        {
            get { return this.Content.GetValue("Host", StringConverter.Instance); }
        }

        /// <inheritdoc/>
        public virtual int HttpPort
        {
            get { return this.Content.GetValue("Httpport", Int32Converter.Instance); }
        }

        /// <inheritdoc/>
        public virtual int ManagementHostPort
        {
            get { return this.Content.GetValue("MgmtHostPort", Int32Converter.Instance); }
        }

        /// <inheritdoc/>
        public virtual int MinFreeSpace
        {
            get { return this.Content.GetValue("MinFreeSpace", Int32Converter.Instance); }
        }

        /// <inheritdoc/>
        public virtual string Pass4SymmetricKey
        {
            get { return this.Content.GetValue("Pass4SymmKey", StringConverter.Instance); }
        }

        /// <inheritdoc/>
        public virtual string ServerName
        {
            get { return this.Content.GetValue("ServerName", StringConverter.Instance); }
        }

        /// <inheritdoc/>
        public virtual string SessionTimeout
        {
            get { return this.Content.GetValue("SessionTimeout", StringConverter.Instance); }
        }

        /// <inheritdoc/>
        public virtual bool StartWebServer
        {
            get { return this.Content.GetValue("Startwebserver", BooleanConverter.Instance); }
        }

        /// <inheritdoc/>
        public virtual string TrustedIP
        {
            get { return this.Content.GetValue("TrustedIP", StringConverter.Instance); }
        }

        #endregion
    }
}


text: SELECT * FROM func1_mod_setint_vol(func2_nosql_vol(5)) order by 1;


text:
package betterwithaddons.crafting.manager;

import betterwithaddons.block.EriottoMod.BlockNettedScreen.SifterType;

public class CraftingManagerWaterNet extends CraftingManagerNet {
    private static final CraftingManagerWaterNet instance = new CraftingManagerWaterNet();

    public CraftingManagerWaterNet()
    {
        super(SifterType.WATER);
    }

    public static final CraftingManagerWaterNet getInstance()
    {
        return instance;
    }
}


text:
<?php

define('DS', DIRECTORY_SEPARATOR);

$arquivo = (isset($_GET['arquivo'])) ? $_GET['arquivo'] : '';

switch ($arquivo) {
	case 'ifelse':
		include 'estruturas'.DS.'ifelse.php';
		break;

	case 'switch':
		include 'estruturas'.DS.'switch.php';
		break;

	case 'for':
		include 'estruturas'.DS.'for.php';
		break;

	case 'foreach':
		include 'estruturas'.DS.'foreach.php';
		break;

	case 'while':
		include 'estruturas'.DS.'while.php';
		break;

	default:
		echo "Informe uma pagina!";
		break;
}

?>

Pagina do IfElse

Pagina do Switch

Pagina do For

Pagina do Foreach

Pagina do While


text:
package invdapi

import (
	"errors"
	"strconv"

	"github.com/Invoiced/invoiced-go/invdendpoint"
)

type Subscription struct {
	*Connection
	*invdendpoint.Subscription
}

type Subscriptions []*Subscription

func (c *Connection) NewSubscription() *Subscription {
	subscription := new(invdendpoint.Subscription)
	return &Subscription{c, subscription}
}

func (c *Connection) NewPreviewRequest() *invdendpoint.SubscriptionPreviewRequest {
	return &invdendpoint.SubscriptionPreviewRequest{}
}

func (c *Subscription) Count() (int64, error) {
	endpoint := invdendpoint.SubscriptionEndpoint

	count, apiErr := c.count(endpoint)

	if apiErr != nil {
		return -1, apiErr
	}

	return count, nil
}

func (c *Subscription) Create(subscription *Subscription) (*Subscription, error) {
	endpoint := invdendpoint.SubscriptionEndpoint

	if subscription == nil {
		return nil, errors.New("Subscription is nil")
	}

	subDataToCreate, err := SafeSubscriptionForCreation(subscription.Subscription)
	if err != nil {
		return nil, err
	}

	subResp := c.NewSubscription()

	apiErr := c.create(endpoint, subDataToCreate, subResp)

	if apiErr != nil {
		return nil, apiErr
	}

	subResp.Connection = c.Connection

	return subResp, nil
}

func (c *Subscription) Cancel() error {
	endpoint := invdendpoint.SubscriptionEndpoint + "/" + strconv.FormatInt(c.Id, 10)

	apiErr := c.delete(endpoint)

	if apiErr != nil {
		return apiErr
	}

	return nil
}

func (c *Subscription) Save() error {
	endpoint := invdendpoint.SubscriptionEndpoint + "/" + strconv.FormatInt(c.Id, 10)
	subResp := c.NewSubscription()

	subDataToUpdate, err := SafeSubscriptionsForUpdate(c.Subscription)
	if err != nil {
		return err
	}

	apiErr := c.update(endpoint, subDataToUpdate, subResp)

	if apiErr != nil {
		return apiErr
	}

	c.Subscription = subResp.Subscription

	return nil
}

func (c *Subscription) Retrieve(id int64) (*Subscription, error) {
	endpoint := invdendpoint.SubscriptionEndpoint + "/" + strconv.FormatInt(id, 10)

	custEndpoint := new(invdendpoint.Subscription)

	subscription := &Subscription{c.Connection, custEndpoint}

	_, apiErr := c.retrieveDataFromAPI(endpoint, subscription)

	if apiErr != nil {
		return nil, apiErr
	}

	return subscription, nil
}
func (c *Subscription) ListAllCanceled(filter *invdendpoint.Filter, sort *invdendpoint.Sort,canceled bool) (Subscriptions, error) {
	endpoint := invdendpoint.SubscriptionEndpoint
	if canceled {
		endpoint = addQueryParameter(endpoint,"canceled","1")
	}
	endpoint = addFilterAndSort(endpoint, filter, sort)

	subscriptions := make(invdendpoint.Subscriptions, 0)
	subscriptionsToReturn := make(Subscriptions,0)

NEXT:
	tmpSubscriptions := make(invdendpoint.Subscriptions, 0)

	endpoint, apiErr := c.retrieveDataFromAPI(endpoint, &tmpSubscriptions)

	if apiErr != nil {
		return nil, apiErr
	}

	subscriptions = append(subscriptions, tmpSubscriptions...)

	if endpoint != "" {
		goto NEXT
	}

	for _, subscription := range subscriptions {
		sub := c.Connection.NewSubscription()
		subData := subscription
		sub.Subscription = &subData
		subscriptionsToReturn = append(subscriptionsToReturn,sub)
	}

	return subscriptionsToReturn, nil
}

func (c *Subscription) ListAll(filter *invdendpoint.Filter, sort *invdendpoint.Sort) (Subscriptions, error) {
	endpoint := invdendpoint.SubscriptionEndpoint
	endpoint = addFilterAndSort(endpoint, filter, sort)

	subscriptions := make(invdendpoint.Subscriptions, 0)
	subscriptionsToReturn := make(Subscriptions,0)

NEXT:
	tmpSubscriptions := make(invdendpoint.Subscriptions, 0)

	endpoint, apiErr := c.retrieveDataFromAPI(endpoint, &tmpSubscriptions)

	if apiErr != nil {
		return nil, apiErr
	}

	subscriptions = append(subscriptions, tmpSubscriptions...)

	if endpoint != "" {
		goto NEXT
	}

	for _, subscription := range subscriptions {
		sub := c.Connection.NewSubscription()
		subData := subscription
		sub.Subscription = &subData
		subscriptionsToReturn = append(subscriptionsToReturn,sub)
	}

	return subscriptionsToReturn, nil
}

func (c *Subscription) List(filter *invdendpoint.Filter, sort *invdendpoint.Sort) (Subscriptions, string, error) {
	endpoint := invdendpoint.SubscriptionEndpoint
	endpoint = addFilterAndSort(endpoint, filter, sort)

	subscriptions := make(invdendpoint.Subscriptions, 0)
	subscriptionsToReturn := make(Subscriptions,0)

	nextEndpoint, apiErr := c.retrieveDataFromAPI(endpoint, &subscriptions)

	if apiErr != nil {
		return nil, "", apiErr
	}

	for _, subscription := range subscriptions {
		sub := c.Connection.NewSubscription()
		subData := subscription
		sub.Subscription = &subData
		subscriptionsToReturn = append(subscriptionsToReturn,sub)
	}

	return subscriptionsToReturn, nextEndpoint, nil
}

func (c *Subscription) Preview(subPreviewRequest *invdendpoint.SubscriptionPreviewRequest) (*invdendpoint.SubscriptionPreview, error) {
	endpoint := invdendpoint.SubscriptionEndpoint + "/" + strconv.FormatInt(c.Id, 10) + "/preview"

	if subPreviewRequest == nil {
		return nil, errors.New("Subscription is nil")
	}

	subPreviewResp := new(invdendpoint.SubscriptionPreview)

	apiErr := c.create(endpoint, subPreviewRequest, subPreviewResp)

	if apiErr != nil {
		return nil, apiErr
	}

	return subPreviewResp, nil
}

// SafeSubscriptionForCreation prunes subscription data for just fields that can be used for creation of a subscription
func SafeSubscriptionForCreation(sub *invdendpoint.Subscription) (*invdendpoint.Subscription, error) {
	if sub == nil {
		return nil, errors.New("Subscription is nil")
	}

	subData := new(invdendpoint.Subscription)
	subData.Customer = sub.Customer
	subData.Plan = sub.Plan
	subData.Amount = sub.Amount
	subData.StartDate = sub.StartDate
	subData.BillIn = sub.BillIn
	subData.BillInAdvanceDays = sub.BillInAdvanceDays
	subData.Quantity = sub.Quantity
	subData.Addons = sub.Addons
	subData.Discounts = sub.Discounts
	subData.Cycles = sub.Cycles
	subData.SnapToNthDay = sub.SnapToNthDay
	subData.Paused = sub.Paused
	subData.ContractRenewalCycles = sub.ContractRenewalCycles
	subData.ContractRenewalMode = sub.ContractRenewalMode
	subData.Taxes = sub.Taxes
	subData.CancelAtPeriodEnd = sub.CancelAtPeriodEnd
	subData.Metadata = sub.Metadata

	return subData, nil
}

// SafeSubscriptionsForUpdate prunes subscription data for just fields that can be used for updating of a subscription
func SafeSubscriptionsForUpdate(sub *invdendpoint.Subscription) (*invdendpoint.Subscription, error) {
	if sub == nil {
		return nil, errors.New("Subscription is nil")
	}

	subData := new(invdendpoint.Subscription)

	subData.Plan = sub.Plan
	subData.Amount = sub.Amount
	subData.StartDate = sub.StartDate
	subData.BillIn = sub.BillIn
	subData.BillInAdvanceDays = sub.BillInAdvanceDays
	subData.Quantity = sub.Quantity
	subData.Addons = sub.Addons
	subData.Paused = sub.Paused
	subData.Discounts = sub.Discounts
	subData.ContractRenewalCycles = sub.ContractRenewalCycles
	subData.ContractRenewalMode = sub.ContractRenewalMode
	subData.CancelAtPeriodEnd = sub.CancelAtPeriodEnd
	subData.Prorate = sub.Prorate
	subData.ProrationDate = sub.ProrationDate

	return subData, nil
}


text:
using namespace ofp;

const MPMeterConfigRequest *MPMeterConfigRequest::cast(
    const MultipartRequest *req) {
  return req->body_cast<MPMeterConfigRequest>();
}

bool MPMeterConfigRequest::validateInput(Validation *context) const {
  size_t length = context->lengthRemaining();
  return (length == sizeof(MPMeterConfigRequest));
}

void MPMeterConfigRequestBuilder::write(Writable *channel) {
  channel->write(&msg_, sizeof(msg_));
  channel->flush();
}