text:
/**
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
  *  You may obtain a copy of the License at
  *
  *  http://www.apache.org/licenses/LICENSE-2.0
  *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */
package com.fireflysemantics.math.precision;

import java.math.BigDecimal;

/**
 * Supports comparison and rounding of double values.
 */
public class RoundDouble {

	/** Positive zero. */
	private static final double POSITIVE_ZERO = 0d;

	/**
	 * Private constructor.
	 */
	private RoundDouble() {
	}

	/**
	 * Rounds the given value to the specified number of decimal places. The
	 * value is rounded using the {@link BigDecimal#ROUND_HALF_UP} method.
	 *
	 * @param x
	 *            Value to round.
	 * @param scale
	 *            Number of digits to the right of the decimal point.
	 * @return the rounded value as a double.
	 */
	public static double round(double x, int scale) {
		return round(x, scale, BigDecimal.ROUND_HALF_UP);
	}

	/**
	 * Rounds the given value to the specified number of decimal places. The
	 * value is rounded using the given method which is any method defined in
	 * {@link BigDecimal}. If {@code x} is infinite or {@code NaN}, then the
	 * value of {@code x} is returned unchanged, regardless of the other
	 * parameters.
	 *
	 * @param x
	 *            Value to round.
	 * @param scale
	 *            Number of digits to the right of the decimal point.
	 * @param roundingMethod
	 *            Rounding method as defined in {@link BigDecimal}.
	 * @return the rounded value.
	 * @throws ArithmeticException
	 *             if {@code roundingMethod == ROUND_UNNECESSARY} and the
	 *             specified scaling operation would require rounding.
	 * @throws IllegalArgumentException
	 *             if {@code roundingMethod} does not represent a valid rounding
	 *             mode.
	 */
	public static double round(double x, int scale, int roundingMethod) {
		try {
			final double rounded =
					(new BigDecimal(Double.toString(x)).setScale(scale, roundingMethod)).doubleValue();
			// Commons Math JIRA MATH-1089: negative values rounded to zero
			// https://issues.apache.org/jira/browse/MATH-1089
			// should result in negative zero
			return rounded == POSITIVE_ZERO ? POSITIVE_ZERO
					* x : rounded;
		} catch (NumberFormatException ex) {
			if (Double.isInfinite(x)) {
				return x;
			} else {
				return Double.NaN;
			}
		}
	}
}


text:
{% if widget.display_corporate_navigation.value == "true" %}
  {% if widget.display_navigation.value == "true" %}

  {% else %}

  {% endif %}

      {% for web_page in widget.corporate_navigation %}
        {% if web_page[1].display != "false" and web_page[1].child_template? == false %}

          {{ web_page[1].name }}
          {% if web_page[1].child_templates != blank %}

              {% for child_page in web_page[1].child_templates %}
                {% if forloop.first %}

{{ web_page[1].name }}

                {% endif %}

{{ child_page[1].name }}

              {% endfor %}

          {% endif %}

        {% endif %}
      {% endfor %}

{% endif %}

{% if widget.display_navigation.value == "true" %}
  {% if widget.display_as_calls_to_action.value == "true" %}

  {% else %}

  {% endif %}

      {% for web_page in widget.navigation.value %}
        {% if web_page[1].display != "false" and web_page[1].child_template? == false %}

          {{ web_page[1].name }}
          {% if web_page[1].child_templates != blank %}

              {% for child_page in web_page[1].child_templates %}
                {% if forloop.first %}

{{ web_page[1].name }}

                {% endif %}
                {% if child_page[1].display != "false" %}

{{ child_page[1].name }}

                {% endif %}
              {% endfor %}

          {% endif %}

        {% endif %}
      {% endfor %}
      {% if widget.display_as_calls_to_action.value != "true" and widget.display_corporate_navigation.value == "true" %}

          Corporate Home

      {% endif %}

{% endif %}

redpajama_set_name: RedPajamaGithub


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

/*=====================================================================

**

** Source:  test2.c

**

** Purpose:   Test the return value of GetLastError() after calling

**            some file_io functions with an invalid path.

**

**            Functions covered by this test are:

**            MoveFileW, FindFirstFileA, FindFirstFileW,

**            GetFileAttributesA, GetFileAttributesW,

**            SetFileAttributesA, SetFileAttributesW.

**
**

**

**

**===================================================================*/

#include <palsuite.h>

int __cdecl main(int argc, char *argv[])

