text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

title: Hooks Guide
toc_title: Hooks
description: List of hooks supported by the Cordova CLI.
---

# Hooks

## Introduction

Cordova Hooks represent special scripts which could be added by application and
plugin developers or even by your own build system  to customize cordova commands.

Cordova hooks allow you to perform special activities around cordova commands. For example,
you may have a custom tool that checks for code formatting in your javascript file. And, you
would like to run this tool before every build. In such a case, you could use a
'before_build' hook and instruct the cordova run time to run the custom tool to be invoked
before every build.

Hooks might be related to your application activities such as such as `before_build`,
`after_build`, etc. Or, they might be related to the plugins of your application. For example,
hooks such as `before_plugin_add`, `after_plugin_add`, etc applies to plugin related
activities. These hooks can be associated with all plugins within your application or
be specific to only one plugin.

Cordova supports the following hook types:

    <col width="20%">
    <col width="30%">
    <col width="50%">

            Hook Type
            Associated Cordova Commands
            Description

            before_platform_add
            cordova platform add
            To be executed before and after adding a platform.

            after_platform_add

            before_platform_rm
            cordova platform rm
            To be executed before and after removing a platform.

            after_platform_rm

            before_platform_ls
            cordova platform ls
            To be executed before and after listing the installed and available platforms.

            after_platform_ls

            before_prepare
            cordova prepare
cordova platform add
cordova build
cordova run
            To be executed before and after preparing your application.

            after_prepare

            before_compile
            cordova compile
cordova build
            To be executed before and after compiling your application.

            after_compile

            before_deploy
            cordova emulate
cordova run
            To be executed before deploying your application.

            before_build
            cordova build
            To be executed before and after building your application.

            after_build

            before_emulate
            cordova emulate
            To be executed before and after emulating your application.

            after_emulate

            before_run
            cordova run
            To be executed before and after running your application.

            after_run

            before_serve
            cordova serve
            To be executed before and after serving your application.

            after_serve

            before_clean
            cordova clean
            To be executed before and after cleaning your application.

            after_clean

            pre_package
            N/A
            Applicable to Windows 8 and Windows Phone only. This hook is deprecated.

            before_plugin_add
            cordova plugin add
            To be executed before and after adding a plugin.

            after_plugin_add

            before_plugin_rm
            cordova plugin rm
            To be executed before and after removing a plugin.

            after_plugin_rm

            before_plugin_ls
            cordova plugin ls
            To be executed before and after listing the plugins in your application.

            after_plugin_ls

            before_plugin_search
            cordova plugin search
            To be executed before and after a plugin search.

            after_plugin_search

            before_plugin_install
            cordova plugin add
            To be executed before and after installing a plugin (to the platforms). Plugin hooks in plugin.xml are executed for a plugin being installed only

            after_plugin_install

            before_plugin_uninstall
            cordova plugin rm
            To be executed before uninstalling a plugin (from the platforms).Plugin hooks in plugin.xml are executed for a plugin being installed only

## Ways to define hooks

### Config.xml

Hooks could be defined in project's `config.xml` using `<hook>` elements, for example:

```xml
<hook type="before_build" src="scripts/appBeforeBuild.bat" />
<hook type="before_build" src="scripts/appBeforeBuild.js" />
<hook type="before_plugin_install" src="scripts/appBeforePluginInstall.js" />

<platform name="android">
    <hook type="before_build" src="scripts/wp8/appAndroidBeforeBuild.bat" />
    <hook type="before_build" src="scripts/wp8/appAndroidBeforeBuild.js" />
    <hook type="before_plugin_install" src="scripts/wp8/appWP8BeforePluginInstall.js" />
    ...
</platform>

<platform name="windows">
    <hook type="before_build" src="scripts/windows/appWinBeforeBuild.bat" />
    <hook type="before_build" src="scripts/windows/appWinBeforeBuild.js" />
    <hook type="before_plugin_install" src="scripts/windows/appWinBeforePluginInstall.js" />
    ...
</platform>
```

### Plugin hooks (plugin.xml)

As a plugin developer you can define hook scripts using `<hook>` elements in a `plugin.xml` like that:

```xml
<hook type="before_plugin_install" src="scripts/beforeInstall.js" />
<hook type="after_build" src="scripts/afterBuild.js" />

<platform name="android">
    <hook type="before_plugin_install" src="scripts/androidBeforeInstall.js" />
    <hook type="before_build" src="scripts/androidBeforeBuild.js" />
    ...
</platform>
```

`before_plugin_install`, `after_plugin_install`, `before_plugin_uninstall` plugin hooks will be fired
exclusively for the plugin being installed/uninstalled.

### Via `/hooks` directory (Deprecated)

To execute custom action when corresponding hook type is fired, use hook type as a name for a subfolder inside 'hooks' directory and place you script file here, for example:

```
# script file will be automatically executed after each build
hooks/after_build/after_build_custom_action.js
```

When using these hooks, they will always be run as executable files, not as loadable JavaScript modules.

__Remember__: Make your scripts executable in this case.

__Note__: this method is considered deprecated in favor of the hook elements in config.xml and plugin.xml.

### Order of Hooks execution

#### Based on Hooks Definition

Hook scripts could be defined by adding them to the special predefined folder
(`/hooks`) or via configuration files (`config.xml` and `plugin.xml`) and run
serially in the following order:

* Application hooks from `/hooks`;
* Application hooks from `config.xml`;
* Plugin hooks from `plugins/.../plugin.xml`.

#### Based on the Internal order of execution

The internal order of execution of hooks is fixed.

##### Example 1 (cordova platform add)
If there are hooks associated with `before_platform_add`, `after_platform_add`, `before_prepare`, `after_prepare`,
`before_plugin_install` and `after_plugin_install` (and assuming you have one plugin installed on your project),
adding a new platform will execute the hooks in the following order:

```
before_platform_add
    before_prepare
    after_prepare
    before_plugin_install
    after_plugin_install
after_platform_add
```

##### Example 2 (cordova build)
If there are hooks associated with `before_prepare`, `after_prepare`, `before_compile`, `after_compile`, `before_build`
and `after_build` - running a build command will execute the hooks in the following order:

```
before_build
    before_prepare
    after_prepare
    before_compile
    after_compile
after_build
```

## Script Interface
### Windows Quirks

If you are working on Windows, and in case your hook (Javascript/Non-Javascript)scripts aren't bat files (which is recommended, if you want your scripts to work in non-Windows operating systems) Cordova CLI will expect a shebang line as the first line for it to know the interpreter it needs to use to launch the script. The shebang line should match the following example:

```
#!/usr/bin/env [name_of_interpreter_executable]
```

### Javascript

If you are writing hooks using Node.js you should use the following module definition:

```javascript
module.exports = function(context) {
    ...
}
```

`context` object contains hook type, executed script full path, hook options, command-line arguments passed to Cordova and top-level "cordova" object of the following format:

```json
{
  "hook": "before_plugin_install",
  "scriptLocation": "c:\\script\\full\\path\\appBeforePluginInstall.js",
  "cmdLine": "The\\exact\\command\\cordova\\run\\with arguments",
  "opts": {
    "projectRoot":"C:\\path\\to\\the\\project",
    "cordova": {
      "platforms": ["android"],
      "plugins": ["plugin-withhooks"],
      "version": "0.21.7-dev"
    },
    "plugin": {
      "id": "plugin-withhooks",
      "pluginInfo": {
        ...
      },
      "platform": "android",
      "dir": "C:\\path\\to\\the\\project\\plugins\\plugin-withhooks"
    }
  },
  "cordova": {...}
}

```
`context.opts.plugin` object will only be passed to plugin hooks scripts.

You can also require additional Cordova modules in your script using `context.requireCordovaModule` in the following way:

```javascript
var Q = context.requireCordovaModule('q');
```

You can make your scipts async using Q:

```javascript
module.exports = function(context) {
    var Q = context.requireCordovaModule('q');
    var deferral = new Q.defer();

    setTimeout(function(){
      console.log('hook.js>> end');
    deferral.resolve();
    }, 1000);

    return deferral.promise;
}
```
> __Note__:  new module loader script interface is used for the `.js` files defined via `config.xml` or `plugin.xml` only.
For compatibility reasons hook files specified via `/hooks` folders are run via Node child_process spawn, see 'Non-javascript' section below.

### Non-javascript

Non-javascript scripts are run via Node child_process spawn from the project's root directory and have the root directory passes as the first argument. All other options are passed to the script using environment variables:

Environment Variable Name     | Description
------------------------------|--------------------------------------------
CORDOVA_VERSION               | The version of the Cordova-CLI.
CORDOVA_PLATFORMS             | Comma separated list of platforms that the command applies to (e.g: android, ios).
CORDOVA_PLUGINS               | Comma separated list of plugin IDs that the command applies to (e.g: cordova-plugin-file-transfer, cordova-plugin-file).
CORDOVA_HOOK                  | Path to the hook that is being executed.
CORDOVA_CMDLINE               | The exact command-line arguments passed to cordova (e.g: cordova run ios --emulate).

If a script returns a non-zero exit code, then the parent cordova command will be aborted.

