text:
<?php

class ttfImage {

	private $text;
	private $style;
	private $gzip;
	private $fontsettings;
	private $etag;

	/**
	* @param $style style to be used (must be defined in styles.ini)
	* @param $text string to be converted to an image
	* @param $gzip boolean to control if the response should be gzipped or not.
	*/
	public function __construct($text, $style, $displaytext, $gzip){
		isset($text) ? $this->text = $text : 0;
		isset($style) ? $this->style = $style : 0;
		isset($displaytext) ? $this->displaytext = $displaytext : 0;
		isset($gzip) ? $this->gzip = $gzip : 0;
		if($this->style == "admin"){
			$this->fontsettings = array();
			$this->fontsettings['font-name'] = $this->text;
			$this->text = $this->displaytext;
			if($this->displaytext == "charactermap"){
				$this->text = self::charMap();
				$this->fontsettings['max-width-text-align'] = "center";
			} else {
				$this->fontsettings['max-width-text-align'] = "left";
			}
			$this->fontsettings["max-width"] = 900;
			$this->fontsettings['color'] = "333333";
			$this->fontsettings['font-size'] = 27;
			$this->fontsettings['shadow'] = false;
			$this->fontsettings['shadow-color'] = "FFFFFF";
			$this->fontsettings["limit-width"] = true;
			$this->fontsettings["line-height"] = 50;
			$this->fontsettings['is_admin'] = true;
			$this->fontsettings['image-padding'] = true;
			$this->fontsettings['image-padding-bottom'] = 10;
			$this->fontsettings['image-padding-left'] = 10;
		} else if($this->style == "admin-small"){
			$this->fontsettings = array();
			$this->fontsettings['font-name'] = $this->text;
			$this->text = $this->displaytext;
			$this->fontsettings['color'] = "333333";
			$this->fontsettings['font-size'] = 20;
			$this->fontsettings['shadow'] = false;
			$this->fontsettings['shadow-color'] = "FFFFFF";
			$this->fontsettings['shadow-spread'] = 0;
			$this->fontsettings['is_admin'] = true;
		}else {
			$styles = maybe_unserialize(get_option('anyfont_styles'));
			if(isset($styles['image'][$this->style])){
				$this->fontsettings = $styles['image'][$this->style];
			} else {
				wp_redirect(get_option('siteurl'));
				exit(0);
			}
		}
		if(is_array($this->fontsettings)){
			$this->linecount = 1;

			!isset($this->fontsettings['shadow-distance']) ? $this->fontsettings['shadow-distance'] = 1 : 0;
			!isset($this->fontsettings['shadow-spread']) ? $this->fontsettings['shadow-spread'] = 1 : 0;
			!isset($this->fontsettings['image-padding']) ? $this->fontsettings['image-padding'] = 0 : 0;
			!isset($this->fontsettings['image-padding-top']) ? $this->fontsettings['image-padding-top'] = 0 : 0;
			!isset($this->fontsettings['image-padding-bottom']) ? $this->fontsettings['image-padding-bottom'] = 0 : 0;
			!isset($this->fontsettings['image-padding-left']) ? $this->fontsettings['image-padding-left'] = 0 : 0;
			!isset($this->fontsettings['image-padding-right']) ? $this->fontsettings['image-padding-right'] = 0 : 0;
			!isset($this->fontsettings['line-height']) ? $this->fontsettings['line-height'] = 0 : 0;
			!isset($this->fontsettings['max-width-text-align']) ? $this->fontsettings['max-width-text-align'] = !$this->fontsettings['text-align-center'] ? "left" : "center" : 0;
			$this->fonttype = !file_exists(ANYFONT_FONTDIR."/".$this->fontsettings['font-name'].".ttf") ? ".otf" : ".ttf";
			$pre_hash = "";
			foreach($this->fontsettings as $value){
				$pre_hash.=$value;
			}
			$hash = md5($pre_hash.$this->text."imagick");
			$this->etag = $hash;

			if(!isset($this->fontsettings['is_admin'])){
				$this->cache_file = ANYFONT_CACHE."/$hash-site.png";
			} else {
				$this->cache_file = ANYFONT_CACHE."/$hash-admin.png";
			}
			if(file_exists($this->cache_file)){
				if(isset($_SERVER["HTTP_IF_NONE_MATCH"]) || isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
					if($_SERVER["HTTP_IF_NONE_MATCH"] == $this->etag || $_SERVER['HTTP_IF_MODIFIED_SINCE'] == gmdate('D, d M Y H:i:s', filemtime($this->cache_file)).' GMT'){
						header("HTTP/1.0 304 Not Modified");
						exit(304);
					} else {
						self::text2Image();
					}
				} else {
					self::printImage();
				}
			} else {
				self::text2Image();
			}
		}
	}

	/** Description
	* Creates a png image from a text string using truetype fonts and writes the file to cache
	*/
	private function text2Image(){
		$image = new Imagick();
		$draw = new ImagickDraw();
		$draw->setTextEncoding("UTF-8");
		$draw->setFillColor(new ImagickPixel("#".$this->fontsettings['color']));
		if(file_exists(ANYFONT_FONTDIR."/".$this->fontsettings['font-name'].$this->fonttype)){
			$draw->setFont(ANYFONT_FONTDIR."/".$this->fontsettings['font-name'].$this->fonttype);
		}
		$draw->setFontSize($this->fontsettings['font-size']);
		if($this->fontsettings["limit-width"]){
			$str = explode(" ", $this->text);
			$count = count($str);
			$n = 0;
			$l = 0;
			$lines = array();
			$max_width = (int)$this->fontsettings["max-width"];
			$max = $max_width;
			while($n < $count){
				!isset($lines[$l]) ? $lines[$l] = "" : 0;
				$test_str = $lines[$l] !== "" ? $lines[$l]." ".$str[$n] : $str[$n];
				$metrics =  $image->queryFontMetrics($draw, $test_str);
				if ($metrics['textWidth'] < $max) {
					$lines[$l] != "" ? $lines[$l].=" ".$str[$n] : $lines[$l] = $str[$n];
					$n++;
				} else if($test_str !== $str[$n]){
					$max = $max_width;
					$l++;
				} else {
					$max+=10;
				}
			}
			$this->text = implode("\n", $lines);
		}
		$this->linecount = substr_count($this->text, "\n")+1;
		//get metrics for width
		$fm = $image->queryFontMetrics($draw, $this->text);
		//get metrics for first letter
		$fcm = $image->queryFontMetrics($draw, substr($this->text, 0, 1));
		$min_x = min(array($fcm["boundingBox"]["x2"],$fcm["boundingBox"]["x1"]));
		if($min_x < 0){
			$min_x = -($min_x);
		}
		//get metrics for font height and baseline
		$fym = $image->queryFontMetrics($draw, self::charMap());
		$min_y = min(array($fym["boundingBox"]["y2"],$fym["boundingBox"]["y1"]));
		$max_y = max(array($fym["boundingBox"]["y2"],$fym["boundingBox"]["y1"]));
		$padding_x = !$this->fontsettings['image-padding'] ? 0 : (int)$this->fontsettings['image-padding-left']+(int)$this->fontsettings['image-padding-right'];
		$padding_y = !$this->fontsettings['image-padding'] ? 0 : (int)$this->fontsettings['image-padding-top']+(int)$this->fontsettings['image-padding-bottom'];
		$shadowspread = !$this->fontsettings['shadow'] ? 0 : $this->fontsettings['shadow-spread'];
		$width = $fm["textWidth"]+$padding_x;
		$height = $max_y+(-($min_y))+$padding_y;
		if($this->fontsettings['shadow']){
			$height += ((int)$this->fontsettings['shadow-distance']+((int)$this->fontsettings['shadow-spread']*2.8));
	        $width += ((int)$this->fontsettings['shadow-distance']+((int)$this->fontsettings['shadow-spread']*2.8));
		}
		if($this->linecount > 1){
			$this->fontsettings["line-height"] > 0 ? $height = $this->fontsettings["line-height"] < $height ? $height-(($height-$this->fontsettings["line-height"])/2) : $this->fontsettings["line-height"] : 0;
			$height*=$this->linecount;
		}
		if($this->fontsettings["limit-width"] && $this->fontsettings['max-width-text-align'] == "center"){
			$width = $this->fontsettings['max-width'];
		}
		$x = $min_x+$shadowspread+(!$this->fontsettings['image-padding'] ? 0 : ((int)$this->fontsettings['image-padding-left']));
		$y = $max_y+$shadowspread+(!$this->fontsettings['image-padding'] ? 0 : ((int)$this->fontsettings['image-padding-top']));
		$image->newImage($width, $height, "transparent", "png");
		if($this->fontsettings['shadow']){
			if($this->linecount > 1 && $this->fontsettings["line-height"] > 0){

				$l = 0;
				$ly = $y;
				$lines = explode("\n", $this->text);
				while($l < $this->linecount){
					if($this->fontsettings["limit-width"] && $this->fontsettings['max-width-text-align'] == "center"){
						$m = $image->queryFontMetrics($draw, $lines[$l]);
						$x = (($width-$m['textWidth'])/2)+(!$this->fontsettings['image-padding'] ? 0 : ((int)$this->fontsettings['image-padding-left']));;
					}
					$l > 0 ? $ly += $this->fontsettings["line-height"] : 0;
					$image = $this->shadowImage($image, $x, $ly, $lines[$l]);
					$l++;
				}
			}else{
				if($this->fontsettings["limit-width"] && $this->fontsettings['max-width-text-align'] == "center"){
					$m = $image->queryFontMetrics($draw, $this->text);
					$x = (($width-$m['textWidth'])/2)+(!$this->fontsettings['image-padding'] ? 0 : ((int)$this->fontsettings['image-padding-left']));;
				}
				$image = $this->shadowImage($image, $x, $y, $this->text);
			}
			$this->fontsettings['shadow-spread'] > 0 ? $image->blurImage(0, (int)$this->fontsettings['shadow-spread'], Imagick::CHANNEL_ALL) : 0;
		}
		if($this->linecount > 1 && $this->fontsettings["line-height"] > 0){
			$l = 0;
			$lines = explode("\n", $this->text);
			while($l < $this->linecount){
				if($this->fontsettings["limit-width"] && $this->fontsettings['max-width-text-align'] == "center"){
					$m = $image->queryFontMetrics($draw, $lines[$l]);
					$x = (($width-$m['textWidth'])/2)+(!$this->fontsettings['image-padding'] ? 0 : ((int)$this->fontsettings['image-padding-left']));;
				}
				$l > 0 ? $y += $this->fontsettings["line-height"] : 0;
				$image->annotateImage($draw, $x, $y, 0, $lines[$l]);
				$l++;
			}
		}else{
			if($this->fontsettings["limit-width"] && $this->fontsettings['max-width-text-align'] == "center"){
				$m = $image->queryFontMetrics($draw, $this->text);
				$x = (($width-$m['textWidth'])/2)+(!$this->fontsettings['image-padding'] ? 0 : ((int)$this->fontsettings['image-padding-left']));;
			}
			$image->annotateImage($draw, $x, $y, 0, $this->text);
		}
		$image->writeImage($this->cache_file);
		self::printImage($image);
	}

	private function shadowImage($image, $x, $y, $text){
		$shadow = new ImagickDraw();
		$shadow->setFillColor(new ImagickPixel("#".$this->fontsettings['shadow-color']));
		$shadow->setFont(ANYFONT_FONTDIR."/".$this->fontsettings['font-name'].$this->fonttype);
		$shadow->setFontSize($this->fontsettings['font-size']);
		$image->annotateImage($shadow, $x+$this->fontsettings['shadow-distance'], $y+$this->fontsettings['shadow-distance'], 0, $text);
		return $image;
	}

