text:
namespace Microsoft.Azure.Management.WebSites.Models
{
    using Azure;
    using Management;
    using WebSites;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for StatusOptions.
    /// </summary>
    [JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    public enum StatusOptions
    {
        [EnumMember(Value = "Ready")]
        Ready,
        [EnumMember(Value = "Pending")]
        Pending
    }
}


text:
<?php
/**
 *
 */
class BackWPup_Destination_SugarSync extends BackWPup_Destinations {

	public static $backwpup_job_object = NULL;

	/**
	 * @return array
	 */
	public function option_defaults() {
		return array( 'sugarrefreshtoken' => '', 'sugarroot' => '', 'sugardir' => trailingslashit( sanitize_file_name( get_bloginfo( 'name' ) ) ), 'sugarmaxbackups' => 15 );
	}

	/**
	 * @param $jobid
	 */
	public function edit_tab( $jobid ) {
		?>

<?php _e( 'Sugarsync Login', 'backwpup' ); ?>

		<?php if ( ! BackWPup_Option::get( $jobid, 'sugarrefreshtoken' ) ) { ?>

				<?php _e( 'Authentication', 'backwpup' ); ?>

                    <?php _e( 'Email address:', 'backwpup' ); ?>

                    <input id="sugaremail" name="sugaremail" type="text"
						   value="<?php if ( isset( $_POST[ 'sugaremail' ] ) ) echo $_POST[ 'sugaremail' ];?>" class="large-text" autocomplete="off" />

                    <?php _e( 'Password:', 'backwpup' ); ?>

					<input id="sugarpass" name="sugarpass" type="password"
						   value="<?php if ( isset( $_POST[ 'sugarpass' ] ) ) echo $_POST[ 'sugarpass' ];?>" class="large-text" autocomplete="off" />

					<input type="submit" id="idauthbutton" name="authbutton" class="button-primary" accesskey="d"
						   value="<?php _e( 'Authenticate with Sugarsync!', 'backwpup' ); ?>"/>
					     <input type="submit" name="authbutton" class="button"
														 value="<?php _e( 'Create Sugarsync account', 'backwpup' ); ?>"/>

		<?php } else { ?>

                <?php _e( 'Authentication', 'backwpup' ); ?>

					<?php _e( 'Authenticated!', 'backwpup' ); ?>
					<input type="submit" id="idauthbutton" name="authbutton" class="button-primary" accesskey="d"
						   value="<?php _e( 'Delete Sugarsync authentication!', 'backwpup' ); ?>" />

		<?php } ?>

<?php _e( 'SugarSync Root', 'backwpup' ); ?>

                <?php _e( 'Sync folder selection', 'backwpup' ); ?>

				<?php
				try {
					$sugarsync   = new BackWPup_Destination_SugarSync_API( BackWPup_Option::get( $jobid, 'sugarrefreshtoken' ) );
					$user        = $sugarsync->user();
					$syncfolders = $sugarsync->get( $user->syncfolders );
					if ( ! is_object( $syncfolders ) )
						echo '' . __( 'No Syncfolders found!', 'backwpup' ) . '';
				}
				catch ( Exception $e ) {
					echo '' . $e->getMessage() . '';
				}
				if ( isset( $syncfolders ) && is_object( $syncfolders ) ) {
					echo '<select name="sugarroot" id="sugarroot">';
					foreach ( $syncfolders->collection as $roots ) {
						echo "<option " . selected( strtolower( BackWPup_Option::get( $jobid, 'sugarroot' ) ), strtolower( $roots->ref ), FALSE ) . " value=\"" . $roots->ref . "\">" . $roots->displayName . "</option>";
					}
					echo '</select>';
				}
				?>

<?php _e( 'Backup settings', 'backwpup' ); ?>

            <?php _e( 'Folder in root', 'backwpup' ); ?>

                <input id="idsugardir" name="sugardir" type="text" value="<?php echo  BackWPup_Option::get( $jobid, 'sugardir' ); ?>" class="regular-text" />

            <?php _e( 'File Deletion', 'backwpup' ); ?>

				<?php
				if ( BackWPup_Option::get( $jobid, 'backuptype' ) == 'archive' ) {
					?>
                    <input id="idsugarmaxbackups" name="sugarmaxbackups" type="text" size="3" value="<?php echo BackWPup_Option::get( $jobid, 'sugarmaxbackups' );?>" class="small-text help-tip" title="<?php esc_attr_e( 'Oldest files will be deleted first. 0 = no deletion', 'backwpup' ); ?>" />
					<?php  _e( 'Number of files to keep in folder.', 'backwpup' ); ?>
					<?php } else { ?>
                    <input class="checkbox" value="1"
                           type="checkbox" <?php checked( BackWPup_Option::get( $jobid, 'sugarsyncnodelete' ), TRUE ); ?>
                           name="sugarsyncnodelete" id="idsugarsyncnodelete" /> <?php _e( 'Do not delete files while syncing to destination!', 'backwpup' ); ?>
					<?php } ?>

	<?php
	}

	/**
	 * @param $jobid
	 */
	public function edit_form_post_save( $jobid ) {

		if ( ! empty( $_POST[ 'sugaremail' ] ) && ! empty( $_POST[ 'sugarpass' ] ) && $_POST[ 'authbutton' ] == __( 'Authenticate with Sugarsync!', 'backwpup' ) ) {
			try {
				$sugarsync     = new BackWPup_Destination_SugarSync_API();
				$refresh_token = $sugarsync->get_Refresh_Token( $_POST[ 'sugaremail' ], $_POST[ 'sugarpass' ] );
				if ( ! empty( $refresh_token ) )
					BackWPup_Option::update( $jobid, 'sugarrefreshtoken', $refresh_token );
			}
			catch ( Exception $e ) {
				BackWPup_Admin::message( 'SUGARSYNC: ' . $e->getMessage(), TRUE );
			}
		}

		if ( isset( $_POST[ 'authbutton' ] ) && $_POST[ 'authbutton' ] == __( 'Delete Sugarsync authentication!', 'backwpup' ) ) {
			BackWPup_Option::delete( $jobid, 'sugarrefreshtoken' );
		}

		if ( isset( $_POST[ 'authbutton' ] ) && $_POST[ 'authbutton' ] == __( 'Create Sugarsync account', 'backwpup' ) ) {
			try {
				$sugarsync = new BackWPup_Destination_SugarSync_API();
				$sugarsync->create_account( $_POST[ 'sugaremail' ], $_POST[ 'sugarpass' ] );
			}
			catch ( Exception $e ) {
				BackWPup_Admin::message( 'SUGARSYNC: ' . $e->getMessage(), TRUE );
			}
		}

		$_POST[ 'sugardir' ] = trailingslashit( str_replace( '//', '/', str_replace( '\\', '/', trim( stripslashes( $_POST[ 'sugardir' ] ) ) ) ) );
		if ( substr( $_POST[ 'sugardir' ], 0, 1 ) == '/' )
			$_POST[ 'sugardir' ] = substr( $_POST[ 'sugardir' ], 1 );
		if ( $_POST[ 'sugardir' ] == '/' )
			$_POST[ 'sugardir' ] = '';
		BackWPup_Option::update( $jobid, 'sugardir', $_POST[ 'sugardir' ] );

		BackWPup_Option::update( $jobid, 'sugarroot', isset( $_POST[ 'sugarroot' ] ) ? $_POST[ 'sugarroot' ] : '' );
		BackWPup_Option::update( $jobid, 'sugarmaxbackups', isset( $_POST[ 'sugarmaxbackups' ] ) ? (int)$_POST[ 'sugarmaxbackups' ] : 0 );
	}

	/**
	 * @param $jobdest
	 * @param $backupfile
	 */
	public function file_delete( $jobdest, $backupfile ) {

		$files = get_site_transient( 'backwpup_' . strtolower( $jobdest ) );
		list( $jobid, $dest ) = explode( '_', $jobdest );

		if ( BackWPup_Option::get( $jobid, 'sugarrefreshtoken' ) ) {
			try {
				$sugarsync = new BackWPup_Destination_SugarSync_API( BackWPup_Option::get( $jobid, 'sugarrefreshtoken' ) );
				$sugarsync->delete( urldecode( $backupfile ) );
				//update file list
				foreach ( $files as $key => $file ) {
					if ( is_array( $file ) && $file[ 'file' ] == $backupfile )
						unset( $files[ $key ] );
				}
				unset( $sugarsync );
			}
			catch ( Exception $e ) {
				BackWPup_Admin::message( 'SUGARSYNC: ' . $e->getMessage(), TRUE );
			}
		}

		set_site_transient( 'backwpup_' . strtolower( $jobdest ), $files, 60 * 60 * 24 * 7 );
	}

	/**
	 * @param $jobid
	 * @param $get_file
	 */
	public function file_download( $jobid, $get_file ) {

		try {
			$sugarsync = new BackWPup_Destination_SugarSync_API( BackWPup_Option::get( $jobid, 'sugarrefreshtoken' ) );
			$response  = $sugarsync->get( urldecode( $get_file ) );
			header( "Pragma: public" );
			header( "Expires: 0" );
			header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
			header( "Content-Type: application/octet-stream" );
			header( "Content-Disposition: attachment; filename=" . (string)$response->displayName . ";" );
			header( "Content-Transfer-Encoding: binary" );
			header( "Content-Length: " . (int)$response->size );
			@set_time_limit( 300 );
			echo $sugarsync->download( urldecode( $get_file ) );
			die();
		}
		catch ( Exception $e ) {
			die( $e->getMessage() );
		}
	}

	/**
	 * @param $jobdest
	 * @return mixed
	 */
	public function file_get_list( $jobdest ) {

		return get_site_transient( 'backwpup_' . strtolower( $jobdest ) );
	}

