text:
<?xml version="1.0" encoding="utf-8"?>
<rsp stat="ok">
<photo id="34394586825" secret="375e0b1706" server="4169" farm="5" dateuploaded="1493683350" isfavorite="0" license="7" safety_level="0" rotation="0" originalsecret="d46e9b19cc" originalformat="jpg" views="499" media="photo">
	<owner nsid="49487266@N07" username="San Diego Air & Space Museum Archives" realname="SDASM Archives" location="" iconserver="4070" iconfarm="5" path_alias="sdasmarchives"/>
	<title>Ryan Aeronautical Image</title>
	<description>PictionID:56100666 - Catalog:C87-047-040.tif - Title:Ryan Aeronautical Negative Collection Image - Filename:C87-047-040.tif - - Image from the Teledyne Ryan Archives, donated to SDASM in the 1990s. Many of these images are from Ryan's UAV program-----Please Tag these images so that the information can be permanently stored with the digital file.---Repository: <a href="http://www.sandiegoairandspace.org/library/stillimages.html" rel="nofollow">San Diego Air and Space Museum </a></description>
	<visibility ispublic="1" isfriend="0" isfamily="0"/>
	<dates posted="1493683350" taken="2017-05-01 17:02:30" takengranularity="0" takenunknown="1" lastupdate="1493683351"/>
	<editability cancomment="0" canaddmeta="0"/>
	<publiceditability cancomment="1" canaddmeta="1"/>
	<usage candownload="1" canblog="0" canprint="0" canshare="1"/>
	<comments>0</comments>
    <notes>
    <note id="313" author="12037949754@N01" authorname="Bees" x="10" y="10" w="50" h="50">foo</note>
    </notes>
    <tags>
      <tag id="1234" author="12037949754@N01" raw="woo yay">wooyay</tag>
      <tag id="1235" author="12037949754@N01" raw="hoopla">hoopla</tag>
    </tags>
	<people haspeople="0"/>
	<urls>
		<url type="photopage">https://www.flickr.com/photos/sdasmarchives/34394586825/</url>
	</urls>
</photo>
</rsp>


text:
@implementation TZWNews

+ (instancetype)newsWithDict:(NSDictionary *)dict {
    id obj = [[self alloc] init];

    [obj setValuesForKeysWithDictionary:dict];

    return obj;
}

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{}

+(void)loadNewsWithUrlString:(NSString *)UrlString success:(void(^)(NSArray *))success
                      failed:(void (^)(NSError *))failed{
    [[TZWNetworkTool shareNetworkTool]GET:UrlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        NSString *rootKey=responseObject.keyEnumerator.nextObject;

        NSArray *news=responseObject[rootKey];

        NSMutableArray *arrayM=[NSMutableArray arrayWithCapacity:news.count];
        [news enumerateObjectsUsingBlock:^(NSDictionary  *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            TZWNews *new=[TZWNews newsWithDict:obj];
            [arrayM addObject:new];
        }];
        success(arrayM.copy);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failed) {
            failed(error);
        }
    }];
}

@end

redpajama_set_name: RedPajamaGithub


text:
export KSROOT=/koolshare
source $KSROOT/scripts/base.sh
eval `dbus export bridge`

confs=`dbus list bridge|cut -d "=" -f1`

for conf in $confs
do
	dbus remove $conf
done

sleep 1
rm -rf $KSROOT/scripts/bridge*
rm -rf $KSROOT/webs/Module_bridge.asp
rm -rf $KSROOT/webs/res/icon-bridge.png
rm -rf $KSROOT/webs/res/icon-bridge-bg.png

dbus remove softcenter_module_bridge_home_url
dbus remove softcenter_module_bridge_install
dbus remove softcenter_module_bridge_md5
dbus remove softcenter_module_bridge_version
dbus remove softcenter_module_bridge_name
dbus remove softcenter_module_bridge_description

rm -rf $KSROOT/scripts/uninstall_bridge.sh


text:
package org.apache.calcite.rel.rules;

import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.logical.LogicalFilter;
import org.apache.calcite.rel.logical.LogicalTableFunctionScan;
import org.apache.calcite.rel.metadata.RelColumnMapping;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Planner rule that pushes
 * a {@link org.apache.calcite.rel.logical.LogicalFilter}
 * past a {@link org.apache.calcite.rel.logical.LogicalTableFunctionScan}.
 */
public class FilterTableFunctionTransposeRule extends RelOptRule {
  public static final FilterTableFunctionTransposeRule INSTANCE =
      new FilterTableFunctionTransposeRule();

  //~ Constructors -----------------------------------------------------------

  /**
   * Creates a FilterTableFunctionTransposeRule.
   */
  private FilterTableFunctionTransposeRule() {
    super(
        operand(LogicalFilter.class,
            operand(LogicalTableFunctionScan.class, any())));
  }

  //~ Methods ----------------------------------------------------------------

  // implement RelOptRule
  public void onMatch(RelOptRuleCall call) {
    LogicalFilter filter = call.rel(0);
    LogicalTableFunctionScan funcRel = call.rel(1);
    Set<RelColumnMapping> columnMappings = funcRel.getColumnMappings();
    if (columnMappings == null || columnMappings.isEmpty()) {
      // No column mapping information, so no push-down
      // possible.
      return;
    }

    List<RelNode> funcInputs = funcRel.getInputs();
    if (funcInputs.size() != 1) {
      // TODO:  support more than one relational input; requires
      // offsetting field indices, similar to join
      return;
    }
    // TODO:  support mappings other than 1-to-1
    if (funcRel.getRowType().getFieldCount()
        != funcInputs.get(0).getRowType().getFieldCount()) {
      return;
    }
    for (RelColumnMapping mapping : columnMappings) {
      if (mapping.iInputColumn != mapping.iOutputColumn) {
        return;
      }
      if (mapping.derived) {
        return;
      }
    }
    final List<RelNode> newFuncInputs = new ArrayList<RelNode>();
    final RelOptCluster cluster = funcRel.getCluster();
    final RexNode condition = filter.getCondition();

    // create filters on top of each func input, modifying the filter
    // condition to reference the child instead
    RexBuilder rexBuilder = filter.getCluster().getRexBuilder();
    List<RelDataTypeField> origFields = funcRel.getRowType().getFieldList();
    // TODO:  these need to be non-zero once we
    // support arbitrary mappings
    int[] adjustments = new int[origFields.size()];
    for (RelNode funcInput : funcInputs) {
      RexNode newCondition =
          condition.accept(
              new RelOptUtil.RexInputConverter(
                  rexBuilder,
                  origFields,
                  funcInput.getRowType().getFieldList(),
                  adjustments));
      newFuncInputs.add(
          new LogicalFilter(cluster, funcInput, newCondition));
    }

    // create a new UDX whose children are the filters created above
    LogicalTableFunctionScan newFuncRel =
        new LogicalTableFunctionScan(
            cluster,
            newFuncInputs,
            funcRel.getCall(),
            funcRel.getElementType(), funcRel.getRowType(),
            columnMappings);
    call.transformTo(newFuncRel);
  }
}

// End FilterTableFunctionTransposeRule.java


text:
angular.module('staff', ['ionic', 'ngResource', 'templates', 'staff.controllers', 'staff.services'])

.run(function($ionicPlatform, $rootScope, $localStorage, $location, $state, $http, $ionicLoading, APIService) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  })

  $rootScope.server_url = $localStorage.get('server_url') || 'http://10.162.168.55:3001'
  $rootScope.connected = $rootScope.connected || false;
  $rootScope.error_message = "No Internet connection or not in the internal SUSE network?"

  $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if(!$rootScope.connected) {
      console.log("Offline")

      APIService.status($rootScope.server_url).finally(function() {
        if($rootScope.connected) {
          $state.transitionTo('tab.employees');
        } else {
          $state.transitionTo('tab.status');
        }
      });
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider.state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: "tabs.html"
  })

  .state('tab.status', {
    url: '/status',
    views: {
      'tab-status': {
        templateUrl: 'tab-status.html',
        controller: 'StatusCtrl'
      }
    }
  })

  .state('tab.employees', {
      url: '/employees',
      views: {
        'tab-employees': {
          templateUrl: 'tab-employees.html',
          controller: 'EmployeesCtrl'
        }
      }
  })

  .state('tab.employee-detail', {
    url: '/employees/:employeeId',
    views: {
      'tab-employees': {
        templateUrl: 'employee-detail.html',
        controller: 'EmployeeDetailCtrl'
      }
    }
  })

  .state('tab.team', {
    url: '/employees/:employeeId/team',
    views: {
      'tab-employees': {
        templateUrl: 'team.html',
        controller: 'TeamMembersCtrl'
      }
    }
  })

  .state('tab.newcomers', {
    url: '/newcomers',
    views: {
      'tab-newcomers': {
        templateUrl: 'tab-newcomers.html',
        controller: 'NewcomersCtrl'
      }
    }
  })

  .state('tab.newcomer-detail', {
    url: '/newcomers/:employeeId',
    views: {
      'tab-newcomers': {
        templateUrl: 'employee-detail.html',
        controller: 'EmployeeDetailCtrl'
      }
    }
  })

  .state('tab.apprentices', {
    url: '/apprentices',
    views: {
      'tab-apprentices': {
        templateUrl: 'tab-apprentices.html',
        controller: 'ApprenticesCtrl'
      }
    }
  })

  .state('tab.apprentices-detail', {
    url: '/apprentices/:employeeId',
    views: {
      'tab-apprentices': {
        templateUrl: 'employee-detail.html',
        controller: 'EmployeeDetailCtrl'
      }
    }
  })

  $urlRouterProvider.otherwise('/tab/employees');
});


text:
#ifndef PHP_SOCKETS_H
#define PHP_SOCKETS_H

/* $Id$ */

#if HAVE_SOCKETS

extern zend_module_entry sockets_module_entry;
#define phpext_sockets_ptr &sockets_module_entry

#ifdef PHP_WIN32
#include <winsock.h>
#else
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#endif

#ifndef PHP_WIN32
typedef int PHP_SOCKET;
# define PHP_SOCKETS_API PHPAPI
#else
# define PHP_SOCKETS_API __declspec(dllexport)
typedef SOCKET PHP_SOCKET;
#endif

typedef struct {
	PHP_SOCKET	bsd_socket;
	int			type;
	int			error;
	int			blocking;
	zval		*zstream;
} php_socket;

#ifdef PHP_WIN32
struct	sockaddr_un {
	short	sun_family;
	char	sun_path[108];
};
#endif

PHP_SOCKETS_API int php_sockets_le_socket(void);

#define php_sockets_le_socket_name "Socket"

ZEND_BEGIN_MODULE_GLOBALS(sockets)
	int last_error;
	char *strerror_buf;