> __Note__: we highly recommend writing your hooks using Node.js so that they are cross-platform, see [Javascript](#link-javascript) section above.

## Sample Usage

This sample demonstrates Cordova hooks usage to trace to the console output the
size of generated .apk file for Android platform.

Create blank Cordova app and add the following definition to `config.xml` to
tell Cordova to run `afterBuild.js` script after each platform build.

```xml
<hook type="after_build" src="scripts/afterBuild.js" />
```

Create `scripts/afterBuild.js` file and add the following implementation.
We use async version of `fs.stat` method to demonstrate how async functionality
could be done via hooks.

```javascript
module.exports = function(ctx) {
    // make sure android platform is part of build
    if (ctx.opts.platforms.indexOf('android') < 0) {
        return;
    }
    var fs = ctx.requireCordovaModule('fs'),
        path = ctx.requireCordovaModule('path'),
        deferral = ctx.requireCordovaModule('q').defer();

    var platformRoot = path.join(ctx.opts.projectRoot, 'platforms/android');
    var apkFileLocation = path.join(platformRoot, 'build/outputs/apk/android-debug.apk');

    fs.stat(apkFileLocation, function(err,stats) {
        if (err) {
                deferral.reject('Operation failed');
        } else {
            console.log('Size of ' + apkFileLocation + ' is ' + stats.size +' bytes');
            deferral.resolve();
        }
    });

    return deferral.promise;
};
```

Parameter `ctx` in example above is passed by Cordova and represents execution
context such as script full path, target platform, command-line arguments, etc and
also exposes additional helper functionality. See `Script Interface` section above
for more details.

You can now add android platform and execute build.

```
cordova platform add android
..
cordova build
..
Size of path\to\app\platforms\android\build\outputs\apk\android-debug.apk is 1821193 bytes
```

More good usage examples could be found in [Three Hooks Your Cordova Phone Gap Project needs][Devgirl_Hooks_Link]

[Devgirl_Hooks_Link]: http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/


text:
<?php
/**
 * @file
 * @author: dabeen(lidianbin@baidu.com)
 * @date:   2017-01-03 16:50:06
 * @Last Modified by:   dabeen
 * @Last Modified time: 2017-01-03 16:58:21
 */

namespace Beenlee\Framework\Storage;
use Exception;

class StorageException extends Exception {

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using JetBrains.Annotations;

namespace iSukces.Code.VsSolutions
{
    public class NugetVersionRange
    {
        public static NugetVersionRange Parse([NotNull] string text)
        {
            if (text == null) throw new ArgumentNullException("text");
            text = text.Trim();
            const string msg     = "Invalid version range {0}";
            var          minEdge = ParseRangeEdge(text[0], '[', '(');
            var          maxEdge = ParseRangeEdge(text[text.Length - 1], ']', ')');

            if (minEdge != RangeEdge.None)
                text = text.Substring(1).Trim();
            if (maxEdge != RangeEdge.None)
                text = text.Substring(0, text.Length - 1).Trim();

            var textArray = text.Split(',');
            if (textArray.Length > 2)
                throw new Exception(string.Format(msg, text));

            var result = new NugetVersionRange
            {
                VersionMin = NugetVersion.Parse(textArray[0]),
                MinEdge    = minEdge,
                MaxEdge    = maxEdge
            };
            result.VersionMax = textArray.Length == 2
                ? NugetVersion.Parse(textArray[1])
                : result.VersionMin;
            return result;
        }
        // Private Methods

        private static RangeEdge ParseRangeEdge(char c, char t, char f) =>
            c == t ? RangeEdge.Inclusive : c == f ? RangeEdge.Exclusive : RangeEdge.None;

        private static string RangeEdgeToString(RangeEdge flag, string inclusiveText, string exclusiveText)
        {
            switch (flag)
            {
                case RangeEdge.Inclusive:
                    return inclusiveText;
                case RangeEdge.Exclusive:
                    return exclusiveText;
            }

            return "";
        }

        // Public Methods

        public VersionCheckResult CheckVersion(NugetVersion x)
        {
            if (_matchAnyVersion)
                return VersionCheckResult.Ok;
            if (x < VersionMin)
                return VersionCheckResult.TooLow;
            if (x <= VersionMin && MinEdge == RangeEdge.Exclusive)
                return VersionCheckResult.TooLow;

            if (x > VersionMax)
                return VersionCheckResult.TooHigh;
            if (x >= VersionMax && MaxEdge == RangeEdge.Exclusive)
                return VersionCheckResult.TooHigh;

            return VersionCheckResult.Ok;
        }

        public override string ToString()
        {
            if (_matchAnyVersion)
                return "Any version";
            if (VersionMin.ToString() == VersionMax.ToString()
                && MinEdge == RangeEdge.None
                && MaxEdge == RangeEdge.None)
                return VersionMin.ToString();
            return string.Format("{1}{0} x {2}{3}",
                RangeEdgeToString(MinEdge, "<=", "<"),
                VersionMin,
                RangeEdgeToString(MaxEdge, "<=", "<"),
                VersionMax
            );
        }

        public static NugetVersionRange Any
        {
            get
            {
                return new NugetVersionRange
                {
                    _matchAnyVersion = true
                };
            }
        }

        public NugetVersion VersionMin { get; set; }

        public NugetVersion VersionMax { get; set; }

        public RangeEdge MinEdge { get; set; }

        public RangeEdge MaxEdge { get; set; }

        private bool _matchAnyVersion;
    }
}


text:
FROM debian:jessie

# persistent / runtime deps
ENV PHPIZE_DEPS \
		autoconf \
		file \
		g++ \
		gcc \
		libc-dev \
		make \
		pkg-config \
		re2c
RUN apt-get update && apt-get install -y \
		$PHPIZE_DEPS \
		ca-certificates \
		curl \
		libedit2 \
		libsqlite3-0 \
		libxml2 \
		xz-utils \
	--no-install-recommends && rm -r /var/lib/apt/lists/*

ENV PHP_INI_DIR /usr/local/etc/php
RUN mkdir -p $PHP_INI_DIR/conf.d

##<autogenerated>##
ENV PHP_EXTRA_CONFIGURE_ARGS --enable-maintainer-zts
##</autogenerated>##

ENV GPG_KEYS 0BD78B5F97500D450838F95DFE857D9A90D90EC1 6E4F6AB321FDC07F2C332E3AC2BF0BC433CFC8B3

ENV PHP_VERSION 5.6.26
ENV PHP_FILENAME php-5.6.26.tar.xz
ENV PHP_SHA256 203a854f0f243cb2810d1c832bc871ff133eccdf1ff69d32846f93bc1bef58a8

RUN set -xe \
	&& cd /usr/src \
	&& curl -fSL "https://secure.php.net/get/$PHP_FILENAME/from/this/mirror" -o php.tar.xz \
	&& echo "$PHP_SHA256 *php.tar.xz" | sha256sum -c - \
	&& curl -fSL "https://secure.php.net/get/$PHP_FILENAME.asc/from/this/mirror" -o php.tar.xz.asc \
	&& export GNUPGHOME="$(mktemp -d)" \
	&& for key in $GPG_KEYS; do \
		gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key"; \
	done \
	&& gpg --batch --verify php.tar.xz.asc php.tar.xz \
	&& rm -r "$GNUPGHOME"

COPY docker-php-source /usr/local/bin/

RUN set -xe \
	&& buildDeps=" \
		$PHP_EXTRA_BUILD_DEPS \
		libcurl4-openssl-dev \
		libedit-dev \
		libsqlite3-dev \
		libssl-dev \
		libxml2-dev \
	" \
	&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
	\
	&& docker-php-source extract \
	&& cd /usr/src/php \
	&& ./configure \
		--with-config-file-path="$PHP_INI_DIR" \
		--with-config-file-scan-dir="$PHP_INI_DIR/conf.d" \
		\
		--disable-cgi \
		--enable-bcmath \
		\
# --enable-ftp is included here because ftp_ssl_connect() needs ftp to be compiled statically (see https://github.com/docker-library/php/issues/236)
		--enable-ftp \
# --enable-mbstring is included here because otherwise there's no way to get pecl to use it properly (see https://github.com/docker-library/php/issues/195)
		--enable-mbstring \
# --enable-mysqlnd is included here because it's harder to compile after the fact than extensions are (since it's a plugin for several extensions, not an extension in itself)
		--enable-mysqlnd \
		\
		--with-curl \
		--with-mhash \
		--with-libedit \
		--with-openssl \
		--with-zlib \
		\
		$PHP_EXTRA_CONFIGURE_ARGS \
	&& make -j"$(nproc)" \
	&& make install \
	&& { find /usr/local/bin /usr/local/sbin -type f -executable -exec strip --strip-all '{}' + || true; } \
	&& make clean \
	&& docker-php-source delete \
	\
	&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false $buildDeps

COPY docker-php-ext-* /usr/local/bin/

##<autogenerated>##
CMD ["php", "-a"]
##</autogenerated>##


text:
package net.runelite.client.task;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import javax.inject.Inject;
import javax.inject.Singleton;
import lombok.extern.slf4j.Slf4j;

@Singleton
@Slf4j
public class Scheduler
{
	private final List<ScheduledMethod> scheduledMethods = new CopyOnWriteArrayList<>();

	@Inject
	ScheduledExecutorService executor;

	public void addScheduledMethod(ScheduledMethod method)
	{
		scheduledMethods.add(method);
	}

	public void removeScheduledMethod(ScheduledMethod method)
	{
		scheduledMethods.remove(method);
	}

	public List<ScheduledMethod> getScheduledMethods()
	{
		return Collections.unmodifiableList(scheduledMethods);
	}

	public void tick()
	{
		Instant now = Instant.now();

		for (ScheduledMethod scheduledMethod : scheduledMethods)
		{
			Instant last = scheduledMethod.getLast();

			Duration difference = Duration.between(last, now);

			Schedule schedule = scheduledMethod.getSchedule();
			Duration timeSinceRun = Duration.of(schedule.period(), schedule.unit());

			if (difference.compareTo(timeSinceRun) > 0)
			{
				log.trace("Scheduled task triggered: {}", scheduledMethod);

				scheduledMethod.setLast(now);

				if (schedule.asynchronous())
				{
					executor.submit(() -> run(scheduledMethod));
				}
				else
				{
					run(scheduledMethod);
				}
			}
		}
	}

	private void run(ScheduledMethod scheduledMethod)
	{
		try
		{
			Runnable lambda = scheduledMethod.getLambda();
			if (lambda != null)
			{
				lambda.run();
			}
			else
			{
				Method method = scheduledMethod.getMethod();
				method.invoke(scheduledMethod.getObject());
			}
		}
		catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex)
		{
			log.warn("error invoking scheduled task", ex);
		}
		catch (Exception ex)
		{
			log.warn("error during scheduled task", ex);
		}
	}
}


text:
<?php

namespace Google\Cloud\Spanner\Tests\Unit;

use Google\Cloud\Spanner\CommitTimestamp;
use Google\Cloud\Spanner\Database;
use Yoast\PHPUnitPolyfills\TestCases\TestCase;

/**
 * @group spanner
 */
class CommitTimestampTest extends TestCase
{
    private $t;

    public function set_up()
    {
        $this->t = new CommitTimestamp;
    }

    public function testType()
    {
        $this->assertEquals(Database::TYPE_TIMESTAMP, $this->t->type());
    }

    /**
     * @dataProvider methodProvider
     */
    public function testValues($method)
    {
        $this->assertEquals(CommitTimestamp::SPECIAL_VALUE, $this->t->$method());
    }

    public function methodProvider()
    {
        return [
            ['get'],
            ['formatAsString'],
            ['__toString'],
        ];
    }
}


text:
package io.coala.xml;

import javax.xml.stream.XMLInputFactory;

import org.aeonbits.owner.Config.LoadPolicy;
import org.aeonbits.owner.Config.LoadType;
import org.aeonbits.owner.Config.Sources;
import org.aeonbits.owner.ConfigCache;

import io.coala.config.GlobalConfig;
import io.coala.config.YamlConfig;
import io.coala.log.LogUtil;

/**
 * {@link StAXConfig}
 *
 * @version $Id: b8d074110a052aa4099af0f651d94410ffe8f661 $
 * @author Rick van Krevelen
 */
@LoadPolicy( LoadType.MERGE )
@Sources( { "classpath:" + StAXConfig.STAX_CONFIG_FILE_LOCATION } )
public interface StAXConfig extends GlobalConfig, YamlConfig
{
	String STAX_CONFIG_FILE_LOCATION = "stax.properties";

	/**
	 * @return the system property for {@code javax.xml.stream.XMLInputFactory}
	 *         as per the javadoc of {@link XMLInputFactory#newFactory()}
	 */
	@Key( "javax.xml.stream.XMLInputFactory" )
//	@DefaultValue( "com.ctc.wstx.stax.WstxInputFactory" )
//	@DefaultValue( "com.sun.xml.internal.stream.XMLInputFactoryImpl" )
	Class<? extends XMLInputFactory> xmlInputFactoryImpl();

	@Key( XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES )
	@DefaultValue( "" + false )
	Boolean isReplacingEntityReferences();

	@Key( XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES )
	@DefaultValue( "" + false )
	Boolean isSupportingExternalEntities();

	@Key( XMLInputFactory.IS_COALESCING )
	@DefaultValue( "" + false )
	Boolean isCoalescing();

	/** @return a cached StAXConfig instance */
	static StAXConfig getOrCreate()
	{
		return ConfigCache.getOrCreate( StAXConfig.class,
				System.getProperties(), System.getenv() );
	}

	/**
	 * @return a new (StAX) XMLInputFactory instance
	 * @see javax.xml.stream.XMLInputFactory#newFactory()
	 */
	default XMLInputFactory newXMLInputFactory()
	{
//		@SuppressWarnings( "deprecation" )
		final XMLInputFactory result = XMLInputFactory.newInstance(
//				xmlInputFactoryImpl().getName(),
//				Thread.currentThread().getContextClassLoader()
				);
		LogUtil.getLogger( StAXConfig.class ).trace( "Using StAX {}: {}",
				XMLInputFactory.class.getSimpleName(),
				result.getClass().getName() );
		result.setProperty( XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,
				isReplacingEntityReferences() );
		result.setProperty( XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,
				isSupportingExternalEntities() );
		result.setProperty( XMLInputFactory.IS_COALESCING, isCoalescing() );
		return result;
	}
}


text:
namespace picojson {

class value;

}  // namespace picojson

class DownloadInstance : public common::Instance {
 public:
  DownloadInstance();
  ~DownloadInstance();

 private:
  VirtualFS vfs_;
  virtual void HandleMessage(const char* msg);
  virtual void HandleSyncMessage(const char* msg);

  void HandleStart(const picojson::value& msg);
  template <typename FnType>
  bool HandleGeneral(const picojson::value& msg,
                     FnType fn,
                     const char* fn_name);
  void HandleGetState(const picojson::value& msg);
  void HandleGetNetworkType(const picojson::value& msg);
  void HandleGetMIMEType(const picojson::value& msg);
  struct DownloadArgs {
    std::string download_uid;
    DownloadInstance* instance;
    DownloadArgs(std::string uid, DownloadInstance* i)
      : download_uid(uid), instance(i) {}
  };
  typedef std::vector<DownloadArgs*> DownloadArgsVector;
  DownloadArgsVector args_;
  static void OnStateChanged(int download_id,
                             download_state_e state,
                             void* user_data);
  static void OnProgressInfo(int download_id,
                             long long unsigned received,  // NOLINT
                             void* user_param);
  static void OnStartInfo(int download_id, void* user_param);
  static void OnFinishedInfo(int download_id, void* user_param);
  static void OnPausedInfo(void* user_param);
  static void OnCanceledInfo(void* user_param);
  static void OnFailedInfo(void* user_param,
                           const std::string& error);

  struct DownloadItem {
    std::string uid;
    std::string url;
    std::string destination;
    std::string file_name;
    download_network_type_e network_type;
    std::string http_header;

    int download_id;
    char* file_type;
    long long unsigned file_size;  // NOLINT
    char* tmp_saved_path;
    char* content_name;

    DownloadItem() {}
    ~DownloadItem() {
      download_unset_state_changed_cb(download_id);
      download_unset_progress_cb(download_id);
      download_destroy(download_id);
    }

   private:
    DISALLOW_COPY_AND_ASSIGN(DownloadItem);
  };
  typedef std::tr1::shared_ptr<DownloadItem> DownloadItemRefPtr;
  typedef std::map<std::string, DownloadItemRefPtr> DownloadItemMap;
  DownloadItemMap downloads_;

  const std::string GetFullDestinationPath(const std::string destination) const;

  bool GetDownloadID(const picojson::value& msg,
                     int& download_id, DownloadArgs** args);
  bool GetID(const picojson::value& msg,
             std::string& uid, int& download_id) const;
  std::string GetUID(int download_id) const;

 private:
  DISALLOW_COPY_AND_ASSIGN(DownloadInstance);
};

#endif  // DOWNLOAD_DOWNLOAD_INSTANCE_H_


text:
#include "clsparse-validate.hpp"
#include "ocl-type-traits.hpp"
#include <iostream>
#include <string>

template< typename T >
std::string to_string_comma( T num )
{
    std::string num_string = std::to_string( num );

    // Signed is important; if length < 3 then we need a negative number
    int comma_pos = static_cast<int>( num_string.length( ) ) - 3;
    while( comma_pos > 0 )
    {
        num_string.insert( comma_pos, "," );
        comma_pos -= 3;
    }

    return num_string;
}

clsparseStatus
validateMemObject(clsparseScalarPrivate &scalar, size_t required_size)
{
#if !defined(NDEBUG) && (BUILD_CLVERSION >= 200)
    std::cout << "Don't know how to validate SVM void* buffer" << std::endl;
    return clsparseSuccess;
#else
    return validateMemObject(scalar.value, required_size);
#endif
}

clsparseStatus
validateMemObject(cldenseVector &vector, size_t required_size)
{
#if !defined(NDEBUG) && (BUILD_CLVERSION >= 200)
    std::cout << "Don't know how to validate SVM void* buffer" << std::endl;
    return clsparseSuccess;
#else
    return validateMemObject(vector.values, required_size);
#endif
}

clsparseStatus
validateMemObject(void* mem, size_t required_size)
{
#ifndef NDEBUG
    std::cout << "validateMemObject void* buffer" << std::endl;
#endif
    return clsparseSuccess;
}

clsparseStatus
validateMemObject( cl_mem mem, size_t required_size)
{
#ifndef NDEBUG
    //check if valid mem object,
    cl_mem_object_type mem_type = 0;
    clGetMemObjectInfo(mem, CL_MEM_TYPE, sizeof(mem_type), &mem_type, NULL);
    if (mem_type != CL_MEM_OBJECT_BUFFER)
    {
        return clsparseInvalidMemObj;
    }
    //check if mem object have valid required size
    if (required_size > 0)
    {
        size_t current_size;
        clGetMemObjectInfo(mem, CL_MEM_SIZE,
                            sizeof(current_size), &current_size, NULL);

        std::cout << "[validateMemObject] Buffer size: " << to_string_comma( current_size ) << " bytes. ";
        std::cout << "Required size: " << to_string_comma( required_size ) << " bytes." << std::endl;
        if (current_size < required_size)
            return clsparseInvalidSize;
    }
#endif
    return clsparseSuccess;
}

/*
 * Validate cl_mem buffers regarding required size including offset;
 * element_size - size of vector element in bytes, sizeof(T)
 * count - number of elements,
 * mem - object to validate
 * off_mem - offset of first element of vector mem counted in elements
 */
clsparseStatus
validateMemObjectSize(size_t element_size,
                       size_t count,
                       cl_mem mem,
                       size_t off_mem)
{
#ifndef NDEBUG
    size_t mem_size; //cl_mem current size
    size_t vec_size = count * element_size;
    off_mem *= element_size; //it's a copy

    if (count == 0)
    {
        return clsparseInvalidSize;
    }

    cl_int status =
            clGetMemObjectInfo(mem, CL_MEM_SIZE,
                               sizeof(mem_size), &mem_size, NULL);
    if (status != CL_SUCCESS)
    {
        return clsparseInvalidMemObj;
    }

    if ((off_mem + vec_size > mem_size) || (off_mem + vec_size < off_mem))
    {
        return clsparseInsufficientMemory;
    }
#endif
    return clsparseSuccess;
}


text:
package com.asakusafw.lang.compiler.model.description;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Test;

import com.asakusafw.lang.compiler.model.description.TypeDescription.TypeKind;

/**
 * Test for {@link ClassDescription}.
 */
public class ClassDescriptionTest {

    /**
     * simple case.
     */
    @Test
    public void simple() {
        ClassDescription desc = new ClassDescription("com.example.Testing");
        assertThat(desc.getTypeKind(), is(TypeKind.CLASS));
        assertThat(desc.getClassName(), is("com.example.Testing"));
        assertThat(desc.getBinaryName(), is("com.example.Testing"));
        assertThat(desc.getInternalName(), is("com/example/Testing"));
        assertThat(desc.getSimpleName(), is("Testing"));
    }

    /**
     * simple case.
     * @throws Exception if failed
     */
    @Test
    public void of() throws Exception {
        ClassDescription desc = ClassDescription.of(String.class);
        assertThat(desc.getClassName(), is("java.lang.String"));
        assertThat(desc.getBinaryName(), is("java.lang.String"));
        assertThat(desc.getInternalName(), is("java/lang/String"));
        assertThat(desc.getSimpleName(), is("String"));
        assertThat(desc.resolve(getClass().getClassLoader()), is((Object) String.class));
    }

    /**
     * inner class.
     * @throws Exception if failed
     */
    @Test
    public void of_inner() throws Exception {
        ClassDescription desc = ClassDescription.of(Thread.State.class);
        assertThat(desc.getClassName(), is("java.lang.Thread.State"));
        assertThat(desc.getBinaryName(), is("java.lang.Thread$State"));
        assertThat(desc.getInternalName(), is("java/lang/Thread$State"));
        assertThat(desc.getSimpleName(), is("State"));
        assertThat(desc.resolve(getClass().getClassLoader()), is((Object) Thread.State.class));
    }

    /**
     * pass primitive type.
     * @throws Exception if failed
     */
    @Test(expected = IllegalArgumentException.class)
    public void of_primitive() throws Exception {
        ClassDescription.of(int.class);
    }

    /**
     * pass array type.
     * @throws Exception if failed
     */
    @Test(expected = IllegalArgumentException.class)
    public void of_array() throws Exception {
        ClassDescription.of(String[].class);
    }
}


text:
// Generated by CoffeeScript 1.7.1
var concat, gulp, jsFiles, jshint, rename, sass, uglify;

gulp = require('gulp');

jshint = require('gulp-jshint');

sass = require('gulp-sass');

concat = require('gulp-concat');

uglify = require('gulp-uglify');

rename = require('gulp-rename');

jsFiles = ['src/*.js', 'src/services/*.js', 'src/controllers/*.js', 'src/directives/*.js'];

gulp.task('lint', function() {
  return gulp.src(jsFiles).pipe(jshint()).pipe(jshint.reporter('default'));
});

/*
 * Compile Our Sass
gulp.task 'sass', ->
  gulp.src('scss/*.scss')
    .pipe(sass())
    .pipe gulp.dest('css')
 */

gulp.task('scripts', function() {
  return gulp.src(jsFiles).pipe(concat('rogue-like-like.js')).pipe(gulp.dest('dist')).pipe(rename('rogue-like-like.min.js')).pipe(uglify()).pipe(gulp.dest('dist'));
});

gulp.task('watch', function() {
  gulp.watch(jsFiles, ['lint', 'scripts']);
});

gulp.task('default', ['lint', 'scripts', 'watch']);


text:
class AssessorAssignmentService
  attr_reader :params, :current_subject, :resource
  DESC_REGEX = /_desc$/
  RATE_REGEX = /_rate$/

  def initialize(params, current_subject)
    @params = params
    @current_subject = current_subject
    @resource = AssessorAssignment.find(params[:id])
    normalize_params
  end

  def save
    resource.assign_attributes(update_params)
    resource.editable = current_subject
    resource.assessed_at = DateTime.now unless assignment_request?
    resource.save
  end

  def permitted_params
    permitted = AppraisalForm.all
    permitted += assignment_params if admin_or_lead?
    permitted
  end

  private

  def update_params
    params.require(:assessor_assignment).permit(*permitted_params)
  end

  def admin_or_lead?
    current_subject.is_a?(Admin) || current_subject.try(:lead?, form_answer)
  end

  def normalize_params
    p = params[:assessor_assignment]
    p.delete_if { |k, v| v.blank? && k != "assessor_id" }
    if updated_section.present?
      # Because every text field has separated submit form button
      # but there is only single huge form for all of the descriptions
      # it's needed to updated only description marked explicitly by the admin
      # to achieve data other description fields should be removed from params
      if updated_section =~ DESC_REGEX
        p.delete_if { |k, _| k =~ DESC_REGEX && k != updated_section }
      elsif updated_section =~ RATE_REGEX
        p.delete_if { |k, _| k != updated_section && (k =~ DESC_REGEX || k =~ RATE_REGEX) }
      end
    end
  end

  def updated_section
    params[:updated_section]
  end

  def assignment_request?
    (update_params.keys.map(&:to_s) & assignment_params.map(&:to_s)).present?
  end

  def assignment_params
    [:assessor_id]
  end

  def form_answer
    @form_answer ||= FormAnswer.find(resource.form_answer_id)
  end
end


text:
package uk.co.benjiweber.expressions.caseclass;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static uk.co.benjiweber.expressions.caseclass.DecompositionConstructorReferenceTest.Person;
import static uk.co.benjiweber.expressions.caseclass.DecompositionConstructorReferenceTest.Person.person;
import static uk.co.benjiweber.expressions.caseclass.MatchesAny._;

public class UnreadableDecompositionTest {

    @Test
    public void one_missings() {
        assertEquals("foo", person("Bob", "asdf", 18).match().when(Person::person, _, "asdf", 18).then(a -> "foo")._("unknown"));
        assertEquals("unknown", person("Bob", "fdsa", 18).match().when(Person::person, _, "asdf", 18).then(a -> "foo")._("unknown"));

        assertEquals("foo", person("Bob", "sfasdf", 18).match().when(Person::person, "Bob", _, 18).then(a -> "foo")._("unknown"));
        assertEquals("unknown", person("Bob", "", 18).match().when(Person::person, "Bill", _, 18).then(a -> "foo")._("unknown"));

        assertEquals("foo", person("Bob", "sfasdf", 18).match().when(Person::person, "Bob", "sfasdf", _).then(a -> "foo")._("unknown"));
        assertEquals("unknown", person("Bob", "", 18).match().when(Person::person, "Bob", "sfasdf", _).then(a -> "foo")._("unknown"));

        assertEquals("foo", person("Bob", "asdf", 18).match().when(Person::person, _, "aaaaaaa", 18).then(age -> "aaaaaaa").when(Person::person, _,"asdf", 18).then(a -> "foo")._("unknown"));
        assertEquals("unknown", person("Bob", "fdsa", 18).match().when(Person::person, _, "aaaaaaa", 18).then(age -> "aaaaaaa").when(Person::person, _,"asdf", 18).then(a -> "foo")._("unknown"));

        assertEquals("foo", person("Bob", "asdf", 18).match().when(Person::person, _, "aaaaaaa", 18).then(age -> "aaaaaaa").when(Person::person, "Bob",_, 18).then(a -> "foo")._("unknown"));
        assertEquals("unknown", person("Bob", "fdsa", 18).match().when(Person::person, _, "aaaaaaa", 18).then(age -> "aaaaaaa").when(Person::person, "Bill",_, 18).then(a -> "foo")._("unknown"));

        assertEquals("foo", person("Bob", "asdf", 18).match().when(Person::person, _, "aaaaaaa", 18).then(age -> "aaaaaaa").when(Person::person, "Bob","asdf", _).then(a -> "foo")._("unknown"));
        assertEquals("unknown", person("Bob", "fdsa", 18).match().when(Person::person, _, "aaaaaaa", 18).then(age -> "aaaaaaa").when(Person::person, "Bob","asdf", _).then(a -> "foo")._("unknown"));
    }

    @Test
    public void all_missing() {
        assertEquals("foo", person("Bob","asdf",18).match().when(Person::person, _,_,_).then((firstname,lastname,age) -> "foo")._(""));
    }

    @Test
    public void none_missing() {
        assertEquals("foo", person("Bob","asdf",18).match().when(Person::person, "Bob", "asdf", 18).then(person -> "foo")._(""));
    }

}


text:
import argparse
import subprocess
import utils.utils as utils
import os

parser = argparse.ArgumentParser(
        description="cleanup (remove comments and redundancies) configuration of design(s) per given PDK")

parser.add_argument('--designs_dir', '-r', action='store', default='./designs',
                help="The root directory for the designs.")

parser.add_argument('--pdk', '-p', action='store', required=True,
                help="The name of the PDK")

parser.add_argument('--std-cell-library', '-scl', action='store', required=True,
                help="The name of the standard cell library")

parser.add_argument('--designs', '-d', nargs='+', default=[],
                help="designs to update ")

args = parser.parse_args()
root = args.designs_dir
pdk = args.pdk
std_cell_library = args.std_cell_library
designs = list(dict.fromkeys(args.designs))

if len(designs) == 0:
    designs= [x  for x in os.listdir(str(root)+'/')]
    for i in designs:
        if os.path.isdir(str(root)+'/'+i) == False:
            designs.remove(i)

for design in designs:
    print("Updating "+ design + " config...")
    try:
        base_path = utils.get_design_path(design=design)
        configFileToUpdate = str(base_path)+"/"+str(pdk)+"_"+str(std_cell_library)+"_config.tcl"
        configFileToUpdateOpener = open(configFileToUpdate, 'r')
        configsContent = configFileToUpdateOpener.read().split("\n")
        configFileToUpdateOpener.close()
        configsMap = dict()
        for line in configsContent:
            if line.strip().startswith("set"):
                config = ' '.join(line.split()).split()
                if len(config) > 2:
                    configsMap[config[1]] = ' '.join(config[2:])
        newData= "# SCL Configs\n"
        for key in configsMap:
            newData+= "set "+key+" "+configsMap[key]+"\n"
        configFileToUpdateOpener = open(configFileToUpdate, 'w')
        configFileToUpdateOpener.write(newData)
        configFileToUpdateOpener.close()
    except OSError as e:
        print("No config found for "+ design)


text:
package com.socks.androiddemo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by zhaokaiqiang on 15/9/17.
 */
public class ShaderView extends View {

    private float mWidth;
    private float mHeight;

    private Paint mPaint;

    LinearGradient linearGradient;

    public ShaderView(Context context) {
        super(context);
        init();
    }

    public ShaderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ShaderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
        linearGradient = new LinearGradient(0, 0, 0, mHeight / 2,
                new int[]{Color.RED, Color.YELLOW},
                new float[]{0.2f, 0.8f}, Shader.TileMode.CLAMP);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setShader(linearGradient);
        canvas.drawRect(0, 0, mWidth / 2, mHeight / 2, mPaint);
    }
}


text:
using content::BrowserThread;
using fileapi::ConflictFileInfoCallback;
using fileapi::FileSystemURL;
using fileapi::SyncFileMetadata;
using fileapi::SyncStatusCallback;
using fileapi::SyncStatusCode;

namespace sync_file_system {

namespace {

// Run the given join_callback when all the callbacks created by this runner
// are run. If any of the callbacks return non-OK state the given join_callback
// will be dispatched with the non-OK state that comes first.
class SharedCallbackRunner
    : public base::RefCountedThreadSafe<SharedCallbackRunner> {
 public:
  explicit SharedCallbackRunner(const SyncStatusCallback& join_callback)
      : join_callback_(join_callback),
        num_shared_callbacks_(0),
        status_(fileapi::SYNC_STATUS_OK) {}

  SyncStatusCallback CreateCallback() {
    ++num_shared_callbacks_;
    return base::Bind(&SharedCallbackRunner::Done, this);
  }

  template <typename R>
  base::Callback<void(SyncStatusCode, const R& in)>
  CreateAssignAndRunCallback(R* out) {
    ++num_shared_callbacks_;
    return base::Bind(&SharedCallbackRunner::AssignAndRun<R>, this, out);
  }

 private:
  virtual ~SharedCallbackRunner() {}
  friend class base::RefCountedThreadSafe<SharedCallbackRunner>;

  template <typename R>
  void AssignAndRun(R* out, SyncStatusCode status, const R& in) {
    DCHECK(out);
    DCHECK_GT(num_shared_callbacks_, 0);
    if (join_callback_.is_null())
      return;
    *out = in;
    Done(status);
  }

  void Done(SyncStatusCode status) {
    if (status != fileapi::SYNC_STATUS_OK &&
        status_ == fileapi::SYNC_STATUS_OK) {
      status_ = status;
    }
    if (--num_shared_callbacks_ > 0)
      return;
    join_callback_.Run(status_);
    join_callback_.Reset();
  }

  SyncStatusCallback join_callback_;
  int num_shared_callbacks_;
  SyncStatusCode status_;
};

void VerifyFileSystemURLSetCallback(
    base::WeakPtr<SyncFileSystemService> service,
    const GURL& app_origin,
    const std::string& service_name,
    const fileapi::SyncFileSetCallback& callback,
    fileapi::SyncStatusCode status,
    const fileapi::FileSystemURLSet& urls) {
  if (!service.get())
    return;

#ifndef NDEBUG
  if (status == fileapi::SYNC_STATUS_OK) {
    for (fileapi::FileSystemURLSet::const_iterator iter = urls.begin();
         iter != urls.end(); ++iter) {
      DCHECK(iter->origin() == app_origin);
      DCHECK(iter->filesystem_id() == service_name);
    }
  }
#endif

  callback.Run(status, urls);
}

SyncEventObserver::SyncServiceState RemoteStateToSyncServiceState(
    RemoteServiceState state) {
  switch (state) {
    case REMOTE_SERVICE_OK:
      return SyncEventObserver::SYNC_SERVICE_RUNNING;
    case REMOTE_SERVICE_TEMPORARY_UNAVAILABLE:
      return SyncEventObserver::SYNC_SERVICE_TEMPORARY_UNAVAILABLE;
    case REMOTE_SERVICE_AUTHENTICATION_REQUIRED:
      return SyncEventObserver::SYNC_SERVICE_AUTHENTICATION_REQUIRED;
    case REMOTE_SERVICE_DISABLED:
      return SyncEventObserver::SYNC_SERVICE_DISABLED;
  }
  NOTREACHED();
  return SyncEventObserver::SYNC_SERVICE_DISABLED;
}

}  // namespace

void SyncFileSystemService::Shutdown() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  local_file_service_->Shutdown();
  local_file_service_.reset();

  remote_file_service_.reset();

  profile_ = NULL;
}

SyncFileSystemService::~SyncFileSystemService() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!profile_);
}

