text:
/******************************************************************************
 *
 * Name: hwesleep.c - ACPI Hardware Sleep/Wake Support functions for the
 *                    extended FADT-V5 sleep registers.
 *
 *****************************************************************************/

/*
 * Copyright (C) 2000 - 2013, Intel Corp.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * Alternatively, this software may be distributed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 */

#include <acpi/acpi.h>
#include <linux/acpi.h>
#include "accommon.h"

#define _COMPONENT          ACPI_HARDWARE
ACPI_MODULE_NAME("hwesleep")

/*******************************************************************************
 *
 * FUNCTION:    acpi_hw_execute_sleep_method
 *
 * PARAMETERS:  method_pathname     - Pathname of method to execute
 *              integer_argument    - Argument to pass to the method
 *
 * RETURN:      None
 *
 * DESCRIPTION: Execute a sleep/wake related method with one integer argument
 *              and no return value.
 *
 ******************************************************************************/
void acpi_hw_execute_sleep_method(char *method_pathname, u32 integer_argument)
{
	struct acpi_object_list arg_list;
	union acpi_object arg;
	acpi_status status;

	ACPI_FUNCTION_TRACE(hw_execute_sleep_method);

	/* One argument, integer_argument; No return value expected */

	arg_list.count = 1;
	arg_list.pointer = &arg;
	arg.type = ACPI_TYPE_INTEGER;
	arg.integer.value = (u64)integer_argument;

	status = acpi_evaluate_object(NULL, method_pathname, &arg_list, NULL);
	if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
		ACPI_EXCEPTION((AE_INFO, status, "While executing method %s",
				method_pathname));
	}

	return_VOID;
}

/*******************************************************************************
 *
 * FUNCTION:    acpi_hw_extended_sleep
 *
 * PARAMETERS:  sleep_state         - Which sleep state to enter
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Enter a system sleep state via the extended FADT sleep
 *              registers (V5 FADT).
 *              THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED
 *
 ******************************************************************************/

acpi_status acpi_hw_extended_sleep(u8 sleep_state)
{
	acpi_status status;
	u8 sleep_type_value;
	u64 sleep_status;

	ACPI_FUNCTION_TRACE(hw_extended_sleep);

	/* Extended sleep registers must be valid */

	if (!acpi_gbl_FADT.sleep_control.address ||
	    !acpi_gbl_FADT.sleep_status.address) {
		return_ACPI_STATUS(AE_NOT_EXIST);
	}

	/* Clear wake status (WAK_STS) */

	status =
	    acpi_write((u64)ACPI_X_WAKE_STATUS, &acpi_gbl_FADT.sleep_status);
	if (ACPI_FAILURE(status)) {
		return_ACPI_STATUS(status);
	}

	acpi_gbl_system_awake_and_running = FALSE;

	/* Flush caches, as per ACPI specification */

	ACPI_FLUSH_CPU_CACHE();

	status = acpi_os_prepare_extended_sleep(sleep_state,
						acpi_gbl_sleep_type_a,
						acpi_gbl_sleep_type_b);
	if (ACPI_SKIP(status))
		return_ACPI_STATUS(AE_OK);
	if (ACPI_FAILURE(status))
		return_ACPI_STATUS(status);

	/*
	 * Set the SLP_TYP and SLP_EN bits.
	 *
	 * Note: We only use the first value returned by the \_Sx method
	 * (acpi_gbl_sleep_type_a) - As per ACPI specification.
	 */
	ACPI_DEBUG_PRINT((ACPI_DB_INIT,
			  "Entering sleep state [S%u]\n", sleep_state));

	sleep_type_value =
	    ((acpi_gbl_sleep_type_a << ACPI_X_SLEEP_TYPE_POSITION) &
	     ACPI_X_SLEEP_TYPE_MASK);

	status = acpi_write((u64)(sleep_type_value | ACPI_X_SLEEP_ENABLE),
			    &acpi_gbl_FADT.sleep_control);
	if (ACPI_FAILURE(status)) {
		return_ACPI_STATUS(status);
	}

	/* Wait for transition back to Working State */

	do {
		status = acpi_read(&sleep_status, &acpi_gbl_FADT.sleep_status);
		if (ACPI_FAILURE(status)) {
			return_ACPI_STATUS(status);
		}

	} while (!(((u8)sleep_status) & ACPI_X_WAKE_STATUS));

	return_ACPI_STATUS(AE_OK);
}

/*******************************************************************************
 *
 * FUNCTION:    acpi_hw_extended_wake_prep
 *
 * PARAMETERS:  sleep_state         - Which sleep state we just exited
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Perform first part of OS-independent ACPI cleanup after
 *              a sleep. Called with interrupts ENABLED.
 *
 ******************************************************************************/

acpi_status acpi_hw_extended_wake_prep(u8 sleep_state)
{
	acpi_status status;
	u8 sleep_type_value;

	ACPI_FUNCTION_TRACE(hw_extended_wake_prep);

	status = acpi_get_sleep_type_data(ACPI_STATE_S0,
					  &acpi_gbl_sleep_type_a,
					  &acpi_gbl_sleep_type_b);
	if (ACPI_SUCCESS(status)) {
		sleep_type_value =
		    ((acpi_gbl_sleep_type_a << ACPI_X_SLEEP_TYPE_POSITION) &
		     ACPI_X_SLEEP_TYPE_MASK);

		(void)acpi_write((u64)(sleep_type_value | ACPI_X_SLEEP_ENABLE),
				 &acpi_gbl_FADT.sleep_control);
	}

	return_ACPI_STATUS(AE_OK);
}

/*******************************************************************************
 *
 * FUNCTION:    acpi_hw_extended_wake
 *
 * PARAMETERS:  sleep_state         - Which sleep state we just exited
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Perform OS-independent ACPI cleanup after a sleep
 *              Called with interrupts ENABLED.
 *
 ******************************************************************************/

acpi_status acpi_hw_extended_wake(u8 sleep_state)
{
	ACPI_FUNCTION_TRACE(hw_extended_wake);

	/* Ensure enter_sleep_state_prep -> enter_sleep_state ordering */

	acpi_gbl_sleep_type_a = ACPI_SLEEP_TYPE_INVALID;

	/* Execute the wake methods */

	acpi_hw_execute_sleep_method(METHOD_PATHNAME__SST, ACPI_SST_WAKING);
	acpi_hw_execute_sleep_method(METHOD_PATHNAME__WAK, sleep_state);

	/*
	 * Some BIOS code assumes that WAK_STS will be cleared on resume
	 * and use it to determine whether the system is rebooting or
	 * resuming. Clear WAK_STS for compatibility.
	 */
	(void)acpi_write((u64)ACPI_X_WAKE_STATUS, &acpi_gbl_FADT.sleep_status);
	acpi_gbl_system_awake_and_running = TRUE;

	acpi_hw_execute_sleep_method(METHOD_PATHNAME__SST, ACPI_SST_WORKING);
	return_ACPI_STATUS(AE_OK);
}


text:
<!DOCTYPE HTML>

<title>Service (Apache Ant API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2020-05-10">
<meta name="description" content="declaration: package: org.apache.tools.ant.types.spi, class: Service">
<meta name="generator" content="javadoc/ClassWriterImpl">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../script-dir/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Package org.apache.tools.ant.types.spi

Class Service

java.lang.Object

org.apache.tools.ant.ProjectComponent

org.apache.tools.ant.types.spi.Service

All Implemented Interfaces:

java.lang.Cloneable

public class Service
extends ProjectComponent

ANT Jar-Task SPI extension

See Also:

 https://issues.apache.org/bugzilla/show_bug.cgi?id=31520

Field Summary

Fields inherited from class org.apache.tools.ant.ProjectComponent

description, location, project

Constructor Summary

Constructors

Constructor
Description

Service()

Method Summary

<button role="tab" aria-selected="true" aria-controls="memberSummary_tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="activeTableTab">All Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t2" class="tableTab" onclick="show(2);">Instance Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t4" class="tableTab" onclick="show(8);">Concrete Methods</button>

Modifier and Type
Method
Description

void
addConfiguredProvider(Provider provider)

Add a nested provider element.

void
check()

Check if this object is configured correctly as a nested
 element.

java.io.InputStream
getAsStream()

Return the implementations of this
 services as an inputstream.

java.lang.String
getType()

void
setProvider(java.lang.String className)

Set the provider classname.

void
setType(java.lang.String type)

Set the service type.

Methods inherited from class org.apache.tools.ant.ProjectComponent

clone, getDescription, getLocation, getProject, log, log, setDescription, setLocation, setProject

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Details

Service

public Service()

Method Details

setProvider

public void setProvider(java.lang.String className)

Set the provider classname.

Parameters:

className - the classname of a provider of this service.

addConfiguredProvider

public void addConfiguredProvider(Provider provider)

Add a nested provider element.

Parameters:

provider - a provider element.

getType

public java.lang.String getType()

Returns:

the service type.

setType

public void setType(java.lang.String type)

Set the service type.

Parameters:

type - the service type, a classname of
             an interface or a class (normally
             abstract).

getAsStream

public java.io.InputStream getAsStream()
                                throws java.io.IOException

Return the implementations of this
 services as an inputstream.

Returns:

an inputstream of the classname names
         encoded as UTF-8.

Throws:

java.io.IOException - if there is an error.

check

public void check()

Check if this object is configured correctly as a nested
 element.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package gin

import (
	"crypto/subtle"
	"encoding/base64"
	"errors"
	"fmt"
	"sort"
)

const (
	AuthUserKey = "user"
)

type (
	Accounts map[string]string
	authPair struct {
		Value string
		User  string
	}
	authPairs []authPair
)

func (a authPairs) Len() int           { return len(a) }
func (a authPairs) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }

// Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where
// the key is the user name and the value is the password, as well as the name of the Realm
// (see http://tools.ietf.org/html/rfc2617#section-1.2)
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
	pairs, err := processAccounts(accounts)
	if err != nil {
		panic(err)
	}
	return func(c *Context) {
		// Search user in the slice of allowed credentials
		user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization"))
		if !ok {
			// Credentials doesn't match, we return 401 Unauthorized and abort request.
			if realm == "" {
				realm = "Authorization Required"
			}
			c.Writer.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", realm))
			c.Fail(401, errors.New("Unauthorized"))
		} else {
			// user is allowed, set UserId to key "user" in this context, the userId can be read later using
			// c.Get(gin.AuthUserKey)
			c.Set(AuthUserKey, user)
		}
	}
}

// Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where
// the key is the user name and the value is the password.
func BasicAuth(accounts Accounts) HandlerFunc {
	return BasicAuthForRealm(accounts, "")
}

func processAccounts(accounts Accounts) (authPairs, error) {
	if len(accounts) == 0 {
		return nil, errors.New("Empty list of authorized credentials")
	}
	pairs := make(authPairs, 0, len(accounts))
	for user, password := range accounts {
		if len(user) == 0 {
			return nil, errors.New("User can not be empty")
		}
		base := user + ":" + password
		value := "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
		pairs = append(pairs, authPair{
			Value: value,
			User:  user,
		})
	}
	// We have to sort the credentials in order to use bsearch later.
	sort.Sort(pairs)
	return pairs, nil
}

func searchCredential(pairs authPairs, auth string) (string, bool) {
	if len(auth) == 0 {
		return "", false
	}
	// Search user in the slice of allowed credentials
	r := sort.Search(len(pairs), func(i int) bool { return pairs[i].Value >= auth })
	if r < len(pairs) && secureCompare(pairs[r].Value, auth) {
		return pairs[r].User, true
	} else {
		return "", false
	}
}

func secureCompare(given, actual string) bool {
	if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
		return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
	} else {
		/* Securely compare actual to itself to keep constant time, but always return false */
		return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
	}
}


text:
package core.framework.internal.stat;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.lang.management.GarbageCollectorMXBean;
import java.time.Duration;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

/**
 * @author neo
 */
@ExtendWith(MockitoExtension.class)
class GCStatTest {
    @Mock
    GarbageCollectorMXBean bean;
    private GCStat stat;

    @BeforeEach
    void createGCStat() {
        when(bean.getName()).thenReturn("G1 Young Generation");
        stat = GCStat.of(bean);
    }

    @Test
    void collector() {
        assertThat(GCStat.collector("G1 Young Generation")).isEqualTo("young");
        assertThat(GCStat.collector("G1 Old Generation")).isEqualTo("old");
        assertThat(GCStat.collector("PS Scavenge")).isEqualTo("young");
        assertThat(GCStat.collector("PS MarkSweep")).isEqualTo("old");
        assertThat(GCStat.collector("Copy")).isNull();
    }

    @Test
    void elapsed() {
        when(bean.getCollectionTime()).thenReturn(500L, 1000L, 3000L);
        assertThat(stat.elapsed()).isEqualTo(Duration.ZERO.toNanos());
        assertThat(stat.elapsed()).isEqualTo(Duration.ofMillis(500).toNanos());
        assertThat(stat.elapsed()).isEqualTo(Duration.ofMillis(2000).toNanos());
    }

    @Test
    void count() {
        when(bean.getCollectionCount()).thenReturn(1L, 2L, 3L);
        assertThat(stat.count()).isEqualTo(0);
        assertThat(stat.count()).isEqualTo(1);
        assertThat(stat.count()).isEqualTo(1);
    }
}


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

    (function chainedm2m() {
        return {
            fireEvent: function (element, event) {
                var evt, rtn;
                if (document.createEventObject) {
                    // dispatch for IE
                    evt = document.createEventObject();
                    rtn = element.fireEvent('on' + event, evt);
                } else {
                    // dispatch for firefox + others
                    evt = document.createEvent("HTMLEvents");
                    evt.initEvent(event, true, true); // event type,bubbling,cancelable
                    rtn = !element.dispatchEvent(evt);
                }

                return rtn;
            },

            dismissRelatedLookupPopup: function(win, chosenId) {
                var name = windowname_to_id(win.name),
                    elem = document.getElementById(name);
                if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) {
                    elem.value += ',' + chosenId;
                } else {
                    elem.value = chosenId;
                }
                fireEvent(elem, 'change');
                win.close();
            },

            fill_field: function (val, initial_value, elem_id, url, initial_parent, auto_choose) {
                var $selectField = $(elem_id),
                    $selectedto = $(elem_id + '_to'),
                    cache_to = elem_id.replace('#', '') + '_to',
                    cache_from = elem_id.replace('#', '') + '_from';
                if (!$selectField.length) {
                    $selectField = $(elem_id + '_from');
                }
                function trigger_chosen_updated() {
                    if ($.fn.chosen !== undefined) {
                        $selectField.trigger('chosen:updated');
                    }
                }

                // SelectBox is a global var from djangojs "admin/js/SelectBox.js"
                // Clear cache to avoid the elements duplication
                if (typeof SelectBox !== 'undefined') {
                    if (typeof SelectBox.cache[cache_to] !== 'undefined') {
                        SelectBox.cache[cache_to].splice(0);
                    }
                    if (typeof SelectBox.cache[cache_from] !== 'undefined') {
                        SelectBox.cache[cache_from].splice(0);
                    }
                }

                if (!val || val === '') {
                    $selectField.html('');
                    $selectedto.html('');
                    trigger_chosen_updated();
                    return;
                }

                // Make sure that these are always an arrays
                val = [].concat(val);
                initial_parent = [].concat(initial_parent);

                var target_url = url + "/" + val + "/",
                    options = [],
                    selectedoptions = [];

                $.getJSON(target_url, function (j) {
                    var i, width;
                    auto_choose = j.length === 1 && auto_choose;

                    var selected_values = {};
                    // if val and initial_parent have any common values, we need to set selected options.
                    if ($(val).filter(initial_parent).length >= 0 && initial_value) {
                        for (i = 0; i < initial_value.length; i = i + 1) {
                            selected_values[initial_value[i]] = true;
                        }
                    }

                    // select values which were previously selected (for many2many - many2many chain)
                    $(elem_id + ' option:selected').each(function () {
                        selected_values[$(this).val()] = true;
                    });

                    $.each(j, function (index, optionData) {
                        var option = $('<option></option>')
                            .attr('value', optionData.value)
                            .text(optionData.display)
                            .attr('title', optionData.display);
                        if (auto_choose === "true" || auto_choose === "True") {
                            auto_choose = true;
                        } else if (auto_choose === "false" || auto_choose === "False") {
                            auto_choose = false;
                        }
                        if (auto_choose || selected_values[optionData.value] === true) {
                            if ($selectedto.length) {
                                selectedoptions.push(option);
                            } else {
                                option.prop('selected', true);
                                options.push(option);
                            }
                        } else {
                            options.push(option);
                        }
                    });

                    $selectField.html(options);
                    if ($selectedto.length) {
                        $selectedto.html(selectedoptions);
                        // SelectBox is a global var from djangojs "admin/js/SelectBox.js"
                        for (i = 0, j = selectedoptions.length; i < j; i = i + 1) {
                            node = selectedoptions[i];
                            SelectBox.cache[cache_to].push({value: node.prop("value"), text: node.prop("text"), displayed: 1});
                        }
                        for (i = 0, j = options.length; i < j; i = i + 1) {
                            node = options[i];
                            SelectBox.cache[cache_from].push({value: node.prop("value"), text: node.prop("text"), displayed: 1});
                        }
                    }
                    width = $selectField.outerWidth();
                    if (navigator.appVersion.indexOf("MSIE") !== -1) {
                        $selectField.width(width + 'px');
                    }

                    $selectField.trigger('change');

                    trigger_chosen_updated();
                });
            },

            init: function (chainfield, url, id, value, auto_choose) {
                var fill_field, val, initial_parent = $(chainfield).val(),
                    initial_value = value;

                if (!$(chainfield).hasClass("chained")) {
                    val = $(chainfield).val();
                    this.fill_field(val, initial_value, id, url, initial_parent, auto_choose);
                }
                fill_field = this.fill_field;
                $(chainfield).change(function () {
                    var prefix, start_value, this_val, localID = id;
                    if (localID.indexOf("__prefix__") > -1) {
                        prefix = $(this).attr("id").match(/\d+/)[0];
                        localID = localID.replace("__prefix__", prefix);
                    }

                    start_value = $(localID).val();
                    this_val = $(this).val();
                    fill_field(this_val, initial_value, localID, url, initial_parent, auto_choose);
                });

                // allait en bas, hors du documentready
                if (typeof(dismissAddAnotherPopup) !== 'undefined') {
                    var oldDismissAddAnotherPopup = dismissAddAnotherPopup;
                    dismissAddAnotherPopup = function (win, newId, newRepr) {
                        oldDismissAddAnotherPopup(win, newId, newRepr);
                        if ("#" + windowname_to_id(win.name) === chainfield) {
                            $(chainfield).change();
                        }
                    };
                }
                if (typeof(dismissRelatedLookupPopup) !== 'undefined') {
                    var oldDismissRelatedLookupPopup = dismissRelatedLookupPopup;
                    dismissRelatedLookupPopup = function (win, chosenId) {
                        oldDismissRelatedLookupPopup(win, chosenId);
                        if ("#" + windowname_to_id(win.name) === chainfield) {
                            $(chainfield).change();
                        }
                    };
                }
            }
        };
    }());
}(jQuery || django.jQuery));


