text:
id: recipes
title: Recipes
---

## Typescript

__If you're using `@haul-bundler/babel-preset-react-native` Babel preset, you don't need to do anything__ and start using Typescript immediately!

### with Babel

The easiest way to use Typescript in React Native apps is by using Babel to transpile TS files. There are some limitations, which you can read more about [here](https://babeljs.io/docs/en/babel-plugin-transform-typescript).

If you're using Haul's `@haul-bundler/babel-preset-react-native` you can start using Typescript without any manual work, since it support TS out of the box.

If you have custom Babel config, you need to add [`@babel/preset-typescript`](https://babeljs.io/docs/en/babel-preset-typescript) preset and configure it.

### with TS compiler (`tsc`)

If you want to use Typescript's official compiler and toolchain, you will need to install `ts-loader` and add it to Webpack config:

```yarn add --dev ts-loader```

To use the Typescript compiler exclusively on Typescript files without Babel's intervention, you have to remove the Babel loader and then re-add it to the module rules. This is needed if you want to use Typescript features that are currently not supported by Babel, like `const enum` or `namespace`.

The `haul.config.js` should then look something like this:

```js
import { makeConfig, withPolyfills } from '@haul-bundler/preset-0.60';

const removeRuleByTest = (moduleConfig, test) => {
  const index = moduleConfig.findIndex(rule => {
    if (rule.test) {
      return rule.test.toString() === test.toString();
    }
    return false;
  });
  moduleConfig.splice(index, 1);
};

export default makeConfig({
  bundles: {
    index: {
      entry: withPolyfills('./index.ts'),
      transform({ config }) {

        // Remove babel-loader, as it handles both .ts(x) and .js(x) files
        removeRuleByTest(config.module.rules, /\.[jt]sx?$/);

        config.module.rules = [
          {
            test: /\.tsx?$/,
            loader: 'ts-loader',
          },
          ...config.module.rules,

          // Re-add the babel-loader, now only for .js(x)
          {
            test: /\.jsx?$/,
            loader: require.resolve('babel-loader'),
            options: {
              plugins: [
                require.resolve(
                  '@haul-bundler/core/build/utils/fixRequireIssues',
                ),
              ],
            },
          },
        ];
      },
    },
  },
});
```

And a corresponding (example) `tsconfig.json`
```json
{
  "compilerOptions": {
    "jsx": "react",
    "target": "es2015",
    "moduleResolution": "node",
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}
```

Please note, that if you want to use synthetic default imports, a.k.a. things like `import React from 'react'` instead of `import * as React from 'react'` you will need to:

1. Add `"allowSyntheticDefaultImports": true` to `tsconfig.json`.
2. Pass the compiled TS files through Babel (you will need `babel-loader` for this - `yarn add --dev babel-loader`).

Revised `haul.config.js`:
```javascript
import { makeConfig, withPolyfills } from "@haul-bundler/preset-0.59";

export default makeConfig({
  bundles: {
    index: {
      entry: withPolyfills('./index.ts'),
      transform({ config }) {
        config.module.rules = [
          {
            test: /\.tsx?$/,
            exclude: '/node_modules/',
            use: [
              {
                loader: 'babel-loader',
              },
              {
                loader: 'ts-loader',
              }
            ]
          },
          ...config.module.rules,
        ];
      },
    },
  },
});
```

## Use Haul with `react-native-windows`

Unless you're using different JavaScript VM than ChakraCore (default) to run your JavaScript, add `chakra: true` flag to your `babel.config.js`:
```js
module.exports = {
  presets: [['module:@haul-bundler/babel-preset-react-native', { chakra: true }]],
};
```

### With React Native 0.59

If you want to use `react-native-windows`, you have to register it as a provider of JS modules.

Update your `haul.config.js` like so:
```js
import { makeConfig, withPolyfills } from "@haul-bundler/preset-0.59";

export default makeConfig({
  platforms: ['windows', 'ios', 'android'], // or ['windows'] if you only use windows platform
  bundles: {
    index: {
      entry: withPolyfills('./index.js'),
      providesModuleNodeModules: ['react-native', 'react-native-windows'],
      hasteOptions: { platforms: ['native', 'windows'] },
    },
  },
});
```

### With React Native 0.60 and newer

With React Native 0.60 and newer, you need to register `react-native-windows` as a module provider and modify `InitializeCore` location and alias `react-native`.

Update your `haul.config.js` like so:
```js
import { makeConfig, withPolyfills } from "@haul-bundler/preset-0.60";

export default makeConfig({
  platforms: ['windows', 'ios', 'android'], // or ['windows'] if you only use windows platform
  bundles: {
    index: {
      entry: withPolyfills('./index.js', {
        initializeCoreLocation: 'react-native-windows/Libraries/Core/InitializeCore.js'
      }),
      providesModuleNodeModules: ['react-native', 'react-native-windows'],
      hasteOptions: { platforms: ['native', 'windows'] },
      transform({ config }) {
        config.resolve.alias = {
          ...config.resolve.alias,
          'react-native': 'react-native-windows'
        };
      },
    },
  },
});
```

## Mock files when running detox tests

[Detox](https://github.com/wix/detox) is a "grey box" e2e framework developed by wix.
It provides the ability to mock files during tests using [react-native-repackager](https://github.com/wix/react-native-repackager)

`react-native-repackager` is built for the standard `react-native` packager, so your mocks won't work with Haul out-of-the-box. Luckily, it's easy to configure Haul (webpack, actually) to resolve the mocked files instead of the original ones during tests:

```js
// haul.config.js
import { makeConfig, withPolyfills } from "@haul-bundler/preset-0.59";

export default makeConfig({
  bundles: {
    index: {
      entry: withPolyfills('./index.ts'),
      transform({ config }) {
        config.resolve = {
          ...config.resolve,
          extensions: process.env.APP_ENV === 'detox_tests'
            ? ['.mock.behaviour.js', ...config.resolve.extensions]
            : config.resolve.extensions
        };
      },
    },
  },
});
```

Set the environment variable `APP_ENV` to `detox_tests` when running Haul:

```sh
APP_ENV=detox_tests yarn haul
```

## Using with Lottie or loose-mode-only-compatible libraries

Some React Native libraries might not work with Haul out of the box. If the library if throw error, it is possible that it's not compatible with strict mode checks.

By default all modules with Haul have `'use strict';` annotation, which makes the code evaluated in strict mode, whereas the default React Native bundler - Metro - generates the code without this annotation. For that reason, some libraries eg `Lottie` need special steps to work.

To enable loose mode, you need to add `looseMode` property to your config set to:

- `true` - removes all `'use strict';` from the whole bundle
- array for absolute filenames of modules - matched modules will have `'use strict';` removed
- array of regexes - matched modules will have `'use strict';` removed
- function that accepts absolute module filename and must return `true` to remove `'use strict';` or `false`

You can mix string and regexes in array.

For example:

```js
// haul.config.js
import { makeConfig, withPolyfills } from "@haul-bundler/preset-0.59";

export default makeConfig({
  bundles: {
    index: {
      entry: withPolyfills('./index.ts'),
      looseMode: [
        require.resolve('./MyModule.js'),
        /node_modules\/react-native-lottie/,
      ],
    },
  },
});
```

## Debugging with React Native Tools (`vscode-react-native`)

In order to use React Native Tools extension you must first install the extension:
```bash
code --install-extension msjsdiag.vscode-react-native
```

Next, you need to tweak your `haul.config.js` and add `source-map-loader`:
```js
import { withPolyfills, makeConfig } from "@haul-bundler/preset-0.60";

export default makeConfig({
  bundles: {
    index: {
      entry: withPolyfills('./index.js'),
      transform({ config }) {
        config.module.rules = [
          ...config.module.rules,
          {
            test: /\.js$/,
            use: ["source-map-loader"],
            enforce: "pre"
          }
        ];
      },
    },
  },
});
```

Now use can start Haul packager server (`yarn haul start`) and use _Attach to packager_ configuration in Debug panel in VS Code.

From within the app tap on _Enable remote debugging_. This will open a page in Chrome, which you can safely close.

Finally press _Start debugging_ icon (green triangle) in Debug panel in VS Code.

## Debugging Haul process

You can easily attach Node debugger to Haul process by passing `--node-inspector` option or `NODE_INSPECTOR` environment variable when running Haul:
```bash
yarn haul bundle --platform ios --dev false --node-inspector
# or
NODE_INSPECTOR=1 yarn haul bundle --platform ios --dev false
```

It will run Haul and open debugger connection to which you can attach Node debugger using Chrome debugger for Node or Visual Studio Code debugger.

`--node-inspector`, `--node-inspector true` and `NODE_INSPECTOR=1` work in similar way as passing `--inspect` to a `node` - it doesn't add breakpoint on the first line. If you want to attach debugger before Haul proceed further, use `wait` value:
```bash
yarn haul bundle --platform ios --dev false --node-inspector=wait
# or
NODE_INSPECTOR=wait yarn haul bundle --platform ios --dev false
```

This will make sure the Node debugger is attached before Haul starts executing a command. It works in a similar way as `--inspect-brk` option for `node`.

You can use `NODE_INSPECTOR=1`/`NODE_INSPECTOR=wait` in XCode build phase _Bundle React Native code and images_:
```bash
export CLI_PATH=node_modules/@haul-bundler/cli/bin/haul.js
export NODE_BINARY=node
export NODE_INSPECTOR=wait
../node_modules/react-native/scripts/react-native-xcode.sh
```

and `--node-inspector`/`--node-inspector=wait` in Gradle build file:
```groovy
// android/app/build.gradle
project.ext.react = [
    entryFile: "index.js",
    cliPath: "node_modules/@haul-bundler/cli/bin/haul.js"
    extraPackagerArgs: ['--node-inspector=wait']
]
```

__Note__: you can use Haul inspector and Node debugger together at the same time!

## Using Haul inspector

Haul inspector is a handy tool for monitoring a Haul process. It provides information about all messages logged in Haul process as well as the startup arguments and additional logs. It is useful, when you want to check what's happening in Haul when it's being run by a 3rd party tool, for example when XCode is building a JS bundle.

In order to use Haul inspector, you need to have `@haul-bundler/inspector` package installed:
```bash
yarn add -D @haul-bundler/inspector
# or
yarn global add @haul-bundler/inspector
```

and running:
```
yarn haul-inspector
```

By default it will bind to port `7777` on `localhost`. If you with to use different port/host use `--port <number>` or `--host <string>` options.

Now, you need to tell Haul to attach to inspector process by using `--haul-inspector` options or `HAUL_INSPECTOR` environment variable:
```bash
yarn haul bundle --platform ios --dev false --haul-inspector
# or
HAUL_INSPECTOR=1 yarn haul bundle --platform ios --dev false
```

Now the Haul process will try to connect to the inspector on `localhost:7777`. If you want to use different host/port use:
* `HAUL_INSPECTOR_HOST=<string>`
* `HAUL_INSPECTOR_PORT=<number>`

when running Haul process:
```bash
HAUL_INSPECTOR_HOST=0.0.0.0 HAUL_INSPECTOR_PORT=1234 yarn haul bundle --platform ios --dev false --haul-inspector
# or
HAUL_INSPECTOR=1 HAUL_INSPECTOR_HOST=0.0.0.0 HAUL_INSPECTOR_PORT=1234 yarn haul bundle --platform ios --dev false
```

When `--haul-inspector`, `--haul-inspector true` or `HAUL_INSPECTOR=1` are used, the Haul process with try to attach to the inspector, but it won't block the command execution. If you want to wait for the connection with inspector to be established use `wait` value:
```bash
yarn haul bundle --platform ios --dev false --haul-inspector=wait
# or
HAUL_INSPECTOR=wait yarn haul bundle --platform ios --dev false
```

You can use `HAUL_INSPECTOR=1`/`HAUL_INSPECTOR=wait` in XCode build phase _Bundle React Native code and images_:
```bash
export CLI_PATH=node_modules/@haul-bundler/cli/bin/haul.js
export NODE_BINARY=node
export HAUL_INSPECTOR=wait
../node_modules/react-native/scripts/react-native-xcode.sh
```

and `--haul-inspector`/`--haul-inspector=wait` in Gradle build file:
```groovy
// android/app/build.gradle
project.ext.react = [
    entryFile: "index.js",
    cliPath: "node_modules/@haul-bundler/cli/bin/haul.js"
    extraPackagerArgs: ['--node-inspector=wait']
]
```

__Note__: you can use Haul inspector and Node debugger together at the same time!


text:
std::string&& globalTopicName = "/vicon/Superdude/head";

class Receiver
{
private:
	geometry_msgs::TransformStamped transformed_msg;
	geometry_msgs::Vector3 translation;
	geometry_msgs::Quaternion rotQuat;
	std::mutex mutex;
	bool updatePose;
	double roll, pitch, yaw;
	std::thread getRPYThread;
	std::vector<std::thread> threadsVector;
	ros::NodeHandle np_;
 	unsigned long const hardware_concurrency;
	ros::AsyncSpinner spinner;
	ros::Subscriber pose_sub_;

public:
	Receiver(ros::NodeHandle np)
	: updatePose(false), np_(np), hardware_concurrency(std::thread::hardware_concurrency()),
	spinner(hardware_concurrency/2)
	{
		// pose_sub_ = np_.subscribe("/vicon/Superdude/root", 10, &Receiver::pose_callback, this);
		setZeroPose();

	}

	~Receiver()
	{

	}

	// set zero pose for head at rest
	void setZeroPose()
	{
	  std::string&& zeropose = globalTopicName + "/zero_pose";
	  if(!ros::param::has(zeropose + "orientation/w"))
	  {
  		ros::param::set(zeropose + "orientation/w", 0.47201963140666453);
  	    ros::param::set(zeropose + "orientation/x", 0.34138949874457175);
  	    ros::param::set(zeropose + "orientation/y", -0.5408836743327365);
  	    ros::param::set(zeropose + "orientation/z", 0.6067087674938981);

  	    ros::param::set(zeropose + "position/x", 2.4439054570820558);
  	    ros::param::set(zeropose + "position/y", -0.4104102425921056);
  	    ros::param::set(zeropose + "position/z", 1.0033158333551102);
	  }
	}

	void pose_callback(const geometry_msgs::TransformStamped::ConstPtr& pose_msg)
	{
		// ROS_INFO("in callback");
		geometry_msgs::Vector3 translation = pose_msg->transform.translation;
		geometry_msgs::Quaternion rotQuat = pose_msg->transform.rotation;
		//convert to millimeters
		metersTomilli(std::move(translation));
		//convert quaternion representation to degree
		// rad2deg(std::move(rotQuat));

		double roll, pitch, yaw;
		getRPYFromQuaternion(std::move(translation), std::move(rotQuat),
							 std::move(roll), std::move(pitch),
							 std::move(yaw));

		// ROS_INFO("Roll, %f, Pitch: %f, Yaw: %f", roll, pitch, yaw);

		std::lock_guard<std::mutex> lock(mutex);
		{
			this->translation 	= translation;
			this->rotQuat    	= rotQuat;
			this->roll 			= roll;
			this->pitch 		= pitch;
			this->yaw 			= yaw;
			updatePose 			= true;
		}
	}

	void getRPYFromQuaternion(geometry_msgs::Vector3&& translation,
							 geometry_msgs::Quaternion&& rotQuat, double&& roll,
							 double&& pitch, double&& yaw)
	{

		tf::Quaternion q(rotQuat.x, rotQuat.y, rotQuat.z, rotQuat.w);
		tf::Matrix3x3 m(q);
		m.getRPY(roll, pitch, yaw);

		rad2deg(std::move(roll)); rad2deg(std::move(pitch)); rad2deg(std::move(yaw));

		printf("\n|\tx \t|\ty \t|\tz \t|\troll \t|\tpitch \t|\tyaw\n %f, \t%f, \t%f,  \t%f , \t%f, \t%f", translation.x,
					translation.y, translation.z,
					roll, pitch, yaw);
	}

	inline void metersTomilli(geometry_msgs::Vector3&& translation)
	{
		translation.x	*= 1000;
		translation.y 	*= 1000;
		translation.z 	*= 1000;
	}

	inline void rad2deg(double&& x)
	{
		x  *= 180/M_PI;
	}
};

int main(int argc, char** argv)
{
	ros::init(argc, argv, "pose_retriever_node");

	ros::NodeHandle np;

	Receiver pose(np);// = new Receiver;
	// pose.spawn();

	ros::Subscriber sub = np.subscribe(globalTopicName, 10, &Receiver::pose_callback, &pose);

	ros::spin();

	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
import numpy as np
import pdb
def subpixel_roll(im, roll_in_pix):
	"""
	Parameters
	----------
	im: numpy array
		The input image (real)
	roll_in_pix: numpy array(2)
		Floating point amounts to shift in each direction.

	Returns
	-------
	shifted_im: numpy array
		The shifted image.
	"""
	#y and x in conventional screen plotting sense.
	ny = im.shape[0]
	nx = im.shape[1]

	#Create a Fourier domain y co-ordinate uv[0], and a Fourier domain x co-ordinate uv[1]
	uv = np.meshgrid((((np.arange(ny) + ny//2) % ny) - ny//2)/ny, np.arange(nx//2 + 1)/nx, indexing='ij')

	#Fourier transform the image
	ftim = np.fft.rfft2(im)

	#Now the magical Fourier shift, where convolution with a delta function is multiplication
	#by a phase ramp in the Fourier domain.
	ftim *= np.exp(-2j*np.pi*(uv[0]*roll_in_pix[0] + uv[1]*roll_in_pix[1]))

	#Return the inverse transform.
	return np.fft.irfft2(ftim)

def filter_image(image):
        image1 = np.roll(image,1,0)
        image2 = np.roll(image,-1,0)
        cube = np.ndarray((image.shape[0],image.shape[1],9))
        cube[:,:,0] = image
        cube[:,:,1] = image1
        cube[:,:,2] = image2
        cube[:,:,3] = np.roll(image,1,1)
        cube[:,:,4] = np.roll(image1,1,1)
        cube[:,:,5] = np.roll(image2,1,1)
        cube[:,:,6] = np.roll(image,-1,1)
        cube[:,:,7] = np.roll(image1,-1,1)
        cube[:,:,8] = np.roll(image2,-1,1)
        return np.median(cube,2)

def peak_coords(image):
# takes a numpy array and returns the x,y coords of the peak value
# takes the median filtered image from filter_image() as input
    shape = np.shape(image)
    maxindex = image.argmax()
    coords = []
    coords.append(maxindex % shape[1]) # max pixel x value
    coords.append(int(maxindex/shape[1])) # max pixel y value
    coords.append(image.max())
    return coords

# Walk into directories in filesystem
# Ripped from os module and slightly modified
# for alphabetical sorting
#

def sortedWalk(top, topdown=True, onerror=None):
    from os.path import join, isdir, islink
    import os
    names = os.listdir(top)
    names.sort()
    dirs, nondirs = [], []
    for name in names:
        if isdir(os.path.join(top, name)):
            dirs.append(name)
        else:
            nondirs.append(name)
    if topdown:
        yield top, dirs, nondirs
    for name in dirs:
        path = join(top, name)
        if not os.path.islink(path):
            for x in sortedWalk(path, topdown, onerror):
                yield x
    if not topdown:
        yield top, dirs, nondirs


text:
const gulp = require('gulp');
const config = require('./config');
const cachebust = require('gulp-cache-bust');

/**
 * Lets browser know that styles need to be updated
 *
 * @task {build:cache-bust}
 * @group {Build}
 */
gulp.task('build:cache-bust', () => {
    const dist = config.base.dist;
    return gulp
        .src(`${dist}/index.html`)
        .pipe(cachebust())
        .pipe(gulp.dest(dist));
});


text:
// Copyright (c) 1994 James Clark
// See the file COPYING for copying permission.

#ifndef Attribute_INCLUDED
#define Attribute_INCLUDED 1
#ifdef __GNUG__
#pragma interface
#endif

#include <stddef.h>
#include "Resource.h"
#include "Owner.h"
#include "StringC.h"
#include "Vector.h"
#include "CopyOwner.h"
#include "Boolean.h"
#include "Text.h"
#include "Ptr.h"
#include "Message.h"

#ifdef SP_NAMESPACE
namespace SP_NAMESPACE {
#endif

class Entity;
class Notation;
class DeclaredValue;
class AttributeValue;
class TokenizedAttributeValue;
class AttributeSemantics;
class AttributeContext;
class Syntax;

 class SP_API AttributeValue : public Resource {
 public:
   enum Type {
     implied,
     cdata,
     tokenized
   };
   AttributeValue();
   virtual ~AttributeValue();
   virtual AttributeSemantics *makeSemantics(const DeclaredValue *,
                                             AttributeContext &,
                                             const StringC &,
                                             unsigned &,
                                             unsigned &) const;
   virtual Type info(const Text *&, const StringC *&) const = 0;
   virtual const Text *text() const;
   virtual Boolean recoverUnquoted(const StringC &, const Location &,
                                   AttributeContext &, const StringC &);
   static Boolean handleAsUnterminated(const Text &, AttributeContext &);
 };

class SP_API AttributeDefinitionDesc {
public:
  AttributeDefinitionDesc() { }
  enum DeclaredValue {
    cdata,
    name,
    number,
    nmtoken,
    nutoken,
    entity,
    idref,
    names,
    numbers,
    nmtokens,
    nutokens,
    entities,
    idrefs,
    id,
    notation,
    nameTokenGroup
  };
  DeclaredValue declaredValue;
  enum DefaultValueType {
    required,
    current,
    implied,
    conref,
    defaulted,
    fixed
  };
  DefaultValueType defaultValueType;
  ConstPtr<AttributeValue> defaultValue;
  Vector<StringC> allowedValues;
  Vector<StringC> origAllowedValues;
  // Attribute definitions whose default value type is current and
  // which have the same currentIndex share current values.
  size_t currentIndex;
private:
  AttributeDefinitionDesc(const AttributeDefinitionDesc &); // undefined
  void operator=(const AttributeDefinitionDesc &);	    // undefined
};

class DeclaredValue {
public:
  DeclaredValue();
  virtual ~DeclaredValue();
  // This performs syntactic checking on the value.
  virtual AttributeValue *makeValue(Text &, AttributeContext &,
				    const StringC &name,
				    unsigned &specLength) const = 0;
  // This is used to avoid unnecessary syntactic checking in the
  // case where the attribute name and vi have been omitted.
  virtual AttributeValue *makeValueFromToken(Text &,
					     AttributeContext &,
					     const StringC &name,
					     unsigned &specLength) const;
  // This performs semantic checking on the value.
  virtual AttributeSemantics *makeSemantics(const TokenizedAttributeValue &,
					    AttributeContext &,
					    const StringC &,
					    unsigned &nIdrefs,
					    unsigned &nEntityNames) const;
  virtual Boolean containsToken(const StringC &) const;
  virtual Boolean tokenized() const = 0;
  virtual Boolean isNotation() const;
  virtual Boolean isEntity() const;
  virtual Boolean isId() const;
  virtual Boolean isIdref() const;
  virtual const Vector<StringC> *getTokens() const;
  virtual const Vector<StringC> *getOrigTokens() const;
  virtual void buildDesc(AttributeDefinitionDesc &) const = 0;
  virtual DeclaredValue *copy() const = 0;
};

class CdataDeclaredValue : public DeclaredValue {
public:
  CdataDeclaredValue();
  Boolean tokenized() const;
  AttributeValue *makeValue(Text &, AttributeContext &, const StringC &,
			    unsigned &) const;
  void buildDesc(AttributeDefinitionDesc &) const;
  DeclaredValue *copy() const;
protected:
  void checkNormalizedLength(Text &, AttributeContext &, unsigned &) const;
};

class TokenizedDeclaredValue : public DeclaredValue {
public:
  // must be in same order as AttributeDefinitionDesc
  enum TokenType {
    name,
    number,
    nameToken,
    numberToken,
    entityName
  };
  TokenizedDeclaredValue(TokenType type, Boolean isList);
  AttributeValue *makeValue(Text &, AttributeContext &, const StringC &,
			    unsigned &) const;
  TokenizedAttributeValue *makeTokenizedValue(Text &, AttributeContext &,
					      const StringC &, unsigned &) const;
  Boolean tokenized() const;
  void buildDesc(AttributeDefinitionDesc &) const;
  DeclaredValue *copy() const;
private:
  TokenType type_;
  Boolean isList_;
  unsigned initialCategories_;
  unsigned subsequentCategories_;
};

class GroupDeclaredValue : public TokenizedDeclaredValue {
public:
  GroupDeclaredValue(TokenType, Vector<StringC> &);
  Boolean containsToken(const StringC &) const;
  AttributeValue *makeValue(Text &, AttributeContext &, const StringC &,
			    unsigned &) const;
  AttributeValue *makeValueFromToken(Text &,
				     AttributeContext &,
				     const StringC &name,
				     unsigned &) const;
  const Vector<StringC> *getTokens() const;
  const Vector<StringC> *getOrigTokens() const;
  void buildDesc(AttributeDefinitionDesc &) const;
  DeclaredValue *copy() const;
  void setOrigAllowedValues(Vector<StringC> &origAllowedValues);

private:
  Vector<StringC> allowedValues_;
  Vector<StringC> origAllowedValues_;
};

class NameTokenGroupDeclaredValue : public GroupDeclaredValue {
public:
  NameTokenGroupDeclaredValue(Vector<StringC> &);
  void buildDesc(AttributeDefinitionDesc &) const;
  DeclaredValue *copy() const;
};

class NotationDeclaredValue : public GroupDeclaredValue {
public:
  NotationDeclaredValue(Vector<StringC> &);
  AttributeSemantics *makeSemantics(const TokenizedAttributeValue &,
				    AttributeContext &,
				    const StringC &,
				    unsigned &nIdrefs,
				    unsigned &nEntityNames) const;
  Boolean isNotation() const;
  void buildDesc(AttributeDefinitionDesc &) const;
  DeclaredValue *copy() const;
};

class EntityDeclaredValue : public TokenizedDeclaredValue {
public:
  EntityDeclaredValue(Boolean isList);
  AttributeSemantics *makeSemantics(const TokenizedAttributeValue &,
				    AttributeContext &,
				    const StringC &,
				    unsigned &nIdrefs,
				    unsigned &nEntityNames) const;
  Boolean isEntity() const;
  DeclaredValue *copy() const;
};

class IdDeclaredValue : public TokenizedDeclaredValue {
public:
  IdDeclaredValue();
  AttributeSemantics *makeSemantics(const TokenizedAttributeValue &,
				    AttributeContext &,
				    const StringC &,
				    unsigned &nIdrefs,
				    unsigned &nEntityNames) const;
  Boolean isId() const;
  void buildDesc(AttributeDefinitionDesc &) const;
  DeclaredValue *copy() const;
};

class IdrefDeclaredValue : public TokenizedDeclaredValue {
public:
  IdrefDeclaredValue(Boolean isList);
  AttributeSemantics *makeSemantics(const TokenizedAttributeValue &,
				    AttributeContext &,
				    const StringC &,
				    unsigned &nIdrefs,
				    unsigned &nEntityNames) const;
  Boolean isIdref() const;
  void buildDesc(AttributeDefinitionDesc &) const;
  DeclaredValue *copy() const;
};

class SP_API AttributeDefinition {
public:
  AttributeDefinition(const StringC &, DeclaredValue *);
  virtual ~AttributeDefinition();
  virtual ConstPtr<AttributeValue>
    makeMissingValue(AttributeContext &) const = 0;
  virtual Boolean missingValueWouldMatch(const Text &,
					 const AttributeContext &) const;
  virtual const AttributeValue *
    defaultValue(const AttributeValue *impliedValue) const;
  AttributeValue *makeValue(Text &, AttributeContext &, unsigned &) const;
  AttributeValue *makeValueFromToken(Text &,
				     AttributeContext &,
				     unsigned &) const;

  virtual Boolean isConref() const;
  virtual Boolean isCurrent() const;
  virtual Boolean isFixed() const;
  AttributeSemantics *makeSemantics(const AttributeValue *,
				    AttributeContext &,
				    unsigned &nIdrefs,
				    unsigned &nEntityNames) const;
  Boolean tokenized() const;
  const StringC &name() const;
  const StringC &origName() const;
  Boolean containsToken(const StringC &) const;
  Boolean isNotation() const;
  Boolean isEntity() const;
  Boolean isId() const;
  Boolean isIdref() const;
  void getDesc(AttributeDefinitionDesc &) const;
  const Vector<StringC> *getTokens() const;
  const Vector<StringC> *getOrigTokens() const;
  virtual AttributeDefinition *copy() const = 0;
  void setDeclaredValue(DeclaredValue *);
  void setSpecified(Boolean implicit);
  Boolean isSpecified(Boolean &implicit);
  void setOrigName(StringC &origName);
private:
  virtual void buildDesc(AttributeDefinitionDesc &) const = 0;
  virtual AttributeValue *checkValue(AttributeValue *, AttributeContext &) const;
  PackedBoolean implicit_;
  PackedBoolean all_;
  StringC name_;
  StringC origName_;
  CopyOwner<DeclaredValue> declaredValue_;
};

class RequiredAttributeDefinition : public AttributeDefinition {
public:
  RequiredAttributeDefinition(const StringC &, DeclaredValue *);
  ConstPtr<AttributeValue> makeMissingValue(AttributeContext &) const;
  void buildDesc(AttributeDefinitionDesc &) const;
  AttributeDefinition *copy() const;
};

class CurrentAttributeDefinition : public AttributeDefinition {
public:
  CurrentAttributeDefinition(const StringC &, DeclaredValue *, size_t index);
  ConstPtr<AttributeValue> makeMissingValue(AttributeContext &) const;
  Boolean missingValueWouldMatch(const Text &, const AttributeContext &) const;
  AttributeValue *checkValue(AttributeValue *, AttributeContext &) const;
  void buildDesc(AttributeDefinitionDesc &) const;
  Boolean isCurrent() const;
  AttributeDefinition *copy() const;
private:
  size_t currentIndex_;
};

class ImpliedAttributeDefinition : public AttributeDefinition {
public:
  ImpliedAttributeDefinition(const StringC &, DeclaredValue *);
  ConstPtr<AttributeValue> makeMissingValue(AttributeContext &) const;
  const AttributeValue *defaultValue(const AttributeValue *) const;
  void buildDesc(AttributeDefinitionDesc &) const;
  AttributeDefinition *copy() const;
};

class ConrefAttributeDefinition : public ImpliedAttributeDefinition {
public:
  ConrefAttributeDefinition(const StringC &, DeclaredValue *);
  Boolean isConref() const;
  void buildDesc(AttributeDefinitionDesc &) const;
  AttributeDefinition *copy() const;
};

class DefaultAttributeDefinition : public AttributeDefinition {
public:
  DefaultAttributeDefinition(const StringC &, DeclaredValue *,
			     AttributeValue *);
  ConstPtr<AttributeValue> makeMissingValue(AttributeContext &) const;
  Boolean missingValueWouldMatch(const Text &, const AttributeContext &) const;
  void buildDesc(AttributeDefinitionDesc &) const;
  AttributeDefinition *copy() const;
  const AttributeValue *defaultValue(const AttributeValue *) const;
private:
  ConstPtr<AttributeValue> value_;
};

class FixedAttributeDefinition : public DefaultAttributeDefinition {
public:
  FixedAttributeDefinition(const StringC &, DeclaredValue *,
			   AttributeValue *);
  // check that it's equal to the default
  AttributeValue *checkValue(AttributeValue *, AttributeContext &) const;
  void buildDesc(AttributeDefinitionDesc &) const;
  Boolean isFixed() const;
  AttributeDefinition *copy() const;
};

class SP_API AttributeDefinitionList : public Resource {
public:
  AttributeDefinitionList(Vector<CopyOwner<AttributeDefinition> > &,
			  size_t listIndex,
			  Boolean anyCurrent = 0,
			  size_t idIndex = size_t(-1),
			  size_t notationIndex = size_t(-1));
  AttributeDefinitionList(const ConstPtr<AttributeDefinitionList> &);
  size_t size() const;
  AttributeDefinition *def(size_t);
  const AttributeDefinition *def(size_t) const;
  Boolean tokenIndex(const StringC &, unsigned &) const;
  Boolean tokenIndexUnique(const StringC &, unsigned) const;
  Boolean attributeIndex(const StringC &, unsigned &) const;
  size_t index() const;
  size_t idIndex() const;
  size_t notationIndex() const;
  Boolean anyCurrent() const;
  void setIndex(size_t);
  void append(AttributeDefinition *);
private:
  Vector<CopyOwner<AttributeDefinition> > defs_;
  size_t index_;
  size_t idIndex_;		// -1 if no ID attribute
  size_t notationIndex_;	// -1 if no notation attribute
  Boolean anyCurrent_;
  ConstPtr<AttributeDefinitionList> prev_;
};

class AttributeSemantics {
public:
  AttributeSemantics();
  virtual ~AttributeSemantics();
  virtual size_t nEntities() const;
  virtual ConstPtr<Entity> entity(size_t) const;
  virtual ConstPtr<Notation> notation() const;
  virtual AttributeSemantics *copy() const = 0;
};

class EntityAttributeSemantics  : public AttributeSemantics {
public:
  EntityAttributeSemantics(Vector<ConstPtr<Entity> > &);
  size_t nEntities() const;
  ConstPtr<Entity> entity(size_t) const;
  AttributeSemantics *copy() const;
private:
  Vector<ConstPtr<Entity> > entity_;
};

class NotationAttributeSemantics : public AttributeSemantics {
public:
  NotationAttributeSemantics(const ConstPtr<Notation> &);
  ConstPtr<Notation> notation() const;
  AttributeSemantics *copy() const;
private:
  ConstPtr<Notation> notation_;
};

class SP_API ImpliedAttributeValue : public AttributeValue {
public:
  ImpliedAttributeValue();
  Type info(const Text *&, const StringC *&) const;
};

class CdataAttributeValue : public AttributeValue {
public:
  CdataAttributeValue(Text &);
  Type info(const Text *&, const StringC *&) const;
  const Text *text() const;
  Boolean recoverUnquoted(const StringC &, const Location &,
			  AttributeContext &, const StringC &);
  virtual const Notation *notation() const;
private:
  Text text_;
};

class TokenizedAttributeValue : public AttributeValue {
public:
  TokenizedAttributeValue(Text &, const Vector<size_t> &);
  size_t nTokens() const;
  AttributeSemantics *makeSemantics(const DeclaredValue *,
				    AttributeContext &,
				    const StringC &,
				    unsigned &,
				    unsigned &) const;
  Type info(const Text *&, const StringC *&) const;
  const Text *text() const;
  const StringC &string() const;
  StringC token(size_t) const;
  void token(size_t, const Char *&, size_t &) const;
  Location tokenLocation(size_t) const;
  Boolean tokenLocation(size_t, const ConstPtr<Origin> *&, Index &) const;
  Boolean recoverUnquoted(const StringC &, const Location &,
			  AttributeContext &, const StringC &);
private:
  TokenizedAttributeValue(const TokenizedAttributeValue &); // undefined
  void operator=(const TokenizedAttributeValue &);	    // undefined
  Text text_;
  // index into value of each space
  // length is number of tokens - 1
  Vector<size_t> spaceIndex_;
};

class SP_API Attribute {
public:
  Attribute();
  Boolean specified() const;
  size_t specIndex() const;
  const AttributeValue *value() const;
  const ConstPtr<AttributeValue> &valuePointer() const;
  const AttributeSemantics *semantics() const;
  void setSpec(size_t);
  void setValue(const ConstPtr<AttributeValue> &);
  void setSemantics(AttributeSemantics *);
  void clear();
private:
  size_t specIndexPlus_;
  ConstPtr<AttributeValue> value_;
  CopyOwner<AttributeSemantics> semantics_;
};

class SP_API AttributeList  {
public:
  AttributeList();
  AttributeList(const ConstPtr<AttributeDefinitionList> &);
  void init(const ConstPtr<AttributeDefinitionList> &);
  // was a conref attribute specified?
  Boolean conref() const;
  size_t size() const;
  const StringC &name(unsigned) const;
  const AttributeValue *value(unsigned) const;
  size_t specIndex(size_t) const;
  const ConstPtr<AttributeValue> &valuePointer(unsigned) const;
  const AttributeSemantics *semantics(unsigned) const;
  Boolean tokenized(unsigned index) const;
  Boolean tokenIndex(const StringC &, unsigned &) const;
  Boolean tokenIndexUnique(const StringC &, unsigned) const;
  Boolean attributeIndex(const StringC &, unsigned &) const;
  void finish(AttributeContext &);
  Boolean setValue(unsigned index, Text &, AttributeContext &,
		   unsigned &specLength);
  void setValueToken(unsigned index, Text &, AttributeContext &,
		     unsigned &specLength);
  void setSpec(unsigned index, AttributeContext &);
  Boolean recoverUnquoted(const StringC &, const Location &,
			  AttributeContext &);
  Boolean handleAsUnterminated(AttributeContext &context);
  void swap(AttributeList &);
  size_t nSpec() const;
  size_t defIndex() const;
  // is the attribute #current
  Boolean current(unsigned) const;
  Boolean anyCurrent() const;
  Boolean specified(unsigned) const;
  Boolean id(unsigned) const;
  Boolean idref(unsigned) const;
  const Vector<StringC> *getAllowedTokens(unsigned) const;
  const StringC *getId() const;	// null if none
  Boolean idIndex(unsigned &) const;
  void noteInvalidSpec();
  void changeDef(const ConstPtr<AttributeDefinitionList> &);
  const ConstPtr<AttributeDefinitionList> &def() const;
private:
  const AttributeDefinition *def(size_t) const;
  PackedBoolean conref_;
  unsigned nIdrefs_;
  unsigned nEntityNames_;
  size_t nSpec_;
  Vector<Attribute> vec_;
  ConstPtr<AttributeDefinitionList> def_;
};

class DataDeclaredValue : public CdataDeclaredValue {
public:
  DataDeclaredValue(const ConstPtr<Notation> &, AttributeList &);
  AttributeValue *makeValue(Text &, AttributeContext &, const StringC &,
                            unsigned &) const;
  DeclaredValue *copy() const;
private:
  ConstPtr<Notation> notation_;
  AttributeList attributes_;
};

class SP_API DataAttributeValue : public CdataAttributeValue {
public:
  DataAttributeValue(Text &, const ConstPtr<Notation> &, const AttributeList &);
  const AttributeList &attributes() const;
  const Notation *notation() const;
private:
  const ConstPtr<Notation> notation_;
  const AttributeList *attributes_;
};

class SP_API AttributeContext : public Messenger {
public:
  AttributeContext();
  virtual ~AttributeContext();
  virtual Boolean defineId(const StringC &, const Location &, Location &);
  virtual void noteIdref(const StringC &, const Location &);
  virtual void noteCurrentAttribute(size_t, AttributeValue *);
  virtual ConstPtr<AttributeValue> getCurrentAttribute(size_t) const;
  virtual ConstPtr<Entity> getAttributeEntity(const StringC &,
					      const Location &);
  virtual ConstPtr<Notation> getAttributeNotation(const StringC &,
						  const Location &);
  virtual const Syntax &attributeSyntax() const = 0;

  ConstPtr<AttributeValue> makeImpliedAttributeValue();
  Boolean mayDefaultAttribute() const;
  Boolean validate() const;
protected:
  Boolean mayDefaultAttribute_;
  Boolean validate_;
private:
  ConstPtr<AttributeValue> impliedAttributeValue_;
};

inline
Boolean AttributeDefinition::tokenized() const
{
  return declaredValue_->tokenized();
}

inline
Boolean AttributeDefinition::isNotation() const
{
  return declaredValue_->isNotation();
}

inline
Boolean AttributeDefinition::isEntity() const
{
  return declaredValue_->isEntity();
}

inline
Boolean AttributeDefinition::isId() const
{
  return declaredValue_->isId();
}

inline
Boolean AttributeDefinition::isIdref() const
{
  return declaredValue_->isIdref();
}

inline
const Vector<StringC> *AttributeDefinition::getTokens() const
{
  return declaredValue_->getTokens();
}

inline
const Vector<StringC> *AttributeDefinition::getOrigTokens() const
{
  return declaredValue_->getOrigTokens();
}

inline
AttributeSemantics *
AttributeDefinition::makeSemantics(const AttributeValue *value,
				   AttributeContext &context,
				   unsigned &nIdrefs,
				   unsigned &nEntityNames) const
{
  return value->makeSemantics(declaredValue_.pointer(), context, name_,
			      nIdrefs, nEntityNames);
}

inline
AttributeValue *AttributeDefinition::makeValue(Text &text,
					       AttributeContext &context,
					       unsigned &specLength) const
{
  return checkValue(declaredValue_->makeValue(text, context, name_,
					      specLength),
		    context);
}

inline
AttributeValue *
AttributeDefinition::makeValueFromToken(Text &text,
					AttributeContext &context,
					unsigned &specLength) const
{
  return checkValue(declaredValue_->makeValueFromToken(text, context,
						       name_, specLength),
		    context);
}

inline
Boolean AttributeDefinition::containsToken(const StringC &token) const
{
  return declaredValue_->containsToken(token);
}

inline
const StringC &AttributeDefinition::name() const
{
  return name_;
}

inline
const StringC &AttributeDefinition::origName() const
{
  return origName_;
}

inline
void AttributeDefinition::setDeclaredValue(DeclaredValue *declaredValue)
{
  declaredValue_ = declaredValue;
}

inline
size_t AttributeDefinitionList::size() const
{
  return defs_.size();
}

inline
size_t AttributeDefinitionList::index() const
{
  return index_;
}

inline
void AttributeDefinitionList::setIndex(size_t index)
{
  index_ = index;
}

inline
size_t AttributeDefinitionList::idIndex() const
{
  return idIndex_;
}

inline
size_t AttributeDefinitionList::notationIndex() const
{
  return notationIndex_;
}

inline
Boolean AttributeDefinitionList::anyCurrent() const
{
  return anyCurrent_;
}

inline
AttributeDefinition *AttributeDefinitionList::def(size_t i)
{
  return defs_[i].pointer();
}

inline
const AttributeDefinition *AttributeDefinitionList::def(size_t i) const
{
  return defs_[i].pointer();
}

inline
size_t TokenizedAttributeValue::nTokens() const
{
  return spaceIndex_.size() + 1;
}

inline
const StringC &TokenizedAttributeValue::string() const
{
  return text_.string();
}

inline
void TokenizedAttributeValue::token(size_t i,
				    const Char *&ptr, size_t &len) const
{
  size_t startIndex = i == 0 ? 0 : spaceIndex_[i - 1] + 1;
  ptr = text_.string().data() + startIndex;
  len = (i == spaceIndex_.size() ? text_.size() : spaceIndex_[i]) - startIndex;
}

inline
StringC TokenizedAttributeValue::token(size_t i) const
{
  const Char *ptr;
  size_t len;
  token(i, ptr, len);
  return StringC(ptr, len);
}

inline
Location TokenizedAttributeValue::tokenLocation(size_t i) const
{
  return text_.charLocation(i == 0 ? 0 : spaceIndex_[i - 1] + 1);
}

inline
Boolean TokenizedAttributeValue::tokenLocation(size_t i,
					       const ConstPtr<Origin> *&origin,
					       Index &index) const
{
  return text_.charLocation(i == 0 ? 0 : spaceIndex_[i - 1] + 1, origin, index);
}

inline
size_t Attribute::specIndex() const
{
  return specIndexPlus_ - 1;
}

inline
Boolean Attribute::specified() const
{
  return specIndexPlus_ != 0;
}

inline
const AttributeValue *Attribute::value() const
{
  return value_.pointer();
}

inline
const ConstPtr<AttributeValue> &Attribute::valuePointer() const
{
  return value_;
}

inline
const AttributeSemantics *Attribute::semantics() const
{
  return semantics_.pointer();
}

inline
void Attribute::setSpec(size_t index)
{
  specIndexPlus_ = index + 1;
}

inline
void Attribute::setValue(const ConstPtr<AttributeValue> &value)
{
  value_ = value;
}

inline
void Attribute::setSemantics(AttributeSemantics *semantics)
{
  semantics_ = semantics;
}

inline
size_t AttributeList::size() const
{
  return vec_.size();
}

inline
const AttributeDefinition *AttributeList::def(size_t i) const
{
  return def_->def(i);
}

inline
const ConstPtr<AttributeDefinitionList> &AttributeList::def() const
{
  return def_;
}

inline
Boolean AttributeList::tokenized(unsigned i) const
{
  return def(i)->tokenized();
}

inline
Boolean AttributeList::tokenIndex(const StringC &name, unsigned &index) const
{
  return !def_.isNull() && def_->tokenIndex(name, index);
}

inline
Boolean AttributeList::tokenIndexUnique(const StringC &name, unsigned index) const
{
  return def_->tokenIndexUnique(name, index);
}

inline
Boolean AttributeList::attributeIndex(const StringC &name, unsigned &index) const
{
  return !def_.isNull() && def_->attributeIndex(name, index);
}

inline
const StringC &AttributeList::name(unsigned i) const
{
  return def(i)->name();
}

inline
const Vector<StringC> *AttributeList::getAllowedTokens(unsigned i) const
{
  return def(i)->getTokens();
}

inline
const AttributeValue *AttributeList::value(unsigned i) const
{
  return vec_[i].value();
}

inline
const ConstPtr<AttributeValue> &AttributeList::valuePointer(unsigned i)
     const
{
  return vec_[i].valuePointer();
}

inline
const AttributeSemantics *AttributeList::semantics(unsigned i) const
{
  return vec_[i].semantics();
}

inline
size_t AttributeList::specIndex(size_t i) const
{
  return vec_[i].specIndex();
}

inline
size_t AttributeList::nSpec() const
{
  return nSpec_;
}

inline
Boolean AttributeList::conref() const
{
  return conref_;
}

inline
size_t AttributeList::defIndex() const
{
  return def_.isNull() ? size_t(-1) : def_->index();
}

inline
Boolean AttributeList::current(unsigned i) const
{
  return def(i)->isCurrent();
}

inline
Boolean AttributeList::anyCurrent() const
{
  return !def_.isNull() && def_->anyCurrent();
}

inline
const AttributeValue *
DefaultAttributeDefinition::defaultValue(const AttributeValue *)
     const
{
  return value_.pointer();
}

inline
Boolean AttributeList::idIndex(unsigned &ind) const
{
  if (def_.isNull() || def_->idIndex() == size_t(-1))
    return 0;
  else {
    ind = def_->idIndex();
    return 1;
  }
}

inline
Boolean AttributeList::id(unsigned i) const
{
  return def(i)->isId();
}

inline
Boolean AttributeList::idref(unsigned i) const
{
  return def(i)->isIdref();
}

inline
Boolean AttributeList::specified(unsigned i) const
{
  return vec_[i].specified();
}

inline
Boolean AttributeContext::mayDefaultAttribute() const
{
  return mayDefaultAttribute_;
}

inline
Boolean AttributeContext::validate() const
{
  return validate_;
}

#ifdef SP_NAMESPACE
}
#endif

#endif /* not Attribute_INCLUDED */


text:
<?xml version="1.0" encoding="UTF-8"?>
<tileset name="icecave" tilewidth="32" tileheight="32">
 <image source="../graphics/tiles/icecave.png" width="512" height="256"/>
</tileset>


text:
"""Repository class for viewing uncompressed bundles.

This provides a read-only repository interface to bundles as if they
were part of the actual repository.
"""

from node import nullid
from i18n import _
import os, tempfile, shutil
import changegroup, util, mdiff, discovery, cmdutil, scmutil
import localrepo, changelog, manifest, filelog, revlog, error

class bundlerevlog(revlog.revlog):
    def __init__(self, opener, indexfile, bundle, linkmapper):
        # How it works:
        # To retrieve a revision, we need to know the offset of the revision in
        # the bundle (an unbundle object). We store this offset in the index
        # (start). The base of the delta is stored in the base field.
        #
        # To differentiate a rev in the bundle from a rev in the revlog, we
        # check revision against repotiprev.
        opener = scmutil.readonlyvfs(opener)
        revlog.revlog.__init__(self, opener, indexfile)
        self.bundle = bundle
        n = len(self)
        self.repotiprev = n - 1
        chain = None
        self.bundlerevs = set() # used by 'bundle()' revset expression
        while True:
            chunkdata = bundle.deltachunk(chain)
            if not chunkdata:
                break
            node = chunkdata['node']
            p1 = chunkdata['p1']
            p2 = chunkdata['p2']
            cs = chunkdata['cs']
            deltabase = chunkdata['deltabase']
            delta = chunkdata['delta']

            size = len(delta)
            start = bundle.tell() - size

            link = linkmapper(cs)
            if node in self.nodemap:
                # this can happen if two branches make the same change
                chain = node
                self.bundlerevs.add(self.nodemap[node])
                continue

            for p in (p1, p2):
                if p not in self.nodemap:
                    raise error.LookupError(p, self.indexfile,
                                            _("unknown parent"))

            if deltabase not in self.nodemap:
                raise LookupError(deltabase, self.indexfile,
                                  _('unknown delta base'))

            baserev = self.rev(deltabase)
            # start, size, full unc. size, base (unused), link, p1, p2, node
            e = (revlog.offset_type(start, 0), size, -1, baserev, link,
                 self.rev(p1), self.rev(p2), node)
            self.index.insert(-1, e)
            self.nodemap[node] = n
            self.bundlerevs.add(n)
            chain = node
            n += 1

    def _chunk(self, rev):
        # Warning: in case of bundle, the diff is against what we stored as
        # delta base, not against rev - 1
        # XXX: could use some caching
        if rev <= self.repotiprev:
            return revlog.revlog._chunk(self, rev)
        self.bundle.seek(self.start(rev))
        return self.bundle.read(self.length(rev))

    def revdiff(self, rev1, rev2):
        """return or calculate a delta between two revisions"""
        if rev1 > self.repotiprev and rev2 > self.repotiprev:
            # hot path for bundle
            revb = self.index[rev2][3]
            if revb == rev1:
                return self._chunk(rev2)
        elif rev1 <= self.repotiprev and rev2 <= self.repotiprev:
            return revlog.revlog.revdiff(self, rev1, rev2)

        return mdiff.textdiff(self.revision(self.node(rev1)),
                              self.revision(self.node(rev2)))

    def revision(self, nodeorrev):
        """return an uncompressed revision of a given node or revision
        number.
        """
        if isinstance(nodeorrev, int):
            rev = nodeorrev
            node = self.node(rev)
        else:
            node = nodeorrev
            rev = self.rev(node)

        if node == nullid:
            return ""

        text = None
        chain = []
        iterrev = rev
        # reconstruct the revision if it is from a changegroup
        while iterrev > self.repotiprev:
            if self._cache and self._cache[1] == iterrev:
                text = self._cache[2]
                break
            chain.append(iterrev)
            iterrev = self.index[iterrev][3]
        if text is None:
            text = revlog.revlog.revision(self, iterrev)

        while chain:
            delta = self._chunk(chain.pop())
            text = mdiff.patches(text, [delta])

        self._checkhash(text, node, rev)
        self._cache = (node, rev, text)
        return text

    def addrevision(self, text, transaction, link, p1=None, p2=None, d=None):
        raise NotImplementedError
    def addgroup(self, revs, linkmapper, transaction):
        raise NotImplementedError
    def strip(self, rev, minlink):
        raise NotImplementedError
    def checksize(self):
        raise NotImplementedError

class bundlechangelog(bundlerevlog, changelog.changelog):
    def __init__(self, opener, bundle):
        changelog.changelog.__init__(self, opener)
        linkmapper = lambda x: x
        bundlerevlog.__init__(self, opener, self.indexfile, bundle,
                              linkmapper)

class bundlemanifest(bundlerevlog, manifest.manifest):
    def __init__(self, opener, bundle, linkmapper):
        manifest.manifest.__init__(self, opener)
        bundlerevlog.__init__(self, opener, self.indexfile, bundle,
                              linkmapper)

class bundlefilelog(bundlerevlog, filelog.filelog):
    def __init__(self, opener, path, bundle, linkmapper, repo):
        filelog.filelog.__init__(self, opener, path)
        bundlerevlog.__init__(self, opener, self.indexfile, bundle,
                              linkmapper)
        self._repo = repo

    def _file(self, f):
        self._repo.file(f)

class bundlepeer(localrepo.localpeer):
    def canpush(self):
        return False

class bundlerepository(localrepo.localrepository):
    def __init__(self, ui, path, bundlename):
        self._tempparent = None
        try:
            localrepo.localrepository.__init__(self, ui, path)
        except error.RepoError:
            self._tempparent = tempfile.mkdtemp()
            localrepo.instance(ui, self._tempparent, 1)
            localrepo.localrepository.__init__(self, ui, self._tempparent)
        self.ui.setconfig('phases', 'publish', False)

        if path:
            self._url = 'bundle:' + util.expandpath(path) + '+' + bundlename
        else:
            self._url = 'bundle:' + bundlename

        self.tempfile = None
        f = util.posixfile(bundlename, "rb")
        self.bundle = changegroup.readbundle(f, bundlename)
        if self.bundle.compressed():
            fdtemp, temp = tempfile.mkstemp(prefix="hg-bundle-",
                                            suffix=".hg10un", dir=self.path)
            self.tempfile = temp
            fptemp = os.fdopen(fdtemp, 'wb')

            try:
                fptemp.write("HG10UN")
                while True:
                    chunk = self.bundle.read(2**18)
                    if not chunk:
                        break
                    fptemp.write(chunk)
            finally:
                fptemp.close()

            f = util.posixfile(self.tempfile, "rb")
            self.bundle = changegroup.readbundle(f, bundlename)

        # dict with the mapping 'filename' -> position in the bundle
        self.bundlefilespos = {}

    @localrepo.unfilteredpropertycache
    def changelog(self):
        # consume the header if it exists
        self.bundle.changelogheader()
        c = bundlechangelog(self.sopener, self.bundle)
        self.manstart = self.bundle.tell()
        return c

    @localrepo.unfilteredpropertycache
    def manifest(self):
        self.bundle.seek(self.manstart)
        # consume the header if it exists
        self.bundle.manifestheader()
        m = bundlemanifest(self.sopener, self.bundle, self.changelog.rev)
        self.filestart = self.bundle.tell()
        return m

    @localrepo.unfilteredpropertycache
    def manstart(self):
        self.changelog
        return self.manstart

    @localrepo.unfilteredpropertycache
    def filestart(self):
        self.manifest
        return self.filestart

    def url(self):
        return self._url

    def file(self, f):
        if not self.bundlefilespos:
            self.bundle.seek(self.filestart)
            while True:
                chunkdata = self.bundle.filelogheader()
                if not chunkdata:
                    break
                fname = chunkdata['filename']
                self.bundlefilespos[fname] = self.bundle.tell()
                while True:
                    c = self.bundle.deltachunk(None)
                    if not c:
                        break

        if f in self.bundlefilespos:
            self.bundle.seek(self.bundlefilespos[f])
            return bundlefilelog(self.sopener, f, self.bundle,
                                 self.changelog.rev, self)
        else:
            return filelog.filelog(self.sopener, f)

    def close(self):
        """Close assigned bundle file immediately."""
        self.bundle.close()
        if self.tempfile is not None:
            os.unlink(self.tempfile)
        if self._tempparent:
            shutil.rmtree(self._tempparent, True)

    def cancopy(self):
        return False

    def peer(self):
        return bundlepeer(self)

    def getcwd(self):
        return os.getcwd() # always outside the repo

def instance(ui, path, create):
    if create:
        raise util.Abort(_('cannot create new bundle repository'))
    parentpath = ui.config("bundle", "mainreporoot", "")
    if not parentpath:
        # try to find the correct path to the working directory repo
        parentpath = cmdutil.findrepo(os.getcwd())
        if parentpath is None:
            parentpath = ''
    if parentpath:
        # Try to make the full path relative so we get a nice, short URL.
        # In particular, we don't want temp dir names in test outputs.
        cwd = os.getcwd()
        if parentpath == cwd:
            parentpath = ''
        else:
            cwd = os.path.join(cwd,'')
            if parentpath.startswith(cwd):
                parentpath = parentpath[len(cwd):]
    u = util.url(path)
    path = u.localpath()
    if u.scheme == 'bundle':
        s = path.split("+", 1)
        if len(s) == 1:
            repopath, bundlename = parentpath, s[0]
        else:
            repopath, bundlename = s
    else:
        repopath, bundlename = parentpath, path
    return bundlerepository(ui, repopath, bundlename)

def getremotechanges(ui, repo, other, onlyheads=None, bundlename=None,
                     force=False):
    '''obtains a bundle of changes incoming from other

    "onlyheads" restricts the returned changes to those reachable from the
      specified heads.
    "bundlename", if given, stores the bundle to this file path permanently;
      otherwise it's stored to a temp file and gets deleted again when you call
      the returned "cleanupfn".
    "force" indicates whether to proceed on unrelated repos.

    Returns a tuple (local, csets, cleanupfn):

    "local" is a local repo from which to obtain the actual incoming
      changesets; it is a bundlerepo for the obtained bundle when the
      original "other" is remote.
    "csets" lists the incoming changeset node ids.
    "cleanupfn" must be called without arguments when you're done processing
      the changes; it closes both the original "other" and the one returned
      here.
    '''
    tmp = discovery.findcommonincoming(repo, other, heads=onlyheads,
                                       force=force)
    common, incoming, rheads = tmp
    if not incoming:
        try:
            if bundlename:
                os.unlink(bundlename)
        except OSError:
            pass
        return repo, [], other.close

    bundle = None
    bundlerepo = None
    localrepo = other.local()
    if bundlename or not localrepo:
        # create a bundle (uncompressed if other repo is not local)

        if other.capable('getbundle'):
            cg = other.getbundle('incoming', common=common, heads=rheads)
        elif onlyheads is None and not other.capable('changegroupsubset'):
            # compat with older servers when pulling all remote heads
            cg = other.changegroup(incoming, "incoming")
            rheads = None
        else:
            cg = other.changegroupsubset(incoming, rheads, 'incoming')
        bundletype = localrepo and "HG10BZ" or "HG10UN"
        fname = bundle = changegroup.writebundle(cg, bundlename, bundletype)
        # keep written bundle?
        if bundlename:
            bundle = None
        if not localrepo:
            # use the created uncompressed bundlerepo
            localrepo = bundlerepo = bundlerepository(repo.baseui, repo.root,
                                                      fname)
            # this repo contains local and other now, so filter out local again
            common = repo.heads()
    if localrepo:
        # Part of common may be remotely filtered
        # So use an unfiltered version
        # The discovery process probably need cleanup to avoid that
        localrepo = localrepo.unfiltered()

    csets = localrepo.changelog.findmissing(common, rheads)

    def cleanup():
        if bundlerepo:
            bundlerepo.close()
        if bundle:
            os.unlink(bundle)
        other.close()

    return (localrepo, csets, cleanup)


text:
package main

import (
	"bytes"
	"flag"
	"fmt"
	"go/ast"
	"go/build"
	"go/format"
	"go/parser"
	"go/printer"
	"go/token"
	"go/types"
	"io/ioutil"
	"log"
	"os"
	"path"
	"strconv"
	"strings"

	"golang.org/x/tools/go/loader"
)

var (
	outputFile = flag.String("o", "", "write output to `file` (default standard output)")
	dstPath    = flag.String("dst", "", "set destination import `path` (default taken from current directory)")
	pkgName    = flag.String("pkg", "", "set destination package `name` (default taken from current directory)")
	prefix     = flag.String("prefix", "&_", "set bundled identifier prefix to `p` (default is \"&_\", where & stands for the original name)")
	underscore = flag.Bool("underscore", false, "rewrite golang.org/x/* to internal/x/* imports; temporary workaround for golang.org/issue/16333")

	importMap = map[string]string{}
)

func init() {
	flag.Var(flagFunc(addImportMap), "import", "rewrite import using `map`, of form old=new (can be repeated)")
}

func addImportMap(s string) {
	if strings.Count(s, "=") != 1 {
		log.Fatal("-import argument must be of the form old=new")
	}
	i := strings.Index(s, "=")
	old, new := s[:i], s[i+1:]
	if old == "" || new == "" {
		log.Fatal("-import argument must be of the form old=new; old and new must be non-empty")
	}
	importMap[old] = new
}

func usage() {
	fmt.Fprintf(os.Stderr, "Usage: bundle [options] <src>\n")
	flag.PrintDefaults()
}

func main() {
	log.SetPrefix("bundle: ")
	log.SetFlags(0)

	flag.Usage = usage
	flag.Parse()
	args := flag.Args()
	if len(args) != 1 {
		usage()
		os.Exit(2)
	}

	if *dstPath != "" {
		if *pkgName == "" {
			*pkgName = path.Base(*dstPath)
		}
	} else {
		wd, _ := os.Getwd()
		pkg, err := build.ImportDir(wd, 0)
		if err != nil {
			log.Fatalf("cannot find package in current directory: %v", err)
		}
		*dstPath = pkg.ImportPath
		if *pkgName == "" {
			*pkgName = pkg.Name
		}
	}

	code, err := bundle(args[0], *dstPath, *pkgName, *prefix)
	if err != nil {
		log.Fatal(err)
	}
	if *outputFile != "" {
		err := ioutil.WriteFile(*outputFile, code, 0666)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		_, err := os.Stdout.Write(code)
		if err != nil {
			log.Fatal(err)
		}
	}
}

// isStandardImportPath is copied from cmd/go in the standard library.
func isStandardImportPath(path string) bool {
	i := strings.Index(path, "/")
	if i < 0 {
		i = len(path)
	}
	elem := path[:i]
	return !strings.Contains(elem, ".")
}

var ctxt = &build.Default

func bundle(src, dst, dstpkg, prefix string) ([]byte, error) {
	// Load the initial package.
	conf := loader.Config{ParserMode: parser.ParseComments, Build: ctxt}
	conf.TypeCheckFuncBodies = func(p string) bool { return p == src }
	conf.Import(src)

	lprog, err := conf.Load()
	if err != nil {
		return nil, err
	}

	// Because there was a single Import call and Load succeeded,
	// InitialPackages is guaranteed to hold the sole requested package.
	info := lprog.InitialPackages()[0]
	if strings.Contains(prefix, "&") {
		prefix = strings.Replace(prefix, "&", info.Files[0].Name.Name, -1)
	}

	objsToUpdate := make(map[types.Object]bool)
	var rename func(from types.Object)
	rename = func(from types.Object) {
		if !objsToUpdate[from] {
			objsToUpdate[from] = true

			// Renaming a type that is used as an embedded field
			// requires renaming the field too. e.g.
			// 	type T int // if we rename this to U..
			// 	var s struct {T}
			// 	print(s.T) // ...this must change too
			if _, ok := from.(*types.TypeName); ok {
				for id, obj := range info.Uses {
					if obj == from {
						if field := info.Defs[id]; field != nil {
							rename(field)
						}
					}
				}
			}
		}
	}

	// Rename each package-level object.
	scope := info.Pkg.Scope()
	for _, name := range scope.Names() {
		rename(scope.Lookup(name))
	}

	var out bytes.Buffer

	fmt.Fprintf(&out, "// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT.\n")
	if *outputFile != "" {
		fmt.Fprintf(&out, "//go:generate bundle %s\n", strings.Join(os.Args[1:], " "))
	} else {
		fmt.Fprintf(&out, "//   $ bundle %s\n", strings.Join(os.Args[1:], " "))
	}
	fmt.Fprintf(&out, "\n")

	// Concatenate package comments from all files...
	for _, f := range info.Files {
		if doc := f.Doc.Text(); strings.TrimSpace(doc) != "" {
			for _, line := range strings.Split(doc, "\n") {
				fmt.Fprintf(&out, "// %s\n", line)
			}
		}
	}
	// ...but don't let them become the actual package comment.
	fmt.Fprintln(&out)

	fmt.Fprintf(&out, "package %s\n\n", dstpkg)

	// BUG(adonovan,shurcooL): bundle may generate incorrect code
	// due to shadowing between identifiers and imported package names.
	//
	// The generated code will either fail to compile or
	// (unlikely) compile successfully but have different behavior
	// than the original package. The risk of this happening is higher
	// when the original package has renamed imports (they're typically
	// renamed in order to resolve a shadow inside that particular .go file).

	// TODO(adonovan,shurcooL):
	// - detect shadowing issues, and either return error or resolve them
	// - preserve comments from the original import declarations.

	// pkgStd and pkgExt are sets of printed import specs. This is done
	// to deduplicate instances of the same import name and path.
	var pkgStd = make(map[string]bool)
	var pkgExt = make(map[string]bool)
	for _, f := range info.Files {
		for _, imp := range f.Imports {
			path, err := strconv.Unquote(imp.Path.Value)
			if err != nil {
				log.Fatalf("invalid import path string: %v", err) // Shouldn't happen here since conf.Load succeeded.
			}
			if path == dst {
				continue
			}
			if newPath, ok := importMap[path]; ok {
				path = newPath
			}

			var name string
			if imp.Name != nil {
				name = imp.Name.Name
			}
			spec := fmt.Sprintf("%s %q", name, path)
			if isStandardImportPath(path) {
				pkgStd[spec] = true
			} else {
				if *underscore {
					spec = strings.Replace(spec, "golang.org/x/", "internal/x/", 1)
				}
				pkgExt[spec] = true
			}
		}
	}

	// Print a single declaration that imports all necessary packages.
	fmt.Fprintln(&out, "import (")
	for p := range pkgStd {
		fmt.Fprintf(&out, "\t%s\n", p)
	}
	if len(pkgExt) > 0 {
		fmt.Fprintln(&out)
	}
	for p := range pkgExt {
		fmt.Fprintf(&out, "\t%s\n", p)
	}
	fmt.Fprint(&out, ")\n\n")

	// Modify and print each file.
	for _, f := range info.Files {
		// Update renamed identifiers.
		for id, obj := range info.Defs {
			if objsToUpdate[obj] {
				id.Name = prefix + obj.Name()
			}
		}
		for id, obj := range info.Uses {
			if objsToUpdate[obj] {
				id.Name = prefix + obj.Name()
			}
		}

		// For each qualified identifier that refers to the
		// destination package, remove the qualifier.
		// The "@@@." strings are removed in postprocessing.
		ast.Inspect(f, func(n ast.Node) bool {
			if sel, ok := n.(*ast.SelectorExpr); ok {
				if id, ok := sel.X.(*ast.Ident); ok {
					if obj, ok := info.Uses[id].(*types.PkgName); ok {
						if obj.Imported().Path() == dst {
							id.Name = "@@@"
						}
					}
				}
			}
			return true
		})

		last := f.Package
		if len(f.Imports) > 0 {
			imp := f.Imports[len(f.Imports)-1]
			last = imp.End()
			if imp.Comment != nil {
				if e := imp.Comment.End(); e > last {
					last = e
				}
			}
		}

		// Pretty-print package-level declarations.
		// but no package or import declarations.
		var buf bytes.Buffer
		for _, decl := range f.Decls {
			if decl, ok := decl.(*ast.GenDecl); ok && decl.Tok == token.IMPORT {
				continue
			}

			beg, end := sourceRange(decl)

			printComments(&out, f.Comments, last, beg)

			buf.Reset()
			format.Node(&buf, lprog.Fset, &printer.CommentedNode{Node: decl, Comments: f.Comments})
			// Remove each "@@@." in the output.
			// TODO(adonovan): not hygienic.
			out.Write(bytes.Replace(buf.Bytes(), []byte("@@@."), nil, -1))

			last = printSameLineComment(&out, f.Comments, lprog.Fset, end)

			out.WriteString("\n\n")
		}

		printLastComments(&out, f.Comments, last)
	}

	// Now format the entire thing.
	result, err := format.Source(out.Bytes())
	if err != nil {
		log.Fatalf("formatting failed: %v", err)
	}

	return result, nil
}

// sourceRange returns the [beg, end) interval of source code
// belonging to decl (incl. associated comments).
func sourceRange(decl ast.Decl) (beg, end token.Pos) {
	beg = decl.Pos()
	end = decl.End()

	var doc, com *ast.CommentGroup

	switch d := decl.(type) {
	case *ast.GenDecl:
		doc = d.Doc
		if len(d.Specs) > 0 {
			switch spec := d.Specs[len(d.Specs)-1].(type) {
			case *ast.ValueSpec:
				com = spec.Comment
			case *ast.TypeSpec:
				com = spec.Comment
			}
		}
	case *ast.FuncDecl:
		doc = d.Doc
	}

	if doc != nil {
		beg = doc.Pos()
	}
	if com != nil && com.End() > end {
		end = com.End()
	}

	return beg, end
}

func printComments(out *bytes.Buffer, comments []*ast.CommentGroup, pos, end token.Pos) {
	for _, cg := range comments {
		if pos <= cg.Pos() && cg.Pos() < end {
			for _, c := range cg.List {
				fmt.Fprintln(out, c.Text)
			}
			fmt.Fprintln(out)
		}
	}
}

const infinity = 1 << 30

func printLastComments(out *bytes.Buffer, comments []*ast.CommentGroup, pos token.Pos) {
	printComments(out, comments, pos, infinity)
}

func printSameLineComment(out *bytes.Buffer, comments []*ast.CommentGroup, fset *token.FileSet, pos token.Pos) token.Pos {
	tf := fset.File(pos)
	for _, cg := range comments {
		if pos <= cg.Pos() && tf.Line(cg.Pos()) == tf.Line(pos) {
			for _, c := range cg.List {
				fmt.Fprintln(out, c.Text)
			}
			return cg.End()
		}
	}
	return pos
}

type flagFunc func(string)

func (f flagFunc) Set(s string) error {
	f(s)
	return nil
}

func (f flagFunc) String() string { return "" }


text:
<?php

class Cate_model extends CI_Model
{

    function __construct()
    {
        parent::__construct();
    }

    /*
     *  Load All Category
     */
    public function loadAllCate(){
        $sql = 'Select CATEGORY_ID, CATEGORY_NM_VI, CATEGORY_DESC_VI, cate.GROUP_ID, GROUP_NAME From category cate, cate_group grp Where cate.GROUP_ID = grp.GROUP_ID';
        $result = $this->db->query($sql);
        return $result->result();
    }

    /*
     *  Load All Category Group
     */
    public function loadAllGroupCate(){
        $query = $this->db->get('cate_group');
        return $query->result();
    }

    /*
     *  Create Category ID
     */
    public function createCateID($grpID){
        $maxID = 1;
        $categoryID = $grpID;
        $sql = 'SELECT MAX(CATEGORY_ID) AS CATEGORY_ID FROM category WHERE CATEGORY_ID LIKE ?'.'"%"';
        $result = $this->db->query($sql,$grpID);
        foreach($result->result() as $row){
            $maxID = $row->CATEGORY_ID;
        }
        if(isset($maxID)){
            $subID = substr($maxID,1,5);
            $subMaxID = $subID + 1;
            $subLen = strlen($subMaxID);
            for($i = 0; $i < 5 - $subLen; $i++){
                $categoryID .= '0';
            }
            $categoryID .= $subMaxID;
        }else{
            $categoryID = $grpID.'00001';
        }
        return $categoryID;
    }
    /*
     *  Insert New Category
     */
    public function insertCate($cateData){
        if($this->db->insert('category',$cateData)){
            return true;
        }else{
            return false;
        }
    }
    /*
     *  get category by cateID
     */
    public function getCateByID($cateID){
        $sql = 'SELECT
                    CATEGORY_ID
                    , CATEGORY_NM_EN
                    , CATEGORY_NM_VI
                    , CATEGORY_DESC_VI
                    , CATEGORY_DESC_EN
                    , cate.GROUP_ID
                    , grp.GROUP_NAME
                    , cate.IMG_URL
                    , cate.MAIN_CATE
                    , cate.COLOR_CD
                    , cate.TITLE_COLOR_CD
                    , cate.FONT_COLOR_CD
                FROM
                    category cate
                    , cate_group grp
                WHERE
                    CATEGORY_ID = ?
                    AND cate.GROUP_ID = grp.GROUP_ID';
        $result = $this->db->query($sql,$cateID);
        return $result->result();
    }

    public function updateCate($cateID, $cateData){
        $this->db->where('CATEGORY_ID',$cateID);
        if($this->db->update('category',$cateData)){
            return true;
        }else{
            return false;
        }
    }
}


text:
layout: default
title: Quantitative Neurobiology
desc: Matlab notes, assignments, and code
post_title: "Week 3: Imaging data"
author: John Pearson
category: blog
---
For week three, we'll be working with imaging data. Two-photon imaging, to be precise, though other types of imaging present similar challenges. Unlike point process (i.e., spike) data, which are just collections of events — temporal data — imaging data are *spatiotemporal*: we must deal not only with time, but space as well. In practice, this means not only working with time series, but with images: **time series of images**.

On the coding side, we'll be devoting some time this week to learning what makes code run fast, why some programming languages are faster than others, the strengths and weaknesses of Matlab as a coding platform when we need lots of computation, and the tools Matlab provides for helping us find and remove speed bottlenecks in our code.

Much of what we will learn can be summarized in the classic quote by computer scientist Donald Knuth:

> "We should forget about small efficiencies, say about 97% of the time: **premature optimization is the root of all evil.** Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified."

So **before our first class**:

- Read about how to measure the [performance of your program](https://www.mathworks.com/help/matlab/matlab_prog/measure-performance-of-your-program.html).
- Read about [`image`](https://www.mathworks.com/help/matlab/ref/image.html),  [`imshow`](http://www.mathworks.com/help/matlab/ref/imshow.html), and [`imagesc`](http://www.mathworks.com/help/matlab/ref/imagesc.html) as well as [the difference](https://www.mathworks.com/matlabcentral/answers/1288-what-is-the-difference-between-image-and-imshow) between them.
- Know about the [`squeeze`](http://www.mathworks.com/help/matlab/ref/squeeze.html) function.

and **before our second class**:

- Learn about [how to use the Matlab profiler](https://www.mathworks.com/help/matlab/matlab_prog/profiling-for-improving-performance.html).
- Learn about [strategies for improving performance](https://www.mathworks.com/help/matlab/matlab_prog/techniques-for-improving-performance.html).
- Learn about simple parallel computing with [parfor](https://www.mathworks.com/help/distcomp/parfor.html).

<!-- - Watch a short video about convolutions:
    <video width="100%" align="center" controls src="{{ site.videourl }}/convolutions.mp4" type="video/mp4">
		Your browser does not support the video tag.
	</video> -->


text:
Helper scripts to install and run [SyncPlay](http://syncplay.pl/) on OSX

# Installation

1. [Download and Install XCode](https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12)
1. [Download and Install VLC](https://www.videolan.org/vlc/download-macosx.html)
1. Open [Terminal.app](https://www.youtube.com/watch?v=zw7Nd67_aFw)
1. Paste this into the terminal:

        curl https://raw.githubusercontent.com/edalquist/syncplay_osx_install/master/install.sh | bash

1. The output should [look like this](https://gist.github.com/edalquist/bfcf6d41e5e615bc643a).
1. Download the run script via the Terminal

        curl -o run.sh https://raw.githubusercontent.com/edalquist/syncplay_osx_install/master/run.sh

# Running

1. In Terminal run ```bash run.sh```


text:
from crosscompute.macros.iterable import extend_uniquely

def test_extend_uniquely():
    items = [1, 2]
    extend_uniquely(items, [2, 3])
    assert len(items) == 3


text: from django.contrib.sitemaps.tests.basic import *


text:
import * as pageTypes from './page/mutation-types'
import * as blockTypes from './block/mutation-types'
import { cmsPagesStorageKey } from './page'
import { cmsBlockStorageKey } from './block'
import { StorageManager } from '@vue-storefront/core/lib/storage-manager'
import { Logger } from '@vue-storefront/core/lib/logger'

const cmsPersistPlugin = (mutation, state) => {
  const cmsStorage = StorageManager.get('cms')

  if (mutation.type.startsWith(pageTypes.SN_CMS_PAGE)) {
    cmsStorage.setItem(cmsPagesStorageKey, state.cmsPage.items).catch((reason) => {
      Logger.error(reason, 'cms') // it doesn't work on SSR
    })
  }

  if (mutation.type.startsWith(blockTypes.SN_CMS_BLOCK)) {
    cmsStorage.setItem(cmsBlockStorageKey, state.cmsBlock.items).catch((reason) => {
      Logger.error(reason, 'cms') // it doesn't work on SSR
    })
  }
}

export default cmsPersistPlugin


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Physaliastrum kimurae Makino

### Remarks
null


text:
(function ($){
    "use strict";

    var TTOColor = function ($el,options){
        //vars
        var _tto = this,
            _wpcolor = jQuery().wpColorPicker;

        //element
        _tto.$el = $el;
        _tto.options = options;

        //WP version < 3.5
        if (!_wpcolor) {
            _tto.farbastic();
        }
        //WP version >= 3.5
        else {
            _tto.colorpicker();

            $('a.iris-square-value').on('click', function (e){
                e.preventDefault();
            });
        }
    };

    TTOColor.prototype.$el = null;
    TTOColor.prototype.options = null;

    TTOColor.prototype.farbastic = function (){
        var _tto = this;

        //use functions plugin
        var _id = _tto.$el.attr('id');
        var $farb = $(document.createElement('div')).attr('id', _id + '_farb');
        $farb.insertAfter(_tto.$el);
        $farb.farbtastic('#' + _id);
    };

    TTOColor.prototype.colorpicker = function (){
        var _tto = this;

        //use functions plugin
        _tto.$el.wpColorPicker({
            change: function (){
                var _value = _tto.$el.wpColorPicker('color');
                _tto.$el.val(_value);

                //check if change option is defined and is a function, then execute it
                if ('function' === typeof _tto.options.afterchange) {
                    _tto.options.afterchange(_value);
                }
            },
            clear: function (){
                _tto.$el.val('');

                //check if change option is defined and is a function, then execute it
                if ('function' === typeof _tto.options.afterclear) {
                    _tto.options.afterclear();
                }
            }
        });
    };

    var methods = {
        init: function (options){
            if (!this.length) {
                return false;
            }

            var settings = {
                afterchange: '',
                afterclear: '',
            };

            return this.each(function (){
                if (options) {
                    $.extend(settings, options);
                }

                new TTOColor($(this), settings);
            });
        },
        update: function (){},
        destroy: function (){}
    };

    $.fn.tto_color = function (method){
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        }
        else {
            $.error('Method '+method+' does not exist on tto_color');
            return false;
        }
    };
})(window.jQuery);