	/**
	 * @param $job_object BackWPup_Job
	 * @return bool
	 */
	public function job_run_archive( BackWPup_Job $job_object ) {

		$job_object->substeps_todo = 2 + $job_object->backup_filesize;
		$job_object->log( sprintf( __( '%d. Try to send backup to SugarSync …', 'backwpup' ), $job_object->steps_data[ $job_object->step_working ][ 'STEP_TRY' ] ), E_USER_NOTICE );

		try {
			$sugarsync = new BackWPup_Destination_SugarSync_API( $job_object->job[ 'sugarrefreshtoken' ] );
			//Check Quota
			$user = $sugarsync->user();
			if ( ! empty( $user->nickname ) )
				$job_object->log( sprintf( __( 'Authenticated to SugarSync with nickname %s', 'backwpup' ), $user->nickname ), E_USER_NOTICE );
			$sugarsyncfreespase = (float)$user->quota->limit - (float)$user->quota->usage; //float fixes bug for display of no free space
			if ( $job_object->backup_filesize > $sugarsyncfreespase ) {
				$job_object->log( sprintf( _x( 'Not enough disk space available on SugarSync. Available: %s.','Available space on SugarSync', 'backwpup' ), size_format( $sugarsyncfreespase, 2 ) ), E_USER_ERROR );
				$job_object->substeps_todo = 1 + $job_object->backup_filesize;

				return TRUE;
			}
			else {
				$job_object->log( sprintf( __( '%s available at SugarSync', 'backwpup' ), size_format( $sugarsyncfreespase, 2 ) ), E_USER_NOTICE );
			}
			//Create and change folder
			$sugarsync->mkdir( $job_object->job[ 'sugardir' ], $job_object->job[ 'sugarroot' ] );
			$dirid = $sugarsync->chdir( $job_object->job[ 'sugardir' ], $job_object->job[ 'sugarroot' ] );
			//Upload to SugarSync
			$job_object->substeps_done = 0;
			$job_object->log( __( 'Starting upload to SugarSync …', 'backwpup' ), E_USER_NOTICE );
			self::$backwpup_job_object = &$job_object;
			$reponse = $sugarsync->upload( $job_object->backup_folder . $job_object->backup_file );
			if ( is_object( $reponse ) ) {
				if ( ! empty( $job_object->job[ 'jobid' ] ) )
					BackWPup_Option::update( $job_object->job[ 'jobid' ], 'lastbackupdownloadurl', network_admin_url( 'admin.php' ) . '?page=backwpupbackups&action=downloadsugarsync&file=' . (string)$reponse . '&jobid=' . $job_object->job[ 'jobid' ] );
				$job_object->substeps_done ++;
				$job_object->log( sprintf( __( 'Backup transferred to %s', 'backwpup' ), 'https://' . $user->nickname . '.sugarsync.com/' . $sugarsync->showdir( $dirid ) . $job_object->backup_file ), E_USER_NOTICE );
			}
			else {
				$job_object->log( __( 'Cannot transfer backup to SugarSync!', 'backwpup' ), E_USER_ERROR );

				return FALSE;
			}

			$backupfilelist = array();
			$files          = array();
			$filecounter    = 0;
			$dir            = $sugarsync->showdir( $dirid );
			$getfiles       = $sugarsync->getcontents( 'file' );
			if ( is_object( $getfiles ) ) {
				foreach ( $getfiles->file as $getfile ) {
					$getfile->displayName = utf8_decode( (string)$getfile->displayName );
					if ( $job_object->is_backup_archive( $getfile->displayName ) )
						$backupfilelist[ strtotime( (string)$getfile->lastModified ) ] = (string)$getfile->ref;
					$files[ $filecounter ][ 'folder' ]      = 'https://' . (string)$user->nickname . '.sugarsync.com/' . $dir;
					$files[ $filecounter ][ 'file' ]        = (string)$getfile->ref;
					$files[ $filecounter ][ 'filename' ]    = (string)$getfile->displayName;
					$files[ $filecounter ][ 'downloadurl' ] = network_admin_url( 'admin.php' ) . '?page=backwpupbackups&action=downloadsugarsync&file=' . (string)$getfile->ref . '&jobid=' . $job_object->job[ 'jobid' ];
					$files[ $filecounter ][ 'filesize' ]    = (int)$getfile->size;
					$files[ $filecounter ][ 'time' ]        = strtotime( (string)$getfile->lastModified ) + ( get_option( 'gmt_offset' ) * 3600 );
					$filecounter ++;
				}
			}
			if ( ! empty( $job_object->job[ 'sugarmaxbackups' ] ) && $job_object->job[ 'sugarmaxbackups' ] > 0 ) { //Delete old backups
				if ( count( $backupfilelist ) >  $job_object->job[ 'sugarmaxbackups' ] ) {
					ksort( $backupfilelist );
					$numdeltefiles = 0;
					while ( $file = array_shift( $backupfilelist ) ) {
						if ( count( $backupfilelist ) <  $job_object->job[ 'sugarmaxbackups' ] )
							break;
						$sugarsync->delete( $file ); //delete files on Cloud
						foreach ( $files as $key => $filedata ) {
							if ( $filedata[ 'file' ] == $file )
								unset( $files[ $key ] );
						}
						$numdeltefiles ++;
					}
					if ( $numdeltefiles > 0 )
						$job_object->log( sprintf( _n( 'One file deleted on SugarSync folder', '%d files deleted on SugarSync folder', $numdeltefiles, 'backwpup' ), $numdeltefiles ), E_USER_NOTICE );
				}
			}
			set_site_transient( 'BackWPup_' .  $job_object->job[ 'jobid' ] . '_SUGARSYNC', $files, 60 * 60 * 24 * 7 );
		}
		catch ( Exception $e ) {
			$job_object->log( E_USER_ERROR, sprintf( __( 'SugarSync API: %s', 'backwpup' ), $e->getMessage() ), $e->getFile(), $e->getLine() );

			return FALSE;
		}
		$job_object->substeps_done ++;

		return TRUE;
	}

	/**
	 * @param $job_settings array
	 * @return bool
	 */
	public function can_run( array $job_settings ) {

		if ( empty( $job_settings[ 'sugarrefreshtoken' ] ) )
			return FALSE;

		if ( empty( $job_settings[ 'sugarroot' ] ) )
			return FALSE;

		return TRUE;
	}
}

/**
 *
 */
class BackWPup_Destination_SugarSync_API {

	/**
	 * url for the sugarsync-api
	 */
	const API_URL  = 'https://api.sugarsync.com';

	/**
	 *
	 * @var    string
	 */
	protected $folder = '';

	/**
	 * @var mixed|string
	 */
	protected $encoding = 'UTF-8';

	/**
	 * @var null|string
	 */
	protected $refresh_token = '';

	/**
	 * The Auth-token
	 *
	 * @var string
	 */
	protected $access_token = '';

	// class methods
	/**
	 * Default constructor/Auth
	 */
	public function __construct( $refresh_token = NULL ) {

		//auth xml
		$this->encoding = mb_internal_encoding();

		//get access token
		if ( isset( $refresh_token ) and ! empty( $refresh_token ) ) {
			$this->refresh_token = $refresh_token;
			$this->get_Access_Token();
		}
	}