	/** Description
	* Fetches the image from cache and delivers it to the browser along with the required headers.
	* @prints PNG image
	*/
	private function printImage($img=false){
		!$img ?  $img = file_get_contents($this->cache_file) : 0;
		$encoding = false;
		if($this->gzip && !ini_get('zlib.output_compression') && 'ob_gzhandler' != ini_get('output_handler') && isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
			header('Vary: Accept-Encoding'); // Handle proxies
			if ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'deflate') && function_exists('gzdeflate') && $this->gzip) {
				$encoding = 'deflate';
				$img = gzdeflate( $img, 3 );
			} elseif ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'gzip') && function_exists('gzencode') && $this->gzip) {
				$encoding = 'gzip';
				$img = gzencode( $img, 3 );
			}
		}
		ob_clean();
		header('X-Generated-By: AnyFont v'.ANYFONT_VERSION.' for WordPress');
		header('Last-modified: '.gmdate('D, d M Y H:i:s', filemtime($this->cache_file)).' GMT');
		header('Expires: '.gmdate("D, d M Y H:i:s", mktime(0, 0, 0, date("m")  , date("d")-1, date("Y") )).' GMT');   //FORMAT: Wed, 11 Jan 1984 05:00:00 GMT
		header('Etag: "'.$this->etag.'"');
		$encoding !== false ? header('Content-Encoding: '.$encoding) : 0;
		header('Content-type: image/png');
		header('Content-length: '.strlen($img));
		echo $img;
		ob_end_flush();
		die;
	}

	private function hexToRgb($hex){
		substr($hex,0,1) == '#' ? $hex = substr($hex,1) : 0;

		if(strlen($hex) == 3){
			$hex = substr($hex,0,1) . substr($hex,0,1).
			substr($hex,1,1) . substr($hex,1,1).
			substr($hex,2,1) . substr($hex,2,1);
		}

		strlen($hex) != 6 ? $error = 'Error: Invalid color "'.$hex.'"' : 0 ;

		$rgb[] = hexdec(substr($hex,0,2));
		$rgb[] = hexdec(substr($hex,2,2));
		$rgb[] = hexdec(substr($hex,4,2));

		return $rgb;
	}

	private function charMap(){
		$i = 65;
		$txt = self::getChars(65, 90)."\n";
		$txt .= self::getChars(97, 122)."\n";
		$txt .= self::getChars(48, 57)."\n";
		$txt .= self::getChars(33, 47).self::getChars(58, 64).self::getChars(91, 96).self::getChars(123, 126)."\n";
		$txt .= self::getChars(192, 223)."\n";
		$txt .= self::getChars(224, 255);
		return html_entity_decode(urldecode($txt), ENT_QUOTES);
	}

	private function getChars($start, $end){
		$txt = "";
		while($start <= $end){
			$txt .= "&#$start; ";
			$start++;
		}
		return $txt;
	}
}

?>


text:
ts-jest

A Jest transformer with source map support that lets you use Jest to test projects written in TypeScript.