void SyncFileSystemService::InitializeForApp(
    fileapi::FileSystemContext* file_system_context,
    const std::string& service_name,
    const GURL& app_origin,
    const SyncStatusCallback& callback) {
  DCHECK(local_file_service_);
  DCHECK(remote_file_service_);
  DCHECK(app_origin == app_origin.GetOrigin());

  DVLOG(1) << "InitializeForApp: " << app_origin.spec();

  if (initialized_app_origins_.find(app_origin) !=
      initialized_app_origins_.end()) {
    DVLOG(1) << "The app is already initialized: " << app_origin.spec();
    callback.Run(fileapi::SYNC_STATUS_OK);
    return;
  }

  local_file_service_->MaybeInitializeFileSystemContext(
      app_origin, service_name, file_system_context,
      base::Bind(&SyncFileSystemService::DidInitializeFileSystem,
                 AsWeakPtr(), app_origin, callback));
}

void SyncFileSystemService::GetConflictFiles(
    const GURL& app_origin,
    const std::string& service_name,
    const fileapi::SyncFileSetCallback& callback) {
  DCHECK(remote_file_service_);
  DCHECK(app_origin == app_origin.GetOrigin());

  if (!ContainsKey(initialized_app_origins_, app_origin)) {
    callback.Run(fileapi::SYNC_STATUS_NOT_INITIALIZED,
                 fileapi::FileSystemURLSet());
    return;
  }

  remote_file_service_->GetConflictFiles(
      app_origin, base::Bind(&VerifyFileSystemURLSetCallback,
                             AsWeakPtr(), app_origin, service_name, callback));
}

