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

package com.google.caja.parser.js;

import com.google.caja.lexer.FilePosition;
import com.google.caja.lexer.TokenConsumer;
import com.google.caja.parser.ParseTreeNode;
import com.google.caja.render.Concatenator;
import com.google.caja.render.JsMinimalPrinter;
import com.google.caja.render.JsPrettyPrinter;
import com.google.caja.reporting.RenderContext;
import java.util.List;

/**
 * A RenderedExpression is a Javascript expression tree rendered as a string,
 * which is cheaper to clone and/or cache than an actual ParseTreeNode tree.
 * <p>
 * Used by {@link CajoledModule#flattenProperty}.
 */
public final class RenderedExpression extends AbstractExpression {
  private static final long serialVersionUID = 1L;

  private final String value;

  @ReflectiveCtor
  public RenderedExpression(FilePosition pos, String value, List<?> children) {
    this(pos, value);
    assert children.isEmpty();
  }

  public RenderedExpression(ParseTreeNode n, boolean minify) {
    this(render(n, minify));
  }

  public RenderedExpression(String value) {
    this(FilePosition.UNKNOWN, value);
  }

  public RenderedExpression(FilePosition pos, String value) {
    super(pos, RenderedExpression.class);
    this.value = value;
  }

  @Override
  public Object getValue() {
    return value;
  }

  @Override
  public String typeOf() {
    return null;
  }

  @Override
  public void render(RenderContext r) {
    r.getOut().consume(value);
  }

  private static String render(ParseTreeNode n, boolean minify) {
    StringBuilder buf = new StringBuilder();
    TokenConsumer tc;
    if (minify) {
      tc = new JsMinimalPrinter(new Concatenator(buf));
    } else {
      tc = new JsPrettyPrinter(new Concatenator(buf));
    }
    RenderContext rc = new RenderContext(tc);
    n.render(rc);
    tc.noMoreTokens();
    return buf.toString();
  }
}


text:
using Newtonsoft.Json;