ZEND_END_MODULE_GLOBALS(sockets)

#ifdef ZTS
#define SOCKETS_G(v) TSRMG(sockets_globals_id, zend_sockets_globals *, v)
#else
#define SOCKETS_G(v) (sockets_globals.v)
#endif

#else
#define phpext_sockets_ptr NULL
#endif

#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 */


text:
////////////////////////////////////////////////////////////////////////////////
//
// Customized itkSubsampledImageRegionIteratorWithIndex
//
// Supports offsets for doing subsampling
//
////////////////////////////////////////////////////////////////////////////////

#ifndef __SubsampledImageRegionIterator_h
#define __SubsampledImageRegionIterator_h

#include "itkImageRegionConstIteratorWithIndex.h"

template<typename TImage>
class SubsampledImageRegionIterator:
  public itk::ImageRegionConstIteratorWithIndex<TImage>
{
public:
  /** Standard class typedefs. */
  typedef SubsampledImageRegionIterator Self;
  typedef itk::ImageRegionConstIteratorWithIndex<TImage>  Superclass;

  /** Types inherited from the Superclass */
  typedef typename Superclass::IndexType              IndexType;
  typedef typename Superclass::IndexValueType         IndexValueType;
  typedef typename Superclass::SizeType               SizeType;
  typedef typename Superclass::SizeValueType          SizeValueType;
  typedef typename Superclass::OffsetType             OffsetType;
  typedef typename Superclass::OffsetValueType        OffsetValueType;
  typedef typename Superclass::RegionType             RegionType;
  typedef typename Superclass::ImageType              ImageType;
  typedef typename Superclass::PixelContainer         PixelContainer;
  typedef typename Superclass::PixelContainerPointer  PixelContainerPointer;
  typedef typename Superclass::InternalPixelType      InternalPixelType;
  typedef typename Superclass::PixelType              PixelType;
  typedef typename Superclass::AccessorType           AccessorType;

  /** Constructor establishes an iterator to walk a particular image and a
   * particular region of that image. */
  SubsampledImageRegionIterator(TImage *ptr, const RegionType& region, double sampleSpacing);

  /** Set the pixel value */
  void Set( const PixelType & value) const
    { this->m_PixelAccessorFunctor.Set(*(const_cast<InternalPixelType *>(this->m_Position)),value); }

  /** Return a reference to the pixel
   * This method will provide the fastest access to pixel
   * data, but it will NOT support ImageAdaptors. */
  PixelType & Value(void)
    { return *(const_cast<InternalPixelType *>(this->m_Position)); }

  void GoToBegin();
  void GoToReverseBegin();

  // Override the walk operators
  Self& operator++();
  Self& operator--();

  // Make sure that locations are snapped to the subsampled grid
  void SnapToGrid();

protected:

  OffsetType m_Skips;
  IndexType m_SnappedEndIndex;

};

#ifndef MU_MANUAL_INSTANTIATION
#include "SubsampledImageRegionIterator.txx"
#endif

#endif


text:
using Microsoft.AspNetCore.Http;

namespace Aspose.Slides.Web.API.Models
{
	public class UploadRequest
	{
		public IFormFileCollection UploadFileInput { get; set; }

		public string idUpload { get; set; }
	}
}


text:
'use strict';

import HtmlContent = require('vs/base/common/htmlContent');
import Strings = require('vs/base/common/strings');
import WinJS = require('vs/base/common/winjs.base');
import nls = require('vs/nls');
import JSONWorker = require('vs/languages/json/common/jsonWorker');
import {IRequestService} from 'vs/platform/request/common/request';
import URI from 'vs/base/common/uri';
import {JSONLocation} from 'vs/languages/json/common/parser/jsonLocation';

export class BowerJSONContribution implements JSONWorker.IJSONWorkerContribution {

	private requestService : IRequestService;

	private topRanked = ['twitter','bootstrap','angular-1.1.6','angular-latest','angulerjs','d3','myjquery','jq','abcdef1234567890','jQuery','jquery-1.11.1','jquery',
		'sushi-vanilla-x-data','font-awsome','Font-Awesome','font-awesome','fontawesome','html5-boilerplate','impress.js','homebrew',
		'backbone','moment1','momentjs','moment','linux','animate.css','animate-css','reveal.js','jquery-file-upload','blueimp-file-upload','threejs','express','chosen',
		'normalize-css','normalize.css','semantic','semantic-ui','Semantic-UI','modernizr','underscore','underscore1',
		'material-design-icons','ionic','chartjs','Chart.js','nnnick-chartjs','select2-ng','select2-dist','phantom','skrollr','scrollr','less.js','leancss','parser-lib',
		'hui','bootstrap-languages','async','gulp','jquery-pjax','coffeescript','hammer.js','ace','leaflet','jquery-mobile','sweetalert','typeahead.js','soup','typehead.js',
		'sails','codeigniter2'];

	public constructor(@IRequestService requestService: IRequestService) {
		this.requestService = requestService;
	}

	private isBowerFile(resource: URI): boolean {
		var path = resource.path;
		return Strings.endsWith(path, '/bower.json') || Strings.endsWith(path, '/.bower.json');
	}

	public collectDefaultSuggestions(resource: URI, result: JSONWorker.ISuggestionsCollector): WinJS.Promise {
		if (this.isBowerFile(resource)) {
			var defaultValue = {
				'name': '{{name}}',
				'description': '{{description}}',
				'authors': [ '{{author}}' ],
				'version': '{{1.0.0}}',
				'main': '{{pathToMain}}',
				'dependencies': {}
			};
			result.add({ type: 'snippet', label: nls.localize('json.bower.default', 'Default bower.json'), codeSnippet: JSON.stringify(defaultValue, null, '\t'), documentationLabel: '' });
		}
		return null;
	}