text:
(function ($) {
    $('.navbar-burger').click(function () {
        $(this).toggleClass('is-active');
        $('.navbar-main .navbar-start').toggleClass('is-active');
        $('.navbar-main .navbar-end').toggleClass('is-active');
    });

    // Hide Header on on scroll down
    var didScroll;
    var lastScrollTop = 0;
    var delta = 5;
    var navbarHeight = $('.navbar-main').outerHeight();

    $(window).scroll(function(event){
        didScroll = true;
    });

    setInterval(function() {
        if (didScroll) {
            hasScrolled();
            didScroll = false;
        }
    }, 250);

    function hasScrolled() {
        var st = $(this).scrollTop();

        // Make sure they scroll more than delta
        if(Math.abs(lastScrollTop - st) <= delta) {
            return;
        }

        // If they scrolled down and are past the navbar, add class .navbar-down.
        // This is necessary so you never see what is "behind" the navbar.
        if (st > lastScrollTop && st > navbarHeight) {
            var posY = Math.min(st, navbarHeight);
            // Scroll Down
            $('.navbar-main').css({
                '-webkit-transform' : 'translateY(-' + posY + 'px)',
                '-moz-transform'    : 'translateY(-' + posY + 'px)',
                '-ms-transform'     : 'translateY(-' + posY + 'px)',
                '-o-transform'      : 'translateY(-' + posY + 'px)',
                'transform'         : 'translateY(-' + posY + 'px)'
            });
        } else {
            // Scroll Up
            if(st + $(window).height() < $(document).height()) {
                $('.navbar-main').css({
                    '-webkit-transform' : 'translateY(0px)',
                    '-moz-transform'    : 'translateY(0px)',
                    '-ms-transform'     : 'translateY(0px)',
                    '-o-transform'      : 'translateY(0px)',
                    'transform'         : 'translateY(0px)'
                });
            }
        }

        lastScrollTop = st;
    }

    $('.article.gallery img:not(".not-gallery-item")').each(function () {
        // wrap images with link and add caption if possible
        if ($(this).parent('a').length === 0) {
            $(this).wrap('');
            if (this.alt) {
                $(this).after('
' + this.alt + '
');
            }
        }
    });

    $('.article-entry').find('h1, h2, h3, h4, h5, h6').on('click', function () {
        if ($(this).get(0).id) {
            window.location.hash = $(this).get(0).id;
        }
    });

    if (typeof(moment) === 'function') {
        $('.article-meta time').each(function () {
            $(this).text(moment($(this).attr('datetime')).fromNow());
        });
    }
})(jQuery);


text:
package org.thehellnet.mobile.myinfos.fragment;

import static android.content.Context.TELEPHONY_SERVICE;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import org.thehellnet.mobile.myinfos.R;

public class SIMFragment extends AbstractFragment {

    private static final String TAG = SIMFragment.class.getName();

    private int simNumber = 1;

    private TelephonyManager telephonyManager;
    private SubscriptionManager subscriptionManager;

    private EditText iccid;
    private EditText country;
    private EditText operator;
    private EditText number;
    private EditText carrier;
    private EditText subscriber;

    public SIMFragment() {
    }

    public SIMFragment(int simNumber) {
        this.simNumber = simNumber;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_sim;
    }

    @Override
    protected void initVars(View view) {
        telephonyManager = (TelephonyManager) applicationContext.getSystemService(TELEPHONY_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            subscriptionManager = (SubscriptionManager) applicationContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
        }

        iccid = view.findViewById(R.id.sim_iccid_value);
        country = view.findViewById(R.id.sim_country_value);
        operator = view.findViewById(R.id.sim_operator_value);
        number = view.findViewById(R.id.number_value);
        carrier = view.findViewById(R.id.carrier_value);
        subscriber = view.findViewById(R.id.subscriber_value);
    }

    @SuppressLint("HardwareIds")
    @Override
    protected void computeValues() throws SecurityException {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                SubscriptionInfo activeSubscriptionInfo = subscriptionManager.getActiveSubscriptionInfo(simNumber);

                if (activeSubscriptionInfo != null) {
                    updateEditTextValue(iccid, activeSubscriptionInfo.getIccId());
                    updateEditTextValue(country, activeSubscriptionInfo.getCountryIso());
                    updateEditTextValue(operator, activeSubscriptionInfo.getDisplayName().toString());
                    updateEditTextValue(number, activeSubscriptionInfo.getNumber());
                    updateEditTextValue(carrier, activeSubscriptionInfo.getCarrierName().toString());
                    updateEditTextValue(subscriber, telephonyManager.getSubscriberId());
                }
            } else {
                updateEditTextValue(iccid, telephonyManager.getSimSerialNumber());
                updateEditTextValue(country, telephonyManager.getSimCountryIso());
                updateEditTextValue(operator, telephonyManager.getSimOperatorName());
                updateEditTextValue(number, telephonyManager.getLine1Number());
                updateEditTextValue(carrier, telephonyManager.getNetworkOperatorName());
                updateEditTextValue(subscriber, telephonyManager.getSubscriberId());
            }
        } catch (SecurityException e) {
            Log.e(TAG, e.getMessage());
        }
    }
}


text:
function(spiffs_create_partition_image partition base_dir)
    set(options FLASH_IN_PROJECT)
    set(multi DEPENDS)
    cmake_parse_arguments(arg "${options}" "" "${multi}" "${ARGN}")

    idf_build_get_property(idf_path IDF_PATH)
    set(spiffsgen_py ${PYTHON} ${idf_path}/components/spiffs/spiffsgen.py)

    get_filename_component(base_dir_full_path ${base_dir} ABSOLUTE)

    partition_table_get_partition_info(size "--partition-name ${partition}" "size")
    partition_table_get_partition_info(offset "--partition-name ${partition}" "offset")

    if("${size}" AND "${offset}")
        set(image_file ${CMAKE_BINARY_DIR}/${partition}.bin)

        if(CONFIG_SPIFFS_USE_MAGIC)
            set(use_magic "--use-magic")
        endif()

        if(CONFIG_SPIFFS_USE_MAGIC_LENGTH)
            set(use_magic_len "--use-magic-len")
        endif()

        if(CONFIG_SPIFFS_FOLLOW_SYMLINKS)
            set(follow_symlinks "--follow-symlinks")
        endif()

        # Execute SPIFFS image generation; this always executes as there is no way to specify for CMake to watch for
        # contents of the base dir changing.
        add_custom_target(spiffs_${partition}_bin ALL
            COMMAND ${spiffsgen_py} ${size} ${base_dir_full_path} ${image_file}
            --page-size=${CONFIG_SPIFFS_PAGE_SIZE}
            --obj-name-len=${CONFIG_SPIFFS_OBJ_NAME_LEN}
            --meta-len=${CONFIG_SPIFFS_META_LENGTH}
            ${follow_symlinks}
            ${use_magic}
            ${use_magic_len}
            DEPENDS ${arg_DEPENDS}
            )

        set_property(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" APPEND PROPERTY
            ADDITIONAL_MAKE_CLEAN_FILES
            ${image_file})

        idf_component_get_property(main_args esptool_py FLASH_ARGS)
        idf_component_get_property(sub_args esptool_py FLASH_SUB_ARGS)
        # Last (optional) parameter is the encryption for the target. In our
        # case, spiffs is not encrypt so pass FALSE to the function.
        esptool_py_flash_target(${partition}-flash "${main_args}" "${sub_args}" ALWAYS_PLAINTEXT)
        esptool_py_flash_to_partition(${partition}-flash "${partition}" "${image_file}")

        add_dependencies(${partition}-flash spiffs_${partition}_bin)

        if(arg_FLASH_IN_PROJECT)
            esptool_py_flash_to_partition(flash "${partition}" "${image_file}")
            add_dependencies(flash spiffs_${partition}_bin)
        endif()
    else()
        set(message "Failed to create SPIFFS image for partition '${partition}'. "
                    "Check project configuration if using the correct partition table file.")
        fail_at_build_time(spiffs_${partition}_bin "${message}")
    endif()
endfunction()


text:
package newrelic

import (
	"testing"
	"time"

	"github.com/newrelic/go-agent/internal"
	"github.com/newrelic/go-agent/internal/cat"
)

func TestShouldSaveTrace(t *testing.T) {
	for _, tc := range []struct {
		name          string
		expected      bool
		synthetics    bool
		tracerEnabled bool
		collectTraces bool
		duration      time.Duration
		threshold     time.Duration
	}{
		{
			name:          "insufficient duration, all disabled",
			expected:      false,
			synthetics:    false,
			tracerEnabled: false,
			collectTraces: false,
			duration:      1 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "insufficient duration, only synthetics enabled",
			expected:      true,
			synthetics:    true,
			tracerEnabled: false,
			collectTraces: false,
			duration:      1 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "insufficient duration, only tracer enabled",
			expected:      false,
			synthetics:    false,
			tracerEnabled: true,
			collectTraces: false,
			duration:      1 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "insufficient duration, only collect traces enabled",
			expected:      false,
			synthetics:    false,
			tracerEnabled: false,
			collectTraces: true,
			duration:      1 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "insufficient duration, all normal flags enabled",
			expected:      false,
			synthetics:    false,
			tracerEnabled: true,
			collectTraces: true,
			duration:      1 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "insufficient duration, all flags enabled",
			expected:      true,
			synthetics:    true,
			tracerEnabled: true,
			collectTraces: true,
			duration:      1 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "sufficient duration, all disabled",
			expected:      false,
			synthetics:    false,
			tracerEnabled: false,
			collectTraces: false,
			duration:      3 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "sufficient duration, only synthetics enabled",
			expected:      true,
			synthetics:    true,
			tracerEnabled: false,
			collectTraces: false,
			duration:      3 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "sufficient duration, only tracer enabled",
			expected:      false,
			synthetics:    false,
			tracerEnabled: true,
			collectTraces: false,
			duration:      3 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "sufficient duration, only collect traces enabled",
			expected:      false,
			synthetics:    false,
			tracerEnabled: false,
			collectTraces: true,
			duration:      3 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "sufficient duration, all normal flags enabled",
			expected:      true,
			synthetics:    false,
			tracerEnabled: true,
			collectTraces: true,
			duration:      3 * time.Second,
			threshold:     2 * time.Second,
		},
		{
			name:          "sufficient duration, all flags enabled",
			expected:      true,
			synthetics:    true,
			tracerEnabled: true,
			collectTraces: true,
			duration:      3 * time.Second,
			threshold:     2 * time.Second,
		},
	} {
		txn := &txn{}
		txn.Config.TransactionTracer.Enabled = tc.tracerEnabled
		txn.Config.TransactionTracer.Threshold.Duration = tc.threshold
		txn.Reply = &internal.ConnectReply{CollectTraces: tc.collectTraces}
		txn.Duration = tc.duration
		if tc.synthetics {
			txn.CrossProcess.Synthetics = &cat.SyntheticsHeader{}
			txn.CrossProcess.SetSynthetics(tc.synthetics)
		}

		if actual := txn.shouldSaveTrace(); actual != tc.expected {
			t.Errorf("%s: unexpected shouldSaveTrace value; expected %v; got %v", tc.name, tc.expected, actual)
		}
	}
}