namespace PedroLamas.GDrive.Service
{
    public class GoogleDriveMaxUploadSize
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("size")]
        public long? Size { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  MAEFragment.h
//  MantleArrayExtension
//
//  Created by Hinagiku Soranoba on 2017/01/29.
//  Copyright © 2017年 Hinagiku Soranoba. All rights reserved.
//

#import "MAESeparatedString.h"
#import <Foundation/Foundation.h>

/**
 * Type of string
 */
typedef NS_ENUM(NSUInteger, MAEFragmentType) {
    /// Allow both 'sigle-quoted-string', "double-quoted-string" and enumulate-string
    MAEFragmentMaybeQuotedString = 0,
    /// Must be "double-quoted-string"
    MAEFragmentDoubleQuotedString,
    /// Must be 'single-quoted-string'
    MAEFragmentSingleQuotedString,
    /// Must be enumerate-string
    MAEFragmentEnumerateString,
};

@protocol MAEFragment;
@class MAEFragment;

/**
 * A double-quoted-string fragment
 *
 * usage:
 *    -  MAEQuoted(@"propertyName")
 */
MAEFragment* _Nonnull MAEQuoted(NSString* _Nonnull);

/**
 * A single-quoted-string fragment
 *
 * usage:
 *    -  MAESignleQuoted(@"propertyName")
 */
MAEFragment* _Nonnull MAESingleQuoted(NSString* _Nonnull);

/**
 * A maybe enumerate-string fragment
 * Enumerate-string means string that MUST NOT be enclosed with quoted.
 *
 * usage:
 *    - MAEEnum(@"propertyName")
 */
MAEFragment* _Nonnull MAEEnum(NSString* _Nonnull);

/**
 * An optional fragment
 *
 * usage:
 *    - MAEOptional(@"propertyName")
 *    - MAEOptional(MAEQuoted(@"proeprtyName"))
 */
id<MAEFragment> _Nonnull MAEOptional(id _Nonnull);

/**
 * A fragment that means to group from this position as one array.
 *
 * usage:
 *    - MAEVariadic(@"propertyName")
 *    - MAEVariadic(MAEQuoted(@"propertyName"))
 *    - MAEVariadic(MAEEnum(@"propertyName"))
 */
id<MAEFragment> _Nonnull MAEVariadic(id _Nonnull);

@protocol MAEFragment <NSObject, NSCopying>

// It returns that name, if it have corresponding property
@property (nonatomic, nullable, copy, readonly) NSString* propertyName;
// If it is optional element, it returns YES. Otherwise, it returns NO.
@property (nonatomic, assign, readonly, getter=isOptional) BOOL optional;
// If it is variadic elements, it returns YES. Otherwise, it returns NO.
@property (nonatomic, assign, readonly, getter=isVariadic) BOOL variadic;

/**
 * Returns whether separatedString is in correct format.
 * It will call when a string convert to model.
 *
 * @param separatedString  A corresponding string
 * @param error            If it return nil, an error information is saved here.
 * @return Returns YES, if the separatedString is correct. Otherwise, it returns NO.
 */
- (BOOL)validateWithSeparatedString:(MAESeparatedString* _Nonnull)separatedString
                              error:(NSError* _Nullable* _Nullable)error;

/**
 * Returns a string corresponding the fragment.
 * It will call when a model convert to string.
 *
 * @param transformedValue  A string after transformer is executed.
 * @param error             If it return nil, an error information is saved here.
 * @return Returns a string corresponding the fragment.
 */
- (MAESeparatedString* _Nullable)separatedStringFromTransformedValue:(NSString* _Nullable)transformedValue
                                                               error:(NSError* _Nullable* _Nullable)error;

@optional

/**
 * You should implements, if you want to be supported by `MAEOptional`.
 *
 * @param optional  The value of optional to be set.
 */
- (void)setOptional:(BOOL)optional;

/**
 * You should implements, if you want to be supported by `MAEVariadic`.
 *
 * @param variadic  The value of variadic to be set.
 */
- (void)setVariadic:(BOOL)variadic;

@end

/**
 * A Class is the simplest MAEFragment
 * It use to define a value corresponding to one property.
 */
@interface MAEFragment : NSObject <MAEFragment>

/// Type of string
@property (nonatomic, assign, readonly) MAEFragmentType type;

#pragma mark - Lifecycle

/**
 * Create an instance
 *
 * @param propertyName   A property name
 * @return An instance
 */
- (instancetype _Nonnull)initWithPropertyName:(NSString* _Nonnull)propertyName;

@end


text:
if (( ! $+commands[poetry] )); then
  return
fi

# If the completion file doesn't exist yet, we need to autoload it and
# bind it to `poetry`. Otherwise, compinit will have already done that.
if [[ ! -f "$ZSH_CACHE_DIR/completions/_poetry" ]]; then
  typeset -g -A _comps
  autoload -Uz _poetry
  _comps[poetry]=_poetry
fi

poetry completions zsh >| "$ZSH_CACHE_DIR/completions/_poetry" &|


text:
package realmadmin_test

import (
	"net/http"
	"strings"
	"testing"

	"github.com/google/exposure-notifications-verification-server/internal/envstest"
	"github.com/google/exposure-notifications-verification-server/internal/project"
	"github.com/google/exposure-notifications-verification-server/pkg/controller"
	"github.com/google/exposure-notifications-verification-server/pkg/controller/realmadmin"
	"github.com/google/exposure-notifications-verification-server/pkg/database"
	"github.com/google/exposure-notifications-verification-server/pkg/rbac"
	"github.com/gorilla/sessions"
)

func TestHandleEnableExpress(t *testing.T) {
	t.Parallel()

	ctx := project.TestContext(t)
	harness := envstest.NewServerConfig(t, testDatabaseInstance)

	c := realmadmin.New(harness.Config, harness.Database, harness.RateLimiter, harness.Renderer, harness.Cacher)
	handler := harness.WithCommonMiddlewares(c.HandleEnableExpress())

	t.Run("middleware", func(t *testing.T) {
		t.Parallel()

		envstest.ExerciseSessionMissing(t, handler)
		envstest.ExerciseMembershipMissing(t, handler)
		envstest.ExercisePermissionMissing(t, handler)
	})

	t.Run("internal_error", func(t *testing.T) {
		t.Parallel()

		c := realmadmin.New(harness.Config, harness.BadDatabase, harness.RateLimiter, harness.Renderer, harness.Cacher)
		handler := c.HandleEnableExpress()

		ctx := ctx
		ctx = controller.WithSession(ctx, &sessions.Session{})
		ctx = controller.WithMembership(ctx, &database.Membership{
			Realm: &database.Realm{
				EnableENExpress: false,
			},
			User:        &database.User{},
			Permissions: rbac.SettingsWrite,
		})

		w, r := envstest.BuildFormRequest(ctx, t, http.MethodPut, "/", nil)
		handler.ServeHTTP(w, r)

		if got, want := w.Code, http.StatusInternalServerError; got != want {
			t.Errorf("Expected %d to be %d: %s", got, want, w.Body.String())
		}
	})

	t.Run("already_enabled", func(t *testing.T) {
		t.Parallel()

		realm := database.NewRealmWithDefaults("already_enabled")
		realm.EnableENExpress = true

		ctx := ctx
		ctx = controller.WithSession(ctx, &sessions.Session{})
		ctx = controller.WithMembership(ctx, &database.Membership{
			Realm:       realm,
			User:        &database.User{},
			Permissions: rbac.SettingsWrite,
		})

		w, r := envstest.BuildFormRequest(ctx, t, http.MethodPut, "/", nil)
		handler.ServeHTTP(w, r)

		if got, want := w.Code, http.StatusUnprocessableEntity; got != want {
			t.Errorf("Expected %d to be %d", got, want)
		}
		if got, want := w.Body.String(), "already enrolled in EN Express"; !strings.Contains(got, want) {
			t.Errorf("Expected %q to contain %q", got, want)
		}
	})

	t.Run("validation", func(t *testing.T) {
		t.Parallel()

		ctx := ctx
		ctx = controller.WithSession(ctx, &sessions.Session{})
		ctx = controller.WithMembership(ctx, &database.Membership{
			Realm: &database.Realm{
				EnableENExpress:     false,
				ShortCodeMaxMinutes: 60,
			},
			User:        &database.User{},
			Permissions: rbac.SettingsWrite,
		})

		w, r := envstest.BuildFormRequest(ctx, t, http.MethodPut, "/", nil)
		handler.ServeHTTP(w, r)

		if got, want := w.Code, http.StatusUnprocessableEntity; got != want {
			t.Errorf("Expected %d to be %d", got, want)
		}
		if got, want := w.Body.String(), "cannot be blank"; !strings.Contains(got, want) {
			t.Errorf("Expected %q to contain %q", got, want)
		}
	})

	t.Run("success", func(t *testing.T) {
		t.Parallel()

		realm := database.NewRealmWithDefaults("realmy2")
		realm.RegionCode = "TT"
		if err := harness.Database.SaveRealm(realm, database.SystemTest); err != nil {
			t.Errorf("%#v", realm.ErrorMessages())
			t.Fatal(err)
		}

		ctx := ctx
		ctx = controller.WithSession(ctx, &sessions.Session{})
		ctx = controller.WithMembership(ctx, &database.Membership{
			Realm:       realm,
			User:        &database.User{},
			Permissions: rbac.SettingsWrite,
		})

		w, r := envstest.BuildFormRequest(ctx, t, http.MethodPut, "/", nil)
		handler.ServeHTTP(w, r)

		if got, want := w.Code, http.StatusSeeOther; got != want {
			t.Errorf("Expected %d to be %d: %s", got, want, w.Body.String())
		}
		if got, want := w.Header().Get("Location"), "/realm/settings"; got != want {
			t.Errorf("expected %s to be %s", got, want)
		}

		realm, err := harness.Database.FindRealm(realm.ID)
		if err != nil {
			t.Fatal(err)
		}
		if got, want := realm.EnableENExpress, true; got != want {
			t.Errorf("expected %t to be %t", got, want)
		}
	})
}


text:
<?php

/**
* PHP class for dynamically resizing, cropping, and rotating images for thumbnail purposes and either displaying them on-the-fly or saving them.
* with ImageMagick
*/

class ngg_Thumbnail {
/**
* Error message to display, if any
* @var string
*/
var $errmsg;
/**
* Whether or not there is an error
* @var boolean
*/
var $error;
/**
* File name and path of the image file
* @var string
*/
var $fileName;
/**
* Image meta data if any is available (jpeg/tiff) via the exif library
* @var array
*/
var $imageMeta;
/**
* Current dimensions of working image
* @var array
*/
var $currentDimensions;
/**
* New dimensions of working image
* @var array
*/
var $newDimensions;
/**
* Percentage to resize image b
* @var int
* @access private
*/
var $percent;
/**
* Maximum width of image during resize
* @var int
* @access private
*/
var $maxWidth;
/**
* Maximum height of image during resize
* @var int
* @access private
*/
var $maxHeight;
/**
* Image for Watermark
* @var string
*/
var $watermarkImgPath;
/**
* Text for Watermark
* @var string
*/
var $watermarkText;
/**
* Path to ImageMagick convert
* @var string
*/
var $imageMagickDir;
/**
* String to execute ImageMagick convert.
* @var string
*/
var $imageMagickExec;
/**
* String to execute ImageMagick composite.
* @var string
*/
var $imageMagickComp;
/**
* String to execute ImageMagick (before the filename).
* @var string
*/
var $imageMagickBefore;

  /*
   * in: filename, error
   * out: nothing
   * init of class: init of variables, detect needed memory (gd), image format (gd), detect image size (GetImageSize is general PHP, not GD), Image Meta?
   */

	function ngg_Thumbnail($fileName, $no_ErrorImage = false) {

		//initialize variables
      	$this->errmsg				= '';
      	$this->error				= false;
      	$this->currentDimensions	= array();
      	$this->newDimensions		= array();
      	$this->fileName				= $fileName;
      	$this->imageMeta			= array();
      	$this->percent				= 100;
      	$this->maxWidth				= 0;
      	$this->maxHeight			= 0;
      	$this->watermarkImgPath		= '';
      	$this->watermarkText		= '';
		$this->imageMagickExec		= '';
      	$this->imageMagickComp		= '';
      	$this->imageMagickBefore	= '';

		//make sure ImageMagick is installed
		$this->checkVersion();

		//check to see if file exists
		if(!file_exists($this->fileName)) {
			$this->errmsg = 'File not found';
			$this->error = true;
		}
		//check to see if file is readable
		elseif(!is_readable($this->fileName)) {
			$this->errmsg = 'File is not readable';
			$this->error = true;
		}

		if($this->error == false) {
	    	$size = GetImageSize($this->fileName);
      		$this->currentDimensions = array('width'=>$size[0],'height'=>$size[1]);
	  	}

		if($this->error == true) {
			// for SinglePic send the error message out
	    	if(!$no_ErrorImage)
	    		echo $this->errmsg;
	    	return;
	    }
	}

	function checkVersion() {

		// very often exec()or passthru() is disabled. No chance for Imagick
		if ( ini_get('disable_functions') ) {
			$not_allowed = ini_get('disable_functions');
			if ( stristr($not_allowed, 'exec') || stristr($not_allowed, 'passthru') ) {
				$this->errmsg = 'exec() or passthru() is not allowed. Could not execute Imagick';
				$this->error = true;
				return false;
			}
		}

		// get the path to imageMagick
		$ngg_options = get_option('ngg_options');
		$this->imageMagickDir = trim( $ngg_options['imageMagickDir']);
		$this->imageMagickDir = str_replace( "\\", "/", $this->imageMagickDir );

		// Try to get the ImageMagick version
		$magickv = $this->execute('convert', '-version');

		if ( empty($magickv) ) {
			$this->errmsg = 'Could not execute ImageMagick. Check path ';
			$this->error = true;
			return false;
		}

		// We need as least version 6 or higher
		$helper = preg_match('/Version: ImageMagick ([0-9])/', $magickv[0], $magickversion);
		if ( !$magickversion[0] > '5' ) {
			$this->errmsg = 'Require ImageMagick Version 6 or higher';
			$this->error = true;
			return false;
		}

      	return true;
	}

	/**
     * Execute ImageMagick/GraphicsMagick commands
     *
     * @param string $cmd an ImageMagick command (eg. "convert")
     * @param string $args the arguments which should be passed
     * @param bool �passthru(optional) output the result to the webserver instead
     * @return void | if passthru return the image
     */
	function execute( $cmd, $args, $passthru = false) {

		// in error case we do not continue
		if($this->error == true)
			return;

		//if path is not empty
		if ($this->imageMagickDir != '') {
		// the path must have a slash at the end
			if ( $this->imageMagickDir{strlen($this->imageMagickDir)-1} != '/')
		    	$this->imageMagickDir .= '/';
		}

		//$args = escapeshellarg($args);
		//var_dump( escapeshellcmd ( "{$this->imageMagickDir}/{$cmd} {$args}" ) ); return;
		//$this->errmsg = escapeshellcmd( "{$this->imageMagickDir}{$cmd} {$args}" );

		if ( !$passthru ) {
			exec( "{$this->imageMagickDir}{$cmd} {$args}", $result );
			//var_dump( "{$this->imageMagickDir}/{$cmd} {$args}" );
			return $result;

		}
		//var_dump( escapeshellcmd ( "{$this->imageMagickDir}/{$cmd} {$args}" ) ); return;

		// for single pic we need the direct output
		header('Content-type: image/jpeg');
		$this->errmsg = "{$this->imageMagickDir}{$cmd} {$args}";
		passthru( "{$this->imageMagickDir}{$cmd} {$args}" );
	}

    /**
     * Must be called to free up allocated memory after all manipulations are done
     */
    function destruct() {
     	//not needed for ImageMagick
		return;
    }

    /**
     * Returns the current width of the image
     * @return int
     */
    function getCurrentWidth() {
        return $this->currentDimensions['width'];
    }

    /**
     * Returns the current height of the image
     * @return int
     */
    function getCurrentHeight() {
        return $this->currentDimensions['height'];
    }

    /**
     * Calculates new image width
     * @param int $width
     * @param int $height
     * @return array
     */
    function calcWidth($width, $height) {
        $newWp = (100 * $this->maxWidth) / $width;
        $newHeight = ($height * $newWp) / 100;
        return array('newWidth'=>intval($this->maxWidth), 'newHeight'=>intval($newHeight));
    }

    /**
     * Calculates new image height
     * @param int $width
     * @param int $height
     * @return array
     */
    function calcHeight($width, $height) {
        $newHp = (100 * $this->maxHeight) / $height;
        $newWidth = ($width * $newHp) / 100;
        return array('newWidth'=>intval($newWidth), 'newHeight'=>intval($this->maxHeight));
    }

    /**
     * Calculates new image size based on percentage
     * @param int $width
     * @param int $height
     * @return array
     */
    function calcPercent($width, $height) {
        $newWidth = ($width * $this->percent) / 100;
        $newHeight = ($height * $this->percent) / 100;
        return array('newWidth'=>intval($newWidth), 'newHeight'=>intval($newHeight));
    }

    /**
     * Calculates new image size based on width and height, while constraining to maxWidth and maxHeight
     * @param int $width
     * @param int $height
     */
    function calcImageSize($width,$height) {
        $newSize = array('newWidth'=>$width,'newHeight'=>$height);

        if($this->maxWidth > 0) {

            $newSize = $this->calcWidth($width,$height);

            if($this->maxHeight > 0 && $newSize['newHeight'] > $this->maxHeight) {
                $newSize = $this->calcHeight($newSize['newWidth'],$newSize['newHeight']);
            }

            //$this->newDimensions = $newSize;
        }

        if($this->maxHeight > 0) {
            $newSize = $this->calcHeight($width,$height);

            if($this->maxWidth > 0 && $newSize['newWidth'] > $this->maxWidth) {
                $newSize = $this->calcWidth($newSize['newWidth'],$newSize['newHeight']);
            }

            //$this->newDimensions = $newSize;
        }

        $this->newDimensions = $newSize;
    }

    /**
     * Calculates new image size based percentage
     * @param int $width
     * @param int $height
     */
    function calcImageSizePercent($width,$height) {
        if($this->percent > 0) {
            $this->newDimensions = $this->calcPercent($width,$height);
        }
    }

    /**
     * Resizes image to maxWidth x maxHeight
     *
     * @param int $maxWidth
     * @param int $maxHeight
     */

	function resize($maxWidth = 0, $maxHeight = 0, $resampleMode = 3) {
		$this->maxWidth = $maxWidth;
    	$this->maxHeight = $maxHeight;

    	$this->calcImageSize($this->currentDimensions['width'],$this->currentDimensions['height']);

		//string to resize the picture to $this->newDimensions['newWidth'],$this->newDimensions['newHeight']
		//should result in: -thumbnail $this->newDimensions['newWidth']x$this->newDimensions['newHeight']
		if($maxWidth=='0')
			$this->imageMagickExec .= " -resize x".$maxHeight;
		elseif($maxHeight=='0')
			$this->imageMagickExec .= " -resize ".$maxWidth."x";
		elseif($maxHeight!='0' && $maxWidth!='0')
			$this->imageMagickExec .= " -resize ".$maxWidth."x".$maxHeight;

		// next calculations should be done with the 'new' dimensions
		$this->currentDimensions['width'] = $this->newDimensions['newWidth'];
		$this->currentDimensions['height'] = $this->newDimensions['newHeight'];

	}

	/**
	 * Flip an image.
	 *
	 * @param bool $horz flip the image in horizontal mode
	 * @param bool $vert flip the image in vertical mode
	 */
	function flipImage( $horz = false, $vert = false ) {

		//TODO: need to be added

	}

	/**
     * Rotates image either 90 degrees clockwise or counter-clockwise
     *
     * @param string $direction
     */
	function rotateImage($dir = 'CW') {

		$angle = ($dir == 'CW') ? 90 : -90;

  		$this->imageMagickExec .= " -rotate $angle ";

		$newWidth = $this->currentDimensions['height'];
	   	$newHeight = $this->currentDimensions['width'];
		$this->currentDimensions['width'] = $newWidth;
		$this->currentDimensions['height'] = $newHeight;
	}

   /**
	 * Crops the image from calculated center in a square of $cropSize pixels
	 *
	 * @param int $cropSize
	 */
	function cropFromCenter($cropSize, $resampleMode = 3) {
	   if($cropSize > $this->currentDimensions['width']) $cropSize = $this->currentDimensions['width'];
	   if($cropSize > $this->currentDimensions['height']) $cropSize = $this->currentDimensions['height'];

	   //$cropX = intval(($this->currentDimensions['width'] - $cropSize) / 2);
	   //$cropY = intval(($this->currentDimensions['height'] - $cropSize) / 2);

		//string to crop the picture to $cropSize,$cropSize (from center)
		//result: -gravity Center -crop $cropSizex$cropSize+0+0
		$this->imageMagickExec .= ' -gravity Center -crop ' . $cropSize . 'x' . $cropSize . '+0+0';

		// next calculations should be done with the 'new' dimensions
		$this->currentDimensions['width'] = $cropSize;
		$this->currentDimensions['height'] = $cropSize;
	}

	/**
	 * Advanced cropping function that crops an image using $startX and $startY as the upper-left hand corner.
	 *
	 * @param int $startX
	 * @param int $startY
	 * @param int $width
	 * @param int $height
	 */
	function crop($startX,$startY,$width,$height) {
	    //make sure the cropped area is not greater than the size of the image
	   if($width > $this->currentDimensions['width']) $width = $this->currentDimensions['width'];
	   if($height > $this->currentDimensions['height']) $height = $this->currentDimensions['height'];
	    //make sure not starting outside the image
	   if(($startX + $width) > $this->currentDimensions['width']) $startX = ($this->currentDimensions['width'] - $width);
	   if(($startY + $height) > $this->currentDimensions['height']) $startY = ($this->currentDimensions['height'] - $height);
	   if($startX < 0) $startX = 0;
	   if($startY < 0) $startY = 0;

		//string to crop the picture to $width,$height (from $startX,$startY)
		//result: -crop $widthx$height+$startX+$startY
		$this->imageMagickExec .= ' -crop ' . $width . 'x' . $height . '+' . $startX .'+' . $startY;

		$this->currentDimensions['width'] = $width;
		$this->currentDimensions['height'] = $height;
	}

	/**
	 * Creates Apple-style reflection under image, optionally adding a border to main image
	 *
	 * @param int $percent
	 * @param int $reflection
	 * @param int $white
	 * @param bool $border
	 * @param string $borderColor
	 */
	function createReflection($percent, $reflection, $white, $border = true, $borderColor = '#a4a4a4') {

	    $width = $this->currentDimensions['width'];
	    $height = $this->currentDimensions['height'];

	    $reflectionHeight = intval($height * ($reflection / 100));
	    $newHeight = $height + $reflectionHeight;
	        //$reflectedPart = $height * ((100-$percent) / 100);
	    $reflectedsize = intval($height * ((100 - (100 - $percent) + $reflection) / 100));

		$this->imageMagickBefore = "-size $width" . "x" ."$newHeight xc:white ";

		if($border == true) {
			$this->imageMagickBefore .= " \( ";
			$this->imageMagickExec = " -bordercolor '$borderColor' -border 1 \) ";
		}

		$this->imageMagickExec .= " -geometry +0+0 -composite ";
		$gradientWhite = 100-$white;
		$this->imageMagickExec .= " \( '$this->fileName' -flip -resize $width"."x"."$reflectedsize\! \( -size $width"."x"."$reflectionHeight gradient: -fill black -colorize $gradientWhite \) +matte -compose copy_opacity -composite \) -geometry +0+$height -composite ";

		$this->currentDimensions['width'] = $width;
		$this->currentDimensions['height'] = $newHeight;
	}

	/**
 	 * @param string $color
	 * @param string $wmFont
	 * @param int $wmSize
 	 * @param int $wmOpaque
     */
	function watermarkCreateText($color = '000000', $wmFont, $wmSize = 10, $wmOpaque = 90 ){
		//create a watermark.png image with the requested text.

		// set font path
		$wmFontPath = NGGALLERY_ABSPATH . 'fonts/' . $wmFont;
		if ( !is_readable($wmFontPath) )
			return;

		/*
		$exec = "convert -size 800x500 xc:grey30 -font $wmFontPath -pointsize $wmSize -gravity center -draw \"fill '#$color$wmOpaque'  text 0,0  '$this->watermarkText'\" stamp_fgnd.png";
		$make_magick = system($exec);
		$exec = "convert -size 800x500 xc:black -font $wmFontPath -pointsize $wmSize -gravity center -draw \"fill white  text  1,1  '$this->watermarkText'  text  0,0  '$this->watermarkText' fill black  text -1,-1 '$this->watermarkText'\" +matte stamp_mask.png";
		$make_magick = system($exec);
		$exec = "composite -compose CopyOpacity  stamp_mask.png  stamp_fgnd.png  watermark.png";*/

		//convert the opacity between FF or 00; 100->0 and 0->FF (256)
		$opacity = dechex( round( (100-$wmOpaque) * 256/100 ) );
		if ($opacity == "0") {$opacity = "00";}

		$cmd = "-size 800x500 xc:none -fill '#{$color}{$opacity}' -font {$wmFontPath} -pointsize {$wmSize} -gravity center -annotate 0 '{$this->watermarkText}' watermark_text.png";
		$this->execute('convert', $cmd);

		$cmd = "-trim +repage watermark_text.png";
		$this->execute('mogrify', $cmd);

		$this->watermarkImgPath = NGGALLERY_ABSPATH . 'watermark_text.png';

		return;
	}

    /**
     *
 	 * @param string $relPOS
	 * @param int $xPOS
 	 * @param int $yPOS
     */
    function watermarkImage( $relPOS = 'botRight', $xPOS = 0, $yPOS = 0) {

		// if it's not a valid file die...
		/*if ( !is_readable($this->watermarkImgPath))
		{
			echo $this->watermarkImgPath;
			return;
		}	*/

		$size = GetImageSize($this->watermarkImgPath);
    	$watermarkDimensions = array('width'=>$size[0],'height'=>$size[1]);

		$sourcefile_width=$this->currentDimensions['width'];
		$sourcefile_height=$this->currentDimensions['height'];

		$watermarkfile_width=$watermarkDimensions['width'];
		$watermarkfile_height=$watermarkDimensions['height'];

		switch( substr($relPOS, 0, 3) ){
			case 'top': $dest_y = 0 + $yPOS; break;
			case 'mid': $dest_y = ($sourcefile_height / 2) - ($watermarkfile_height / 2); break;
			case 'bot': $dest_y = $sourcefile_height - $watermarkfile_height - $yPOS; break;
			default   : $dest_y = 0; break;
		}
		switch( substr($relPOS, 3) ){
			case 'Left'	:	$dest_x = 0 + $xPOS; break;
			case 'Center':	$dest_x = ($sourcefile_width / 2) - ($watermarkfile_width / 2); break;
			case 'Right':	$dest_x = $sourcefile_width - $watermarkfile_width - $xPOS; break;
			default : 		$dest_x = 0; break;
		}
		if ($dest_y<0) {
			$dest_y = $dest_y;
		} else {
			$dest_y = '+' . $dest_y;
		}
		if ($dest_x<0) {
			$dest_x = $dest_x;
		} else {
			$dest_x = '+' . $dest_x;
		}

		$this->imageMagickComp .=  "'$this->watermarkImgPath' -geometry $dest_x$dest_y  -composite";
		//" -dissolve 80% -geometry +$dest_x+$dest_y $this->watermarkImgPath";
	}

	/**
	 * Saves image as $name (can include file path), with quality of # percent if file is a jpeg
	 *
	 * @param string $name
	 * @param int $quality
	 * @return bool errorstate
	 */
	function save( $name, $quality = 85 ) {
	    $this->show($quality,$name);
	    if ($this->error == true) {
	    	//$this->errmsg = 'Create Image failed. Check safe mode settings';
	    	return false;
	    }

        if( function_exists('do_action') )
	       do_action('ngg_ajax_image_save', $name);

	    return true;
	}

	/**
	 * Outputs the image to the screen, or saves to $name if supplied.  Quality of JPEG images can be controlled with the $quality variable
	 *
	 * @param int $quality
	 * @param string $name
	 */
	function show( $quality = 85, $name = '') {
		//save the image if we get a filename
		if( $name != '' ) {
			$args = "{$this->imageMagickBefore} ";
			$args .= escapeshellarg("$this->fileName");
			$args .= " $this->imageMagickExec $this->imageMagickComp -quality '$quality' ";
			$args .= escapeshellarg("$name");
			//$args = "{$this->imageMagickBefore} '$this->fileName' $this->imageMagickExec $this->imageMagickComp -quality $quality '$name'";
			$this->execute('convert', $args);
			//$this->error = true;
	  } else {
	  	//return a raw image stream
			$args = "{$this->imageMagickBefore} '$this->fileName' $this->imageMagickExec $this->imageMagickComp -quality $quality JPG:-";
			$this->execute('convert', $args, true);
			$this->error = true;
		}
	}
}


text:
class AddPlanDateFromCompanies < ActiveRecord::Migration
  def change
    add_column :companies, :payment_plan, :date
    add_column :companies, :appoint_plan, :date
    add_column :companies, :contract_plan, :date
    add_column :companies, :proposed_plan, :date
  end
end


text:
angular.module('ordercloud-lineitems', [])
    .factory('LineItemHelpers', LineItemFactory)
    .controller('LineItemModalCtrl', LineItemModalController)
;

function LineItemFactory($rootScope, $q, $state, $uibModal, Underscore, OrderCloudSDK, CurrentOrder, buyernetwork) {
    return {
        SpecConvert: _specConvert,
        RemoveItem: _removeItem,
        UpdateQuantity: _updateQuantity,
        GetProductInfo: _getProductInfo,
        GetBlankProductInfo: _getBlankProductInfo,
        CustomShipping: _customShipping,
        UpdateShipping: _updateShipping,
        ListAll: _listAll
    };

    function _specConvert(specs) {
        var results = [];
        angular.forEach(specs, function (spec) {
            var spec_to_push = {SpecID: spec.ID};
            if (spec.Options.length > 0) {
                if (spec.DefaultOptionID) {
                    spec_to_push.OptionID = spec.DefaultOptionID;
                }
                if (spec.OptionID) {
                    spec_to_push.OptionID = spec.OptionID;
                }
                if (spec.Value) {
                    spec_to_push.Value = spec.Value;
                }
            }
            else {
                spec_to_push.Value = spec.Value || spec.DefaultValue || null;
            }
            results.push(spec_to_push);
        });
        return results;
    }

    function _removeItem(Order, LineItem) {
        var direction = "Incoming";
        OrderCloudSDK.LineItems.Delete(direction, Order.ID, LineItem.ID)
            .then(function () {
                var filter = {
                    'Order.xp.BuyerID' : Order.xp.BuyerID
                };
                // If all line items are removed delete the order.
                OrderCloudSDK.LineItems.List(direction, Order.ID, {'filters' : filter})
                    .then(function (data) {
                        if (!data.Items.length) {
                            CurrentOrder.Remove();
                            OrderCloudSDK.Orders.Delete(direction, Order.ID, Order.xp.BuyerID)
                                .then(function () {
                                    $state.reload();
                                    $rootScope.$broadcast('OC:RemoveOrder');
                                });
                        }
                        else {
                            $state.reload();
                        }
                    });
            });
    }

    function _updateQuantity(Order, LineItem) {
        if (LineItem.Quantity > 0) {
            var direction = "Incoming";
            OrderCloudSDK.LineItems.Patch(direction, Order.ID, LineItem.ID, { Quantity: LineItem.Quantity })
                .then(function () {
                    $rootScope.$broadcast('OC:UpdateOrder', Order.ID);
                    $rootScope.$broadcast('OC:UpdateLineItem',Order);
                });
        }
    }

    function _getProductInfo(LineItems, Order, lang) {
        var li = LineItems.Items || LineItems;
        var productIDs = Underscore.uniq(Underscore.pluck(li, 'ProductID'));
        var dfd = $q.defer();
        var queue = [];
        angular.forEach(productIDs, function (productid) {
            if(productid != "PLACEHOLDER") {
                queue.push(OrderCloudSDK.Products.Get(productid));
            }
        });
        $q.all(queue)
            .then(function (results) {
                angular.forEach(li, function (item) {
                    if(item.ProductID != "PLACEHOLDER") {
                        item.Product = angular.copy(Underscore.where(results, {ID: item.ProductID})[0]);
                        item.xp.TagNumber = typeof item.xp.TagNumber === 'undefined' ? item.Product.xp.TagNumber: item.xp.TagNumber;
                        item.xp.ProductName = typeof item.xp.ProductName === 'undefined' ? item.Product.Name: item.xp.ProductName;
                        if (lang) {
                            if (typeof item.xp.Description === 'undefined' || !item.xp.Description) {
                                item.xp.Description = item.Product.xp[lang].Description ? item.Product.xp[lang].Description : item.Product.Description;
                            } else {
                                item.xp.Description = item.xp.Description ? item.xp.Description : item.Product.Description;
                            }
                        } else {
                            item.xp.Description = typeof item.xp.Description === 'undefined' ? item.Product.Description : item.xp.Description;
                        }
                        item.xp.ReplacementSchedule = typeof item.xp.ReplacementSchedule === 'undefined' ? item.Product.xp.ReplacementSchedule : item.xp.ReplacementSchedule;
                        item.xp.LeadTime = typeof item.xp.LeadTime === 'undefined' ?  item.Product.xp.LeadTime: item.xp.LeadTime;
                    }
                });
                dfd.resolve(li);
            })
            .catch(function (e) {
                console.log("Exception caught: " + JSON.stringify(e));
                dfd.reject();
            });
        return dfd.promise;
    }

    function _getBlankProductInfo(LineItems) {
    	var li = LineItems || LineItems.Items;

	    angular.forEach(li, function(item) {
	    	if(item.ProductID == "PLACEHOLDER") {
	    		item.Product = {
				    "Name": item.xp.ProductName,
				    "Description": item.xp.Description
			    };
                item.xp.ProductName = typeof item.xp.ProductName === 'undefined' ? item.Product.Name: item.xp.ProductName;
                item.xp.Description = typeof item.xp.Description === 'undefined' ? item.Product.Description : item.xp.Description;
                item.xp.ReplacementSchedule = typeof item.xp.ReplacementSchedule === 'undefined' ? item.Product.xp.ReplacementSchedule : item.xp.ReplacementSchedule;
                item.xp.LeadTime = typeof item.xp.LeadTime === 'undefined' ?  item.Product.xp.LeadTime: item.xp.LeadTime;
                item.xp.TagNumber = typeof item.xp.TagNumber === 'undefined' ? "" : item.xp.TagNumber;
                item.xp.SN = typeof item.xp.SN === 'undefined' ? "" : item.xp.SN;
            }
	    });

	    return li;
    }

    function _customShipping(Order, LineItem) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'common/lineitems/templates/shipping.tpl.html',
            controller: 'LineItemModalCtrl',
            controllerAs: 'liModal',
            size: 'lg'
        });

        modalInstance.result
            .then(function (address) {
                address.ID = Math.floor(Math.random() * 1000000).toString();
                var direction = "Incoming";
                OrderCloudSDK.LineItems.SetShippingAddress(direction, Order.ID, LineItem.ID, address)
                    .then(function () {
                        $rootScope.$broadcast('LineItemAddressUpdated', LineItem.ID, address);
                    });
            });
    }

    function _updateShipping(Order, LineItem, AddressID) {
        OrderCloudSDK.Addresses.Get(Order.xp.BuyerID, AddressID)
            .then(function (address) {
                var direction = "Incoming";
                OrderCloudSDK.LineItems.SetShippingAddress(direction, Order.ID, LineItem.ID, address);
                $rootScope.$broadcast('LineItemAddressUpdated', LineItem.ID, address);
            });
    }

    function _listAll(orderID, buyerID) {
        var li;
        var dfd = $q.defer();
        var queue = [];
        var filter = {
        'filters' : {'buyerID' : buyerID},
            'page': 1,
            'pageSize' : 100
        };
        var direction = "Incoming" ;
        OrderCloudSDK.LineItems.List(direction, orderID, filter)
            .then(function (data) {
                li = data;
                if (data.Meta.TotalPages > data.Meta.Page) {
                    var page = data.Meta.Page;
                    while (page < data.Meta.TotalPages) {
                        page += 1;
                        var filter = {
                            'page' : page,
                            'pageSize' : 100,
                            'filters' : { 'buyerID' : buyerID }
                        };
                        queue.push(OrderCloudSDK.LineItems.List(direction, orderID, filter));
                    }
                }
                $q.all(queue)
                    .then(function (results) {
                        angular.forEach(results, function (result) {
                            li.Items = [].concat(li.Items, result.Items);
                            li.Meta = result.Meta;
                        });
                        dfd.resolve(li.Items);
                    });
            });
        return dfd.promise;
    }
}