	/**
	 * Make the call
	 *
	 * @return    string
	 *
	 * @param    string $url                        The url to call.
	 * @param string    $data
	 * @param string    $method
	 * @throws BackWPup_Destination_SugarSync_API_Exception
	 * @internal param $string [optiona] $data            File on put, xml on post.
	 * @internal param $string [optional] $method        The method to use. Possible values are GET, POST, PUT, DELETE.
	 */
	private function doCall( $url, $data = '', $method = 'GET' ) {

		// allowed methods
		$allowedMethods = array( 'GET', 'POST', 'PUT', 'DELETE' );

		// redefine
		$url    = (string)$url;
		$method = (string)$method;

		// validate method
		if ( ! in_array( $method, $allowedMethods ) )
			throw new BackWPup_Destination_SugarSync_API_Exception( 'Unknown method (' . $method . '). Allowed methods are: ' . implode( ', ', $allowedMethods ) );

		// check auth token
		if ( empty( $this->access_token ) )
			throw new BackWPup_Destination_SugarSync_API_Exception( 'Auth Token not set correctly!' );
		else
			$headers[ ] = 'Authorization: ' . $this->access_token;
		$headers[ ] = 'Expect:';

		// init
		$curl = curl_init();
		//set options
		curl_setopt( $curl, CURLOPT_URL, $url );
		curl_setopt( $curl, CURLOPT_USERAGENT, BackWPup::get_plugin_data( 'User-Agent' )  );
		if ( ini_get( 'open_basedir' ) == '' ) curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE );
		curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE );
		if ( BackWPup::get_plugin_data( 'cacert' ) ) {
			curl_setopt( $curl, CURLOPT_SSLVERSION, 1 );
			curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, TRUE );
			curl_setopt( $curl, CURLOPT_CAINFO, BackWPup::get_plugin_data( 'cacert' ) );
			curl_setopt( $curl, CURLOPT_CAPATH, dirname( BackWPup::get_plugin_data( 'cacert' ) ) );
		} else {
			curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
		}

		if ( $method == 'POST' ) {
			$headers[ ] = 'Content-Type: application/xml; charset=UTF-8';
			curl_setopt( $curl, CURLOPT_POSTFIELDS, $data );
			curl_setopt( $curl, CURLOPT_POST, TRUE );
			$headers[ ] = 'Content-Length: ' . strlen( $data );
		}
		elseif ( $method == 'PUT' ) {
			if ( is_readable( $data ) ) {
				$headers[ ] = 'Content-Length: ' . filesize( $data );
				$datafilefd = fopen( $data, 'rb' );
				curl_setopt( $curl, CURLOPT_PUT, TRUE );
				curl_setopt( $curl, CURLOPT_INFILE, $datafilefd );
				curl_setopt( $curl, CURLOPT_INFILESIZE, filesize( $data ) );
				curl_setopt( $curl, CURLOPT_READFUNCTION,  array( BackWPup_Destination_SugarSync::$backwpup_job_object, 'curl_read_callback' ) );
			}
			else {
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Is not a readable file:' . $data );
			}
		}
		elseif ( $method == 'DELETE' ) {
			curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'DELETE' );
		}
		else {
			curl_setopt( $curl, CURLOPT_POST, FALSE );
		}

		// set headers
		curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
		curl_setopt( $curl, CURLINFO_HEADER_OUT, TRUE );
		// execute
		$response    = curl_exec( $curl );
		$curlgetinfo = curl_getinfo( $curl );

		// fetch curl errors
		if ( curl_errno( $curl ) != 0 )
			throw new BackWPup_Destination_SugarSync_API_Exception( 'cUrl Error: ' . curl_error( $curl ) );
		curl_close( $curl );
		if ( ! empty( $datafilefd ) && is_resource( $datafilefd ) )
			fclose( $datafilefd );

		if ( $curlgetinfo[ 'http_code' ] >= 200 && $curlgetinfo[ 'http_code' ] < 300 ) {
			if ( FALSE !== stripos( $curlgetinfo[ 'content_type' ], 'xml' ) && ! empty( $response ) )
				return simplexml_load_string( $response );
			else
				return $response;
		}
		else {
			if ( $curlgetinfo[ 'http_code' ] == 401 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' Authorization required.' );
			elseif ( $curlgetinfo[ 'http_code' ] == 403 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' (Forbidden)  Authentication failed.' );
			elseif ( $curlgetinfo[ 'http_code' ] == 404 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' Not found' );
			else
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] );
		}
	}

	/**
	 * @return string
	 * @throws BackWPup_Destination_SugarSync_API_Exception
	 */
	private function get_Access_Token() {

		$auth = '<?xml version="1.0" encoding="UTF-8" ?>';
		$auth .= '<tokenAuthRequest>';
		$auth .= '<accessKeyId>' . get_site_option( 'backwpup_cfg_sugarsynckey', base64_decode( "TlRBek1EY3lOakV6TkRrMk1URXhNemM0TWpJ" ) ) . '</accessKeyId>';
		$auth .= '<privateAccessKey>' . BackWPup_Encryption::decrypt( get_site_option( 'backwpup_cfg_sugarsyncsecret', base64_decode( "TkRFd01UazRNVEpqTW1Ga05EaG1NR0k1TVRFNFpqa3lPR1V6WlRVMk1tTQ==" ) ) ) . '</privateAccessKey>';
		$auth .= '<refreshToken>' . trim( $this->refresh_token ) . '</refreshToken>';
		$auth .= '</tokenAuthRequest>';
		// init
		$curl = curl_init();
		//set options
		curl_setopt( $curl, CURLOPT_URL, self::API_URL . '/authorization' );
		curl_setopt( $curl, CURLOPT_USERAGENT, BackWPup::get_plugin_data( 'User-Agent' )  );
		if ( ini_get( 'open_basedir' ) == ''  ) curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE );
		curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE );
		if ( BackWPup::get_plugin_data( 'cacert' ) ) {
			curl_setopt( $curl, CURLOPT_SSLVERSION, 1 );
			curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, TRUE );
			curl_setopt( $curl, CURLOPT_CAINFO, BackWPup::get_plugin_data( 'cacert' ) );
			curl_setopt( $curl, CURLOPT_CAPATH, dirname( BackWPup::get_plugin_data( 'cacert' ) ) );
		} else {
			curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
		}
		curl_setopt( $curl, CURLOPT_HEADER, TRUE );
		curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/xml; charset=UTF-8', 'Content-Length: ' . strlen( $auth ) ) );
		curl_setopt( $curl, CURLOPT_POSTFIELDS, $auth );
		curl_setopt( $curl, CURLOPT_POST, TRUE );
		// execute
		$response    = curl_exec( $curl );
		$curlgetinfo = curl_getinfo( $curl );
		// fetch curl errors
		if ( curl_errno( $curl ) != 0 )
			throw new BackWPup_Destination_SugarSync_API_Exception( 'cUrl Error: ' . curl_error( $curl ) );

		curl_close( $curl );

		if ( $curlgetinfo[ 'http_code' ] >= 200 && $curlgetinfo[ 'http_code' ] < 300 ) {
			if ( preg_match( '/Location:(.*?)\r/i', $response, $matches ) )
				$this->access_token = trim( $matches[ 1 ] );

			return $this->access_token;
		}
		else {
			if ( $curlgetinfo[ 'http_code' ] == 401 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' Authorization required.' );
			elseif ( $curlgetinfo[ 'http_code' ] == 403 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' (Forbidden)  Authentication failed.' );
			elseif ( $curlgetinfo[ 'http_code' ] == 404 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' Not found' );
			else
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] );
		}
	}

	/**
	 * @param $email
	 * @param $password
	 * @return null|string
	 * @throws BackWPup_Destination_SugarSync_API_Exception
	 */
	public function get_Refresh_Token( $email, $password ) {

		$auth = '<?xml version="1.0" encoding="UTF-8" ?>';
		$auth .= '<appAuthorization>';
		$auth .= '<username>' . mb_convert_encoding( $email, 'UTF-8', $this->encoding ) . '</username>';
		$auth .= '<password>' . mb_convert_encoding( $password, 'UTF-8', $this->encoding ) . '</password>';
		$auth .= '<application>' . get_site_option( 'backwpup_cfg_sugarsyncappid', "/sc/5030726/449_18207099" ) . '</application>';
		$auth .= '<accessKeyId>' . get_site_option( 'backwpup_cfg_sugarsynckey',base64_decode( "TlRBek1EY3lOakV6TkRrMk1URXhNemM0TWpJ" ) ) . '</accessKeyId>';
		$auth .= '<privateAccessKey>' . BackWPup_Encryption::decrypt( get_site_option( 'backwpup_cfg_sugarsyncsecret', base64_decode( "TkRFd01UazRNVEpqTW1Ga05EaG1NR0k1TVRFNFpqa3lPR1V6WlRVMk1tTQ==" ) ) ) . '</privateAccessKey>';
		$auth .= '</appAuthorization>';
		// init
		$curl = curl_init();
		//set options
		curl_setopt( $curl, CURLOPT_URL, self::API_URL . '/app-authorization' );
		curl_setopt( $curl, CURLOPT_USERAGENT, BackWPup::get_plugin_data( 'User-Agent' )  );
		if ( ini_get( 'open_basedir' ) == '' ) curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE );
		curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE );
		if ( BackWPup::get_plugin_data( 'cacert' ) ) {
			curl_setopt( $curl, CURLOPT_SSLVERSION, 1 );
			curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, TRUE );
			curl_setopt( $curl, CURLOPT_CAINFO, BackWPup::get_plugin_data( 'cacert' ) );
			curl_setopt( $curl, CURLOPT_CAPATH, dirname( BackWPup::get_plugin_data( 'cacert' ) ) );
		} else {
			curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
		}
		curl_setopt( $curl, CURLOPT_HEADER, TRUE );
		curl_setopt( $curl, CURLOPT_POSTFIELDS, $auth );
		curl_setopt( $curl, CURLOPT_POST, TRUE );
		curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/xml; charset=UTF-8', 'Content-Length: ' . strlen( $auth ) ) );
		// execute
		$response    = curl_exec( $curl );
		$curlgetinfo = curl_getinfo( $curl );
		// fetch curl errors
		if ( curl_errno( $curl ) != 0 )
			throw new BackWPup_Destination_SugarSync_API_Exception( 'cUrl Error: ' . curl_error( $curl ) );

		curl_close( $curl );

		if ( $curlgetinfo[ 'http_code' ] >= 200 && $curlgetinfo[ 'http_code' ] < 300 ) {
			if ( preg_match( '/Location:(.*?)\r/i', $response, $matches ) )
				$this->refresh_token = trim( $matches[ 1 ] );

			return $this->refresh_token;
		}
		else {
			if ( $curlgetinfo[ 'http_code' ] == 401 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' Authorization required.' );
			elseif ( $curlgetinfo[ 'http_code' ] == 403 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' (Forbidden)  Authentication failed.' );
			elseif ( $curlgetinfo[ 'http_code' ] == 404 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' Not found' );
			else
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] );
		}
	}

	/**
	 * @param $email
	 * @param $password
	 * @throws BackWPup_Destination_SugarSync_API_Exception
	 */
	public function create_account( $email, $password ) {

		$auth = '<?xml version="1.0" encoding="UTF-8" ?>';
		$auth .= '<user>';
		$auth .= '<email>' . mb_convert_encoding( $email, 'UTF-8', $this->encoding ) . '</email>';
		$auth .= '<password>' . mb_convert_encoding( $password, 'UTF-8', $this->encoding ) . '</password>';
		$auth .= '<accessKeyId>' . get_site_option( 'backwpup_cfg_sugarsynckey', base64_decode( "TlRBek1EY3lOakV6TkRrMk1URXhNemM0TWpJ" ) ) . '</accessKeyId>';
		$auth .= '<privateAccessKey>' . BackWPup_Encryption::decrypt( get_site_option( 'backwpup_cfg_sugarsyncsecret', base64_decode( "TkRFd01UazRNVEpqTW1Ga05EaG1NR0k1TVRFNFpqa3lPR1V6WlRVMk1tTQ==" ) ) ) . '</privateAccessKey>';
		$auth .= '</user>';
		// init
		$curl = curl_init();
		//set options
		curl_setopt( $curl, CURLOPT_URL, 'https://provisioning-api.sugarsync.com/users' );
		curl_setopt( $curl, CURLOPT_USERAGENT, BackWPup::get_plugin_data( 'User-Agent' )  );
		if ( ini_get( 'open_basedir' ) == '' ) curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE );
		curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE );
		if ( BackWPup::get_plugin_data( 'cacert' ) ) {
			curl_setopt( $curl, CURLOPT_SSLVERSION, 1 );
			curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, TRUE );
			curl_setopt( $curl, CURLOPT_CAINFO, BackWPup::get_plugin_data( 'cacert' ) );
			curl_setopt( $curl, CURLOPT_CAPATH, dirname( BackWPup::get_plugin_data( 'cacert' ) ) );
		} else {
			curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
		}
		curl_setopt( $curl, CURLOPT_HEADER, TRUE );
		curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/xml; charset=UTF-8', 'Content-Length: ' . strlen( $auth ) ) );
		curl_setopt( $curl, CURLOPT_POSTFIELDS, $auth );
		curl_setopt( $curl, CURLOPT_POST, TRUE );
		// execute
		$response    = curl_exec( $curl );
		$curlgetinfo = curl_getinfo( $curl );
		// fetch curl errors
		if ( curl_errno( $curl ) != 0 )
			throw new BackWPup_Destination_SugarSync_API_Exception( 'cUrl Error: ' . curl_error( $curl ) );

		curl_close( $curl );

		if ( $curlgetinfo[ 'http_code' ] == 201 ) {
			throw new BackWPup_Destination_SugarSync_API_Exception( 'Account created.' );
		}
		else {
			if ( $curlgetinfo[ 'http_code' ] == 400 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' ' . substr( $response, $curlgetinfo[ 'header_size' ] ) );
			elseif ( $curlgetinfo[ 'http_code' ] == 401 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' Developer credentials cannot be verified. Either a developer with the specified accessKeyId does not exist or the privateKeyID does not match an assigned accessKeyId.' );
			elseif ( $curlgetinfo[ 'http_code' ] == 403 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' ' . substr( $response, $curlgetinfo[ 'header_size' ] ) );
			elseif ( $curlgetinfo[ 'http_code' ] == 503 )
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] . ' ' . substr( $response, $curlgetinfo[ 'header_size' ] ) );
			else
				throw new BackWPup_Destination_SugarSync_API_Exception( 'Http Error: ' . $curlgetinfo[ 'http_code' ] );
		}
	}

	/**
	 * @param        $folder
	 * @param string $root
	 * @return string
	 * @throws BackWPup_Destination_SugarSync_API_Exception
	 */
	public function chdir( $folder, $root = '' ) {

		$folder = rtrim( $folder, '/' );
		if ( substr( $folder, 0, 1 ) == '/' || empty( $this->folder ) ) {
			if ( ! empty( $root ) )
				$this->folder = $root;
			else
				throw new BackWPup_Destination_SugarSync_API_Exception( 'chdir: root folder must set!' );
		}
		$folders = explode( '/', $folder );
		foreach ( $folders as $dir ) {
			if ( $dir == '..' ) {
				$contents = $this->doCall( $this->folder );
				if ( ! empty( $contents->parent ) )
					$this->folder = $contents->parent;
			}
			elseif ( ! empty( $dir ) && $dir != '.' ) {
				$isdir    = FALSE;
				$contents = $this->getcontents( 'folder' );
				foreach ( $contents->collection as $collection ) {
					if ( strtolower( $collection->displayName ) == strtolower( $dir ) ) {
						$isdir        = TRUE;
						$this->folder = $collection->ref;
						break;
					}
				}
				if ( ! $isdir )
					throw new BackWPup_Destination_SugarSync_API_Exception( 'chdir: Folder ' . $folder . ' not exitst' );
			}
		}

		return $this->folder;
	}

	/**
	 * @param $folderid
	 * @return string
	 */
	public function showdir( $folderid ) {

		$showfolder = '';
		while ( $folderid ) {
			$contents   = $this->doCall( $folderid );
			$showfolder = $contents->displayName . '/' . $showfolder;
			if ( isset( $contents->parent ) )
				$folderid = $contents->parent;
			else
				break;
		}

		return $showfolder;
	}

	/**
	 * @param        $folder
	 * @param string $root
	 * @return bool
	 * @throws BackWPup_Destination_SugarSync_API_Exception
	 */
	public function mkdir( $folder, $root = '' ) {

		$savefolder = $this->folder;
		$folder     = rtrim( $folder, '/' );
		if ( substr( $folder, 0, 1 ) == '/' || empty( $this->folder ) ) {
			if ( ! empty( $root ) )
				$this->folder = $root;
			else
				throw new BackWPup_Destination_SugarSync_API_Exception( 'mkdir: root folder must set!' );
		}
		$folders = explode( '/', $folder );
		foreach ( $folders as $dir ) {
			if ( $dir == '..' ) {
				$contents = $this->doCall( $this->folder );
				if ( ! empty( $contents->parent ) )
					$this->folder = $contents->parent;
			}
			elseif ( ! empty( $dir ) && $dir != '.' ) {
				$isdir    = FALSE;
				$contents = $this->getcontents( 'folder' );
				foreach ( $contents->collection as $collection ) {
					if ( strtolower( $collection->displayName ) == strtolower( $dir ) ) {
						$isdir        = TRUE;
						$this->folder = $collection->ref;
						break;
					}
				}
				if ( ! $isdir ) {
					$this->doCall( $this->folder, '<?xml version="1.0" encoding="UTF-8"?><folder><displayName>' . mb_convert_encoding( $dir, 'UTF-8', $this->encoding ) . '</displayName></folder>', 'POST' );
					$contents = $this->getcontents( 'folder' );
					foreach ( $contents->collection as $collection ) {
						if ( strtolower( $collection->displayName ) == strtolower( $dir ) ) {
							$isdir        = TRUE;
							$this->folder = $collection->ref;
							break;
						}
					}
				}
			}
		}
		$this->folder = $savefolder;

		return TRUE;
	}

	/**
	 * @return string
	 */
	public function user() {
		return $this->doCall( self::API_URL . '/user' );
	}

	/**
	 * @param $url
	 * @return string
	 */
	public function get( $url ) {
		return $this->doCall( $url, '', 'GET' );
	}

	/**
	 * @param $url
	 * @return string
	 */
	public function download( $url ) {
		return $this->doCall( $url . '/data' );
	}

	/**
	 * @param $url
	 * @return string
	 */
	public function delete( $url ) {
		return $this->doCall( $url, '', 'DELETE' );
	}

	/**
	 * @param string $type
	 * @param int    $start
	 * @param int    $max
	 * @return string
	 */
	public function getcontents( $type = '', $start = 0, $max = 500 ) {

		$parameters = '';

		if ( strtolower( $type ) == 'folder' || strtolower( $type ) == 'file' )
			$parameters .= 'type=' . strtolower( $type );
		if ( ! empty( $start ) && is_integer( $start ) ) {
			if ( ! empty( $parameters ) )
				$parameters .= '&';
			$parameters .= 'start=' . $start;

		}
		if ( ! empty( $max ) && is_integer( $max ) ) {
			if ( ! empty( $parameters ) )
				$parameters .= '&';
			$parameters .= 'max=' . $max;
		}

		$request = $this->doCall( $this->folder . '/contents?' . $parameters );

		return $request;
	}

	/**
	 * @param        $file
	 * @param string $name
	 * @return mixed
	 */
	public function upload( $file, $name = '' ) {

		if ( empty( $name ) ) {
			$name = basename( $file );
		}

		$content_type = BackWPup_Job::get_mime_type( $file );

		$xmlrequest = '<?xml version="1.0" encoding="UTF-8"?>';
		$xmlrequest .= '<file>';
		$xmlrequest .= '<displayName>' . mb_convert_encoding( $name, 'UTF-8', $this->encoding ) . '</displayName>';
		$xmlrequest .= '<mediaType>' . $content_type . '</mediaType>';
		$xmlrequest .= '</file>';

		$this->doCall( $this->folder, $xmlrequest, 'POST' );
		$getfiles = $this->getcontents( 'file' );
		foreach ( $getfiles->file as $getfile ) {
			if ( $getfile->displayName == $name ) {
				$this->doCall( $getfile->ref . '/data', $file, 'PUT' );

				return $getfile->ref;
			}
		}
	}
}