void SyncFileSystemService::GetConflictFileInfo(
    const GURL& app_origin,
    const std::string& service_name,
    const FileSystemURL& url,
    const ConflictFileInfoCallback& callback) {
  DCHECK(local_file_service_);
  DCHECK(remote_file_service_);
  DCHECK(app_origin == app_origin.GetOrigin());

  if (!ContainsKey(initialized_app_origins_, app_origin)) {
    callback.Run(fileapi::SYNC_STATUS_NOT_INITIALIZED,
                 fileapi::ConflictFileInfo());
    return;
  }

  // Call DidGetConflictFileInfo when both remote and local service's
  // GetFileMetadata calls are done.
  SyncFileMetadata* remote_metadata = new SyncFileMetadata;
  SyncFileMetadata* local_metadata = new SyncFileMetadata;
  SyncStatusCallback completion_callback =
      base::Bind(&SyncFileSystemService::DidGetConflictFileInfo,
                 AsWeakPtr(), callback, url,
                 base::Owned(local_metadata),
                 base::Owned(remote_metadata));
  scoped_refptr<SharedCallbackRunner> callback_runner(
      new SharedCallbackRunner(completion_callback));
  local_file_service_->GetLocalFileMetadata(
      url, callback_runner->CreateAssignAndRunCallback(local_metadata));
  remote_file_service_->GetRemoteFileMetadata(
      url, callback_runner->CreateAssignAndRunCallback(remote_metadata));
}

void SyncFileSystemService::GetFileSyncStatus(
    const fileapi::FileSystemURL& url,
    const fileapi::SyncFileStatusCallback& callback) {
  DCHECK(local_file_service_);
  DCHECK(remote_file_service_);

  if (!ContainsKey(initialized_app_origins_, url.origin())) {
    base::MessageLoopProxy::current()->PostTask(
        FROM_HERE,
        base::Bind(callback,
                   fileapi::SYNC_STATUS_NOT_INITIALIZED,
                   fileapi::SYNC_FILE_STATUS_UNKNOWN));
    return;
  }

  if (remote_file_service_->IsConflicting(url)) {
    base::MessageLoopProxy::current()->PostTask(
        FROM_HERE,
        base::Bind(callback,
                   fileapi::SYNC_STATUS_OK,
                   fileapi::SYNC_FILE_STATUS_CONFLICTING));
    return;
  }

  local_file_service_->HasPendingLocalChanges(
      url,
      base::Bind(&SyncFileSystemService::DidGetLocalChangeStatus,
                 AsWeakPtr(), callback));
}

void SyncFileSystemService::AddSyncEventObserver(SyncEventObserver* observer) {
  observers_.AddObserver(observer);
}

void SyncFileSystemService::RemoveSyncEventObserver(
    SyncEventObserver* observer) {
  observers_.RemoveObserver(observer);
}

SyncFileSystemService::SyncFileSystemService(Profile* profile)
    : profile_(profile),
      pending_local_changes_(0),
      pending_remote_changes_(0),
      local_sync_running_(false),
      remote_sync_running_(false),
      is_waiting_remote_sync_enabled_(false),
      auto_sync_enabled_(true) {
}

void SyncFileSystemService::Initialize(
    scoped_ptr<LocalFileSyncService> local_file_service,
    scoped_ptr<RemoteFileSyncService> remote_file_service) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(local_file_service);
  DCHECK(remote_file_service);
  DCHECK(profile_);

  local_file_service_ = local_file_service.Pass();
  remote_file_service_ = remote_file_service.Pass();

  local_file_service_->AddChangeObserver(this);
  remote_file_service_->AddObserver(this);
}

void SyncFileSystemService::DidGetConflictFileInfo(
    const ConflictFileInfoCallback& callback,
    const FileSystemURL& url,
    const SyncFileMetadata* local_metadata,
    const SyncFileMetadata* remote_metadata,
    SyncStatusCode status) {
  DCHECK(local_metadata);
  DCHECK(remote_metadata);
  fileapi::ConflictFileInfo info;
  info.url = url;
  info.local_metadata = *local_metadata;
  info.remote_metadata = *remote_metadata;
  callback.Run(status, info);
}