function LineItemModalController($uibModalInstance) {
    var vm = this;
    vm.address = {};

    vm.submit = function () {
        $uibModalInstance.close(vm.address);
    };

    vm.cancel = function () {
        vm.address = {};
        $uibModalInstance.dismiss('cancel');
    };
}


text:
akewa
=====

Akewa is an old (2004/05ish) IRC bot that collected URLs from a channel and store them into a database.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Essai Tax. Hyménomyc. (Lons-le-Saunier) 80 (1900)

#### Original name
Melanopus elegans f. elegans

### Remarks
null


text:
module.exports = function() {
  return {
    todayDate: function() {
      return new Date();
    },

    sendGreeting: function(user) {
      var today = this.todayDate();
      var birthday = user.birthdate();

      if(birthday.getMonth() === today.getMonth() &&
        birthday.getDate() === today.getDate()) {
        // Send greeting.
        console.log('Happy birthday!');
        return true;
      }

      return false;
    }
  }
};


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

    class ShowHidePassword {

        static $inject = ['$element'];

        /**
         * @type {ng.IAugmentedJQuery}
         */
        $element;

        /**
         * @type {ng.IAugmentedJQuery}
         */
        inputEl;

        /**
         * @type {boolean}
         */
        isActive = false;

        constructor($element) {
            this.$element = $element;
        }

        $postLink() {
            this.$element.addClass('show-hide-password');

            this.inputEl = this.$element.find('input');
        }

        toggle() {
            this.isActive = !this.isActive;

            this.inputEl.attr('type', this.isActive ? 'text' : 'password');
        }

    }

    angular.module('app.ui').component('wShowHidePassword', {
        templateUrl: 'modules/ui/directives/showHidePassword/showHidePassword.html',
        controller: ShowHidePassword,
        transclude: true
    });
})();


