text:
All URIs are relative to *http://localhost/api/v2*

Method | HTTP request | Description
------------- | ------------- | -------------
[**createDriverUnavailability**](DriverunavailabilityApi.md#createDriverUnavailability) | **POST** /driver-unavailability | Add a new DriverUnavailability
[**deleteDriverUnavailability**](DriverunavailabilityApi.md#deleteDriverUnavailability) | **DELETE** /driver-unavailability/{driverunavailabilityId} | Delete a DriverUnavailability entry
[**retrieveDriverUnavailability**](DriverunavailabilityApi.md#retrieveDriverUnavailability) | **GET** /driver-unavailability/{driverunavailabilityId} | Retrieve a DriverUnavailability
[**retrieveListDriverUnavailability**](DriverunavailabilityApi.md#retrieveListDriverUnavailability) | **PUT** /driver-unavailability | Retrieve List of DriverUnavailability
[**setDriverUnavailability**](DriverunavailabilityApi.md#setDriverUnavailability) | **POST** /driver-unavailability/set | Set (create or update) a driver unavailability
[**updateDriverUnavailability**](DriverunavailabilityApi.md#updateDriverUnavailability) | **PUT** /driver-unavailability/{driverunavailabilityId} | Update a specific DriverUnavailability object

# **createDriverUnavailability**
> \BumbalClient\Model\ApiResponse4 createDriverUnavailability($body)

Add a new DriverUnavailability

Add a new DriverUnavailability

### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: api_key
BumbalClient\Configuration::getDefaultConfiguration()->setApiKey('ApiKey', 'YOUR_API_KEY');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// BumbalClient\Configuration::getDefaultConfiguration()->setApiKeyPrefix('ApiKey', 'Bearer');

$api_instance = new BumbalClient\Api\DriverunavailabilityApi();
$body = new \BumbalClient\Model\DriverUnavailabilityModel(); // \BumbalClient\Model\DriverUnavailabilityModel | DriverUnavailability object that needs to be created

try {
    $result = $api_instance->createDriverUnavailability($body);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DriverunavailabilityApi->createDriverUnavailability: ', $e->getMessage(), PHP_EOL;
}
?>
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **body** | [**\BumbalClient\Model\DriverUnavailabilityModel**](../Model/DriverUnavailabilityModel.md)| DriverUnavailability object that needs to be created | [optional]

### Return type

[**\BumbalClient\Model\ApiResponse4**](../Model/ApiResponse4.md)

### Authorization

[api_key](../../README.md#api_key)

### HTTP request headers

 - **Content-Type**: application/json, application/xml
 - **Accept**: application/json, application/xml

[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)

# **deleteDriverUnavailability**
> \BumbalClient\Model\ApiResponse2 deleteDriverUnavailability($driverunavailability_id)

Delete a DriverUnavailability entry

Delete a Metadata entry

### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: api_key
BumbalClient\Configuration::getDefaultConfiguration()->setApiKey('ApiKey', 'YOUR_API_KEY');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// BumbalClient\Configuration::getDefaultConfiguration()->setApiKeyPrefix('ApiKey', 'Bearer');

$api_instance = new BumbalClient\Api\DriverunavailabilityApi();
$driverunavailability_id = 789; // int | ID of DriverUnavailability to delete

try {
    $result = $api_instance->deleteDriverUnavailability($driverunavailability_id);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DriverunavailabilityApi->deleteDriverUnavailability: ', $e->getMessage(), PHP_EOL;
}
?>
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **driverunavailability_id** | **int**| ID of DriverUnavailability to delete |

### Return type

[**\BumbalClient\Model\ApiResponse2**](../Model/ApiResponse2.md)

### Authorization

[api_key](../../README.md#api_key)

### HTTP request headers

 - **Content-Type**: application/json, application/xml
 - **Accept**: application/json, application/xml

[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)

# **retrieveDriverUnavailability**
> \BumbalClient\Model\DriverUnavailabilityModel retrieveDriverUnavailability($driverunavailability_id, $include_object_type_name, $include_record_info)

Retrieve a DriverUnavailability

Retrieve an DriverUnavailability

### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: api_key
BumbalClient\Configuration::getDefaultConfiguration()->setApiKey('ApiKey', 'YOUR_API_KEY');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// BumbalClient\Configuration::getDefaultConfiguration()->setApiKeyPrefix('ApiKey', 'Bearer');

$api_instance = new BumbalClient\Api\DriverunavailabilityApi();
$driverunavailability_id = 789; // int | ID of DriverUnavailability to retrieve
$include_object_type_name = false; // bool | Show the name of the object type
$include_record_info = false; // bool | Show the record info

try {
    $result = $api_instance->retrieveDriverUnavailability($driverunavailability_id, $include_object_type_name, $include_record_info);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DriverunavailabilityApi->retrieveDriverUnavailability: ', $e->getMessage(), PHP_EOL;
}
?>
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **driverunavailability_id** | **int**| ID of DriverUnavailability to retrieve |
 **include_object_type_name** | **bool**| Show the name of the object type | [optional] [default to false]
 **include_record_info** | **bool**| Show the record info | [optional] [default to false]

### Return type

[**\BumbalClient\Model\DriverUnavailabilityModel**](../Model/DriverUnavailabilityModel.md)

### Authorization

[api_key](../../README.md#api_key)

### HTTP request headers

 - **Content-Type**: application/json, application/xml
 - **Accept**: application/json, application/xml

[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)

# **retrieveListDriverUnavailability**
> \BumbalClient\Model\DriverUnavailabilityListResponse retrieveListDriverUnavailability($arguments)

Retrieve List of DriverUnavailability

Retrieve List of DriverUnavailability

### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: api_key
BumbalClient\Configuration::getDefaultConfiguration()->setApiKey('ApiKey', 'YOUR_API_KEY');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// BumbalClient\Configuration::getDefaultConfiguration()->setApiKeyPrefix('ApiKey', 'Bearer');

$api_instance = new BumbalClient\Api\DriverunavailabilityApi();
$arguments = new \BumbalClient\Model\DriverUnavailabilityRetrieveListArguments(); // \BumbalClient\Model\DriverUnavailabilityRetrieveListArguments | DriverUnavailability RetrieveList Arguments

try {
    $result = $api_instance->retrieveListDriverUnavailability($arguments);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DriverunavailabilityApi->retrieveListDriverUnavailability: ', $e->getMessage(), PHP_EOL;
}
?>
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **arguments** | [**\BumbalClient\Model\DriverUnavailabilityRetrieveListArguments**](../Model/DriverUnavailabilityRetrieveListArguments.md)| DriverUnavailability RetrieveList Arguments |

### Return type

[**\BumbalClient\Model\DriverUnavailabilityListResponse**](../Model/DriverUnavailabilityListResponse.md)

### Authorization

[api_key](../../README.md#api_key)

### HTTP request headers

 - **Content-Type**: application/json, application/xml
 - **Accept**: application/json, application/xml

[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)

# **setDriverUnavailability**
> \BumbalClient\Model\ApiResponse setDriverUnavailability($body)

Set (create or update) a driver unavailability

Set (create or update) a driver unavailability. If id or links are set in the data, and a corresponding driver unavailability is found in Bumbal, an update will be performed.

### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: api_key
BumbalClient\Configuration::getDefaultConfiguration()->setApiKey('ApiKey', 'YOUR_API_KEY');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// BumbalClient\Configuration::getDefaultConfiguration()->setApiKeyPrefix('ApiKey', 'Bearer');

$api_instance = new BumbalClient\Api\DriverunavailabilityApi();
$body = new \BumbalClient\Model\DriverUnavailabilityModel(); // \BumbalClient\Model\DriverUnavailabilityModel | DriverUnavailability object

try {
    $result = $api_instance->setDriverUnavailability($body);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DriverunavailabilityApi->setDriverUnavailability: ', $e->getMessage(), PHP_EOL;
}
?>
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **body** | [**\BumbalClient\Model\DriverUnavailabilityModel**](../Model/DriverUnavailabilityModel.md)| DriverUnavailability object | [optional]

### Return type

[**\BumbalClient\Model\ApiResponse**](../Model/ApiResponse.md)

### Authorization

[api_key](../../README.md#api_key)

### HTTP request headers

 - **Content-Type**: application/json, application/xml
 - **Accept**: application/json, application/xml

[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)

# **updateDriverUnavailability**
> \BumbalClient\Model\ApiResponse1 updateDriverUnavailability($driverunavailability_id, $body)

Update a specific DriverUnavailability object

Update a specific DriverUnavailability object

### Example
```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: api_key
BumbalClient\Configuration::getDefaultConfiguration()->setApiKey('ApiKey', 'YOUR_API_KEY');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// BumbalClient\Configuration::getDefaultConfiguration()->setApiKeyPrefix('ApiKey', 'Bearer');

$api_instance = new BumbalClient\Api\DriverunavailabilityApi();
$driverunavailability_id = 789; // int | ID of the DriverUnavailability object to update
$body = new \BumbalClient\Model\DriverUnavailabilityModel(); // \BumbalClient\Model\DriverUnavailabilityModel | DriverUnavailability object that needs to be updated

try {
    $result = $api_instance->updateDriverUnavailability($driverunavailability_id, $body);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DriverunavailabilityApi->updateDriverUnavailability: ', $e->getMessage(), PHP_EOL;
}
?>
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **driverunavailability_id** | **int**| ID of the DriverUnavailability object to update |
 **body** | [**\BumbalClient\Model\DriverUnavailabilityModel**](../Model/DriverUnavailabilityModel.md)| DriverUnavailability object that needs to be updated | [optional]

### Return type

[**\BumbalClient\Model\ApiResponse1**](../Model/ApiResponse1.md)

### Authorization

[api_key](../../README.md#api_key)

### HTTP request headers

 - **Content-Type**: application/json, application/xml
 - **Accept**: application/json, application/xml

[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)


text:
/*global QUnit, sinon*/

QUnit.config.autostart = false;

sap.ui.require([
	'sap/ui/rta/ControlTreeModifier',
	'sap/ui/fl/changeHandler/JsControlTreeModifier',
	'sap/m/Button',
	'sap/ui/layout/HorizontalLayout',
	'sap/ui/core/TooltipBase',
	'sap/ui/model/json/JSONModel',
	'sap/ui/thirdparty/sinon',
	'sap/ui/thirdparty/sinon-ie',
	'sap/ui/thirdparty/sinon-qunit'
],
function(
	RtaControlTreeModifier,
	JSControlTreeModifier,
	Button,
	HorizontalLayout,
	TooltipBase,
	JSONModel
){
	"use strict";
	QUnit.start();

	var sandbox = sinon.sandbox.create();

	QUnit.module("Given a button is instantiated...", {

		beforeEach : function(assert) {
			this.oModel = new JSONModel({
				text1 : "text1",
				text2 : "text2"
			});
			this.oButton = new Button();
		},
		afterEach : function(assert) {
			this.oButton.destroy();
		}
	}, function() {
		QUnit.test("when the button's property is changed via RTA ControlTreeModifier...", function(assert) {
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.setProperty(this.oButton, "text", "value");
			assert.strictEqual(this.oButton.getText(), "value", "then the correct property is set.");
		});

		QUnit.test("when the button's visibility is set to false and an undo happens afterwards...", function(assert) {
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.setVisible(this.oButton, false);
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(
				this.oButton.getVisible(),
				false,
				"then the button's visibility is false before the undo.");
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oButton.getVisible(),
				true,
				"then the visibility of the button is set back to true after the undo.");
		});

		QUnit.test("when the button's text property is set and bound to a path...", function(assert){
			RtaControlTreeModifier.setProperty(this.oButton, "text", "first value");
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.bindProperty(this.oButton, "text", "/Binding");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oButton.getText(),
				"first value",
				"then after the undo the text of the button goes back to the first value.");
		});

		QUnit.test("when the button's text property binding changes using bindProperty...", function(assert){
			RtaControlTreeModifier.bindProperty(this.oButton, "text", "/Binding");
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.bindProperty(this.oButton, "text", "/NewBinding");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(
				this.oButton.getBindingPath("text"),
				"/NewBinding",
				"then the binding path of the text property is changed properly."
				);
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oButton.getBindingPath("text"),
				"/Binding",
				"then after the undo the binding of the text of the button goes back to the first value."
				);
		});

		QUnit.test("when the button's text property binding was done using a binding info object and is changed...", function(assert){
			this.oButton.bindProperty("text", {
					path: '/date',
					type: 'sap.ui.model.type.Date',
					formatOptions: {
						relative: true,
						relativeScale: 'auto'
					}
				});
			var mBindingInfo = this.oButton.getBindingInfo("text");
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.bindProperty(this.oButton, "text", "/NewBinding");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(
				this.oButton.getBindingPath("text"),
				"/NewBinding",
				"then the binding path of the text property is changed properly."
				);
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oButton.getBindingInfo("text"),
				mBindingInfo,
				"then after the undo the binding of the text of the button goes back to the first value."
				);
		});

		QUnit.test("when the button's property binding is set with an expression and an undo is executed...", function(assert){
			this.oButton = new Button({text : "{= ${/Items}.length > 0}"});
			var mBindingInfo = this.oButton.getBindingInfo("text");
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.setPropertyBinding(this.oButton, "text", "/newBinding");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oButton.getBindingInfo("text"),
				mBindingInfo,
				"then after the undo the previous binding is restored."
				);
		});

		QUnit.test("when a data model is present and a button's text property previously set as value is bound to a path...", function(assert){
			RtaControlTreeModifier.setProperty(this.oButton, "text", "first value");
			this.oButton.setModel(this.oModel);
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.bindProperty(this.oButton, "text", "/text1");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(
				this.oButton.getText(),
				"text1",
				"the text property is correctly set to the value in the data model.");
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oButton.getText(),
				"first value",
				"then after the undo the text of the button goes back to the first value.");
		});

		QUnit.test("when a data model is present and a button's text property bound to a path is bound to a different path...", function(assert){
			this.oButton.setModel(this.oModel);
			RtaControlTreeModifier.bindProperty(this.oButton, "text", "/text1");
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.bindProperty(this.oButton, "text", "/text2");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(
				this.oButton.getText(),
				"text2",
				"the text property is correctly set to the value in the data model.");
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oButton.getText(),
				"text1",
				"then after the undo the text of the button goes back to the first value in the data model.");
		});

		QUnit.test("when a data model is present and a button's text property binding was done using a binding info object and is changed...", function(assert){
			this.oButton.bindProperty("text", {
					path: '/date',
					type: 'sap.ui.model.type.Date',
					formatOptions: {
						relative: true,
						relativeScale: 'auto'
					}
				});
			this.oButton.setModel(this.oModel);
			var mBindingInfo = this.oButton.getBindingInfo("text");
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.bindProperty(this.oButton, "text", "/NewBinding");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(
				this.oButton.getBindingPath("text"),
				"/NewBinding",
				"then the binding path of the text property is changed properly."
				);
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oButton.getBindingInfo("text"),
				mBindingInfo,
				"then after the undo the binding of the text of the button goes back to the first value."
				);
		});

		QUnit.test("when a button's text property is directly unbound (with unbindProperty())...", function(assert){
			this.oButton.bindProperty("text", {
					path: '/date',
					type: 'sap.ui.model.type.Date',
					formatOptions: {
						relative: true,
						relativeScale: 'auto'
					}
				});
			this.oButton.setModel(this.oModel);
			var mBindingInfo = this.oButton.getBindingInfo("text");
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.unbindProperty(this.oButton, "text");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(
				this.oButton.getBinding("text"),
				undefined,
				"then the binding is removed properly."
				);
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oButton.getBindingInfo("text"),
				mBindingInfo,
				"then after the undo the binding of the text of the button goes back to the first value."
				);
		});
	});

	QUnit.module("Given an ObjectPageLayout with a visible Section and an invisible Section are available...", {

		beforeEach : function(assert) {
			this.oView = sap.ui.xmlview("idMain1", "sap.ui.rta.test.ObjectPage");
			this.oView.placeAt("test-view");
			sap.ui.getCore().applyChanges();
		},
		afterEach : function(assert) {
			this.oView.destroy();
		}

	}, function() {
		QUnit.test("when stashed section is unstashed...", function(assert) {
			RtaControlTreeModifier.startRecordingUndo();
			var oStashedControl = sap.ui.getCore().byId(this.oView.createId("ObjectPageSection3"));
			RtaControlTreeModifier.setStashed(oStashedControl, false);
			var oCreatedControl = sap.ui.getCore().byId(this.oView.createId("ObjectPageSection3"));
			assert.strictEqual(oCreatedControl.getVisible(), true, "then the Object Page Section control is created and visible");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(oCreatedControl.getVisible(), false, "then after the undo the Page Section control is no longer visible");

		});

		QUnit.test("when visible section is stashed...", function(assert) {
			RtaControlTreeModifier.startRecordingUndo();
			var oControl = sap.ui.getCore().byId(this.oView.createId("ObjectPageSection1"));
			RtaControlTreeModifier.setStashed(oControl, true);
			assert.strictEqual(oControl.getVisible(), false, "then the Object Page Section control is now invisible");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(oControl.getVisible(), true, "then after the undo the Page Section control is again visible");
		});

		QUnit.test("when invisible section is stashed...", function(assert) {
			RtaControlTreeModifier.startRecordingUndo();
			var oControl = sap.ui.getCore().byId(this.oView.createId("ObjectPageSection4"));
			RtaControlTreeModifier.setStashed(oControl, true);
			assert.strictEqual(oControl.getVisible(), false, "then the Object Page Section control remains invisible");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(oControl.getVisible(), false, "then after the undo the Page Section control also remains invisible");
		});
	});

	QUnit.module("Given an HorizontalLayout with two buttons...", {

		beforeEach : function(assert) {
			this.oHorizontalLayout = new HorizontalLayout(
				{content : [new Button("firstButton"), new Button("secondButton")]}
			);
		},
		afterEach : function(assert) {
			this.oHorizontalLayout.destroy();
		}
	}, function() {
		QUnit.test("when insertAggregation is called to add a button in the middle of the layout...", function(assert){
			var oButton = new Button("AddedMiddle");
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.insertAggregation(this.oHorizontalLayout, "content", oButton, 1);
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(this.oHorizontalLayout.getAggregation("content")[1].getId(), "AddedMiddle", "then the button was properly added");
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(this.oHorizontalLayout.getAggregation("content").length, 2, "then after the undo the button is removed");
		});

		QUnit.test("when removeAggregation on the second button is called...", function(assert){
			var oControl = sap.ui.getCore().byId("secondButton");
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.removeAggregation(this.oHorizontalLayout, "content", oControl);
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(this.oHorizontalLayout.getAggregation("content").length, 1, "then the button was properly removed");
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(
				this.oHorizontalLayout.getAggregation("content")[1].getId(),
				"secondButton",
				"then after the undo the button is restored at the same position of the aggregation"
			);
		});

		QUnit.test("when removeAllAggregation is called to remove all buttons...", function(assert){
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.removeAllAggregation(this.oHorizontalLayout, "content");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(this.oHorizontalLayout.getAggregation("content"), null, "then the buttons were properly removed");
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(this.oHorizontalLayout.getAggregation("content").length, 2, "then after the undo all buttons are restored");
			assert.strictEqual(
				this.oHorizontalLayout.getAggregation("content")[1].getId(),
				"secondButton",
				"then after the undo the buttons are restored at the same position of the aggregation"
			);
		});
	});

	QUnit.module("Given a button and a tooltip...", {
		beforeEach : function(assert) {
			this.oButton = new Button("TooltipButton");
			this.oToolTip = new TooltipBase("ToolTip", { text : "first text" });
			this.oNewToolTip = new TooltipBase("NewToolTip", { text : "new text"});
		},
		afterEach : function(assert) {
			this.oButton.destroy();
			this.oToolTip.destroy();
			this.oNewToolTip.destroy();
		}
	}, function() {
		QUnit.test("when a tooltip aggregation is inserted in the button...", function(assert){
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.insertAggregation(this.oButton, "tooltip", this.oToolTip);
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(this.oButton.getTooltip().getText(), "first text", "then the tooltip was properly added to the button");
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(this.oButton.getTooltip(), null, "then after the undo the tooltip is removed");
		});

		QUnit.test("when a tooltip aggregation is inserted in the button with a tooltip already...", function(assert){
			RtaControlTreeModifier.insertAggregation(this.oButton, "tooltip", this.oToolTip);
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.insertAggregation(this.oButton, "tooltip", this.oNewToolTip);
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(this.oButton.getAggregation("tooltip").getText(), "new text", "then the tooltip was properly modified on the button");
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(this.oButton.getAggregation("tooltip").getText(), "first text", "then after the undo the first tooltip is restored");
		});

		QUnit.test("when a tooltip aggregation is removed from the button...", function(assert){
			RtaControlTreeModifier.insertAggregation(this.oButton, "tooltip", this.oToolTip);
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.insertAggregation(this.oButton, "tooltip");
			this.aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			assert.strictEqual(this.oButton.getAggregation("tooltip"), null, "then the tooltip was properly removed from the button");
			RtaControlTreeModifier.performUndo(this.aUndoStack);
			assert.strictEqual(this.oButton.getAggregation("tooltip").getText(), "first text", "then after the undo the tooltip is restored");
		});
	});

	QUnit.module("Given that instantiateFragment returns 3 Buttons...", {
		beforeEach: function(assert) {
			this.oButton1 = new Button("button1");
			this.oButton2 = new Button("button2");
			this.oButton3 = new Button("button3");
			sandbox.stub(JSControlTreeModifier, "instantiateFragment").returns([this.oButton1, this.oButton2, this.oButton3]);
		},
		afterEach: function() {
			sandbox.restore();
		}
	}, function() {
		QUnit.test("when undoing instantiateFragment", function(assert) {
			RtaControlTreeModifier.startRecordingUndo();
			RtaControlTreeModifier.instantiateFragment();
			var aUndoStack = RtaControlTreeModifier.stopRecordingUndo();
			RtaControlTreeModifier.performUndo(aUndoStack);

			assert.ok(this.oButton1._bIsBeingDestroyed, "the first Button got destroyed");
			assert.ok(this.oButton2._bIsBeingDestroyed, "and the second Button got destroyed");
			assert.ok(this.oButton3._bIsBeingDestroyed, "and the third Button got destroyed");
		});
	});
});

redpajama_set_name: RedPajamaGithub


text:
namespace MedicineBatchControl
{
    partial class MedicineBatchControl
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.label1 = new System.Windows.Forms.Label();
            this.dateTimeTextBox有效期至 = new CustomTextBox.DateTimeTextBox();
            this.classMedicineProductionBatchPropertiesBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.label2 = new System.Windows.Forms.Label();
            this.dateTimeTextBox生产日期 = new CustomTextBox.DateTimeTextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.textBox生产批号 = new System.Windows.Forms.TextBox();
            this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components);
            this.groupBox1.SuspendLayout();
            this.tableLayoutPanel1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.classMedicineProductionBatchPropertiesBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit();
            this.SuspendLayout();
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.tableLayoutPanel1);
            this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.groupBox1.Location = new System.Drawing.Point(0, 0);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(223, 103);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "生产批号";
            //
            // tableLayoutPanel1
            //
            this.tableLayoutPanel1.ColumnCount = 2;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
            this.tableLayoutPanel1.Controls.Add(this.dateTimeTextBox有效期至, 1, 2);
            this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.dateTimeTextBox生产日期, 1, 1);
            this.tableLayoutPanel1.Controls.Add(this.label3, 0, 2);
            this.tableLayoutPanel1.Controls.Add(this.textBox生产批号, 1, 0);
            this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 17);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 4;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 8F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(217, 83);
            this.tableLayoutPanel1.TabIndex = 7;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.label1.Location = new System.Drawing.Point(3, 13);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "生产批号:";
            //
            // dateTimeTextBox有效期至
            //
            this.dateTimeTextBox有效期至.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dateTimeTextBox有效期至.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.classMedicineProductionBatchPropertiesBindingSource, "有效期至", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "d"));
            this.dateTimeTextBox有效期至.errorMessage = null;
            this.dateTimeTextBox有效期至.Location = new System.Drawing.Point(74, 53);
            this.dateTimeTextBox有效期至.Margin = new System.Windows.Forms.Padding(3, 3, 28, 3);
            this.dateTimeTextBox有效期至.Name = "dateTimeTextBox有效期至";
            this.dateTimeTextBox有效期至.Size = new System.Drawing.Size(115, 21);
            this.dateTimeTextBox有效期至.TabIndex = 2;
            this.dateTimeTextBox有效期至.Text = "2009年10月11日";
            this.dateTimeTextBox有效期至.Value = new System.DateTime(2009, 10, 11, 0, 0, 0, 0);
            this.dateTimeTextBox有效期至.Validating += new System.ComponentModel.CancelEventHandler(this.dateTimeTextBox_Validating);
            this.dateTimeTextBox有效期至.Validated += new System.EventHandler(this.dateTimeTextBox_Validated);
            //
            // classMedicineProductionBatchPropertiesBindingSource
            //
            this.classMedicineProductionBatchPropertiesBindingSource.DataSource = typeof(ClassLibraryMedicineProductionBatch.ClassMedicineProductionBatchProperties);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.label2.Location = new System.Drawing.Point(3, 38);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(65, 12);
            this.label2.TabIndex = 2;
            this.label2.Text = "生产日期:";
            //
            // dateTimeTextBox生产日期
            //
            this.dateTimeTextBox生产日期.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dateTimeTextBox生产日期.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.classMedicineProductionBatchPropertiesBindingSource, "生产日期", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "d"));
            this.dateTimeTextBox生产日期.errorMessage = null;
            this.dateTimeTextBox生产日期.Location = new System.Drawing.Point(74, 28);
            this.dateTimeTextBox生产日期.Margin = new System.Windows.Forms.Padding(3, 3, 28, 3);
            this.dateTimeTextBox生产日期.Name = "dateTimeTextBox生产日期";
            this.dateTimeTextBox生产日期.Size = new System.Drawing.Size(115, 21);
            this.dateTimeTextBox生产日期.TabIndex = 1;
            this.dateTimeTextBox生产日期.Text = "2009年10月11日";
            this.dateTimeTextBox生产日期.Value = new System.DateTime(2009, 10, 11, 0, 0, 0, 0);
            this.dateTimeTextBox生产日期.Validating += new System.ComponentModel.CancelEventHandler(this.dateTimeTextBox_Validating);
            this.dateTimeTextBox生产日期.Validated += new System.EventHandler(this.dateTimeTextBox_Validated);
            this.dateTimeTextBox生产日期.ValueChanged += new System.EventHandler(this.dateTimeTextBox生产日期_ValueChanged);
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.label3.Location = new System.Drawing.Point(3, 63);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(65, 12);
            this.label3.TabIndex = 4;
            this.label3.Text = "有效期至:";
            //
            // textBox生产批号
            //
            this.textBox生产批号.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox生产批号.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.classMedicineProductionBatchPropertiesBindingSource, "生产批号", true));
            this.textBox生产批号.Location = new System.Drawing.Point(74, 3);
            this.textBox生产批号.Margin = new System.Windows.Forms.Padding(3, 3, 28, 3);
            this.textBox生产批号.Name = "textBox生产批号";
            this.textBox生产批号.Size = new System.Drawing.Size(115, 21);
            this.textBox生产批号.TabIndex = 0;
            this.textBox生产批号.Validated += new System.EventHandler(this.textBox生产批号_Validated);
            this.textBox生产批号.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.control_KeyPress);
            //
            // errorProvider1
            //
            this.errorProvider1.ContainerControl = this;
            //
            // MedicineBatchControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.groupBox1);
            this.Name = "MedicineBatchControl";
            this.Size = new System.Drawing.Size(223, 103);
            this.groupBox1.ResumeLayout(false);
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.classMedicineProductionBatchPropertiesBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox生产批号;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.BindingSource classMedicineProductionBatchPropertiesBindingSource;
        private System.Windows.Forms.ErrorProvider errorProvider1;
        private CustomTextBox.DateTimeTextBox dateTimeTextBox有效期至;
        private CustomTextBox.DateTimeTextBox dateTimeTextBox生产日期;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
    }
}


text:
namespace dotless.Core.Parser.Tree
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using Infrastructure;
    using Infrastructure.Nodes;
    using Utils;
    using Exceptions;
    using Plugins;
    using dotless.Core.Importers;

    public class Url : Node
    {
        public Node Value { get; set; }
        public List<string> ImportPaths { get; set; }
        public IImporter Importer { get; set; }

        public Url(Node value, IImporter importer)
        {
            Importer = importer;
            ImportPaths = importer.GetCurrentPathsClone();

            Value = value;
        }

        public Url(Node value)
        {
            Value = value;
        }

        /// <summary>
        ///  Gets the url value, unadjusted, as in the less
        ///  If the url does not contain a text node this will return null
        /// </summary>
        /// <returns></returns>
        public string GetUnadjustedUrl()
        {
            var textValue = Value as TextNode;
            if (textValue != null)
            {
                return textValue.Value;
            }

            return null;
        }

        private Node AdjustUrlPath(Node value)
        {
            var textValue = value as TextNode;
            if (textValue != null)
                return AdjustUrlPath(textValue);
            return value;
        }

        private TextNode AdjustUrlPath(TextNode textValue)
        {
            if (Importer != null)
            {
                textValue.Value = Importer.AlterUrl(textValue.Value, ImportPaths);
            }
            return textValue;
        }

        public override Node Evaluate(Env env)
        {
            return new Url(AdjustUrlPath(Value.Evaluate(env)));
        }

        public override void AppendCSS(Env env)
        {
            env.Output
                .Append("url(")
                .Append(Value)
                .Append(")");
        }

        public override void Accept(IVisitor visitor)
        {
            Value = VisitAndReplace(Value, visitor);
        }
    }
}


text:
//
//  MVPCalendarViewController.m
//  MoviePro
//
//  Created by 风海 on 17/2/21.
//  Copyright © 2017年 moviepro. All rights reserved.
//

#import "MVPCalendarViewController.h"
#import "FSCalendar.h"
#import "MVPCalendarResultModel.h"
#import "MVPCalendarConfigModel.h"
#import "MVPWeekTitleView.h"
#import "MVPCommonUtils.h"
#import "NSDictionary+SHYUtil.h"
#import "UIColor+SHYUtil.h"
#import "NSArray+SHYUtil.h"
#import <Masonry/Masonry.h>

@interface MVPCalendarViewController ()<FSCalendarDataSource,FSCalendarDelegate,FSCalendarDelegateAppearance>

@property (weak, nonatomic) FSCalendar *calendar;
@property (strong, nonatomic) NSDate *minimumDate;
@property (strong, nonatomic) NSDate *maximumDate;
@property (strong, nonatomic) NSDateFormatter *dateFormatter;
@property (strong, nonatomic) NSCalendar *gregorian;
@property (strong, nonatomic) NSDateComponents *comps;
@property (strong, nonatomic) MVPWeekTitleView *weekTitleView;

@property (strong, nonatomic) MVPCalenarConfigModel *bizConfigModel;
@property (assign, nonatomic) long baseYear;
@property (assign, nonatomic) long bizType;

@end

@implementation MVPCalendarViewController

- (NSDateFormatter *)dateFormatter{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        _dateFormatter.dateFormat = @"yyyy-MM-dd";
    }
    return _dateFormatter;
}

- (NSDateComponents *)comps{
    if (!_comps) {
        _comps = [[NSDateComponents alloc] init];
    }
    return _comps;
}

- (MVPWeekTitleView *)weekTitleView{
    if (!_weekTitleView) {
        _weekTitleView = [[MVPWeekTitleView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 25)];
    }
    return _weekTitleView;
}

- (void)setSelectionModel:(MVPCalendarResultModel *)selectionModel{
    _selectionModel = selectionModel;
    if (_selectionModel && selectionModel.startModel.year >= _baseYear) {
        [self configSelectionUI];
    }
}

//bizType
- (void)setBizType:(long)bizType configModel:(MVPCalenarConfigModel *)bizConfigModel{
    _bizType = bizType;
    MVPCalenarConfigModel *configModel = [[MVPCalenarConfigModel alloc] initWithDefaultData];

    if (bizConfigModel) {
        configModel = bizConfigModel;
    }
    //codereview: 如果非法字符转义 检查是否crash
    _baseYear = [[configModel.startDate substringToIndex:4] longLongValue];
    if (_baseYear == 0) {
        _baseYear = 2011;
    }
    self.bizConfigModel = configModel;

    [self configUI];
}

- (void)configUI{

    NSDateFormatter *dateFormatter = [MVPCommonUtils chineseDateFormater];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    self.minimumDate = [dateFormatter dateFromString:self.bizConfigModel.startDate.length>0?self.bizConfigModel.startDate:@"20110101"];

    if (self.bizConfigModel.singleDayDelta < 0) {
        //显示到昨天
        self.maximumDate = [MVPCommonUtils getPreDate:[NSDate date] days:abs(self.bizConfigModel.singleDayDelta)];

    }else if(self.bizConfigModel.singleDayDelta > 0){
        self.maximumDate = [MVPCommonUtils getNextDate:[NSDate date] days:self.bizConfigModel.singleDayDelta];
    }else if (self.bizConfigModel.presaleForSingle){
        long presaleDay = self.bizConfigModel.presaleForSingle;
        self.maximumDate = [MVPCommonUtils getNextDate:[NSDate date] days:presaleDay];
    }else{
        self.maximumDate = [NSDate date];
    }
    if ([self.maximumDate compare:self.minimumDate] == NSOrderedAscending) {
        self.minimumDate =[dateFormatter dateFromString:@"20110101"];
    }

    self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    [self configDayCalendar];

    self.calendar.accessibilityIdentifier = @"calendar";
}

- (void)configSelectionUI{
    NSString *dateString = [NSString stringWithFormat:@"%ld-%ld-%ld",_selectionModel.startModel.year,_selectionModel.startModel.month,_selectionModel.startModel.day];
    NSDate *tagDate = [self.dateFormatter dateFromString:dateString];
    if ([tagDate compare:self.maximumDate] == NSOrderedDescending || _selType != CalendarTypeDay) {
        return;
    }
    [self.calendar selectDate:tagDate scrollToDate:YES];
}

- (void)configDayCalendar{
    FSCalendar *calendar = [[FSCalendar alloc] init];
    if (self.bizConfigModel.presaleForSingle || self.bizConfigModel.singleDayDelta >0) {
        calendar.isPreSale = YES;
        calendar.preNum = 15;
        if (self.bizConfigModel.singleDayDelta > 0) {
            calendar.preNum = self.bizConfigModel.singleDayDelta;
        }
    }
    calendar.backgroundColor = [UIColor whiteColor];
    calendar.dataSource = self;
    calendar.delegate = self;
    calendar.pagingEnabled = NO; // important
    calendar.allowsMultipleSelection = NO;
    calendar.firstWeekday = 1;
    calendar.placeholderType = FSCalendarPlaceholderTypeNone;
    calendar.appearance.caseOptions = FSCalendarCaseOptionsWeekdayUsesSingleUpperCase|FSCalendarCaseOptionsHeaderUsesUpperCase;
    self.calendar = calendar;
    [self.view addSubview:self.calendar];
    [self.view addSubview:self.weekTitleView];
    [_calendar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.weekTitleView.mas_bottom).offset(-1);
        make.left.right.bottom.equalTo(self.view);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

}

#pragma mark - FSCalendarDataSource

- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar
{
    return self.minimumDate;
}

- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar
{
    return self.maximumDate;
}

#pragma mark - FSCalendarDelegate

- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date
{
    return [MVPCommonUtils isSameDay:[NSDate date] date2:date] ? @"今天" : nil;
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    [self callBackResult:date];
}

- (void)calendar:(FSCalendar *)calendar didDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{

}

- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date
{
    int limitDay;
    if (self.bizConfigModel.singleDayDelta > 0) {
        limitDay = self.bizConfigModel.singleDayDelta - 1;
    }else{
        limitDay = 14;
    }

    if ((self.bizConfigModel.presaleForSingle || self.bizConfigModel.singleDayDelta > 0) && ([date compare:[NSDate date]] == NSOrderedDescending)&&[MVPCommonUtils getDaysBetweenOneDay:date otherDay:[NSDate date]] <= limitDay) {
        return @"预售";
    }
    return nil;
}

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar
{
    NSLog(@"did change page %@",[self.dateFormatter stringFromDate:calendar.currentPage]);
}

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

- (void)callBackResult:(NSDate *)date{

    NSInteger unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;
    self.comps = [_gregorian components:unitFlags fromDate:date];
    NSInteger day = [self.comps day];
    NSInteger month = [self.comps month];
    NSInteger year = [self.comps year];

    MVPCalendarResultModel *resultModel = [[MVPCalendarResultModel alloc] init];
    MVPCalendarModel *startModel = [[MVPCalendarModel alloc] init];
    MVPCalendarModel *endModel = [[MVPCalendarModel alloc] init];

    startModel.year = year;
    startModel.week = 0;
    startModel.month = month;
    startModel.day = day;
    endModel.year = year;
    endModel.week = 0;
    endModel.month = month;
    endModel.day = day;

    resultModel.type = CalendarTypeDay;
    resultModel.startModel = startModel;
    resultModel.endModel = endModel;
    _resultBlock(resultModel);

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
freebsd_major=`uname -r | awk -F. '{ print $1 }'`
if [ $freebsd_major -gt 9 ]; then
  pkg_command="pkg install -y"
  perl_pkg="perl5"
else
  pkg_command="pkg_add -r"
  perl_pkg="perl"
fi

if [ $PACKER_BUILDER_TYPE == 'virtualbox-iso' ]; then
  # disable X11 because vagrants are (usually) headless
  echo 'WITHOUT_X11="YES"' >> /etc/make.conf

  $pkg_command virtualbox-ose-additions

  echo 'vboxdrv_load="YES"' >> /boot/loader.conf
  echo 'vboxnet_enable="YES"' >> /etc/rc.conf
  echo 'vboxguest_enable="YES"' >> /etc/rc.conf
  echo 'vboxservice_enable="YES"' >> /etc/rc.conf

  echo 'virtio_blk_load="YES"' >> /boot/loader.conf
  if [ $freebsd_major -gt 9 ]; then
    # Appeared in FreeBSD 10
    echo 'virtio_scsi_load="YES"' >> /boot/loader.conf
  fi
  echo 'virtio_balloon_load="YES"' >> /boot/loader.conf
  echo 'if_vtnet_load="YES"' >> /boot/loader.conf

  echo 'ifconfig_vtnet0_name="em0"' >> /etc/rc.conf
  echo 'ifconfig_vtnet1_name="em1"' >> /etc/rc.conf
  echo 'ifconfig_vtnet2_name="em2"' >> /etc/rc.conf
  echo 'ifconfig_vtnet3_name="em3"' >> /etc/rc.conf
fi

if [ $PACKER_BUILDER_TYPE == 'vmware-iso' ]; then
  mkdir /tmp/vmfusion
  mkdir /tmp/vmfusion-archive
  mdconfig -a -t vnode -f /home/vagrant/freebsd.iso -u 0
  mount -t cd9660 /dev/md0 /tmp/vmfusion
  tar xzf /tmp/vmfusion/vmware-freebsd-tools.tar.gz -C /tmp/vmfusion-archive
  $pkg_command $perl_pkg
  # Welcome to 2005. Have you heard of this "YouTube" thing?
  $pkg_command compat6x-`uname -m`
  /tmp/vmfusion-archive/vmware-tools-distrib/vmware-install.pl --default

  echo 'ifconfig_vxn0="dhcp"' >> /etc/rc.conf
  umount /tmp/vmfusion
  rmdir /tmp/vmfusion
  rm -rf /tmp/vmfusion-archive
  rm /home/vagrant/freebsd.iso
fi


text:
from xml.etree import ElementTree as ET

from malwareconfig import crypto
from malwareconfig.common import Decoder

class AdWind(Decoder):
    decoder_name = "AdWind"
    decoder__version = 1
    decoder_author = "@kevthehermit"
    decoder_description = "AdWind Decoder"

    def __init__(self):
        self.config = {}

    @staticmethod
    def parse_config(old_config):
        if old_config['Version'] == 'Adwind RAT v1.0':
            new_config = {}
            new_config['Version'] = old_config['Version']
            new_config['Delay'] = old_config['delay']
            new_config['Domain'] = old_config['dns']
            new_config['Install Flag'] = old_config['instalar']
            new_config['Jar Name'] = old_config['jarname']
            new_config['Reg Key'] = old_config['keyClase']
            new_config['Install Folder'] = old_config['nombreCarpeta']
            new_config['Password'] = old_config['password']
            new_config['Campaign ID'] = old_config['prefijo']
            new_config['Port1'] = old_config['puerto1']
            new_config['Port2'] = old_config['puerto2']
            new_config['Reg Value'] = old_config['regname']
            return new_config

        if old_config['Version'] == 'Adwind RAT v2.0':
            new_config = {}
            new_config['Version'] = old_config['Version']
            new_config['Delay'] = old_config['delay']
            new_config['Domain'] = old_config['dns']
            new_config['Install Flag'] = old_config['instalar']
            new_config['Reg Key'] = old_config['keyClase']
            new_config['Password'] = old_config['password']
            new_config['Campaign ID'] = old_config['prefijo']
            new_config['Port1'] = old_config['puerto']
            return new_config
        return old_config

    def get_config(self):
        '''
        This is the main entry
        :return:
        '''

        key = "awenubisskqi"

        # Get the file from the zip
        zip_xml = self.file_info.file_from_zip('config.xml')

        # No Easy way to detect version so just try it

        try:
            xml_string = crypto.decrypt_des_ecb(key[:-4], zip_xml)
        except ValueError:
            xml_string = crypto.decrypt_arc4(key, zip_xml)

        # Convert to XML
        xml = ET.fromstring(xml_string)

        # Read the XML to a config dict
        config_dict = {}

        for child in xml:
            if child.text.startswith("Adwind RAT"):
                config_dict['Version'] = child.text
            else:
                config_dict[child.attrib['key']] = child.text

        # Parse the config
        config_dict = self.parse_config(config_dict)

        # Set the config to the class for use
        self.config = config_dict


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Volvariella krizii Pilát

### Remarks
null


text:
#include "allocator/AllocatorFactory.h"

#include <cassert>

#include "allocator/CrSeparableAllocator.h"
#include "allocator/RcSeparableAllocator.h"
#include "allocator/RSeparableAllocator.h"

Allocator* AllocatorFactory::createAllocator(
    const std::string& _name, const Component* _parent,
    u32 _numClients, u32 _numResources, Json::Value _settings) {
  std::string type = _settings["type"].asString();

  if (type == "cr_separable") {
    return new CrSeparableAllocator(_name, _parent, _numClients, _numResources,
                                    _settings);
  } else if (type == "rc_separable") {
    return new RcSeparableAllocator(_name, _parent, _numClients, _numResources,
                                    _settings);
  } else if (type == "r_separable") {
    return new RSeparableAllocator(_name, _parent, _numClients, _numResources,
                                   _settings);
  } else {
    fprintf(stderr, "unknown Allocator 'type': %s\n", type.c_str());
    assert(false);
  }
}


text:
var babelPresetES2015;
var modulesCommonJs;
var es2015PluginsWithCommonJs;
var es2015NativeModulesOnly;

babelPresetES2015 = require('babel-preset-es2015');
es2015PluginsWithCommonJs = babelPresetES2015.plugins;

try {
  // console.log('\nTrying to require CommonJS module using npm3 style...');
  modulesCommonJs = require('babel-plugin-transform-es2015-modules-commonjs');
} catch (error) {
  // console.log('\t\t\t\t\t\t\t...npm3 is no go');
}

if (!modulesCommonJs) {
  try {
    // console.log('\nTrying to require CommonJS module using npm2 style...');
    modulesCommonJs = require('babel-preset-es2015/node_modules/babel-plugin-transform-es2015-modules-commonjs');
  } catch (error) {
    // console.log('\t\t\t\t\t\t\t...npm2 is no go!');
  }
}

if (!modulesCommonJs) {
  throw new Error('Cannot resolve babel-plugin-transform-es2015-modules-commonjs');
} else {
  // console.log('\nSuccess, CommonJS module have been located!');
}

es2015NativeModulesOnly = es2015PluginsWithCommonJs.filter(function (es2015Plugin) {
  // console.log('\nRemoving it from es2015 preset and transforming it into es2015-native-modules');
  return es2015Plugin !== modulesCommonJs;
});

if (es2015PluginsWithCommonJs.length === es2015NativeModulesOnly.length) {
  // throw new Error('Failed to remove babel-plugin-transform-es2015-modules-commonjs from the preset.');
  /* In order to facilitate webpack-isomorphic-tools we will not throw an error but rather silent warning.
   * Reason being that one might want to use native-modules mode and still have access to common modules
   * on the development server at the same time. */
  console.log('\nWarning: CommonJS modules detected - Strict ES6-modules mode disabled.\n');
} else {
  // console.log('All Done!');
}

module.exports = {
  plugins: es2015NativeModulesOnly
};


text:
"use strict";
var $ = require("jquery"),
    Class = require("../core/class"),
    errors = require("./errors");
var CommandMapping = Class.inherit({
    ctor: function() {
        this._commandMappings = {};
        this._containerDefaults = {}
    },
    setDefaults: function(containerId, defaults) {
        this._containerDefaults[containerId] = defaults;
        return this
    },
    mapCommands: function(containerId, commandMappings) {
        var that = this;
        $.each(commandMappings, function(index, commandMapping) {
            if ("string" === typeof commandMapping) {
                commandMapping = {
                    id: commandMapping
                }
            }
            var commandId = commandMapping.id;
            var mappings = that._commandMappings[containerId] || {};
            mappings[commandId] = $.extend({
                showIcon: true,
                showText: true
            }, that._containerDefaults[containerId] || {}, commandMapping);
            that._commandMappings[containerId] = mappings
        });
        this._initExistingCommands();
        return this
    },
    unmapCommands: function(containerId, commandIds) {
        var that = this;
        $.each(commandIds, function(index, commandId) {
            var mappings = that._commandMappings[containerId] || {};
            if (mappings) {
                delete mappings[commandId]
            }
        });
        this._initExistingCommands()
    },
    getCommandMappingForContainer: function(commandId, containerId) {
        return (this._commandMappings[containerId] || {})[commandId]
    },
    checkCommandsExist: function(commands) {
        var that = this,
            result = $.grep(commands, function(commandName, index) {
                return $.inArray(commandName, that._existingCommands) < 0 && $.inArray(commandName, commands) === index
            });
        if (0 !== result.length) {
            throw errors.Error("E3005", result.join("', '"), 1 === result.length ? " is" : "s are")
        }
    },
    load: function(config) {
        if (!config) {
            return
        }
        var that = this;
        $.each(config, function(name, container) {
            that.setDefaults(name, container.defaults);
            that.mapCommands(name, container.commands)
        });
        return this
    },
    _initExistingCommands: function() {
        var that = this;
        this._existingCommands = [];
        $.each(that._commandMappings, function(name, _commands) {
            $.each(_commands, function(index, command) {
                if ($.inArray(command.id, that._existingCommands) < 0) {
                    that._existingCommands.push(command.id)
                }
            })
        })
    }
});
CommandMapping.defaultMapping = {
    "global-navigation": {
        defaults: {
            showIcon: true,
            showText: true
        },
        commands: []
    },
    "ios-header-toolbar": {
        defaults: {
            showIcon: false,
            showText: true,
            location: "after"
        },
        commands: ["edit", "save", {
            id: "back",
            location: "before"
        }, {
            id: "cancel",
            location: "before"
        }, {
            id: "create",
            showIcon: true,
            showText: false
        }]
    },
    "ios-action-sheet": {
        defaults: {
            showIcon: false,
            showText: true
        },
        commands: []
    },
    "ios-view-footer": {
        defaults: {
            showIcon: false,
            showText: true
        },
        commands: [{
            id: "delete",
            type: "danger"
        }]
    },
    "android-header-toolbar": {
        defaults: {
            showIcon: true,
            showText: false,
            location: "after"
        },
        commands: [{
            id: "back",
            showIcon: false,
            location: "before"
        }, "create", {
            id: "save",
            showText: true,
            showIcon: false,
            location: "after"
        }, {
            id: "edit",
            showText: false,
            location: "after"
        }, {
            id: "cancel",
            showText: false,
            location: "before"
        }, {
            id: "delete",
            showText: false,
            location: "after"
        }]
    },
    "android-simple-toolbar": {
        defaults: {
            showIcon: true,
            showText: false,
            location: "after"
        },
        commands: [{
            id: "back",
            showIcon: false,
            location: "before"
        }, {
            id: "create"
        }, {
            id: "save",
            showText: true,
            showIcon: false,
            location: "after"
        }, {
            id: "edit",
            showText: false,
            location: "after"
        }, {
            id: "cancel",
            showText: false,
            location: "before"
        }, {
            id: "delete",
            showText: false,
            location: "after"
        }]
    },
    "android-footer-toolbar": {
        defaults: {
            location: "after"
        },
        commands: [{
            id: "create",
            showText: false,
            location: "center"
        }, {
            id: "edit",
            showText: false,
            location: "before"
        }, {
            id: "delete",
            locateInMenu: "always"
        }, {
            id: "save",
            showIcon: false,
            location: "before"
        }]
    },
    "generic-header-toolbar": {
        defaults: {
            showIcon: false,
            showText: true,
            location: "after"
        },
        commands: ["edit", "save", {
            id: "back",
            location: "before"
        }, {
            id: "cancel",
            location: "before"
        }, {
            id: "create",
            showIcon: true,
            showText: false
        }]
    },
    "generic-view-footer": {
        defaults: {
            showIcon: false,
            showText: true
        },
        commands: [{
            id: "delete",
            type: "danger"
        }]
    },
    "win8-appbar": {
        defaults: {
            location: "after"
        },
        commands: ["edit", "cancel", "save", "delete", {
            id: "create",
            location: "before"
        }, {
            id: "refresh",
            location: "before"
        }]
    },
    "win8-toolbar": {
        defaults: {
            showText: false,
            location: "before"
        },
        commands: [{
            id: "previousPage"
        }]
    },
    "win8-phone-appbar": {
        defaults: {
            location: "center"
        },
        commands: ["create", "edit", "cancel", "save", "refresh", {
            id: "delete",
            locateInMenu: "always"
        }]
    },
    "win8-split-toolbar": {
        defaults: {
            showIcon: true,
            showText: false,
            location: "after"
        },
        commands: [{
            id: "back",
            showIcon: false,
            location: "before"
        }, {
            id: "create"
        }, {
            id: "save",
            showText: true,
            location: "before"
        }, {
            id: "edit",
            showText: true,
            locateInMenu: "always"
        }, {
            id: "cancel",
            showText: true,
            locateInMenu: "always"
        }, {
            id: "delete",
            showText: true,
            locateInMenu: "always"
        }]
    },
    "win8-master-detail-toolbar": {
        defaults: {
            showText: false,
            location: "before"
        },
        commands: ["back"]
    },
    "win10-appbar": {
        defaults: {
            showText: false,
            location: "after"
        },
        commands: [{
            id: "back",
            location: "before"
        }, "edit", "cancel", "save", "delete", "create", "refresh"]
    },
    "win10-phone-appbar": {
        defaults: {
            location: "after"
        },
        commands: ["create", "edit", "cancel", "save", "refresh", {
            id: "delete",
            locateInMenu: "always"
        }]
    },
    "desktop-toolbar": {
        defaults: {
            showIcon: false,
            showText: true,
            location: "after"
        },
        commands: ["cancel", "create", "edit", "save", {
            id: "delete",
            type: "danger"
        }]
    }
};
module.exports = CommandMapping;


text:
from collections import defaultdict

from django.conf import settings
from django.db.models import Q
from django.shortcuts import redirect
from django.utils.encoding import smart_str

import commonware.log
import jingo
from tower import ugettext as _
from mobility.decorators import mobile_template

import amo
import bandwagon.views
import browse.views
from addons.models import Addon, Category
from amo.decorators import json_view
from amo.helpers import locale_url, urlparams
from amo.urlresolvers import reverse
from amo.utils import MenuItem, sorted_groupby
from versions.compare import dict_from_int, version_int
from webapps.models import Webapp

from . import forms
from .client import (Client as SearchClient, SearchError,
                           CollectionsClient, PersonasClient, sphinx)
from .forms import SearchForm, SecondarySearchForm, ESSearchForm

DEFAULT_NUM_RESULTS = 20

log = commonware.log.getLogger('z.search')

def _get_versions(request, versions, version):
    compats = []
    url = request.get_full_path()

    c = MenuItem()
    (c.text, c.url) = (_('All Versions'), urlparams(url, lver=None, page=None))

    if not version or version == 'any':
        c.selected = True

    compats.append(c)
    seen = {}
    exclude = request.APP.__dict__.get('exclude_versions', [])
    versions.sort(reverse=True)

    for v in versions:
        # v is a version_int so we can get the major and minor:
        v = dict_from_int(v)
        if v['minor1'] == 99:
            text = '%s.*' % v['major']
            v_float = float('%s.99' % v['major'])
        else:
            text = '%s.%s' % (v['major'], v['minor1'])
            v_float = float(text)

        if seen.get(text):
            continue

        seen[text] = 1

        if v_float < request.APP.min_display_version or v_float in exclude:
            continue

        c = MenuItem()
        c.text = text
        c.url = urlparams(url, lver=c.text, page=None)

        if c.text == version:
            c.selected = True
        compats.append(c)

    return compats

def _get_categories(request, categories, addon_type=None, category=None):
    items = []
    url = request.get_full_path()

    i = MenuItem()
    (i.text, i.url) = (_('All'), urlparams(url, atype=None, cat=None,
                                           page=None))

    if not addon_type and not category:
        i.selected = True

    items.append(i)

    # Bucket the categories as addon_types so we can display them in a
    # hierarchy.
    bucket = defaultdict(list)

    for cat in categories:
        item = MenuItem()
        (item.text, item.url) = (cat.name, urlparams(url, atype=None,
                page=None, cat="%d,%d" % (cat.type, cat.id)))

        if category == cat.id:
            item.selected = True

        bucket[cat.type].append(item)

    for key in sorted(bucket):
        children = bucket[key]
        item = MenuItem()
        item.children = children
        (item.text, item.url) = (amo.ADDON_TYPES[key],
                                 urlparams(url, atype=key, cat=None,
                                           page=None))
        if not category and addon_type == key:
            item.selected = True

        items.append(item)

    return items

def _get_platforms(request, platforms, selected=None):
    items = []
    url = request.get_full_path()

    if amo.PLATFORM_ALL.id in platforms:
        platforms = amo.PLATFORMS.keys()

    for platform in platforms:
        if platform == amo.PLATFORM_ALL.id:
            continue
        item = MenuItem()
        p = amo.PLATFORMS[platform]
        (item.text, item.url) = (p.name,
                                 urlparams(url, pid=(p.id or None), page=None))
        if p.id == selected:
            item.selected = True
        items.append(item)

    return items

def _get_tags(request, tags, selected):
    items = []
    url = request.get_full_path()

    for tag in tags:
        item = MenuItem()
        (item.text, item.url) = (tag.tag_text.lower(),
                 urlparams(url, tag=tag.tag_text.encode('utf8').lower(),
                           page=None))

        if tag.tag_text.lower() == selected:
            item.selected = True

        items.append(item)

    return items

def _get_sort_menu(request, sort):
    items = []
    sorts = forms.sort_by

    item = (None, _('Keyword Match'))
    items.append(item)

    for key, val in sorts:
        if key == '':
            continue
        item = (key, val)
        items.append(item)

    return items

def _get_sorts(request, sort):
    items = []
    url = request.get_full_path()

    sorts = forms.sort_by

    item = MenuItem()
    (item.text, item.url) = (_('Keyword Match'), urlparams(url, sort=None))

    if not sort:
        item.selected = True

    items.append(item)

    for key, val in sorts:
        if key == '':
            continue

        item = MenuItem()
        (item.text, item.url) = (val, urlparams(url, sort=key, page=None))

        if sort == key:
            item.selected = True

        items.append(item)

    return items

def _personas(request):
    """Handle the request for persona searches."""
    form = SecondarySearchForm(request.GET)
    if not form.is_valid():
        log.error(form.errors)

    query = form.data.get('q', '')

    search_opts = {}
    search_opts['limit'] = form.cleaned_data.get('pp', DEFAULT_NUM_RESULTS)
    page = form.cleaned_data.get('page') or 1
    search_opts['offset'] = (page - 1) * search_opts['limit']

    try:
        results = PersonasClient().query(query, **search_opts)
    except SearchError:
        return jingo.render(request, 'search/down.html', {}, status=503)

    pager = amo.utils.paginate(request, results, search_opts['limit'])
    categories, filter, _, _ = browse.views.personas_listing(request)
    c = dict(pager=pager, form=form, categories=categories, query=query,
             filter=filter)
    return jingo.render(request, 'search/personas.html', c)

def _collections(request):
    """Handle the request for collections."""
    form = SecondarySearchForm(request.GET)
    form.is_valid()

    query = form.cleaned_data.get('q', '')

    search_opts = {}
    search_opts['limit'] = form.cleaned_data.get('pp', DEFAULT_NUM_RESULTS)
    page = form.cleaned_data.get('page') or 1
    search_opts['offset'] = (page - 1) * search_opts['limit']
    search_opts['sort'] = form.cleaned_data.get('sortby')

    try:
        results = CollectionsClient().query(query, **search_opts)
    except SearchError:
        return jingo.render(request, 'search/down.html', {}, status=503)

    pager = amo.utils.paginate(request, results, search_opts['limit'])
    c = dict(pager=pager, form=form, query=query, opts=search_opts,
             filter=bandwagon.views.get_filter(request))
    return jingo.render(request, 'search/collections.html', c)

class BaseAjaxSearch(object):
    """Generates a list of dictionaries of add-on objects based on
    ID or name matches. Safe to be served to a JSON-friendly view.

    Sample output:
    [
        {
            "id": 1865,
            "label": "Adblock Plus",
            "url": "http://path/to/details/page",
            "icon": "http://path/to/icon",
        },
        ...
    ]

    """

    def __init__(self, request, excluded_ids=[]):
        self.request = request
        self.excluded_ids = excluded_ids
        self.types = getattr(self, 'types', amo.ADDON_SEARCH_TYPES)
        self.limit = 10
        self.key = 'q'  # Name of search field.

        # Mapping of JSON key => add-on property.
        default_fields = {
            'id': 'id',
            'name': 'name',
            'url': 'get_url_path',
            'icon': 'icon_url'
        }
        self.fields = getattr(self, 'fields', default_fields)
        self.items = self.build_list()

    def queryset(self):
        """Get items based on ID or search by name."""
        results = []
        if self.key in self.request.GET:
            q = self.request.GET[self.key]
            if q.isdigit() or (not q.isdigit() and len(q) > 2):
                if q.isdigit():
                    qs = Addon.objects.filter(id=int(q),
                                              disabled_by_user=False)
                else:
                    # Oh, how I wish I could elastically exclude terms.
                    qs = (Addon.search().query(or_=name_only_query(q))
                          .filter(is_disabled=False))
                results = qs.filter(type__in=self.types,
                                    status__in=amo.REVIEWED_STATUSES)
        return results

    def build_list(self):
        """Populate a list of dictionaries based on label => property."""
        results = []
        for item in self.queryset()[:self.limit]:
            if item.id in self.excluded_ids:
                continue
            d = {}
            for key, prop in self.fields.iteritems():
                val = getattr(item, prop, '')
                if callable(val):
                    val = val()
                d[key] = unicode(val)
            results.append(d)
        return results

class SuggestionsAjax(BaseAjaxSearch):
    # No personas. No webapps.
    types = [amo.ADDON_ANY, amo.ADDON_EXTENSION, amo.ADDON_THEME,
             amo.ADDON_DICT, amo.ADDON_SEARCH, amo.ADDON_LPAPP]

@json_view
def ajax_search(request):
    """This is currently used only to return add-ons for populating a
    new collection. Personas are included by default, so this can be
    used elsewhere.

    """
    return BaseAjaxSearch(request).items

@json_view
def ajax_search_suggestions(request):
    # TODO(cvan): Tests will come when I know this is what fligtar wants.
    results = []
    q = request.GET.get('q')
    if q and (q.isdigit() or (not q.isdigit() and len(q) > 2)):
        q_ = q.lower()

        # Applications.
        for a in amo.APP_USAGE:
            if q_ in unicode(a.pretty).lower():
                results.append({
                    'id': a.id,
                    'name': _(u'{0} Add-ons').format(a.pretty),
                    'url': locale_url(a.short),
                    'cls': 'app ' + a.short
                })

        # Categories.
        cats = (Category.objects
                .filter(Q(application=request.APP.id) |
                        Q(type=amo.ADDON_SEARCH))
                .exclude(type=amo.ADDON_WEBAPP))
        for c in cats:
            if not c.name:
                continue
            name_ = unicode(c.name).lower()
            word_matches = [w for w in q_.split() if name_ in w]
            if q_ in name_ or word_matches:
                results.append({
                    'id': c.id,
                    'name': unicode(c.name),
                    'url': c.get_url_path(),
                    'cls': 'cat'
                })

        # Add-ons.
        results += SuggestionsAjax(request).items

    return results

def name_only_query(q):
    return dict(name__text={'query': q, 'boost': 3, 'analyzer': 'standard'},
                name__fuzzy={'value': q, 'boost': 2, 'prefix_length': 4},
                name__startswith={'value': q, 'boost': 1.5})

def name_query(q):
    # 1. Prefer text matches first, using the standard text analyzer (boost=3).
    # 2. Then try fuzzy matches ("fire bug" => firebug) (boost=2).
    # 3. Then look for the query as a prefix of a name (boost=1.5).
    # 4. Look for phrase matches inside the summary (boost=0.8).
    # 5. Look for phrase matches inside the description (boost=0.3).
    more = dict(summary__text={'query': q, 'boost': 0.8, 'type': 'phrase'},
                description__text={'query': q, 'boost': 0.3, 'type': 'phrase'})
    return dict(more, **name_only_query(q))

@mobile_template('search/{mobile/}results.html')
def app_search(request, template=None):
    form = ESSearchForm(request.GET or {}, type=amo.ADDON_WEBAPP)
    form.is_valid()  # Let the form try to clean data.
    query = form.cleaned_data
    qs = (Webapp.search().query(or_=name_query(query['q']))
          .filter(type=amo.ADDON_WEBAPP, status=amo.STATUS_PUBLIC,
                  is_disabled=False)
          .facet(tags={'terms': {'field': 'tag'}},
                 categories={'terms': {'field': 'category', 'size': 100}}))
    if query.get('tag'):
        qs = qs.filter(tag=query['tag'])
    if query.get('cat'):
        qs = qs.filter(category=query['cat'])
    if query.get('sort'):
        mapping = {'downloads': '-weekly_downloads',
                   'rating': '-bayesian_rating',
                   'created': '-created',
                   'name': '-name_sort',
                   'hotness': '-hotness'}
        qs = qs.order_by(mapping[query['sort']])

    pager = amo.utils.paginate(request, qs)
    facets = pager.object_list.facets

    ctx = {
        'is_pjax': request.META.get('HTTP_X_PJAX'),
        'pager': pager,
        'query': query,
        'form': form,
        'sorting': sort_sidebar(request, query, form),
        'sort_opts': form.fields['sort'].choices,
    }
    if not ctx['is_pjax']:
        ctx.update({
            'categories': category_sidebar(request, query, facets),
            'tags': tag_sidebar(request, query, facets),
        })
    return jingo.render(request, template, ctx)

@mobile_template('search/{mobile/}results.html')
def search(request, tag_name=None, template=None):
    APP = request.APP
    types = (amo.ADDON_EXTENSION, amo.ADDON_THEME, amo.ADDON_DICT,
             amo.ADDON_SEARCH, amo.ADDON_LPAPP)

    fixed = fix_search_query(request.GET)
    if fixed is not request.GET:
        return redirect(urlparams(request.path, **fixed), permanent=True)

    form = ESSearchForm(request.GET or {})
    form.is_valid()  # Let the form try to clean data.

    category = request.GET.get('cat')
    query = form.cleaned_data

    if category == 'collections':
        return _collections(request)
    elif category == 'personas' or query.get('atype') == amo.ADDON_PERSONA:
        return _personas(request)

    sort, extra_sort = split_choices(form.fields['sort'].choices, 'created')

    qs = (Addon.search()
          .filter(status__in=amo.REVIEWED_STATUSES, is_disabled=False,
                  app=APP.id)
          .facet(tags={'terms': {'field': 'tag'}},
                 platforms={'terms': {'field': 'platform'}},
                 appversions={'terms':
                              {'field': 'appversion.%s.max' % APP.id}},
                 categories={'terms': {'field': 'category', 'size': 100}}))
    if query.get('q'):
        qs = qs.query(or_=name_query(query['q']))
    if tag_name or query.get('tag'):
        qs = qs.filter(tag=tag_name or query['tag'])
    if query.get('platform') and query['platform'] in amo.PLATFORM_DICT:
        ps = (amo.PLATFORM_DICT[query['platform']].id, amo.PLATFORM_ALL.id)
        qs = qs.filter(platform__in=ps)
    if query.get('appver'):
        # Get a min version less than X.0.
        low = version_int(query['appver'])
        # Get a max version greater than X.0a.
        high = version_int(query['appver'] + 'a')
        qs = qs.filter(**{'appversion.%s.max__gte' % APP.id: high,
                          'appversion.%s.min__lte' % APP.id: low})
    if query.get('atype') and query['atype'] in amo.ADDON_TYPES:
        qs = qs.filter(type=query['atype'])
        if query['atype'] == amo.ADDON_SEARCH:
            # Search add-ons should not be searched by ADU, so replace 'Users'
            # sort with 'Weekly Downloads'.
            sort[1] = extra_sort[1]
            del extra_sort[1]
    else:
        qs = qs.filter(type__in=types)
    if query.get('cat'):
        qs = qs.filter(category=query['cat'])
    if query.get('sort'):
        mapping = {'users': '-average_daily_users',
                   'rating': '-bayesian_rating',
                   'created': '-created',
                   'name': 'name_sort',
                   'downloads': '-weekly_downloads',
                   'updated': '-last_updated',
                   'hotness': '-hotness'}
        qs = qs.order_by(mapping[query['sort']])
    elif not query.get('q'):
        # Sort by weekly downloads if there was no query so we get predictable
        # results.
        qs = qs.order_by('-weekly_downloads')

    pager = amo.utils.paginate(request, qs)

    ctx = {
        'is_pjax': request.META.get('HTTP_X_PJAX'),
        'pager': pager,
        'query': query,
        'form': form,
        'sort_opts': sort,
        'extra_sort_opts': extra_sort,
        'sorting': sort_sidebar(request, query, form),
    }
    if not ctx['is_pjax']:
        facets = pager.object_list.facets
        ctx.update({
            'categories': category_sidebar(request, query, facets),
            'platforms': platform_sidebar(request, query, facets),
            'versions': version_sidebar(request, query, facets),
            'tags': tag_sidebar(request, query, facets),
        })
    return jingo.render(request, template, ctx)

class FacetLink(object):

    def __init__(self, text, urlparams, selected=False, children=None):
        self.text = text
        self.urlparams = urlparams
        self.selected = selected
        self.children = children or []

def sort_sidebar(request, query, form):
    sort = query.get('sort')
    return [FacetLink(text, dict(sort=key), key == sort)
            for key, text in form.fields['sort'].choices]

def category_sidebar(request, query, facets):
    APP = request.APP
    qatype, qcat = query.get('atype'), query.get('cat')
    cats = [f['term'] for f in facets['categories']]
    categories = (Category.objects.filter(id__in=cats)
                  # Search categories don't have an application.
                  .filter(Q(application=APP.id) | Q(type=amo.ADDON_SEARCH)))
    if qatype in amo.ADDON_TYPES:
        categories = categories.filter(type=qatype)
    categories = [(atype, sorted(cats, key=lambda x: x.name))
                  for atype, cats in sorted_groupby(categories, 'type')]
    rv = [FacetLink(_(u'All Add-ons'), dict(atype=None, cat=None), not qatype)]
    for addon_type, cats in categories:
        link = FacetLink(amo.ADDON_TYPES[addon_type],
                         dict(atype=addon_type, cat=None),
                         addon_type == qatype and not qcat)
        link.children = [FacetLink(c.name, dict(atype=addon_type, cat=c.id),
                                   c.id == qcat) for c in cats]
        rv.append(link)
    return rv

def version_sidebar(request, query, facets):
    appver = query.get('appver')
    app = unicode(request.APP.pretty)
    exclude_versions = getattr(request.APP, 'exclude_versions', [])
    # L10n: {0} is an application, such as Firefox. This means "any version of
    # Firefox."
    rv = [FacetLink(_(u'Any {0}').format(app), dict(appver=None), not appver)]
    vs = [dict_from_int(f['term']) for f in facets['appversions']]
    vs = set((v['major'], v['minor1'] if v['minor1'] != 99 else 0)
             for v in vs)
    versions = ['%s.%s' % v for v in sorted(vs, reverse=True)]
    for version, floated in zip(versions, map(float, versions)):
        if (floated not in exclude_versions
            and floated > request.APP.min_display_version):
            rv.append(FacetLink('%s %s' % (app, version), dict(appver=version),
                                appver == version))
    return rv

def platform_sidebar(request, query, facets):
    qplatform = query.get('platform')
    app_platforms = request.APP.platforms.values()
    ALL = app_platforms[0]
    platforms = [facet['term'] for facet in facets['platforms']
                 if facet['term'] != ALL.id]
    all_selected = not qplatform or qplatform == ALL.shortname
    rv = [FacetLink(_(u'All Systems'), dict(platform=ALL.shortname),
                    all_selected)]
    for platform in app_platforms[1:]:
        if platform.id in platforms:
            rv.append(FacetLink(platform.name,
                                dict(platform=platform.shortname),
                                platform.shortname == qplatform))
    return rv

def tag_sidebar(request, query, facets):
    qtag = query.get('tag')
    rv = [FacetLink(_(u'All Tags'), dict(tag=None), not qtag)]
    tags = [facet['term'] for facet in facets['tags']]
    rv += [FacetLink(tag, dict(tag=tag), tag == qtag) for tag in tags]
    return rv

def fix_search_query(query):
    rv = dict((smart_str(k), v) for k, v in query.items())
    changed = False
    # Change old keys to new names.
    keys = {
        'lver': 'appver',
        'pid': 'platform',
    }
    for old, new in keys.items():
        if old in query:
            rv[new] = rv.pop(old)
            changed = True

    # Change old parameter values to new values.
    params = {
        'sort': {
            'newest': 'updated',
            'weeklydownloads': 'users',
            'averagerating': 'rating',
        },
        'platform': dict((str(p.id), p.shortname)
                         for p in amo.PLATFORMS.values())
    }
    for key, fixes in params.items():
        if key in rv and rv[key] in fixes:
            rv[key] = fixes[rv[key]]
            changed = True
    return rv if changed else query

def split_choices(choices, split):
    """Split a list of [(key, title)] pairs after key == split."""
    index = [idx for idx, (key, title) in enumerate(choices)
             if key == split]
    if index:
        index = index[0] + 1
        return choices[:index], choices[index:]
    else:
        return choices, []


text:
package commands

import (
	"bytes"
	"os"
	"path/filepath"
	"strings"

	"github.com/gohugoio/hugo/create"
	"github.com/gohugoio/hugo/helpers"
	"github.com/gohugoio/hugo/hugolib"
	"github.com/spf13/afero"
	"github.com/spf13/cobra"
	jww "github.com/spf13/jwalterweatherman"
)

var _ cmder = (*newCmd)(nil)

type newCmd struct {
	contentEditor string
	contentType   string

	*baseBuilderCmd
}

func (b *commandsBuilder) newNewCmd() *newCmd {
	cmd := &cobra.Command{
		Use:   "new [path]",
		Short: "Create new content for your site",
		Long: `Create a new content file and automatically set the date and title.
It will guess which kind of file to create based on the path provided.

You can also specify the kind with ` + "`-k KIND`" + `.

If archetypes are provided in your theme or site, they will be used.

Ensure you run this within the root directory of your site.`,
	}

	cc := &newCmd{baseBuilderCmd: b.newBuilderCmd(cmd)}

	cmd.Flags().StringVarP(&cc.contentType, "kind", "k", "", "content type to create")
	cmd.PersistentFlags().StringVarP(&cc.source, "source", "s", "", "filesystem path to read files relative from")
	cmd.PersistentFlags().SetAnnotation("source", cobra.BashCompSubdirsInDir, []string{})
	cmd.Flags().StringVar(&cc.contentEditor, "editor", "", "edit new content with this editor, if provided")

	cmd.AddCommand(newNewSiteCmd().getCommand())
	cmd.AddCommand(newNewThemeCmd().getCommand())

	cmd.RunE = cc.newContent

	return cc
}

func (n *newCmd) newContent(cmd *cobra.Command, args []string) error {
	cfgInit := func(c *commandeer) error {
		if cmd.Flags().Changed("editor") {
			c.Set("newContentEditor", n.contentEditor)
		}
		return nil
	}

	c, err := initializeConfig(true, false, &n.hugoBuilderCommon, n, cfgInit)

	if err != nil {
		return err
	}

	if len(args) < 1 {
		return newUserError("path needs to be provided")
	}

	createPath := args[0]

	var kind string

	createPath, kind = newContentPathSection(c.hugo, createPath)

	if n.contentType != "" {
		kind = n.contentType
	}

	return create.NewContent(c.hugo, kind, createPath)
}

func mkdir(x ...string) {
	p := filepath.Join(x...)

	err := os.MkdirAll(p, 0777) // before umask
	if err != nil {
		jww.FATAL.Fatalln(err)
	}
}

func touchFile(fs afero.Fs, x ...string) {
	inpath := filepath.Join(x...)
	mkdir(filepath.Dir(inpath))
	err := helpers.WriteToDisk(inpath, bytes.NewReader([]byte{}), fs)
	if err != nil {
		jww.FATAL.Fatalln(err)
	}
}

func newContentPathSection(h *hugolib.HugoSites, path string) (string, string) {
	// Forward slashes is used in all examples. Convert if needed.
	// Issue #1133
	createpath := filepath.FromSlash(path)

	if h != nil {
		for _, s := range h.Sites {
			createpath = strings.TrimPrefix(createpath, s.PathSpec.ContentDir)
		}
	}

	var section string
	// assume the first directory is the section (kind)
	if strings.Contains(createpath[1:], helpers.FilePathSeparator) {
		parts := strings.Split(strings.TrimPrefix(createpath, helpers.FilePathSeparator), helpers.FilePathSeparator)
		if len(parts) > 0 {
			section = parts[0]
		}

	}

	return createpath, section
}


text:
MODELS FOLDER
===================

All models created here are accessible via ```Models('ModelName')```. It will return a Mongoose Model.

Models directory do not officially support sub folders as of now.

e.g.

/web/models/Book.js ==> ```models('Book')```

###schema [required]

Return the attributes of the schema. See Mongoose' Schema for the syntax.

###options [optional]

Mongoose schema options

e.g.

```
module.exports = {
  ...

  options: {
    strict: false
  }
}
```

###initSchema [optional]

You can initialize a Schema by adding an initSchema in your model. The Schema is a Mongoose Schema.

e.g.

```
module.exports = {
  ...

  initSchema: function(schema) {
  	//do something in schema like apply a compound index
  	schema.index({ author: 1, title: 1 });
  }
}
```

###connection [optional]

You can specify the connection (defined in conf.js). The default will be 'mainDb' or the first connection defined in conf.js.

```
module.exports = {
  ...

  connection: 'mainDb'
}
```


text:
/* Read-only tables for Lua */

#include "c_string.h"
#include "lrotable.h"
#include "lua.h"
#include "lauxlib.h"
#include "lstring.h"
#include "lobject.h"
#include "lapi.h"

/* Local defines */
#define LUAR_FINDFUNCTION     0
#define LUAR_FINDVALUE        1

/* Externally defined read-only table array */
extern const luaR_table lua_rotable[];

/* Find a global "read only table" in the constant lua_rotable array */
void* luaR_findglobal(const char *name, unsigned len) {
  unsigned i;

  if (c_strlen(name) > LUA_MAX_ROTABLE_NAME)
    return NULL;
  for (i=0; lua_rotable[i].name; i ++)
    if (*lua_rotable[i].name != '\0' && c_strlen(lua_rotable[i].name) == len && !c_strncmp(lua_rotable[i].name, name, len)) {
      return (void*)(lua_rotable[i].pentries);
    }
  return NULL;
}

/* Find an entry in a rotable and return it */
static const TValue* luaR_auxfind(const luaR_entry *pentry, const char *strkey, luaR_numkey numkey, unsigned *ppos) {
  const TValue *res = NULL;
  unsigned i = 0;

  if (pentry == NULL)
    return NULL;
  while(pentry->key.type != LUA_TNIL) {
    if ((strkey && (pentry->key.type == LUA_TSTRING) && (!c_strcmp(pentry->key.id.strkey, strkey))) ||
        (!strkey && (pentry->key.type == LUA_TNUMBER) && ((luaR_numkey)pentry->key.id.numkey == numkey))) {
      res = &pentry->value;
      break;
    }
    i ++; pentry ++;
  }
  if (res && ppos)
    *ppos = i;
  return res;
}

int luaR_findfunction(lua_State *L, const luaR_entry *ptable) {
  const TValue *res = NULL;
  const char *key = luaL_checkstring(L, 2);

  res = luaR_auxfind(ptable, key, 0, NULL);
  if (res && ttislightfunction(res)) {
    luaA_pushobject(L, res);
    return 1;
  }
  else
    return 0;
}

/* Find an entry in a rotable and return its type
   If "strkey" is not NULL, the function will look for a string key,
   otherwise it will look for a number key */
const TValue* luaR_findentry(void *data, const char *strkey, luaR_numkey numkey, unsigned *ppos) {
  return luaR_auxfind((const luaR_entry*)data, strkey, numkey, ppos);
}

/* Find the metatable of a given table */
void* luaR_getmeta(void *data) {
#ifdef LUA_META_ROTABLES
  const TValue *res = luaR_auxfind((const luaR_entry*)data, "__metatable", 0, NULL);
  return res && ttisrotable(res) ? rvalue(res) : NULL;
#else
  return NULL;
#endif
}

static void luaR_next_helper(lua_State *L, const luaR_entry *pentries, int pos, TValue *key, TValue *val) {
  setnilvalue(key);
  setnilvalue(val);
  if (pentries[pos].key.type != LUA_TNIL) {
    /* Found an entry */
    if (pentries[pos].key.type == LUA_TSTRING)
      setsvalue(L, key, luaS_newro(L, pentries[pos].key.id.strkey))
    else
      setnvalue(key, (lua_Number)pentries[pos].key.id.numkey)
   setobj2s(L, val, &pentries[pos].value);
  }
}
/* next (used for iteration) */
void luaR_next(lua_State *L, void *data, TValue *key, TValue *val) {
  const luaR_entry* pentries = (const luaR_entry*)data;
  char strkey[LUA_MAX_ROTABLE_NAME + 1], *pstrkey = NULL;
  luaR_numkey numkey = 0;
  unsigned keypos;

  /* Special case: if key is nil, return the first element of the rotable */
  if (ttisnil(key))
    luaR_next_helper(L, pentries, 0, key, val);
  else if (ttisstring(key) || ttisnumber(key)) {
    /* Find the previoud key again */
    if (ttisstring(key)) {
      luaR_getcstr(strkey, rawtsvalue(key), LUA_MAX_ROTABLE_NAME);
      pstrkey = strkey;
    } else
      numkey = (luaR_numkey)nvalue(key);
    luaR_findentry(data, pstrkey, numkey, &keypos);
    /* Advance to next key */
    keypos ++;
    luaR_next_helper(L, pentries, keypos, key, val);
  }
}

/* Convert a Lua string to a C string */
void luaR_getcstr(char *dest, const TString *src, size_t maxsize) {
  if (src->tsv.len+1 > maxsize)
    dest[0] = '\0';
  else {
    c_memcpy(dest, getstr(src), src->tsv.len);
    dest[src->tsv.len] = '\0';
  }
}

/* Return 1 if the given pointer is a rotable */
#ifdef LUA_META_ROTABLES

#include "compiler.h"

int luaR_isrotable(void *p) {
  return RODATA_START_ADDRESS <= (char*)p && (char*)p <= RODATA_END_ADDRESS;
}
#endif