void SyncFileSystemService::DidInitializeFileSystem(
    const GURL& app_origin,
    const fileapi::SyncStatusCallback& callback,
    fileapi::SyncStatusCode status) {
  DVLOG(1) << "DidInitializeFileSystem: " << app_origin.spec() << " " << status;

  if (status != fileapi::SYNC_STATUS_OK) {
    callback.Run(status);
    return;
  }

  // Local side of initialization for the app is done.
  // Continue on initializing the remote side.
  remote_file_service_->RegisterOriginForTrackingChanges(
      app_origin,
      base::Bind(&SyncFileSystemService::DidRegisterOrigin,
                 AsWeakPtr(), app_origin, callback));
}

void SyncFileSystemService::DidRegisterOrigin(
    const GURL& app_origin,
    const fileapi::SyncStatusCallback& callback,
    fileapi::SyncStatusCode status) {
  DVLOG(1) << "DidRegisterOrigin: " << app_origin.spec() << " " << status;

  if (status == fileapi::SYNC_STATUS_OK)
    initialized_app_origins_.insert(app_origin);

  callback.Run(status);
}

void SyncFileSystemService::MaybeStartSync() {
  if (!profile_ || !auto_sync_enabled_)
    return;

  DCHECK(local_file_service_);
  DCHECK(remote_file_service_);

  MaybeStartRemoteSync();
  MaybeStartLocalSync();
}

void SyncFileSystemService::MaybeStartRemoteSync() {
  if (remote_file_service_->GetCurrentState() == REMOTE_SERVICE_DISABLED)
    return;
  // See if we cannot / should not start a new remote sync.
  if (remote_sync_running_ || pending_remote_changes_ == 0)
    return;
  // If we have registered a URL for waiting until sync is enabled on a
  // file (and the registerred URL seems to be still valid) it won't be
  // worth trying to start another remote sync.
  if (is_waiting_remote_sync_enabled_)
    return;
  DVLOG(1) << "Calling ProcessRemoteChange";
  remote_sync_running_ = true;
  remote_file_service_->ProcessRemoteChange(
      local_file_service_.get(),
      base::Bind(&SyncFileSystemService::DidProcessRemoteChange,
                 AsWeakPtr()));
}

void SyncFileSystemService::MaybeStartLocalSync() {
  // If the remote service is not ready probably we should not start a
  // local sync yet.
  // (We should be still trying a remote sync so the state should become OK
  // if the remote-side attempt succeeds.)
  if (remote_file_service_->GetCurrentState() != REMOTE_SERVICE_OK)
    return;
  // See if we cannot / should not start a new local sync.
  if (local_sync_running_ || pending_local_changes_ == 0)
    return;
  DVLOG(1) << "Calling ProcessLocalChange";
  local_sync_running_ = true;
  local_file_service_->ProcessLocalChange(
      remote_file_service_->GetLocalChangeProcessor(),
      base::Bind(&SyncFileSystemService::DidProcessLocalChange,
                 AsWeakPtr()));
}

void SyncFileSystemService::DidProcessRemoteChange(
    fileapi::SyncStatusCode status,
    const FileSystemURL& url,
    fileapi::SyncOperationResult result) {
  DVLOG(1) << "DidProcessRemoteChange: "
           << " status=" << status
           << " (" << SyncStatusCodeToString(status) << ")"
           << " url=" << url.DebugString()
           << " operation_result=" << result;
  DCHECK(remote_sync_running_);
  remote_sync_running_ = false;

  if (status != fileapi::SYNC_STATUS_NO_CHANGE_TO_SYNC &&
      remote_file_service_->GetCurrentState() != REMOTE_SERVICE_DISABLED) {
    DCHECK(url.is_valid());
    local_file_service_->ClearSyncFlagForURL(url);
  }

  if (status == fileapi::SYNC_STATUS_NO_CHANGE_TO_SYNC) {
    // We seem to have no changes to work on for now.
    // TODO(kinuko): Might be better setting a timer to call MaybeStartSync.
    return;
  }
  if (status == fileapi::SYNC_STATUS_FILE_BUSY) {
    is_waiting_remote_sync_enabled_ = true;
    local_file_service_->RegisterURLForWaitingSync(
        url, base::Bind(&SyncFileSystemService::OnSyncEnabledForRemoteSync,
                        AsWeakPtr()));
    return;
  }

  if ((status == fileapi::SYNC_STATUS_OK ||
       status == fileapi::SYNC_STATUS_HAS_CONFLICT) &&
      result != fileapi::SYNC_OPERATION_NONE) {
    // Notify observers of the changes made for a remote sync.
    FOR_EACH_OBSERVER(SyncEventObserver, observers_, OnFileSynced(url, result));
  }
  base::MessageLoopProxy::current()->PostTask(
      FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync,
                            AsWeakPtr()));
}

void SyncFileSystemService::DidProcessLocalChange(
    fileapi::SyncStatusCode status, const FileSystemURL& url) {
  DVLOG(1) << "DidProcessLocalChange:"
           << " status=" << status
           << " (" << SyncStatusCodeToString(status) << ")"
           << " url=" << url.DebugString();
  DCHECK(local_sync_running_);
  local_sync_running_ = false;

  if (status == fileapi::SYNC_STATUS_NO_CHANGE_TO_SYNC) {
    // We seem to have no changes to work on for now.
    return;
  }

  DCHECK(url.is_valid());
  local_file_service_->ClearSyncFlagForURL(url);

  if (status == fileapi::SYNC_STATUS_HAS_CONFLICT) {
    FOR_EACH_OBSERVER(SyncEventObserver, observers_,
                      OnFileSynced(url, fileapi::SYNC_OPERATION_CONFLICTED));
  }

  base::MessageLoopProxy::current()->PostTask(
      FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync,
                            AsWeakPtr()));
}

void SyncFileSystemService::DidGetLocalChangeStatus(
    const fileapi::SyncFileStatusCallback& callback,
    bool has_pending_local_changes) {
  callback.Run(
      fileapi::SYNC_STATUS_OK,
      has_pending_local_changes ? fileapi::SYNC_FILE_STATUS_HAS_PENDING_CHANGES
                                : fileapi::SYNC_FILE_STATUS_SYNCED);
}

void SyncFileSystemService::OnSyncEnabledForRemoteSync() {
  is_waiting_remote_sync_enabled_ = false;
  MaybeStartRemoteSync();
}

void SyncFileSystemService::OnLocalChangeAvailable(int64 pending_changes) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK_GE(pending_changes, 0);
  DVLOG(1) << "OnLocalChangeAvailable: " << pending_changes;
  pending_local_changes_ = pending_changes;
  base::MessageLoopProxy::current()->PostTask(
      FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync,
                            AsWeakPtr()));
}

void SyncFileSystemService::OnRemoteChangeQueueUpdated(int64 pending_changes) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK_GE(pending_changes, 0);
  DVLOG(1) << "OnRemoteChangeQueueUpdated: " << pending_changes;
  pending_remote_changes_ = pending_changes;
  if (pending_changes > 0) {
    // The smallest change available might have changed from the previous one.
    // Reset the is_waiting_remote_sync_enabled_ flag so that we can retry.
    is_waiting_remote_sync_enabled_ = false;
  }
  base::MessageLoopProxy::current()->PostTask(
      FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync,
                            AsWeakPtr()));
}

void SyncFileSystemService::OnRemoteServiceStateUpdated(
    RemoteServiceState state,
    const std::string& description) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DVLOG(1) << "OnRemoteServiceStateUpdated: " << state
           << " " << description;
  if (state == REMOTE_SERVICE_OK) {
    base::MessageLoopProxy::current()->PostTask(
        FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync,
                              AsWeakPtr()));
  }

  FOR_EACH_OBSERVER(
      SyncEventObserver, observers_,
      OnSyncStateUpdated(GURL(),
                         RemoteStateToSyncServiceState(state),
                         description));
}

// SyncFileSystemServiceFactory -----------------------------------------------

// static
SyncFileSystemService* SyncFileSystemServiceFactory::GetForProfile(
    Profile* profile) {
  return static_cast<SyncFileSystemService*>(
      GetInstance()->GetServiceForProfile(profile, true));
}

// static
SyncFileSystemServiceFactory* SyncFileSystemServiceFactory::GetInstance() {
  return Singleton<SyncFileSystemServiceFactory>::get();
}

void SyncFileSystemServiceFactory::set_mock_remote_file_service(
    scoped_ptr<RemoteFileSyncService> mock_remote_service) {
  mock_remote_file_service_ = mock_remote_service.Pass();
}

SyncFileSystemServiceFactory::SyncFileSystemServiceFactory()
    : ProfileKeyedServiceFactory("SyncFileSystemService",
                                 ProfileDependencyManager::GetInstance()) {
}

SyncFileSystemServiceFactory::~SyncFileSystemServiceFactory() {}

ProfileKeyedService* SyncFileSystemServiceFactory::BuildServiceInstanceFor(
    Profile* profile) const {
  SyncFileSystemService* service = new SyncFileSystemService(profile);

  scoped_ptr<LocalFileSyncService> local_file_service(
      new LocalFileSyncService(profile));

  scoped_ptr<RemoteFileSyncService> remote_file_service;
  if (mock_remote_file_service_)
    remote_file_service = mock_remote_file_service_.Pass();
  else
    remote_file_service.reset(new DriveFileSyncService(profile));

  service->Initialize(local_file_service.Pass(),
                      remote_file_service.Pass());
  return service;
}

}  // namespace sync_file_system


text:
from impacket.ldap import ldapasn1 as ldapasn1_impacket

class CMEModule:
    '''
      Module by technobro refactored by @mpgn (now compatible with LDAP protocol + filter by computer)

      Initial module:
      @T3KX: https://github.com/T3KX/Crackmapexec-LAPS

      Credit: @n00py1
        Reference: https://www.n00py.io/2020/12/dumping-laps-passwords-from-linux/
        https://github.com/n00py/LAPSDumper
    '''

    name = 'laps'
    description = 'Retrieves the LAPS passwords'
    supported_protocols = ['ldap']
    opsec_safe = True
    multiple_hosts = False

    def options(self, context, module_options):
        """
            COMPUTER    Computer name or wildcard ex: WIN-S10, WIN-* etc. Default: *
        """

        self.computer = None
        if 'COMPUTER' in module_options:
            self.computer = module_options['COMPUTER']

    def on_login(self, context, connection):
        context.log.info('Getting LAPS Passwords')
        if self.computer is not None:
            searchFilter = '(&(objectCategory=computer)(ms-MCS-AdmPwd=*)(name=' + self.computer + '))'
        else:
            searchFilter = '(&(objectCategory=computer)(ms-MCS-AdmPwd=*))'
        attributes = ['ms-MCS-AdmPwd', 'sAMAccountName']
        results = connection.search(searchFilter, attributes, 10000)
        results = [r for r in results if isinstance(r, ldapasn1_impacket.SearchResultEntry)]

        laps_computers = []
        for computer in results:
            msMCSAdmPwd = ''
            sAMAccountName = ''
            values = {str(attr['type']).lower(): str(attr['vals'][0]) for attr in computer['attributes']}
            laps_computers.append((values['samaccountname'], values['ms-mcs-admpwd']))

        laps_computers = sorted(laps_computers, key=lambda x: x[0])
        for sAMAccountName, msMCSAdmPwd in laps_computers:
            context.log.highlight("Computer: {:<20} Password: {}".format(sAMAccountName, msMCSAdmPwd))


text:
'use strict';

angular.module('<%= scriptAppName %>')
    .provider('<%= cameledName %>', function() {

        // Private variables
        var salutation = 'Hello';

        // Private constructor
        function Greeter() {
            this.greet = function() {
                return salutation;
            };
        }

        // Public API for configuration
        this.setSalutation = function(s) {
            salutation = s;
        };

        // Method for instantiating
        this.$get = function() {
            return new Greeter();
        };
    });


text:
#ifndef LWIS_BUFFERS_H
#define LWIS_BUFFERS_H

#include "NvInfer.h"
#include "half.h"
#include <cuda_runtime_api.h>
#include <cassert>
#include <glog/logging.h>
#include <iostream>
#include <iterator>
#include <memory>
#include <numeric>
#include <string>
#include <vector>
#include <new>
#include <random>
#include <fstream>