	public collectPropertySuggestions(resource: URI, location: JSONLocation, currentWord: string, addValue: boolean, isLast:boolean, result: JSONWorker.ISuggestionsCollector) : WinJS.Promise {
		if (this.isBowerFile(resource) && (location.matches(['dependencies']) || location.matches(['devDependencies']))) {
			if (currentWord.length > 0) {
				var queryUrl = 'https://bower.herokuapp.com/packages/search/' + encodeURIComponent(currentWord);

				return this.requestService.makeRequest({
					url : queryUrl
				}).then((success) => {
					if (success.status === 200) {
						try {
							var obj = JSON.parse(success.responseText);
							if (Array.isArray(obj)) {
								var results = <{name:string; description:string;}[]> obj;
								for (var i = 0; i < results.length; i++) {
									var name = results[i].name;
									var description = results[i].description || '';
									var codeSnippet = JSON.stringify(name);
									if (addValue) {
										codeSnippet += ': "{{*}}"';
										if (!isLast) {
											codeSnippet += ',';
										}
									}
									result.add({ type: 'property', label: name, codeSnippet: codeSnippet, documentationLabel: description });
								}
								result.setAsIncomplete();
							}
						} catch (e) {
							// ignore
						}
					} else {
						result.error(nls.localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', success.responseText));
						return 0;
					}
				}, (error) => {
					result.error(nls.localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', error.responseText));
					return 0;
				});
			} else {
				this.topRanked.forEach((name) => {
					var codeSnippet = JSON.stringify(name);
					if (addValue) {
						codeSnippet += ': "{{*}}"';
						if (!isLast) {
							codeSnippet += ',';
						}
					}
					result.add({ type: 'property', label: name, codeSnippet: codeSnippet, documentationLabel: '' });
				});
				result.setAsIncomplete();
			}
		}
		return null;
	}

	public collectValueSuggestions(resource: URI, location: JSONLocation, currentKey: string, result: JSONWorker.ISuggestionsCollector): WinJS.Promise {
		// not implemented. Could be do done calling the bower command. Waiting for web API: https://github.com/bower/registry/issues/26
		return null;
	}

	public getInfoContribution(resource: URI, location: JSONLocation): WinJS.TPromise<HtmlContent.IHTMLContentElement[]> {
		if (this.isBowerFile(resource) && (location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']))) {
			var pack = location.getSegments()[location.getSegments().length - 1];
			var htmlContent : HtmlContent.IHTMLContentElement[] = [];
			htmlContent.push({className: 'type', text: nls.localize('json.bower.package.hover', '{0}', pack) });

			var queryUrl = 'https://bower.herokuapp.com/packages/' + encodeURIComponent(pack);

			return this.requestService.makeRequest({
				url : queryUrl
			}).then((success) => {
				try {
					var obj = JSON.parse(success.responseText);
					if (obj && obj.url) {
						var url = obj.url;
						if (Strings.startsWith(url, 'git://')) {
							url = url.substring(6);
						}
						if (Strings.endsWith(url, '.git')) {
							url = url.substring(0, url.length - 4);
						}
						htmlContent.push({className: 'documentation', text: url });
					}
				} catch (e) {
					// ignore
				}
				return htmlContent;
			}, (error) => {
				return htmlContent;
			});
		}
		return null;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        tools:ignore="HardcodedText"
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:minWidth="@dimen/schedule_time_min_width"
        android:orientation="vertical"
        android:padding="@dimen/schedule_time_padding">

        <TextView
            android:id="@+id/lesson_time_start"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxWidth="@dimen/schedule_time_max_width"
            android:gravity="bottom"
            android:text="10:00"
            android:textAlignment="center"
            android:textColor="?android:attr/textColorPrimary"
            android:textSize="@dimen/font_size_15" />

        <ImageView
            android:id="@+id/lesson_time_icon"
            android:layout_width="match_parent"
            android:layout_height="@dimen/dimen_16dp"
            android:src="@drawable/ic_access_time"
            android:tint="?android:attr/textColorPrimary"/>

        <TextView
            android:id="@+id/lesson_time_end"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxWidth="@dimen/schedule_time_max_width"
            android:gravity="top"
            android:text="10:00"
            android:textAlignment="center"
            android:textColor="?android:attr/textColorPrimary"
            android:textSize="@dimen/font_size_15" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/data"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:paddingTop="@dimen/schedule_data_padding_top"
        android:paddingBottom="@dimen/schedule_data_padding_bottom"
        android:paddingStart="0dp"
        android:paddingEnd="@dimen/schedule_data_padding_end">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/lesson_title"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:paddingEnd="4dp"
                android:paddingStart="0dp"
                android:text="@string/lorem_ipsum"
                android:textColor="?android:attr/textColorPrimary"
                android:textSize="@dimen/font_size_14"
                android:ellipsize="end" />

            <ImageView
                android:id="@+id/lesson_reduced_icon"
                android:layout_width="@dimen/schedule_data_icon"
                android:layout_height="@dimen/schedule_data_icon"
                android:padding="2dp"
                android:src="@drawable/ic_visibility_off"
                android:tint="?android:attr/textColorPrimary" />

            <ImageView
                android:id="@+id/lesson_synthetic_icon"
                android:layout_width="@dimen/schedule_data_icon"
                android:layout_height="@dimen/schedule_data_icon"
                android:padding="2dp"
                android:src="@drawable/ic_synthetic"
                android:tint="?android:attr/textColorPrimary" />

            <ImageView
                android:id="@+id/lesson_touch_icon"
                android:layout_width="@dimen/schedule_data_icon"
                android:layout_height="@dimen/schedule_data_icon"
                android:src="@drawable/ic_more_vert"
                android:tint="?android:attr/textColorPrimary"
                android:background="?android:attr/selectableItemBackgroundBorderless" />

        </LinearLayout>

        <TextView
            android:id="@+id/lesson_desc"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:text="@string/lorem_ipsum"
            android:textColor="?android:attr/textColorSecondary"
            android:textSize="@dimen/font_size_14" />

        <LinearLayout
            android:id="@+id/lesson_flags"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" />

        <TextView
            android:id="@+id/lesson_meta"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:text="@string/lorem_ipsum"
            android:textColor="?android:attr/textColorSecondary"
            android:textSize="@dimen/font_size_14" />

    </LinearLayout>

</LinearLayout>


text:
<TITLE>Review for Waxwork II: Lost in Time (1992)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Waxwork II: Lost in Time (1992)

reviewed by
Brian L. Johnson

                          Two Horror Film Reviews
                      Two film reviews by Ken Johnson
                        Copyright 1992 Ken Johnson

     I was just going to review the new film WAXWORK 2: LOST IN TIME,
but I figured while I was at it I might as well write one for WAXWORK as
well, so here goes...

                                  WAXWORK
100 min., not rated, Horror, 1988
Director: Anthony Hickox
Cast: Zach Galligan, Deborah Foreman, Michelle Johnson, Dana Ashbrook,
      Miles O'Keeffe, Charles McCaughtan, J. Kenneth Campbell,
      John Rhys-Davies, Patrick McNee, David Warner

     Deborah Foreman and Michelle Johnson get invited to the premiere
opening of a wax museum run by David Warner.  Warner tells them that the
showing is at midnight and they can bring four friends with them.
Johnson and Foreman invite four friends but two chicken out.  The two
remaining are Zach Galligan and Dana Ashbrook.  Galligan and Foreman
leave after they find out that Ashbrook and Johnson had left the wax
museum, but the next morning Galligan and Foreman find out that Ashbrook
and Johnson never got home.  Galligan suspects that they never left the
waxwork and finds out that Warner is trying to bring hell to Earth.

     WAXWORK is an excellent horror film with a neat new idea (at least
I haven't seen it before).  I highly recommend that you see this film;
it is definitely worth a rental.  On a scale of zero to five, I give
WAXWORK a four.  WAXWORK is not rated but contains explicit language,
violence, and adult situations.   There is also an R rated version of
WAXWORK out, but the only version I have been able to see, or find for
that matter, is the unrated uncensored version.  There is nothing really
bad in the uncensored version so I would recommend that you watch that
one for it will contain more than the R rated version, at least that is
what I would assume.

     The part that I like the most about WAXWORK is how it combines old
horror films with this new one.  I like the idea of when a person walks
into an exhibit they get transported into a world where that exhibit is
going on.  It is also interesting that some of the worlds, like the
NIGHT OF THE LIVING DEAD exhibit, are in black and white, like in the
original version.

     The sets are very well done, and look like the films that they are
pretending to be.  The script is very well written and the acting is
great.  Most of the people in this film end up with cameos because they
are only in one waxwork exhibit.

                          WAXWORK 2: LOST IN TIME
104 min., R, Horror/Science Fiction/Comedy, 1991
Director: Anthony Hickox
Cast: Zach Galligan, Monika Schnarre, Martin Kemp, Bruce Campbell,
      Michael Des Barres, Jim Metzler, Sophie Ward, Marina Sirtis,
      Billy Kane, Joe Baker, Juliet Mills, John Ireland,
      Patrick Macnee, David Carradine, Alexander Godunov,
      Kate Murtagh, Drew Barrymore

The opening paragraph contains spoilers for WAXWORK.

     This sequel to WAXWORK starts off right where WAXWORK left off with
Zach Galligan and Monika Schnarre (played in WAXWORK by Deborah Foreman)
leaving the burning waxwork.  Schnarre is put on trial for the murder of
her father, which was really done by a zombie hand that escaped from the
waxwork.  Galligan finds a time key, that allows you to travel forward
or backwards in time, and they try to travel back in time to try to
prove that such thing as a zombie hand could exist.

     WAXWORK 2 is, I feel, just as good as WAXWORK and a true sequel.
Unlike the first film, the idea for this one is a bit recycled, the last
time I remember this idea being used was in BILL AND TED'S EXCELLENT
ADVENTURE, but it is still fun to watch.   Before watching this film, I
suggest you should watch, or re- watch, WAXWORK because it is important
to remember what happened in the first film.  In fact, the ending scenes
of WAXWORK are the opening scenes for this one to remind you what
happened at the end.  On a scale of zero to five, I give WAXWORK 2 a
four.   WAXWORK 2 is rated R for explicit language, adult situations,
and violence.

     WAXWORK was, what I thought, a film that would be impossible to
make a true sequel to.  I consider a true sequel to be a film that
continues a story.  Like SHOCK TREATMENT was not a true sequel to THE
ROCKY HORROR PICTURE SHOW but POLICE ACADEMY 2: THEIR FIRST ASSIGNMENT
was a true sequel to POLICE ACADEMY.   WAXWORK 2 is a true sequel, and I
feel that it is just as good as the original film (something that is
very rare).  I hope that there will be no more WAXWORK films because I
don't think they could make another good one, but I may be wrong.

     It took me a while to rent WAXWORK 2 because my local video store
was out every time I went in.  I am glad that I finally got to see it
for I definitely think it is worth watching.  Unlike WAXWORK this film
is partially a spoof of horror films.  The climatic sword fight through
monster films is priceless, and I feel it is worth watching the film for
that if nothing else.

     The film was very well written and well acted.  Many of the actors
have cameos because they are in one scenario and not in others, but they
all do a good job.  The cinematography was great.  I especially liked
the parts where, when the people went into old films, the picture became
black and white.  The sets were very well done and all together the film
is technically above most horror films today.

Ken J.
blj@mithrandir.cs.unh.edu

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?php

/**
 * @namespace
 */
namespace Zend\Pdf\Destination;
use Zend\Pdf\InternalType;
use Zend\Pdf;

/**
 * \Zend\Pdf\Destination\FitBoundingBox explicit detination
 *
 * Destination array: [page /FitB]
 *
 * (PDF 1.1) Display the page designated by page, with its contents magnified
 * just enough to fit its bounding box entirely within the window both horizontally
 * and vertically. If the required horizontal and vertical magnification
 * factors are different, use the smaller of the two, centering the bounding box
 * within the window in the other dimension.
 *
 * @uses       \Zend\Pdf\Destination\Explicit
 * @uses       \Zend\Pdf\InternalType\ArrayObject
 * @uses       \Zend\Pdf\InternalType\NameObject
 * @uses       \Zend\Pdf\InternalType\NumericObject
 * @uses       \Zend\Pdf\Exception
 * @package    Zend_PDF
 * @subpackage Zend_PDF_Destination
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class FitBoundingBox extends Explicit
{
    /**
     * Create destination object
     *
     * @param \Zend\Pdf\Page|integer $page  Page object or page number
     * @return \Zend\Pdf\Destination\FitBoundingBox
     * @throws \Zend\Pdf\Exception
     */
    public static function create($page)
    {
        $destinationArray = new InternalType\ArrayObject();

        if ($page instanceof Pdf\Page) {
            $destinationArray->items[] = $page->getPageDictionary();
        } else if (is_integer($page)) {
            $destinationArray->items[] = new InternalType\NumericObject($page);
        } else {
            throw new Pdf\Exception('Page entry must be a Zend_PDF_Page object or a page number.');
        }

        $destinationArray->items[] = new InternalType\NameObject('FitB');

        return new self($destinationArray);
    }
}


text:
reactjs-tutorial
================

Code from the tutorial on React.js - http://facebook.github.io/react/docs/tutorial.html.

It builds a simple ajax comment system using React.js and NodeJS.

## Steps to Run ##

1. `npm install express`
2. `node server.js`
3. visit `localhost:3000/main.html`


text:
#include "BulletCollision/CollisionShapes/btPolyhedralConvexShape.h"
#include "btConvexPolyhedron.h"
#include "LinearMath/btConvexHullComputer.h"
#include <new>

btPolyhedralConvexShape::btPolyhedralConvexShape() :btConvexInternalShape(),
m_polyhedron(0)
{

}

btPolyhedralConvexShape::~btPolyhedralConvexShape()
{
	if (m_polyhedron)
	{
		btAlignedFree(m_polyhedron);
	}
}

bool	btPolyhedralConvexShape::initializePolyhedralFeatures()
{
	if (m_polyhedron)
		btAlignedFree(m_polyhedron);

	void* mem = btAlignedAlloc(sizeof(btConvexPolyhedron),16);
	m_polyhedron = new (mem) btConvexPolyhedron;

	btAlignedObjectArray<btVector3> tmpVertices;
	for (int i=0;i<getNumVertices();i++)
	{
		btVector3& newVertex = tmpVertices.expand();
		getVertex(i,newVertex);
	}

	btConvexHullComputer conv;
	conv.compute(&tmpVertices[0].getX(), sizeof(btVector3),tmpVertices.size(),0.f,0.f);

	btAlignedObjectArray<btVector3> faceNormals;
	int numFaces = conv.faces.size();
	faceNormals.resize(numFaces);
	btConvexHullComputer* convexUtil = &conv;

	m_polyhedron->m_faces.resize(numFaces);
	int numVertices = convexUtil->vertices.size();
	m_polyhedron->m_vertices.resize(numVertices);
	for (int p=0;p<numVertices;p++)
	{
		m_polyhedron->m_vertices[p] = convexUtil->vertices[p];
	}

	for (int i=0;i<numFaces;i++)
	{
		int face = convexUtil->faces[i];
		//printf("face=%d\n",face);
		const btConvexHullComputer::Edge*  firstEdge = &convexUtil->edges[face];
		const btConvexHullComputer::Edge*  edge = firstEdge;

		btVector3 edges[3];
		int numEdges = 0;
		//compute face normals

		//btScalar maxCross2 = 0.f;
		//int chosenEdge = -1;

		do
		{

			int src = edge->getSourceVertex();
			m_polyhedron->m_faces[i].m_indices.push_back(src);
			int targ = edge->getTargetVertex();
			btVector3 wa = convexUtil->vertices[src];

			btVector3 wb = convexUtil->vertices[targ];
			btVector3 newEdge = wb-wa;
			newEdge.normalize();
			if (numEdges<2)
				edges[numEdges++] = newEdge;

			edge = edge->getNextEdgeOfFace();
		} while (edge!=firstEdge);

		btScalar planeEq = 1e30f;

		if (numEdges==2)
		{
			faceNormals[i] = edges[0].cross(edges[1]);
			faceNormals[i].normalize();
			m_polyhedron->m_faces[i].m_plane[0] = -faceNormals[i].getX();
			m_polyhedron->m_faces[i].m_plane[1] = -faceNormals[i].getY();
			m_polyhedron->m_faces[i].m_plane[2] = -faceNormals[i].getZ();
			m_polyhedron->m_faces[i].m_plane[3] = planeEq;

		}
		else
		{
			btAssert(0);//degenerate?
			faceNormals[i].setZero();
		}

		for (int v=0;v<m_polyhedron->m_faces[i].m_indices.size();v++)
		{
			btScalar eq = m_polyhedron->m_vertices[m_polyhedron->m_faces[i].m_indices[v]].dot(faceNormals[i]);
			if (planeEq>eq)
			{
				planeEq=eq;
			}
		}
		m_polyhedron->m_faces[i].m_plane[3] = planeEq;
	}

	if (m_polyhedron->m_faces.size() && conv.vertices.size())
	{

		for (int f=0;f<m_polyhedron->m_faces.size();f++)
		{

			btVector3 planeNormal(m_polyhedron->m_faces[f].m_plane[0],m_polyhedron->m_faces[f].m_plane[1],m_polyhedron->m_faces[f].m_plane[2]);
			btScalar planeEq = m_polyhedron->m_faces[f].m_plane[3];

			btVector3 supVec = localGetSupportingVertex(-planeNormal);

			if (supVec.dot(planeNormal)<planeEq)
			{
				m_polyhedron->m_faces[f].m_plane[0] *= -1;
				m_polyhedron->m_faces[f].m_plane[1] *= -1;
				m_polyhedron->m_faces[f].m_plane[2] *= -1;
				m_polyhedron->m_faces[f].m_plane[3] *= -1;
				int numVerts = m_polyhedron->m_faces[f].m_indices.size();
				for (int v=0;v<numVerts/2;v++)
				{
					btSwap(m_polyhedron->m_faces[f].m_indices[v],m_polyhedron->m_faces[f].m_indices[numVerts-1-v]);
				}
			}
		}
	}

	m_polyhedron->initialize();

	return true;
}

btVector3	btPolyhedralConvexShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
{

	btVector3 supVec(0,0,0);
#ifndef __SPU__
	int i;
	btScalar maxDot(btScalar(-BT_LARGE_FLOAT));

	btVector3 vec = vec0;
	btScalar lenSqr = vec.length2();
	if (lenSqr < btScalar(0.0001))
	{
		vec.setValue(1,0,0);
	} else
	{
		btScalar rlen = btScalar(1.) / btSqrt(lenSqr );
		vec *= rlen;
	}

	btVector3 vtx;
	btScalar newDot;

	for (i=0;i<getNumVertices();i++)
	{
		getVertex(i,vtx);
		newDot = vec.dot(vtx);
		if (newDot > maxDot)
		{
			maxDot = newDot;
			supVec = vtx;
		}
	}

#endif //__SPU__
	return supVec;
}

void	btPolyhedralConvexShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
#ifndef __SPU__
	int i;

	btVector3 vtx;
	btScalar newDot;

	for (i=0;i<numVectors;i++)
	{
		supportVerticesOut[i][3] = btScalar(-BT_LARGE_FLOAT);
	}

	for (int j=0;j<numVectors;j++)
	{

		const btVector3& vec = vectors[j];

		for (i=0;i<getNumVertices();i++)
		{
			getVertex(i,vtx);
			newDot = vec.dot(vtx);
			if (newDot > supportVerticesOut[j][3])
			{
				//WARNING: don't swap next lines, the w component would get overwritten!
				supportVerticesOut[j] = vtx;
				supportVerticesOut[j][3] = newDot;
			}
		}
	}
#endif //__SPU__
}

void	btPolyhedralConvexShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
#ifndef __SPU__
	//not yet, return box inertia

	btScalar margin = getMargin();

	btTransform ident;
	ident.setIdentity();
	btVector3 aabbMin,aabbMax;
	getAabb(ident,aabbMin,aabbMax);
	btVector3 halfExtents = (aabbMax-aabbMin)*btScalar(0.5);

	btScalar lx=btScalar(2.)*(halfExtents.x()+margin);
	btScalar ly=btScalar(2.)*(halfExtents.y()+margin);
	btScalar lz=btScalar(2.)*(halfExtents.z()+margin);
	const btScalar x2 = lx*lx;
	const btScalar y2 = ly*ly;
	const btScalar z2 = lz*lz;
	const btScalar scaledmass = mass * btScalar(0.08333333);

	inertia = scaledmass * (btVector3(y2+z2,x2+z2,x2+y2));
#endif //__SPU__
}

void	btPolyhedralConvexAabbCachingShape::setLocalScaling(const btVector3& scaling)
{
	btConvexInternalShape::setLocalScaling(scaling);
	recalcLocalAabb();
}

btPolyhedralConvexAabbCachingShape::btPolyhedralConvexAabbCachingShape()
:btPolyhedralConvexShape(),
m_localAabbMin(1,1,1),
m_localAabbMax(-1,-1,-1),
m_isLocalAabbValid(false)
{
}

void btPolyhedralConvexAabbCachingShape::getAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax) const
{
	getNonvirtualAabb(trans,aabbMin,aabbMax,getMargin());
}

void	btPolyhedralConvexAabbCachingShape::recalcLocalAabb()
{
	m_isLocalAabbValid = true;

	#if 1
	static const btVector3 _directions[] =
	{
		btVector3( 1.,  0.,  0.),
		btVector3( 0.,  1.,  0.),
		btVector3( 0.,  0.,  1.),
		btVector3( -1., 0.,  0.),
		btVector3( 0., -1.,  0.),
		btVector3( 0.,  0., -1.)
	};

	btVector3 _supporting[] =
	{
		btVector3( 0., 0., 0.),
		btVector3( 0., 0., 0.),
		btVector3( 0., 0., 0.),
		btVector3( 0., 0., 0.),
		btVector3( 0., 0., 0.),
		btVector3( 0., 0., 0.)
	};

	batchedUnitVectorGetSupportingVertexWithoutMargin(_directions, _supporting, 6);

	for ( int i = 0; i < 3; ++i )
	{
		m_localAabbMax[i] = _supporting[i][i] + m_collisionMargin;
		m_localAabbMin[i] = _supporting[i + 3][i] - m_collisionMargin;
	}

	#else

	for (int i=0;i<3;i++)
	{
		btVector3 vec(btScalar(0.),btScalar(0.),btScalar(0.));
		vec[i] = btScalar(1.);
		btVector3 tmp = localGetSupportingVertex(vec);
		m_localAabbMax[i] = tmp[i]+m_collisionMargin;
		vec[i] = btScalar(-1.);
		tmp = localGetSupportingVertex(vec);
		m_localAabbMin[i] = tmp[i]-m_collisionMargin;
	}
	#endif
}


text:
#include "kernel/unification_constraint.h"
#include "kernel/metavar.h"

namespace lean {
unification_constraint_cell::unification_constraint_cell(unification_constraint_kind k, context const & c, justification const & j):
    m_kind(k), m_ctx(c), m_justification(j), m_rc(1) {
}
unification_constraint_cell::~unification_constraint_cell() {
}
void unification_constraint_cell::dealloc() {
    delete this;
}

static format add_context(formatter const & fmt, options const & opts, context const & ctx, format const & body, optional<metavar_env> const & menv) {
    bool unicode     = get_pp_unicode(opts);
    format ctx_fmt   = fmt(instantiate_metavars(menv, ctx), opts);
    format turnstile = unicode ? format("\u22A2") /* ⊢ */ : format("|-");
    return group(format{ctx_fmt, space(), turnstile, line(), body});
}

static format add_justification(formatter const & fmt, options const & opts, format const & body, justification const & jst, pos_info_provider const * p, bool include_justification, optional<metavar_env> const & menv) {
    if (jst && include_justification) {
        unsigned indent  = get_pp_indent(opts);
        return format{body, line(), format("Justification:"), nest(indent, compose(line(), jst.pp(fmt, opts, p, true, menv)))};
    } else {
        return body;
    }
}

static format mk_binary(formatter const & fmt, options const & opts, context const & ctx, expr const & lhs, expr const & rhs, format const & op,
                        optional<metavar_env> const & menv) {
    format lhs_fmt  = fmt(ctx, instantiate_metavars(menv, lhs), false, opts);
    format rhs_fmt  = fmt(ctx, instantiate_metavars(menv, rhs), false, opts);
    return group(format{lhs_fmt, space(), op, line(), rhs_fmt});
}

static format mk_unification_op(options const & opts) {
    bool unicode = get_pp_unicode(opts);
    return unicode ? format("\u2248") /* ≈ */ : format("=?=");
}

unification_constraint_eq::unification_constraint_eq(context const & c, expr const & lhs, expr const & rhs, justification const & j):
    unification_constraint_cell(unification_constraint_kind::Eq, c, j),
    m_lhs(lhs),
    m_rhs(rhs) {
}

unification_constraint_eq::~unification_constraint_eq() {
}

format unification_constraint_eq::pp(formatter const & fmt, options const & opts, pos_info_provider const * p, bool include_justification,
                                     optional<metavar_env> const & menv) const {
    format op   = mk_unification_op(opts);
    format body = mk_binary(fmt, opts, m_ctx, m_lhs, m_rhs, op, menv);
    body = add_context(fmt, opts, m_ctx, body, menv);
    return add_justification(fmt, opts, body, m_justification, p, include_justification, menv);
}

unification_constraint unification_constraint_eq::updt_justification(justification const & j) const {
    return mk_eq_constraint(m_ctx, m_lhs, m_rhs, j);
}

unification_constraint_convertible::unification_constraint_convertible(context const & c, expr const & from, expr const & to, justification const & j):
    unification_constraint_cell(unification_constraint_kind::Convertible, c, j),
    m_from(from),
    m_to(to) {
}

unification_constraint_convertible::~unification_constraint_convertible() {
}

format unification_constraint_convertible::pp(formatter const & fmt, options const & opts, pos_info_provider const * p,
                                              bool include_justification, optional<metavar_env> const & menv) const {
    bool unicode = get_pp_unicode(opts);
    format op    = unicode ? format("\u227A") /* ≺ */ : format("<<");
    format body  = mk_binary(fmt, opts, m_ctx, m_from, m_to, op, menv);
    body = add_context(fmt, opts, m_ctx, body, menv);
    return add_justification(fmt, opts, body, m_justification, p, include_justification, menv);
}

unification_constraint unification_constraint_convertible::updt_justification(justification const & j) const {
    return mk_convertible_constraint(m_ctx, m_from, m_to, j);
}

unification_constraint_max::unification_constraint_max(context const & c, expr const & lhs1, expr const & lhs2, expr const & rhs, justification const & j):
    unification_constraint_cell(unification_constraint_kind::Max, c, j),
    m_lhs1(lhs1),
    m_lhs2(lhs2),
    m_rhs(rhs) {
}

unification_constraint_max::~unification_constraint_max() {
}

format unification_constraint_max::pp(formatter const & fmt, options const & opts, pos_info_provider const * p, bool include_justification,
                                      optional<metavar_env> const & menv) const {
    format op       = mk_unification_op(opts);
    format lhs1_fmt = fmt(m_ctx, instantiate_metavars(menv, m_lhs1), false, opts);
    format lhs2_fmt = fmt(m_ctx, instantiate_metavars(menv, m_lhs2), false, opts);
    format rhs_fmt  = fmt(m_ctx, instantiate_metavars(menv, m_rhs), false, opts);
    format body     = group(format{format("max"), lp(), lhs1_fmt, comma(), nest(4, compose(line(), lhs2_fmt)), rp(), space(), op, line(), rhs_fmt});
    body = add_context(fmt, opts, m_ctx, body, menv);
    return add_justification(fmt, opts, body, m_justification, p, include_justification, menv);
}

unification_constraint unification_constraint_max::updt_justification(justification const & j) const {
    return mk_max_constraint(m_ctx, m_lhs1, m_lhs2, m_rhs, j);
}

unification_constraint_choice::unification_constraint_choice(context const & c, expr const & mvar, unsigned num, expr const * choices, justification const & j):
    unification_constraint_cell(unification_constraint_kind::Choice, c, j),
    m_mvar(mvar),
    m_choices(choices, choices + num) {
}

unification_constraint_choice::~unification_constraint_choice() {
}

format unification_constraint_choice::pp(formatter const & fmt, options const & opts, pos_info_provider const * p, bool include_justification,
                                         optional<metavar_env> const & menv) const {
    bool unicode    = get_pp_unicode(opts);
    format m_fmt    = fmt(m_ctx, m_mvar, false, opts);
    format eq_op    = mk_unification_op(opts);
    format or_op    = unicode ? format("\u2295") : format("OR");
    format body;
    for (unsigned i = 0; i < m_choices.size(); i++) {
        body += group(paren(format{m_fmt, space(), eq_op, compose(line(), fmt(m_ctx, instantiate_metavars(menv, m_choices[i]), false, opts))}));
        if (i + 1 < m_choices.size())
            body += format{space(), or_op, line()};
    }
    body = group(body);
    body = add_context(fmt, opts, m_ctx, body, menv);
    return add_justification(fmt, opts, body, m_justification, p, include_justification, menv);
}

unification_constraint unification_constraint_choice::updt_justification(justification const & j) const {
    return mk_choice_constraint(m_ctx, m_mvar, m_choices.size(), m_choices.data(), j);
}

format unification_constraint::pp(formatter const & fmt, options const & opts, pos_info_provider const * p, bool include_justification,
                                  optional<metavar_env> const & menv) const {
    return m_ptr->pp(fmt, opts, p, include_justification, menv);
}

format unification_constraint::pp(formatter const & fmt, options const & opts, pos_info_provider const * p, bool include_justification) const {
    return pp(fmt, opts, p, include_justification, optional<metavar_env>());
}

unification_constraint mk_eq_constraint(context const & c, expr const & lhs, expr const & rhs, justification const & j) {
    return unification_constraint(new unification_constraint_eq(c, lhs, rhs, j));
}

unification_constraint mk_convertible_constraint(context const & c, expr const & from, expr const & to, justification const & j) {
    return unification_constraint(new unification_constraint_convertible(c, from, to, j));
}

unification_constraint mk_max_constraint(context const & c, expr const & lhs1, expr const & lhs2, expr const & rhs, justification const & j) {
    return unification_constraint(new unification_constraint_max(c, lhs1, lhs2, rhs, j));
}

unification_constraint mk_choice_constraint(context const & c, expr const & mvar, unsigned num, expr const * choices, justification const & j) {
    return unification_constraint(new unification_constraint_choice(c, mvar, num, choices, j));
}

unification_constraint mk_choice_constraint(context const & c, expr const & mvar, std::initializer_list<expr> const & choices, justification const & j) {
    return mk_choice_constraint(c, mvar, choices.size(), choices.begin(), j);
}
}


text:
package net.jonp.armi.base;

import java.util.Arrays;

/**
 * Used to test serialization with array fields.
 */
public class ArrayTestClass
    extends TestClass
    implements Cloneable
{
    public static final String NAME = "ArrayTestObject";

    public static final String COMMAND = "ArrayTestObject (" +
                                         //
                                         ArrayTestClass.class.getName() +
                                         ".intarray = array(java.lang.Integer) [3, 5, 7], " +
                                         //
                                         ArrayTestClass.class.getName() + ".nestedarray = array(java.lang.Object) [" +
                                         "\"String1\", 2, 3.4, array(java.lang.Object) [" +
                                         "\"Sub1\", array(java.lang.String) [\"SubSub1\", null, \"SubSub2\"]," + " \"Sub2\"]," +
                                         " true], " +
                                         //
                                         ArrayTestClass.class.getName() + ".nullarray = null, " +
                                         //
                                         ArrayTestClass.class.getName() +
                                         ".stringarray = array(java.lang.String) [\"s1\", \"s2\", \"s3\"])";

    public static final String STRING =
        "ArrayTestClass([3, 5, 7], [s1, s2, s3], null, [String1, 2, 3.4, [Sub1, [SubSub1, null, SubSub2], Sub2], true])";

    public Integer[] intarray;

    public String[] stringarray;

    public final Short[] nullarray = null;

    public Object[] nestedarray;

    public ArrayTestClass()
    {
        this(false);
    }

    public ArrayTestClass(final boolean initialize)
    {
        if (initialize) {
            intarray = new Integer[] {
                3, 5, 7
            };

            stringarray = new String[] {
                "s1", "s2", "s3"
            };

            nestedarray = new Object[] {
                "String1", 2, 3.4, new Object[] {
                    "Sub1", new String[] {
                        "SubSub1", null, "SubSub2"
                    }, "Sub2"
                }, true
            };
        }
    }

    @Override
    public String getName()
    {
        return NAME;
    }

    @Override
    public String getCommand()
    {
        return COMMAND;
    }

    @Override
    public String getString()
    {
        return STRING;
    }

    @Override
    public int hashCode()
    {
        return (intarray.length ^ stringarray.length ^ nestedarray.length);
    }

    @Override
    public boolean equals(final Object obj)
    {
        if (null == obj) {
            return false;
        }
        else if (obj instanceof ArrayTestClass) {
            final ArrayTestClass rhs = (ArrayTestClass)obj;
            return (Arrays.equals(intarray, rhs.intarray) && //
                    Arrays.equals(stringarray, rhs.stringarray) && //
            Arrays.deepEquals(nestedarray, rhs.nestedarray));
        }
        else {
            return false;
        }
    }

    @Override
    public ArrayTestClass clone()
    {
        return (ArrayTestClass)super.clone();
    }

    @Override
    public String toString()
    {
        return String.format("%s(%s, %s, %s, %s)", getClass().getSimpleName(), Conversion.describe(intarray),
                             Conversion.describe(stringarray), Conversion.describe(nullarray), Conversion.describe(nestedarray));
    }
}


text:
package ee.telekom.workflow.graph;

import java.util.Date;
import java.util.Map;

/**
 * When a {@link Node} execution does not immediately return a result it may
 * entitle an external system to perform some actions asynchronously. The action
 * to be done is described by a work item (e.g. wait for a timer or an incoming
 * signal, call a method on a bean or ask a human to perform a task).
 * <p>
 * Another way of describing a {@link GraphWorkItem} is: A work item is a handle/reference
 * to an uncompleted node execution in order to complete it at some future point in time.
 */
public interface GraphWorkItem{

    Long getExternalId();

    Long getExternalGraphInstanceId();

    Token getToken();

    String getSignal();

    Date getDueDate();

    String getBean();

    String getMethod();

    String getRole();

    String getUser();

    Object[] getTaskArguments();

    Map<String, Object> getHumanTaskArguments();

    Object getResult();

    WorkItemStatus getStatus();

    void setStatus( WorkItemStatus status );

    void setResult( Object result );

}


text:
from sklearn.ensemble import RandomForestClassifier

class RFClassificationModel(object):
    def __init__(self,reg_model=None):
        self.reg_model = RandomForestClassifier(n_estimators=100,n_jobs=2)

    def Train(self,x,y):
        self.reg_model.fit(x,y)

    def GetClassifier(self):
        return self.reg_model

    def GetFeatureImportances(self):
        return self.reg_model.feature_importances_


text:
package com.netflix.fenzo.queues.tiered;

import java.util.*;
import java.util.function.BiFunction;

import com.netflix.fenzo.AssignmentFailure;
import com.netflix.fenzo.VMResource;
import com.netflix.fenzo.queues.*;
import com.netflix.fenzo.sla.ResAllocs;
import com.netflix.fenzo.sla.ResAllocsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class represents a tier of the multi-tiered queue that {@link TieredQueue} represents. The tier holds one or
 * more buckets for queues, {@link QueueBucket} and maintains them in an order defined by the dynamic value for
 * dominant resource usage via {@link SortedBuckets}. The values are dynamically updated via the implementation of
 * {@link UsageTrackedQueue} this class provides.
 */
class Tier implements UsageTrackedQueue {

    private static final Logger logger = LoggerFactory.getLogger(Tier.class);
    private final int tierNumber;
    private final String tierName;

    private TierSla tierSla;
    private final ResUsage totals;

    private ResAllocs tierResources = null;
    private ResAllocs effectiveUsedResources;
    private ResAllocs remainingResources = null;
    private final Map<String, ResAllocs> lastEffectiveUsedResources = new HashMap<>();

    private final SortedBuckets sortedBuckets;
    private Map<VMResource, Double> currTotalResourcesMap = new HashMap<>();
    private final BiFunction<Integer, String, Double> allocsShareGetter;

    Tier(int tierNumber, BiFunction<Integer, String, Double> allocsShareGetter) {
        this.tierNumber = tierNumber;
        this.tierName = "tier#" + tierNumber;

        this.totals = new ResUsage();
        this.effectiveUsedResources = ResAllocsUtil.emptyOf(tierName);

        // TODO: need to consider the impact of this comparator to any others we may want, like simple round robin.
        // Use DRF sorting. Except, note that it is undefined when two entities compare to 0 (equal values) which
        // one gets ahead of the other.
        sortedBuckets = new SortedBuckets(totals);
        this.allocsShareGetter = allocsShareGetter;
    }

    void setTierSla(TierSla tierSla) {
        this.tierSla = tierSla;

        if (tierSla == null) {
            sortedBuckets.getSortedList().forEach(bucket -> bucket.setBucketGuarantees(null));
            tierResources = ResAllocsUtil.emptyOf(tierName);
        } else {
            sortedBuckets.getSortedList().forEach(bucket -> bucket.setBucketGuarantees(tierSla.getBucketAllocs(bucket.getName())));

            // Always create a bucket, if there is SLA defined for it for proper accounting
            tierSla.getAllocsMap().keySet().forEach(this::getOrCreateBucket);
            this.tierResources = tierSla.getTierCapacity();
        }

        this.effectiveUsedResources = ResAllocsUtil.emptyOf(tierName);
        this.lastEffectiveUsedResources.clear();
        for (QueueBucket bucket : sortedBuckets.getSortedList()) {
            effectiveUsedResources = ResAllocsUtil.add(effectiveUsedResources, bucket.getEffectiveUsage());
            lastEffectiveUsedResources.put(bucket.getName(), bucket.getEffectiveUsage());
        }

        this.remainingResources = ResAllocsUtil.subtract(tierResources, effectiveUsedResources);

        sortedBuckets.resort();
    }

    private QueueBucket getOrCreateBucket(QueuableTask t) {
        if (t == null)
            throw new NullPointerException();
        return getOrCreateBucket(t.getQAttributes().getBucketName());
    }

    private QueueBucket getOrCreateBucket(String bucketName) {
        QueueBucket bucket = sortedBuckets.get(bucketName);
        if (bucket == null) {
            bucket = new QueueBucket(tierNumber, bucketName, totals, allocsShareGetter);
            sortedBuckets.add(bucket);
            bucket.setBucketGuarantees(tierSla == null ? null : tierSla.getBucketAllocs(bucketName));
        }
        return bucket;
    }

    public int getTierNumber() {
        return tierNumber;
    }

    @Override
    public void queueTask(QueuableTask t) throws TaskQueueException {
        getOrCreateBucket(t).queueTask(t);
    }

    @Override
    public Assignable<QueuableTask> nextTaskToLaunch() throws TaskQueueException {
        for (QueueBucket bucket : sortedBuckets.getSortedList()) {
            final Assignable<QueuableTask> taskOrFailure = bucket.nextTaskToLaunch();
            if (taskOrFailure != null) {
                if (taskOrFailure.hasFailure()) {
                    return taskOrFailure;
                }
                QueuableTask task = taskOrFailure.getTask();
                if (bucket.hasGuaranteedCapacityFor(task)) {
                    return taskOrFailure;
                }
                if (remainingResources == null || ResAllocsUtil.isBounded(task, remainingResources)) {
                    return taskOrFailure;
                }
                return Assignable.error(task, new AssignmentFailure(VMResource.ResAllocs, 0, 0, 0,
                        "No guaranteed capacity left for queue."
                                + "\n" + bucket.getBucketCapacityAsString()
                                + "\n" + getTierCapacityAsString()
                ));
            }
        }
        return null;
    }

    @Override
    public void assignTask(QueuableTask t) throws TaskQueueException {
        // assigning the task changes resource usage and therefore, sorting order must be updated.
        // We do this by removing the bucket from sortedBuckets, assigning the task in the bucket,
        // then adding the bucket back into the sortedBuckets. It will then fall into its right new place.
        // This operation therefore takes time complexity of O(log N).
        final QueueBucket bucket = sortedBuckets.remove(t.getQAttributes().getBucketName());
        if (bucket == null)
            throw new TaskQueueException("Invalid to not find bucket to assign task id=" + t.getId());
        try {
            bucket.assignTask(t);
            addUsage(bucket, t);
        } finally {
            sortedBuckets.add(bucket);
        }
    }

    @Override
    public boolean launchTask(QueuableTask t) throws TaskQueueException {
        // launching the task changes the resource usage and therefore sorting order must be updated.
        // We do this by removing the bucket from the sortedBuckets, launching the task in the bucket,
        // then adding the bucket back into the sortedBuckets. It will then fall into its right new place.
        // This operation therefore takes time complexity of O(log N).
        if (logger.isDebugEnabled())
            logger.debug("Adding " + t.getId() + ": to ordered buckets: " + getSortedListString());
        final String bucketName = t.getQAttributes().getBucketName();
        QueueBucket bucket = sortedBuckets.remove(bucketName);
        if (bucket == null) {
            bucket = new QueueBucket(tierNumber, bucketName, totals, allocsShareGetter);
        }
        try {
            if (bucket.launchTask(t)) {
                addUsage(bucket, t);
                return true;
            }
        } finally {
            sortedBuckets.add(bucket);
        }
        return false;
    }

    private void verifySortedBuckets() throws TaskQueueException {
        if (sortedBuckets.getSortedList().isEmpty())
            return;
        List<QueueBucket> list = new ArrayList<>(sortedBuckets.getSortedList());
        if (list.size() > 1) {
            QueueBucket prev = list.get(0);
            for (int i = 1; i < list.size(); i++) {
                if (list.get(i).getDominantUsageShare() < prev.getDominantUsageShare()) {
                    final String msg = "Incorrect sorting order : " + getSortedListString();
                    throw new TaskQueueException(msg);
                }
                prev = list.get(i);
            }
        }
    }

    @Override
    public QueuableTask removeTask(String id, QAttributes qAttributes) throws TaskQueueException {
        // removing a task can change the resource usage and therefore the sorting order of queues. So, we take the
        // same approach as in launchTask() above - remove the bucket and readd to keep sorting order updated.
        final QueueBucket bucket = sortedBuckets.remove(qAttributes.getBucketName());
        if (bucket == null)
            return null;
        final QueuableTask removed;
        try {
            removed = bucket.removeTask(id, qAttributes);
            if (removed != null) {
                removeUsage(bucket, removed);
            }
        } finally {
            if (bucket.size() > 0 || (tierSla != null && tierSla.getBucketAllocs(bucket.getName()) != null))
                sortedBuckets.add(bucket);
        }
        return removed;
    }

    private void addUsage(QueueBucket bucket, QueuableTask t) {
        totals.addUsage(t);
        updateEffectiveBucketTotals(bucket);
    }

    private void removeUsage(QueueBucket bucket, QueuableTask removed) {
        totals.remUsage(removed);
        updateEffectiveBucketTotals(bucket);
    }

    private void updateEffectiveBucketTotals(QueueBucket bucket) {
        ResAllocs lastEffective = lastEffectiveUsedResources.get(bucket.getName());
        if (lastEffective != null) {
            effectiveUsedResources = ResAllocsUtil.subtract(effectiveUsedResources, lastEffective);
        }
        lastEffectiveUsedResources.put(bucket.getName(), bucket.getEffectiveUsage());
        effectiveUsedResources = ResAllocsUtil.add(effectiveUsedResources, bucket.getEffectiveUsage());

        if (tierResources == null) {
            remainingResources = null;
        } else {
            remainingResources = ResAllocsUtil.subtract(tierResources, effectiveUsedResources);
        }
    }

    @Override
    public double getDominantUsageShare() {
        return 0.0; // undefined for a tier
    }

    @Override
    public void setTaskReadyTime(String taskId, QAttributes qAttributes, long when) throws TaskQueueException {
        final QueueBucket bucket = sortedBuckets.get(qAttributes.getBucketName());
        if (bucket != null)
            bucket.setTaskReadyTime(taskId, qAttributes, when);
    }

    @Override
    public void reset() {
        if (logger.isDebugEnabled()) {
            try {
                verifySortedBuckets();
            } catch (TaskQueueException e) {
                logger.error(e.getMessage());
            }
        }
        for (QueueBucket bucket : sortedBuckets.getSortedList()) {
            bucket.reset();
        }
    }

    private String getSortedListString() {
        StringBuilder b = new StringBuilder("Tier " + tierNumber + " sortedBs: [");
        for (QueueBucket bucket : sortedBuckets.getSortedList()) {
            b.append(bucket.getName()).append(" (").append(bucket.getDominantUsageShare()).append("), ");
        }
        b.append("]");
        return b.toString();
    }

    private String getTierCapacityAsString() {
        StringBuilder sb = new StringBuilder();
        if (tierResources != null) {
            sb.append("Tier ").append(tierNumber).append(" Total Capacity: ").append(tierResources.getAsString());
        }
        if (effectiveUsedResources != null) {
            sb.append("\nTier ").append(tierNumber).append(" Used Capacity: ").append(effectiveUsedResources.getAsString());
        }
        if (remainingResources != null) {
            sb.append("\nTier ").append(tierNumber).append(" Remaining Capacity: ").append(remainingResources.getAsString());
        }
        return sb.toString();
    }

    @Override
    public void setTotalResources(Map<VMResource, Double> totalResourcesMap) {
        if (totalResMapChanged(currTotalResourcesMap, totalResourcesMap)) {
            currTotalResourcesMap.clear();
            currTotalResourcesMap.putAll(totalResourcesMap);
            for (QueueBucket b : sortedBuckets.getSortedList()) {
                b.setTotalResources(tierResources);
            }
            logger.debug("Re-sorting buckets in tier " + tierNumber + " after totals changed");
            sortedBuckets.resort();
        }
    }

    private boolean totalResMapChanged(Map<VMResource, Double> currTotalResourcesMap, Map<VMResource, Double> totalResourcesMap) {
        if (currTotalResourcesMap.size() != totalResourcesMap.size())
            return true;
        Set<VMResource> curr = new HashSet<>(currTotalResourcesMap.keySet());
        for (VMResource r : totalResourcesMap.keySet()) {
            final Double c = currTotalResourcesMap.get(r);
            final Double n = totalResourcesMap.get(r);
            if ((c == null && n != null) || (c != null && n == null) || (n != null && !n.equals(c)))
                return true;
            curr.remove(r);
        }
        return !curr.isEmpty();
    }

    @Override
    public Map<TaskQueue.TaskState, Collection<QueuableTask>> getAllTasks() throws TaskQueueException {
        Map<TaskQueue.TaskState, Collection<QueuableTask>> result = new HashMap<>();
        for (QueueBucket bucket : sortedBuckets.getSortedList()) {
            final Map<TaskQueue.TaskState, Collection<QueuableTask>> allTasks = bucket.getAllTasks();
            if (!allTasks.isEmpty()) {
                for (TaskQueue.TaskState s : TaskQueue.TaskState.values()) {
                    final Collection<QueuableTask> q = allTasks.get(s);
                    if (q != null && !q.isEmpty()) {
                        Collection<QueuableTask> resQ = result.get(s);
                        if (resQ == null) {
                            resQ = new LinkedList<>();
                            result.put(s, resQ);
                        }
                        resQ.addAll(q);
                    }
                }
            }
        }
        return result;
    }
}


text:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Floor Plan Monitor</title>

<meta charset="UTF-8">

Floor Plan Monitor

Open a floor plan made in the "Floor Plan Editor" and watch simulated alerts decorate the screen.

Choose a floor plan:

Overview:

            <select id="file list" name="File List" multiple="multiple" style="font-family:Arial; font-size:medium; width:300px; height:200px; margin-left: 50px"></select>

            <button id="open" type="button">Open</button>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">
  <scan>
    <!-- These exclusions were added by Errai to avoid deploying client-side classes to the server -->
    <!-- End of Errai exclusions -->

    <!-- These exclusions are added for Weld to avoid loading client-side classes when running in Super Dev Mode -->
    <exclude name="org.drools.workbench.client.**"/>
    <exclude name="org.drools.workbench.screens.categories.client.**"/>
    <exclude name="org.drools.workbench.screens.drltext.client.**"/>
    <exclude name="org.drools.workbench.screens.dsltext.client.**"/>
    <exclude name="org.drools.workbench.screens.dtablexls.client.**"/>
    <exclude name="org.drools.workbench.screens.enums.client.**"/>
    <exclude name="org.drools.workbench.screens.globals.client.**"/>
    <exclude name="org.drools.workbench.screens.guided.dtable.client.**"/>
    <exclude name="org.drools.workbench.screens.guided.dtree.client.**"/>
    <exclude name="org.drools.workbench.screens.guided.rule.client.**"/>
    <exclude name="org.drools.workbench.screens.guided.scorecard.client.**"/>
    <exclude name="org.drools.workbench.screens.guided.template.client.**"/>
    <exclude name="org.drools.workbench.screens.scorecardxls.client.**"/>
    <exclude name="org.drools.workbench.screens.testscenario.client.**"/>
    <exclude name="org.drools.workbench.screens.workitems.client.**"/>

    <exclude name="org.guvnor.asset.management.client.**"/>
    <exclude name="org.guvnor.client.**"/>
    <exclude name="org.guvnor.common.services.project.client.**"/>
    <exclude name="org.guvnor.common.services.workingset.client.**"/>
    <exclude name="org.guvnor.inbox.client.**"/>
    <exclude name="org.guvnor.messageconsole.client.**"/>
    <exclude name="org.guvnor.m2repo.client.**"/>
    <exclude name="org.guvnor.organizationalunit.manager.client.**"/>
    <exclude name="org.guvnor.structure.client.**"/>

    <exclude name="org.kie.workbench.common.screens.contributors.client.**"/>
    <exclude name="org.kie.workbench.common.screens.datamodeller.client.**"/>
    <exclude name="org.kie.workbench.common.screens.defaulteditor.client.**"/>
    <exclude name="org.kie.workbench.common.screens.examples.client.**"/>
    <exclude name="org.kie.workbench.common.screens.explorer.client.**"/>
    <exclude name="org.kie.workbench.common.screens.home.client.**"/>
    <exclude name="org.kie.workbench.common.screens.javaeditor.client.**"/>
    <exclude name="org.kie.workbench.common.screens.projecteditor.client.**"/>
    <exclude name="org.kie.workbench.common.screens.projectimportsscreen.client.**"/>
    <exclude name="org.kie.workbench.common.screens.search.client.**"/>
    <exclude name="org.kie.workbench.common.screens.server.management.client.**"/>
    <exclude name="org.kie.workbench.common.screens.social.hp.client.**"/>
    <exclude name="org.kie.workbench.common.widgets.client.**"/>
    <exclude name="org.kie.workbench.common.widgets.configresource.client.**"/>
    <exclude name="org.kie.workbench.common.widgets.decoratedgrid.client.**"/>
    <exclude name="org.kie.workbench.common.widgets.metadata.client.**"/>
    <exclude name="org.kie.workbench.common.workbench.client.**"/>

    <exclude name="org.optaplanner.workbench.client.**"/>
    <exclude name="org.optaplanner.workbench.screens.domaineditor.client.**"/>
    <exclude name="org.optaplanner.workbench.screens.solver.client.**"/>
  </scan>
</beans>


text:
extern "C" {
#endif

//
// used to register a basic type descriptor in the basic type table
//
int luacwrap_registerbasictype  ( lua_State*          L
                                , luacwrap_BasicType* desc);

//
// register a type descriptor in the given (namespace) table
//
int luacwrap_registertype       ( lua_State*            L
                                , int                   nsidx
                                , luacwrap_Type*        desc);

//
// check a userdata type descriptor against a given type descriptor
//
void* luacwrap_checktype        ( lua_State*            L
                                , int                   ud
                                , luacwrap_Type*        desc);

//
// create a boxed object on the top of the Lua stack, use initval to fill memory
//
void* luacwrap_pushboxedobj     ( lua_State*            L
                                , luacwrap_Type*        desc
                                , int                   initval);

//
// push a pointer as a typed light (means not garbage collected) object
//
int luacwrap_pushtypedptr       ( lua_State*            L
                                , luacwrap_Type*        desc
                                , void*                 pObj);

//
// access to reference table
//
int luacwrap_createreference    (lua_State* L, int index);
int luacwrap_pushreference      (lua_State* L, int tag);

//
//  Registers a list of global constants maintained in an array or
//  luacwrap_DefUIntConst structs.
//
void luacwrap_defuintconstants  ( lua_State*              L
                                , luacwrap_DefUIntConst*  constants);

#ifdef __cplusplus
}
#endif


text:
package kubernetes

import (
	"github.com/astaxie/beego"
	"github.com/cloudawan/cloudone_gui/controllers/identity"
	"github.com/cloudawan/cloudone_gui/controllers/utility/guimessagedisplay"
	"github.com/cloudawan/cloudone_utility/rbac"
	"github.com/cloudawan/cloudone_utility/restclient"
	"strconv"
	"time"
)

type ListController struct {
	beego.Controller
}

type KubernetesEvent struct {
	Namespace                              string
	Name                                   string
	Kind                                   string
	Source                                 map[string]interface{}
	Id                                     string
	FirstTimestamp                         time.Time
	LastTimestamp                          time.Time
	Count                                  int
	Message                                string
	Reason                                 string
	Acknowledge                            bool
	Action                                 string
	Button                                 string
	HiddenTagGuiEventKubernetesAcknowledge string
}

const (
	amountPerPage = 10
)

func (c *ListController) Get() {
	c.TplName = "event/kubernetes/list.html"
	guimessage := guimessagedisplay.GetGUIMessage(c)

	// Authorization for web page display
	c.Data["layoutMenu"] = c.GetSession("layoutMenu")
	// Authorization for Button
	user, _ := c.GetSession("user").(*rbac.User)
	// Tag won't work in loop so need to be placed in data
	hasGuiEventKubernetesAcknowledge := user.HasPermission(identity.GetConponentName(), "GET", "/gui/event/kubernetes/acknowledge")

	cloudoneAnalysisProtocol := beego.AppConfig.String("cloudoneAnalysisProtocol")
	cloudoneAnalysisHost := beego.AppConfig.String("cloudoneAnalysisHost")
	cloudoneAnalysisPort := beego.AppConfig.String("cloudoneAnalysisPort")

	acknowledge := c.GetString("acknowledge")
	if acknowledge == "" {
		acknowledge = "false"
	}

	offset, _ := c.GetInt("offset")

	url := cloudoneAnalysisProtocol + "://" + cloudoneAnalysisHost + ":" + cloudoneAnalysisPort +
		"/api/v1/historicalevents?acknowledge=" + acknowledge + "&size=" + strconv.Itoa(amountPerPage) + "&offset=" + strconv.Itoa(offset)

	jsonMapSlice := make([]map[string]interface{}, 0)

	tokenHeaderMap, _ := c.GetSession("tokenHeaderMap").(map[string]string)

	_, err := restclient.RequestGetWithStructure(url, &jsonMapSlice, tokenHeaderMap)

	if identity.IsTokenInvalidAndRedirect(c, c.Ctx, err) {
		return
	}

	if err != nil {
		// Error
		guimessage.AddDanger(guimessagedisplay.GetErrorMessage(err))
	} else {
		var action string
		var button string
		if acknowledge == "true" {
			action = "false"
			button = "Unacknowledge"
		} else {
			action = "true"
			button = "Acknowledge"
		}

		kubernetesEventSlice := make([]KubernetesEvent, 0)
		for _, jsonMap := range jsonMapSlice {
			sourceJsonMap, _ := jsonMap["_source"].(map[string]interface{})

			namespace, _ := sourceJsonMap["metadata"].(map[string]interface{})["namespace"].(string)
			name, _ := sourceJsonMap["involvedObject"].(map[string]interface{})["name"].(string)
			kind, _ := sourceJsonMap["involvedObject"].(map[string]interface{})["kind"].(string)
			source, _ := sourceJsonMap["source"].(map[string]interface{})
			id, _ := jsonMap["_id"].(string)
			firstTimestamp, _ := sourceJsonMap["firstTimestamp"].(string)
			lastTimestamp, _ := sourceJsonMap["lastTimestamp"].(string)
			count, _ := sourceJsonMap["count"].(float64)
			message, _ := sourceJsonMap["message"].(string)
			reason, _ := sourceJsonMap["reason"].(string)
			acknowledge, _ := sourceJsonMap["searchMetaData"].(map[string]interface{})["acknowledge"].(bool)

			firstTime, err := time.Parse(time.RFC3339, firstTimestamp)
			if err == nil {
				firstTime = firstTime.Local()
			}
			lastTime, err := time.Parse(time.RFC3339, lastTimestamp)
			if err == nil {
				lastTime = lastTime.Local()
			}

			kubernetesEvent := KubernetesEvent{
				namespace,
				name,
				kind,
				source,
				id,
				firstTime,
				lastTime,
				int(count),
				message,
				reason,
				acknowledge,
				action,
				button,
				"",
			}

			kubernetesEventSlice = append(kubernetesEventSlice, kubernetesEvent)
		}

		previousOffset := offset - amountPerPage
		if previousOffset < 0 {
			previousOffset = 0
		}
		nextOffset := offset + amountPerPage

		previousFrom := previousOffset
		if previousFrom < 0 {
			previousFrom = 0
		}
		previousFrom += 1
		previousTo := previousOffset + amountPerPage
		c.Data["previousLabel"] = strconv.Itoa(previousFrom) + "~" + strconv.Itoa(previousTo)
		if offset == 0 {
			c.Data["previousButtonHidden"] = "hidden"
		} else {
			c.Data["previousButtonHidden"] = ""
		}

		nextFrom := nextOffset + 1
		nextTo := nextOffset + amountPerPage
		c.Data["nextLabel"] = strconv.Itoa(nextFrom) + "~" + strconv.Itoa(nextTo)

		if acknowledge == "true" {
			c.Data["acknowledgeActive"] = "active"
			c.Data["paginationUrlPrevious"] = "/gui/event/kubernetes/list?acknowledge=true&offset=" + strconv.Itoa(previousOffset)
			c.Data["paginationUrlNext"] = "/gui/event/kubernetes/list?acknowledge=true&offset=" + strconv.Itoa(nextOffset)
		} else {
			c.Data["unacknowledgeActive"] = "active"
			c.Data["paginationUrlPrevious"] = "/gui/event/kubernetes/list?acknowledge=false&offset=" + strconv.Itoa(previousOffset)
			c.Data["paginationUrlNext"] = "/gui/event/kubernetes/list?acknowledge=false&offset=" + strconv.Itoa(nextOffset)
		}

		for i := 0; i < len(kubernetesEventSlice); i++ {
			if hasGuiEventKubernetesAcknowledge {
				kubernetesEventSlice[i].HiddenTagGuiEventKubernetesAcknowledge = "<div class='btn-group'>"
			} else {
				kubernetesEventSlice[i].HiddenTagGuiEventKubernetesAcknowledge = "<div hidden>"
			}
		}

		c.Data["kubernetesEventSlice"] = kubernetesEventSlice
	}

	guimessage.OutputMessage(c.Data)
}


text:
#include "ClangTidyTest.h"
#include "llvm/HeaderGuardCheck.h"
#include "llvm/IncludeOrderCheck.h"
#include "gtest/gtest.h"

using namespace clang::tidy::llvm;

namespace clang {
namespace tidy {
namespace test {

// FIXME: It seems this might be incompatible to dos path. Investigating.
#if !defined(_WIN32)
static std::string runHeaderGuardCheck(StringRef Code, const Twine &Filename,
                                       Optional<StringRef> ExpectedWarning) {
  std::vector<ClangTidyError> Errors;
  std::string Result = test::runCheckOnCode<LLVMHeaderGuardCheck>(
      Code, &Errors, Filename, std::string("-xc++-header"));
  if (Errors.size() != (size_t)ExpectedWarning.hasValue())
    return "invalid error count";
  if (ExpectedWarning && *ExpectedWarning != Errors.back().Message.Message)
    return "expected: '" + ExpectedWarning->str() + "', saw: '" +
           Errors.back().Message.Message + "'";
  return Result;
}

namespace {
struct WithEndifComment : public LLVMHeaderGuardCheck {
  WithEndifComment(StringRef Name, ClangTidyContext *Context)
      : LLVMHeaderGuardCheck(Name, Context) {}
  bool shouldSuggestEndifComment(StringRef Filename) override { return true; }
};
} // namespace

static std::string
runHeaderGuardCheckWithEndif(StringRef Code, const Twine &Filename,
                             Optional<StringRef> ExpectedWarning) {
  std::vector<ClangTidyError> Errors;
  std::string Result = test::runCheckOnCode<WithEndifComment>(
      Code, &Errors, Filename, std::string("-xc++-header"));
  if (Errors.size() != (size_t)ExpectedWarning.hasValue())
    return "invalid error count";
  if (ExpectedWarning && *ExpectedWarning != Errors.back().Message.Message)
    return "expected: '" + ExpectedWarning->str() + "', saw: '" +
           Errors.back().Message.Message + "'";
  return Result;
}

TEST(LLVMHeaderGuardCheckTest, FixHeaderGuards) {
  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
            "#define LLVM_ADT_FOO_H\n"
            "#endif\n",
            runHeaderGuardCheck(
                "#ifndef FOO\n"
                "#define FOO\n"
                "#endif\n",
                "include/llvm/ADT/foo.h",
                StringRef("header guard does not follow preferred style")));

  // Allow trailing underscores.
  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H_\n"
            "#define LLVM_ADT_FOO_H_\n"
            "#endif\n",
            runHeaderGuardCheck("#ifndef LLVM_ADT_FOO_H_\n"
                                "#define LLVM_ADT_FOO_H_\n"
                                "#endif\n",
                                "include/llvm/ADT/foo.h", None));

  EXPECT_EQ("#ifndef LLVM_CLANG_C_BAR_H\n"
            "#define LLVM_CLANG_C_BAR_H\n"
            "\n"
            "\n"
            "#endif\n",
            runHeaderGuardCheck("", "./include/clang-c/bar.h",
                                StringRef("header is missing header guard")));

  EXPECT_EQ("#ifndef LLVM_CLANG_LIB_CODEGEN_C_H\n"
            "#define LLVM_CLANG_LIB_CODEGEN_C_H\n"
            "\n"
            "\n"
            "#endif\n",
            runHeaderGuardCheck("", "tools/clang/lib/CodeGen/c.h",
                                StringRef("header is missing header guard")));

  EXPECT_EQ("#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_X_H\n"
            "#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_X_H\n"
            "\n"
            "\n"
            "#endif\n",
            runHeaderGuardCheck("", "tools/clang/tools/extra/clang-tidy/x.h",
                                StringRef("header is missing header guard")));

  EXPECT_EQ(
      "int foo;\n"
      "#ifndef LLVM_CLANG_BAR_H\n"
      "#define LLVM_CLANG_BAR_H\n"
      "#endif\n",
      runHeaderGuardCheck("int foo;\n"
                          "#ifndef LLVM_CLANG_BAR_H\n"
                          "#define LLVM_CLANG_BAR_H\n"
                          "#endif\n",
                          "include/clang/bar.h",
                          StringRef("code/includes outside of area guarded by "
                                    "header guard; consider moving it")));

  EXPECT_EQ(
      "#ifndef LLVM_CLANG_BAR_H\n"
      "#define LLVM_CLANG_BAR_H\n"
      "#endif\n"
      "int foo;\n",
      runHeaderGuardCheck("#ifndef LLVM_CLANG_BAR_H\n"
                          "#define LLVM_CLANG_BAR_H\n"
                          "#endif\n"
                          "int foo;\n",
                          "include/clang/bar.h",
                          StringRef("code/includes outside of area guarded by "
                                    "header guard; consider moving it")));

  EXPECT_EQ("#ifndef LLVM_CLANG_BAR_H\n"
            "#define LLVM_CLANG_BAR_H\n"
            "\n"
            "int foo;\n"
            "#ifndef FOOLOLO\n"
            "#define FOOLOLO\n"
            "#endif\n"
            "\n"
            "#endif\n",
            runHeaderGuardCheck("int foo;\n"
                                "#ifndef FOOLOLO\n"
                                "#define FOOLOLO\n"
                                "#endif\n",
                                "include/clang/bar.h",
                                StringRef("header is missing header guard")));

  // Fix incorrect #endif comments even if we shouldn't add new ones.
  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
            "#define LLVM_ADT_FOO_H\n"
            "#endif // LLVM_ADT_FOO_H\n",
            runHeaderGuardCheck(
                "#ifndef FOO\n"
                "#define FOO\n"
                "#endif // FOO\n",
                "include/llvm/ADT/foo.h",
                StringRef("header guard does not follow preferred style")));

  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
            "#define LLVM_ADT_FOO_H\n"
            "#endif // LLVM_ADT_FOO_H\n",
            runHeaderGuardCheckWithEndif(
                "#ifndef FOO\n"
                "#define FOO\n"
                "#endif\n",
                "include/llvm/ADT/foo.h",
                StringRef("header guard does not follow preferred style")));

  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
            "#define LLVM_ADT_FOO_H\n"
            "#endif // LLVM_ADT_FOO_H\n",
            runHeaderGuardCheckWithEndif(
                "#ifndef LLVM_ADT_FOO_H\n"
                "#define LLVM_ADT_FOO_H\n"
                "#endif // LLVM_H\n",
                "include/llvm/ADT/foo.h",
                StringRef("#endif for a header guard should reference the "
                          "guard macro in a comment")));

  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
            "#define LLVM_ADT_FOO_H\n"
            "#endif /* LLVM_ADT_FOO_H */\n",
            runHeaderGuardCheckWithEndif("#ifndef LLVM_ADT_FOO_H\n"
                                         "#define LLVM_ADT_FOO_H\n"
                                         "#endif /* LLVM_ADT_FOO_H */\n",
                                         "include/llvm/ADT/foo.h", None));

  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H_\n"
            "#define LLVM_ADT_FOO_H_\n"
            "#endif // LLVM_ADT_FOO_H_\n",
            runHeaderGuardCheckWithEndif("#ifndef LLVM_ADT_FOO_H_\n"
                                         "#define LLVM_ADT_FOO_H_\n"
                                         "#endif // LLVM_ADT_FOO_H_\n",
                                         "include/llvm/ADT/foo.h", None));

  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
            "#define LLVM_ADT_FOO_H\n"
            "#endif // LLVM_ADT_FOO_H\n",
            runHeaderGuardCheckWithEndif(
                "#ifndef LLVM_ADT_FOO_H_\n"
                "#define LLVM_ADT_FOO_H_\n"
                "#endif // LLVM\n",
                "include/llvm/ADT/foo.h",
                StringRef("header guard does not follow preferred style")));

  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
            "#define LLVM_ADT_FOO_H\n"
            "#endif \\ \n"
            "// LLVM_ADT_FOO_H\n",
            runHeaderGuardCheckWithEndif(
                "#ifndef LLVM_ADT_FOO_H\n"
                "#define LLVM_ADT_FOO_H\n"
                "#endif \\ \n"
                "// LLVM_ADT_FOO_H\n",
                "include/llvm/ADT/foo.h",
                StringRef("backslash and newline separated by space")));

  EXPECT_EQ("#ifndef LLVM_ADT_FOO_H\n"
            "#define LLVM_ADT_FOO_H\n"
            "#endif  /* LLVM_ADT_FOO_H\\ \n"
            " FOO */",
            runHeaderGuardCheckWithEndif("#ifndef LLVM_ADT_FOO_H\n"
                                         "#define LLVM_ADT_FOO_H\n"
                                         "#endif  /* LLVM_ADT_FOO_H\\ \n"
                                         " FOO */",
                                         "include/llvm/ADT/foo.h", None));
}
#endif

} // namespace test
} // namespace tidy
} // namespace clang