text:
namespace PALAST
{
    partial class AddonList
    {
        /// <summary>
        /// Erforderliche Designervariable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Verwendete Ressourcen bereinigen.
        /// </summary>
        /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Vom Komponenten-Designer generierter Code

        /// <summary>
        /// Erforderliche Methode für die Designerunterstützung.
        /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AddonList));
            this._Listbox = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
            //
            // _Listbox
            //
            this._Listbox.BackColor = System.Drawing.SystemColors.Window;
            this._Listbox.BorderStyle = System.Windows.Forms.BorderStyle.None;
            resources.ApplyResources(this._Listbox, "_Listbox");
            this._Listbox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this._Listbox.FormattingEnabled = true;
            this._Listbox.Name = "_Listbox";
            this._Listbox.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
            this._Listbox.MouseClick += new System.Windows.Forms.MouseEventHandler(this._Listbox_MouseClick);
            this._Listbox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this._Listbox_DrawItem);
            this._Listbox.SelectedIndexChanged += new System.EventHandler(this._Listbox_SelectedIndexChanged);
            this._Listbox.KeyDown += new System.Windows.Forms.KeyEventHandler(this._Listbox_KeyDown);
            //
            // AddonList
            //
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this._Listbox);
            this.DoubleBuffered = true;
            this.Name = "AddonList";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.ListBox _Listbox;

    }
}


text:
'use strict';
/* global django */

(function ($) {
    window.dismissPopupAndReload = function (win) {
        document.location.reload();
        win.close();
    };
    window.dismissRelatedImageLookupPopup = function (win, chosenId, chosenThumbnailUrl, chosenDescriptionTxt) {
        var name = window.windowname_to_id(win.name);
        var img_name = name + '_thumbnail_img';
        var txt_name = name + '_description_txt';
        var clear_name = name + '_clear';
        var elem = document.getElementById(name);
        var old_id = elem.value;
        document.getElementById(name).value = chosenId;
        document.getElementById(img_name).src = chosenThumbnailUrl;
        document.getElementById(txt_name).innerHTML = chosenDescriptionTxt;
        document.getElementById(clear_name).style.display = 'inline';
        if (old_id !== chosenId) {
            $(elem).trigger('change');
        }
        win.close();
    };
    window.dismissRelatedFolderLookupPopup = function (win, chosenId, chosenName) {
        var id = window.windowname_to_id(win.name);
        var id_name = id + '_description_txt';
        document.getElementById(id).value = chosenId;
        document.getElementById(id_name).innerHTML = chosenName;
        win.close();
    };
})(django.jQuery);


text:
<?php

namespace Concrete\Core\User;

use Concrete\Core\Application\UserInterface\Dashboard\Navigation\NavigationCache;
use Concrete\Core\Config\Repository\Repository;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\Database\Query\LikeBuilder;
use Concrete\Core\Entity\Notification\GroupSignupNotification;
use Concrete\Core\Entity\User\GroupSignup;
use Concrete\Core\Foundation\ConcreteObject;
use Concrete\Core\Http\Request;
use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerFactory;
use Concrete\Core\Notification\Type\GroupSignupType;
use Concrete\Core\Permission\Access\Entity\GroupEntity;
use Concrete\Core\Session\SessionValidator;
use Concrete\Core\Support\Facade\Application;
use Concrete\Core\User\Group\Group;
use Concrete\Core\Authentication\AuthenticationType;
use Concrete\Core\Page\Page;
use Concrete\Core\User\Group\GroupList;
use Concrete\Core\User\Group\GroupRepository;
use Concrete\Core\User\Group\GroupRole;
use Concrete\Core\Permission\Access\Entity\Entity as PermissionAccessEntity;
use Concrete\Core\Encryption\PasswordHasher;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;

class User extends ConcreteObject
{
    public $uID = '';
    public $uName = '';
    public $uGroups = [];
    public $superUser = false;
    public $uTimezone = null;
    protected $uDefaultLanguage = null;
    // an associative array of all access entity objects that are associated with this user.
    protected $accessEntities = null;
    protected $hasher;
    protected $uLastPasswordChange;

    /** Return an User instance given its id (or null if it's not found)
     * @param int $uID The id of the user
     * @param bool $login = false Set to true to make the user the current one
     * @param bool $cacheItemsOnLogin = false Set to true to cache some items when $login is true
     *
     * @return User|null
     */
    public static function getByUserID($uID, $login = false, $cacheItemsOnLogin = true)
    {
        $app = Application::getFacadeApplication();
        $db = $app['database']->connection();

        $v = [$uID];
        $q = 'SELECT uID, uName, uIsActive, uLastOnline, uTimezone, uDefaultLanguage, uLastPasswordChange FROM Users WHERE uID = ? LIMIT 1';
        $r = $db->query($q, $v);
        $row = $r ? $r->fetch() : null;
        $nu = null;
        if ($row) {
            $nu = new static();
            $nu->setPropertiesFromArray($row);
            $nu->uGroups = $nu->_getUserGroups(true);
            $nu->superUser = ($nu->getUserID() == USER_SUPER_ID);
            if ($login) {
                $nu->persist($cacheItemsOnLogin);
                $nu->recordLogin();
                $app = Application::getFacadeApplication();
                /** @var NavigationCache $navigationCache */
                $navigationCache = $app->make(NavigationCache::class);
                $navigationCache->clear();
            }
        }

        return $nu;
    }

    /**
     * @param int $uID
     *
     * @return User
     */
    public static function loginByUserID($uID)
    {
        return static::getByUserID($uID, true);
    }

    /**
     * @deprecated
     * Use isRegistered() instead
     */
    public static function isLoggedIn()
    {
        $app = Application::getFacadeApplication();
        $u = $app->make(User::class);
        return $u->isRegistered();
    }

    /**
     * @return bool
     */
    public function checkLogin()
    {
        $app = Application::getFacadeApplication();
        $session = $app['session'];
        $config = $app['config'];

        $aeu = $config->get('concrete.misc.access_entity_updated');
        if ($aeu && $aeu > $session->get('accessEntitiesUpdated')) {
            $this->refreshUserGroups();
        }

        $invalidate = $app->make('Concrete\Core\Session\SessionValidatorInterface')->handleSessionValidation($session);
        if ($invalidate) {
            $this->loadError(USER_SESSION_EXPIRED);
        }

        if ($session->get('uID') > 0) {
            $db = $app['database']->connection();

            $row = $db->GetRow('select * from Users where uID = ? and uName = ?', [$session->get('uID'), $session->get('uName')]);
            $checkUID = (isset($row['uID'])) ? ($row['uID']) : (false);

            if ($checkUID == $session->get('uID')) {
                if (!$row['uIsActive']) {
                    return false;
                }

                if ($row['uLastPasswordChange'] > $session->get('uLastPasswordChange')) {
                    $this->loadError(USER_SESSION_EXPIRED);

                    return false;
                }

                if (!empty($row['uIsPasswordReset'])) {
                    return false;
                }

                $session->set('uOnlineCheck', time());
                if (($session->get('uOnlineCheck') - $session->get('uLastOnline') > (ONLINE_NOW_TIMEOUT / 2))) {
                    // This code throttles the writing of uLastOnline to the database, so that we're not constantly
                    // updating the Users table. If you need to have the exact up to date metric on when a session
                    // last looked at a page, use uOnlineCheck.
                    $db->query('update Users set uLastOnline = ? where uID = ?', [$session->get('uOnlineCheck'), $this->uID]);
                    $session->set('uLastOnline', $session->get('uOnlineCheck'));
                }

                return true;
            } else {
                return false;
            }
        }

        return false;
    }

    /**
     * @return UserInfo|null
     */
    public function getUserInfoObject()
    {
        return UserInfo::getByID($this->uID);
    }