text:
package net.researchgate.restler.service.resources;

import io.dropwizard.testing.ResourceHelpers;
import io.dropwizard.testing.junit.DropwizardAppRule;
import net.researchgate.restler.RestlerApplication;
import net.researchgate.restler.domain.Publication;
import net.researchgate.restler.service.config.RestlerConfig;
import net.researchgate.restler.service.util.AbstractMongoDBTest;
import org.glassfish.jersey.client.JerseyClientBuilder;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

/**
 * Testing publication resource
 */
public class PublicationResourceTest extends AbstractMongoDBTest {

    @Rule
    public DropwizardAppRule<RestlerConfig> APP =
            new DropwizardAppRule<>(RestlerApplication.class, ResourceHelpers.resourceFilePath("config.yaml"));

    //TODO: make sure headers are propagated
    @Test
    @Ignore
    public void testBasic() {
        String clientName = "community";
        Client client = new JerseyClientBuilder().build();

        Publication p = new Publication();
        p.setPublicationUid(1L);
        p.setTitle("Test title");

        String url = String.format("http://localhost:%d%s/publications", APP.getLocalPort(),
                APP.getEnvironment().getApplicationContext().getContextPath());
        Response response = client.target(url)
                .request()
                .header("X-Client-Id", clientName)
                .post(Entity.entity(p, MediaType.APPLICATION_JSON_TYPE));

        Publication p2 = response.readEntity(Publication.class);
        assertNotEquals(p, p2);

        assertEquals(clientName, p2.getLastModificationClientId());
    }