namespace lwis {

/* read in engine file into character array */
inline size_t GetModelStream(std::vector<char> &dst, std::string engineName) {
  size_t size{0};
  std::ifstream file(engineName, std::ios::binary);
  if (file.good()) {
    file.seekg(0, file.end);
    size = file.tellg();
    file.seekg(0, file.beg);
    dst.resize(size);
    file.read(dst.data(), size);
    file.close();
  }

  return size;
}

inline unsigned int getElementSize(nvinfer1::DataType t) {
  switch (t) {
  case nvinfer1::DataType::kINT32: return 4;
  case nvinfer1::DataType::kFLOAT: return 4;
  case nvinfer1::DataType::kHALF: return 2;
  case nvinfer1::DataType::kINT8: return 1;
  // Fall through to error
  default: break;
  }
  throw std::runtime_error("Invalid DataType.");
  return 0;
}

// Return m rounded up to nearest multiple of n
inline int roundUp(int m, int n)
{
    return ((m + n - 1) / n) * n;
}

inline int64_t volume(const nvinfer1::Dims& d, const nvinfer1::TensorFormat& format, const bool hasImplicitBatch)
{
    nvinfer1::Dims d_new = d;
    // Get number of scalars per vector.
    int spv{1};
    int channelDim{-1};
    switch(format)
    {
        case nvinfer1::TensorFormat::kCHW2: spv = 2; channelDim = d_new.nbDims - 3; break;
        case nvinfer1::TensorFormat::kCHW4: spv = 4; channelDim = d_new.nbDims - 3; break;
        case nvinfer1::TensorFormat::kHWC8: spv = 8; channelDim = d_new.nbDims - 3; break;
        case nvinfer1::TensorFormat::kDHWC8: spv = 8; channelDim = d_new.nbDims - 4; break;
        case nvinfer1::TensorFormat::kCHW16: spv = 16; channelDim = d_new.nbDims - 3; break;
        case nvinfer1::TensorFormat::kCHW32: spv = 32; channelDim = d_new.nbDims - 3; break;
        case nvinfer1::TensorFormat::kCDHW32: spv = 32; channelDim = d_new.nbDims - 4; break;
        case nvinfer1::TensorFormat::kLINEAR:
        default: spv = 1; channelDim = -1; break;
    }
    if (spv > 1)
    {
        assert(channelDim >= 0); // Make sure we have valid channel dimension.
        d_new.d[channelDim] = roundUp(d_new.d[channelDim], spv);
    }
    // Skip the first dimension, which is batch dim.
    return std::accumulate(d_new.d + (hasImplicitBatch ? 0 : 1), d_new.d + d_new.nbDims, 1, std::multiplies<int64_t>());
}

inline int64_t volume(const nvinfer1::Dims& d, const bool hasImplicitBatch)
{
    return volume(d, nvinfer1::TensorFormat::kLINEAR, hasImplicitBatch);
}

//!
//! \brief  The GenericBuffer class is a templated class for buffers.
//!
//! \details This templated RAII (Resource Acquisition Is Initialization) class handles the allocation,
//!          deallocation, querying of buffers on both the device and the host.
//!          It can handle data of arbitrary types because it stores byte buffers.
//!          The template parameters AllocFunc and FreeFunc are used for the
//!          allocation and deallocation of the buffer.
//!          AllocFunc must be a functor that takes in (void** ptr, size_t size)
//!          and returns bool. ptr is a pointer to where the allocated buffer address should be stored.
//!          size is the amount of memory in bytes to allocate.
//!          The boolean indicates whether or not the memory allocation was successful.
//!          FreeFunc must be a functor that takes in (void* ptr) and returns void.
//!          ptr is the allocated buffer address. It must work with nullptr input.
//!
template <typename AllocFunc, typename FreeFunc>
class GenericBuffer
{
public:
    //!
    //! \brief Construct an empty buffer.
    //!
    GenericBuffer()
        : mByteSize(0)
        , mBuffer(nullptr)
    {
    }

    //!
    //! \brief Construct a buffer with the specified allocation size in bytes.
    //!
    GenericBuffer(size_t size)
        : mByteSize(size)
    {
        if (!allocFn(&mBuffer, mByteSize))
            throw std::bad_alloc();
    }

    GenericBuffer(GenericBuffer&& buf)
        : mByteSize(buf.mByteSize)
        , mBuffer(buf.mBuffer)
    {
        buf.mByteSize = 0;
        buf.mBuffer = nullptr;
    }

    GenericBuffer& operator=(GenericBuffer&& buf)
    {
        if (this != &buf)
        {
            freeFn(mBuffer);
            mByteSize = buf.mByteSize;
            mBuffer = buf.mBuffer;
            buf.mByteSize = 0;
            buf.mBuffer = nullptr;
        }
        return *this;
    }

    //!
    //! \brief Returns pointer to underlying array.
    //!
    void* data() { return mBuffer; }

    //!
    //! \brief Returns pointer to underlying array.
    //!
    const void* data() const { return mBuffer; }

    //!
    //! \brief Returns the size (in bytes) of the buffer.
    //!
    size_t size() const { return mByteSize; }

    ~GenericBuffer()
    {
        freeFn(mBuffer);
    }

private:
    size_t mByteSize;
    void* mBuffer;
    AllocFunc allocFn;
    FreeFunc freeFn;
};

class DeviceAllocator
{
public:
    bool operator()(void** ptr, size_t size) const { return cudaMalloc(ptr, size) == cudaSuccess; }
};

class DeviceFree
{
public:
    void operator()(void* ptr) const { cudaFree(ptr); }
};

class HostAllocator
{
public:
    bool operator()(void** ptr, size_t size) const
    {
      return cudaMallocHost(ptr, size) == cudaSuccess;
    }
};

class HostFree
{
public:
    void operator()(void* ptr) const {
        cudaFreeHost(ptr);
    }
};

using DeviceBuffer = GenericBuffer<DeviceAllocator, DeviceFree>;
using HostBuffer = GenericBuffer<HostAllocator, HostFree>;

//!
//! \brief  The ManagedBuffer class groups together a pair of corresponding device and host buffers.
//!
class ManagedBuffer
{
public:
    DeviceBuffer deviceBuffer;
    HostBuffer hostBuffer;
};

//!
//! \brief  The BufferManager class handles host and device buffer allocation and deallocation.
//!
//! \details This RAII class handles host and device buffer allocation and deallocation,
//!          memcpy between host and device buffers to aid with inference,
//!          and debugging dumps to validate inference. The BufferManager class is meant to be
//!          used to simplify buffer management and any interactions between buffers and the engine.
//!
class BufferManager
{
public:
    static const size_t kINVALID_SIZE_VALUE = ~size_t(0);

    //!
    //! \brief Create a BufferManager for handling buffer interactions with engine.
    //!
    BufferManager(std::shared_ptr<nvinfer1::ICudaEngine> engine, const int& batchSize, const int profileIdx)
        : mEngine(engine)
        , mBatchSize(batchSize)
        , mProfileIdx(profileIdx)
    {
        // Each optimization profile owns numBindings bindings.
        int numBindingsTotal = engine->getNbBindings();
        int numBindings = numBindingsTotal / engine->getNbOptimizationProfiles();
        int bindingOffset = profileIdx * numBindings;
        mHostBindings.resize(numBindingsTotal, nullptr);
        mDeviceBindings.resize(numBindingsTotal, nullptr);
        for (int i = 0; i < numBindings; i++)
        {
            // Create host and device buffers
            size_t vol = lwis::volume(mEngine->getBindingDimensions(i), mEngine->getBindingFormat(i), mEngine->hasImplicitBatchDimension());
            size_t elementSize = lwis::getElementSize(mEngine->getBindingDataType(i));
            size_t allocationSize = static_cast<size_t>(mBatchSize) * vol * elementSize;
            std::unique_ptr<ManagedBuffer> manBuf{new ManagedBuffer()};
            manBuf->deviceBuffer = DeviceBuffer(allocationSize);
            manBuf->hostBuffer = HostBuffer(allocationSize);
            //std::cout << "Allocated Address: " << manBuf->hostBuffer.data() << std::endl;
            mHostBindings[bindingOffset + i] = manBuf->hostBuffer.data();
            mDeviceBindings[bindingOffset + i] = manBuf->deviceBuffer.data();
            mManagedBuffers.emplace_back(std::move(manBuf));
            //std::cout << (mEngine->bindingIsInput(i) ? "Input" : "Output") << " BindingName: " << mEngine->getBindingName(i) << std::endl;
        }
    }

    //!
    //! \brief Returns a vector of device buffers that you can use directly as
    //!        bindings for the execute and enqueue methods of IExecutionContext.
    //!
    std::vector<void*>& getDeviceBindings() { return mDeviceBindings; }

    //!
    //! \brief Returns a vector of device buffers.
    //!
    const std::vector<void*>& getDeviceBindings() const { return mDeviceBindings; }

    //!
    //! \brief Returns a vector of host buffers that you can use directly as
    //!        bindings for the execute and enqueue methods of IExecutionContext.
    //!
    std::vector<void*>& getHostBindings() { return mHostBindings; }

    //!
    //! \brief Returns a vector of host buffers.
    //!
    const std::vector<void*>& getHostBindings() const { return mHostBindings; }

    //!
    //! \brief Returns the device buffer corresponding to tensorName.
    //!        Returns nullptr if no such tensor can be found.
    //!
    void* getDeviceBuffer(const std::string& tensorName) const { return getBuffer(false, tensorName); }

    //!
    //! \brief Returns the device buffer corresponding to index.
    //!
    void* getDeviceBuffer(const size_t index) const { return getBuffer(false, index); }

    //!
    //! \brief Returns the host buffer corresponding to tensorName.
    //!        Returns nullptr if no such tensor can be found.
    //!
    void* getHostBuffer(const std::string& tensorName) const { return getBuffer(true, tensorName); }

    //!
    //! \brief Returns the host buffer corresponding to index.
    //!
    void* getHostBuffer(const size_t index) const { return getBuffer(true, index); }

    //!
    //! \brief Returns the size of the host and device buffers that correspond to tensorName.
    //!        Returns kINVALID_SIZE_VALUE if no such tensor can be found.
    //!
    size_t size(const std::string& tensorName) const
    {
        int index = mEngine->getBindingIndex(tensorName.c_str());
        if (index == -1)
            return kINVALID_SIZE_VALUE;
        return mManagedBuffers[index]->hostBuffer.size();
    }

    //!
    //! \brief Returns the volume of the host and device buffers that correspond to tensorName.
    //!        Returns kINVALID_SIZE_VALUE if no such tensor can be found.
    //!
    size_t volume(const std::string& tensorName) const
    {
        int index = mEngine->getBindingIndex(tensorName.c_str());
        if (index == -1)
            return kINVALID_SIZE_VALUE;
        return lwis::volume(mEngine->getBindingDimensions(index), mEngine->getBindingFormat(index), mEngine->hasImplicitBatchDimension());
    }

    //!
    //! \brief Returns the elementSize of the host and device buffers that correspond to tensorName.
    //!        Returns kINVALID_SIZE_VALUE if no such tensor can be found.
    //!
    size_t elementSize(const std::string& tensorName) const
    {
        int index = mEngine->getBindingIndex(tensorName.c_str());
        if (index == -1)
            return kINVALID_SIZE_VALUE;
        return lwis::getElementSize(mEngine->getBindingDataType(index));
    }

    //!
    //! \brief Dump host buffer with specified tensorName to ostream.
    //!        Prints error message to std::ostream if no such tensor can be found.
    //!
    void dumpBuffer(std::ostream& os, const std::string& tensorName)
    {
        int index = mEngine->getBindingIndex(tensorName.c_str());
        if (index == -1)
        {
            os << "Invalid tensor name" << std::endl;
            return;
        }
        void* buf = mManagedBuffers[index]->hostBuffer.data();
        size_t bufSize = mManagedBuffers[index]->hostBuffer.size();
        nvinfer1::Dims bufDims = mEngine->getBindingDimensions(index);
        size_t rowCount = static_cast<size_t>(bufDims.nbDims >= 1 ? bufDims.d[bufDims.nbDims - 1] : mBatchSize);

        os << "[" << mBatchSize;
        for (int i = 0; i < bufDims.nbDims; i++)
            os << ", " << bufDims.d[i];
        os << "]" << std::endl;
        switch (mEngine->getBindingDataType(index))
        {
        case nvinfer1::DataType::kINT32: print<int32_t>(os, buf, bufSize, rowCount); break;
        case nvinfer1::DataType::kFLOAT: print<float>(os, buf, bufSize, rowCount); break;
        case nvinfer1::DataType::kHALF: print<half_float::half>(os, buf, bufSize, rowCount); break;
        case nvinfer1::DataType::kINT8: assert(0 && "Int8 network-level input and output is not supported"); break;
        case nvinfer1::DataType::kBOOL: assert(0 && "Bool network-level input and output is not supported");
        }
    }