    public function __construct()
    {
        $app = Application::getFacadeApplication();
        $args = func_get_args();
        $config = $app['config'];
        $session = $app['session'];
        $validator = $app->make(SessionValidator::class);
        // We need to check for the cookie so that we don't auto create a session when this runs super early.
        if (isset($args[1])) {
            // first, we check to see if the username and password match the admin username and password
            // $username = uName normally, but if not it's email address

            $username = $args[0];
            $password = $args[1];
            $disableLogin = isset($args[2]) ? (bool) $args[2] : false;
            if (!$disableLogin) {
                $session->migrate();
                $session->remove('uGroups');
                $session->remove('accessEntities');
            }
            $v = [$username];
            if ($config->get('concrete.user.registration.email_registration')) {
                $q = 'select uID, uName, uIsActive, uIsValidated, uTimezone, uDefaultLanguage, uPassword, uLastPasswordChange, uIsPasswordReset from Users where uEmail = ?';
            } else {
                $q = 'select uID, uName, uIsActive, uIsValidated, uTimezone, uDefaultLanguage, uPassword, uLastPasswordChange, uIsPasswordReset from Users where uName = ?';
            }

            $hasher = $app->make(PasswordHasher::class);
            $db = $app->make('Concrete\Core\Database\Connection\Connection');
            $r = $db->query($q, $v);
            if ($r) {
                $row = $r->fetch();
                if ($row) {
                    $pw_is_valid_legacy = false;
                    if ($config->get('concrete.user.password.legacy_salt')) {
                        $pw_is_valid_legacy = self::legacyEncryptPassword($password) === $row['uPassword'];
                    }

                    $pw_is_valid = $pw_is_valid_legacy || $hasher->checkPassword($password, $row['uPassword']);
                    if ($pw_is_valid && $hasher->needsRehash($row['uPassword'])) {
                        $em = $app->make(EntityManagerInterface::class);

                        try {
                            $em->transactional(function (EntityManagerInterface $em) use ($hasher, $password, $row) {
                                $user = $em->find(\Concrete\Core\Entity\User\User::class, $row['uID']);
                                if (!$user) {
                                    throw new \RuntimeException('User not found.');
                                }

                                $user->setUserPassword($hasher->hashPassword($password));
                            });
                        } catch (\Throwable $e) {
                            $app->make(LoggerInterface::class)->emergency('Unable to rehash password for user {user} ({id}): {message}', [
                                'user' => $row['uName'],
                                'id' => $row['uID'],
                                'message' => $e->getMessage(),
                            ]);
                        }
                    }

                    if ($row['uID'] && $row['uIsValidated'] === '0' && $config->get(
                            'concrete.user.registration.validate_email'
                        )) {
                        $this->loadError(USER_NON_VALIDATED);
                    } elseif ($row['uID'] && $row['uIsActive'] && $pw_is_valid) {
                        if ($row['uIsPasswordReset']) {
                            $this->loadError(USER_PASSWORD_RESET);
                        } elseif ($this->isPasswordExpired($db, $config, $row['uLastPasswordChange'])) {
                            $this->loadError(USER_PASSWORD_EXPIRED);
                        } else {
                            $this->uID = $row['uID'];
                            $this->uName = $row['uName'];
                            $this->uIsActive = $row['uIsActive'];
                            $this->uTimezone = $row['uTimezone'];
                            $this->uDefaultLanguage = $row['uDefaultLanguage'];
                            $this->uLastPasswordChange = $row['uLastPasswordChange'];
                            $this->uGroups = $this->_getUserGroups($disableLogin);
                            if ($row['uID'] == USER_SUPER_ID) {
                                $this->superUser = true;
                            } else {
                                $this->superUser = false;
                            }
                            $this->recordLogin();
                            if (!$disableLogin) {
                                $this->persist();
                            }
                        }
                    } elseif ($row['uID'] && !$row['uIsActive']) {
                        $this->loadError(USER_INACTIVE);
                    } else {
                        $this->loadError(USER_INVALID);
                    }
                } else {
                    $this->loadError(USER_INVALID);
                }
            } else {
                $hasher->hashPassword($password); // HashPassword and CheckPassword are slow functions.
                // We run one here just take time.
                // Without it an attacker would be able to tell that the
                // username doesn't exist using a timing attack.
                $this->loadError(USER_INVALID);
            }
        } else {
            $req = Request::getInstance();
            $this->uID = null;
            $this->uName = null;
            $this->superUser = false;
            $this->uDefaultLanguage = null;
            $this->uTimezone = null;
            if ($req->hasCustomRequestUser()) {
                $ux = $req->getCustomRequestUser();
                if ($ux && is_object($ux)) {
                    $this->uID = $ux->getUserID();
                    $this->uName = $ux->getUserName();
                    $this->superUser = $ux->getUserID() == USER_SUPER_ID;
                    if ($ux->getUserDefaultLanguage()) {
                        $this->uDefaultLanguage = $ux->getUserDefaultLanguage();
                    }
                    $this->uTimezone = $ux->getUserTimezone();
                } elseif ($ux === -1) {
                    $this->uID = 0;
                    $this->uName = t('Guest');
                }
                $this->uGroups = $this->_getUserGroups(true);
            } elseif ($validator->hasActiveSession() || $this->uID) {
                if ($session->has('uID')) {
                    $this->uID = $session->get('uID');
                    $this->uName = $session->get('uName');
                    $this->uTimezone = $session->get('uTimezone');
                    if ($session->has('uDefaultLanguage')) {
                        $this->uDefaultLanguage = $session->get('uDefaultLanguage');
                    }
                    $this->superUser = ($session->get('uID') == USER_SUPER_ID) ? true : false;
                }
                $this->uGroups = $this->_getUserGroups();
                if (!isset($args[2]) && !$req->hasCustomRequestUser()) {
                    $session->set('uGroups', $this->uGroups);
                }
            }
        }
    }

    /**
     * Increment number of logins and update login timestamps.
     *
     * @throws \Exception
     */
    public function recordLogin()
    {
        $app = Application::getFacadeApplication();
        $db = $app['database']->connection();
        $uLastLogin = $db->getOne('select uLastLogin from Users where uID = ?', [$this->uID]);

        // Add a log entry
        $logger = $app->make(LoggerFactory::class)->createLogger(Channels::CHANNEL_AUTHENTICATION);
        $logger->info(t('Login from user {user} (ID {id}) succeeded'), [
            'user' => $this->getUserName(),
            'id' => $this->getUserID(),
        ]);

        /** @var \Concrete\Core\Permission\IPService $iph */
        $iph = $app->make('helper/validation/ip');
        $ip = $iph->getRequestIP();
        $db->query('update Users set uLastIP = ?, uLastLogin = ?, uPreviousLogin = ?, uNumLogins = uNumLogins + 1 where uID = ?', [($ip === false) ? ('') : ($ip->getIp()), time(), $uLastLogin, $this->uID]);
    }

    /**
     * $salt is retained for compatibilty with older versions of concerete5, but not used.
     *
     * @param string $uPassword
     * @param null $salt
     *
     * @return string
     */
    public function encryptPassword($uPassword, $salt = null)
    {
        return app(PasswordHasher::class)->hashPassword($uPassword);
    }

    /**
     * This is for compatibility with passwords generated in older versions of concrete5.
     * Use only for checking password hashes, not generating new ones to store.
     *
     * @param string $uPassword
     *
     * @return string
     */
    public function legacyEncryptPassword($uPassword)
    {
        $app = Application::getFacadeApplication();

        return md5($uPassword . ':' . $app['config']->get('concrete.user.password.legacy_salt'));
    }

    /**
     * @return bool
     */
    public function isActive()
    {
        return isset($this->uIsActive) ? $this->uIsActive : null;
    }

    /**
     * @return bool
     */
    public function isSuperUser()
    {
        return $this->superUser;
    }

    /**
     * @return int|null
     */
    public function getLastOnline()
    {
        return isset($this->uLastOnline) ? $this->uLastOnline : null;
    }

    /**
     * @return string|null
     */
    public function getUserName()
    {
        return $this->uName;
    }

    /**
     * @return bool
     */
    public function isRegistered()
    {
        return $this->getUserID() > 0;
    }

    /**
     * @return string
     */
    public function getUserID()
    {
        return $this->uID;
    }

    /**
     * @return string|null
     */
    public function getUserTimezone()
    {
        return $this->uTimezone;
    }

    /**
     * Return date in yyyy-mm-dd H:i:s format.
     *
     * @return string
     */
    public function getUserSessionValidSince()
    {
        return $this->uLastPasswordChange;
    }

    /**
     * @param string $authType
     *
     * @throws \Exception
     */
    public function setAuthTypeCookie($authType)
    {
        $app = Application::getFacadeApplication();
        $at = AuthenticationType::getByHandle($authType);
        $token = $at->getController()->buildHash($this);
        $value = new PersistentAuthentication\CookieValue((int)$this->getUserID(), $authType, $token);
        $app->make(PersistentAuthentication\CookieService::class)->setCookie($value);
    }

    /**
     * @param AuthenticationType $at
     */
    public function setLastAuthType(AuthenticationType $at)
    {
        $app = Application::getFacadeApplication();
        $db = $app['database']->connection();
        $db->Execute('UPDATE Users SET uLastAuthTypeID=? WHERE uID=?', [$at->getAuthenticationTypeID(), $this->getUserID()]);
    }

    /**
     * @return int
     */
    public function getLastAuthType()
    {
        $app = Application::getFacadeApplication();
        $db = $app['database']->connection();
        $id = $db->getOne('SELECT uLastAuthTypeID FROM Users WHERE uID=?', [$this->getUserID()]);

        return intval($id);
    }

    public function unloadAuthenticationTypes()
    {
        $ats = AuthenticationType::getList();
        foreach ($ats as $at) {
            $at->controller->deauthenticate($this);
        }
    }

    /**
     * @param bool $hard
     */
    public function logout($hard = true)
    {
        $app = Application::getFacadeApplication();
        $events = $app['director'];
        $logger = $app->make(LoggerFactory::class)->createLogger(Channels::CHANNEL_AUTHENTICATION);
        $logger->info(t('Logout from user {user} (ID {id}) requested'), [
            'user' => $this->getUserName(),
            'id' => $this->getUserID(),
        ]);

        // First, we check to see if we have any collection in edit mode
        $this->unloadCollectionEdit();
        $this->unloadAuthenticationTypes();

        $this->invalidateSession($hard);
        $app->singleton(User::class, function () {
            return new User();
        });
        $events->dispatch('on_user_logout');

        $app = Application::getFacadeApplication();
        /** @var NavigationCache $navigationCache */
        $navigationCache = $app->make(NavigationCache::class);
        $navigationCache->clear();
    }

    /**
     * @param bool $hard
     */
    public function invalidateSession($hard = true)
    {
        $app = Application::getFacadeApplication();
        $session = $app['session'];
        $config = $app['config'];
        $cookie = $app['cookie'];

        // @todo remove this hard option if `Session::clear()` does what we need.
        if (!$hard) {
            $session->clear();
        } else {
            $session->invalidate();
            // Really not sure why this doesn't happen with invalidate, but oh well.
            $cookie->clear($config->get('concrete.session.name'));
        }

        if ($cookie->has('ConcreteSitemapTreeID')) {
            $cookie->clear('ConcreteSitemapTreeID');
        }

        $app->make(PersistentAuthentication\CookieService::class)->deleteCookie();

        $loginCookie = sprintf('%s_LOGIN', $app['config']->get('concrete.session.name'));
        if ($cookie->has($loginCookie) && $cookie->get($loginCookie)) {
            $cookie->clear($loginCookie, 1);
        }
    }

    public static function verifyAuthTypeCookie()
    {
        $app = Application::getFacadeApplication();
        $cookie = $app->make(PersistentAuthentication\CookieService::class)->getCookie();
        if ($cookie === null) {
            return;
        }
        $at = AuthenticationType::getByHandle($cookie->getAuthenticationTypeHandle());
        $u = self::getByUserID($cookie->getUserID());
        if ($u === null || $u->isError()) {
            return;
        }
        if ($at->controller->verifyHash($u, $cookie->getToken())) {
            self::loginByUserID($cookie->getUserID());
        }
    }

    /**
     * Returns an array of Group objects the user belongs to.
     *
     * @return array
     */
    public function getUserGroupObjects()
    {
        $gs = new GroupList();
        $gs->filterByUserID($this->uID);

        return $gs->getResults();
    }

    /**
     * Returns an array of group ids the user belongs to.
     *
     * @return array
     */
    public function getUserGroups()
    {
        return $this->uGroups;
    }