    // calls an external service (that happens to be the same service) to get a publication
    @Test
    public void testExternalDao() {
        Client client = new JerseyClientBuilder().build();

        Publication p = new Publication();
        p.setPublicationUid(1L);
        p.setTitle("Test title");

        String url = String.format("http://localhost:%d%s/publications", APP.getLocalPort(),
                APP.getEnvironment().getApplicationContext().getContextPath());
        client.target(url)
                .request()
                .post(Entity.entity(p, MediaType.APPLICATION_JSON_TYPE));

        url = String.format("http://localhost:%d%s/publications/external/1", APP.getLocalPort(),
                APP.getEnvironment().getApplicationContext().getContextPath());

        Publication p2 = client.target(url).request().get(Publication.class);

        assertEquals(p, p2);
    }

}


text:
<?php
namespace Neobazaar\Service;

use Zend\ServiceManager\ServiceLocatorInterface,
	Zend\ServiceManager\FactoryInterface;

use Neobazaar\Options\ModuleOptions;

class NeobazaarMainServiceFactory
	implements FactoryInterface
{
    /**
     *
     * @param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator
     * @return \Options\ModuleOptions
     */
    public function createService(ServiceLocatorInterface $sl)
    {
        $service = new MainModuleService;
        $service->setEntityManager($sl->get('neobazaar.doctrine.em'));
        $service->setView($sl->get('Zend\View\Renderer\PhpRenderer'));
        $service->setServiceManager($sl);

        return $service;
    }
}