    //!
    //! \brief Templated print function that dumps buffers of arbitrary type to std::ostream.
    //!        rowCount parameter controls how many elements are on each line.
    //!        A rowCount of 1 means that there is only 1 element on each line.
    //!
    template <typename T>
    void print(std::ostream& os, void* buf, size_t bufSize, size_t rowCount)
    {
        assert(rowCount != 0);
        assert(bufSize % sizeof(T) == 0);
        T* typedBuf = static_cast<T*>(buf);
        size_t numItems = bufSize / sizeof(T);
        for (int i = 0; i < static_cast<int>(numItems); i++)
        {
            // Handle rowCount == 1 case
            if (rowCount == 1 && i != static_cast<int>(numItems) - 1)
                os << typedBuf[i] << std::endl;
            else if (rowCount == 1)
                os << typedBuf[i];
            // Handle rowCount > 1 case
            else if (i % rowCount == 0)
                os << typedBuf[i];
            else if (i % rowCount == rowCount - 1)
                os << " " << typedBuf[i] << std::endl;
            else
                os << " " << typedBuf[i];
        }
    }

    //!
    //! \brief Copy the contents of input host buffers to input device buffers asynchronously.
    //!
    void copyInputToDeviceAsync(const size_t index, const cudaStream_t& stream = 0, void *src = nullptr, const size_t size = 0, const size_t offset = 0) {
        memcpyBuffers(index, true, false, true, stream, src, size, offset);
    }

    //!
    //! \brief Copy the contents of output device buffers to output host buffers asynchronously.
    //!
    void copyOutputToHostAsync(const size_t index, const cudaStream_t& stream = 0, void *dst = nullptr, const size_t size = 0, const size_t offset = 0) {
        memcpyBuffers(index, false, true, true, stream, dst, size, offset);
    }

    ~BufferManager() = default;

private:
    void* getBuffer(const bool isHost, const std::string& tensorName) const
    {
        int index = mEngine->getBindingIndex(tensorName.c_str());
        if (index == -1)
            return nullptr;
        return (isHost ? mManagedBuffers[index]->hostBuffer.data() : mManagedBuffers[index]->deviceBuffer.data());
    }

    void* getBuffer(const bool isHost, const size_t index) const {
        return (isHost ? mManagedBuffers[index]->hostBuffer.data() : mManagedBuffers[index]->deviceBuffer.data());
    }

    void memcpyBuffers(const size_t index, const bool copyInput, const bool deviceToHost, const bool async, const cudaStream_t& stream = 0,
        void *buf = nullptr, const size_t size = 0, const size_t offset = 0)
    {
        auto numBindings = mManagedBuffers.size();
        CHECK(index < numBindings) << "Invalid binding index.";
        CHECK((copyInput && mEngine->bindingIsInput(index)) || (!copyInput && !mEngine->bindingIsInput(index)))
            << "Expecting binding " << index << " to be " << (copyInput ? "input" : "output") << "but get the opposite.";

        void* dstPtr = deviceToHost ? (buf ? buf : mManagedBuffers[index]->hostBuffer.data()) : static_cast<char *>(mManagedBuffers[index]->deviceBuffer.data()) + (buf ? offset * size : 0);
        const void* srcPtr = deviceToHost ? static_cast<char *>(mManagedBuffers[index]->deviceBuffer.data()) + (buf ? 0 : offset * size) : (buf ? buf : mManagedBuffers[index]->hostBuffer.data());
        const size_t byteSize = buf && size ? size : mManagedBuffers[index]->hostBuffer.size();
        const cudaMemcpyKind memcpyType = deviceToHost ? cudaMemcpyDeviceToHost : cudaMemcpyHostToDevice;
        if (async)
        {
            CHECK_EQ(cudaMemcpyAsync(dstPtr, srcPtr, byteSize, memcpyType, stream), cudaSuccess);
        }
        else
        {
            CHECK_EQ(cudaMemcpy(dstPtr, srcPtr, byteSize, memcpyType), cudaSuccess);
        }
    }

    std::shared_ptr<nvinfer1::ICudaEngine> mEngine;              //!< The pointer to the engine
    int mBatchSize;                                              //!< The batch size
    int mProfileIdx;                                             //!< The optimization profile index
    std::vector<std::unique_ptr<ManagedBuffer>> mManagedBuffers; //!< The vector of pointers to managed buffers
    std::vector<void*> mHostBindings;                            //!< The vector of host buffers needed for engine execution
    std::vector<void*> mDeviceBindings;                          //!< The vector of device buffers needed for engine execution
};

} // namespace lwis

#endif // LWIS_BUFFERS_H


text:
import React from "react";
import PropTypes from "prop-types";
import injectSheet from "react-jss";
import Link from "gatsby-link";

const styles = theme => ({
  infoMenu: {
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    listStyle: "none",
    margin: 0,
    width: "100%"
  },
  link: {
    padding: ".5em",
    fontWeight: 300,
    fontTransform: "lowercase",
    color: theme.info.colors.menuLink,
    "&:hover": {
      color: theme.info.colors.menuLinkHover
    }
  }
});

const InfoMenu = props => {
  const { classes, pages, linkOnClick } = props;

  return (
    <nav className={classes.infoMenu}>
      {pages.map((page, i) => {
        const { fields, frontmatter } = page.node;
        return (
          <Link
            key={fields.slug}
            to={fields.slug}
            onClick={linkOnClick}
            className={classes.link}
            data-shape="closed"
          >
            {frontmatter.menuTitle ? frontmatter.menuTitle : frontmatter.title}
          </Link>
        );
      })}
    </nav>
  );
};

InfoMenu.propTypes = {
  pages: PropTypes.array.isRequired,
  classes: PropTypes.object.isRequired,
  linkOnClick: PropTypes.func.isRequired
};

export default injectSheet(styles)(InfoMenu);


text:
package com.zxytech.designpatterns.gof.structuralpatterns.compositepattern;

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

/**
 * Created by ryan on 2016/12/18.
 */
public class Employee {
    private String name;
    private String dept;
    private float salary;
    private List<Employee> subOrdinates;

    // 构造函数
    public Employee(String name, String dept, float salary) {
        this.name = name;
        this.dept = dept;
        this.salary = salary;
        subOrdinates = new ArrayList<Employee>();
    }

    public void add(Employee employee) {
        subOrdinates.add(employee);
    }

    public void remove(Employee employee) {
        subOrdinates.remove(employee);
    }

    public List<Employee> getSubOrdinates() {
        return subOrdinates;
    }

    public String toString() {
        return ("Employee: [Name: " + name + " dept: " + dept + " salary: " + salary + "]");
    }
}


text:
package com.oktay.service;

import java.util.List;

import com.oktay.models.Book;

/**
 * @author oktay
 *
 */
public interface BookService {

	public void addBook(Book book);

	public Book getBook(Integer bookId);

	public Book updateBook(Integer BookId,Book book);

	public void deleteBook(Integer bookId);

	public List<Book> getAllBooks();
}


text:
<?php
function spider_featured($current_plugin = '') {
  $plugins = array(
    "form-maker" => array(
      'title'    => 'Form Maker',
      'text'     => 'Wordpress form builder plugin',
      'content'  => 'Form Maker is a modern and advanced tool for creating WordPress forms easily and fast.',
      'href'     => 'http://web-dorado.com/products/wordpress-form.html'
    ),
    "photo-gallery" => array(
      'title'    => 'Photo Gallery',
      'text'     => 'WordPress Photo Gallery plugin',
      'content'  => 'Photo Gallery is a fully responsive WordPress Gallery plugin with advanced functionality. It allows having different image galleries for your posts and pages, as well as different widgets.',
      'href'     => 'http://web-dorado.com/products/wordpress-photo-gallery-plugin.html'
    ),
    "contact-form-builder" => array(
      'title'    => 'Contact Form Builder',
      'text'     => 'WordPress contact form builder plugin',
      'content'  => 'WordPress Contact Form Builder is an intuitive tool for creating contact forms.',
      'href'     => 'http://web-dorado.com/products/wordpress-contact-form-builder.html'
    ),
    "slider" => array(
      'title'    => 'Slider WD',
      'text'     => 'WordPress slider plugin',
      'content'  => 'Slider WD is a responsive plugin for adding sliders to your site. Slides can use individual effects as well as effects for the layers (textual content, images, social sharing buttons).',
      'href'     => 'http://web-dorado.com/products/wordpress-slider-plugin.html'
    ),
    "contact-form-maker" => array(
      'title'    => 'Contact Form Maker',
      'text'     => 'WordPress contact form maker plugin',
      'content'  => 'WordPress Contact Form Maker is an advanced and easy-to-use tool for creating forms.',
      'href'     => 'http://web-dorado.com/products/wordpress-contact-form-maker-plugin.html'
    ),
    "spider-calendar" => array(
      'title'    => 'Spider Calendar',
      'text'     => 'WordPress event calendar plugin',
      'content'  => 'Spider Event Calendar is a highly configurable product which allows you to have multiple organized events.',
      'href'     => 'http://web-dorado.com/products/wordpress-calendar.html'
    ),
    "catalog" => array(
      'title'    => 'Spider Catalog',
      'text'     => 'WordPress product catalog plugin',
      'content'  => 'Spider Catalog for WordPress is a convenient tool for organizing the products represented on your website into catalogs.',
      'href'     => 'http://web-dorado.com/products/wordpress-catalog.html'
    ),
    "player" => array(
      'title'    => 'Video Player',
      'text'     => 'WordPress Video player plugin',
      'content'  => 'Spider Video Player for WordPress is a Flash & HTML5 video player plugin that allows you to easily add videos to your website with the possibility',
      'href'     => 'http://web-dorado.com/products/wordpress-player.html'
    ),
    "contacts" => array(
      'title'    => 'Spider Contacts',
      'text'     => 'Wordpress staff list plugin',
      'content'  => 'Spider Contacts helps you to display information about the group of people more intelligible, effective and convenient.',
      'href'     => 'http://web-dorado.com/products/wordpress-contacts-plugin.html'
    ),
    "facebook" => array(
      'title'    => 'Spider Facebook',
      'text'     => 'WordPress Facebook plugin',
      'content'  => 'Spider Facebook is a WordPress integration tool for Facebook.It includes all the available Facebook social plugins and widgets to be added to your web',
      'href'     => 'http://web-dorado.com/products/wordpress-facebook.html'
    ),
    "twitter-widget" => array(
      'title'    => 'Widget Twitter',
      'text'     => 'WordPress Widget Twitter plugin',
      'content'  => 'The Widget Twitter plugin lets you to fully integrate your WordPress site with your Twitter account.',
      'href'     => 'http://web-dorado.com/products/wordpress-twitter-integration-plugin.html'
    ),
    "faq" => array(
      'title'    => 'Spider FAQ',
      'text'     => 'WordPress FAQ Plugin',
      'content'  => 'The Spider FAQ WordPress plugin is for creating an FAQ (Frequently Asked Questions) section for your website.',
      'href'     => 'http://web-dorado.com/products/wordpress-faq-plugin.html'
    ),
    "zoom" => array(
      'title'    => 'Zoom',
      'text'     => 'WordPress text zoom plugin',
      'content'  => 'Zoom enables site users to resize the predefined areas of the web site.',
      'href'     => 'http://web-dorado.com/products/wordpress-zoom.html'
    ),
    "flash-calendar" => array(
      'title'    => 'Flash Calendar',
      'text'     => 'WordPress flash calendar plugin',
      'content'  => 'Spider Flash Calendar is a highly configurable Flash calendar plugin which allows you to have multiple organized events.',
      'href'     => 'http://web-dorado.com/products/wordpress-events-calendar.html'
    )
  );
  ?>

Featured Plugins

      <?php
      foreach ($plugins as $key => $plugins) {
        if ($current_plugin != $key) {
          ?>
      <li class="<?php echo $key; ?>">

            <?php echo $plugins['title']; ?>

<?php echo $plugins['text']; ?>

<?php echo $plugins['content']; ?>

          <a target="_blank" href="<?php echo $plugins['href']; ?>" class="download">Download

          <?php
        }
      }
      ?>

  <?php
}