    /**
     * Sets a default language for a user record.
     *
     * @param string $lang
     */
    public function setUserDefaultLanguage($lang)
    {
        $app = Application::getFacadeApplication();
        $db = $app['database']->connection();
        $session = $app['session'];

        $this->uDefaultLanguage = $lang;
        $session->set('uDefaultLanguage', $lang);
        $db->Execute('update Users set uDefaultLanguage = ? where uID = ?', [$lang, $this->getUserID()]);
    }

    /**
     * Gets the default language for the logged-in user.
     *
     * @return string
     */
    public function getUserDefaultLanguage()
    {
        return $this->uDefaultLanguage;
    }

    /**
     * Returns date in yyyy-mm-dd H:i:s format.
     *
     * @return string
     */
    public function getLastPasswordChange()
    {
        return $this->uLastPasswordChange;
    }

    /**
     * Checks to see if the current user object is registered. If so, it queries that records
     * default language. Otherwise, it falls back to sitewide settings.
     *
     * @return string
     */
    public function getUserLanguageToDisplay()
    {
        if ($this->getUserDefaultLanguage() != '') {
            return $this->getUserDefaultLanguage();
        } else {
            $app = Application::getFacadeApplication();
            $config = $app['config'];

            return $config->get('concrete.locale');
        }
    }

    public function refreshUserGroups()
    {
        $app = Application::getFacadeApplication();
        $session = $app['session'];

        $session->remove('uGroups');
        $session->remove('accessEntities');
        $ug = $this->_getUserGroups();
        $session->set('uGroups', $ug);
        $this->uGroups = $ug;
    }

    /**
     * Function to return Permission Access Entities belonging to this user object
     *
     * @return PermissionAccessEntity[] | array
     */
    public function getUserAccessEntityObjects()
    {
        $app = Application::getFacadeApplication();

        $req = $app->make(Request::class);
        if ($req->hasCustomRequestUser()) {
            // we bypass session-saving performance
            // and we don't save them in session.
            return PermissionAccessEntity::getForUser($this);
        }

        if ($this->accessEntities === null) {
            $session = $app['session'];
            $validator = $app->make(SessionValidator::class);
            // Check if the user is loggged in
            if ($validator->hasActiveSession() && $session->has('uID')) {
                // If a user is logged in and running a script to get the user access entities
                // return the correct access entities
                if ($session->has('accessEntities') && $this->getUserID() == $session->get('uID')) {
                    $entities = $session->get('accessEntities');
                } elseif ($this->getUserID() == $session->get('uID')) {
                    $entities = PermissionAccessEntity::getForUser($this);
                    $session->set('accessEntities', $entities);
                    $session->set('accessEntitiesUpdated', time());
                } else {
                    $entities = PermissionAccessEntity::getForUser($this);
                }
            } else {
                if ((int)$this->getUserID() > 0) {
                    $entities = PermissionAccessEntity::getForUser($this);
                } else {
                    $repository = $app->make(GroupRepository::class);
                    $group = $repository->getGroupByID(GUEST_GROUP_ID);
                    if ($group) {
                        $entities = [GroupEntity::getOrCreate($group)];
                    } else {
                        $entities = [];
                    }
                }
            }

            $this->accessEntities = $entities;
        }

        return $this->accessEntities;
    }

    /**
     * @param bool $disableLogin
     *
     * @return array
     */
    public function _getUserGroups($disableLogin = false)
    {
        $app = Application::getFacadeApplication();
        $req = Request::getInstance();
        $session = $app['session'];
        $ug = [];

        if (($session->has('uGroups')) && (!$disableLogin) && (!$req->hasCustomRequestUser())) {
            $ug = $session->get('uGroups');
        } else {
            $db = $app['database']->connection();
            if ($this->uID) {
                $ug[REGISTERED_GROUP_ID] = REGISTERED_GROUP_ID;

                $uID = $this->uID;
                $q = 'select gID from UserGroups where uID = ?';
                $r = $db->query($q, [$uID]);
                while ($row = $r->fetch()) {
                    $g = Group::getByID($row['gID']);
                    if ($g->isUserExpired($this)) {
                        $this->exitGroup($g);
                    } else {
                        $ug[$row['gID']] = $row['gID'];
                    }
                }
            }

            // now we populate also with guest information, since presumably logged-in users
            // see the same stuff as guest
            $ug[GUEST_GROUP_ID] = GUEST_GROUP_ID;
        }

        return $ug;
    }

    /**
     * @param Group $g
     * @param GroupRole $r
     */
    public function changeGroupRole($g, $r)
    {
        $app = Application::getFacadeApplication();
        $db = $app['database']->connection();

        if (is_object($g)) {
            if (!$this->inExactGroup($g)) {
                $db->Replace('UserGroups', [
                    'uID' => $this->getUserID(),
                    'gID' => $g->getGroupID(),
                    'grID' => $r->getId()
                ], ['uID', 'gID'], true);

                $ue = new \Concrete\Core\User\Event\UserGroup($this);
                $ue->setGroupObject($g);

                $app['director']->dispatch('on_user_change_group_role', $ue);
            }
        }
    }

    /**
     * @param Group $g
     */
    public function enterGroup($g)
    {
        $app = Application::getFacadeApplication();
        // takes a group object, and, if the user is not already in the group, it puts them into it
        $dt = $app->make('helper/date');

        if (is_object($g)) {
            if (!$this->inExactGroup($g)) {
                $gID = $g->getGroupID();
                $db = $app['database']->connection();
                $grID = DEFAULT_GROUP_ROLE_ID;

                $role = $g->getDefaultRole();

                if (is_object($role)) {
                    $grID = $role->getId();
                }

                $db->Replace('UserGroups', [
                    'uID' => $this->getUserID(),
                    'gID' => $g->getGroupID(),
                    'ugEntered' => $dt->getOverridableNow(),
                    'grID' => $grID
                ],
                    ['uID', 'gID'], true);

                $ue = new \Concrete\Core\User\Event\UserGroup($this);
                $ue->setGroupObject($g);

                $app['director']->dispatch('on_user_enter_group', $ue);

                /** @noinspection PhpUnhandledExceptionInspection */
                $subject = new GroupSignup($g, $this);
                /** @var GroupSignupType $type */
                $type = $app->make('manager/notification/types')->driver('group_signup');
                $notifier = $type->getNotifier();

                if (method_exists($notifier, 'notify')) {
                    $subscription = $type->getSubscription($subject);
                    $users = $notifier->getUsersToNotify($subscription, $subject);
                    $notification = new GroupSignupNotification($subject);
                    $subject->getNotifications()->add($notification);
                    $notifier->notify($users, $notification);
                }
            }
        }
    }

    /**
     * @param Group $g
     */
    public function exitGroup($g)
    {
        // takes a group object, and, if the user is in the group, they exit the group
        if (is_object($g)) {
            $app = Application::getFacadeApplication();
            $db = $app['database']->connection();

            $gID = $g->getGroupID();

            $ue = new \Concrete\Core\User\Event\UserGroup($this);
            $ue->setGroupObject($g);
            $app['director']->dispatch('on_user_exit_group', $ue);

            $q = 'delete from UserGroups where uID = ? and gID = ?';
            $r = $db->executeQuery($q, [$this->uID, $gID]);
        }
    }

    /**
     * Return true if user is in Group or any of this groups children.
     *
     * @param Group $g
     *
     * @return bool
     */
    public function inGroup($g)
    {
        $app = Application::getFacadeApplication();
        /** @var \Concrete\Core\Database\Connection\Connection $db */
        $db = $app['database']->connection();
        /** @var $likeBuilder LikeBuilder */
        $likeBuilder = $app->make(LikeBuilder::class);
        $query = $db->createQueryBuilder();
        $query->select('ug.gID')->from('UserGroups', 'ug')
            ->innerJoin('ug', $query->getConnection()->getDatabasePlatform()->quoteSingleIdentifier('Groups'), 'g', 'ug.gID=g.gID')
            ->where($query->expr()->eq('ug.uID', ':userID'))
            ->andWhere($query->expr()->orX(
                $query->expr()->eq('ug.gID', ':gID'),
                $query->expr()->like('g.gPath', ':groupPath')
            ))
            ->setParameter('userID', $this->uID)
            ->setParameter('gID', $g->getGroupID())
            ->setParameter('groupPath', $likeBuilder->escapeForLike($g->getGroupPath()) . '/%')
            ->setMaxResults(1);
        $results = $query->execute()->fetchColumn();

        return (bool)$results;
    }

    /**
     * Return true if user is in this Group.
     * Does not check if user is a member of children.
     *
     * @param Group $g
     *
     * @return bool
     */
    public function inExactGroup($g)
    {
        $app = Application::getFacadeApplication();
        /** @var \Concrete\Core\Database\Connection\Connection $db */
        $db = $app['database']->connection();
        $query = $db->createQueryBuilder();
        $query->select('ug.gID')->from('UserGroups', 'ug')
            ->where($query->expr()->eq('ug.uID', ':userID'))
            ->andWhere(
                $query->expr()->eq('ug.gID', ':gID'))->setParameter('userID', $this->uID)
            ->setParameter('gID', $g->getGroupID())
            ->setMaxResults(1);
        $results = $query->execute()->fetchColumn();

        return (bool)$results;
    }

    /**
     * @param int $mcID
     * @param int $ocID
     */
    public function loadMasterCollectionEdit($mcID, $ocID)
    {
        $app = Application::getFacadeApplication();
        $session = $app['session'];
        // basically, this function loads the master collection ID you're working on into session
        // so you can work on it without the system failing because you're editing a template
        $session->set('mcEditID', $mcID);
        $session->set('ocID', $ocID);
    }