{

    BOOL              testPass       = TRUE;

    BOOL              bRc            = TRUE;

    HANDLE            hFile;

    WIN32_FIND_DATA   findFileData;

    WIN32_FIND_DATAW  wFindFileData;

    DWORD              fileAttrib;

    const char* sBadFilePath = "bad/badPath.tmp";

    const char* sBadFileName = "badName.tmp";

    const WCHAR wBadFilePath[] =

    {'w','b','a','d','/','b','a',

    'd','.','t','m','p','\0'};

    const WCHAR wBadFileName[] =

    {'w','B','a','d','.','t','m','p','\0'};

    const WCHAR wDest[] =

    {'w','d','e','s','t','.','t','m','p','\0'};

    if (0 != PAL_Initialize(argc,argv))

    {

        return FAIL;

    }

    /*...................Test MoveFileW.............................*/

    /* test with an invalid path */

    bRc = MoveFileW(wBadFilePath,wDest);

    if(!bRc)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("MoveFileW: calling GetLastError() after moving a file"

                " with wrong path returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        testPass = FALSE;

    }

    /* test with invalid file name */

    bRc = MoveFileW(wBadFileName,wDest);

    if(!bRc)

    {

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("MoveFileW: calling GetLastError() after moving a file"

                " with wrong name returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("MoveFileW: managed to move a file with wrong name\n");

        testPass = FALSE;

    }

    /*............. Test FindFirstFileA..................................*/

    /* test with an invalid file name */

    hFile = FindFirstFileA(sBadFileName,&findFileData );

    if (hFile == INVALID_HANDLE_VALUE)

    {

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("FindFirstFileA: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad File Name\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("FindFirstFileA: managed to find a file with an incorrect "

            "filename\n");

        testPass = FALSE;

        if(!FindClose(hFile))

        {

            Trace("FindFirstFileA: Call to FindClose failed with ErrorCode"

                " [%u]\n", GetLastError());

        }

    }

    /* test with an invalid path */

    hFile = FindFirstFileA(sBadFilePath,&findFileData);

    if (hFile == INVALID_HANDLE_VALUE)

    {

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("FindFirstFileA: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad file path name\n",

                GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("FindFirstFileA: managed to find a file with an incorrect"

            " filename\n");

        testPass = FALSE;

        /*this should not happen*/

        if(!FindClose(hFile))

        {

            Trace("FindFirstFileA: Call to FindClose Failed with ErrorCode"

                " [%u]\n", GetLastError());

        }

    }

    /*............. Test FindFirstFileW..................................*/

    /* test with an invalid file name */

    hFile = FindFirstFileW(wBadFileName,&wFindFileData );

    if (hFile == INVALID_HANDLE_VALUE)

    {

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("FindFirstFileW: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad File Name\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("FindFirstFileW: managed to find a file with an incorrect "

            "filename\n");

        testPass = FALSE;

        if(!FindClose(hFile))

        {

            Trace("FindFirstFileW: Call to FindClose failed with ErrorCode"

                " [%u]\n", GetLastError());

        }

    }

    /* test with an invalid path */

    hFile = FindFirstFileW(wBadFilePath,&wFindFileData);

    if (hFile == INVALID_HANDLE_VALUE)

    {

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("FindFirstFileW: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad file path name\n",

                GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("FindFirstFileW: managed to find a file with an incorrect "

            "filename\n");

        testPass = FALSE;

        /*this should not happen*/

        if(!FindClose(hFile))

        {

            Trace("FindFirstFileW: Call to FindClose Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }

    /*...................Test GetFileAttributesW.............................*/

    /* test with an invalid path */

    fileAttrib = GetFileAttributesW(wBadFilePath);

    if(fileAttrib == -1)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("GetFileAttributesW: calling GetLastError() after getting"

                " the attributes of a file with wrong path returned [%u]"

                " while it should return [%u]\n",

                GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("GetFileAttributesW: managed to get the attrib of a file"

            " with wrong path\n");

        testPass = FALSE;

    }

    /* test with invalid file name */

    fileAttrib = GetFileAttributesW(wBadFileName);

    if(fileAttrib == -1)

    {

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("GetFileAttributesW: calling GetLastError() after getting"

                " the attributes of a file with wrong name returned [%u] "

                "while it should return [%u]\n"

                ,GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("GetFileAttributesW: managed to get the attrib of a file"

            " with wrong name\n");

        testPass = FALSE;

    }

    /*...................Test GetFileAttributesA.............................*/

    /* test with an invalid path */

    fileAttrib = GetFileAttributesA(sBadFilePath);

    if(fileAttrib == -1)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("GetFileAttributesA: calling GetLastError() after getting"

                " the attributes of a file with wrong path returned [%u] while"

                " it should return [%u]\n",

                GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("GetFileAttributesA: managed to get the attrib of a file"

            " with wrong path\n");

        testPass = FALSE;

    }

    /* test with invalid file name */

    fileAttrib = GetFileAttributesA(sBadFileName);

    if(fileAttrib == -1)

    {

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("GetFileAttributesA: calling GetLastError() after getting "

                "the attributes of a file with wrong name returned [%u] "

                "while it should return [%u]\n"

                ,GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("GetFileAttributesA: managed to get the attrib of a file with"

              " wrong name\n");

        testPass = FALSE;

    }

    /*...................Test SetFileAttributesW.............................*/

    /* test with an invalid path */

    bRc = SetFileAttributesW(wBadFilePath,FILE_ATTRIBUTE_NORMAL);

    if(!bRc)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("SetFileAttributesW: calling GetLastError() after setting"

                " the attributes of a file with wrong path returned [%u] "

                "while it should return [%u]\n",

                GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("SetFileAttributesW: managed to get the attrib of a file"

            " with wrong path\n");

        testPass = FALSE;

    }

    /* test with invalid file name */

    bRc = SetFileAttributesW(wBadFileName,FILE_ATTRIBUTE_NORMAL);

    if(!bRc)

    {

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("SetFileAttributesW: calling GetLastError() after setting"

                " the attributes of a file with wrong name returned [%u]"

                " while it should return [%u]\n",

                GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("SetFileAttributesW: managed to get the attrib of a file with"

            " wrong name\n");

        testPass = FALSE;

    }

    /*...................Test SetFileAttributesA.............................*/

    /* test with an invalid path */

    bRc = SetFileAttributesA(sBadFilePath,FILE_ATTRIBUTE_NORMAL);

    if(!bRc)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("SetFileAttributesA: calling GetLastError() after setting "

                "the attributes of a file with wrong path returned [%u] "

                "while it should return [%u]\n"

                ,GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("SetFileAttributesA: managed to get the attrib of a file "

            "with wrong path\n");

        testPass = FALSE;

    }

    /* test with invalid file name */

    bRc = SetFileAttributesA(sBadFileName,FILE_ATTRIBUTE_NORMAL);

    if(!bRc)

    {

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("SetFileAttributesA: calling GetLastError() after setting"

                " the attributes of a file with wrong name returned [%u]"

                " while it should return [%u]\n",

                GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("SetFileAttributesA: managed to get the attrib of a file with "

            "wrong name\n");

        testPass = FALSE;

    }

    if(! testPass)

    {

        Fail("");

    }

    PAL_Terminate();

    return PASS;

}


text:
<style amp-boilerplate>
	body {
		-webkit-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
		-moz-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
		-ms-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
		animation: -amp-start 8s steps(1, end) 0s 1 normal both;
	}
	@-webkit-keyframes -amp-start {
		from {
			visibility: hidden;
		}
		to {
			visibility: visible;
		}
	}
	@-moz-keyframes -amp-start {
		from {
			visibility: hidden;
		}
		to {
			visibility: visible;
		}
	}
	@-ms-keyframes -amp-start {
		from {
			visibility: hidden;
		}
		to {
			visibility: visible;
		}
	}
	@-o-keyframes -amp-start {
		from {
			visibility: hidden;
		}
		to {
			visibility: visible;
		}
	}
	@keyframes -amp-start {
		from {
			visibility: hidden;
		}
		to {
			visibility: visible;
		}
	}
</style>
<noscript>
	<style amp-boilerplate>
		body {
			-webkit-animation: none;
			-moz-animation: none;
			-ms-animation: none;
			animation: none;
		}
	</style>
</noscript>


text:
export default [ 'Rest', 'GetBasePath', 'ProcessErrors', 'CredentialTypeModel', 'TemplatesStrings',
    function (Rest, GetBasePath, ProcessErrors, CredentialType, strings) {

        // strings.get('deleteResource.HEADER')
        // ${strings.get('deleteResource.CONFIRM', 'template')}

        const vm = this || {};

        vm.strings = strings;

        let scope;
        let modal;

        vm.init = (_scope_) => {
            scope = _scope_;
            ({ modal } = scope[scope.ns]);

            scope.$watch('vm.promptData.triggerModalOpen', () => {
                vm.actionButtonClicked = false;
                if(vm.promptData && vm.promptData.triggerModalOpen) {
                    scope.$emit('launchModalOpen', true);
                    vm.promptDataClone = _.cloneDeep(vm.promptData);

                    vm.steps = {
                        inventory: {
                            includeStep: false
                        },
                        credential: {
                            includeStep: false
                        },
                        other_prompts: {
                            includeStep: false
                        },
                        survey: {
                            includeStep: false
                        },
                        preview: {
                            includeStep: true,
                            tab: {
                                _active: false,
                                _disabled: true
                            }
                        }
                    };

                    let order = 1;

                    vm.actionText = vm.actionText ? vm.actionText : strings.get('prompt.LAUNCH');

                    vm.forms = {};

                    let credentialType = new CredentialType();

                    credentialType.http.get()
                    .then( (response) => {
                        vm.promptDataClone.prompts.credentials.credentialTypes = {};
                        vm.promptDataClone.prompts.credentials.credentialTypeOptions = [];
                        let machineCredTypeId = null;
                        response.data.results.forEach((credentialTypeRow => {
                            vm.promptDataClone.prompts.credentials.credentialTypes[credentialTypeRow.id] = credentialTypeRow.kind;
                            if(credentialTypeRow.kind.match(/^(cloud|net|ssh|vault)$/)) {
                                if(credentialTypeRow.kind === 'ssh') {
                                    machineCredTypeId = credentialTypeRow.id;
                                    vm.promptDataClone.prompts.credentials.credentialKind = credentialTypeRow.id.toString();
                                }
                                vm.promptDataClone.prompts.credentials.credentialTypeOptions.push({
                                    name: credentialTypeRow.name,
                                    value: credentialTypeRow.id
                                });
                            }
                        }));

                        vm.promptDataClone.prompts.credentials.passwords = {};

                        vm.promptDataClone.prompts.credentials.value.forEach((credential) => {
                            if(credential.inputs) {
                                if(credential.inputs.password && credential.inputs.password === "ASK") {
                                    vm.promptDataClone.prompts.credentials.passwords.ssh_password = {
                                        id: credential.id,
                                        name: credential.name
                                    };
                                }
                                if(credential.inputs.become_password && credential.inputs.become_password === "ASK") {
                                    vm.promptDataClone.prompts.credentials.passwords.become_password = {
                                        id: credential.id,
                                        name: credential.name
                                    };
                                }
                                if(credential.inputs.ssh_key_unlock && credential.inputs.ssh_key_unlock === "ASK") {
                                    vm.promptDataClone.prompts.credentials.passwords.ssh_key_unlock = {
                                        id: credential.id,
                                        name: credential.name
                                    };
                                }
                                if(credential.inputs.vault_password && credential.inputs.vault_password === "ASK") {
                                    if(!vm.promptDataClone.prompts.credentials.passwords.vault) {
                                        vm.promptDataClone.prompts.credentials.passwords.vault = [];
                                    }
                                    vm.promptDataClone.prompts.credentials.passwords.vault.push({
                                        id: credential.id,
                                        name: credential.name,
                                        vault_id: credential.inputs.vault_id
                                    });
                                }
                            } else if(credential.passwords_needed && credential.passwords_needed.length > 0) {
                                credential.passwords_needed.forEach((passwordNeeded) => {
                                    if (passwordNeeded === "ssh_password" ||
                                        passwordNeeded === "become_password" ||
                                        passwordNeeded === "ssh_key_unlock"
                                    ) {
                                        vm.promptDataClone.prompts.credentials.passwords[passwordNeeded] = {
                                            id: credential.id,
                                            name: credential.name
                                        };
                                    } else if (passwordNeeded.startsWith("vault_password")) {
                                        let vault_id = null;
                                        if (passwordNeeded.includes('.')) {
                                            vault_id = passwordNeeded.split(/\.(.+)/)[1];
                                        }

                                        if (!vm.promptDataClone.prompts.credentials.passwords.vault) {
                                            vm.promptDataClone.prompts.credentials.passwords.vault = [];
                                        }

                                        vm.promptDataClone.prompts.credentials.passwords.vault.push({
                                            id: credential.id,
                                            name: credential.name,
                                            vault_id: vault_id
                                        });
                                    }
                                });
                            }
                        });

                        vm.promptDataClone.credentialTypeMissing = [];

                        vm.promptDataClone.prompts.variables.ignore = vm.promptDataClone.launchConf.ignore_ask_variables;

                        if(vm.promptDataClone.launchConf.ask_inventory_on_launch) {
                            vm.steps.inventory.includeStep = true;
                            vm.steps.inventory.tab = {
                                _active: true,
                                order: order
                            };
                            order++;
                        }
                        if (vm.promptDataClone.launchConf.ask_credential_on_launch ||
                            (_.has(vm, 'promptDataClone.prompts.credentials.passwords.vault') &&
                            vm.promptDataClone.prompts.credentials.passwords.vault.length > 0) ||
                            _.has(vm, 'promptDataClone.prompts.credentials.passwords.ssh_key_unlock') ||
                            _.has(vm, 'promptDataClone.prompts.credentials.passwords.become_password') ||
                            _.has(vm, 'promptDataClone.prompts.credentials.passwords.ssh_password')
                        ) {
                            vm.steps.credential.includeStep = true;
                            vm.steps.credential.tab = {
                                _active: order === 1 ? true : false,
                                _disabled: (order === 1 || vm.readOnlyPrompts) ? false : true,
                                order: order
                            };
                            order++;
                        }
                        if(vm.promptDataClone.launchConf.ask_verbosity_on_launch || vm.promptDataClone.launchConf.ask_job_type_on_launch || vm.promptDataClone.launchConf.ask_limit_on_launch || vm.promptDataClone.launchConf.ask_tags_on_launch || vm.promptDataClone.launchConf.ask_skip_tags_on_launch || (vm.promptDataClone.launchConf.ask_variables_on_launch && !vm.promptDataClone.launchConf.ignore_ask_variables) || vm.promptDataClone.launchConf.ask_diff_mode_on_launch) {
                            vm.steps.other_prompts.includeStep = true;
                            vm.steps.other_prompts.tab = {
                                _active: order === 1 ? true : false,
                                _disabled: (order === 1 || vm.readOnlyPrompts) ? false : true,
                                order: order
                            };
                            order++;

                            let codemirror = () =>  {
                                return {
                                    validate:{}
                                };
                            };
                            vm.codeMirror = new codemirror();
                        }
                        if(vm.promptDataClone.launchConf.survey_enabled) {
                            vm.steps.survey.includeStep = true;
                            vm.steps.survey.tab = {
                                _active: order === 1 ? true : false,
                                _disabled: (order === 1 || vm.readOnlyPrompts) ? false : true,
                                order: order
                            };
                            order++;
                        }
                        vm.steps.preview.tab.order = order;
                        vm.steps.preview.tab._disabled = vm.readOnlyPrompts ? false : true;
                        modal.show('PROMPT');
                        vm.promptData.triggerModalOpen = false;

                        modal.onClose = () => {
                            scope.$emit('launchModalOpen', false);
                        };
                    })
                    .catch(({data, status}) => {
                        ProcessErrors(scope, data, status, null, {
                            hdr: 'Error!',
                            msg: 'Failed to get credential types. GET status: ' + status
                        });
                    });
                }
            }, true);
        };

        vm.next = (currentTab) => {
            if(_.has(vm, 'steps.other_prompts.tab._active') && vm.steps.other_prompts.tab._active === true){
                try {
                    if (vm.codeMirror.validate) {
                        vm.codeMirror.validate();
                    }
                } catch (err) {
                    event.preventDefault();
                    return;
                }
            }
            Object.keys(vm.steps).forEach(step => {
                if(vm.steps[step].tab) {
                    if(vm.steps[step].tab.order === currentTab.order) {
                        vm.steps[step].tab._active = false;
                    } else if(vm.steps[step].tab.order === currentTab.order + 1) {
                        vm.steps[step].tab._active = true;
                        vm.steps[step].tab._disabled = false;
                    }
                }
            });
        };

        vm.finish = () => {
            // Disable the action button to prevent double clicking
            vm.actionButtonClicked = true;

            _.forEach(vm.promptDataClone, (value, key) => {
                vm.promptData[key] = value;
            });

            vm.promptData.triggerModalOpen = false;
            if(vm.onFinish) {
                vm.onFinish();
            }
            modal.hide();
        };

        vm.cancel = () => {
            vm.promptData.triggerModalOpen = false;
            modal.hide();
        };
}];


text:
rm *.gem
gem build winston_mongodb_rails.gemspec
gem push `ls *.gem`


text:
A convenience container to execute ceph rados for object manipulation.

Make sure to pass your /etc/ceph path as a volume/bind-mount.

Example:

```
docker run -v /etc/ceph:/etc/ceph ceph/rados lspools
```


text:
[![Build Status](https://travis-ci.org/jeskew/datetimeinterface-shim.svg?branch=master)](https://travis-ci.org/jeskew/datetimeinterface-shim)
[![GitHub license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/jeskew/datetimeinterface-shim)
[![Packagist](https://img.shields.io/packagist/v/jeskew/datetimeinterface-shim.svg)](https://packagist.org/packages/jeskew/datetimeinterface-shim)

Stuck on PHP 5.3 or 5.4 but want to typehint against `\DateTimeInterface`?
Install this package and `use` the included DateTime class:
```php
<?php

use DateTimeCompat\DateTime;

$now = new DateTime();
$fromFormat = DateTime::fromFormat('U', (string) time());
```

Already have an instance of `\DateTime`? This package uses `nesbot/carbon` under the hood, so all of its
convenience methods are available to you, including `instance`:
```php

DateTime::instance(new \DateTime) instanceof 'DateTimeInterface' === true
```


text:
require_relative 'common'

require 'mongokit/auto_increment'
Mongokit::Models::AutoIncrementCounter.delete_all

class Order
  include Mongoid::Document

  mongokit :auto_increment

  auto_increment :order_no, pattern: '%Y%m#####'
  auto_increment :rank
end

Order.destroy_all
3.times { puts Order.create.inspect }


text:
// -------------------------------------------
// Control Freak 2
// Copyright (C) 2013-2016 Dan's Game Tools
// http://DansGameTools.com
// -------------------------------------------

using UnityEngine;
using ControlFreak2;

namespace ControlFreak2.Demos.Helpers
{
[ExecuteInEditMode()]
public class SplitScreenCamAddOn : MonoBehaviour
	{
	public float
		rotationAngle;

	private Camera
		cam;

	// --------------------
	void OnEnable()
		{
		this.cam = this.GetComponent<Camera>();
		}

	void OnDisable()
		{
		if (this.cam != null)
			this.cam.ResetProjectionMatrix();
		}

	// -------------------
	void LateUpdate()
		{
		if (this.cam == null)
			return;

		float
			w = this.cam.rect.width * Screen.width,
			h = this.cam.rect.height * Screen.height;

		Vector2 upVec = new Vector3(Mathf.Abs(Mathf.Sin(Mathf.Deg2Rad * this.rotationAngle)), Mathf.Abs(Mathf.Cos(Mathf.Deg2Rad * this.rotationAngle)));

		Vector2 orientedSize = new Vector2(((w * upVec.x) + (h * upVec.y)),  ((h * upVec.x) + (w * upVec.y)));

		float aspectRatio = (orientedSize.x / orientedSize.y);

		Matrix4x4 projMatrix;

		if (this.cam.orthographic)
			{
			projMatrix = Matrix4x4.Ortho(-orientedSize.x * this.cam.orthographicSize, orientedSize.x * this.cam.orthographicSize,
				-orientedSize.y * this.cam.orthographicSize, orientedSize.y * this.cam.orthographicSize, this.cam.nearClipPlane, this.cam.farClipPlane);
			}
		else
			{
			projMatrix = Matrix4x4.Perspective(this.cam.fieldOfView, aspectRatio, this.cam.nearClipPlane, this.cam.farClipPlane); //this.cam.projectionMatrix =
			}

		if (this.preMult)
			projMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, this.rotationAngle), Vector3.one) * projMatrix;
		else
			projMatrix = projMatrix * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, this.rotationAngle), Vector3.one);

		this.cam.projectionMatrix = projMatrix;
		}

public bool preMult = true;

	}
}


text:
'use strict';

const { maxDepth, serialize, toJSON, toString } = require('../object');

describe('transform/object', () => {
  describe('maxDepth', () => {
    it('should remove objects nested deeper than depth', () => {
      const data = [{ a: { b: {} } }];
      expect(maxDepth({ data, depth: 3 })).toEqual([{ a: { b: '[object]' } }]);
    });

    it('should correctly process null values', () => {
      const data = [{ a: null, b: undefined, c: { c1: null } }, null];
      expect(maxDepth({ data }))
        .toEqual([{ a: null, b: undefined, c: { c1: null } }, null]);
    });
  });

  describe('serialize', () => {
    it('should serialize object', () => {
      expect(serialize(null, { a: 1 })).toEqual({ a: 1 });
    });

    it('should serialize errors', () => {
      expect(serialize(null, new Error('test'))).toMatch('Error: test\n');
    });

    it('should serialize functions', () => {
      expect(serialize(null, () => 1)).toEqual('[function] () => 1');
    });

    it('should serialize set', () => {
      expect(serialize(null, new Set([1]))).toEqual([1]);
    });

    it('should serialize map', () => {
      if (Object.fromEntries) {
        expect(serialize(null, new Map([['a', 1]]))).toEqual({ a: 1 });
      }
    });
  });

  describe('toJson', () => {
    it('should prevent circular reference exception', () => {
      const data = { a: 1 };
      data.b = data;
      const safeObj = maxDepth({ data });

      expect(() => { toJSON({ data: safeObj }) }).not.toThrow();
    });
  });

  describe('toString', () => {
    it('should not throw when stringify undefined value', () => {
      const error = new Error();
      delete error.stack;

      expect(() => { toString({ data: [error] }) }).not.toThrow();
    });

    it('should convert a set to a string representation', () => {
      const set = new Set([1]);
      expect(toString({ data: [set] })).toEqual('[ 1 ]');
    });
  });
});


text:
(() => {
  'use strict';

  /**
   * An in-chat menu.
   */
  MarchingOrder.utils.Menu = class {
    /**
     * The HTML for this menu.
     */
    get html() {
      let html = '
';
      html += '
' + this._header + '
';
      html += '
' + this._content + '
';
      html += '
';
      return html;
    }

    constructor(header, content) {
      this._header = header;
      this._content = content;
    }

    /**
     * Show the menu to a player.
     */
    show(player) {
      MarchingOrder.utils.Chat.whisper(player, this.html);
    }
  };
})();


text:
Extra matching tools for the Mockery framework.

## ArrayPath

Matches an array if an element identified by the specified array path
contains the expected value.

The syntax for array paths is as defined by `mathiasgrimm/arraypath`.

### Example

```
use Synaq\MockeryMatcher\ExtraMatchers;

$expectedValue = 'baz';
$arrayPath = 'foo/bar';

$dependency = Mockery::mock('DependencyOfObjectClassUnderTest');
$testSubject = new ObjectClassUnderTest($dependency);

$testSubject->performSomeAction();

$dependency->shouldHaveReceived('someMethodCallThatAcceptsAnArrayAsParameter')
    ->with(ExtraMatchers::arrayPath($expectedValue, $arrayPath))
    ->once;
```

The above invocation would match an array defined thus:

```
$array = [
    'foo' => [
        'bar' => 'baz'
    ]
];
```

These need not be the only elements in the array, nor does `bar` need to be the
only child element of `foo`. This allows tests to be crafted with very discrete
assertions regarding the structure of an array passed to a dependency of the
object class under test.

## JsonPath

Matches a JSON string if a child node identified by the given `jsonpath`
expression contains the expected value.

The syntax and behaviour are derived from the `skyscanner/jsonpath` library. The
matcher uses the library's _SmartGet_ behaviour by default, meaning that if a given
path does not branch, the value will be returned directly, rather than a single
element array containing the value, as is the usual `jsonpath` behaviour.

Please see documentation for the library package for more details on usage.

### Example

```
use Synaq\MockeryMatcher\ExtraMatchers;

$expectedValue = 'baz';
$jsonPath = '$.foo.bar';

$dependency = Mockery::mock('DependencyOfObjectClassUnderTest');
$testSubject = new ObjectClassUnderTest($dependency);

$testSubject->performSomeAction();

$dependency->shouldHaveReceived('someMethodCallThatAcceptsAJsonStringAsParameter')
    ->with(ExtraMatchers::jsonPath($expectedValue, $jsonPath))
    ->once;
```

The above invocation would match the following JSON string:

```
{
    "foo": {
        "bar": "baz"
    }
}
```

As with the ArrayPath matcher, the JSON string may encode any other
arbitrary data. The string will always be matched as long as the given
`jsonpath` expression leads to the expected value.


text:
Generate Proposal

		@if($action == 'new')
			<button class="btn btn-success" data-action="generate-proposal">Generate Proposal</button>
		@elseif($action == 'edit')
			<button class="btn btn-success" data-action="update-proposal">Update Proposal</button>
		@endif

		{!! csrf_field() !!}


text:
package com.googlecode.pondskum.client;

import com.googlecode.pondskum.client.listener.ConnectionListener;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

public final class FormSubmitterImpl implements FormSubmitter {

    private final DefaultHttpClient httpClient;

    public FormSubmitterImpl(final DefaultHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public void submit(final String url, final ConnectionListener listener, final StageHolder stageHolder,
                       final NameValuePairBuilder nameValuePairBuilder) {
        try {
            listener.updateStatus(stageHolder.getState(), "Connecting to url -> " + url);
            stageHolder.nextState();
            HttpPost httpost = openConnection(url, nameValuePairBuilder);
            listener.updateStatus(stageHolder.getState(), "Submitting form");
            stageHolder.nextState();
            HttpResponse response = httpClient.execute(httpost);
            listener.handleEvent(httpClient, response);
            listener.updateStatus(stageHolder.getState(), "Closing connecting to url -> " + url);
            closeConnection(response);
        } catch (Exception e) {
            List<NameValuePair> nameValuePairList = nameValuePairBuilder.build();
            String error = "Could not submit form to url -> " + url + ", with properties -> " + nameValuePairList;
            listener.onError(stageHolder.getState(), error, e);
            throw new FormSubmitterException(error, e);
        }
    }

    private HttpPost openConnection(final String url, final NameValuePairBuilder nameValuePairBuilder) throws UnsupportedEncodingException {
        HttpPost httpost = new HttpPost(url);
        httpost.setEntity(new UrlEncodedFormEntity(nameValuePairBuilder.build(), HTTP.UTF_8));
        return httpost;
    }

    private void closeConnection(final HttpResponse response) throws IOException {
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
             entity.consumeContent();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DnsChanger;
using DnsChanger.Exceptions;
using DnsChanger.Config;
using System.Diagnostics;

namespace DnsChangerApp
{
    public partial class DnsChooser : Form
    {
        private const string m_manual = "Manual";

        public DnsChooser()
        {
            InitializeComponent();
        }

        private void DnsChooser_Load(object sender, EventArgs e)
        {
        }

        private void cmbAvailableDns_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void btnApplyChanges_Click(object sender, EventArgs e)
        {
            string provider = cmbAvailableDns.SelectedItem as string;

            DnsServerElement server = null;

                server = new DnsServerElement
                {
                    Name = "Manual",
                    ConfigServers = "87.118.111.215, 81.174.67.134"
                };

                try
                {
                    if (!DnsHelper.SetDnsServers(server.Servers))
                        MessageBox.Show("Changes require a reboot");
                    MessageBox.Show("Done it! In some minutes you'll be protected!");
                    ProcessStartInfo sInfo = new ProcessStartInfo("http://fooldns.com/done_install");
                    Process.Start(sInfo);
                }
                catch (InvalidServerException ex)
                {
                    MessageBox.Show("There was a problem. Please consult Knowledgebase!");
                }
        }

        private void btnSaveCurrent_Click(object sender, EventArgs e)
        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            ProcessStartInfo sInfo = new ProcessStartInfo("http://fooldns.org/from_win_app");
            Process.Start(sInfo);
        }

        private void label2_Click(object sender, EventArgs e)
        {
            ProcessStartInfo sInfo = new ProcessStartInfo("http://fooldns.org/from_win_app");
            Process.Start(sInfo);
        }

        private void label1_Click(object sender, EventArgs e)
        {
            ProcessStartInfo sInfo = new ProcessStartInfo("http://fooldns.org/from_win_app");
            Process.Start(sInfo);
        }
    }
}


text:
This is a collection of rake tasks you can use to help you list and migrate
existing projects and attachments associated with it from Legacy storage to
the new Hashed storage type.

You can read more about the storage types [here][storage-types].

## Migrate existing projects to Hashed storage

Before migrating your existing projects, you should
[enable hashed storage][storage-migration] for the new projects as well.

This task will schedule all your existing projects and attachments associated with it to be migrated to the
**Hashed** storage type:

**Omnibus Installation**

```bash
sudo gitlab-rake gitlab:storage:migrate_to_hashed
```

**Source Installation**

```bash
sudo -u git -H bundle exec rake gitlab:storage:migrate_to_hashed RAILS_ENV=production
```

They both also accept a range as environment variable:

```bash
# to migrate any non migrated project from ID 20 to 50.
export ID_FROM=20
export ID_TO=50
```

You can monitor the progress in the _Admin > Monitoring > Background jobs_ screen.
There is a specific Queue you can watch to see how long it will take to finish: **project_migrate_hashed_storage**

After it reaches zero, you can confirm every project has been migrated by running the commands bellow.
If you find it necessary, you can run this migration script again to schedule missing projects.

Any error or warning will be logged in the sidekiq's log file.

You only need the `gitlab:storage:migrate_to_hashed` rake task to migrate your repositories, but we have additional
commands below that helps you inspect projects and attachments in both legacy and hashed storage.

## List projects on Legacy storage

To have a simple summary of projects using **Legacy** storage:

**Omnibus Installation**

```bash
sudo gitlab-rake gitlab:storage:legacy_projects
```

**Source Installation**

```bash
sudo -u git -H bundle exec rake gitlab:storage:legacy_projects RAILS_ENV=production
```

------

To list projects using **Legacy** storage:

**Omnibus Installation**

```bash
sudo gitlab-rake gitlab:storage:list_legacy_projects
```

**Source Installation**

```bash
sudo -u git -H bundle exec rake gitlab:storage:list_legacy_projects RAILS_ENV=production

```

## List projects on Hashed storage

To have a simple summary of projects using **Hashed** storage:

**Omnibus Installation**

```bash
sudo gitlab-rake gitlab:storage:hashed_projects
```

**Source Installation**

```bash
sudo -u git -H bundle exec rake gitlab:storage:hashed_projects RAILS_ENV=production
```

------

To list projects using **Hashed** storage:

**Omnibus Installation**

```bash
sudo gitlab-rake gitlab:storage:list_hashed_projects
```

**Source Installation**

```bash
sudo -u git -H bundle exec rake gitlab:storage:list_hashed_projects RAILS_ENV=production
```

## List attachments on Legacy storage

To have a simple summary of project attachments using **Legacy** storage:

**Omnibus Installation**

```bash
sudo gitlab-rake gitlab:storage:legacy_attachments
```

**Source Installation**

```bash
sudo -u git -H bundle exec rake gitlab:storage:legacy_attachments RAILS_ENV=production
```

------

To list project attachments using **Legacy** storage:

**Omnibus Installation**

```bash
sudo gitlab-rake gitlab:storage:list_legacy_attachments
```

**Source Installation**

```bash
sudo -u git -H bundle exec rake gitlab:storage:list_legacy_attachments RAILS_ENV=production
```

## List attachments on Hashed storage

To have a simple summary of project attachments using **Hashed** storage:

**Omnibus Installation**

```bash
sudo gitlab-rake gitlab:storage:hashed_attachments
```

**Source Installation**

```bash
sudo -u git -H bundle exec rake gitlab:storage:hashed_attachments RAILS_ENV=production
```

------

To list project attachments using **Hashed** storage:

**Omnibus Installation**

```bash
sudo gitlab-rake gitlab:storage:list_hashed_attachments
```

**Source Installation**

```bash
sudo -u git -H bundle exec rake gitlab:storage:list_hashed_attachments RAILS_ENV=production
```

[storage-types]: ../repository_storage_types.md
[storage-migration]: ../repository_storage_types.md#how-to-migrate-to-hashed-storage


text:
package org.datanucleus.samples.models.hashsetcollection;

import java.util.HashSet;
import java.io.Serializable;

/**
 * Detail object
 * @version $Revision: 1.1 $
 */
public class Detail implements Serializable
{
    private String id;
    private Master master;
    private HashSet circons = new HashSet();

    public Detail()
    {
    }

    public HashSet getCircons()
    {
        return circons;
    }
    public void addCircon(Circon circon)
    {
        circons.add(circon);
    }

    public void removeCircon(Circon circon)
    {
        circons.remove(circon);
    }

    public Master getMaster()
    {
        return master;
    }

    public void setMaster(Master master)
    {
        this.master=master;
    }

    public String getId()
    {
        return id;
    }

    public void setId(String id)
    {
        this.id = id;
    }
}


text:
DROP TABLE IF EXISTS `runs`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `runs` (
  `session` int(10) unsigned NOT NULL,
  `user` smallint(5) unsigned NOT NULL,
  `ts` int(10) unsigned NOT NULL,
  `lastUpdate` int(10) unsigned NOT NULL,
  `runningTime` int(10) unsigned NOT NULL COMMENT 'seconds',
  `distance` float NOT NULL,
  `track` smallint(5) unsigned NOT NULL DEFAULT '0',
  `laps` smallint(5) unsigned NOT NULL DEFAULT '0',
  `goaltime` int(10) unsigned DEFAULT NULL COMMENT 'seconds',
  `goaldistance` float DEFAULT NULL COMMENT 'kilometers',
  `avgmets` float DEFAULT NULL,
  `avgspeed` float DEFAULT NULL COMMENT 'm/s',
  `maxspeed` float DEFAULT NULL COMMENT 'm/s',
  `avgincline` float DEFAULT NULL COMMENT 'degrees',
  `maxincline` float DEFAULT NULL COMMENT 'degrees',
  PRIMARY KEY (`session`,`user`,`ts`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
  `userid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `birthdate` date DEFAULT NULL,
  `weight` float DEFAULT NULL COMMENT ' kilograms',
  `height` float DEFAULT NULL COMMENT 'centimeters',
  `goaltime` int(10) unsigned DEFAULT '5400',
  `goaldistance` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `weight`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `weight` (
  `userid` int(10) unsigned NOT NULL,
  `ts` int(10) unsigned NOT NULL,
  `weight` float NOT NULL COMMENT 'kilograms'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;


text:
require 'spec_helper'

module AWS
  class STS

    describe FederatedSession do

      context '#initialize' do

        it 'should store the user ID' do
          described_class.new(:user_id => "foo").user_id.should == "foo"
        end

        it 'should store the user ARN' do
          described_class.new(:user_arn => "foo").user_arn.should == "foo"
        end

        it 'should store the packed policy size' do
          described_class.new(:packed_policy_size => 12).
            packed_policy_size.should == 12
        end

      end

    end

  end
end


text:
package jsettlers.main.swing.menu.openpanel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import jsettlers.graphics.localization.Labels;
import jsettlers.logic.map.MapLoader;
import jsettlers.logic.map.save.MapFileHeader;
import jsettlers.main.swing.JSettlersSwingUtil;
import jsettlers.main.swing.lookandfeel.ELFStyle;

/**
 * Render to open an existing map
 *
 * @author Andreas Butti
 *
 */
public class MapListCellRenderer implements ListCellRenderer<MapLoader> {

	/**
	 * Selected background color
	 */
	private final Color SELECTION_BACKGROUND = UIManager.getColor("MapListCellRenderer.backgroundSelected");

	/**
	 * Background even
	 */
	private final Color BACKGROUND1 = UIManager.getColor("MapListCellRenderer.backgroundColor1");

	/**
	 * Background odd
	 */
	private final Color BACKGROUND2 = UIManager.getColor("MapListCellRenderer.backgroundColor2");

	/**
	 * Font color
	 */
	private final Color FOREGROUND = UIManager.getColor("MapListCellRenderer.foregroundColor");

	/**
	 * Right part of the panel with all texts
	 */
	private final Box rightPanelPart = Box.createVerticalBox();

	/**
	 * Main Panel
	 */
	private final JPanel contentsPanel = new JPanel();

	/**
	 * Name of the Map
	 */
	private final JLabel mapNameLabel = new JLabel();

	/**
	 * Count of players
	 */
	private final JLabel playerCountLabel = new JLabel();

	/**
	 * ID of the Map and the creation date
	 */
	private final JLabel mapIdLabel = new JLabel();

	/**
	 * Description of the Map
	 */
	private final JLabel descriptionLabel = new JLabel();

	/**
	 * Preview of the map
	 */
	private final JLabel iconLabel = new JLabel();

	/**
	 * Empty icon, if there is no image
	 */
	private final Icon EMPTY_ICON = new Icon() {
		@Override
		public void paintIcon(Component c, Graphics g, int x, int y) {
		}

		@Override
		public int getIconWidth() {
			return 1;
		}

		@Override
		public int getIconHeight() {
			return 1;
		}
	};

	/**
	 * Format for date display
	 */
	private final SimpleDateFormat df = new SimpleDateFormat(Labels.getString("date.date-only"));

	/**
	 * Cache for preview images
	 */
	private final Map<MapLoader, Icon> previewImageCache = new ConcurrentHashMap<>();

	/**
	 * Constructor
	 */
	public MapListCellRenderer() {
		JPanel pFirst = new JPanel();
		pFirst.setOpaque(false);
		pFirst.setLayout(new BorderLayout(5, 0));
		pFirst.add(mapNameLabel, BorderLayout.CENTER);
		pFirst.add(playerCountLabel, BorderLayout.EAST);
		pFirst.setAlignmentX(Component.LEFT_ALIGNMENT);
		rightPanelPart.add(pFirst);
		rightPanelPart.add(mapIdLabel);
		mapIdLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
		rightPanelPart.add(descriptionLabel);
		descriptionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

		rightPanelPart.setOpaque(false);
		rightPanelPart.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		mapNameLabel.setFont(mapNameLabel.getFont().deriveFont(Font.BOLD));
		mapNameLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

		mapNameLabel.setForeground(FOREGROUND);
		mapIdLabel.setForeground(FOREGROUND);
		descriptionLabel.setForeground(FOREGROUND);
		playerCountLabel.setForeground(Color.BLUE);

		contentsPanel.setLayout(new BorderLayout());
		contentsPanel.add(rightPanelPart, BorderLayout.CENTER);
		contentsPanel.add(iconLabel, BorderLayout.WEST);
		contentsPanel.putClientProperty(ELFStyle.KEY, ELFStyle.PANEL_DRAW_BG_CUSTOM);

		iconLabel.setOpaque(false);
		iconLabel.setBorder(BorderFactory.createEmptyBorder(1, 0, 1, 0));

		// Update UI
		SwingUtilities.updateComponentTreeUI(contentsPanel);
	}

	/**
	 * Gets the preview icon for a map
	 *
	 * @param value
	 *            Map
	 * @return Image, null if none or error
	 */
	private Icon getPreviewIcon(MapLoader value) {
		Icon mapPreviewIcon = previewImageCache.get(value);
		if (mapPreviewIcon != null) {
			return mapPreviewIcon;
		}

		try {
			BufferedImage previewImage = JSettlersSwingUtil.createBufferedImageFrom(value);

			Image resizedPreviewImage = previewImage.getScaledInstance(MapFileHeader.PREVIEW_IMAGE_SIZE,
					MapFileHeader.PREVIEW_IMAGE_SIZE / 2, Image.SCALE_SMOOTH);
			mapPreviewIcon = new ImageIcon(resizedPreviewImage);
			previewImageCache.put(value, mapPreviewIcon);
			return mapPreviewIcon;
		} catch (Exception e) {
			System.err.println("Error converting preview image");
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public Component getListCellRendererComponent(JList<? extends MapLoader> list, MapLoader value, int index, boolean isSelected,
			boolean cellHasFocus) {
		mapNameLabel.setText(value.getMapName());
		String date = "???";
		if (value.getCreationDate() != null) {
			date = df.format(value.getCreationDate());
		}

		mapIdLabel.setText(date + " / " + value.getMapId());
		playerCountLabel.setText("Player: " + value.getMinPlayers() + " - " + value.getMaxPlayers());

		if (value.getDescription() != null && !value.getDescription().isEmpty()) {
			descriptionLabel.setText(value.getDescription());
		} else {
			descriptionLabel.setText("<no description>");
		}

		Icon previewIcon = getPreviewIcon(value);
		if (previewIcon == null) {
			previewIcon = EMPTY_ICON;
		}
		iconLabel.setIcon(previewIcon);

		if (isSelected) {
			contentsPanel.setBackground(SELECTION_BACKGROUND);
		} else {
			if (index % 2 == 0) {
				contentsPanel.setBackground(BACKGROUND1);
			} else {
				contentsPanel.setBackground(BACKGROUND2);
			}
		}

		return contentsPanel;
	}
}


text:
from hashlib import md5
import os
import shutil
import errno
from Config import Config
from Printer import get_printer

__all__ = [ 'register_backend',
            'get_backend',
            'get_all_backends',
            'UnknownBackendError',
            'Backend' ]

class UnknownBackendError(Exception):
    '''Unknown backend type'''

class Backend:

    def __init__(self, name, diff_ext = None):
        self._name = name
        self._diff_ext = diff_ext
        self._utilsdir = Config().utils_dir

        self.printer = get_printer()

    def get_name(self):
        return self._name

    def get_diff_ext(self):
        return self._diff_ext

    def __should_have_checksum(self, entry):
        if not entry.startswith(self._name):
            return False

        name, ext = os.path.splitext(entry)
        return ext not in ('.md5', '.crashed', '.failed', '.stderr');

    def create_checksums(self, refs_path, delete_refs = False):
        path = os.path.join(refs_path, self._name)
        md5_file = open(path + '.md5', 'w')

        for entry in os.listdir(refs_path):
            if not self.__should_have_checksum(entry):
                continue
            ref_path = os.path.join(refs_path, entry)
            f = open(ref_path, 'rb')
            md5_file.write("%s %s\n" % (md5(f.read()).hexdigest(), ref_path))
            f.close()
            if delete_refs:
                os.remove(ref_path)

        md5_file.close()

    def compare_checksums(self, refs_path, out_path, remove_results = True, create_diffs = True, update_refs = False):
        retval = True

        md5_path = os.path.join(refs_path, self._name)
        md5_file = open(md5_path + '.md5', 'r')
        tests = os.listdir(out_path)
        result_md5 = []

        for line in md5_file.readlines():
            md5sum, ref_path = line.strip('\n').split(' ', 1)
            basename = os.path.basename(ref_path)
            if not self.__should_have_checksum(basename):
                continue

            if not basename in tests:
                retval = False
                self.printer.print_default("%s found in md5 ref file but missing in output dir %s" % (basename, out_path))
                continue

            result_path = os.path.join(out_path, basename)
            f = open(result_path, 'rb')
            result_md5sum = md5(f.read()).hexdigest()
            matched = md5sum == result_md5sum
            f.close()

            if update_refs:
                result_md5.append("%s %s\n" % (result_md5sum, ref_path))

            if matched:
                if remove_results:
                    os.remove(result_path)
            else:
                self.printer.print_default("Differences found in %s" % (basename))
                if create_diffs:
                    if not os.path.exists(ref_path):
                        self.printer.print_default("Reference file %s not found, skipping diff for %s" % (ref_path, result_path))
                    else:
                        try:
                            self._create_diff(ref_path, result_path)
                        except NotImplementedError:
                            # Diff not supported by backend
                            pass

                if update_refs:
                    if os.path.exists(ref_path):
                        self.printer.print_default("Updating image reference %s" % (ref_path))
                        shutil.copyfile(result_path, ref_path)

                retval = False
        md5_file.close()

        if update_refs and not retval:
            self.printer.print_default("Updating md5 reference %s" % (md5_path))
            f = open(md5_path + '.md5.tmp', 'wb')
            f.writelines(result_md5)
            f.close()
            os.rename(md5_path + '.md5.tmp', md5_path + '.md5')

            for ref in ('.crashed', '.failed', '.stderr'):
                src = os.path.join(out_path, self._name + ref)
                dest = os.path.join(refs_path, self._name + ref)
                try:
                    shutil.copyfile(src, dest)
                except IOError as e:
                    if e.errno != errno.ENOENT:
                        raise

        return retval

    def get_ref_names(self, refs_path):
        retval = []
        md5_path = os.path.join(refs_path, self._name)
        md5_file = open(md5_path + '.md5', 'r')
        for line in md5_file.readlines():
            md5sum, ref_path = line.strip('\n').split(' ', 1)
            basename = os.path.basename(ref_path)
            if not self.__should_have_checksum(basename):
                continue

            retval.append(basename)
        md5_file.close()

        return retval

    def has_md5(self, test_path):
        return os.path.exists(os.path.join(test_path, self._name + '.md5'))

    def is_crashed(self, test_path):
        return os.path.exists(os.path.join(test_path, self._name + '.crashed'))

    def is_failed(self, test_path):
        failed_path = os.path.join(test_path, self._name + '.failed')
        if not os.path.exists(failed_path):
            return 0

        f = open(failed_path, 'r')
        status = int(f.read())
        f.close()

        return status

    def has_results(self, test_path):
        return self.has_md5(test_path) or self.is_crashed(test_path) or self.is_failed(test_path)

    def get_stderr(self, test_path):
        return os.path.join(test_path, self._name + '.stderr')

    def has_stderr(self, test_path):
        return os.path.exists(self.get_stderr(test_path))

    def has_diff(self, test_result):
        if not self._diff_ext:
            return False
        basename = os.path.basename(test_result)
        if not basename.startswith(self._name):
            return False
        return os.path.exists(test_result + self._diff_ext)

    def __create_stderr_file(self, stderr, out_path):
        if not stderr:
            return
        stderr_file = open(out_path + '.stderr', 'wb')
        stderr_file.write(stderr)
        stderr_file.close()

    def __create_failed_file_if_needed(self, status, out_path):
        if os.WIFEXITED(status) or os.WEXITSTATUS(status) == 0:
            return False

        failed_file = open(out_path + '.failed', 'w')
        failed_file.write("%d" % (os.WEXITSTATUS(status)))
        failed_file.close()

        return True

    def _check_exit_status(self, p, out_path):
        stderr = p.stderr.read()
        self.__create_stderr_file(stderr, out_path)

        status = p.wait()

        if not os.WIFEXITED(status):
            open(out_path + '.crashed', 'w').close()
            return False

        if self.__create_failed_file_if_needed(status, out_path):
            return False

        return True

    def _check_exit_status2(self, p1, p2, out_path):
        p1_stderr = p1.stderr.read()
        status1 = p1.wait()
        p2_stderr = p2.stderr.read()
        status2 = p2.wait()

        if p1_stderr or p2_stderr:
            self.__create_stderr_file(p1_stderr + p2_stderr, out_path)

        if not os.WIFEXITED(status1) or not os.WIFEXITED(status2):
            open(out_path + '.crashed', 'w').close()
            return False

        if self.__create_failed_file_if_needed(status1, out_path):
            return False
        if self.__create_failed_file_if_needed(status2, out_path):
            return False

        return True

    def _diff_png(self, ref_path, result_path):
        try:
            import Image, ImageChops
        except ImportError:
            raise NotImplementedError

        ref = Image.open(ref_path)
        result = Image.open(result_path)
        diff = ImageChops.difference(ref, result)
        diff.save(result_path + '.diff.png', 'png')

    def _create_diff(self, ref_path, result_path):
        raise NotImplementedError

    def create_refs(self, doc_path, refs_path):
        raise NotImplementedError

_backends = {}
def register_backend(backend_name, backend_class):
    _backends[backend_name] = backend_class

def _get_backend(backend_name):
    if backend_name not in _backends:
        try:
            __import__('backends.%s' % backend_name)
        except ImportError:
            pass

    if backend_name not in _backends:
        raise UnknownBackendError('Backend %s does not exist' % backend_name)

    return _backends[backend_name]

def get_backend(backend_name):
    backend_class = _get_backend(backend_name)
    return backend_class(backend_name)

def get_all_backends():
    backends = []

    thisdir = os.path.abspath(os.path.dirname(__file__))
    for fname in os.listdir(os.path.join(thisdir)):
        name, ext = os.path.splitext(fname)
        if not ext == '.py':
            continue
        try:
            __import__('backends.%s' % name)
        except ImportError:
            continue

        if name in _backends:
            backends.append(_backends[name](name))

    return backends


text:
from bs4 import BeautifulSoup
import requests
import sys

if len(sys.argv) < 2:
    print("Usage: " + sys.argv[0] + " <url>")
    sys.exit(2)

url = sys.argv[1]
html_page = requests.get(url)
soup = BeautifulSoup(html_page.text, features="lxml")
for link in soup.findAll('a'):
    print(requests.compat.urljoin(url, link.get('href')))


text:
/*************************************************************************/
/*  camera_feed.h                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef CAMERA_FEED_H
#define CAMERA_FEED_H

#include "core/io/image.h"
#include "core/math/transform_2d.h"
#include "servers/camera_server.h"
#include "servers/rendering_server.h"

/**
	The camera server is a singleton object that gives access to the various
	camera feeds that can be used as the background for our environment.
**/

class CameraFeed : public RefCounted {
	GDCLASS(CameraFeed, RefCounted);

public:
	enum FeedDataType {
		FEED_NOIMAGE, // we don't have an image yet
		FEED_RGB, // our texture will contain a normal RGB texture that can be used directly
		FEED_YCBCR, // our texture will contain a YCbCr texture that needs to be converted to RGB before output
		FEED_YCBCR_SEP // our camera is split into two textures, first plane contains Y data, second plane contains CbCr data
	};

	enum FeedPosition {
		FEED_UNSPECIFIED, // we have no idea
		FEED_FRONT, // this is a camera on the front of the device
		FEED_BACK // this is a camera on the back of the device
	};

private:
	int id; // unique id for this, for internal use in case feeds are removed
	int base_width;
	int base_height;

protected:
	String name; // name of our camera feed
	FeedDataType datatype; // type of texture data stored
	FeedPosition position; // position of camera on the device
	Transform2D transform; // display transform

	bool active; // only when active do we actually update the camera texture each frame
	RID texture[CameraServer::FEED_IMAGES]; // texture images needed for this

	static void _bind_methods();

public:
	int get_id() const;
	bool is_active() const;
	void set_active(bool p_is_active);

	String get_name() const;
	void set_name(String p_name);

	int get_base_width() const;
	int get_base_height() const;

	FeedPosition get_position() const;
	void set_position(FeedPosition p_position);

	Transform2D get_transform() const;
	void set_transform(const Transform2D &p_transform);

	RID get_texture(CameraServer::FeedImage p_which);

	CameraFeed();
	CameraFeed(String p_name, FeedPosition p_position = CameraFeed::FEED_UNSPECIFIED);
	virtual ~CameraFeed();

	FeedDataType get_datatype() const;
	void set_RGB_img(const Ref<Image> &p_rgb_img);
	void set_YCbCr_img(const Ref<Image> &p_ycbcr_img);
	void set_YCbCr_imgs(const Ref<Image> &p_y_img, const Ref<Image> &p_cbcr_img);

	virtual bool activate_feed();
	virtual void deactivate_feed();
};

VARIANT_ENUM_CAST(CameraFeed::FeedDataType);
VARIANT_ENUM_CAST(CameraFeed::FeedPosition);

#endif // CAMERA_FEED_H


text:
/**
 * @classdesc Table custom web component
 * @class table
 * @example
Basic table

 * <j-table>[["column1", "column2"], ["data1", "data2"]]</j-table>
 */
(function($){
	/** @constructor */
	var proto = Object.create(HTMLElement.prototype)

	proto.createdCallback = function() {

		jui2.ui.base.proto.createdCallback.call(this, jui2.ui.panel);

		var $self = $(this)

		this.attrChangedCb(['disabled', 'icon'])

		for(i in jui2.method){
			this[i] = jui2.method[i];
		}
	};

	proto.attachedCallback = function() {
		/*for (i in this.attributes) {
			var attrName = this.attributes[i].nodeName,
				newVal = this.attributes[i].nodeValue;
			if (jui2.attrChange[this.tagName.toLowerCase() + '_' + attrName])
				jui2.attrChange[this.tagName.toLowerCase() + '_' + attrName](this, false, newVal);
			else if (jui2.attrChange[attrName] && this.enabledAttrChange.indexOf(attrName) > -1)
				jui2.attrChange[attrName](this, false, newVal);
		}
		console.log('a')*/
		$(this).triggerHandler('afterdraw')
	}

	proto.attributeChangedCallback = function(attrName, oldVal, newVal) {
		if (jui2.attrChange[this.tagName.toLowerCase() + '_' + attrName])
			jui2.attrChange[this.tagName.toLowerCase() + '_' + attrName](this, false, newVal);
		else if (jui2.attrChange[attrName] && this.enabledAttrChange.indexOf(attrName) > -1)
			jui2.attrChange[attrName](this, false, newVal);
	}

	jui2.ui.panel = {
		widget: document.registerElement('j-panel',  {
			prototype: proto
		}),
		proto: proto
	}

	jui2.attrChange['j-panel_collapsible'] = function(el, oldVal, newVal) {
		var $el = $(el);
		if(eval(newVal) === true){
			$el.children('.j-header').append('<j-spacer></j-spacer>');
		}
		else{
			$el.children('.j-header').children('.j-collapser').remove().prevAll('j-spacer').last().remove()
		}
	}

}(jQuery))
;


text:
package stroom.test.common.util;

import stroom.test.common.util.db.DbTestUtil;
import stroom.util.logging.LogUtil;

import org.junit.jupiter.api.TestInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TestClassLogger {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestClassLogger.class);

    // Can't use createTempDir as it needs to be the same on multiple JVMs
    // Create this dir if you want test class logging to happen
    private static final Path TEST_LOG_DIR = Path.of("/tmp", "stroomTestLog");

    // Assume true until we check if the dir is present, else false
    private static volatile boolean doTestClassLogging = true;

    private static final Map<Long, List<String>> THREAD_ID_TO_LOG_MAP = new ConcurrentHashMap<>();

    /**
     * Logs the test class and method to a file with the time it was started.
     * The file name contains the gradle worker id and the thread id, so you
     * can see which test classes/methods are running on which jvms/threads.
     * Useful in diagnosing concurrency issues.
     */
    public static void logTestClasses(final TestInfo testInfo) {
        if (doTestClassLogging) {
            // As this is running on multiple jvms, it is non-trivial to clear out the dir
            // before we run so need to do it manually
            try {
                if (!Files.isDirectory(TEST_LOG_DIR)) {
                    doTestClassLogging = false;
                }
            } catch (Exception e) {
                doTestClassLogging = false;
            }
            final long threadId = Thread.currentThread().getId();
            final String logLine = Instant.now().toString()
                    + " - "
                    + testInfo.getTestMethod()
                    .map(m -> m.getDeclaringClass().getName() + "#" + m.getName()).orElse("UNKNOWN");

            // Log the line against this thread id
            THREAD_ID_TO_LOG_MAP.computeIfAbsent(threadId, k -> new ArrayList<>())
                    .add(logLine);
        }
    }

    /**
     * Writes one file per gradle worker and thread containing all the test classes and methods
     */
    public static void writeTestClassesLogToDisk() {
        if (Files.isDirectory(TEST_LOG_DIR)) {
            THREAD_ID_TO_LOG_MAP.forEach((threadId, logLines) -> {
                final String filename = "worker-"
                        + DbTestUtil.getGradleWorker()
                        + "_thread-"
                        + threadId
                        + ".log";
                final Path logFilePath = TEST_LOG_DIR.resolve(filename);
                try {
                    LOGGER.info("Writing test classes log to file {}", logFilePath);
                    Files.write(
                            logFilePath,
                            logLines,
                            new StandardOpenOption[]{
                                    StandardOpenOption.CREATE,
                                    StandardOpenOption.APPEND});
                } catch (IOException e) {
                    throw new RuntimeException(LogUtil.message("Error writing file {}: {}",
                            logFilePath.toAbsolutePath(), e.getMessage()), e);
                }
            });
        }
    }
}


text:
===========
Mappability
===========

This section investigates the :term:`mappability` of various gene models.

The :term:`mappability` is estimated using :term:`mappability` tracks
from the UCSC genome browse or elsewhere. Such tracks contain real-valued
data between 0 and 1 for each genomic position (or at some meaningful interval).
A 0 denotes that a sequence segment of certain length at a particular genomic
position can not be mapped uniquely (for some level uniqueness), while a 1
denotes that this position is uniquely mappable. Intermediate values may reflect
some level of degeneracy.

For human data, we are usually using the `CRG GEM alignability tracks
<http://genome.ucsc.edu/cgi-bin/hgTrackUi?db=hg19&g=wgEncodeMapability>`_.

Genes and transcripts
=====================

The following plot shows the mean alignability for each transcrip, i.e, the average
mappability across all genomic positions within a transcript.

.. report:: Genemodels.GenesetMappability
   :render: line-plot
   :transform: histogram
   :tf-aggregate: normalized-total,cumulative
   :as-lines:

   Distribution of mean mappability for transcipts in each geneset.

.. report:: Genemodels.GenesetMappability
   :render: box-plot

   Distribution of mean mappability for transcipts in each geneset.


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* With the exception of GetPasswordString, this file was
   copied from NSS's cmd/lib/secutil.c hg revision 8f011395145e */

#include "nss_secutil.h"

#include "prprf.h"
#ifdef XP_WIN
#include <io.h>
#else
#include <unistd.h>
#endif

static char consoleName[] =  {
#ifdef XP_UNIX
  "/dev/tty"
#else
#ifdef XP_OS2
  "\\DEV\\CON"
#else
  "CON:"
#endif
#endif
};

#if defined(_WINDOWS)
static char * quiet_fgets (char *buf, int length, FILE *input)
{
  int c;
  char *end = buf;

  /* fflush (input); */
  memset (buf, 0, length);

  if (!isatty(fileno(input))) {
    return fgets(buf,length,input);
  }

  while (1)
  {
#if defined (_WIN32_WCE)
    c = getchar();	/* gets a character from stdin */
#else
    c = getch();	/* getch gets a character from the console */
#endif
    if (c == '\b')
    {
      if (end > buf)
        end--;
    }

    else if (--length > 0)
      *end++ = c;

    if (!c || c == '\n' || c == '\r')
      break;
  }

  return buf;
}
#endif

char *
GetPasswordString(void *arg, char *prompt)
{
  FILE *input = stdin;
  char phrase[200] = {'\0'};
  int isInputTerminal = isatty(fileno(stdin));

#ifndef _WINDOWS
  if (isInputTerminal) {
    input = fopen(consoleName, "r");
    if (input == NULL) {
      fprintf(stderr, "Error opening input terminal for read\n");
      return NULL;
    }
  }
#endif

  if (isInputTerminal) {
    fprintf(stdout, "Please enter your password:\n");
    fflush(stdout);
  }

  QUIET_FGETS (phrase, sizeof(phrase), input);

  if (isInputTerminal) {
    fprintf(stdout, "\n");
  }

#ifndef _WINDOWS
  if (isInputTerminal) {
    fclose(input);
  }
#endif

  /* Strip off the newlines if present */
  if (phrase[PORT_Strlen(phrase)-1] == '\n' ||
      phrase[PORT_Strlen(phrase)-1] == '\r') {
    phrase[PORT_Strlen(phrase)-1] = 0;
  }
  return (char*) PORT_Strdup(phrase);
}

char *
SECU_FilePasswd(PK11SlotInfo *slot, PRBool retry, void *arg)
{
  char* phrases, *phrase;
  PRFileDesc *fd;
  int32_t nb;
  char *pwFile = arg;
  int i;
  const long maxPwdFileSize = 4096;
  char* tokenName = NULL;
  int tokenLen = 0;

  if (!pwFile)
    return 0;

  if (retry) {
    return 0;  /* no good retrying - the files contents will be the same */
  }

  phrases = PORT_ZAlloc(maxPwdFileSize);

  if (!phrases) {
    return 0; /* out of memory */
  }

  fd = PR_Open(pwFile, PR_RDONLY, 0);
  if (!fd) {
    fprintf(stderr, "No password file \"%s\" exists.\n", pwFile);
    PORT_Free(phrases);
    return NULL;
  }

  nb = PR_Read(fd, phrases, maxPwdFileSize);

  PR_Close(fd);

  if (nb == 0) {
    fprintf(stderr,"password file contains no data\n");
    PORT_Free(phrases);
    return NULL;
  }

  if (slot) {
    tokenName = PK11_GetTokenName(slot);
    if (tokenName) {
      tokenLen = PORT_Strlen(tokenName);
    }
  }
  i = 0;
  do
  {
    int startphrase = i;
    int phraseLen;

    /* handle the Windows EOL case */
    while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++;
    /* terminate passphrase */
    phrases[i++] = '\0';
    /* clean up any EOL before the start of the next passphrase */
    while ( (i<nb) && (phrases[i] == '\r' || phrases[i] == '\n')) {
      phrases[i++] = '\0';
    }
    /* now analyze the current passphrase */
    phrase = &phrases[startphrase];
    if (!tokenName)
      break;
    if (PORT_Strncmp(phrase, tokenName, tokenLen)) continue;
    phraseLen = PORT_Strlen(phrase);
    if (phraseLen < (tokenLen+1)) continue;
    if (phrase[tokenLen] != ':') continue;
    phrase = &phrase[tokenLen+1];
    break;

  } while (i<nb);

  phrase = PORT_Strdup((char*)phrase);
  PORT_Free(phrases);
  return phrase;
}

char *
SECU_GetModulePassword(PK11SlotInfo *slot, PRBool retry, void *arg)
{
    char prompt[255];
    secuPWData *pwdata = (secuPWData *)arg;
    secuPWData pwnull = { PW_NONE, 0 };
    secuPWData pwxtrn = { PW_EXTERNAL, "external" };
    char *pw;

    if (pwdata == NULL)
  pwdata = &pwnull;

    if (PK11_ProtectedAuthenticationPath(slot)) {
  pwdata = &pwxtrn;
    }
    if (retry && pwdata->source != PW_NONE) {
  PR_fprintf(PR_STDERR, "Incorrect password/PIN entered.\n");
      return NULL;
    }

    switch (pwdata->source) {
    case PW_NONE:
  sprintf(prompt, "Enter Password or Pin for \"%s\":",
                   PK11_GetTokenName(slot));
  return GetPasswordString(NULL, prompt);
    case PW_FROMFILE:
  /* Instead of opening and closing the file every time, get the pw
   * once, then keep it in memory (duh).
   */
  pw = SECU_FilePasswd(slot, retry, pwdata->data);
  pwdata->source = PW_PLAINTEXT;
  pwdata->data = PL_strdup(pw);
  /* it's already been dup'ed */
  return pw;
    case PW_EXTERNAL:
  sprintf(prompt,
          "Press Enter, then enter PIN for \"%s\" on external device.\n",
    PK11_GetTokenName(slot));
  (void) GetPasswordString(NULL, prompt);
      /* Fall Through */
    case PW_PLAINTEXT:
  return PL_strdup(pwdata->data);
    default:
  break;
    }

    PR_fprintf(PR_STDERR, "Password check failed:  No password found.\n");
    return NULL;
}


text:
namespace Idecom.Bus.Implementations.Behaviors
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Interfaces;
    using Interfaces.Behaviors;
    using Telemetry;
    using Telemetry.Snaps;

    public class ChainExecutor : IChainExecutor
    {
        readonly IContainer _container;

        public ChainExecutor(IContainer container)
        {
            _container = container;
        }

        public virtual void RunWithIt(IBehaviorChain chain, IChainExecutionContext context)
        {
            using (_container.BeginUnitOfWork())
            {
                var behaviorQueue = new Queue<Type>(chain);
                IBehavior behavior = null;
                try { behavior = ExecuteNextBehavior(_container, behaviorQueue, context); }
                finally { _container.Release(behavior); }
            }
        }

        IBehavior ExecuteNextBehavior(IContainer container, Queue<Type> behaviorQueue, IChainExecutionContext context)
        {
            var nextType = behaviorQueue.Dequeue();

            IBehavior behavior = container.Resolve(nextType) as IBehavior;
            using (context.Telemetry.RecordStart(new BehaviorInvocation(behavior)))
            {

                if (behavior != null)
                    behavior.Execute(() =>
                                     {
                                         if (!behaviorQueue.Any())
                                             return;

                                         IBehavior behavior1 = null;

                                         try
                                         {
                                             behavior1 = ExecuteNextBehavior(_container, behaviorQueue, context); //context has to be a tree
                                         }
                                         finally
                                         {
                                             _container.Release(behavior1);
                                         }
                                     }, context);
            }
            return behavior;
        }
    }
}


text:
SYNONYM

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

#### Published in
Madroño 15:107, fig. 2-3. 1959

#### Original name
null

### Remarks
null


text:
<?php

namespace AcistGroup\DoaManagerBundle\Entity;

use Gedmo\Mapping\Annotation as Gedmo; // this will be like an alias for Gedmo extensions annotations
use Doctrine\ORM\Mapping\Id; // includes single annotation
use Doctrine\ORM\Mapping as ORM; // alias for doctrine ORM annotations
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * AcistGroup\DoaManagerBundle\Entity\Model
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AcistGroup\DoaManagerBundle\Entity\ModelRepository")
 * @UniqueEntity("name")
 */
class Model
{

  /**
   * @var integer $id
   *
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   */
  private $id;

  /**
   * @var string $name
   * @Assert\NotBlank()
   * @ORM\Column(name="name", type="string", length=60)
   */
  private $name;

  /**
   * @var integer $serie
   *
   * @Assert\Type(type="AcistGroup\DoaManagerBundle\Entity\Serie")
   * @ORM\ManyToOne(targetEntity="Serie", inversedBy="models")
   * @ORM\JoinColumn(name="serie_id", referencedColumnName="id", nullable=false)
   */
  private $serie;

  /**
   * @ORM\OneToMany(targetEntity="Product", mappedBy="model")
   */
  protected $products;

  /**
   * @var datetime $created
   *
   * @Gedmo\Timestampable(on="create")
   * @ORM\Column(type="datetime")
   */
  private $created;

  /**
   * @var datetime $updated
   *
   * @Gedmo\Timestampable(on="update")
   * @ORM\Column(type="datetime")
   */
  private $updated;

  /**
   * Constructor
   */
  public function __construct()
  {
    $this->products = new \Doctrine\Common\Collections\ArrayCollection();
  }

  /**
   * Get id
   *
   * @return integer
   */
  public function getId()
  {
    return $this->id;
  }

  /**
   * Set name
   *
   * @param string $name
   * @return Model
   */
  public function setName($name)
  {
    $this->name = $name;

    return $this;
  }

  /**
   * Get name
   *
   * @return string
   */
  public function getName()
  {
    return $this->name;
  }

  /**
   * Set serie
   *
   * @param AcistGroup\DoaManagerBundle\Entity\Serie $serie
   * @return Model
   */
  public function setSerie(\AcistGroup\DoaManagerBundle\Entity\Serie $serie)
  {
    $this->serie = $serie;

    return $this;
  }

  /**
   * Get serie
   *
   * @return AcistGroup\DoaManagerBundle\Entity\Serie
   */
  public function getSerie()
  {
    return $this->serie;
  }

  /**
   * Add products
   *
   * @param AcistGroup\DoaManagerBundle\Entity\Product $products
   * @return Model
   */
  public function addProduct(\AcistGroup\DoaManagerBundle\Entity\Product $products)
  {
    $this->products[] = $products;

    return $this;
  }

  /**
   * Remove products
   *
   * @param AcistGroup\DoaManagerBundle\Entity\Product $products
   */
  public function removeProduct(\AcistGroup\DoaManagerBundle\Entity\Product $products)
  {
    $this->products->removeElement($products);
  }

  /**
   * Get products
   *
   * @return Doctrine\Common\Collections\Collection
   */
  public function getProducts()
  {
    return $this->products;
  }

    /**
     * Set created
     *
     * @param  \DateTime $created
     * @return Model
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param  \DateTime $updated
     * @return Model
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }
}


text:
package org.mifos.dto.screen;

import java.io.Serializable;
import java.util.Date;
import java.util.Locale;

@SuppressWarnings("PMD")
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value={"SE_NO_SERIALVERSIONID", "EI_EXPOSE_REP", "EI_EXPOSE_REP2", "EQ_COMPARETO_USE_OBJECT_EQUALS"}, justification="should disable at filter level and also for pmd - not important for us")
public class TransactionHistoryDto implements Serializable, Comparable<TransactionHistoryDto> {

    private Date transactionDate;
    private Integer paymentId;
    private Integer accountTrxnId;
    private String type;
    private String glcode;
    private String debit = "-";
    private String credit = "-";
    private String balance;
    private String clientName = "-";
    private Date postedDate;
    private String postedBy;
    private String notes = "-";
    private Locale locale = null;
    private String userPrefferedTransactionDate;
    private String userPrefferedPostedDate;

    public Integer getAccountTrxnId() {
        return accountTrxnId;
    }

    public void setAccountTrxnId(Integer accountTrxnId) {
        this.accountTrxnId = accountTrxnId;
    }

    public String getBalance() {
        return balance;
    }

    public void setBalance(String balance) {
        this.balance = balance;
    }

    public String getClientName() {
        return clientName;
    }

    public void setClientName(String clientName) {
        this.clientName = clientName;
    }

    public String getCredit() {
        return credit;
    }

    public void setCredit(String credit) {
        this.credit = credit;
    }

    public String getDebit() {
        return debit;
    }

    public void setDebit(String debit) {
        this.debit = debit;
    }

    public String getGlcode() {
        return glcode;
    }

    public void setGlcode(String glcode) {
        this.glcode = glcode;
    }

    public Locale getLocale() {
        return locale;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    public Integer getPaymentId() {
        return paymentId;
    }

    public void setPaymentId(Integer paymentId) {
        this.paymentId = paymentId;
    }

    public String getPostedBy() {
        return postedBy;
    }

    public void setPostedBy(String postedBy) {
        this.postedBy = postedBy;
    }

    public Date getPostedDate() {
        return postedDate;
    }

    public void setPostedDate(Date postedDate) {
        this.postedDate = postedDate;
    }

    public Date getTransactionDate() {
        return transactionDate;
    }

    public void setTransactionDate(Date transactionDate) {
        this.transactionDate = transactionDate;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUserPrefferedPostedDate() {
        return userPrefferedPostedDate;
    }

    public String getUserPrefferedTransactionDate() {
        return userPrefferedTransactionDate;
    }

    public void setFinancialEnteries(Integer trxnId, Date trxnDate, String actionType, String glCode, String debit,
            String credit, Date postedDate, String notes) {
        this.accountTrxnId = trxnId;
        this.transactionDate = trxnDate;
        this.type = actionType;
        this.glcode = glCode;
        this.debit = debit;
        this.credit = credit;
        this.postedDate = postedDate;
        this.notes = notes;
    }

    public void setAccountingEnteries(Integer paymentId, String balance, String clientName, String postedBy) {
        this.paymentId = paymentId;
        this.balance = balance;
        this.clientName = clientName;
        this.postedBy = postedBy;
    }

    /*
     * This is only written for test purposes. The idea is to guarantee the
     * order in which these objects can be organized in a list - first compare
     * by postedDates, if dates are equal - 'Credit' should come before 'Debit'.
     * There is no philosophical reasoning behind this ordering, just something
     * we can count on --> this should be changed to suite a production need if
     * one exists. The tests that rely on this ordering include:
     * <b>SavingsActionStrutsTest#testSuccessfullGetTransactionHistory()</b>
     */
    public int compareTo(TransactionHistoryDto o) {
        int dateCompare = this.getPostedDate().compareTo(o.getPostedDate());
        if (dateCompare != 0) {
            return dateCompare;
        } else if (!this.getDebit().equals("-")) {
            return !o.getDebit().equals("-") ? this.getDebit().compareTo(o.getDebit()) : 1;
        } else if (!this.getCredit().equals("-")) {
            return !o.getCredit().equals("-") ? this.getCredit().compareTo(o.getCredit()) : -1;
        } else {
            return 0;
        }
    }

    public void setUserPrefferedPostedDate(String userPrefferedPostedDate) {
        this.userPrefferedPostedDate = userPrefferedPostedDate;
    }

    public void setUserPrefferedTransactionDate(String userPrefferedTransactionDate) {
        this.userPrefferedTransactionDate = userPrefferedTransactionDate;
    }
}


text:
<?php

namespace Admin\Form;

use Zend\Form\Element;
use ZfcBase\Form\ProvidesEventsForm;
use ZfcUser\Form\Base as ZfcUserBaseForm;

class AdminUserForm extends ZfcUserBaseForm
{
    public function __construct()
    {
        parent::__construct();

        $this->add(array(
            'name' => 'first_name',
            'options' => array(
                'label' => 'First Name',
            ),
            'attributes' => array(
                'type' => 'text'
            ),
        ));

        $this->add(array(
            'name' => 'last_name',
            'options' => array(
                'label' => 'Last Name',
            ),
            'attributes' => array(
                'type' => 'text'
            ),
        ));

        // @TODO: Fix this... getValidator() is a protected method.
        //$csrf = new Element\Csrf('csrf');
        //$csrf->getValidator()->setTimeout($this->getRegistrationOptions()->getUserFormTimeout());
        //$this->add($csrf);

        $this->getEventManager()->trigger('init', $this);
    }

    public function init()
    {
    }
}


text:
<?php

if (!is_callable('RandomCompat_intval')) {

    /**
     * Cast to an integer if we can, safely.
     *
     * If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
     * (non-inclusive), it will sanely cast it to an int. If you it's equal to
     * ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
     * lose precision, so the <= and => operators might accidentally let a float
     * through.
     *
     * @param int|float $number    The number we want to convert to an int
     * @param boolean   $fail_open Set to true to not throw an exception
     *
     * @return int (or float if $fail_open)
     *
     * @throws TypeError
     */
    function RandomCompat_intval($number, $fail_open = false)
    {
        if (is_numeric($number)) {
            $number += 0;
        }

        if (
            is_float($number)
            &&
            $number > ~PHP_INT_MAX
            &&
            $number < PHP_INT_MAX
        ) {
            $number = (int) $number;
        }

        if (is_int($number) || $fail_open) {
            return $number;
        }

        throw new TypeError(
            'Expected an integer.'
        );
    }
}


text:
Au programme:

* Les comparaisons
* Les instructions de branchement

## Intro

Un branchement s'effectue depuis le flot de votre code vers des symboles ou des adresses définies directement (fortement déconseillé, à la moindre modification du code source, les adresses deviennent invalides).

On va travailler avec les structures de contrôle de flot que vous connaissez des langages de programmation de plus haut niveau avec des variables de types primitifs pour plus de facilité à la traduction en assembleur.

Chaque exercice prendra un morceau de pseudo-code qui sera ensuite traduit en PEP-8.

## Exercice 1

Traduisez ce pseudo-code en assembleur

~~~nit

var x = deci

if x > 10 then
	print "> 10"
else
	print "<= 10"
end

~~~

## Exercice 2

Traduisez ce pseudo-code en assembleur

~~~nit

var x = deci

if x < 10 then
	print "< 10"
else
	print ">= 10"
end

~~~

## Exercice 3

Traduisez ce pseudo-code en assembleur

~~~nit

var min = deci
var max = deci
var nb = deci

if nb >= min and nb <= max then
	print "In bounds"
else if nb < min then
	print "Too low"
else
	print "Too high"
end

~~~

## Exercice 4

Traduisez ce pseudo-code en assembleur

~~~nit

var chr = chari

if (chr >= 'a' and chr <= 'z') or (chr >= 'A' and chr <= 'Z') then
	print "It is a letter"
else
	print "Not a letter"
end

~~~

## Exercice 5

Traduisez ce pseudo-code en assembleur

~~~nit

var chr1 = chari
var chr2 = chari

if chr1 > chr2 then
	print "chr1 > chr2"
else if chr1 < chr2 then
	print "chr1 < chr2"
else
	print "chr1 == chr2"
end

~~~

## Exercice 6

Traduisez ce pseudo-code en assembleur

~~~nit

var loops = deci

var i = 0

while i < loops do
	print "Iteration " + i
	i += 1
end

~~~

## Exercice 7

Traduisez ce pseudo-code en assembleur

~~~nit

var loops = deci

for i in [0 .. loops] do
	print "Iteration " + i
end

~~~

## Exercice 8

Traduisez ce pseudo-code en assembleur

~~~nit

var c = chari

while c != '\n' do
	if c < 'A' or c > 'z' then
		print "There was a non-letter character in the string"
		# Since there was an error, we exit with error code 1
		# This is useful in real-world programs, but in Pep/8,
		# we will just represent it with a `STOP` instruction.
		exit 1
	end
	if c > 'Z' and c < 'a' then
		print "There was a non-letter character in the string"
		exit 1
	end
	c = chari
end

print "The string contained letters only"

~~~


text:
export default function camelize(string) {
  return string.trim().replace(/[-_\s]+(.)?/g, function(match, word) {
    return word ? word.toUpperCase() : "";
  });
}


text:
from __future__ import unicode_literals

import datetime
from django.db import migrations, models
import django.utils.timezone
from django.utils.timezone import utc

class Migration(migrations.Migration):

    dependencies = [
        ('crowdsourcing', '0086_get_requester_ratings_fn_updated'),
    ]

    operations = [
        migrations.AddField(
            model_name='messagerecipient',
            name='created_at',
            field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='messagerecipient',
            name='delivered_at',
            field=models.DateTimeField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='messagerecipient',
            name='read_at',
            field=models.DateTimeField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='messagerecipient',
            name='updated_at',
            field=models.DateTimeField(auto_now=True, default=datetime.datetime(2016, 6, 6, 20, 14, 50, 357747, tzinfo=utc)),
            preserve_default=False,
        ),
    ]