text:
"""Tests for the VFS back-end CLI arguments helper."""

import argparse
import unittest

from plaso.cli import tools
from plaso.cli.helpers import vfs_backend
from plaso.lib import errors

from tests.cli import test_lib as cli_test_lib

class VFSBackEndArgumentsHelperTest(cli_test_lib.CLIToolTestCase):
  """Tests for the VFS back-end CLI arguments helper."""

  # pylint: disable=no-member,protected-access

  _EXPECTED_OUTPUT = """\
usage: cli_helper.py [--vfs_back_end TYPE]

Test argument parser.

{0:s}:
  --vfs_back_end TYPE, --vfs-back-end TYPE
                        The preferred dfVFS back-end: "auto", "fsext",
                        "fsfat", "fshfs", "fsntfs", "tsk" or "vsgpt".
""".format(cli_test_lib.ARGPARSE_OPTIONS)

  def testAddArguments(self):
    """Tests the AddArguments function."""
    argument_parser = argparse.ArgumentParser(
        prog='cli_helper.py', description='Test argument parser.',
        add_help=False,
        formatter_class=cli_test_lib.SortedArgumentsHelpFormatter)

    vfs_backend.VFSBackEndArgumentsHelper.AddArguments(argument_parser)

    output = self._RunArgparseFormatHelp(argument_parser)
    self.assertEqual(output, self._EXPECTED_OUTPUT)

  def testParseOptions(self):
    """Tests the ParseOptions function."""
    options = cli_test_lib.TestOptions()
    options.vfs_back_end = 'auto'

    test_tool = tools.CLITool()
    vfs_backend.VFSBackEndArgumentsHelper.ParseOptions(options, test_tool)

    self.assertEqual(test_tool._vfs_back_end, options.vfs_back_end)

    with self.assertRaises(errors.BadConfigObject):
      vfs_backend.VFSBackEndArgumentsHelper.ParseOptions(options, None)

if __name__ == '__main__':
  unittest.main()


text:
package com.frameworkset.common.tag.pager.tags;

import java.io.Serializable;

/**
 * @author biaoping.yin
 * created on 2005-3-29
 * version 1.0
 */
public  interface FieldHelper extends Serializable{
    public abstract String[] getWidths();
    public abstract String[] getTitles();
    public abstract String[] getFields();

}


text:
#include "device_manager.h"
#include "poll_thread.h"
#include "xcam_thread.h"
#include "x3a_image_process_center.h"
#include "x3a_analyzer_manager.h"
#include "isp_image_processor.h"
#include "isp_controller.h"
#if HAVE_IA_AIQ
#include "x3a_analyzer_aiq.h"
#endif

#define XCAM_FAILED_STOP(exp, msg, ...)                 \
    if ((exp) != XCAM_RETURN_NO_ERROR) {                \
        XCAM_LOG_ERROR (msg, ## __VA_ARGS__);           \
        stop ();                                        \
        return ret;                                     \
    }

namespace XCam {

class MessageThread
    : public Thread
{
public:
    explicit MessageThread (DeviceManager *dev_manager)
        : Thread ("MessageThread")
        , _manager (dev_manager)
    {}

protected:
    virtual bool loop ();

    DeviceManager *_manager;
};

bool
MessageThread::loop()
{
    XCamReturn ret = _manager->message_loop();
    if (ret == XCAM_RETURN_NO_ERROR || ret == XCAM_RETURN_ERROR_TIMEOUT)
        return true;

    return false;
}

XCamMessage::XCamMessage (XCamMessageType type, int64_t timestamp, const char *message)
    : timestamp (timestamp)
    , msg_id (type)
{
    if (message)
        this->msg = strdup (message);
}

XCamMessage::~XCamMessage ()
{
    if (msg)
        xcam_free (msg);
}

DeviceManager::DeviceManager()
    : _has_3a (true)
    , _is_running (false)
{
    _3a_process_center = new X3aImageProcessCenter;
    XCAM_LOG_DEBUG ("~DeviceManager construction");
}

DeviceManager::~DeviceManager()
{
    XCAM_LOG_DEBUG ("~DeviceManager destruction");
}

bool
DeviceManager::set_capture_device (SmartPtr<V4l2Device> device)
{
    if (is_running())
        return false;

    XCAM_ASSERT (device.ptr () && !_device.ptr ());
    _device = device;
    return true;
}

bool
DeviceManager::set_event_device (SmartPtr<V4l2SubDevice> device)
{
    if (is_running())
        return false;

    XCAM_ASSERT (device.ptr () && !_subdevice.ptr ());
    _subdevice = device;
    return true;
}

bool
DeviceManager::set_isp_controller (SmartPtr<IspController> controller)
{
    if (is_running())
        return false;

    XCAM_ASSERT (controller.ptr () && !_isp_controller.ptr ());
    _isp_controller = controller;
    return true;
}

bool
DeviceManager::set_analyzer (SmartPtr<X3aAnalyzer> analyzer)
{
    if (is_running())
        return false;

    XCAM_ASSERT (analyzer.ptr () && !_3a_analyzer.ptr ());
    _3a_analyzer = analyzer;

    return true;
}

bool
DeviceManager::add_image_processor (SmartPtr<ImageProcessor> processor)
{
    if (is_running())
        return false;

    XCAM_ASSERT (processor.ptr ());
    return _3a_process_center->insert_processor (processor);
}

XCamReturn
DeviceManager::start ()
{
    XCamReturn ret = XCAM_RETURN_NO_ERROR;

    // start device
    XCAM_ASSERT (_device->is_opened());
    if (!_device.ptr() || !_device->is_opened()) {
        XCAM_FAILED_STOP (ret = XCAM_RETURN_ERROR_FILE, "capture device not ready");
    }
    XCAM_FAILED_STOP (ret = _device->start(), "capture device start failed");

    //start subdevice
    XCAM_ASSERT (_subdevice->is_opened());
    if (!_subdevice.ptr() || !_subdevice->is_opened()) {
        XCAM_FAILED_STOP (ret = XCAM_RETURN_ERROR_FILE, "event device not ready");
    }
    XCAM_FAILED_STOP (ret = _subdevice->start(), "start event device failed");

    //suppose _device and _subdevice already started
    if (!_isp_controller.ptr ())
        _isp_controller = new IspController (_device);
    XCAM_ASSERT (_isp_controller.ptr());

    if (_has_3a) {
        // Initialize and start analyzer
        uint32_t width = 0, height = 0;
        uint32_t fps_n = 0, fps_d = 0;
        double framerate = 30.0;

        if (!_3a_analyzer.ptr()) {
            _3a_analyzer = X3aAnalyzerManager::instance()->create_analyzer();
            if (!_3a_analyzer.ptr()) {
                XCAM_FAILED_STOP (ret = XCAM_RETURN_ERROR_PARAM, "create analyzer failed");
            }
        }
        if (_3a_analyzer->prepare_handlers () != XCAM_RETURN_NO_ERROR) {
            XCAM_FAILED_STOP (ret = XCAM_RETURN_ERROR_PARAM, "prepare analyzer handler failed");
        }
        _3a_analyzer->set_results_callback (this);

        _device->get_size (width, height);
        _device->get_framerate (fps_n, fps_d);
        if (fps_d)
            framerate = (double)fps_n / (double)fps_d;
        XCAM_FAILED_STOP (
            ret = _3a_analyzer->init (width, height, framerate),
            "initialize analyzer failed");

        XCAM_FAILED_STOP (ret = _3a_analyzer->start (), "start analyzer failed");

        // Initialize and start image processors
        if (!_3a_process_center->has_processors()) {
            // default processor
            SmartPtr<ImageProcessor> default_processor = new IspImageProcessor (_isp_controller);
            XCAM_ASSERT (default_processor.ptr ());
            _3a_process_center->insert_processor (default_processor);
        }

        _3a_process_center->set_image_callback(this);
        XCAM_FAILED_STOP (ret = _3a_process_center->start (), "3A process center start failed");

    }

    //Initialize and start poll thread
    _poll_thread = new PollThread;
    _poll_thread->set_capture_device (_device);
    _poll_thread->set_event_device (_subdevice);
    _poll_thread->set_isp_controller (_isp_controller);
    _poll_thread->set_poll_callback (this);
    _poll_thread->set_stats_callback (this);

    XCAM_FAILED_STOP (ret = _poll_thread->start(), "start poll failed");

    _is_running = true;

    XCAM_LOG_DEBUG ("Device manager started");
    return XCAM_RETURN_NO_ERROR;
}

XCamReturn
DeviceManager::stop ()
{
    _is_running = false;

    if (_poll_thread.ptr())
        _poll_thread->stop ();

    if (_3a_analyzer.ptr()) {
        _3a_analyzer->stop ();
        _3a_analyzer->deinit ();
    }

    if (_3a_process_center.ptr())
        _3a_process_center->stop ();

    _subdevice->stop ();
    _device->stop ();

    _isp_controller.release ();
    _poll_thread.release ();

    XCAM_LOG_DEBUG ("Device manager stopped");
    return XCAM_RETURN_NO_ERROR;
}

XCamReturn
DeviceManager::x3a_stats_ready (const SmartPtr<X3aStats> &stats)
{
    XCamReturn ret = XCAM_RETURN_NO_ERROR;
    X3aResultList results;
    XCAM_ASSERT (_3a_analyzer.ptr());

    ret = _3a_analyzer->push_3a_stats (stats);
    XCAM_FAIL_RETURN (ERROR,
                      ret == XCAM_RETURN_NO_ERROR,
                      ret,
                      "analyze 3a statistics failed");

    return XCAM_RETURN_NO_ERROR;
}

XCamReturn
DeviceManager::dvs_stats_ready ()
{
    XCAM_ASSERT (false);
    // TODO
    return XCAM_RETURN_NO_ERROR;
}

XCamReturn
DeviceManager::poll_buffer_ready (SmartPtr<V4l2BufferProxy> &buf)
{
    if (_has_3a) {
        SmartPtr<VideoBuffer> video_buf = buf;
        if (_3a_process_center->put_buffer (video_buf) == false)
            return XCAM_RETURN_ERROR_UNKNOWN;
    }
    return XCAM_RETURN_NO_ERROR;
}

XCamReturn
DeviceManager::poll_buffer_failed (int64_t timestamp, const char *msg)
{
    post_message (XCAM_MESSAGE_BUF_ERROR, timestamp, msg);
    return XCAM_RETURN_NO_ERROR;
}

void
DeviceManager::x3a_calculation_done (X3aAnalyzer *analyzer, X3aResultList &results)
{
    XCamReturn ret = _3a_process_center->put_3a_results (results);
    if (ret != XCAM_RETURN_NO_ERROR && ret != XCAM_RETURN_BYPASS) {
        XCAM_LOG_WARNING ("apply 3a results failed");
        return;
    }
    AnalyzerCallback::x3a_calculation_done (analyzer, results);
}

void
DeviceManager::x3a_calculation_failed (X3aAnalyzer *analyzer, int64_t timestamp, const char *msg)
{
    AnalyzerCallback::x3a_calculation_failed (analyzer, timestamp, msg);
}

void
DeviceManager::process_buffer_done (ImageProcessor *processor, const SmartPtr<VideoBuffer> &buf)
{
    ImageProcessCallback::process_buffer_done (processor, buf);
    handle_buffer (buf);
}

void
DeviceManager::process_buffer_failed (ImageProcessor *processor, const SmartPtr<VideoBuffer> &buf)
{
    ImageProcessCallback::process_buffer_failed (processor, buf);
}

void
DeviceManager::process_image_result_done (ImageProcessor *processor, const SmartPtr<X3aResult> &result)
{
    ImageProcessCallback::process_image_result_done (processor, result);
}

void
DeviceManager::post_message (XCamMessageType type, int64_t timestamp, const char *msg)
{
    SmartPtr<XCamMessage> new_msg = new XCamMessage (type, timestamp, msg);
    _msg_queue.push (new_msg);
}

XCamReturn
DeviceManager::message_loop ()
{
    const static int32_t msg_time_out = -1; //wait until wakeup
    SmartPtr<XCamMessage> msg = _msg_queue.pop (msg_time_out);
    if (!msg.ptr ())
        return XCAM_RETURN_ERROR_THREAD;
    handle_message (msg);
    return XCAM_RETURN_NO_ERROR;
}

};