    /**
     * Loads a page in edit mode.
     *
     * @param Page $c
     *
     * @return bool
     */
    public function loadCollectionEdit(&$c)
    {
        $c->refreshCache();

        // clear the cached available areas before entering edit mode
        $app = Application::getFacadeApplication();
        /** @var \Symfony\Component\HttpFoundation\Session\Session $session */
        $session = $app->make("session");
        $session->remove("used_areas");

        // can only load one page into edit mode at a time.
        if ($c->isCheckedOut()) {
            return false;
        }

        $app = Application::getFacadeApplication();
        $db = $app['database']->connection();

        $cID = $c->getCollectionID();
        // first, we check to see if we have a collection in edit mode. If we do, we relinquish it
        $this->unloadCollectionEdit(false);

        $q = 'select cIsCheckedOut, cCheckedOutDatetime from Pages where cID = ?';
        $r = $db->executeQuery($q, [$cID]);
        if ($r) {
            $row = $r->fetch();
            if (!$row['cIsCheckedOut']) {
                $app['session']->set('editCID', $cID);
                $uID = $this->getUserID();
                $dh = $app->make('helper/date');
                $datetime = $dh->getOverridableNow();
                $q2 = 'update Pages set cIsCheckedOut = ?, cCheckedOutUID = ?, cCheckedOutDatetime = ?, cCheckedOutDatetimeLastEdit = ? where cID = ?';
                $r2 = $db->executeQuery($q2, [1, $uID, $datetime, $datetime, $cID]);

                $c->cIsCheckedOut = 1;
                $c->cCheckedOutUID = $uID;
                $c->cCheckedOutDatetime = $datetime;
                $c->cCheckedOutDatetimeLastEdit = $datetime;
            }
        }

        return true;
    }

    /**
     * @param bool $removeCache
     */
    public function unloadCollectionEdit($removeCache = true)
    {
        $app = Application::getFacadeApplication();
        $db = $app['database']->connection();

        if ($this->getUserID() > 0) {
            $col = $db->GetCol('select cID from Pages where cCheckedOutUID = ?', [$this->getUserID()]);
            foreach ($col as $cID) {
                $p = Page::getByID($cID);
                if ($removeCache) {
                    $p->refreshCache();
                }
            }

            $q = 'update Pages set cIsCheckedOut = 0, cCheckedOutUID = null, cCheckedOutDatetime = null, cCheckedOutDatetimeLastEdit = null where cCheckedOutUID = ?';
            $db->query($q, [$this->getUserID()]);
        }
    }

    /**
     * @param string $cfKey
     *
     * @return string|null
     */
    public function config($cfKey)
    {
        if ($this->isRegistered()) {
            $app = Application::getFacadeApplication();
            $db = $app['database']->connection();

            $val = $db->GetOne('select cfValue from ConfigStore where uID = ? and cfKey = ?', [$this->getUserID(), $cfKey]);

            return $val;
        }

        return null;
    }

    /**
     * @param Page $c
     */
    public function markPreviousFrontendPage(Page $c)
    {
        $app = Application::getFacadeApplication();
        $app['session']->set('frontendPreviousPageID', $c->getCollectionID());
    }

    /**
     * @return int
     */
    public function getPreviousFrontendPageID()
    {
        $app = Application::getFacadeApplication();

        return (int)$app['session']->get('frontendPreviousPageID');
    }

    /**
     * @param string $cfKey
     * @param string $cfValue
     */
    public function saveConfig($cfKey, $cfValue)
    {
        $app = Application::getFacadeApplication();
        $app['database']->connection()->Replace('ConfigStore', ['cfKey' => $cfKey, 'cfValue' => $cfValue, 'uID' => $this->getUserID()], ['cfKey', 'uID'], true);
    }

    /**
     * @param Page $c
     */
    public function refreshCollectionEdit(&$c)
    {
        if ($this->isLoggedIn() && $c->getCollectionCheckedOutUserID() == $this->getUserID()) {
            $app = Application::getFacadeApplication();
            $db = $app['database']->connection();
            $cID = $c->getCollectionID();

            $dh = $app->make('helper/date');
            $datetime = $dh->getOverridableNow();

            $q = 'update Pages set cCheckedOutDatetimeLastEdit = ? where cID = ?';
            $r = $db->executeQuery($q, [$datetime, $cID]);

            $c->cCheckedOutDatetimeLastEdit = $datetime;
        }
    }

    /**
     * @return \Doctrine\DBAL\Driver\Statement
     */
    public function forceCollectionCheckInAll()
    {
        // This function forces checkin to take place
        $app = Application::getFacadeApplication();
        $db = $app['database']->connection();

        $q = 'update Pages set cIsCheckedOut = 0, cCheckedOutUID = null, cCheckedOutDatetime = null, cCheckedOutDatetimeLastEdit = null';
        $r = $db->query($q);

        return $r;
    }

    /**
     * Manage user session writing.
     *
     * @param bool $cache_interface
     */
    public function persist($cache_interface = true)
    {
        $this->refreshUserGroups();

        $app = Application::getFacadeApplication();

        /** @var Repository $config */
        $config = $app->make(Repository::class);

        /** @var \Symfony\Component\HttpFoundation\Session\Session $session */
        $session = $app['session'];
        $session->set('uID', $this->getUserID());
        $session->set('uName', $this->getUserName());
        $session->set('uBlockTypesSet', false);
        $session->set('uGroups', $this->getUserGroups());
        $session->set('uLastOnline', $this->getLastOnline());
        $session->set('uTimezone', $this->getUserTimezone());
        $session->set('uDefaultLanguage', $this->getUserDefaultLanguage());
        $session->set('uLastPasswordChange', $this->getLastPasswordChange());

        /** @var \Concrete\Core\Cookie\CookieJar $cookie */
        $cookie = $app['cookie'];

        $cookie->set(
            sprintf('%s_LOGIN', $app['config']->get('concrete.session.name')),
            1,
            // $expire
            time() + (int)$config->get('concrete.session.remember_me.lifetime'),
            // $path
            DIR_REL . '/',
            // $domain
            $config->get('concrete.session.cookie.cookie_domain'),
            // $secure
            $config->get('concrete.session.cookie.cookie_secure'),
            // $httpOnly
            $config->get('concrete.session.cookie.cookie_httponly')
        );

        if ($cache_interface) {
            $app->make('helper/concrete/ui')->cacheInterfaceItems();
        }
        $app->instance(User::class, $this);
    }

    /**
     * @param bool $cache_interface
     */
    public function logIn($cache_interface = true)
    {
        $this->persist($cache_interface);
    }

    /**
     * @param string|null $uLastPasswordChange
     * @return bool
     */
    private function isPasswordExpired(Connection $cn, Repository $config, $uLastPasswordChange)
    {
        if (!$uLastPasswordChange) {
            return false;
        }
        $maxAge = (int) ($config->get('concrete.user.password.max_age') ?? 0);
        if ($maxAge <= 0) {
            return false;
        }
        $lastChangeDateTime = DateTimeImmutable::createFromFormat($cn->getDatabasePlatform()->getDateTimeFormatString(), $uLastPasswordChange);
        if (!$lastChangeDateTime) {
            return false;
        }
        $ageInSeconds = time() - $lastChangeDateTime->getTimestamp();
        $ageInDays = floor($ageInSeconds / 86400);

        return $ageInDays >= $maxAge;
    }
}


text:
import React from 'react';
import ReactTestRenderer from 'react-test-renderer';
import 'styled-components-test-utils/lib/jest';
import theme from '../src/theme';
import Card from '../src/Card';

describe('Card', () => {
  test('should render a Card', () => {
    const component = ReactTestRenderer.create(<Card theme={theme} />);
    expect(component).toBeDefined();
    expect(component.toJSON()).toMatchSnapshot();
  });

  test('should have a div tag', () => {
    const component = ReactTestRenderer.create(<Card theme={theme} />).toJSON();
    expect(component.type).toEqual('div');
  });

  test('should have a default width', () => {
    const component = ReactTestRenderer.create(
      <Card
        theme={theme}
      />,
    );
    expect(component).toHaveStyleRule('width', '300px');
  });

  test('should handle string width', () => {
    const component = ReactTestRenderer.create(
      <Card
        theme={theme}
        width="20em"
      />,
    );
    expect(component).toHaveStyleRule('width', '20em');
  });

  test('should handle numeric width', () => {
    const component = ReactTestRenderer.create(
      <Card
        theme={theme}
        width={30}
      />,
    );
    expect(component).toHaveStyleRule('width', '30px');
  });
});


text:
package org.camunda.bpm.engine.cassandra.provider;

import org.camunda.bpm.engine.impl.db.DbEntity;

import com.datastax.driver.core.BatchStatement;
import com.datastax.driver.core.Statement;

public abstract class LockedBatch<T extends DbEntity> {

  protected T entity;

  protected BatchStatement batch = new BatchStatement();
  protected BatchStatement indexBatch = null;
  protected String version = null;

  protected boolean shouldNotLock = false;

  public LockedBatch(T entity) {
    this.entity = entity;
  }

  public BatchStatement getBatch() {
    if(!shouldNotLock && !isEmpty()) {
      addLockStatement(batch);
    }
    return batch;
  }

  public boolean isEmpty() {
    return batch.getStatements().isEmpty();
  }

  protected abstract void addLockStatement(BatchStatement batch);

  public void addStatement(Statement statement) {
    batch.add(statement);
  }

  public void addIndexStatement(Statement statement) {
    if(indexBatch==null){
      indexBatch=new BatchStatement();
    }
    indexBatch.add(statement);
  }

  public void setShouldNotLock() {
    this.shouldNotLock = true;
  }

  public BatchStatement getIndexBatch() {
    return indexBatch;
  }

  public String getVersion() {
    return version;
  }

  public void setVersion(String version) {
    this.version = version;
  }

}


text:
.class Lcom/android/internal/telephony/DataConnection$DcActiveState;
.super Lcom/android/internal/util/State;
.source "DataConnection.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/telephony/DataConnection;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "DcActiveState"
.end annotation

# instance fields
.field private mConnectionParams:Lcom/android/internal/telephony/DataConnection$ConnectionParams;

.field private mFailCause:Lcom/android/internal/telephony/DataConnection$FailCause;

.field final synthetic this$0:Lcom/android/internal/telephony/DataConnection;

# direct methods
.method private constructor <init>(Lcom/android/internal/telephony/DataConnection;)V
    .locals 1
    .parameter

    .prologue
    const/4 v0, 0x0

    .line 1038
    iput-object p1, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    invoke-direct {p0}, Lcom/android/internal/util/State;-><init>()V

    .line 1039
    iput-object v0, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mConnectionParams:Lcom/android/internal/telephony/DataConnection$ConnectionParams;

    .line 1040
    iput-object v0, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mFailCause:Lcom/android/internal/telephony/DataConnection$FailCause;

    return-void