/**
 * SugarSync Exception class
 *
 * @author    Daniel Hüsken <daniel@huesken-net.de>
 */
class BackWPup_Destination_SugarSync_API_Exception extends Exception {

}

redpajama_set_name: RedPajamaGithub


text:
package org.ensime.sexp.formats

import org.ensime.sexp._

class SexpFormatsSpec extends FormatSpec with SexpFormats {

  def assertFormat(sexp: Sexp): Unit = assertFormat(sexp, sexp)

  describe("SexpFormats") {
    it("should support SexpAtoms") {
      assertFormat(SexpNil)
      assertFormat(SexpPosInf)
      assertFormat(SexpNegInf)
      assertFormat(SexpNaN)
      assertFormat(SexpNumber(1))
      assertFormat(SexpString("hello"))
      assertFormat(SexpSymbol("hello"))
    }

    it("should support SexpList") {
      assertFormat(SexpList(foo, bar))
    }

    it("should support SexpCons") {
      assertFormat(SexpCons(foo, bar))
    }
  }
}


text:
using System;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using T4MVC;
namespace Mn.NewsCms.Web.Controllers
{
    public partial class PhotoController
    {
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected PhotoController(Dummy d) { }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(ActionResult result)
        {
            var callInfo = result.GetT4MVCResult();
            return RedirectToRoute(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(Task<ActionResult> taskResult)
        {
            return RedirectToAction(taskResult.Result);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(ActionResult result)
        {
            var callInfo = result.GetT4MVCResult();
            return RedirectToRoutePermanent(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(Task<ActionResult> taskResult)
        {
            return RedirectToActionPermanent(taskResult.Result);
        }

        [NonAction]
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public virtual System.Web.Mvc.FileContentResult CatPhoto()
        {
            return new T4MVC_System_Web_Mvc_FileContentResult(Area, Name, ActionNames.CatPhoto);
        }
        [NonAction]
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public virtual System.Web.Mvc.FileContentResult GetPhoto()
        {
            return new T4MVC_System_Web_Mvc_FileContentResult(Area, Name, ActionNames.GetPhoto);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public PhotoController Actions { get { return MVC.Photo; } }
        [GeneratedCode("T4MVC", "2.0")]
        public readonly string Area = "";
        [GeneratedCode("T4MVC", "2.0")]
        public readonly string Name = "Photo";
        [GeneratedCode("T4MVC", "2.0")]
        public const string NameConst = "Photo";

        static readonly ActionNamesClass s_actions = new ActionNamesClass();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ActionNamesClass ActionNames { get { return s_actions; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionNamesClass
        {
            public readonly string Index = "Index";
            public readonly string Today = "Today";
            public readonly string GetPhotos = "GetPhotos";
            public readonly string CatPhoto = "CatPhoto";
            public readonly string GetPhoto = "GetPhoto";
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionNameConstants
        {
            public const string Index = "Index";
            public const string Today = "Today";
            public const string GetPhotos = "GetPhotos";
            public const string CatPhoto = "CatPhoto";
            public const string GetPhoto = "GetPhoto";
        }

        static readonly ActionParamsClass_GetPhotos s_params_GetPhotos = new ActionParamsClass_GetPhotos();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ActionParamsClass_GetPhotos GetPhotosParams { get { return s_params_GetPhotos; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionParamsClass_GetPhotos
        {
            public readonly string offset = "offset";
        }
        static readonly ActionParamsClass_CatPhoto s_params_CatPhoto = new ActionParamsClass_CatPhoto();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ActionParamsClass_CatPhoto CatPhotoParams { get { return s_params_CatPhoto; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionParamsClass_CatPhoto
        {
            public readonly string Id = "Id";
        }
        static readonly ActionParamsClass_GetPhoto s_params_GetPhoto = new ActionParamsClass_GetPhoto();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ActionParamsClass_GetPhoto GetPhotoParams { get { return s_params_GetPhoto; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionParamsClass_GetPhoto
        {
            public readonly string ImagByte = "ImagByte";
        }
        static readonly ViewsClass s_views = new ViewsClass();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ViewsClass Views { get { return s_views; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ViewsClass
        {
            static readonly _ViewNamesClass s_ViewNames = new _ViewNamesClass();
            public _ViewNamesClass ViewNames { get { return s_ViewNames; } }
            public class _ViewNamesClass
            {
                public readonly string NewsPaper = "NewsPaper";
                public readonly string Today = "Today";
            }
            public readonly string NewsPaper = "~/Views/Photo/NewsPaper.cshtml";
            public readonly string Today = "~/Views/Photo/Today.cshtml";
        }
    }

    [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
    public partial class T4MVC_PhotoController : Mn.NewsCms.Web.Controllers.PhotoController
    {
        public T4MVC_PhotoController() : base(Dummy.Instance) { }

        [NonAction]
        partial void IndexOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult Index()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Index);
            IndexOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void TodayOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult Today()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Today);
            TodayOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void GetPhotosOverride(T4MVC_Mn_NewsCms_Web_WebLogic_JsonNetResult callInfo, int offset);

        [NonAction]
        public override Mn.NewsCms.Web.WebLogic.JsonNetResult GetPhotos(int offset)
        {
            var callInfo = new T4MVC_Mn_NewsCms_Web_WebLogic_JsonNetResult(Area, Name, ActionNames.GetPhotos);
            ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "offset", offset);
            GetPhotosOverride(callInfo, offset);
            return callInfo;
        }

        [NonAction]
        partial void CatPhotoOverride(T4MVC_System_Web_Mvc_FileContentResult callInfo, int Id);

        [NonAction]
        public override System.Web.Mvc.FileContentResult CatPhoto(int Id)
        {
            var callInfo = new T4MVC_System_Web_Mvc_FileContentResult(Area, Name, ActionNames.CatPhoto);
            ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "Id", Id);
            CatPhotoOverride(callInfo, Id);
            return callInfo;
        }

        [NonAction]
        partial void GetPhotoOverride(T4MVC_System_Web_Mvc_FileContentResult callInfo, byte[] ImagByte);

        [NonAction]
        public override System.Web.Mvc.FileContentResult GetPhoto(byte[] ImagByte)
        {
            var callInfo = new T4MVC_System_Web_Mvc_FileContentResult(Area, Name, ActionNames.GetPhoto);
            ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "ImagByte", ImagByte);
            GetPhotoOverride(callInfo, ImagByte);
            return callInfo;
        }

    }
}

#endregion T4MVC
#pragma warning restore 1591, 3008, 3009, 0108, 0114


text:
import {
  moduleForComponent,
  test
} from 'ember-qunit';

moduleForComponent('dnd-item', {
  // specify the other units that are required for this test
  // needs: ['component:foo', 'helper:bar']
});

test('it renders', function(assert) {
  assert.expect(2);

  // creates the component instance
  var component = this.subject();
  assert.equal(component._state, 'preRender');

  // renders the component to the page
  this.render();
  assert.equal(component._state, 'inDOM');
});

test('it can move down', function(assert) {
  assert.expect(3);
  const component = this.subject({
    list: [
      'A', 'B', 'C', 'D', 'E', 'F', 'G'
    ]
  });
  //moving an object should always place it right before the target
  //which means that we need special case to move the object on the last place

});


text:
<?php
/*
this test works fine with Expat but fails with libxml
which we now use as default

further investigation has shown that not only line count
is skippet on CDATA sections but that libxml does also
show different column numbers and byte positions depending
on context and in opposition to what one would expect to
see and what good old Expat reported just fine ...
*/

$xmls = array();

// Case 1: CDATA Sections
$xmls["CDATA"] ='<?xml version="1.0" encoding="iso-8859-1" ?>
<data>
<![CDATA[
multi
line
CDATA
block
]]>
</data>';

// Case 2: replace some characters so that we get comments instead
$xmls["Comment"] ='<?xml version="1.0" encoding="iso-8859-1" ?>
<data>
<!-- ATA[
multi
line
CDATA
block
-->
</data>';

// Case 3: replace even more characters so that only textual data is left
$xmls["Text"] ='<?xml version="1.0" encoding="iso-8859-1" ?>
<data>
-!-- ATA[
multi
line
CDATA
block
---
</data>';

function startElement($parser, $name, $attrs) {
    printf("<$name> at line %d, col %d (byte %d)\n",
		       xml_get_current_line_number($parser),
		       xml_get_current_column_number($parser),
		       xml_get_current_byte_index($parser));
}

function endElement($parser, $name) {
    printf("</$name> at line %d, col %d (byte %d)\n",
		       xml_get_current_line_number($parser),
		       xml_get_current_column_number($parser),
		       xml_get_current_byte_index($parser));
}

function characterData($parser, $data) {
  // dummy
}

foreach ($xmls as $desc => $xml) {
  echo "$desc\n";
	$xml_parser = xml_parser_create();
	xml_set_element_handler($xml_parser, "startElement", "endElement");
	xml_set_character_data_handler($xml_parser, "characterData");
	if (!xml_parse($xml_parser, $xml, true))
		echo "Error: ".xml_error_string(xml_get_error_code($xml_parser))."\n";
	xml_parser_free($xml_parser);
}
?>


text:
var Predicate = require('./../../../lib/core/predicates/predicates.js');
var _ = require('underscore');
var assert = require('assert');

describe("Verify search predicates [UNIT]", function () {

    it ('Should return correct AND predicate for two functions', function () {
        var firstPredicate = new Predicate(_.constant(true));
        var secondPredicate = new Predicate(_.constant(false));

        var resultPredicate = firstPredicate.and(secondPredicate);

        assert.equal(resultPredicate.fn(), false);
    });

    it ('Should return correct OR predicate for two functions', function () {
        var firstPredicate = new Predicate(_.constant(true));
        var secondPredicate = new Predicate(_.constant(false));

        var resultPredicate = firstPredicate.or(secondPredicate);

        assert.equal(resultPredicate.fn(), true);
    });

    it ('Should return constant predicate that always return true', function () {
        var predicate = Predicate.alwaysTrue();

        assert.equal(predicate.fn(), true);
    });

    it ('Should return correct AND predicate for multiple atomic leaf predicates', function () {
        var firstPredicate = new Predicate(_.constant(true));
        var secondPredicate = new Predicate(_.constant(false));
        var thirdPredicate = new Predicate(_.constant(false));

        var resultPredicate = Predicate.and(firstPredicate, secondPredicate, thirdPredicate);

        assert.equal(resultPredicate.fn(), false);
    });

    it ('Should return correct OR predicate for multiple atomic leaf predicates', function () {
        var firstPredicate = new Predicate(_.constant(true));
        var secondPredicate = new Predicate(_.constant(false));
        var thirdPredicate = new Predicate(_.constant(false));

        var resultPredicate = Predicate.or(firstPredicate, secondPredicate, thirdPredicate);

        assert.equal(resultPredicate.fn(), true);
    });

});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Ploeh.AutoFixture.Kernel;
using Xunit;
using Xunit.Extensions;

namespace Ploeh.AutoFixtureUnitTest.Kernel
{
    public class EnumerableRelayTest
    {
        [Fact]
        public void SutIsSpecimenBuilder()
        {
            // Fixture setup
            // Exercise system
            var sut = new EnumerableRelay();
            // Verify outcome
            Assert.IsAssignableFrom<ISpecimenBuilder>(sut);
            // Teardown
        }

        [Fact]
        public void CreateWithNullContextThrows()
        {
            // Fixture setup
            var sut = new EnumerableRelay();
            var dummyRequest = new object();
            // Exercise system and verify outcome
            Assert.Throws<ArgumentNullException>(() =>
                sut.Create(dummyRequest, null));
            // Teardown
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        [InlineData(1)]
        [InlineData(typeof(object))]
        [InlineData(typeof(string))]
        [InlineData(typeof(int))]
        [InlineData(typeof(Version))]
        [InlineData(typeof(object[]))]
        [InlineData(typeof(string[]))]
        [InlineData(typeof(int[]))]
        [InlineData(typeof(Version[]))]
        [InlineData(typeof(IList<object>))]
        [InlineData(typeof(IList<string>))]
        [InlineData(typeof(IList<int>))]
        [InlineData(typeof(IList<Version>))]
        public void CreateWithNoneEnumerableRequestReturnsCorrectResult(object request)
        {
            // Fixture setup
            var sut = new EnumerableRelay();
            // Exercise system
            var dummyContext = new DelegatingSpecimenContext { OnResolve = r => Enumerable.Empty<object>() };
            var result = sut.Create(request, dummyContext);
            // Verify outcome
#pragma warning disable 618
            var expectedResult = new NoSpecimen(request);
#pragma warning restore 618
            Assert.Equal(expectedResult, result);
            // Teardown
        }

        [Theory]
        [InlineData(typeof(IEnumerable<object>), typeof(object))]
        [InlineData(typeof(IEnumerable<string>), typeof(string))]
        [InlineData(typeof(IEnumerable<int>), typeof(int))]
        [InlineData(typeof(IEnumerable<Version>), typeof(Version))]
        public void CreateWithEnumerableRequestReturnsCorrectResult(Type request, Type itemType)
        {
            // Fixture setup
            var expectedRequest = new MultipleRequest(itemType);
            object contextResult = Enumerable.Empty<object>();
#pragma warning disable 618
            var context = new DelegatingSpecimenContext { OnResolve = r => expectedRequest.Equals(r) ? contextResult : new NoSpecimen(r) };
#pragma warning restore 618

            var sut = new EnumerableRelay();
            // Exercise system
            var result = sut.Create(request, context);
            // Verify outcome
            Assert.NotNull(result);
            // Teardown
        }

        [Fact]
        public void CreateConvertsEnumerableToCorrectGenericType()
        {
            // Fixture setup
            var request = typeof(IEnumerable<int>);
            var expectedRequest = new MultipleRequest(typeof(int));
            var enumerable = Enumerable.Range(1, 3).Cast<object>();
#pragma warning disable 618
            var context = new DelegatingSpecimenContext { OnResolve = r => expectedRequest.Equals(r) ? (object)enumerable : new NoSpecimen(r) };
#pragma warning restore 618

            var sut = new EnumerableRelay();
            // Exercise system
            var result = sut.Create(request, context);
            // Verify outcome
            var e = Assert.IsAssignableFrom<IEnumerable<int>>(result);
            Assert.True(enumerable.Cast<int>().SequenceEqual(e));
            // Teardown
        }

        [Theory]
        [InlineData(0)]
        [InlineData(1)]
        [InlineData(typeof(object))]
        [InlineData(typeof(object[]))]
        public void CreateReturnsCorrectResultWhenContextReturnsNonEnumerableResult(object response)
        {
            // Fixture setup
            var request = typeof(IEnumerable<object>);
            var context = new DelegatingSpecimenContext { OnResolve = r => response };
            var sut = new EnumerableRelay();
            // Exercise system
            var result = sut.Create(request, context);
            // Verify outcome
#pragma warning disable 618
            var expectedResult = new NoSpecimen(request);
#pragma warning restore 618
            Assert.Equal(expectedResult, result);
            // Teardown
        }

        [Fact]
        public void CreateFiltersOmitSpecimenInstances()
        {
            // Fixture setup
            var request = typeof(IEnumerable<int>);
            var expectedRequest = new MultipleRequest(typeof(int));

            var enumerable = new object[]
            {
                1,
                new OmitSpecimen(),
                3
            };
            var context = new DelegatingSpecimenContext
            {
#pragma warning disable 618
                OnResolve = r => expectedRequest.Equals(r) ? (object)enumerable : new NoSpecimen(r)
#pragma warning restore 618
            };

            var sut = new EnumerableRelay();
            // Exercise system
            var actual = sut.Create(request, context);
            // Verify outcome
            var iter = Assert.IsAssignableFrom<IEnumerable<int>>(actual);
            Assert.True(
                enumerable.OfType<int>().SequenceEqual(iter),
                "Actual sequence is not equal to expected sequence.");
            // Teardown
        }
    }
}


text:
package com.ss.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/*
 * This is the main Spring Boot application class. It configures Spring Boot, JPA, Swagger
 */

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.ss.server")
@EnableJpaRepositories("com.ss.server.dao.jpa")
@EnableSwagger2
public class Application {

    private static final Class<Application> applicationClass = Application.class;
    private static final Logger log = LoggerFactory.getLogger(applicationClass);

    public static void main(String[] args) {
        SpringApplication.run(applicationClass, args);
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 67(6): 1112 (1976)

#### Original name
Nannizzia borellii Moraes, A.A. Padhye & Ajello, 1976

### Remarks
null


text:
        <title>${title}</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Please enable Javascript and install Adobe Flash Player.


text:
require(['jquery', 'oae.core', '/tests/qunit/js/util.js'], function($, oae, util) {

    module("JavaScript Formatting");

    /**
     * Test a JavaScript file against a provided regular expression
     *
     * @param  {String}    path           The path to the `jsFile`
     * @param  {String}    jsFile         The content of the JavaScript file that should be tested
     * @param  {Object}    regex          The regular expression to test the JavaScript against
     * @param  {String}    description    The description of the test
     */
    var doRegexTest = function(path, jsFile, regex, description) {
        // Remove comments from file to test
        var testFile = jsFile.replace(/(\/\*([\s\S]*?)\*\/)|(\/\/(.*)$)/gm, '');
        var match = '';
        var errorString = '';
        var count = 0;

        if (regex.test(testFile)) {
            while ((match = regex.exec(jsFile)) !== null) {
                var beforeMatch = jsFile.substring(0, match.index);
                var matchLine = beforeMatch.split(/\n/).length;
                count++;
                errorString = errorString + '\n\nPath: ' + path + '\nLine: ' + matchLine + '\nString:\n' + match + '';
            }
        }

        if (count === 0) {
            ok(true, description);
        } else {
            ok(false, description + ', ' + count + ' error(s): ' + errorString);
        }
    };

    /**
     * Test a JavaScript file for formatting issues
     *
     * @param  {String}    path      The path to the `jsFile`
     * @param  {String}    jsFile    The content of the JavaScript file that should be tested
     */
    var checkJs = function(path, jsFile) {
        var regex = /(?!\'.*)\".*\"(?!.*')/gm;
        var description = 'Double quotes should only be used within single quotes';
        doRegexTest(path, jsFile, regex, description);

        regex = /^\s*function\s.*/gm;
        description = 'Use \"var <functionName> = function() {\"';
        doRegexTest(path, jsFile, regex, description);

        regex = /\)\s*$(\n|\r)^\s*\{.*/gm;
        description = 'Put opening braces on the same line as the statement';
        doRegexTest(path, jsFile, regex, description);

        regex = /.+\)(\s{0}|\s{2,})\{/gm;
        description = 'Use exactly one space before an opening brace';
        doRegexTest(path, jsFile, regex, description);

        regex = /.*\).*\{( |\t)+(\n|\r)/gm;
        description = 'Don\'t put whitespace after an opening brace';
        doRegexTest(path, jsFile, regex, description);

        regex = /.*\}( |\t)+(\n|\r)/gm;
        description = 'Don\'t put whitespace after a closing brace';
        doRegexTest(path, jsFile, regex, description);

        regex = /new\s+(Object|Array|Number|String|Boolean).*/gm;
        description = 'Use literal notation';
        doRegexTest(path, jsFile, regex, description);

        regex = /^\s*const\s/gm;
        description = 'Use \"var <ALLCAPS>\" instead of \"const\"';
        doRegexTest(path, jsFile, regex, description);

        regex = /\.(live|die|bind|unbind)\(/gm;
        description = 'Use \".on()\" and \".off()\" to attach event handlers';
        doRegexTest(path, jsFile, regex, description);

        regex = /\.prototype\..*=/gm;
        description = 'Do not extend prototypes';
        doRegexTest(path, jsFile, regex, description);

        regex = /(^|\s)(Object\.(freeze|preventExtensions|seal)|eval|((?!['"].*)(with)(?!.*['"])))(\s|$)/gm;
        description = 'Avoid using Object.freeze, Object.preventExtensions, Object.seal, with, eval';
        doRegexTest(path, jsFile, regex, description);

        regex = /(^|\s)typeof(\s|$)/gm;
        description = 'Use jquery or underscore for type checking';
        doRegexTest(path, jsFile, regex, description);
    };

    /**
     * Initialize the JavaScript Formatting test
     *
     * @param  {Object}   testData    The testdata containing all files to be tested (html, css, js, properties)
     */
    var jsFormattingTest = function(testData) {
        // Test that the main JavaScript files are properly formatted
        $.each(testData.mainJS, function(mainJSPath, mainJS) {
            test(mainJSPath, function() {
                checkJs(mainJSPath, mainJS);
            });
        });

        // Test that the API JavaScript files are properly formatted
        $.each(testData.apiJS, function(mainApiJSPath, apiJS) {
            test(mainApiJSPath, function() {
                checkJs(mainApiJSPath, apiJS);
            });
        });

        // Test that the OAE specific plugin files are properly formatted
        $.each(testData.oaePlugins, function(oaePluginJSPath, oaePluginJS) {
            test(oaePluginJSPath, function() {
                checkJs(oaePluginJSPath, oaePluginJS);
            });
        });

        // Test that the widget JavaScript files are properly formatted
        $.each(testData.widgetData, function(widgetJSPath, widget) {
            $.each(widget.js, function(widgetJSIndex, widgetJS) {
                test(widgetJSIndex, function() {
                    checkJs(widgetJSIndex, widgetJS);
                });
            });
        });

        // Start consuming tests again
        QUnit.start(2);
    };

    // Stop consuming QUnit test and load the widgets asynchronous
    QUnit.stop();
    util.loadTestData(jsFormattingTest);
});


text:
I'm working on linux, but these tools are cross-platform, so they may (or may not, idk) work on Windows.

- Python
- A serial monitor (I use the one in the Arduino IDE http://www.arduino.cc/en/Main/Software)
- A serial adapter
- A level converter, if the serial adapter is not 3.3V

## Wiring the Serial Connection ##

You'll need a 3.3V serial connection. 5v serial risks damage the ESP-8266, so use a 3.3V device or a level converter. I use SparkFun's 3.3V FTDI breakout (https://www.sparkfun.com/products/9873).

If using a serial converter like mine, you will also need a separate 3.3V power supply for the ESP-8266. It requires more current than most serial converters will supply.

Wiring (pinouts for some ESP-8266 versions at https://github.com/esp8266/esp8266-wiki/wiki/Hardware_versions):
- Serial converter ground, ESP-8266 ground, and power supply ground should all be connected
- ESP-8266 3.3V to power supply 3.3V
- ESP-8266 Tx and Rx to serial converter Tx and Rx. The labeling varies. For my converter, connect Tx to Rx and Rx to Tx. Connecting them backwards won't do any damage, so try both ways if unsure
- ESP-8266 reset and chip enable to power supply 3.3V
- Only when flashing firmware, connect ESP-8266 GPIO 0 to ground

Make sure to power on the serial converter BEFORE the ESP-8266 chip.

## Connecting to AT Firmware (optional) ##

Most ESP-8266 chips come with firmware that responds to AT commands. Some come with other firmware. Some come with firmware that prints an error message and then does nothing else. If you want to try out the AT commands or see what firmware your chip came with, you can play 'find the serial settings':

ESP-8266 default baud rates can be  9600, 19200, 57600, or 115200 depending on what firmware version they come with. Line ending may be CR, LF, or both.

Power on the ESP-8266. It will print a message stating the current firmware version by serial. The message will be in plain text if your serial settings match, or random ascii characters if they don't.

If the serial connection doesn't work, try checking /dev so see if a new tty device is added when plugging in the serial converter, and lsusb to check if a USB device is recognized. The Tx and Rx connections may need to be reversed.

Once the serial connection is working, sending 'AT' to the ESP-8266 should get an 'OK' response. For a full list of AT commands see http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module#AT_Commands

## Building NodeMCU ##

NodeMCU has a handy automatic building tool available here http://frightanic.com/nodemcu-custom-build/

The default options will work fine for this tutorial, and make sure to enter your e-mail address to receive the finished build. The build took about two minutes to run when I tried it.

You'll get an e-mail with links to two files: an integer build and a float build. The integer build only supports integer numbers, the float build supports both integers and floating-point (decimal) numbers. I assume there is some performance advantage to the integer build, though I don't really know. I used the integer build here.

## Flashing with esptool

Get the esptool Python-based flasher

    git clone https://github.com/themadinventor/esptool
    python esptool/setup.py build
    sudo python esptool/setup.py install

Connect GPIO 0 to gound and restart the ESP-8266 to enter flashing mode.

Flash with esptool

    sudo python esptool/esptool.py --port /dev/ttyUSB0 --baud 9600 write_flash 0x00000 your_nodemcu_binary.bin

using the .bin file the online builder e-mailed to you.

This is set to run rather slow to reduce the likelyhood of errors. It may take a few minutes to flash (7 when I did it), during which you should see the ESP-8266 serial transmit LED flash every few seconds.

After the esptool command exits, disconnect GPIO 0 from ground and restart to go back to run mode.

With NodeMCU on the ESP-8266, it will run a lua interpreter, and execute lua commands sent to it over serial. For full details, see NodeMCU's Github (https://github.com/nodemcu/nodemcu-firmware) or docs (http://www.nodemcu.com/docs/). When you first start it, it will print an error about not finding init.lua; this is normal and only means you haven't put an init.lua file in it yet.

The interpreter can be accessed over serial with 9600 baud rate and CR+LF line ending. To see it do something basic, run `print(2+2)`

On startup, NodeMCU checks its internal memory for a file named init.lua and runs it if found. There are lua commands for writing this file without needing to reflash the firmware, and the luatool utility offers a streamlined way to do this.

## Copy .lua Files With luatool ##

Fetch luatool from GitHub

    git clone https://github.com/4refr0nt/luatool

To load a new lua file as init.lua, which will run automatically when the ESP-8266 starts, disconnect the serial monitor and run

    python luatool/luatool/luatool.py --port /dev/ttyUSB0 --src your_lua_file.lua --dest init.lua --verbose

The `--restart` option cause luatool to restart the ESP-8266 after transferring a file. A NodeMCU system can also be restarted by sending `node.restart()` over serial.

## Wifi LED Example ##

The example .lua file in this repo creates a network, and runs a simple HTTP server that allows controlling a connected device over Wifi.

Download the example script

    wget https://raw.githubusercontent.com/Densaugeo/ESP-8266-NodeMCU-Tutorial/master/wifi_led.lua

Connect an LED to NodeMCU pin 4, which is usually GPIO 2 on the ESP-8266's labeling. You can test whether a pin number is correct by sending `gpio.mode(4, gpio.OUTPUT)` and `gpio.write(4, gpio.LOW)` or `gpio.write(4, gpio.HIGH)` or serial to control pin 4, for example. To use different pin numbers, edit the example script.

Disconnect the serial monitor, then load the script and reboot. Loading a lua script is not flashing, and should be done in regular run mode (GPIO 0 not grounded)

    python luatool/luatool/luatool.py --port /dev/ttyUSB0 --src wifi_led.lua --dest init.lua --verbose -- restart

Connect to the 'ESP-test' wifi network (password: ESP-test) and open http://192.168.4.1/

    firefox 192.168.4.1

Clicking the button should toggle GPIO 2.


text:
# com.github.ddth.commons.utils

## Included in `ddth-commons-core`

**Maven**

```xml
<dependency>
    <groupId>com.github.ddth</groupId>
    <artifactId>ddth-commons-core</artifactId>
    <version>${ddth_commons_version}</version>
</dependency>
```

**New since v1.1.0**

`AESUtils` & `RSAUtils` are moved to `ddth-common-crypto` (package `com.github.ddth.commons.crypto`).

### AESUtils

AES encryption utility class.

- Default: 128-bit encryption key
- Default: `AES/CTR/NoPadding` transformation
- Support custom transformation and IV

See [Java Cryptography Architecture Oracle Providers Documentation for JDK 8](https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#cipherTable)

**New since v1.1.0**

`AESUtils` is moved to `ddth-common-crypto` (package `com.github.ddth.commons.crypto`).

**New since v0.9.2**

- Support all AES cipher modes provided by [SunJCE Provider](https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#cipherTable).
- Change `DEFAULT_CIPHER_TRANSFORMATION` to `AES/CTR/NoPadding`
- New methods:
  - `String randomIV(int)` and `byte[] randomIVAsBytes(int)`
  - `byte[] randomKeyAsBytesSecure()`, `byte[] randomIVAsBytesSecure()` and `byte[] randomIVAsBytesSecure(int)`
  - `Cipher createCipher(int, byte[], byte[], String)`
  - `encrypt(...)` and `decrypt(...)` that support encrypting/decrypting stream of large data.
- New classes `CipherException`, `DdthCipherInputStream` and  `DdthCipherOutputStream`.

### DateFormatUtils

Utility to format a `java.util.Date` to string, and parse a string to `java.util.Date`.

- Use a pool of `java.text.DateFormat`s for multi-threading environment.

**New since v0.6.1**

- New constant `DF_ISO8601`: ISO8601 datetime format

### DateTimeUtils & CalendarWrapper

Helper class to work with `java.util.Date` and `java.util.Calendar`.

- Calculate the start-of-second/minute/hour/day/week/month/year point of a supplied `Calendar`.

**New since v0.9.2**

- New methods:
  - `nextMillisecond(Calendar)` and `nextMillisecond(Date)`
  - `addMilliseconds(...)`, `addSeconds(...)`, `addMinutes(...)`, `addHours(...)`, `addDays(...)`, `addWeeks(...)`, `addMonths(...)` and `addYears(...)`

### DPathUtils

Utility to access data from a hierarchy structure.

DPath notation:

- `.` (dot character): path separator.
- `name`: access a map's attribute specified by `name`.
- `[i]`: access i'th element of a list/map (0-based).

(example: `employees.[1].first_name`).

Sample usage: assuming you have the following data structure:

```java
Map<String, Object> company = new HashMap<String, Object>();
company.put("name", "Monster Corp.");
company.put("year", 2003);

List<Map<String, Object>> employees = new ArrayList<Map<String, Object>>();
company.put("employees", employees);

Map<String, Object> employee1 = new HashMap<String, Object>();
employee1.put("first_name", "Mike");
employee1.put("last_name", "Wazowski");
employee1.put("email", "mike.wazowski@monster.com");
employee1.put("age", 29);
employees.add(employee1);

Map<String, Object> employee2 = new HashMap<String, Object>();
employee2.put("first_name", "Sulley");
employee2.put("last_name", "Sullivan");
employee2.put("email", "sulley.sullivan@monster.com");
employee2.put("age", 30);
employees.add(employee2);
```

You can access company's attributes:

```java
String companyName = DPathUtils.getValue(company, "name", String.class);
//got string "Monster Corp."

Integer companyYear = DPathUtils.getValue(company, "year", Integer.class);
//got integer 2003
```

You can access the two employees:

```java
Object user1 = DPathUtils.getValue(company, "employees.[0]");
//got map {first_name=Mike, email=mike.wazowski@monster.com, age=29, last_name=Wazowski}

Map<String, Object> user2 = DPathUtils.getValue(company, "employees.[1]", Map.class);
//got map {first_name=Sulley, email=sulley.sullivan@monster.com, age=30, last_name=Sullivan}
```

Or, employee's attributes:

```java
String firstName1 = DPathUtils.getValue(company, "employees.[0].first_name", String.class);

Object email2 = DPathUtils.getValue(company, "employees.[1].email");
//got string "sulley.sullivan@monster.com"

Long age2 = DPathUtils.getValue(company, "employees.[1].age", Long.class);
//got a Long value of 30
```

**New since v0.1.2**

- `DPathUtils.getValue(Object target, String dPath, Class clazz)` now tries its best to convert returned value to the specified type. For example, the value extracted by `dPath` is a string `"12345"` and the clazz is of type `Integer`, the method will parse the string `"12345"` to the integer `12345`.

**New since v0.6.2**

- `DPathUtils` now supports reading/writing values from/to Jackson's JSON tree (need `ddth-commons-serialization`).

**New since v0.9.2**

- Can mix `JsonNode`s & POJOs in a tree.

### HashUtils

Helper class to calculate hash values.

- Fash hashing function.
- Linear hashing maps an object to a bucket (object -> [0, numBuckets)).
- Consistent hashing map an object to a bucket (object -> [0, numBuckets)).
- CRC32, MD5, SHA1, SHA256, SHA512 hashing functions.

**New since v0.6.3**

- New methods `long checksumXXX(...)`: calculate checksum of an object.
- New methods `String murmur3(String)` and `String murmur3(byte[])`.
- Change `murmur3`, `crc32`, `md5`, `sha1`, `sha256`, `sha512` and `UTF8` to `public final static`.
- New attribute `fashHashFunc`: alias of `murmur3`.

### IdGenerator

A Java implementation of Twitter Snowflake algorithm to generate IDs.

Sample usage:

```java
IdGenerator idGen = IdGenerator.getInstance(IdGenerator.getMacAddr());

long id64 = idGen.generateId64();

String id128Hex = idGen.generateId128Hex();
...
```

### Ipv4Utils

IPV4 utility class.

- Convert IP number to long (e.g. 10.0.0.1 -> 167772161) and vice versa.
- Check if an IP (e.g. 10.0.0.5) matches a subnet (e.g. 10.0.0.0/24).

### MapUtils

**New since v0.6.1**

Helper class to work with `java.util.Map`.

- Extract typed-value from map.
- Construct a map from flat array of objects.
- Calculate map's checksum.

**New since v0.6.3**

- Remove method `long checksum(Map<?,?>)`, use `HashUtils.checksumXXX(...)` instead.

### ReflectionUtils

**New sintce v0.5.0**

Reflection utility class.

### RSAUtils

RSA encryption utility class.

- Support: 512, 1024, 2048 bit encryption key
- Default: `RSA/ECB/PKCS1Padding` transformation (11-byte padding size)
- Support custom transformation and padding size

**New since v1.1.0**

`RSAUtils` is moved to `ddth-common-crypto` (package `com.github.ddth.commons.crypto`).

**New since v0.9.2**

- Unit tested with all RSA cipher modes provided by [SunJCE Provider](https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#cipherTable).
- Unit tested with all RSA signature algorithms provides by [SunRsaSign](https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html#SunRsaSignProvider).

### UnsignedUtils

Utility to work with unsigned `long`s and `int`s, radix up to `62` (`0-9`, `A-Z` and `a-z`).

- `parseInt(s, radix)`: parse a unsigned int with the given radix, up to `62`.
- `parseLong(s, radix)`: parse a unsigned long with the given radix, up to `62`.
- `toString(intValue, radix)`: convert a unsigned int to string for the given radix, up to `62`.
- `toString(longValue, radix)`: convert a unsigned long to string for the given radix, up to `62`.

### ValueUtils

**New since v0.6.1**

Common utility class used by `MapUtils`, `DPathUtils` and `JacksonUtils` (need `ddth-commons-serialization`).

**New since v0.9.2**

Can mix `JsonNode` and POJO.

### VersionUtils

Utility to compare two version strings.

```java
/* "0.1.2" < "0.1.10", returns a negative number */
VersionUtils.compareVersions("0.1.2", "0.1.10");

/* "0.2.0" > "0.1.19", returns a positive number */
VersionUtils.compareVersions("0.2.0", "0.1.19");
```

## Included in `ddth-commons-serialization`

**Maven**

```xml
<dependency>
    <groupId>com.github.ddth</groupId>
    <artifactId>ddth-commons-serialization</artifactId>
    <version>${ddth_commons_version}</version>
</dependency>
```

### SerializationUtils

**New since v0.2.0**

- Serialize/De-serialize object to/from JSON string (use FasterXML's Jackson library).
- Serialize/De-serialize objecct to/from `byte[]` (use Jboss Serialization libary).

**New since v0.6.2**

- Serialize/De-serialize object to/from Jackson's `JsonNode`.

**New since v0.9.2**

- `toByteArray(...)` and `fromByteArray(...)` are now `deprecated` with no replacement. Use `toByteArrayKryo(...)`, `fromByteArrayKryo(...)`, `toByteArrayFst(...)` and `fromByteArrayFst(...)` explicitly.
- Migrate `Kryo` to version `5.0.0-RC2`.

## JacksonUtils

**New since v0.6.2**

Helper class to work with Jackson's `JsonNode`.

- Serialize object to `JsonNode`.
- Deserialize `JsonNode` to object.
- Load JSON tree from source.
- Access data from JSON tree using DPath expression.

**New since v0.6.2.1**

- New method `long checksum(JsonNode)`: calculate checksum of a `JsonNode`

**New since v0.6.3**

- Improve `JsonNode`'s checksum calculation.

## Included in `ddth-commons-spring`

**Maven**

```xml
<dependency>
    <groupId>com.github.ddth</groupId>
    <artifactId>ddth-commons-spring</artifactId>
    <version>${ddth_commons_version}</version>
</dependency>
```

### SpringUtils

Helper class to obtain Spring's beans from an `ApplicationContext`.

- Get a bean/beans, return `null` or empty collection on `NoSuchBeanDefinitionException`

## Included in `ddth-commons-thrift`

**Maven**

```xml
<dependency>
    <groupId>com.github.ddth</groupId>
    <artifactId>ddth-commons-thrift</artifactId>
    <version>${ddth_commons_version}</version>
</dependency>
```

### ThriftUtils

**New since v0.4.0**

Helper class to work with Apache Thrift.

- Serialize/De-serialize a thrift `TBase` object to/from `byte[]`.
- Helper methods to create various thrift servers.

## Included in `ddth-commons-typesafeconfig`

**Maven**

```xml
<dependency>
    <groupId>com.github.ddth</groupId>
    <artifactId>ddth-commons-typesafeconfig</artifactId>
    <version>${ddth_commons_version}</version>
</dependency>
```

### TypesafeConfigUtils

**New since v0.9.1**

Helper class to work with application's config file:

- Support various formats: HOCON, JSON, Properties, etc (see https://github.com/lightbend/config)
- Load, Parse & Resolve config files
- Helper methods to retrieve config value(s) as Java object(s)
- Return `null` in case of `ConfigException.Missing`, `ConfigException.WrongType` or `ConfigException.BadValue`


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>factorio-mod-maker</artifactId>
        <groupId>com.poldigo.factorio</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>desktop</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>

        <dependency>
            <groupId>com.poldigo.factorio</groupId>
            <artifactId>services</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
</project>


text:
package view.viewEvents;

import java.util.Optional;

import applicationConstants.StringConstants;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Alert.AlertType;
import javafx.stage.WindowEvent;

public class WindowCloseEvent implements EventHandler<WindowEvent> {

	@Override
	public void handle(WindowEvent event) {
		Alert l_alert = new Alert( AlertType.CONFIRMATION, StringConstants.WINDOW_CLOSE_DIALOG );
		Optional<ButtonType> l_response = l_alert.showAndWait();
		if ( l_response.isPresent() && l_response.get().equals( ButtonType.OK ) ) {
			Platform.exit();
		} else {
			event.consume();
		}
	}

}


text:
'use strict';

angular
    .module('sample', ['atomic-notify'])
    .config(['atomicNotifyProvider', function(atomicNotifyProvider){

        // atomicNotifyProvider.setDefaultDelay(5000);
        // atomicNotifyProvider.useIconOnNotification(true);

    }])
    .controller('HomeController', function($scope, atomicNotifyService){

        $scope.simple = function(){
            atomicNotifyService.info('Yes, this is the default notification :D');
        };

        $scope.warning = function(){
            atomicNotifyService.warning('Upss you broke the internets');
        };

        $scope.success = function(){
            atomicNotifyService.success('Yeah!, this works as expected!');
        };

        $scope.error = function(){
            atomicNotifyService.error('Something went\'t wrong');
        };

        $scope.custom = function(){
            atomicNotifyService.custom('info', 'Another round!', 'fa fa-beer');
        };

    });


text:
const url = require('url')

const config = require('../config')
const utils = require('../utils')

const UrlCommand = class {
  add (vorpal) {
    vorpal
      .command('url [url]')
      .alias([ 'api', 'site' ])
      .description('Get or set API endpoint')
      .action(function (args, callback) {
        if (args.url) {
          config.set('url', url.parse(args.url))
          vorpal.delimiter(utils.promptString())
        } else {
          this.log(url.format(config.get('url')))
        }
        callback()
      })
  }
}

module.exports = new UrlCommand()


text:
using HFEA.Web.ViewModel.CaFC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using umbraco.interfaces;
using umbraco.NodeFactory;
using Umbraco.Web;
using Umbraco.Web.Routing;

namespace HFEA.Web.Helpers
{
    public class CafcProfileUrlHelper : ICafcProfileUrlHelper
    {
        private INode clinicProfileNode;
        private INode cafcFeedbackNode;
        private INode statsPageNode;

        internal INode ClinicProfileNode
        {
            get
            {
                if (clinicProfileNode == null)
                {
                    clinicProfileNode = new Node(Core.Config.Settings.KeyPages.ClinicProfile);
                }

                return clinicProfileNode;
            }
        }

        internal INode CafcFeedbackNode
        {
            get
            {
                if (cafcFeedbackNode == null)
                {
                    cafcFeedbackNode = new Node(Core.Config.Settings.KeyPages.ClinicProfileFeedback);
                }

                return cafcFeedbackNode;
            }
        }

        internal INode CafcStatsPageNode
        {
            get
            {
                if (statsPageNode == null)
                {
                    statsPageNode = ClinicProfileNode.GetFirstChildByDocType(Core.Config.Settings.KeyDocTypes.ClinicStatistics);
                }

                return statsPageNode;
            }
        }

        public string GetPageUrl(int clinicId)
        {
            return GetPageUrl(clinicId.ToString());
        }

        public string GetPageUrl(string urlSegmentReplacement)
        {
            return this.ReplaceClinicProfileUrlSegment(urlSegmentReplacement);
        }

        public string GetFeedBackUrl(int clinicId)
        {
            return this.GetFeedBackUrl(clinicId.ToString());
        }

        public string GetFeedBackUrl(string urlSegmentReplacement)
        {
            string url = this.CafcFeedbackNode?.NiceUrl;
            return this.ReplaceClinicProfileUrlSegment(urlSegmentReplacement, url);
        }

        public string GetStatsPageUrl(int clinicId)
        {
            return this.GetStatsPageUrl(clinicId.ToString());
        }

        public string GetStatsPageUrl(string urlSegmentReplacement)
        {
            var statsPage = ClinicProfileNode.GetFirstChildByDocType(Core.Config.Settings.KeyDocTypes.ClinicStatistics);
            return this.ReplaceClinicProfileUrlSegment(urlSegmentReplacement, statsPage?.NiceUrl);
        }

        private string ReplaceClinicProfileUrlSegment(string urlSegmentReplacement, string genericPageUrl = null)
        {
            string profilePageUrl = ClinicProfileNode.NiceUrl;

            string url = string.IsNullOrEmpty(genericPageUrl)
                ? profilePageUrl
                : genericPageUrl;

            string dif = profilePageUrl.Remove(0, ClinicProfileNode.Parent.NiceUrl.Length);
            if (dif.EndsWith("/"))
            {
                dif = dif.Substring(0, dif.Length - 1);
            }

            url = url.Replace(dif, urlSegmentReplacement);

            return url;
        }
    }
}


text:
<?php

class AdminModule extends CWebModule
{
	public function init()
	{
		// this method is called when the module is being created
		// you may place code here to customize the module or the application

		// import the module-level models and components
		$this->setImport(array(
			'admin.models.*',
			'admin.components.*',
		));

                //Set layout
                Yii::app()->theme = 'courses/backend';
                Yii::app()->setComponents(array(
                                            'errorHandler'=>array(
                                                    // use 'site/error' action to display errors
                                                    'errorAction'=> '/admin/default/error',
                                            ),
                                            'user'               =>array
                                            (
                                                'loginUrl'       =>array('admin/default/login'),
                                            ),
                ));

	}

	public function beforeControllerAction($controller, $action)
	{
		if(parent::beforeControllerAction($controller, $action))
		{
			// this method is called before any module controller action is performed
			// you may place customized code here
			return true;
		}
		else
			return false;
	}
}


text:
<ion-header>
  <ion-navbar default>
    <ion-title>
      Add Comment
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="comment-page" padding>

{{poi.AddressInfo.Title}}

{{poi.AddressInfo.AddressLine1}}

Recent Check-ins are a big help to other drivers when planning their journey. Tell everyone what you thought about this
    charging location.

  <ion-list>

    <ion-item>
      <ion-label stacked>Comment Type</ion-label>
      <ion-select [(ngModel)]="commentModel.UserCommentTypeID">
        <ion-option *ngFor="let item of commentTypes" [value]="item.ID" [selected]="false">{{item.Title}}</ion-option>
      </ion-select>

    </ion-item>

    <ion-item>
      <ion-label stacked>What Did You Think?</ion-label>
      <ion-input type="text" [(ngModel)]="commentModel.Comment"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label stacked>Did You Successfully Charge?</ion-label>
      <ion-select [(ngModel)]="commentModel.CheckinStatusTypeID">
        <ion-option *ngFor="let item of checkinTypes" [value]="item.ID" [selected]="false">{{item.Title}}</ion-option>
      </ion-select>

    </ion-item>

    <ion-item>
      <ion-label stacked>Your Rating</ion-label>

      <ion-select [(ngModel)]="commentModel.Rating">
        <ion-option value="5">5 - Excellent</ion-option>
        <ion-option value="4">4 - Good</ion-option>
        <ion-option value="3">3 - Average</ion-option>
        <ion-option value="2">2 - Not Good</ion-option>
        <ion-option value="1">1 - Bad</ion-option>
        <ion-option value="" [selected]="true">Not Rated</ion-option>
      </ion-select>
    </ion-item>

  </ion-list>

</ion-content>
<ion-footer>
  <ion-toolbar>
    <ion-buttons start>
      <button ion-button (click)="cancel()" icon-left>
            <ion-icon name="close"></ion-icon>
      Cancel

    </button>
    </ion-buttons>
    <ion-buttons end>
      <button ion-button (click)="add()" icon-right>
      Submit
      <ion-icon name="send" ></ion-icon>
    </button>
    </ion-buttons>
  </ion-toolbar>
</ion-footer>


text:
layout: post
status: publish
published: true
title: Schwarzenegger & Chamberlain at Hefner
author: mick
author_login: mick
author_email: mickael@flochlay.com
wordpress_id: 473
wordpress_url: http://morningcoffee.mickaelflochlay.com/?p=473
date: 2011-07-09 12:05:34.000000000 +02:00
categories:
- Fun
- !binary |-
  Q2luw6ltYQ==
- Sport
tags:
- basket
comments: []
---
Chitwood & Hobbs about an unlikely picture :

Arnold Schwarzenegger, Hugh Hefner and Wilt Chamberlain hanging out at the Playboy Mansion in 1977. If there wasn't photographic evidence I'm not sure I would believe this meeting of the minds actually happened. Can I get a transcript of what this conversation was about? Too bad what happens at the Playboy Mansion, stays at the Playboy Mansion.

via Chitwood & Hobbs, A Couple of Playboys Arnold Schwarzenegger, Hugh....


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>OpenSeadragon v2.1.0</title>
  <meta name="author" content="viaWebGL">
  <meta name="description" content="GLSL shaders for zoomable DZI images: openSeadragonGL">

  <link rel = "stylesheet" type = "text/css" href = "../../style/sea.css" />


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <ffi.h>
#include "fficonfig.h"

#if defined HAVE_STDINT_H
#include <stdint.h>
#endif

#if defined HAVE_INTTYPES_H
#include <inttypes.h>
#endif

#define MAX_ARGS 256

#define CHECK(x) (!(x) ? (abort(), 1) : 0)

/* Define macros so that compilers other than gcc can run the tests.  */
#undef __UNUSED__
#if defined(__GNUC__)
#define __UNUSED__ __attribute__((__unused__))
#define __STDCALL__ __attribute__((stdcall))
#define __THISCALL__ __attribute__((thiscall))
#define __FASTCALL__ __attribute__((fastcall))
#else
#define __UNUSED__
#define __STDCALL__ __stdcall
#define __THISCALL__ __thiscall
#define __FASTCALL__ __fastcall
#endif

#ifndef ABI_NUM
#define ABI_NUM FFI_DEFAULT_ABI
#define ABI_ATTR
#endif

/* Prefer MAP_ANON(YMOUS) to /dev/zero, since we don't need to keep a
   file open.  */
#ifdef HAVE_MMAP_ANON
# undef HAVE_MMAP_DEV_ZERO

# include <sys/mman.h>
# ifndef MAP_FAILED
#  define MAP_FAILED -1
# endif
# if !defined (MAP_ANONYMOUS) && defined (MAP_ANON)
#  define MAP_ANONYMOUS MAP_ANON
# endif
# define USING_MMAP

#endif

#ifdef HAVE_MMAP_DEV_ZERO

# include <sys/mman.h>
# ifndef MAP_FAILED
#  define MAP_FAILED -1
# endif
# define USING_MMAP

#endif

/* MinGW kludge.  */
#ifdef _WIN64
#define PRIdLL "I64d"
#define PRIuLL "I64u"
#else
#define PRIdLL "lld"
#define PRIuLL "llu"
#endif

/* Tru64 UNIX kludge.  */
#if defined(__alpha__) && defined(__osf__)
/* Tru64 UNIX V4.0 doesn't support %lld/%lld, but long is 64-bit.  */
#undef PRIdLL
#define PRIdLL "ld"
#undef PRIuLL
#define PRIuLL "lu"
#define PRId8 "hd"
#define PRIu8 "hu"
#define PRId64 "ld"
#define PRIu64 "lu"
#define PRIuPTR "lu"
#endif

/* PA HP-UX kludge.  */
#if defined(__hppa__) && defined(__hpux__) && !defined(PRIuPTR)
#define PRIuPTR "lu"
#endif

/* IRIX kludge.  */
#if defined(__sgi)
/* IRIX 6.5 <inttypes.h> provides all definitions, but only for C99
   compilations.  */
#define PRId8 "hhd"
#define PRIu8 "hhu"
#if (_MIPS_SZLONG == 32)
#define PRId64 "lld"
#define PRIu64 "llu"
#endif
/* This doesn't match <inttypes.h>, which always has "lld" here, but the
   arguments are uint64_t, int64_t, which are unsigned long, long for
   64-bit in <sgidefs.h>.  */
#if (_MIPS_SZLONG == 64)
#define PRId64 "ld"
#define PRIu64 "lu"
#endif
/* This doesn't match <inttypes.h>, which has "u" here, but the arguments
   are uintptr_t, which is always unsigned long.  */
#define PRIuPTR "lu"
#endif

/* Solaris < 10 kludge.  */
#if defined(__sun__) && defined(__svr4__) && !defined(PRIuPTR)
#if defined(__arch64__) || defined (__x86_64__)
#define PRIuPTR "lu"
#else
#define PRIuPTR "u"
#endif
#endif

/* MSVC kludge.  */
#if defined _MSC_VER
#define PRIuPTR "lu"
#define PRIu8 "u"
#define PRId8 "d"
#define PRIu64 "I64u"
#define PRId64 "I64d"
#endif

#ifndef PRIuPTR
#define PRIuPTR "u"
#endif


text:
openFarmModule.factory('stageService', ['$http', '$log', '$q', 'alertsService',
  function stageService($http, $log, $q, alertsService) {

    // Should return Stage model:
    // {
    //   id: '',
    //   name: '',
    //   location: '',
    //   ...
    //   stages: [],
    //
    // }

    var buildStageWithPromise = function(data, included) {
      return $q(function (resolve, reject) {
        var stage = data.attributes;

        // The toExecute array gathers all the $q promises
        // generated by the missing data and will execute them
        // all in the $q.all that returns at the end of this
        // function.
        var toExecute = [];

        if (data.relationships.stage_actions.data === undefined ||
            data.relationships.stage_actions.data.length === 0) {
          stage.stage_actions = [];
        } else {
          // TODO: we'll need to go fetch these from the
          // server.
          stage.stage_actions = [];
        }

        if (data.relationships.pictures.data === undefined &&
            data.relationships.pictures.data.length === 0) {
          stage.pictures = [];
        } else {
          toExecute.push($q( function(resolve, reject) {
                $http.get(data.relationships.pictures.links.related)
                  .success(function(data) {
                    resolve(data);
                  });
              }));
        }
        $q.all(toExecute).then(function(data){
            data.forEach(function(datum) {
              // if we need to get really meta here
              // we can get services based on their name
              stage[datum.data[0].type] = datum.data;
            })
            resolve(stage);
        });
      });
    }

    var buildStage = function(data, included) {
      var stage = data.attributes;
      stage.id = data.id;

      var stageActions = (included || []).filter(function(obj) {
        return obj.type === 'stage-actions';
      });

      if (data.relationships.stage_actions.data === undefined ||
          data.relationships.stage_actions.data.length === 0) {
        stage.stage_actions = [];
      } else if (stageActions.length > 0) {
        stage.stage_actions = stageActions.map(function(stageAction) {
          return buildStageAction(stageAction);
        });
      }

      if (data.relationships.pictures.data === undefined &&
          data.relationships.pictures.data.length === 0) {
        stage.pictures = [];
      } else {
        var mappedIds = data.relationships.pictures.data.map(function (pic) {
          return pic.id;
        })
        if (included) {
          stage.pictures = included.filter(function (pic) {
            return mappedIds.indexOf(pic.id) !== -1 && pic.type === 'pictures';
          }).map(function(pic) {
            return pic.attributes;
          })
        }
      }
      return stage
    }

    var buildStageAction = function(data) {
      return data.attributes;
    }

    var getStageWithPromise = function(id) {
      return $q(function (resolve, reject) {
        $http.get('/api/v1/stages/' + stage.id + '/pictures')
          .success(function(pictures) {
            resolve(pictures.data);
          })
      });
    }

    var getPictures = function(stage) {
      return $q(function (resolve, reject) {
        $http.get('/api/v1/stages/' + stage.id + '/pictures')
          .success(function(pictures) {
            resolve(pictures.data);
          })
      });
    }

    var createStage = function(params, callback){
      $http.post('/api/v1/stages/', params)
        .success(function (response) {
          return callback (true, buildStage(response.stage, response.included));
        }).error(function (response, code) {
          alertsService.pushToAlerts(response.errors, code);
        });
    };

    var createStageWithPromise = function(params) {
      return $q(function (resolve, reject) {
        $http.post('/api/v1/stages/', params)
          .success(function (response) {
            resolve(buildStage(response.data, response.included));
          }).error(function (response, code) {
            reject();
            alertsService.pushToAlerts(response.errors, code);
          });
      })
    }

    var updateStage = function(stageId, params, callback){
      $http.put('/api/v1/stages/' + stageId + '/', params)
        .success(function (response) {
          return callback (true, response.stage);
        })
        .error(function (response, code) {
          alertsService.pushToAlerts(response.errors, code);
        });
    };

    var updateStageWithPromise = function(stageId, params) {
      return $q(function (resolve, reject) {
        $http.put('/api/v1/stages/' + stageId + '/', params)
          .success(function (response) {
            resolve(buildStage(response.data));
          }).error(function (response, code) {
            $log.error("error when updating a stage", response, code);
            reject();
            alertsService.pushToAlerts(response.errors, code);
          });
      })
    }

    var deleteStage = function(stageId, callback){
      $http.delete('/api/v1/stages/' + stageId + '/')
        .success(function(response){
          return callback (true, response);
        })
        .error(function (response, code){
          alertsService.pushToAlerts(response.errors, code);
        });
    };

    var deleteStageWithPromise = function(stageId) {
      return $q(function (resolve, reject) {
        $http.delete('/api/v1/stages/' + stageId + '/')
          .success(function (response) {
            resolve();
          }).error(function (response, code) {
            reject();
            alertsService.pushToAlerts(response.errors, code);
          });
      })
    }

    return {
      // 'getGuide': getStage,
      'utilities': {
        'buildStage': buildStage,
        'buildStageWithPromise': buildStageWithPromise
      },
      'getStageWithPromise': getStageWithPromise,
      'createStageWithPromise': createStageWithPromise,
      'updateStageWithPromise': updateStageWithPromise,
      'deleteStageWithPromise': deleteStageWithPromise,
      'deleteStage': deleteStage,
      'createStage': createStage,
      'updateStage': updateStage,
      'getPictures': getPictures,
    };
}]);