It supports all features of TypeScript including type-checking. [Read more about Babel7 + `preset-typescript` **vs** TypeScript (and `ts-jest`)](https://kulshekhar.github.io/ts-jest/docs/babel7-or-ts).

---

| We are not doing semantic versioning and `23.10` is a re-write, run `npm i -D ts-jest@"<23.10.0"` to go back to the previous version |
| ------------------------------------------------------------------------------------------------------------------------------------ |

[ View the online documentation (usage & technical)](https://kulshekhar.github.io/ts-jest)

[ Ask for some help in the `Jest` Discord community](https://discord.gg/j6FKKQQrW9) or [`ts-jest` GitHub Discussion](https://github.com/kulshekhar/ts-jest/discussions)

[ Before reporting any issues, be sure to check the troubleshooting page](TROUBLESHOOTING.md)

[ We're looking for collaborators! Want to help improve `ts-jest`?](https://github.com/kulshekhar/ts-jest/issues/223)

---

## Getting Started

These instructions will get you setup to use `ts-jest` in your project. For more detailed documentation, please check [online documentation](https://kulshekhar.github.io/ts-jest).

|                     | using npm                      | using yarn                           |
| ------------------: | ------------------------------ | ------------------------------------ |
|   **Prerequisites** | `npm i -D jest typescript`     | `yarn add --dev jest typescript`     |
|      **Installing** | `npm i -D ts-jest @types/jest` | `yarn add --dev ts-jest @types/jest` |
| **Creating config** | `npx ts-jest config:init`      | `yarn ts-jest config:init`           |
|   **Running tests** | `npm t` or `npx jest`          | `yarn test` or `yarn jest`           |

## Built With

- [TypeScript](https://www.typescriptlang.org/) - JavaScript that scales
- [Jest](https://jestjs.io/) - Delightful JavaScript Testing
- [`ts-jest`](https://kulshekhar.github.io/ts-jest) - Jest [transformer](https://jestjs.io/docs/next/code-transformation#writing-custom-transformers) for TypeScript _(yes, `ts-jest` uses itself for its tests)_

## Contributing

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.

## Versioning

We **DO NOT** use [SemVer](https://semver.org/) for versioning. Though you can think about SemVer when reading our version, except our major number follows the one of Jest. For the versions available, see the [tags on this repository](https://github.com/kulshekhar/ts-jest/tags).

## Authors/maintainers

- **Kulshekhar Kabra** - [kulshekhar](https://github.com/kulshekhar)
- **Gustav Wengel** - [GeeWee](https://github.com/GeeWee)
- **Ahn** - [ahnpnl](https://github.com/ahnpnl)
- **Huafu Gandon** - [huafu](https://github.com/huafu)

See also the list of [contributors](https://github.com/kulshekhar/ts-jest/contributors) who participated in this project.

## Supporters

- [JetBrains](https://www.jetbrains.com/?from=ts-jest) has been kind enough to support ts-jest with an [open source license](https://www.jetbrains.com/community/opensource/?from=ts-jest).

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

redpajama_set_name: RedPajamaGithub


text:
namespace rep_solv {

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

struct Options
{
    // The maximal age of a contig.
    unsigned maxAge { 3 };
    // Largest number of allowed conflicts for mate links.
    int maxMateConflicts { 3 };

    // Maximal error rate for contig overlapping.
    double maxContigOverlapErrorRate { 0.03 };
    // Minimal contig overlap length.
    int contigOverlapMinLen { 20 };
    // Verbosity of output.
    int verbosity { 1 };
};

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

}  // namespace rep_solv

#endif  // #ifndef SANDBOX_HERBARIUM_APPS_ANISE_REP_SOLV_OPTIONS_H_


text:
package kr.ac.kaist.se.tardis.scheduler.api;

import java.util.Date;

public interface StandardNotificationBuilder {

	StandardNotificationBuilder forTask(String id);

	StandardNotificationBuilder forProject(String id);

	StandardNotificationBuilder threeDays(Date endDate);

	StandardNotificationBuilder sevenDays(Date endDate);

	StandardNotificationBuilder oneDay(Date endDate);

	JobInfo submit();
}


text:
public partial class Loop2000ACollection:LoopCollection<Loop2000A>
{
	public Loop2000ACollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2100ACollection:LoopCollection<Loop2100A>
{
	public Loop2100ACollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2000BCollection:LoopCollection<Loop2000B>
{
	public Loop2000BCollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2100BCollection:LoopCollection<Loop2100B>
{
	public Loop2100BCollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2000CCollection:LoopCollection<Loop2000C>
{
	public Loop2000CCollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2100CCollection:LoopCollection<Loop2100C>
{
	public Loop2100CCollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2000DCollection:LoopCollection<Loop2000D>
{
	public Loop2000DCollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2100DCollection:LoopCollection<Loop2100D>
{
	public Loop2100DCollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2200DCollection:LoopCollection<Loop2200D>
{
	public Loop2200DCollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2210DCollection:LoopCollection<Loop2210D>
{
	public Loop2210DCollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2000ECollection:LoopCollection<Loop2000E>
{
	public Loop2000ECollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2100ECollection:LoopCollection<Loop2100E>
{
	public Loop2100ECollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2200ECollection:LoopCollection<Loop2200E>
{
	public Loop2200ECollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}
public partial class Loop2210ECollection:LoopCollection<Loop2210E>
{
	public Loop2210ECollection(string loopName, string loopNameDescription, X12Doc owningDoc, LoopCollection parent, LoopCollection prev)
		:base(loopName, loopNameDescription, owningDoc, parent, prev) { }
}


text:
@interface TakePhotoViewController ()<AVCaptureVideoDataOutputSampleBufferDelegate,FilterListTableViewControllerDelegate>
@property (nonatomic,strong) GPUImageVideoCamera *cameraSession;
@property (nonatomic,strong) GPUImageCameraFilter *imageFilter;

@property (nonatomic,assign) BOOL photoDidTake;

@property (nonatomic,copy) void(^frameProcessingCompletionBlock)(GPUImageOutput*, CMTime);

@end

@implementation TakePhotoViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // init camera.
    self.cameraSession = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
    self.cameraSession.outputImageOrientation = UIInterfaceOrientationPortrait;

    if([self.view isKindOfClass:[GPUImageView class]]){
        NSLog(@"GPUImageView!!!");
    }else{
        return;
    }
    // add backview target view to show camera.
    GPUImageView *filterView = (GPUImageView *)self.view;
//    filterView.fillMode = kGPUImageFillModePreserveAspectRatioAndFill;

    __unsafe_unretained TakePhotoViewController *weakSelf = self;

    self.imageFilter = [[GPUImageCameraFilter alloc] init];
    self.imageFilter.videoCamera = self.cameraSession;
    self.imageFilter.cameraView = filterView;
    self.imageFilter.filterSettingsSlider = self.filterSlider;
    [self.imageFilter setCameraFilter:GPUIMAGE_SKETCH];

    self.frameProcessingCompletionBlock = ^(GPUImageOutput *outImage, CMTime time){
        if (weakSelf.photoDidTake) {
            UIImage *image = [outImage imageFromCurrentlyProcessedOutput];
            weakSelf.photoDidTake = NO;

            dispatch_async(dispatch_get_main_queue(), ^{
                // present edit photo VC.
                EditPhotoViewController *vc = [[EditPhotoViewController alloc] initWithNibName:@"EditPhotoViewController" bundle:nil];
                vc.photoImage = image;
                [weakSelf presentModalViewController:vc animated:YES];

            });
        }
    };
    [self.imageFilter.filter  setFrameProcessingCompletionBlock:self.frameProcessingCompletionBlock];

    // Notification.
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self.cameraSession selector:@selector(pauseCameraCapture) name:UIApplicationWillResignActiveNotification object:nil];
    [nc addObserver:self.cameraSession selector:@selector(resumeCameraCapture) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.cameraSession startCameraCapture];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.cameraSession stopCameraCapture];
}
- (IBAction)takePhoteDidTap:(id)sender {
//    self.photoDidTake = YES;

    CC3DemoMashUpAppDelegate *appDelegate =(CC3DemoMashUpAppDelegate*)[[UIApplication sharedApplication] delegate];

    CCGLView *v = appDelegate.cocos3dViewController.ccGLView;

    NSLog(@"GPUImageView Buffer %d",((GPUImageView *)self.view).displayFramebuffer);
    NSLog(@"cocos3d Buffer %d",[[v renderer] colorRenderBuffer]);

//    [self.cameraSession stopCameraCapture];
//    [appDelegate.cocos3dViewController pauseAnimation];

    UIImage *screenShot = [appDelegate snapshot:self.view renderBuffer:((GPUImageView *)self.view).displayFramebuffer];
    __unsafe_unretained TakePhotoViewController *weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        // present edit photo VC.
        EditPhotoViewController *vc = [[EditPhotoViewController alloc] initWithNibName:@"EditPhotoViewController" bundle:nil];
        NSLog(@"screenShot image %@",screenShot);

        vc.photoImage = screenShot;
        [appDelegate.cocos3dViewController presentModalViewController:vc animated:YES];

    });

}

- (IBAction)silderValueChange:(id)sender {
    [self.imageFilter adjustFilterValue];
}
- (IBAction)filterDidTap:(id)sender {
    FilterListTableViewController *vc = [[FilterListTableViewController alloc] initWithNibName:@"FilterListTableViewController" bundle:nil];
    vc.delegate = self;
    if (self.navigationController) {
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self presentModalViewController:vc animated:YES];
    }
}

#pragma mark - FilterListTableViewController Delegate Callback
- (void)filterTypeDidSelected:(GPUImageShowcaseFilterType)type
{
    [self.imageFilter setCameraFilter:type];
    [self.imageFilter.filter  setFrameProcessingCompletionBlock:self.frameProcessingCompletionBlock];
    [self.cameraSession startCameraCapture];
}
#pragma mark -

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setFilterSlider:nil];
    [self setFilterButton:nil];
    [self setTakePhotoButton:nil];
    [super viewDidUnload];
}
- (void)dealloc {

}
@end


text:
<link rel="stylesheet" type="text/css" href="../../lib/css/themes/jquery-ui/redmond/jquery-ui.min.css"/>
<link rel="stylesheet" type="text/css" href="../../lib/css/jqGrid/ui.jqgrid-4.5.4.css"/>

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

esp8266 adapter settings

IP:	                    <input  class="value" id="ip"/></select>
            esp8266 Name:	            <input  class="value" id="name"/>

ioBroker Web Port:	     <input  class="value" id="port"         maxlength="5"/>
            Poll interval (sec):	   <input  class="value" id="pollInterval" maxlength="3"/>

esp8266 Password:	        <input  class="value" id="password"     maxlength="3"/>
            Long press detect (ms):	<input  class="value" id="longPress"    maxlength="4"/>


text:
+++
author = "Dimitris Zorbas"
date = "2017-08-20"
draft = false
title = "Elixir.LDN 2017"
image = "images/posts/elixirldn2017/logo.png"
tags = ["open-source", "conference", "erlang", "elixir", "london"]
comments = true
share = true
+++

I returned from vacations in beautiful Greece ([Amorgos][amorgos] island 🏝), to
attend [Elixir.LDN-2017][Elixir.LDN-2017] in London.

## General Feeling

The [venue][conf-venue] was at a very convenient location and was well suited for the conference.
I could see many familiar faces and felt like a supercharged edition of the London Elixir meetup.

If you're interested in attending the Elixir London meetups you probably
want to join #london of the [elixir-lang slack][elixir-lang-slack] (get an [invite][elixir-lang-invite]) and
the [meetup.com group][elixir-london-meetup].

## The Talks

### Keynote - [José Valim][Profile-Jose-Valim] - Elixir 1.5 Update and Q&A

[Video][Video-keynote]

The talk was mostly about Elixir 1.5 features and demystifying the way Elixir files are loaded,
parsed and compiled to BEAM files.

There was a lot of focus on the importance of the introduction of the [Dbgi Chunk][beam_lib-debug_info] in OTP 20 (see
[this PR][otp-pr-1367] and [mailing list discussion][dbgi-mailing-list]).

An example of how it is used can be seen in the code below (found in elixir@1.5.1 [lib/iex/lib/iex/pry.ex][pry.ex-github]):

```elixir
defp fetch_elixir_debug_info_with_fa_check(module, fa) do
  case :code.which(module) do
    beam when is_list(beam) ->
      case :beam_lib.chunks(beam, [:debug_info]) do
        {:ok, {_, [debug_info: {:debug_info_v1, backend, {:elixir_v1, map, _} = elixir}]}} ->
          case List.keyfind(map.definitions, fa, 0) do
            {_, _, _, _} -> {:ok, beam, backend, elixir}
            nil -> {:error, :unknown_function_arity}
          end
        {:ok, {_, [debug_info: {:debug_info_v1, _, _}]}} ->
          {:error, :non_elixir_module}
        {:error, :beam_lib, {:unknown_chunk, _, _}} ->
          {:error, :otp_20_is_required} # TODO: Remove this when we require OTP 20+
        {:error, :beam_lib, {:missing_chunk, _, _}} ->
          {:error, :missing_debug_info}
        _ ->
          {:error, :outdated_debug_info}
      end
    _ ->
      {:error, :no_beam_file}
  end
end
```

This feature enables quicker debugging (see: [stackoverflow-question][so-question] and
related [PR][elixir-plug-pr]) for `IEx`, `Plug`, `ExUnit` and opens a wide spectrum of possibilities, even adding a
full type system in Elixir as José hinted during the Q&A session.

#### Exception.blame

José also talked about the new [Exception.blame/3][Exception.blame/3] function which is capable of
attaching debug information to certain exceptions.

Currently this is used to augment `FunctionClauseErrors` with a summary of all clauses and which parts of clause match and which ones didn't.

The feature is showcased best by the video below:

#### ElixirScript@0.30.0
José mentioned the release of ElixirScript version 0.30.0 which now
supports compiling Elixir code to JavaScript on the fly. Read the
release notes [here][elixirscript-release-notes].

### [Evadne Wu][Profile-Evadne-Wu] - How to Sell Elixir

[Slides][Slides-Evadne-Wu]
[Video][Video-wu]

The talk was about suggesting the use of Elixir for a system of Faria Education Group where Evadne works
, what it took to convince the management and their story developing it.

Some of the quotes I noted from this talk are:

* When choosing technologies, you're managing risk
* Good technology can't save you from bad specification
* JVM is a good ecosystem to get things done

### [Peter Saxton][Profile-Peter-Saxton] - Working with HTTP/2 in Elixir

[Slides][Slides-Peter-Saxton]
[Video][Video-saxton]

Peter has built an HTTP/2 only server entirely in Elixir. The server is
called [Ace][ace].

Some of the quotes I noted from this talk are:

* Handling binary protocols in Elixir is easy
* Prefer coding library apps where possible
* Don't use `config.exs` for your library apps

Deconstructing HTTP/2 frames from a binary stream:

```elixir
def parse_from_buffer(
  <<
    length::24,
    type::8,
    flags::bits-size(8),
    _R::1,
    stream_id::31,
    payload::binary-size(length),
    rest::binary
  >>, max_length: max_length)
  when length <= max_length
do
  {:ok, {{type, flags, stream_id, payload}, rest}}
end
```

### [Louis Pilfold][Profile-Louis-Pilfold] - Getting Pretty Serious

[Video][Video-lpil]

Louis "getting pretty serious"

Louis is the author of [exfmt][exfmt] and talked about the differences
between linters and formatters and the difficulties of implementing a
formatter.

He said that he based his algorithm on Philip Wadler's algorithm for
pretty printing (see: [paper][wadler-pp]) and [Inspect.Algebra][hexdocs-inspect-algebra], which is in turn based on
the ["Strictly Pretty" paper][strictly-pretty-linding] by Christian Linding.

There was also a GSoC project for the implementation of a code formatter
for Elixir (see: [here][gsoc-elixir]).

Quotes from the talk:

* Compilers are easy, people are hard
* Adhering to a consistent code style saves you money

I could see that Louis was using the `:Neoformat` command from inside (Neo)Vim to demonstrate exfmt and
luckily there are instructions for integration with Vim [here][exfmt-vim-instructions] 🙌.

### [Georgina McFadyen][Profile-Georgina-McFadyen] - Elixir Umbrella - Microservices or Majestic Monolith?

[Video][Video-mcfadyen]

This was an informative talk about creating, developing and releasing
[umbrella applications][umbrella-apps]. It seemed to me like a condensed version of the
["Microservices under the Umbrella"][microservices-umbrella-link] workshop which I attended at
Elixironf.EU 2017.

She said that you can choose to deploy you application with
[Distillery][distillery] building a release per sub-app, one release
including all sub-apps or you can group sub-apps and release separately.

An interesting question during the Q&A session was if you can nest
umbrella apps where Georgina responded that it's probably not possible
but she hasn't tried it.

In case you didn't know you can scaffold a new umbrella application using:

```shell
mix new some_project --umbrella
```

### [Nikolay Tsvetinov][Profile-Nikolay-Tsvetinov] - How We Created The University Course - Functional Programming With Elixir

Nikolay presented his story teaching Elixir in a functional programming
course at the university of Sofia.

[Slides][slides-meddle]
[Video][Video-tsvetinov]

### [Gary Rennie][Profile-Gary-Rennie] - HTTP/2 Plug to Phoenix, Cowboy too

[Video][Video-Rennie]

Plug is HTTP/1.1 only and developed mostly with the [Cowboy][cowboy] Erlang server
in mind.
Then next major version of Cowboy (2) is soon to be released,
but it has taken a few years. You can read the migration guide [here][cowboy-migration].

Gary did a demo of using Cowboy directly from Elixir and later
one of an HTTP/2 chat service with [Phoenix][phoenix] and [Chatterbox][chatterbox].

### [Péter Gömöri][Profile-Gomori] - Profiling and Tracing for all with Xprof

[Video][Video-gomori]

This talk was about the [Xprof][xprof] tool which is a single-function
profiler aimed for production safety, ideal for immediate visual
feedback and ad-hoc debugging.

It uses ["match_spec"][match_spec] flavored filtering to provide an expressive way to
filter function calls by their usage.

![xprof](/images/posts/elixirldn2017/xprof_resized.png)

#### Q&A Session

Q: Is it safe for production usage?

A: It is meant to be turned on for investigations, not to be constantly
on, just to be safe. It only keeps 1 minute worth of data.

### [Andrea Leopardi][Profile-leopardi] - Stepping into a New Era: Injecting Elixir in an Existing System

[Slides][Slides-leopardi]
[Video][Video-leopardi]

Quotes from the talk:

* Services are good, use the best tool for the job
* Using Elixir in [Football Addicts][football-addicts] was a huge success (perf went ☝, Resources / Server usage went 👇)

### [Brooklyn Zelenka][Profile-zelenka] - Witchcraft: Monads for the Working Alchemist

[Slides][Slides-zelenka]
[Video][Video-zelenka]

She talked about the [Blub Paradox][blub-paradox], coming from a more powerful language (Haskell),
she felt the need to make Elixir look more like it.

She authored the following libraries to achieve that:

* [quark](https://github.com/expede/quark)
* [algae](https://github.com/expede/algae)
* [type_class](https://github.com/expede/type_class)
* [witchcraft](https://github.com/expede/witchcraft)

### Lighthing Talks

I can only remember a talk about [elchemy][elchemy] (Elm -> Elixir) by [Krzysztof Wende][wende].

## Highlights

### After Party

The venue of the after-party

Lot's of amazing conversations which I'm probably still digesting.

## Upcoming Conferences

* [CodeMesh][codemesh] While it's not targeting Elixir specifically, features
  ([Joe Armstrong][armstrong-blog], [Robert Virding][virding-blog], [Fred Herbert][ferd], [Guy L. Steele][guy-steele])
  amongst many others, making the conf profoundly attractive to Erlang / Elixir / Functional Programming engineers.

* For news and announcements about Elixir.LDN follow [@LdnElixir][twitter-elixirldn] on twitter.

[Elixir.LDN-2017]: http://www.elixir.london/
[elixir-lang-slack]: elixir-lang.slack.com
[elixir-lang-invite]: https://elixir-slackin.herokuapp.com/
[elixir-london-meetup]: https://www.meetup.com/Elixir-London
[amorgos]: https://en.wikipedia.org/wiki/Amorgos
[conf-venue]: https://www.etcvenues.co.uk/venues/155bishopsgate
[ferd]: https://ferd.ca/
[armstrong-blog]: http://joearms.github.io/
[virding-blog]: http://rvirding.blogspot.co.uk/
[guy-steele]: https://labs.oracle.com/pls/apex/f?p=labs:bio:0:120
[Profile-Jose-Valim]: https://twitter.com/josevalim
[so-question]: https://stackoverflow.com/questions/44087086/how-to-debug-quickly-in-phoenix-elixir
[elixir-plug-pr]: https://github.com/elixir-plug/plug/issues/552
[otp-pr-1367]: https://github.com/erlang/otp/pull/1367/files
[dbgi-mailing-list]: http://erlang.org/pipermail/erlang-questions/2017-March/091883.html
[beam_lib-debug_info]: http://erlang.org/doc/man/beam_lib.html#type-debug_info
[pry.ex-github]: https://github.com/elixir-lang/elixir/blob/v1.5.1/lib/iex/lib/iex/pry.ex#L306
[Exception.blame/3]: https://hexdocs.pm/elixir/master/Exception.html#blame/3
[elixirscript-release-notes]: https://elixirscript.github.io/post/elixirscript-0.30.0-released/
[Profile-Evadne-Wu]: https://twitter.com/evadne
[Slides-Evadne-Wu]: https://speakerdeck.com/evadne/how-to-sell-elixir
[Slides-Peter-Saxton]: http://crowdhailer.me/talks/2017-08-17/working-with-http2-in-elixir/slides.html#1
[Profile-Peter-Saxton]: http://crowdhailer.me/
[ace]: https://github.com/CrowdHailer/Ace
[Profile-Louis-Pilfold]: https://twitter.com/louispilfold
[exfmt]: https://github.com/lpil/exfmt
[exfmt-vim-instructions]: https://github.com/lpil/exfmt#vim
[gsoc-elixir]: https://summerofcode.withgoogle.com/projects/?sp-page=2#5205518009237504
[wadler-pp]: https://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf
[hexdocs-inspect-algebra]: https://hexdocs.pm/elixir/Inspect.Algebra.html
[strictly-pretty-linding]: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.34.2200
[codemesh]: http://www.codemesh.io/
[Profile-Georgina-McFadyen]: https://twitter.com/gemcfadyen
[microservices-umbrella-link]: {{< relref "post/elixirconfeu-2017.md#tutorials" >}}
[umbrella-apps]: https://elixir-lang.org/getting-started/mix-otp/dependencies-and-umbrella-apps.html
[distillery]: https://github.com/bitwalker/distillery
[slides-meddle]: https://gitpitch.com/meddle0x53/elixir_ldn_2017
[Profile-Nikolay-Tsvetinov]: https://twitter.com/ntzvetinov
[Profile-Gary-Rennie]: https://twitter.com/TheGazler
[cowboy]: https://github.com/ninenines/cowboy
[cowboy-migration]: https://github.com/ninenines/cowboy/blob/master/doc/src/guide/migrating_from_1.0.asciidoc
[phoenix]: http://phoenixframework.org/
[chatterbox]: https://github.com/joedevivo/chatterbox
[elchemy]: https://github.com/wende/elchemy
[wende]: https://github.com/wende
[Profile-Gomori]: https://github.com/gomoripeti
[xprof]: https://github.com/Appliscale/xprof
[match_spec]: http://erlang.org/doc/apps/erts/match_spec.html
[Profile-leopardi]: https://twitter.com/whatyouhide
[Slides-leopardi]: https://speakerdeck.com/whatyouhide/stepping-into-a-new-era-injecting-elixir-in-a-ruby-app
[football-addicts]: https://www.footballaddicts.com/
[Profile-Zelenka]: https://twitter.com/expede
[Slides-zelenka]: https://www.slideshare.net/BrooklynZelenka/witchcraft-78939455
[blub-paradox]: https://en.wikipedia.org/wiki/Paul_Graham_(computer_programmer)#The_Blub_paradox
[Video-lpil]: https://www.youtube.com/watch?v=g4HXeP_CZbc
[Video-zelenka]: https://www.youtube.com/watch?v=psdG5iV57q0
[twitter-elixirldn]: https://twitter.com/LdnElixir
[Video-saxton]: https://www.youtube.com/watch?v=zqzkrUVfv-k
[Video-wu]: https://www.youtube.com/watch?v=YviCIOT7C6I
[Video-Rennie]: https://www.youtube.com/watch?v=R5xTuw7NYg8
[Video-keynote]: https://www.youtube.com/watch?v=p4uE-jTB_Uk
[Video-leopardi]: https://www.youtube.com/watch?v=5EDD1oZ23tY
[Video-mcfadyen]: https://www.youtube.com/watch?v=QJ3tDAdTjPI
[Video-gomori]: https://www.youtube.com/watch?v=AAXtjPiXbWE
[Video-tsvetinov]: https://www.youtube.com/watch?v=cKfme8i_nO0


text:
package org.x3f.android;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by taoqi on 2015/5/21.
 */
public class Lib {

    /**
     * Check if any of the available networks is connected.
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     * @param context Application context.
     * @return Whether connected.
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * Check if wifi is connected.
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     * @param context Application context.
     * @return Whether connected.
     */
    public boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * Check if mobile network is connected.
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     * @param context Application context.
     * @return Whether connected.
     */
    public boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * Get the connected network type.
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     * @param context Application context.
     * @return Network type.
     */
    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }

}


text:
'use strict';

var mogwai = require('mogwai'),
    LocalStrategy = require('passport-local').Strategy,
    TwitterStrategy = require('passport-twitter').Strategy,
    FacebookStrategy = require('passport-facebook').Strategy,
    GitHubStrategy = require('passport-github').Strategy,
    GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
    LinkedinStrategy = require('passport-linkedin').Strategy,
    User = mogwai.model('User'),
    config = require('./config');

module.exports = function(passport) {

    // Serialize the user id to push into the session
    passport.serializeUser(function(user, done) {
        done(null, user._id);
    });

    // Deserialize the user object based on a pre-serialized token
    // which is the user id
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, new User(user[0]) || {});
        });
    });

    // Use local strategy
    passport.use(new LocalStrategy({
            usernameField: 'email',
            passwordField: 'password'
        },
        function(email, password, done) {
            User.findByEmail(email, function(err, user) {
                if (err) {
                    return done(err);
                }
                if (!user || user.length !==1) {
                    return done(null, false, {
                        message: 'Unknown user'
                    });
                }
                user = new User(user[0]);
                if (!user.authenticate(password)) {
                    return done(null, false, {
                        message: 'Invalid password'
                    });
                }
                return done(null, user);
            });
        }
    ));

    // Use twitter strategy
    passport.use(new TwitterStrategy({
            consumerKey: config.twitter.clientID,
            consumerSecret: config.twitter.clientSecret,
            callbackURL: config.twitter.callbackURL
        },
        function(token, tokenSecret, profile, done) {
            User.findOne({
                'twitter.id_str': profile.id
            }, function(err, user) {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        username: profile.username,
                        provider: 'twitter',
                        twitter: profile._json
                    });
                    user.save(function(err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // Use facebook strategy
    passport.use(new FacebookStrategy({
            clientID: config.facebook.clientID,
            clientSecret: config.facebook.clientSecret,
            callbackURL: config.facebook.callbackURL
        },
        function(accessToken, refreshToken, profile, done) {
            User.findOne({
                'facebook.id': profile.id
            }, function(err, user) {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        username: profile.username,
                        provider: 'facebook',
                        facebook: profile._json
                    });
                    user.save(function(err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // Use github strategy
    passport.use(new GitHubStrategy({
            clientID: config.github.clientID,
            clientSecret: config.github.clientSecret,
            callbackURL: config.github.callbackURL
        },
        function(accessToken, refreshToken, profile, done) {
            User.findOne({
                'github.id': profile.id
            }, function(err, user) {
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        username: profile.username,
                        provider: 'github',
                        github: profile._json
                    });
                    user.save(function(err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // Use google strategy
    passport.use(new GoogleStrategy({
            clientID: config.google.clientID,
            clientSecret: config.google.clientSecret,
            callbackURL: config.google.callbackURL
        },
        function(accessToken, refreshToken, profile, done) {
            User.findOne({
                'google.id': profile.id
            }, function(err, user) {
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        username: profile.emails[0].value,
                        provider: 'google',
                        google: profile._json
                    });
                    user.save(function(err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // use linkedin strategy
    passport.use(new LinkedinStrategy({
            consumerKey: config.linkedin.clientID,
            consumerSecret: config.linkedin.clientSecret,
            callbackURL: config.linkedin.callbackURL,
            profileFields: ['id', 'first-name', 'last-name', 'email-address']
        },
        function(accessToken, refreshToken, profile, done) {
            User.findOne({
                'linkedin.id': profile.id
            }, function(err, user) {
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        username: profile.emails[0].value,
                        provider: 'linkedin'
                    });
                    user.save(function(err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));
};


text:
module Data.SBV.Dynamic
  (
  -- * Programming with symbolic values
  -- ** Symbolic types
  -- *** Abstract symbolic value type
    SVal
  , Kind(..), CW(..), CWVal(..), cwToBool
  , svKind, svBitSize, svSigned
  -- *** Arrays of symbolic values
  , SArr
  , readSArr, resetSArr, writeSArr, mergeSArr, newSArr, eqSArr

  -- ** Creating a symbolic variable
  , Symbolic
  , Quantifier(..)
  , svMkSymVar
  -- ** Operations on symbolic values
  -- *** Boolean literals
  , svTrue, svFalse, svBool, svAsBool
  -- *** Integer literals
  , svInteger, svAsInteger
  -- *** Symbolic equality
  , svEqual, svNotEqual
  -- *** Symbolic ordering
  , svLessThan, svGreaterThan, svLessEq, svGreaterEq
  -- *** Arithmetic operations
  , svPlus, svTimes, svMinus, svUNeg, svAbs
  , svDivide, svQuot, svRem
  -- *** Logical operations
  , svAnd, svOr, svXOr, svNot
  , svShl, svShr, svRol, svRor
  -- *** Splitting, joining, and extending
  , svExtract, svJoin
  -- *** Sign-casting
  , svSign, svUnsign
  -- *** Indexed lookups
  , svSelect
  -- *** Word-level operations
  , svToWord1, svFromWord1, svTestBit
  , svShiftLeft, svShiftRight
  , svRotateLeft, svRotateRight
  -- ** Conditionals: Mergeable values
  , svIte, svLazyIte, svSymbolicMerge
  , svReduceInPathCondition
  -- * Uninterpreted sorts, constants, and functions
  , svUninterpreted
  -- * Properties, proofs, and satisfiability
  -- ** Proving properties
  , proveWith
  -- ** Checking satisfiability
  , satWith
  -- * Proving properties using multiple solvers
  , proveWithAll, proveWithAny, satWithAll, satWithAny, allSatWithAll, allSatWithAny
  -- * Model extraction

  -- ** Inspecting proof results
  , ThmResult(..), SatResult(..), AllSatResult(..), SMTResult(..), SafeResult(..)

  -- ** Programmable model extraction
  , genParse, getModel, getModelDictionary
  -- * SMT Interface: Configurations and solvers
  , SMTConfig(..), SMTLibLogic(..), Logic(..), OptimizeOpts(..), Solver(..), SMTSolver(..), boolector, cvc4, yices, z3, mathSAT, abc, defaultSolverConfig, sbvCurrentSolver, defaultSMTCfg, sbvCheckSolverInstallation, sbvAvailableSolvers

  -- * Symbolic computations
  , outputSVal{-, SymWord(..)-}

  -- * Getting SMT-Lib output (for offline analysis)
  , compileToSMTLib, generateSMTBenchmarks
  -- * Code generation from symbolic programs
  , SBVCodeGen

  -- ** Setting code-generation options
  , cgPerformRTCs, cgSetDriverValues, cgGenerateDriver, cgGenerateMakefile

  -- ** Designating inputs
  , svCgInput, svCgInputArr

  -- ** Designating outputs
  , svCgOutput, svCgOutputArr

  -- ** Designating return values
  , svCgReturn, svCgReturnArr

  -- ** Code generation with uninterpreted functions
  , cgAddPrototype, cgAddDecl, cgAddLDFlags

  -- ** Code generation with 'SInteger' and 'SReal' types
  , cgIntegerSize, cgSRealType, CgSRealType(..)

  -- ** Compilation to C
  , compileToC, compileToCLib
  ) where

import Data.Map (Map)

import Data.SBV.BitVectors.Kind
import Data.SBV.BitVectors.Concrete
import Data.SBV.BitVectors.Symbolic
import Data.SBV.BitVectors.Operations

import Data.SBV.Compilers.CodeGen
  ( SBVCodeGen
  , svCgInput, svCgInputArr
  , svCgOutput, svCgOutputArr
  , svCgReturn, svCgReturnArr
  , cgPerformRTCs, cgSetDriverValues, cgGenerateDriver, cgGenerateMakefile
  , cgAddPrototype, cgAddDecl, cgAddLDFlags
  , cgIntegerSize, cgSRealType, CgSRealType(..)
  )
import Data.SBV.Compilers.C
  ( compileToC, compileToCLib )
import Data.SBV.Provers.Prover
  ( boolector, cvc4, yices, z3, mathSAT, abc, defaultSMTCfg )
import Data.SBV.SMT.SMT
  ( ThmResult(..), SatResult(..), AllSatResult(..), SafeResult(..), genParse )
import Data.SBV.Tools.Optimize
  ( OptimizeOpts(..) )
import Data.SBV
  ( sbvCurrentSolver, sbvCheckSolverInstallation, defaultSolverConfig, sbvAvailableSolvers )

import qualified Data.SBV as SBV
  ( SBool, proveWithAll, proveWithAny, satWithAll, satWithAny, allSatWithAll, allSatWithAny )
import qualified Data.SBV.BitVectors.Data as SBV
  ( SBV(..) )
import qualified Data.SBV.BitVectors.Model as SBV
  ( reduceInPathCondition )
import qualified Data.SBV.Provers.Prover as SBV
  ( proveWith, satWith, compileToSMTLib, generateSMTBenchmarks )
import qualified Data.SBV.SMT.SMT as SBV
  ( Modelable(getModel, getModelDictionary) )

-- | Reduce a condition (i.e., try to concretize it) under the given path
svReduceInPathCondition :: SVal -> SVal
svReduceInPathCondition t = c
  where SBV.SBV c = SBV.reduceInPathCondition (SBV.SBV t)

toSBool :: SVal -> SBV.SBool
toSBool = SBV.SBV

-- | Compiles to SMT-Lib and returns the resulting program as a string. Useful for saving
-- the result to a file for off-line analysis, for instance if you have an SMT solver that's not natively
-- supported out-of-the box by the SBV library. It takes two booleans:
--
--    * smtLib2: If 'True', will generate SMT-Lib2 output, otherwise SMT-Lib1 output
--
--    * isSat  : If 'True', will translate it as a SAT query, i.e., in the positive. If 'False', will
--               translate as a PROVE query, i.e., it will negate the result. (In this case, the check-sat
--               call to the SMT solver will produce UNSAT if the input is a theorem, as usual.)
compileToSMTLib :: Bool   -- ^ If True, output SMT-Lib2, otherwise SMT-Lib1
                -> Bool   -- ^ If True, translate directly, otherwise negate the goal. (Use True for SAT queries, False for PROVE queries.)
                -> Symbolic SVal
                -> IO String
compileToSMTLib smtLib2 isSat s = SBV.compileToSMTLib smtLib2 isSat (fmap toSBool s)

-- | Create both SMT-Lib1 and SMT-Lib2 benchmarks. The first argument is the basename of the file,
-- SMT-Lib1 version will be written with suffix ".smt1" and SMT-Lib2 version will be written with
-- suffix ".smt2". The 'Bool' argument controls whether this is a SAT instance, i.e., translate the query
-- directly, or a PROVE instance, i.e., translate the negated query. (See the second boolean argument to
-- 'compileToSMTLib' for details.)
generateSMTBenchmarks :: Bool -> FilePath -> Symbolic SVal -> IO ()
generateSMTBenchmarks isSat f s = SBV.generateSMTBenchmarks isSat f (fmap toSBool s)

-- | Proves the predicate using the given SMT-solver
proveWith :: SMTConfig -> Symbolic SVal -> IO ThmResult
proveWith cfg s = SBV.proveWith cfg (fmap toSBool s)

-- | Find a satisfying assignment using the given SMT-solver
satWith :: SMTConfig -> Symbolic SVal -> IO SatResult
satWith cfg s = SBV.satWith cfg (fmap toSBool s)

-- | Prove a property with multiple solvers, running them in separate threads. The
-- results will be returned in the order produced.
proveWithAll :: [SMTConfig] -> Symbolic SVal -> IO [(Solver, ThmResult)]
proveWithAll cfgs s = SBV.proveWithAll cfgs (fmap toSBool s)

-- | Prove a property with multiple solvers, running them in separate
-- threads. Only the result of the first one to finish will be
-- returned, remaining threads will be killed.
proveWithAny :: [SMTConfig] -> Symbolic SVal -> IO (Solver, ThmResult)
proveWithAny cfgs s = SBV.proveWithAny cfgs (fmap toSBool s)

-- | Find a satisfying assignment to a property with multiple solvers,
-- running them in separate threads. The results will be returned in
-- the order produced.
satWithAll :: [SMTConfig] -> Symbolic SVal -> IO [(Solver, SatResult)]
satWithAll cfgs s = SBV.satWithAll cfgs (fmap toSBool s)

-- | Find a satisfying assignment to a property with multiple solvers,
-- running them in separate threads. Only the result of the first one
-- to finish will be returned, remaining threads will be killed.
satWithAny :: [SMTConfig] -> Symbolic SVal -> IO (Solver, SatResult)
satWithAny cfgs s = SBV.satWithAny cfgs (fmap toSBool s)

-- | Find all satisfying assignments to a property with multiple
-- solvers, running them in separate threads. Only the result of the
-- first one to finish will be returned, remaining threads will be
-- killed.
allSatWithAll :: [SMTConfig] -> Symbolic SVal -> IO [(Solver, AllSatResult)]
allSatWithAll cfgs s = SBV.allSatWithAll cfgs (fmap toSBool s)

-- | Find all satisfying assignments to a property with multiple
-- solvers, running them in separate threads. Only the result of the
-- first one to finish will be returned, remaining threads will be
-- killed.
allSatWithAny :: [SMTConfig] -> Symbolic SVal -> IO (Solver, AllSatResult)
allSatWithAny cfgs s = SBV.allSatWithAny cfgs (fmap toSBool s)

-- | Extract a model, the result is a tuple where the first argument (if True)
-- indicates whether the model was "probable". (i.e., if the solver returned unknown.)
getModel :: SMTResult -> Either String (Bool, [CW])
getModel = SBV.getModel

-- | Extract a model dictionary. Extract a dictionary mapping the variables to
-- their respective values as returned by the SMT solver. Also see `getModelDictionaries`.
getModelDictionary :: SMTResult -> Map String CW
getModelDictionary = SBV.getModelDictionary


text:
package org.apache.kafka.common.utils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import org.apache.kafka.common.KafkaException;

public class Utils {

    public static String NL = System.getProperty("line.separator");

    /**
     * Turn the given UTF8 byte array into a string
     *
     * @param bytes The byte array
     * @return The string
     */
    public static String utf8(byte[] bytes) {
        try {
            return new String(bytes, "UTF8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("This shouldn't happen.", e);
        }
    }

    /**
     * Turn a string into a utf8 byte[]
     *
     * @param string The string
     * @return The byte[]
     */
    public static byte[] utf8(String string) {
        try {
            return string.getBytes("UTF8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("This shouldn't happen.", e);
        }
    }

    /**
     * Read an unsigned integer from the current position in the buffer, incrementing the position by 4 bytes
     *
     * @param buffer The buffer to read from
     * @return The integer read, as a long to avoid signedness
     */
    public static long readUnsignedInt(ByteBuffer buffer) {
        return buffer.getInt() & 0xffffffffL;
    }

    /**
     * Read an unsigned integer from the given position without modifying the buffers position
     *
     * @param buffer the buffer to read from
     * @param index the index from which to read the integer
     * @return The integer read, as a long to avoid signedness
     */
    public static long readUnsignedInt(ByteBuffer buffer, int index) {
        return buffer.getInt(index) & 0xffffffffL;
    }

    /**
     * Write the given long value as a 4 byte unsigned integer. Overflow is ignored.
     *
     * @param buffer The buffer to write to
     * @param value The value to write
     */
    public static void writetUnsignedInt(ByteBuffer buffer, long value) {
        buffer.putInt((int) (value & 0xffffffffL));
    }

    /**
     * Write the given long value as a 4 byte unsigned integer. Overflow is ignored.
     *
     * @param buffer The buffer to write to
     * @param index The position in the buffer at which to begin writing
     * @param value The value to write
     */
    public static void writeUnsignedInt(ByteBuffer buffer, int index, long value) {
        buffer.putInt(index, (int) (value & 0xffffffffL));
    }

    /**
     * Get the absolute value of the given number. If the number is Int.MinValue return 0. This is different from
     * java.lang.Math.abs or scala.math.abs in that they return Int.MinValue (!).
     */
    public static int abs(int n) {
        return n & 0x7fffffff;
    }

    /**
     * Get the length for UTF8-encoding a string without encoding it first
     *
     * @param s The string to calculate the length for
     * @return The length when serialized
     */
    public static int utf8Length(CharSequence s) {
        int count = 0;
        for (int i = 0, len = s.length(); i < len; i++) {
            char ch = s.charAt(i);
            if (ch <= 0x7F) {
                count++;
            } else if (ch <= 0x7FF) {
                count += 2;
            } else if (Character.isHighSurrogate(ch)) {
                count += 4;
                ++i;
            } else {
                count += 3;
            }
        }
        return count;
    }

    /**
     * Read the given byte buffer into a byte array
     */
    public static byte[] toArray(ByteBuffer buffer) {
        return toArray(buffer, 0, buffer.limit());
    }

    /**
     * Read a byte array from the given offset and size in the buffer
     */
    public static byte[] toArray(ByteBuffer buffer, int offset, int size) {
        byte[] dest = new byte[size];
        if (buffer.hasArray()) {
            System.arraycopy(buffer.array(), buffer.arrayOffset() + offset, dest, 0, size);
        } else {
            int pos = buffer.position();
            buffer.get(dest);
            buffer.position(pos);
        }
        return dest;
    }

    /**
     * Check that the parameter t is not null
     *
     * @param t The object to check
     * @return t if it isn't null
     * @throws NullPointerException if t is null.
     */
    public static <T> T notNull(T t) {
        if (t == null)
            throw new NullPointerException();
        else
            return t;
    }

    /**
     * Instantiate the class
     */
    public static Object newInstance(Class<?> c) {
        try {
            return c.newInstance();
        } catch (IllegalAccessException e) {
            throw new KafkaException("Could not instantiate class " + c.getName(), e);
        } catch (InstantiationException e) {
            throw new KafkaException("Could not instantiate class " + c.getName() + " Does it have a public no-argument constructor?", e);
        }
    }

    /**
     * Generates 32 bit murmur2 hash from byte array
     * @param data byte array to hash
     * @return 32 bit hash of the given array
     */
    public static int murmur2(final byte[] data) {
        int length = data.length;
        int seed = 0x9747b28c;
        // 'm' and 'r' are mixing constants generated offline.
        // They're not really 'magic', they just happen to work well.
        final int m = 0x5bd1e995;
        final int r = 24;

        // Initialize the hash to a random value
        int h = seed ^ length;
        int length4 = length / 4;

        for (int i = 0; i < length4; i++) {
            final int i4 = i * 4;
            int k = (data[i4 + 0] & 0xff) + ((data[i4 + 1] & 0xff) << 8) + ((data[i4 + 2] & 0xff) << 16) + ((data[i4 + 3] & 0xff) << 24);
            k *= m;
            k ^= k >>> r;
            k *= m;
            h *= m;
            h ^= k;
        }

        // Handle the last few bytes of the input array
        switch (length % 4) {
            case 3:
                h ^= (data[(length & ~3) + 2] & 0xff) << 16;
            case 2:
                h ^= (data[(length & ~3) + 1] & 0xff) << 8;
            case 1:
                h ^= (data[length & ~3] & 0xff);
                h *= m;
        }

        h ^= h >>> 13;
        h *= m;
        h ^= h >>> 15;

        return h;
    }

}


text:
YAHOO.namespace('GEIESMONADS.test');

var Assert = YAHOO.util.Assert;

/* Go back to maybe and test a better implementation
*/
YAHOO.GEIESMONADS.test.oTestSMMAO = new YAHOO.tool.TestCase({
	name : "TestChainableStateMaybeMonadAsObject",
	testChainableStateMaybeMonadAsObject : function() {

        // modifies value
		var more = function(value) {
			return 'more ' + value;
		};

        // modifies state - already a famb
        var sugar = function(state) {
            return
        }

		// 1) custom built lifter
		var famb = function(fab){
			return function(a) {
				return Monad.stateMaybe.unit(fab(a));
			}
		};

		var mMore = famb(more);

		var coffee = Monad.stateMaybe.unit('coffee');
		Assert.areEqual('coffee', coffee('OK').value());
		Assert.areEqual('OK', coffee('OK').state);

		var moreCoffee = coffee.bind(mMore);

		Assert.areEqual('more coffee',moreCoffee(0).value());
		Assert.areEqual('more coffee',moreCoffee.flatten());
		Assert.areEqual('coffee', coffee('OK').value());
		Assert.areEqual('OK', coffee('OK').state);

		// 2) using liftM
		var mMore2 = Monad.stateMaybe.liftM(more);

		var moreCoffee2 = coffee.bind(mMore2);

		Assert.areEqual('more coffee',moreCoffee2());

		// 3) chaining a mapper
		var moreCoffee3 = coffee.map(more).map(more);

		Assert.areEqual('more more coffee',moreCoffee3());

		// none's in action
		var none = Monad.maybe.unit(null);
		Assert.isUndefined(none());

		var noneChain = none.bind(famb);

		Assert.isUndefined(noneChain());
		Assert.isUndefined(noneChain.flatten());

		// alert fires once
		//var coffeeAlert = coffee.map(alert);

		// need myAlert to pass value down the chain
		var myAlert = function(value) {
			alert(value);
			return value;
		}

		// alerts fire twice with different messages
		// var compositeAlert = coffee.map(myAlert).bind(mMore).map(myAlert);
		// Assert.areEqual('more coffee',compositeAlert());

		var noAlert = none.map(alert);
		Assert.isUndefined(noAlert());
	}
});

/* This test shows the labeling of a tree by using a statemaybe monad
*/
YAHOO.GEIESMONADS.test.oTestStateMaybeMonadicLabelingOK = new YAHOO.tool.TestCase({
	name : "TestStateMaybeMonadicLabelingOK",
	testStateMaybeMonadicLabelingOK : function() {

		var simpleTree = MyTree.leaf('a');

		var simpleTreeMonad = MyTree.monadicMaybeLabeler(simpleTree);
		var simpleResultScp = simpleTreeMonad(0);
		var simpleResultLlt = simpleResultScp.value;
		var simpleResultState = simpleResultScp.state;

		Assert.areEqual(1, simpleResultState);
		Assert.areEqual('LEAF', simpleResultLlt()().type());
		Assert.areEqual('a', simpleResultLlt()()()[1]);

		var simpleTree2 = MyTree.branch(MyTree.leaf('a'),MyTree.leaf('b'));

		var simpleTreeMonad2 = MyTree.monadicMaybeLabeler(simpleTree2);
		var simpleResultScp2 = simpleTreeMonad2(0);
		var simpleResultLlt2 = simpleResultScp2.value;
		var simpleResultState2 = simpleResultScp2.state;

		Assert.areEqual(2, simpleResultState2);
		Assert.areEqual('BRANCH', simpleResultLlt2().type());
		Assert.areEqual('LEAF', MyTree.left(simpleResultLlt2())()().type());

		var testTree = MyTree.branch(
			MyTree.leaf('a'),
			MyTree.branch(
				MyTree.branch(
					MyTree.leaf('b'),
					MyTree.leaf('c')),
				MyTree.leaf('d')
			)
		);

		var treeMonad = MyTree.monadicMaybeLabeler(simpleTree);
		var resultScp = treeMonad(0);
		var resultLlt = resultScp.value;
		var resultState = resultScp.state;

		Assert.areEqual(4, resultState);
		Assert.areEqual('BRANCH', resultLlt().type());
		Assert.areEqual('LEAF', MyTree.left(resultLlt())()().type());

		// here start the errors
		Assert.areEqual(1, MyTree.left(MyTree.left(MyTree.right(resultLlt)))()()[0]);
		Assert.areEqual('b', MyTree.left(MyTree.left(MyTree.right(resultLlt)))()()[1]);
		Assert.areEqual(2, MyTree.right(MyTree.left(MyTree.right(resultLlt)))()()[0]);
		Assert.areEqual('c', MyTree.right(MyTree.left(MyTree.right(resultLlt)))()()[1]);
	}
});

YAHOO.util.Event
		.onDOMReady(function() {
			YAHOO.GEIESMONADS.test.GEIESMONADS_TestSuite = new YAHOO.tool.TestSuite(
					"Second YUI Test Suite for GEIESMONADS");
			YAHOO.GEIESMONADS.test.GEIESMONADS_TestSuite
				.add(YAHOO.GEIESMONADS.test.oTestSMMAO);
			YAHOO.GEIESMONADS.test.GEIESMONADS_TestSuite
				.add(YAHOO.GEIESMONADS.test.oTestStateMaybeMonadicLabelingOK);

			var logger = new YAHOO.tool.TestLogger("testLogger_GEIESMONADS");
			logger.hideCategory("info");

			YAHOO.tool.TestRunner
					.add(YAHOO.GEIESMONADS.test.GEIESMONADS_TestSuite);
			YAHOO.tool.TestRunner.run()
		});


text:
ACCEPTED

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

#### Published in
null

#### Original name
Pachystigma solitariiflorum Verdc.

### Remarks
null


text:
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                            data-target=".navbar-collapse" aria-expanded="false">

                    </button>


text:
<?php //REPORT 16 [Kannel] MO SMS traffic on platform by SMSC and short codes

	$cv = ''; // FIXME: this is SQL query part for WHERE clause

	// Retrieve number of successfully ordered content
$tmp = db_get("select
		smsc,
		dst,
		count(id) as cnt
	from stat.kannel_sms
	where received between '$since' and '$till 24:00:00'
	and direction = 'MO'
	group by smsc, dst
	order by smsc, dst");

	start_table();
	th('Report:');th('MO SMS traffic on platform by SMSC and short codes');row();
	th('Since:');th($since);row();
	th('Till:');th($till);row();
	th('#');th('SMSC');th('Service number (short code)');th('Number of MO SM');row();

	$num = 0;
	foreach ($tmp as $rec) {

      tdn(++$num);

      td($rec['smsc']);
      td($rec['dst']);
      tdn($rec['cnt']);

			row();
	};

	end_table();

?>


text:
layout: post
title: Wie schalte ich zwischen Split Screen / Full Screen auf Tabletten?
date: 2015-05-04 10:31:18.000000000 +03:00
type: post
published: true
status: publish
categories:
- Verbesserte Funktionen
tags: []
lang: de
meta: /switch-between-split-full-screen/
---

Für Tabletten, oben rechts auf Ihrem Bildschirm in BlueMail, können Sie auf die 2 Pfeile Symbol tippen, wird dies zwischen einer Split-Ansicht auf Ihre Haupt-Posteingangsliste Ansicht wechseln

Hinweis: Für Phablets können Sie Split View aktivieren, indem Sie: *More ...* \| verwenden *Globale Einstellungen* \| *Erweiterte Funktionen* \| *Anzeigemodus* \| *Geteilter Bildschirm*. Und startet BlueMail neu.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Linq;
using Cake.Core.Text;
using Xunit;

namespace Cake.Core.Tests.Unit.Text
{
    public sealed class QuoteAwareStringSplitterTests
    {
        public sealed class TheTokenizeMethod
        {
            [Fact]
            public void Should_Return_Zero_Results_If_Input_String_Is_Null()
            {
                // Given
                var input = string.Empty;

                // When
                var result = QuoteAwareStringSplitter.Split(input).ToArray();

                // Then
                Assert.Empty(result);
            }

            [Fact]
            public void Should_Parse_Single_Quoted_Argument_Without_Space_In_It()
            {
                // Given
                const string input = "\"C:\\cake-walk\\cake.exe\"";

                // When
                var result = QuoteAwareStringSplitter.Split(input).ToArray();

                // Then
                Assert.Single(result);
                Assert.Equal("\"C:\\cake-walk\\cake.exe\"", result[0]);
            }

            [Fact]
            public void Should_Parse_Single_Quoted_Argument_With_Space_In_It()
            {
                // Given
                const string input = "\"C:\\cake walk\\cake.exe\"";

                // When
                var result = QuoteAwareStringSplitter.Split(input).ToArray();

                // Then
                Assert.Single(result);
                Assert.Equal("\"C:\\cake walk\\cake.exe\"", result[0]);
            }

            [Fact]
            public void Should_Parse_Multiple_Quoted_Arguments()
            {
                // Given
                const string input = "\"C:\\cake-walk\\cake.exe\" \"build.cake\" \"-dryrun\"";

                // When
                var result = QuoteAwareStringSplitter.Split(input).ToArray();

                // Then
                Assert.Equal(3, result.Length);
                Assert.Equal("\"C:\\cake-walk\\cake.exe\"", result[0]);
                Assert.Equal("\"build.cake\"", result[1]);
                Assert.Equal("\"-dryrun\"", result[2]);
            }

            [Fact]
            public void Should_Parse_Multiple_Mixed_Arguments()
            {
                // Given
                const string input = "\"C:\\cake-walk\\cake.exe\" build.cake -verbosity \"diagnostic\"";

                // When
                var result = QuoteAwareStringSplitter.Split(input).ToArray();

                // Then
                Assert.Equal(4, result.Length);
                Assert.Equal("\"C:\\cake-walk\\cake.exe\"", result[0]);
                Assert.Equal("build.cake", result[1]);
                Assert.Equal("-verbosity", result[2]);
                Assert.Equal("\"diagnostic\"", result[3]);
            }

            [Fact]
            public void Should_Parse_Part_That_Contains_Quotes_With_Space_In_It()
            {
                // Given
                const string input = @"cake.exe build.cake -target=""te st""";

                // When
                var result = QuoteAwareStringSplitter.Split(input).ToArray();

                // Then
                Assert.Equal(3, result.Length);
                Assert.Equal("cake.exe", result[0]);
                Assert.Equal("build.cake", result[1]);
                Assert.Equal("-target=\"te st\"", result[2]);
            }
        }
    }
}


text:
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
    <link rel="stylesheet" href="/stylesheets/bootstrap/bootstrap.css">
</head>
<body>
    {{{ yield }}}
</body>
<script type="text/javascript" src="/javascript/jquery.min.js"></script>
<script type="text/javascript" src="/javascript/bootstrap.min.js"></script>
</html>


text:
import {Injectable} from "@angular/core";
import {Router} from "@angular/router";
import {Response} from "@angular/http";
import {Observable} from "rxjs";
import {UserService} from "../user/user.service";

@Injectable()
export class ErrorHandleService {

  constructor(private router: Router,
              private userService: UserService) {
  }

  catchHttpError(response: Response): Observable<Response> {
    if (response.status == 403) {
      this.userService.clearUser();
      this.router.navigate(['/sign-in']);
      throw "user must be signed in";
    }
    if (response.status == 500) {
      this.router.navigate(['/error']);
    }
    return Observable.never();
  }
}


text:
///<reference path="fourslash.ts" />

// Assignments to 'exports.p' define a property 'p' even if they're not at top-level

// @allowJs: true
// @Filename: myMod.js
//// if (true) {
////     exports.b = true;
//// } else {
////     exports.n = 3;
//// }
//// function fn() {
////     exports.s = 'foo';
//// }

// @Filename: consumer.js
//// var x = require('myMod');
//// x/**/;

goTo.file('consumer.js');
goTo.marker();
edit.insert('.');
verify.completionListContains("n", /*displayText:*/ undefined, /*documentation*/ undefined, "property");
verify.completionListContains("s", /*displayText:*/ undefined, /*documentation*/ undefined, "property");
verify.completionListContains("b", /*displayText:*/ undefined, /*documentation*/ undefined, "property");
edit.insert('n.');
verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");


text:
module 'mock'

--------------------------------------------------------------------
CLASS: UIWidgetElementText ( UIWidgetElement )
	:MODEL{}

function UIWidgetElementText:__init()
	self.styleBaseName = ''
	self.text = ''
	self.label = false
	self.defaultAlignment  = 'left'
	self.defaultAlignmentV = 'center'
end

function UIWidgetElementText:setDefaultAlignment( h, v )
	self.defaultAlignment = h or 'left'
	self.defaultAlignmentV = h or 'center'
end

function UIWidgetElementText:setText( text )
	self.text = text
end

function UIWidgetElementText:onInit( widget, style )
	local label = widget:attachInternal( TextLabel() )
	self.label = label
	label:setText('')
	label:setVisible( false )
	label.fitAlignment = false
	label:setLocZ( 0.1 )
end

function UIWidgetElementText:onDestroy( widget )
	widget:detach( self.label )
end

function UIWidgetElementText:onUpdateStyle( widget, style )
	local align    = style:get( self:makeStyleName( 'alignment' ), self.defaultAlignment )
	local alignV   = style:get( self:makeStyleName( 'alignment_vertical' ), self.defaultAlignmentV )
	local font     = style:getAsset( self:makeStyleName( 'font' ) )
	local fontSize = style:get( self:makeStyleName( 'font_size' ), 12 )
	local color    = { style:getColor( self:makeStyleName( 'color' ), { 1,1,1,1 } ) }
	local styleSheet = makeStyleSheetFromFont( font, fontSize )
	local lineSpacing = style:get( self:makeStyleName( 'line_spacing' ), 2 )

	self:setOffset( style:getVec2( self:makeStyleName( 'offset' ), { 0, 0 } ) )
	local label = self.label
	label:setAlignment( align )
	label:setAlignmentV( alignV )
	label:setStyleSheet( AdHocAsset( styleSheet ) )
	label:setColor( unpack( color ) )
	label:setLineSpacing( lineSpacing )

end

function UIWidgetElementText:onUpdateSize( widget, style )
	local label = self.label
	local ox, oy = self:getOffset()
	local x0, y0, x1, y1 = self:getRect()
	label:setRect( x0 + ox, y0 + oy, x1 + ox, y1 + oy )
	label:setLocZ( self:getZOrder() )
end

function UIWidgetElementText:onUpdateContent( widget, style )
	local label = self.label
	local text = self.text
	if text then
		label:setVisible( true )
		label:setText( text )
	else
		label:setVisible( false )
	end
end


text:
layout:   post
author:   theo
title:    "Agile Adoption - Cucumber Podcast"
date:     2017-09-28 01:00:00
nav:      blog
---
<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/344388290&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false"></iframe>

On the podcast this month, Seb Rose and Steve Tooke speak to Allan Kelly, a well-known agile consultant and long-time friend of the pod.

### On the podcast the three discuss:

 - Why agile often just means agile software development.

 - What companies mean when they say "digital transformation".

 - Advice for ambitious teams who want to spread agile across the organisation.

 - Allan's personal story into agile consulting.

 - Why he advocates a #noprojects mindset

 - Why Seb shares Allan's Dear Customer blog post with all his post-graduate students.

### Shownotes:

 - [Dear Customer](https://leanpub.com/xanpan/c/Trega15)

 - [Agile on the Beach](http://agileonthebeach.com/)

 - How buildings learn [Video](https://www.youtube.com/watch?v=AvEqfg2sIH0), [Book](https://www.amazon.co.uk/How-Buildings-Learn-Happens-Theyre/dp/0140139966)

 - [Allan on Twitter](https://twitter.com/allankellynet)

 - [Allan's blog](https://www.allankellyassociates.co.uk/)

You can also listen and download the podcast on [iTunes](https://itunes.apple.com/gb/podcast/cucumber-podcast-rss/id1078896635) and [Stitcher](http://www.stitcher.com/s?fid=81999&refid=stpr).

Share your thoughts in the comments or on [Twitter](https://twitter.com/cucumberbdd)


text:
namespace Dev.CasClientWebForm {

    public partial class ViewSwitcher {
    }
}


text:
package com.vladsch.MissingInActions.actions.character.custom;

import com.vladsch.MissingInActions.actions.DumbAwareTextComponentEditorAction;
import com.vladsch.MissingInActions.actions.LineSelectionAware;

public class PreviousWordStartInDifferentHumpsModeAction extends DumbAwareTextComponentEditorAction implements LineSelectionAware {
    public PreviousWordStartInDifferentHumpsModeAction() {
        super(new NextOrPrevWordStartHandler(false, false, true));
    }
}


text:
layout: post
title: "United Nations General Assembly Voting Data Analysis"
excerpt: "UN General Assembly Vote, Linear Regression"
tags: [rstats]
share: true
comments: true
---

I recently came across a R package called ["unvote"](https://cran.r-project.org/web/packages/unvotes/unvotes.pdf) that consists the voting history of countries in the United Nations General Assembly from 1946 to 2015. The packaged was developed by [David Robinson](http://varianceexplained.org/).

### Explore the data

{% highlight r %}
library(ggplot2)
library(unvotes)
library(dplyr)
library(lubridate)
library(ggthemes)
library(tidyr)
{% endhighlight %}

The package contains three data set. The first is the history of each country's vote, with more than 700,000 rows.

{% highlight r %}
un_votes
{% endhighlight %}

{% highlight text %}
### A tibble: 738,764 × 4
##    rcid                  country country_code   vote
##   <int>                    <chr>        <chr> <fctr>
##1      3 United States of America           US    yes
##2      3                   Canada           CA     no
##3      3                     Cuba           CU    yes
##4      3                    Haiti           HT    yes
##5      3       Dominican Republic           DO    yes
##6      3                   Mexico           MX    yes
##7      3                Guatemala           GT    yes
##8      3                 Honduras           HN    yes
##9      3              El Salvador           SV    yes
##10     3                Nicaragua           NI    yes
### ... with 738,754 more rows
{% endhighlight %}

The second dataset contains information about each roll call vote, including the date, description, and relevant resolution that was voted on.

{% highlight r %}
un_roll_calls
{% endhighlight %}

{% highlight text %}
### A tibble: 5,429 × 9
##    rcid session importantvote       date   unres amend  para
##   <int>   <dbl>         <dbl>     <date>   <chr> <dbl> <dbl>
##1      3       1             0 1946-01-01  R/1/66     1     0
##2      4       1             0 1946-01-02  R/1/79     0     0
##3      5       1             0 1946-01-04  R/1/98     0     0
##4      6       1             0 1946-01-04 R/1/107     0     0
##5      7       1             0 1946-01-02 R/1/295     1     0
##6      8       1             0 1946-01-05 R/1/297     1     0
##7      9       1             0 1946-02-05 R/1/329     0     0
##8     10       1             0 1946-02-05 R/1/361     1     1
##9     11       1             0 1946-02-05 R/1/376     0     0
##10    12       1             0 1946-02-06 R/1/394     1     1
### ... with 5,419 more rows, and 2 more variables: short <chr>, descr <chr>
{% endhighlight %}

The last data set contains relationships between each vote and six issues, they are "Palestinian conflict", "Nuclear weapons and nuclear material", "Arms control and disarmament", "Human rights", "Colonialism" and "Economic development".

{% highlight r %}
un_roll_call_issues
{% endhighlight %}

{% highlight text %}
### A tibble: 5,281 × 3
##    rcid short_name                issue
##   <int>      <chr>                <chr>
##1   3372         me Palestinian conflict
##2   3658         me Palestinian conflict
##3   3692         me Palestinian conflict
##4   2901         me Palestinian conflict
##5   3020         me Palestinian conflict
##6   3217         me Palestinian conflict
##7   3298         me Palestinian conflict
##8   3429         me Palestinian conflict
##9   3558         me Palestinian conflict
##10  3625         me Palestinian conflict
### ... with 5,271 more rows
{% endhighlight %}

### First, which issue(issues) have been voted the most?

{% highlight r %}
un_roll_call_issues %>% count(issue, sort=TRUE)
{% endhighlight %}

{% highlight text %}
### A tibble: 6 × 2
##                                 issue     n
##                                 <chr> <int>
##1                 Palestinian conflict  1104
##2                          Colonialism   991
##3                         Human rights   986
##4         Arms control and disarmament   956
##5 Nuclear weapons and nuclear material   762
##6                 Economic development   482
{% endhighlight %}

### How often a country voted "yes" from 1946 to 2015?

{% highlight r %}
by_country <- un_votes %>% group_by(country) %>% summarize(votes = n(),
pct_yes = mean(vote == 'yes'))
by_country
{% endhighlight %}

{% highlight text %}
### A tibble: 200 × 3
##               country votes   pct_yes
##                 <chr> <int>     <dbl>
##1          Afghanistan  4972 0.8417136
##2              Albania  3514 0.7157086
##3              Algeria  4527 0.8981666
##4              Andorra  1564 0.6445013
##5               Angola  3075 0.9219512
##6  Antigua and Barbuda  2658 0.9194883
##7            Argentina  5361 0.7789591
##8              Armenia  1629 0.7587477
##9            Australia  5399 0.5523245
##10             Austria  4939 0.6329216
### ... with 190 more rows
{% endhighlight %}

### Percentage yes vote high countries from 1946 to 2015

{% highlight r %}
arrange(by_country, desc(pct_yes))
{% endhighlight %}

{% highlight text %}
### A tibble: 200 × 3
##                 country votes   pct_yes
##                   <chr> <int>     <dbl>
##1             Seychelles  1790 0.9782123
##2            Timor-Leste   837 0.9701314
##3  Sao Tome and Principe  2389 0.9673504
##4             Cabo Verde  3292 0.9599028
##5               Djibouti  3345 0.9563528
##6          Guinea Bissau  3070 0.9560261
##7                Comoros  2530 0.9450593
##8             Mozambique  3456 0.9427083
##9   United Arab Emirates  4031 0.9414537
##10              Suriname  3410 0.9410557
# ... with 190 more rows
{% endhighlight %}

### Percentage yes vote low countries from 1946 to 2015

{% highlight r %}
by_country[order(by_country$pct_yes),]
{% endhighlight %}

{% highlight text %}
### A tibble: 200 × 3
##                                                country votes   pct_yes
##                                                  <chr> <int>     <dbl>
##1                                              Zanzibar     2 0.0000000
##2                              United States of America  5390 0.2836735
##3                                                 Palau   896 0.3225446
##4                                                Israel  4944 0.3460761
##5                           Federal Republic of Germany  2067 0.3962264
##6                      Micronesia (Federated States of)  1462 0.4138167
##7  United Kingdom of Great Britain and Northern Ireland  5372 0.4285182
##8                                                France  5325 0.4336150
##9                                      Marshall Islands  1600 0.4893750
##10                                              Belgium  5391 0.4952699
### ... with 190 more rows
{% endhighlight %}

### Percentage yes vote high countries and years

{% highlight r %}
join1 <- un_votes %>% inner_join(un_roll_calls, by = 'rcid')
by_country_year <- join1 %>% group_by(country, year=year(date)) %>% summarise(votes=n(), pct_yes = mean(vote=='yes'))
arrange(by_country_year, desc(pct_yes))
{% endhighlight %}

{% highlight text %}
##Source: local data frame [9,689 x 4]
##Groups: country [200]

##       country  year votes pct_yes
##         <chr> <dbl> <int>   <dbl>
##1  Afghanistan  2002    40       1
##2  Afghanistan  2004    58       1
##3      Albania  1990    83       1
##4       Angola  1976     4       1
##5       Angola  1977    50       1
##6   Azerbaijan  2013    56       1
##7      Bahrain  1990    86       1
##8      Bahrain  1991    73       1
##9      Bahrain  1992    70       1
##10     Bahrain  1993    60       1
# ... with 9,679 more rows
{% endhighlight %}

### Percentage yes vote low countries and years

{% highlight r %}
by_country_year[order(by_country_year$pct_yes),]
{% endhighlight %}

{% highlight text %}
##Source: local data frame [9,689 x 4]
##Groups: country [200]

##                            country  year votes    pct_yes
##                              <chr> <dbl> <int>      <dbl>
##1  Democratic Republic of the Congo  1998     1 0.00000000
##2                            Jordan  1955     6 0.00000000
##3                           Liberia  1998     1 0.00000000
##4                      South Africa  1974     2 0.00000000
##5                             Spain  1955     5 0.00000000
##6                         Sri Lanka  1955     5 0.00000000
##7                        Yugoslavia  1992     2 0.00000000
##8                          Zanzibar  1963     2 0.00000000
##9          United States of America  1989   115 0.08695652
##10         United States of America  1988   134 0.09701493
### ... with 9,679 more rows
{% endhighlight %}

### Let's look at three countries - Canada, US and UK's "Yes" vote trend in percent over year.

{% highlight r %}
countries <- c('Canada', 'United States of America', 'United Kingdom of Great Britain and Northern Ireland')
by_country_year %>% filter(country %in% countries) %>%
  ggplot(aes(x=year, y=pct_yes, color=country)) + geom_line() +
  ylab("% of votes are 'Yes'") + ggtitle("Trend in percentage Yes Votes of Canada, US and UK 1946-2015") + theme_bw()
{% endhighlight %}

![vote-1](/figs/2017-06-20-Voting-Data/vote-1.png)

### Let's look at those six issues, how were they voted overtime by the above three countries?

{% highlight r %}
join1 %>% filter(country %in% countries) %>%
  inner_join(un_roll_call_issues, by='rcid') %>%
  group_by(year=year(date), country, issue) %>%
  summarise(votes=n(), pct_yes=mean(vote=='yes')) %>%
  ggplot(aes(x=year, y=pct_yes, color=country)) +
  geom_point() +
  geom_smooth(se=FALSE) + facet_wrap(~issue) + ylab("% of votes are 'Yes'") +
  ggtitle('Trend in Percentage Yes Votes by Issues for Canada, US and UK')
{% endhighlight %}

![vote-2](/figs/2017-06-20-Voting-Data/vote-2.png)

### Among these three countries, which countries voted "yes" the most and the least for what issues?

{% highlight r %}
join2 <- join1 %>% filter(country %in% countries) %>%
  inner_join(un_roll_call_issues, by='rcid') %>%
  group_by(country, issue) %>%
  summarise(votes=n(), pct_yes=mean(vote=='yes'))

ggplot(aes(x=country, y=pct_yes, fill = issue), data = join2) + geom_bar(stat = 'identity', position = position_dodge()) + ggtitle('Canada, US, UK and the UN Issues')
{% endhighlight %}

![vote-3](/figs/2017-06-20-Voting-Data/vote-3.png)

### Let's try to estimate the probability of these three countries' changes in voting yes to the UN issues(i.e.whether there is a correlation between trend in year and percentage yes vote')

{% highlight r %}
us_by_year <- by_country_year %>% filter(country=='United States of America')
ca_by_year <- by_country_year %>% filter(country=='Canada')
uk_by_year <- by_country_year %>% filter(country=='United Kingdom of Great Britain and Northern Ireland')
us_model <- lm(pct_yes ~ year, data=us_by_year)
ca_model <- lm(pct_yes ~ year, data=ca_by_year)
uk_model <- lm(pct_yes ~ year, data = uk_by_year)
us_prob <- tidy(us_model) %>% filter(term=='year')
ca_prob <- tidy(ca_model) %>% filter(term=='year')
uk_prob <- tidy(uk_model) %>% filter(term=='year')
us_prob
ca_prob
uk_prob
{% endhighlight %}

{% highlight text %}
##us_prob
##  term     estimate    std.error statistic      p.value
##1 year -0.007103352 0.0006991439 -10.16007 3.357004e-15
##  ca_prob
##  term      estimate    std.error  statistic   p.value
##1 year -0.0001975947 0.0006603795 -0.2992139 0.7657031
##  uk_prob
##  term   estimate    std.error statistic  p.value
##1 year 0.00103754 0.0007739133  1.340641 0.184565
{% endhighlight %}

### Interpretation of the results

* For the USA, the probablity of voting yes to UN issues will decrease 0.0071 percent in the coming years; trend in year and percentage yes vote are highly correlated.
* For Canada, the probability of voting yes to UN issues will decrease 0.0002 percent in the coming years, and there is no correlation between trend in year and percentage yes vote.
* For the UK, the probability of voting yes to UN issues will decrease 0.001 percent in the coming years, and there is no correlation between trend in year and percentage yes vote.

### The End

I realized that this package allows me to perform several statistical analysises including linear regression, logistic regression and I will save it to the next time.


text:
{% extends "base.html" %}

{% block title %} Categories and topics {{block.super}} {% endblock %}

{% block content %}

Categories and topics

                    GroundUp articles are given exactly one category and one or
                    more topics. Here is first a list of all categories and then
                    a list of all topics.

Categories

		    {% for category in categories %}
                        {% with total=category.article_set.published.count %}
                            {% if total > 0 %}

				        {{ category.name|upper }}

                                    ({{total}} article{{total|pluralize}})

                            {% endif %}
                        {% endwith %}
		    {% endfor %}

Topics

		    {% for topic in object_list %}
                        {% with total=topic.article_set.published.count %}
                            {% if total > 0 %}

				        {{ topic.name|upper }}

                                    ({{total}} article{{total|pluralize}})

                            {% endif %}
                        {% endwith %}
		    {% endfor %}

{% endblock %}


text:
package com.qycloud.oatos.convert.domain.logic;

import com.conlect.oatos.dto.client.ConferenceDocDTO;
import com.conlect.oatos.dto.client.FileDTO;
import com.conlect.oatos.dto.client.doc.DocConvertDTO;
import com.conlect.oatos.dto.status.CommConstants;
import com.conlect.oatos.file.DiskUtil;
import com.conlect.oatos.file.ServerInnerUrl;
import com.conlect.oatos.http.PojoMapper;
import com.conlect.oatos.http.XhrProxy;
import com.qycloud.oatos.convert.PDFUtil;
import com.qycloud.oatos.convert.Pdf2SwfThread;
import com.qycloud.oatos.convert.SwfTools;
import com.qycloud.oatos.convert.util.ConfigUtil;

/**
 * swf转换任务
 * @author yang
 *
 */
public class SwfConvertTask extends ConvertTask {

	public SwfConvertTask(DocConvertDTO docDTO) {
		super(docDTO);
	}

	@Override
	protected void doConvert(DocConvertDTO docDTO) throws Exception {
		int start = docDTO.getStartPage();
		if (start <= 0) {
			start = 1;
		}
		// 开始页数
		start = ((start - 1) / CommConstants.PDF_SPLIT_PAGES) * CommConstants.PDF_SPLIT_PAGES + 1;
		// 结束页数
		int end = start + CommConstants.PDF_SPLIT_PAGES - 1;

		String pdfPath = docDTO.getDiskRootPath() + docDTO.getPdfPath();
		Integer pageCount = docDTO.getPageCount();
		if (pageCount == null || pageCount < 1) {
			// 获取pdf总页数
			pageCount = PDFUtil.getPageCount(pdfPath);
			// 更新总页数至数据库
			docDTO.setPageCount(pageCount);
			updatePageCount(docDTO);

			if (start > pageCount) {
				return ;
			}
		}
		// swf文件地址
		String swfPath = docDTO.getDiskRootPath() + DiskUtil.getSplitSwfPath(docDTO.getTargetPath(), start);
		// 转换pdf为swf
		SwfTools.pdfToSwf(pdfPath, swfPath, start, end);

		if (pageCount > 0 && start + CommConstants.PDF_SPLIT_PAGES <= pageCount) {
			// 开启一个线程,转换所有页数
			docDTO.setStartPage(start);
			Pdf2SwfThread thread = new Pdf2SwfThread(docDTO);
			thread.start();
		}
	}

	/**
	 * 更新文件总页数到数据库
	 * @param doc
	 */
	private void updatePageCount(DocConvertDTO doc) {
		if (doc.getFileId() != null) {
			if (CommConstants.FILE_TYPE_SHAREDISK.equals(doc.getFileType())
					|| CommConstants.FILE_TYPE_ONLINEDISK.equals(doc.getFileType())) {
				// 企业网盘或个人网盘文件
				FileDTO fileDTO = new FileDTO();
				fileDTO.setFileId(doc.getFileId());
				fileDTO.setPageCount(doc.getPageCount());
				fileDTO.setType(doc.getFileType());
				String postData = PojoMapper.toJson(fileDTO);
				XhrProxy.getInstance().post(ConfigUtil.getServiceUrl(ServerInnerUrl.updateFilePageCount), doc.getToken(), postData);
			} else if (CommConstants.FILE_TYPE_CONFERENCE_DOC.equals(doc.getFileType())) {
				// 视频会议文档
				ConferenceDocDTO docDTO = new ConferenceDocDTO();
				docDTO.setFileId(doc.getFileId());
				docDTO.setPageCount(doc.getPageCount());
				String postData = PojoMapper.toJson(docDTO);
				XhrProxy.getInstance().post(ConfigUtil.getServiceUrl(ServerInnerUrl.updateConferenceDocPageCount), doc.getToken(), postData);
			}
		}
	}

}