.end method

.method synthetic constructor <init>(Lcom/android/internal/telephony/DataConnection;Lcom/android/internal/telephony/DataConnection$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 1038
    invoke-direct {p0, p1}, Lcom/android/internal/telephony/DataConnection$DcActiveState;-><init>(Lcom/android/internal/telephony/DataConnection;)V

    return-void
.end method

# virtual methods
.method public enter()V
    .locals 3

    .prologue
    .line 1056
    iget-object v0, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mConnectionParams:Lcom/android/internal/telephony/DataConnection$ConnectionParams;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mFailCause:Lcom/android/internal/telephony/DataConnection$FailCause;

    if-eqz v0, :cond_0

    .line 1058
    iget-object v0, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget-object v1, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mConnectionParams:Lcom/android/internal/telephony/DataConnection$ConnectionParams;

    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mFailCause:Lcom/android/internal/telephony/DataConnection$FailCause;

    #calls: Lcom/android/internal/telephony/DataConnection;->notifyConnectCompleted(Lcom/android/internal/telephony/DataConnection$ConnectionParams;Lcom/android/internal/telephony/DataConnection$FailCause;)V
    invoke-static {v0, v1, v2}, Lcom/android/internal/telephony/DataConnection;->access$400(Lcom/android/internal/telephony/DataConnection;Lcom/android/internal/telephony/DataConnection$ConnectionParams;Lcom/android/internal/telephony/DataConnection$FailCause;)V

    .line 1060
    :cond_0
    return-void
.end method

.method public exit()V
    .locals 1

    .prologue
    const/4 v0, 0x0

    .line 1065
    iput-object v0, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mConnectionParams:Lcom/android/internal/telephony/DataConnection$ConnectionParams;

    .line 1066
    iput-object v0, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mFailCause:Lcom/android/internal/telephony/DataConnection$FailCause;

    .line 1067
    return-void
.end method

.method public processMessage(Landroid/os/Message;)Z
    .locals 6
    .parameter "msg"

    .prologue
    const/4 v5, 0x0

    .line 1073
    iget v2, p1, Landroid/os/Message;->what:I

    sparse-switch v2, :sswitch_data_0

    .line 1116
    const/4 v1, 0x0

    .line 1119
    .local v1, retVal:Z
    :goto_0
    return v1

    .line 1075
    .end local v1           #retVal:Z
    :sswitch_0
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget v3, v2, Lcom/android/internal/telephony/DataConnection;->mRefCount:I

    add-int/lit8 v3, v3, 0x1

    iput v3, v2, Lcom/android/internal/telephony/DataConnection;->mRefCount:I

    .line 1076
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "DcActiveState msg.what=EVENT_CONNECT RefCount="

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget-object v4, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget v4, v4, Lcom/android/internal/telephony/DataConnection;->mRefCount:I

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-virtual {v2, v3}, Lcom/android/internal/telephony/DataConnection;->log(Ljava/lang/String;)V

    .line 1077
    iget-object v2, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    if-eqz v2, :cond_0

    .line 1078
    iget-object v3, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget-object v2, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v2, Lcom/android/internal/telephony/DataConnection$ConnectionParams;

    sget-object v4, Lcom/android/internal/telephony/DataConnection$FailCause;->NONE:Lcom/android/internal/telephony/DataConnection$FailCause;

    #calls: Lcom/android/internal/telephony/DataConnection;->notifyConnectCompleted(Lcom/android/internal/telephony/DataConnection$ConnectionParams;Lcom/android/internal/telephony/DataConnection$FailCause;)V
    invoke-static {v3, v2, v4}, Lcom/android/internal/telephony/DataConnection;->access$400(Lcom/android/internal/telephony/DataConnection;Lcom/android/internal/telephony/DataConnection$ConnectionParams;Lcom/android/internal/telephony/DataConnection$FailCause;)V

    .line 1080
    :cond_0
    const/4 v1, 0x1

    .line 1081
    .restart local v1       #retVal:Z
    goto :goto_0

    .line 1083
    .end local v1           #retVal:Z
    :sswitch_1
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget v3, v2, Lcom/android/internal/telephony/DataConnection;->mRefCount:I

    add-int/lit8 v3, v3, -0x1

    iput v3, v2, Lcom/android/internal/telephony/DataConnection;->mRefCount:I

    .line 1084
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "DcActiveState msg.what=EVENT_DISCONNECT RefCount="

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget-object v4, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget v4, v4, Lcom/android/internal/telephony/DataConnection;->mRefCount:I

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-virtual {v2, v3}, Lcom/android/internal/telephony/DataConnection;->log(Ljava/lang/String;)V

    .line 1085
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget v2, v2, Lcom/android/internal/telephony/DataConnection;->mRefCount:I

    if-nez v2, :cond_2

    .line 1087
    iget-object v0, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v0, Lcom/android/internal/telephony/DataConnection$DisconnectParams;

    .line 1088
    .local v0, dp:Lcom/android/internal/telephony/DataConnection$DisconnectParams;
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget v2, v2, Lcom/android/internal/telephony/DataConnection;->mTag:I

    iput v2, v0, Lcom/android/internal/telephony/DataConnection$DisconnectParams;->tag:I

    .line 1089
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    #calls: Lcom/android/internal/telephony/DataConnection;->tearDownData(Ljava/lang/Object;)V
    invoke-static {v2, v0}, Lcom/android/internal/telephony/DataConnection;->access$1700(Lcom/android/internal/telephony/DataConnection;Ljava/lang/Object;)V

    .line 1090
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget-object v3, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    #getter for: Lcom/android/internal/telephony/DataConnection;->mDisconnectingState:Lcom/android/internal/telephony/DataConnection$DcDisconnectingState;
    invoke-static {v3}, Lcom/android/internal/telephony/DataConnection;->access$2400(Lcom/android/internal/telephony/DataConnection;)Lcom/android/internal/telephony/DataConnection$DcDisconnectingState;

    move-result-object v3

    #calls: Lcom/android/internal/telephony/DataConnection;->transitionTo(Lcom/android/internal/util/IState;)V
    invoke-static {v2, v3}, Lcom/android/internal/telephony/DataConnection;->access$2500(Lcom/android/internal/telephony/DataConnection;Lcom/android/internal/util/IState;)V

    .line 1096
    .end local v0           #dp:Lcom/android/internal/telephony/DataConnection$DisconnectParams;
    :cond_1
    :goto_1
    const/4 v1, 0x1

    .line 1097
    .restart local v1       #retVal:Z
    goto :goto_0

    .line 1092
    .end local v1           #retVal:Z
    :cond_2
    iget-object v2, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    if-eqz v2, :cond_1

    .line 1093
    iget-object v3, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget-object v2, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v2, Lcom/android/internal/telephony/DataConnection$DisconnectParams;

    #calls: Lcom/android/internal/telephony/DataConnection;->notifyDisconnectCompleted(Lcom/android/internal/telephony/DataConnection$DisconnectParams;Z)V
    invoke-static {v3, v2, v5}, Lcom/android/internal/telephony/DataConnection;->access$800(Lcom/android/internal/telephony/DataConnection;Lcom/android/internal/telephony/DataConnection$DisconnectParams;Z)V

    goto :goto_1

    .line 1101
    :sswitch_2
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "DcActiveState msg.what=EVENT_DISCONNECT_ALL RefCount="

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget-object v4, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget v4, v4, Lcom/android/internal/telephony/DataConnection;->mRefCount:I

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-virtual {v2, v3}, Lcom/android/internal/telephony/DataConnection;->log(Ljava/lang/String;)V

    .line 1103
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iput v5, v2, Lcom/android/internal/telephony/DataConnection;->mRefCount:I

    .line 1104
    iget-object v0, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v0, Lcom/android/internal/telephony/DataConnection$DisconnectParams;

    .line 1105
    .restart local v0       #dp:Lcom/android/internal/telephony/DataConnection$DisconnectParams;
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget v2, v2, Lcom/android/internal/telephony/DataConnection;->mTag:I

    iput v2, v0, Lcom/android/internal/telephony/DataConnection$DisconnectParams;->tag:I

    .line 1106
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    #calls: Lcom/android/internal/telephony/DataConnection;->tearDownData(Ljava/lang/Object;)V
    invoke-static {v2, v0}, Lcom/android/internal/telephony/DataConnection;->access$1700(Lcom/android/internal/telephony/DataConnection;Ljava/lang/Object;)V

    .line 1107
    iget-object v2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    iget-object v3, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->this$0:Lcom/android/internal/telephony/DataConnection;

    #getter for: Lcom/android/internal/telephony/DataConnection;->mDisconnectingState:Lcom/android/internal/telephony/DataConnection$DcDisconnectingState;
    invoke-static {v3}, Lcom/android/internal/telephony/DataConnection;->access$2400(Lcom/android/internal/telephony/DataConnection;)Lcom/android/internal/telephony/DataConnection$DcDisconnectingState;

    move-result-object v3

    #calls: Lcom/android/internal/telephony/DataConnection;->transitionTo(Lcom/android/internal/util/IState;)V
    invoke-static {v2, v3}, Lcom/android/internal/telephony/DataConnection;->access$2600(Lcom/android/internal/telephony/DataConnection;Lcom/android/internal/util/IState;)V

    .line 1108
    const/4 v1, 0x1

    .line 1109
    .restart local v1       #retVal:Z
    goto/16 :goto_0

    .line 1073
    :sswitch_data_0
    .sparse-switch
        0x40000 -> :sswitch_0
        0x40004 -> :sswitch_1
        0x40006 -> :sswitch_2
    .end sparse-switch
.end method

.method public setEnterNotificationParams(Lcom/android/internal/telephony/DataConnection$ConnectionParams;Lcom/android/internal/telephony/DataConnection$FailCause;)V
    .locals 0
    .parameter "cp"
    .parameter "cause"

    .prologue
    .line 1044
    iput-object p1, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mConnectionParams:Lcom/android/internal/telephony/DataConnection$ConnectionParams;

    .line 1045
    iput-object p2, p0, Lcom/android/internal/telephony/DataConnection$DcActiveState;->mFailCause:Lcom/android/internal/telephony/DataConnection$FailCause;

    .line 1046
    return-void
.end method