text:
package info.longshore.sudoku.domain;

import java.io.Serializable;
import java.util.*;

/**
 * An implementation of the concept of a constraint puzzle.
 *

 * An instance of ConstraintPuzzle is an NxN grid which has a ruleset whose
 * purpose is to restrict the valid values for a given element.
 *

 * TODO: ADD INITIAL SET OF VALUES [range of values]
 */
public class ConstraintPuzzle implements Serializable {

  /**
   * Returns a randomly generated puzzle in its final state (all filled in).
   * Puzzles whose solution is the return of this method can then be generated
   * by using getNewStartState.
   */
  public static ConstraintPuzzle getNewSolution(int size, Ruleset rs) {
    ConstraintPuzzle newSolution = new ConstraintPuzzle(size, rs);
    newSolution.solveWithBacktracking(true);
    return newSolution;
  }

  public ConstraintPuzzle() {
    setRandomNumberGeneratorSeed();
    setSize(0);
    setRuleset(new Ruleset());
  }

  public void setSize(int n) {
    size = n;

    // Initialize Elements
    elements = new int[size * size];
    for (int i = 0; i < elements.length; i++) {
      elements[i] = ConstraintPuzzle.EMPTY_ELEMENT_VALUE;
    }

    placedElements = new HashSet<Integer>();
    emptyElements = new HashSet<Integer>();

    // Setup empty
    for (int i = 0; i < elements.length; i++) {
      emptyElements.add(i);
    }

    // If the ruleset exists, initialize it
    if (ruleSet != null) {
      setRuleset(ruleSet);
    }
  }

  public void setRuleset(Ruleset rs) {
    if (rs == null) {
      return;
    }

    validElementsCache = new ArrayList<Set<Integer>>(elements.length);

    ruleSet = rs;
    for (int i = 0; i < elements.length; i++) {
      validElementsCache.add(i, ruleSet.getValidElementValues(this, i));
    }
  }

  public void setRandomNumberGeneratorSeed() {
    setRandomNumberGeneratorSeed(System.currentTimeMillis());
  }

  public void setRandomNumberGeneratorSeed(long seed) {
    randomNumberGeneratorSeed = seed;
    randomNumberGenerator = new Random(randomNumberGeneratorSeed);
  }

  /**
   * Constructs a constraint puzzle with given size and ruleset. The size is
   * equivalent to the number of rows/columns (both of which are equal).
   *
   * @param n  the size
   * @param rs the ruleset
   */
  public ConstraintPuzzle(int n, Ruleset rs) {
    setRandomNumberGeneratorSeed();
    setSize(n);
    setRuleset(rs);
  }

  public static ConstraintPuzzle getCopy(ConstraintPuzzle p) {

    try {
      ConstraintPuzzle c = p.getClass().newInstance();
      c.setRandomNumberGeneratorSeed(p.randomNumberGeneratorSeed);
      c.setSize(p.getSize());
      c.setRuleset(new Ruleset(p.ruleSet));

      // Should work :F
      for (int i = 0; i < c.elements.length; i++) {
        if (p.getElementWithNumber(i) != ConstraintPuzzle.EMPTY_ELEMENT_VALUE) {
          c.setElementWithNumber(i, p.getElementWithNumber(i));
        }
      }

      return c;
    } catch (Exception e) {
      // Nope.

      return null;
    }

  }

  /**
   * Quick 2 minute implementation until jason s's is done
   *
   * @return
   */
  public ConstraintPuzzle getNewStartState(int x) {

    ConstraintPuzzle copy = ConstraintPuzzle.getCopy(this);

    int numberToDivide = randomNumberGenerator.nextInt(3) + 1;

    int numberToRemove = getSize() / numberToDivide;

    while (numberToRemove > 0) {

      int posToRemove = randomNumberGenerator.nextInt(getNumberOfElements());

      copy.emptyElementWithNumber(posToRemove);

      numberToRemove--;
    }

    return copy;
  }

  /**
   * Returns the size of this instance of the constraint puzzle. The size is
   * equivalent to the number of rows / columns.
   *
   * @return the size
   */
  public int getSize() {
    return size;
  }

  /**
   * Maps row/col to element number, where rows and cols start at 0, and
   * elements start at 0.
   *
   * @param rowNumber    the row number
   * @param columnNumber the column number
   * @return the element number
   */
  public int getElementNumber(int rowNumber, int columnNumber) {
    int elementNumber = (size * rowNumber) + columnNumber;
    return elementNumber;
  }

  /**
   * Returns the next most constrained empty element number -- that is the
   * next element whose valid elements is smallest. If there are two or more
   * elements with the same amount of valid elements, make no assumptions as
   * to which element number will be returned.
   *
   * @return the next most constrained element number
   * @throws Sudoku.NoElementsEmptyException if theres no empty elements
   */
  public int getNextMostConstrainedEmptyElementNumber() throws NoElementsEmptyException {
    int smallestIndex = -1;

    for (Integer emptyElementNumber : emptyElements) {
      if (smallestIndex == -1 || validElementsCache.get(emptyElementNumber).size() < validElementsCache.get(smallestIndex).size()) {
        smallestIndex = emptyElementNumber;
      }
    }

    if (smallestIndex != -1) {
      return smallestIndex;
    } else {
      throw new NoElementsEmptyException();
    }
  }

  /**
   * Returns the number of the next empty element, where the element number is
   * the smallest of all empty element's numbers.
   *

   * i.e. smallest empty index
   *
   * @return the number of the next empty element
   * @throws Sudoku.NoElementsEmptyException no other empty elements
   */
  public int getNextSequentialEmptyElementNumber() throws NoElementsEmptyException {
    int smallestIndex = -1;

    for (Integer emptyElementNumber : emptyElements) {
      if (smallestIndex == -1 || emptyElementNumber < smallestIndex) {
        smallestIndex = emptyElementNumber;
      }
    }

    if (smallestIndex != -1) {
      return smallestIndex;
    } else {
      throw new NoElementsEmptyException();
    }
  }

  /**
   * Returns the number of elements in the Sudoku puzzle, i.e. size^2
   *
   * @return the number of elements
   */
  public int getNumberOfElements() {
    return elements.length;
  }

  /**
   * Returns the value of the element with given number, where number 0 is top
   * left corner.
   *
   * @param elementNumber the element number
   * @return the elements value
   */
  public int getElementWithNumber(int elementNumber) {
    return elements[elementNumber];
  }

  /**
   * Returns value of element at row/col
   *
   * @param rowNumber    the row
   * @param columnNumber the col
   * @return element value
   */
  public int getElementAtPosition(int rowNumber, int columnNumber) {
    return getElementWithNumber(getElementNumber(rowNumber, columnNumber));
  }

  public int[] getElements() {
    return elements;
  }

  /**
   * Sets an element to a value.
   *
   * @param elementNumber the element number
   * @param value         the value
   * @throws Sudoku.ElementValueViolatesRuleException if the value violates
   *                                                  the ruleset
   */
  public void setElementWithNumber(int elementNumber, int value) throws ElementValueViolatesRuleException {
    if (!isValidValueForElementWithNumber(elementNumber, value)) {
      throw new ElementValueViolatesRuleException();
    }

    // Fix empty
    if (elements[elementNumber] == ConstraintPuzzle.EMPTY_ELEMENT_VALUE) {
      emptyElements.remove(elementNumber);
    }

    elements[elementNumber] = value;

    // Fix set
    placedElements.add(elementNumber);

    // Update affected valid elements
    Set<Integer> affectedElements = getRelatedElementNumbersForElementWithNumber(elementNumber);
    affectedElements.add(elementNumber);
    for (Integer affectedElementNumber : affectedElements) {
      validElementsCache.set(affectedElementNumber, getValidValuesForElementWithNumber(affectedElementNumber));
    }

  }

  /**
   * Sets an element at row/col to a value.
   *
   * @param rowNumber    the row
   * @param columnNumber the col
   * @param value        value to set
   * @throws Sudoku.ElementValueViolatesRuleException if value violates
   *                                                  ruleset
   */
  public void setElementAtPosition(int rowNumber, int columnNumber, int value) throws ElementValueViolatesRuleException {
    setElementWithNumber(getElementNumber(rowNumber, columnNumber), value);
  }

  /**
   * Emptys an element with given number
   *
   * @param elementNumber the element number
   */
  protected void emptyElementWithNumber(int elementNumber) {
    placedElements.remove(elementNumber);
    emptyElements.add(elementNumber);
    elements[elementNumber] = EMPTY_ELEMENT_VALUE;

    // Update affected valid elements
    Set<Integer> affectedElements = getRelatedElementNumbersForElementWithNumber(elementNumber);
    affectedElements.add(elementNumber);
    for (Integer affectedElementNumber : affectedElements) {
      validElementsCache.set(affectedElementNumber, getValidValuesForElementWithNumber(affectedElementNumber));
    }
  }

  /**
   * Emptys an element at row/col.
   *
   * @param rowNumber    the row
   * @param columnNumber the col
   */
  protected void emptyElementAtPosition(int rowNumber, int columnNumber) {
    emptyElementWithNumber(getElementNumber(rowNumber, columnNumber));
  }

  /**
   * Returns if the value is a valid one for an element with given number. If
   * the value is in the ruleset's valid values for the element, which
   * includes its current value as long as the element isnt empty, its valid.
   * If its empty or not in the valid set of values, its invalid.
   *
   * @param elementNumber the number of the element
   * @param value         the value to check
   * @return true if valid, false if not
   */
  public boolean isValidValueForElementWithNumber(int elementNumber, int value) {
    if (value == EMPTY_ELEMENT_VALUE) {
      return false;
    } else if (elements[elementNumber] == value) {
      return true;
    } else {
      for (int validElement : getValidValuesForElementWithNumber(elementNumber)) {
        if (validElement == value) {
          return true;
        }
      }

      return false;
    }
  }

  /**
   * Returns if the value is a valid one for an element with given row/col. If
   * the value is in the ruleset's valid values for the element, which
   * includes its current value as long as the element isnt empty, its valid.
   * If its empty or not in the valid set of values, its invalid.
   *
   * @param rowNumber    the row
   * @param columnNumber the col
   * @param value        the value to check
   * @return true if valid, false if not
   */
  public boolean isValidValueForElementAtPosition(int rowNumber, int columnNumber, int value) {
    return isValidValueForElementWithNumber(getElementNumber(rowNumber, columnNumber), value);
  }

  /**
   * Returns all the related element numbers for an element with number
   *
   * @param elementNumber the element number
   * @return a set of related element numbers
   */
  public Set<Integer> getRelatedElementNumbersForElementWithNumber(int elementNumber) {
    return ruleSet.getRelatedElementNumbers(this, elementNumber);
  }

  /**
   * Returns all the related element numbers for an element at row/col
   *
   * @param rowNumber    the row
   * @param columnNumber the col
   * @return a set of related element numbers
   */
  public Set<Integer> getRelatedElementNumbersForElementAtPosition(int rowNumber, int columnNumber) {
    return getRelatedElementNumbersForElementWithNumber(getElementNumber(rowNumber, columnNumber));
  }

  /**
   * Returns all the valid values for an element with number.
   *
   * @param elementNumber the element number
   * @return a set of valid values
   */
  public Set<Integer> getValidValuesForElementWithNumber(int elementNumber) {
    Set<Integer> validElementsFromRuleset = ruleSet.getValidElementValues(this, elementNumber);
    Set<Integer> validValues = validElementsFromRuleset;
    validValues.removeAll(eliminatedValues.get(elementNumber));
    return validValues;
  }

  /**
   * Removes an element from the set of valid elements for this number.
   *
   * @param elementNumber the element number the element number to remove for
   * @param elementValue  the element value the value to remove
   */
  protected void removeValueForElementWithNumber(int elementNumber, int elementValue) {
    // we dont care if they are removing a value which is not valid anyways

    // Add to recalculate list
    eliminatedValues.get(elementNumber).add(elementValue);

    // And update the cache
    validElementsCache.get(elementNumber).remove(elementValue);
  }

  /**
   * Returns all the valid values for an element at row/col
   *
   * @param rowNumber    the row
   * @param columnNumber the col
   * @return a set of valid values
   */
  public Set<Integer> getValidValuesForElementAtPosition(int rowNumber, int columnNumber) {
    return getValidValuesForElementWithNumber(getElementNumber(rowNumber, columnNumber));
  }

  public ConstraintPuzzle getSolution() {
    ConstraintPuzzle copy = ConstraintPuzzle.getCopy(this);
    copy.solveWithBacktracking();
    return copy;
  }

  /**
   * Solves puzzle using constraint backtracking and always picking numbers to
   * use sequentially (not randomly seeded)
   *
   * @return true if solved, false if wasnt solvable
   */
  public boolean solveWithBacktracking() {
    return solveWithBacktracking(false);
  }

  /**
   * Solve the puzzle using constraint backtracking
   *
   * @param guessRandomly Whether to pick numbers to try randomly
   * @return true if solved, false if wasnt solvable
   */
  public boolean solveWithBacktracking(boolean useRandomCode) {
    try {
      return solveWithBacktrackingRecursive(getNextMostConstrainedEmptyElementNumber(), useRandomCode);
    } catch (NoElementsEmptyException e) {
      return true;
    }
  }

  /**
   * Solves the puzzle using constraint backtracking, step by step.
   * Backtracking/Recursive algorithm.
   *
   * @param currentElementNumber next element to try
   * @param guessRandomly        whether to pick elements randomly
   * @return true if solvable, false if wasnt solvable
   */
  private boolean solveWithBacktrackingRecursive(int currentElementNumber, boolean guessRandomly) {
    Set<Integer> validElements = getValidValuesForElementWithNumber(currentElementNumber);

    if (validElements.size() < 1) {
      return false;
    } else {
      while (validElements.size() > 0) {
        int nextIndex;

        if (guessRandomly) {
          nextIndex = randomNumberGenerator.nextInt(validElements.size());
        } else {
          nextIndex = 0;
        }

        Integer validElement = null;
        int currentIndex = 0;
        for (Integer validElementC : validElements) {
          if (nextIndex == currentIndex) {
            validElement = validElementC;
            break;
          }

          currentIndex++;
        }
        setElementWithNumber(currentElementNumber, validElement);

        try {
          if (!solveWithBacktrackingRecursive(getNextMostConstrainedEmptyElementNumber(), guessRandomly)) {
            validElements.remove(validElement);
          } else {
            return true;
          }
        } catch (NoElementsEmptyException e) {
          return true;
        }
      }

      emptyElementWithNumber(currentElementNumber);
      return false;
    }
  }

  /**
   * Returns whether or not the puzzle is solved.
   *
   * @return true if solved, false if not.
   */
  public boolean isSolved() {
    return this.emptyElements.size() == 0;
  }

  /**
   * Returns the difficulty rating for this constraint puzzle.
   *
   * @return the difficulty rating of the puzzle, where the domain is in the
   * set of constants defined in class "Difficulty"
   */
  public ConstraintPuzzleRating getRating() {
    ConstraintPuzzle copy = ConstraintPuzzle.getCopy(this);

    ConstraintPuzzleRating r = new ConstraintPuzzleRating();
    if (copy.isSolved()) {
      r.setDifficulty(Difficulty.SOLVED);
    } else if (copy.solveWithBacktracking()) {
      r.setDifficulty(Difficulty.EASY);
    } else {
      r.setDifficulty(Difficulty.UNSOLVABLE);
    }

    return r;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final ConstraintPuzzle cp = (ConstraintPuzzle) obj;

    if (cp.elements.length != elements.length) {
      return false;
    } else {
      for (int i = 0; i < elements.length; i++) {
        if (cp.elements[i] != this.elements[i]) {
          return false;
        }
      }

      return true;
    }
  }

  @Override
  public int hashCode() {
    int runningTotal = 0;

    for (int i = 0; i < elements.length; i++) {
      runningTotal += i * elements[i];
    }

    return runningTotal;
  }

  @Override
  public String toString() {
    String stringRepresentation = "";

    for (int i = 0; i < (size * size); i++) {
      if (i > 0 && i % size == 0) {
        stringRepresentation += "\n";
      }
      stringRepresentation += " " + elements[i];
    }

    return stringRepresentation;
  }

  public boolean elementWithNumberIsEmpty(int elementNumber) {
    return getElementWithNumber(elementNumber) == ConstraintPuzzle.EMPTY_ELEMENT_VALUE;
  }

  public boolean elementAtPositionIsEmpty(int row, int col) {
    return elementWithNumberIsEmpty(getElementNumber(row, col));
  }

  /**
   * Constricts valid elements based on ruleSet stuff.
   *
   * @return true if applied, false if not
   */
  public boolean applyTechniqueRulesetConstriction() {
    boolean appliedTechnique = false;

    Iterator<Integer> emptyElementIterator = emptyElements.iterator();
    while (emptyElementIterator.hasNext() && !appliedTechnique) {
      int nextEmptyElement = emptyElementIterator.next();

      // Remove all valid elements for all related elements
      // Any numbers left over at the end would be the only valid
      // ones.
      Set<Integer> recalculatedValidElements = getValidValuesForElementWithNumber(nextEmptyElement);

      for (int relatedElement : getRelatedElementNumbersForElementWithNumber(nextEmptyElement)) {
        if (elementWithNumberIsEmpty(relatedElement)) {
          recalculatedValidElements.removeAll(getValidValuesForElementWithNumber(relatedElement));
        } else {
          recalculatedValidElements.remove(getElementWithNumber(nextEmptyElement));
        }
      }

      if (recalculatedValidElements.size() != 0) {
        // Work was done...save it and throw flag

        Set<Integer> elementsToRemove = getValidValuesForElementWithNumber(nextEmptyElement);
        elementsToRemove.removeAll(recalculatedValidElements);

        for (int elementToRemove : elementsToRemove) {
          this.removeValueForElementWithNumber(nextEmptyElement, elementToRemove);
        }

        appliedTechnique = true;
      }

    }

    return appliedTechnique;
  }

  protected Set<Integer> emptyElements; // Holds all the empty element numbers
  // Thoughts: if we keep emptyElements arranged by amount of choices for the element, we can gain some performance.
  private int size;
  private Ruleset ruleSet;
  protected Random randomNumberGenerator;
  protected int[] elements;
  protected ArrayList<Set<Integer>> validElementsCache; // Holds valid elements
  protected ArrayList<Set<Integer>> eliminatedValues; // Holds a set of eliminated values, where the arraylist index is the element number
  protected Set<Integer> placedElements; // Holds all the placed element numbers
  private long randomNumberGeneratorSeed;
  public static final int EMPTY_ELEMENT_VALUE = 0;
}


text:
The time zone information is stored in the following key:

```
HKEY_LOCAL_MACHINE\CurrentControlSet\Control\TimeZoneInformation
```

Values:

Name | Data type | Description
--- | --- | ---
ActiveTimeBias | REG_DWORD | The active time bias, in minutes, as configured for the time zone accounting for daylight saving. This is the bias that was used to configure the CMOS clock.
Bias | REG_DWORD | The current bias, in minutes, for local time translation on this computer.
DaylightBias | REG_DWORD | The bias value, in minutes, to be used during local time translations that occur during daylight saving time.
DaylightName | REG_SZ | A description for daylight saving time.
DaylightStart | REG_BINARY | The date and local time when the transition from standard time to daylight saving time occurs on this operating system.
 Contains a SYSTEMTIME structure.
DynamicDaylightTimeDisabled | REG_DWORD | Indicates whether dynamic daylight saving time is disabled.
 0 indicates automatic adjustment
 1 indicates automatic adjustment is disabled
RealTimeIsUniversal | REG_DWORD | Indicates if the CMOS clock is configured by using the local date/time (default) or UTC.
 0 indicates that the CMOS clock is configured for local date/time
 1 indicates that the CMOS clock is configured by using UTC
StandardBias | REG_DWORD | The bias value, in minutes, to be used during local time translations that occur during standard time.
StandardName | REG_SZ | A description for standard time.
StandardStart | REG_BINARY | The date and local time when the transition from daylight saving time to standard time occurs on this operating system.
 Contains a SYSTEMTIME structure.
TimeZoneKeyName | REG_SZ | The name of the Time Zones name sub key.

Notes:

* the relation between the local time and bias is as following:

```
UTC = local time + bias
```

* the names are stored outside the Windows Registry and are references using [MUI Form](https://winreg-kb.readthedocs.io/en/latest/sources/windows-registry/MUI-form.html)
for example:

```
@tzres.dll,-931
```

* the TimeZoneKeyName is not always present
* The RealTimeIsUniversal value is not installed in the system by default and is not officially supported by Windows

The values in this key corresponds with the [TIME_ZONE_INFORMATION](https://docs.microsoft.com/en-us/windows/win32/api/timezoneapi/ns-timezoneapi-time_zone_information)
and [DYNAMIC_TIME_ZONE_INFORMATION](https://docs.microsoft.com/en-us/windows/win32/api/timezoneapi/ns-timezoneapi-dynamic_time_zone_information)
structures.

## Time Zones key

The time zones definitions are stored in the following key:

```
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zones
```

Sub keys:

Name | Description
--- | ---
%TIMEZONENAME% |

%TIMEZONENAME% represents the name of the Windows name of the time zone. The
Unicode organization maintains windowsZones.xml to map the Windows names to
corresponding IANA names.

Values:

Name | Data type | Description
--- | --- | ---
TzVersion | REG_DWORD |

### Time Zones %TIMEZONENAME% sub key

Sub keys:

Name | Description
--- | ---
Dynamic DST | Contains the dynamic daylight saving time values

Note that not every Time Zones name sub key contains a Dynamic Daylight Saving
Time sub key (Dynamic DST).

Values:

Name | Data type | Description
--- | --- | ---
Display | REG_SZ | The display name
Dlt | REG_SZ | The description for daylight time
Index | |
MapID | |
MUI_Display | REG_SZ | The display name in [MUI Form](https://winreg-kb.readthedocs.io/en/latest/sources/windows-registry/MUI-form.html)
MUI_Dlt | REG_SZ | The description for daylight time in [MUI Form](https://winreg-kb.readthedocs.io/en/latest/sources/windows-registry/MUI-form.html)
MUI_Std | REG_SZ | The description for standard time in [MUI Form](https://winreg-kb.readthedocs.io/en/latest/sources/windows-registry/MUI-form.html)
Std | REG_SZ | The description for standard time
TZI | REG_BINARY | Time zone information
 Contains a Registry Time Zone information structure

#### Dynamic Daylight Saving Time sub key

The Dynamic Daylight Saving Time sub key contains time zone information for time zones that apply different daylight saving per year.

Values:

Name | Data type | Description
--- | --- | ---
FirstEntry | REG_DWORD | The first year in the key
LastEntry | REG_DWORD | The last year in the key
%YEAR% | REG_BINARY | Time zone information
 Contains a Registry Time Zone information structure

Where %YEAR% represents the year the dynamic daylight saving time zone
information applies to, e.g. 2006.

### Data Structures

#### SYSTEMTIME structure

The SYSTEMTIME structure is 16 bytes of size and consists of:

Offset | Size | Value | Description
--- | --- | --- | ---
0 | 2 | | Year
2 | 2 | | Month
 Where 1 represents January
4 | 2 | | Day of week
 Where 0 represents Sunday
6 | 2 | | Day of month
 Where 1 represents the first day
8 | 2 | | Hour
 Where hour ranges from 0 to 23
10 | 2 | | Minutes
 Where minutes ranges from 0 to 59
12 | 2 | | Seconds
 Where seconds ranges from 0 to 59
14 | 2 | | Milli seconds
 Where milli seconds ranges from 0 to 999

#### Registry Time Zone information structure

The Registry Time Zone information (`TIME_ZONE_INFORMATION` or
`_REG_TZI_FORMAT`) structure is 44 bytes of size and consists of:

Offset | Size | Value | Description
--- | --- | --- | ---
0 | 4 | | Bias
 Contains the difference between UTC and local time, in minutes
4 | 4 | | StandardBias
 Contains the difference between UTC and local time, in minutes, or 0 if not set
8 | 4 | | DaylightBias
Contains the difference between standard and daylight savings time, in minutes
 The total difference is: Bias + DaylightBias
12 | 16 | | StandardDate
 Date and time when the daylight savings time switches to standard time, in local time
 Contains a SYSTEMTIME structure with year set to 0
28 | 16 | | DaylightDate
 Date and time when the standard time switches to daylight savings time, in local time
 Contains a SYSTEMTIME structure with year set to 0

The wDayOfWeek member of a SYSTEMTIME structure represents the appropriate
weekday, and the wDay member represents the occurrence of the day of the week
within the month, where 5 indicates the final occurrence during the month if
that day of the week only occurs 4 times in the month.

If the wYear member is 0, the date is relative, meaning the daylight savings
occurs yearly. Otherwise the date is abosule, meaning daylight savings only
changes once.

Note that DaylightBias can be set when DaylightDate is not set.

## External Links

* [Computer Time Management and Embedded Systems (Standard 7 SP1)](https://docs.microsoft.com/en-us/previous-versions/windows/embedded/ff794720(v=winembedded.60))
* [TIME_ZONE_INFORMATION structure (timezoneapi.h)](https://docs.microsoft.com/en-us/windows/win32/api/timezoneapi/ns-timezoneapi-time_zone_information)
* [DYNAMIC_TIME_ZONE_INFORMATION structure (timezoneapi.h)](https://docs.microsoft.com/en-us/windows/win32/api/timezoneapi/ns-timezoneapi-dynamic_time_zone_information)
* [SYSTEMTIME structure (minwinbase.h)](https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime)
* [windowsZones.xml](https://github.com/unicode-org/cldr/blob/main/common/supplemental/windowsZones.xml)

redpajama_set_name: RedPajamaGithub


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

import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network';
import { Observable, Subject } from 'rxjs';

/**
 * Emulates the Cordova Globalization plugin in desktop apps and in browser.
 */
@Injectable()
export class NetworkMock extends Network {
    type: null;

    constructor() {
        super();

        (<any> window).Connection = {
            UNKNOWN: 'unknown',
            ETHERNET: 'ethernet',
            WIFI: 'wifi',
            CELL_2G: '2g',
            CELL_3G: '3g',
            CELL_4G: '4g',
            CELL: 'cellular',
            NONE: 'none'
        };
    }

    /**
     * Returns an observable to watch connection changes.
     *
     * @return {Observable<any>} Observable.
     */
    onchange(): Observable<any> {
        return Observable.merge(this.onConnect(), this.onDisconnect());
    }

    /**
     * Returns an observable to notify when the app is connected.
     *
     * @return {Observable<any>} Observable.
     */
    onConnect(): Observable<any> {
        const observable = new Subject<any>();

        window.addEventListener('online', (ev) => {
            observable.next(ev);
        }, false);

        return observable;
    }

    /**
     * Returns an observable to notify when the app is disconnected.
     *
     * @return {Observable<any>} Observable.
     */
    onDisconnect(): Observable<any> {
        const observable = new Subject<any>();

        window.addEventListener('offline', (ev) => {
            observable.next(ev);
        }, false);

        return observable;
    }
}


text:
from django.apps import AppConfig as BaseAppConfig
from django.utils.importlib import import_module

class AppConfig(BaseAppConfig):

    name = "testapp"

    def ready(self):
        import_module("testapp.receivers")


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/main_screen"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="@null"
      android:baselineAligned="false"
      android:clickable="false"
      android:orientation="vertical"
      android:padding="16dp">
    <!--<TextView-->
    <!--android:id="@+id/timerView"-->
    <!--android:layout_width="match_parent"-->
    <!--android:layout_height="wrap_content"-->
    <!--android:gravity="center"-->
    <!--android:paddingBottom="5dp"-->
    <!--android:text="00:00:00"-->
    <!--android:textColor="@android:color/black"-->
    <!--android:textSize="55sp"-->
    <!--android:textStyle="bold"/>-->

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:paddingBottom="8dp"
        android:text="Record"
        android:textAppearance="?android:textAppearanceMedium"
        android:textColor="@android:color/black"/>
    <Button
        android:id="@+id/pauseResumeButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Pause Recording"
        android:visibility="gone"/>

    <LinearLayout
        android:id="@+id/containerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">

      <ImageView
          android:id="@+id/recordButton"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:src="@drawable/ic_microphone"/>

      <ImageView
          android:id="@+id/stopButton"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginTop="40dp"
          android:paddingBottom="5dp"
          android:src="@drawable/stop"/>
    </LinearLayout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    </LinearLayout>

  </LinearLayout>
</LinearLayout>


text:
ActiveRecord::Schema.define(version: 20160619104435) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "players", force: :cascade do |t|
    t.string   "name",       null: false
    t.integer  "elo"
    t.integer  "tier"
    t.integer  "region"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "players_teams", id: false, force: :cascade do |t|
    t.integer "player_id"
    t.integer "team_id"
  end

  add_index "players_teams", ["player_id"], name: "index_players_teams_on_player_id", using: :btree
  add_index "players_teams", ["team_id"], name: "index_players_teams_on_team_id", using: :btree

  create_table "teams", force: :cascade do |t|
    t.integer  "elo",        null: false
    t.integer  "tier"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end


text:
import PlainListBox from "../src/plain/PlainListBox.js";
export default class ElixListBox extends PlainListBox {}
customElements.define("elix-list-box", ElixListBox);


text:
class Object
  def set_attrs (hash, ignore_missing = false)
    hash.each do |key, value|
      self.set_attr key, value, ignore_missing
    end
  end

  def set_attr(name, value, ignore_missing = false)
    self.send "#{name}=", value if !ignore_missing or self.respond_to? :"#{name}="
  end
end


text:
<?php

/* @vinny_shareon/event/overall_header_head_append.html */
class __TwigTemplate_cbb797e436c3612a46f08f8891732771a292053c4b806dc5d056bcf2351d4eaa extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        if (((isset($context["S_SO_STATUS"]) ? $context["S_SO_STATUS"] : null) && (isset($context["S_VIEWTOPIC"]) ? $context["S_VIEWTOPIC"] : null))) {
            // line 2
            echo "\t";
            $asset_file = "@vinny_shareon/shareon.css";
            $asset = new \phpbb\template\asset($asset_file, $this->getEnvironment()->get_path_helper());
            if (substr($asset_file, 0, 2) !== './' && $asset->is_relative()) {
                $asset_path = $asset->get_path();                $local_file = $this->getEnvironment()->get_phpbb_root_path() . $asset_path;
                if (!file_exists($local_file)) {
                    $local_file = $this->getEnvironment()->findTemplate($asset_path);
                    $asset->set_path($local_file, true);
                $asset->add_assets_version('4');
                $asset_file = $asset->get_url();
                }
            }
            $context['definition']->append('STYLESHEETS', '<link href="' . $asset_file . '" rel="stylesheet" type="text/css" media="screen" />
');
        }
    }

    public function getTemplateName()
    {
        return "@vinny_shareon/event/overall_header_head_append.html";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  21 => 2,  19 => 1,);
    }
}
/* <!-- IF S_SO_STATUS and S_VIEWTOPIC -->*/
/* 	<!-- INCLUDECSS @vinny_shareon/shareon.css -->*/
/* <!-- ENDIF -->*/


text:
<manifest package="com.reactivecascade"
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>


text:
<!DOCTYPE html>

<html>
  <head>
    <title>object-fit on input images</title>
    <style type="text/css">
      img, embed, object, input, canvas, video {
        width: 72px;
        height: 72px;
        margin: 2px 10px;
        border: 1px solid black;
        background-color: gray;
      }

      .group { object-fit: contain; }
      .group > *:nth-child(1) { object-fit: fill; }
      .group > *:nth-child(2) { object-fit: contain; }
      .group > *:nth-child(3) { object-fit: cover; }
      .group > *:nth-child(4) { object-fit: none; }
      .group > *:nth-child(5) { object-fit: scale-down; }
      .group > *:nth-child(6) { object-fit: inherit; }
      .group > *:nth-child(7) { }
    </style>
  </head>
  <body>

    <div class="group">
      <input type="image" src="resources/circles-landscape.png">
      <input type="image" src="resources/circles-landscape.png">
      <input type="image" src="resources/circles-landscape.png">
      <input type="image" src="resources/circles-landscape.png">
      <input type="image" src="resources/circles-landscape.png">
      <input type="image" src="resources/circles-landscape.png">
      <input type="image" src="resources/circles-landscape.png">
    </div>

  </body>
</html>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">

  <title>Bringing FeatureLayer by URL</title>

  <link rel="stylesheet" href="https://js.arcgis.com/4.11/esri/themes/dark/main.css">


text:
{{espai_nom}}

    <datepicker ng-model="dt" min-date="minDate" show-weeks="false" date-disabled="disabled(date, mode)" starting-day="1" class="well well-sm"></datepicker>

Nova Reserva el dia {{dt | date:'dd/MM/yyyy'}}

Les reserves son d'una hora.

  <form ng-submit="novaReserva()">

    <select ng-model="hourSelected" ng-options="hour for hour in hours" class="form-control select-reserva">
      <option value="">Hora de la reserva</option>
    </select>

    <button type="submit" class="btn btn-info">Fer reserva</button>

  </form>

Reserves del dia  {{dt | date:'dd/MM/yyyy'}}

{{reserva.user}}

{{reserva.hour}}:00


text:
package MCview;

import jalview.datamodel.*;
import jalview.gui.schemes.ResidueProperties;
import jalview.gui.*;
import apollo.datamodel.*;

import java.awt.*;
import java.util.*;

public class PDBChain {

  public String id;
  public Vector bonds = new Vector();
  public Vector atoms = new Vector();
  public Vector residues = new Vector();
  public int offset;

  public AlignSequenceI sequence;
  public boolean isVisible = false;

  public DrawableSequence ds;

  public PDBChain(String id) {
    this.id = id;
  }

  public String print() {
    String tmp = "";
    for (int i=0; i < bonds.size() ;i++) {
      tmp = tmp + ((Bond)bonds.elementAt(i)).at1.resName + " " + ((Bond)bonds.elementAt(i)).at1.resNumber +" " + offset+ "\n";
    }
    return tmp;
  }
  public void makeCaBondList() {
    for (int i = 0; i < (residues.size() - 1) ; i++) {
      Residue tmpres = (Residue)residues.elementAt(i);
      Residue tmpres2 = (Residue)residues.elementAt(i+1);
      myAtom at1 = tmpres.findAtom("CA");
      myAtom at2 = tmpres2.findAtom("CA");
      if ((at1 != null) && (at2 != null)) {
        if (at1.chain.equals(at2.chain)) {
          makeBond(at1,at2);
        }
      }
    }
  }

  public void makeBond(myAtom at1, myAtom at2) {
    float[] start = new float[3];
    float[] end = new float[3];

    start[0] = at1.x;
    start[1] = at1.y;
    start[2] = at1.z;

    end[0] = at2.x;
    end[1] = at2.y;
    end[2] = at2.z;

    bonds.addElement(new Bond(start, end, at1,at2));
  }

  public void makeResidueList() {
    int count = 0;
    String seq = "";
    for (int i = 0; i < atoms.size(); i++) {

      myAtom tmp = (myAtom)atoms.elementAt(i);
      String resName = tmp.resName;
      int resNumber = tmp.resNumber;
      int res = resNumber;

      if (i ==0) {
        offset = resNumber;
      }
      Vector resAtoms = new Vector();

      resAtoms.addElement((myAtom)atoms.elementAt(i));
      i++;
      resNumber = ((myAtom)atoms.elementAt(i)).resNumber;

      //Add atoms to a vector while the residue number
      //remains the same
      while ((resNumber == res) && (i < atoms.size())) {

        resAtoms.addElement((myAtom)atoms.elementAt(i));
        i++;
        if (i < atoms.size()) {
          resNumber = ((myAtom)atoms.elementAt(i)).resNumber;
        } else {
          resNumber++;
        }
      }

      //We need this to keep in step with the outer for i = loop
      i--;

      //Make a new Residue object with the new atoms vector
      residues.addElement(new Residue(resAtoms, resNumber - 1,count));
      count++;
      Residue tmpres = (Residue)residues.lastElement();
      myAtom tmpat = (myAtom)tmpres.atoms.elementAt(0);

      // Keep totting up the sequence
      if (ResidueProperties.getAA3Hash().get(tmpat.resName) == null) {
        System.out.println("Null aa3Hash for " + tmpat.resName);
      } else {
        String tmpres2 =
          ResidueProperties.aa[((Integer)ResidueProperties.getAA3Hash().get(tmpat.resName)).intValue()];
        seq = seq + tmpres2;
      }
      //      System.out.println(tmpat.resName + " " + tmpres2);
    }
    sequence = new AlignSequence("PDB_seq",seq,1,seq.length());
    System.out.println("Sequence = " + seq);
    System.out.println("No of residues = " +residues.size());
  }

  public void setChargeColours() {
    for (int i = 0; i < bonds.size(); i++) {
      try {
        Bond b = (Bond)bonds.elementAt(i);

        if (b.at1.resName.toUpperCase().equals("ASP") || b.at1.resName.toUpperCase().equals("GLU")) {
          b.startCol = Color.red;
        } else if (b.at1.resName.toUpperCase().equals("LYS") || b.at1.resName.toUpperCase().equals("ARG")) {
          b.startCol = Color.blue;
        } else if (b.at1.resName.toUpperCase().equals("CYS")) {
          b.startCol = Color.yellow;
        } else {
          int atno = ((Integer)ResidueProperties.getAA3Hash().get(b.at1.resName.toUpperCase())).intValue();
          b.startCol = Color.lightGray;
        }
        if (b.at2.resName.toUpperCase().equals("ASP") || b.at2.resName.toUpperCase().equals("GLU")) {
          b.endCol = Color.red;
        } else if (b.at2.resName.toUpperCase().equals("LYS") || b.at2.resName.toUpperCase().equals("ARG")) {
          b.endCol = Color.blue;
        } else if (b.at2.resName.toUpperCase().equals("CYS")) {
          b.endCol = Color.yellow;
        } else {
          int atno = ((Integer)ResidueProperties.getAA3Hash().get(b.at2.resName.toUpperCase())).intValue();
          b.endCol = Color.lightGray;
        }
      } catch (Exception e) {
        Bond b = (Bond)bonds.elementAt(i);
        b.startCol = Color.gray;
        b.endCol = Color.gray;
      }
    }
  }

  public void setHydrophobicityColours() {
    float hydmin = (float)ResidueProperties.getHydmin();
    float hydmax = (float)ResidueProperties.getHydmax();
    double[] hyd  = ResidueProperties.getHyd();

    Hashtable AA3Hash = ResidueProperties.getAA3Hash();

    for (int i = 0; i < bonds.size(); i++) {
      try {
        Bond b = (Bond)bonds.elementAt(i);

        int   atno = ((Integer)AA3Hash.get(b.at1.resName.toUpperCase())).intValue();
        float red  = ((float)hyd[atno] - hydmin)/(hydmax - hydmin);

        if (red > (float)1.0) {
          red = (float)1.0;
        }
        if (red < (float)0.0) {
          red = (float)0.0;
        }

        b.startCol = new Color(red,(float)0.0,(float)1.0-red);
        atno = ((Integer)AA3Hash.get(b.at2.resName.toUpperCase())).intValue();

        red = ((float)hyd[atno] - hydmin)/(hydmax - hydmin);

        if (red > (float)1.0) {
          red = (float)1.0;
        }
        if (red < (float)0.0) {
          red = (float)0.0;
        }

        b.endCol = new Color(red,(float)0.2,(float)1.0-red);
      } catch (Exception e) {
        Bond b = (Bond)bonds.elementAt(i);
        b.startCol = Color.gray;
        b.endCol = Color.gray;
      }
    }
  }

  public void colourBySequence() {
    colourBySequence(this.ds);
  }

  public void colourBySequence(DrawableSequence seq) {
  }

  public void setChainColours() {
    for (int i = 0; i < bonds.size(); i++) {
      Bond tmp = (Bond)bonds.elementAt(i);
      try {
        tmp.startCol = (Color) ResidueProperties.getChainColours().get(id);
        tmp.endCol   = (Color) ResidueProperties.getChainColours().get(id);
      } catch (Exception e) {
        tmp.startCol = Color.lightGray;
        tmp.endCol   = Color.lightGray;
      }
    }
  }
}


text:
package iso

import (
	"errors"
	"fmt"
	"io/ioutil"
	"path/filepath"
)

var (
	// Wrapped errors for testing.
	errInput        = errors.New("invalid or missing input")
	errFileNotFound = errors.New("file not found")
	errMount        = errors.New("error during mounting")
	errNotMounted   = errors.New("iso not mounted")
	errCopy         = errors.New("error during file copy")
	errDismount     = errors.New("error dismounting iso")
	errDmCleanup    = errors.New("error cleaning up mount dir")

	// Dependency injections.
	mountCmd    = mntCmd
	copyCmd     = cpyCmd
	dismountCmd = dmCmd
)

// Handler exposes a uniform method for ISO handling on all platforms.
type Handler struct {
	image    string
	mount    string
	size     uint64
	contents []string
}

// Mount mounts the ISO at the given path and returns a platform-specific
// handler. It is the primary entry point for the ISO package.
func Mount(isoFile string) (*Handler, error) {
	return mount(isoFile)
}

// ImagePath returns the path to the ISO image used when creating the
// ISO handler.
func (iso *Handler) ImagePath() string {
	return iso.image
}

// MountPath returns the path to the directory where the ISO is mounted.
func (iso *Handler) MountPath() string {
	return iso.mount
}

// Contents returns the contents of the ISO as a slice of strings.
func (iso *Handler) Contents() []string {
	return iso.contents
}

// Size returns the size of the ISO that is mounted in bytes.
func (iso *Handler) Size() uint64 {
	return iso.size
}

// contents returns a list of the contents of a directory.
func contents(path string) ([]string, error) {
	if path == "" {
		return []string{}, errInput
	}
	// Enumerate the contents.
	list, err := ioutil.ReadDir(path)
	if err != nil {
		return nil, fmt.Errorf("ioutil.ReadDir(%s) returned %v: %w", path, err, errFileNotFound)
	}
	var contents []string
	for _, f := range list {
		// Construct complete dir/dest paths
		fullPath := filepath.Join(path, f.Name())
		contents = append(contents, fullPath)
	}
	return contents, nil
}


text:
<?php

namespace Encore\Admin\Form\Field;

use Encore\Admin\Admin;

class CheckboxButton extends Checkbox
{
    /**
     * @var string
     */
    protected $cascadeEvent = 'change';

    protected function addScript()
    {
        $script = <<<'SCRIPT'
$('.checkbox-group-toggle label').click(function(e) {
    e.stopPropagation();
    e.preventDefault();

    if ($(this).hasClass('active')) {
        $(this).removeClass('active');
        $(this).find('input').prop('checked', false);
    } else {
        $(this).addClass('active');
        $(this).find('input').prop('checked', true);
    }

    $(this).find('input').trigger('change');
});
SCRIPT;

        Admin::script($script);
    }

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        $this->addScript();

        $this->addCascadeScript();

        $this->addVariables([
            'options' => $this->options,
            'checked' => $this->checked,
        ]);

        return parent::fieldRender();
    }
}


text:
<?php

namespace PortailPro\Bundle\CalogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * Security controller.
 *
 */
class SecurityController extends Controller
{

    public function loginAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();
        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }
        return $this->render('PortailProCalogBundle:Security:login.html.twig', array(
            // last username entered by the user
            'last_username' => $session->get(SecurityContext::LAST_USERNAME),
            'error'         => $error,
        ));
    }

}


text:
using ATSPM.Application.Models;
using MOE.Common.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ATSPM.Infrastructure.Repositories.EntityFramework
{
    public class RouteRepository : IRouteRepository
    {
        private readonly MOEContext _db;

        public RouteRepository(MOEContext db)
        {
            this._db = db;
        }

        public List<Route> GetAllRoutes()
        {
            var routes = (from r in _db.Routes
                          orderby r.RouteName
                          select r).ToList();
            return routes;
        }

        public Route GetRouteByID(int routeID)
        {

            throw new NotImplementedException();
            //var route = db.Routes
            //    .Include(r => r.RouteSignals.Select(s => s.PhaseDirections)).FirstOrDefault(r => r.Id == routeID);
            //route.RouteSignals = route.RouteSignals.OrderBy(s => s.Order).ToList();
            //var signalRepository = new SignalsRepository();
            //foreach (var routeSignal in route.RouteSignals)
            //{
            //    routeSignal.Signal = signalRepository.GetLatestVersionOfSignalBySignalID(routeSignal.SignalId);
            //}
            //if (route != null)
            //    return route;
            //var repository = new ApplicationEventRepository();
            //var error = new ApplicationEvent();
            //error.ApplicationName = "MOE.Common";
            //error.Class = "Models.Repository.ApproachRouteRepository";
            //error.Function = "GetByRouteID";
            //error.Description = "No Route for ID.  Attempted ID# = " + routeID;
            //error.SeverityLevel = ApplicationEvent.SeverityLevels.High;
            //error.Timestamp = DateTime.Now;
            //repository.Add(error);
            //throw new Exception("There is no Route for this ID");
        }

        public Route GetRouteByIDAndDate(int routeId, DateTime startDate)
        {
            throw new NotImplementedException();
            //var route = db.Routes
            //    //TODO.Include(r => r.RouteSignals.Select(s => s.PhaseDirections)).FirstOrDefault(r => r.Id == routeId);
            //route.RouteSignals = route.RouteSignals.OrderBy(s => s.Order).ToList();
            //var signalRepository = new SignalsRepository();
            //foreach (var routeSignal in route.RouteSignals)
            //{
            //    routeSignal.Signal = signalRepository.GetVersionOfSignalByDate(routeSignal.SignalId, startDate);
            //}
            //if (route != null)
            //    return route;
            //return route;
        }

        public Route GetRouteByName(string routeName)
        {
            var route = (from r in _db.Routes
                         where r.RouteName == routeName
                         select r).FirstOrDefault();
            return route;
        }

        public void DeleteByID(int routeID)
        {
            var route = (from r in _db.Routes
                         where r.Id == routeID
                         select r).FirstOrDefault();

            _db.Routes.Remove(route);
            _db.SaveChanges();
        }

        public void Update(Route newRoute)
        {
            var route = (from r in _db.Routes
                         where r.Id == newRoute.Id
                         select r).FirstOrDefault();

            if (route != null)
            {
                var newroute = new Route();

                newroute.Id = route.Id;
                newroute.RouteName = newroute.RouteName;
                try
                {
                    _db.Entry(route).CurrentValues.SetValues(newroute);
                    _db.SaveChanges();
                }

                catch (Exception ex)
                {

                    var repository = new ApplicationEventRepository(_db);
                    var error = new ApplicationEvent();
                    error.ApplicationName = "MOE.Common";
                    error.Class = "Models.Repository.ApproachRouteRepository";
                    error.Function = "UpdateByID";
                    error.Description = ex.Message;
                    error.SeverityLevel = (int)ApplicationEvent.SeverityLevels.High;
                    error.Timestamp = DateTime.Now;
                    repository.Add(error);
                    throw;
                }
            }
        }

        public void Add(Route newRoute)
        {
            try
            {
                _db.Routes.Add(newRoute);
                _db.SaveChanges();
            }

            catch (Exception ex)
            {

                var repository = new ApplicationEventRepository(_db);
                var error = new ApplicationEvent();
                error.ApplicationName = "MOE.Common";
                error.Class = "Models.Repository.ApproachRouteRepository";
                error.Function = "Add";
                error.Description = ex.Message;
                error.SeverityLevel = (int)ApplicationEvent.SeverityLevels.High;
                error.Timestamp = DateTime.Now;
                repository.Add(error);
                throw;
            }
        }
    }
}


text:
trap(:PIPE) { warn 'Catched SIGPIPE signal' } if Signal.list.include? 'PIPE'
trap(:SYS)  { warn 'Catched SIGSYS signal' }  if Signal.list.include? 'SYS'

trap(:USR1) { settings[:lfv]&.reload } if Signal.list.include? 'USR1'


text:
<ScrollView sdkExampleTitle sdkToggleNavButton>
    <FlexboxLayout flexDirection="column">

        <FlexboxLayout flexDirection="row" class="p-15" color="white">

        </FlexboxLayout>

        <FlexboxLayout flexDirection="row" align-content="space-between" class="p-15" color="white">

        </FlexboxLayout>

        <FlexboxLayout flexDirection="row" class="p-15" color="white">

        </FlexboxLayout>

        <FlexboxLayout flexDirection="row" class="p-15" color="white" width="300">

        </FlexboxLayout>
        git status
    </FlexboxLayout>
</ScrollView>


text:
namespace PR {

class Scene;
class ISpectralMapper;

// Abstraction over infinite and area lights
class PR_LIB_CORE LightSampler {
public:
	using LightList = std::vector<std::unique_ptr<Light>>;

	LightSampler(Scene* scene, const SpectralRange& cameraSpectralRange);
	virtual ~LightSampler() {}

	inline const Light* sample(float rnd, float& pdf) const;
	inline std::pair<const Light*, float> sample(const LightSampleInput& in, LightSampleOutput& out, const RenderTileSession& session) const;

	inline float pdfLightSelection(const Light* light) const;
	inline float pdfEntitySelection(const IEntity* entity) const;
	inline LightPDF pdfPosition(const IEntity* entity, const Vector3f& posOnLight, const EntitySamplingInfo* info = nullptr) const;
	inline float pdfDirection(const Vector3f& dir, const IEntity* entity, float cosLight = 1.0f) const;
	inline const Light* light(const IEntity* entity) const;

	inline const LightList& lights() const { return mLights; }
	inline const std::vector<Light*>& infiniteLights() const { return mInfLights; }

	inline size_t emissiveEntityCount() const { return mLightEntityMap.size(); }
	inline size_t lightCount() const { return mLights.size(); }

	inline float emissiveSurfaceArea() const { return mEmissiveSurfaceArea; }
	inline float emissiveSurfacePower() const { return mEmissiveSurfacePower; }
	inline float emissivePower() const { return mEmissivePower; }
	inline const SpectralRange& cameraSpectralRange() const { return mCameraSpectralRange; }
	inline const SpectralRange& lightSpectralRange() const { return mLightSpectralRange; }

	inline void setWavelengthSampler(const std::shared_ptr<ISpectralMapper>& mapper) { mWavelengthSampler = mapper; }
	inline ISpectralMapper* wavelengthSampler() const { return mWavelengthSampler.get(); }

private:
	using LightEntityMap = std::unordered_map<const IEntity*, size_t>;

	LightList mLights;
	LightEntityMap mLightEntityMap;
	std::vector<Light*> mInfLights; // Special purpose cache, as we expect inf lights be way less then area lights
	std::unique_ptr<Distribution1D> mSelector;
	float mInfLightSelectionProbability;
	float mEmissiveSurfaceArea;
	float mEmissiveSurfacePower;
	float mEmissivePower; // Including inf lights
	const SpectralRange mCameraSpectralRange;
	SpectralRange mLightSpectralRange;

	std::shared_ptr<ISpectralMapper> mWavelengthSampler;
};
} // namespace PR

#include "LightSampler.inl"


text: export const tag = {"viewBox":"0 0 20 20","children":[{"name":"g","attribs":{}}]};


text:
define([
  'dojo/_base/declare',
  './_BasicServiceBrowser',
  'dojo/_base/lang',
  'dojo/_base/array',
  'jimu/serviceBrowserRuleUtils'
],
function(declare, _BasicServiceBrowser, lang, array, serviceBrowserRuleUtils) {
  return declare([_BasicServiceBrowser], {
    baseClass: 'jimu-featurelayer-service-browser',
    declaredClass: 'jimu.dijit.FeaturelayerServiceBrowser',

    //options:
    url: '',
    multiple: false,
    types: null,//available values:point,polyline,polygon
    isSupportQuery: true,//if true, only filter queryable feature layer

    //public methods:
    //setUrl
    //getSelectedItems return [{name,url,definition}]

    //test url:
    //base url: http://sampleserver1.arcgisonline.com/ArcGIS/rest/services
    //folder url:  http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics
    //service url: http://tryitlive.arcgis.com/arcgis/rest/services/GeneralPurpose/MapServer
    //group layer url: http://tryitlive.arcgis.com/arcgis/rest/services/GeneralPurpose/MapServer/0
    //group layer url: http://tryitlive.arcgis.com/arcgis/rest/services/GeneralPurpose/MapServer/1
    //layer url: http://tryitlive.arcgis.com/arcgis/rest/services/GeneralPurpose/MapServer/2

    postMixInProperties:function(){
      this.inherited(arguments);
      this.rule = serviceBrowserRuleUtils.getFeaturelayerServiceBrowserRule(this.types,
                                                                            this.isSupportQuery);
    },

    getSelectedItems: function(){
      var items = this.inherited(arguments);
      items = array.map(items, lang.hitch(this, function(item){
        return {
          name: item.name,
          url: item.url,
          definition: item.definition
        };
      }));
      return items;
    }

  });
});


text:
module Semmy
  module VersionFile
    extend self

    class NotFound < Error; end

    class ConstantNotFound < Error; end

    class UpdateFailed < Error; end

    def find(gem_name)
      gem_name_matcher = gem_name.gsub(/[_-]/, '[/_-]')

      Dir.glob('lib/**/version.rb').detect do |file_name|
        file_name =~ %r{lib/#{gem_name_matcher}/version.rb}
      end || fail(NotFound, 'No version file found.')
    end

    def parse_version(contents)
      match = contents.match(/VERSION\s*=\s*['"]([^'"]+)['"]/) ||
        fail(ConstantNotFound, 'Could not find version constant')

      match[1]
    end

    Update = Struct.new(:new_version) do
      def call(contents)
        contents.dup.tap do |result|
          result.gsub!(/VERSION\s*=\s*(['"])[^']+['"]/,
                       "VERSION = \\1#{new_version}\\1") ||
            fail(UpdateFailed,
                 "Could not update version to #{new_version} in\n\n#{contents}\n\n")
        end
      end
    end
  end
end


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;

/**
 *
 * For vehicles listed through the US eBay Motors site, DepositType
 * indicates how the buyer should pay the deposit amount. It is
 * used in conjunction with a buyer payment method (BuyerPaymentMethodCodeType).
 *
 */
public enum DepositTypeCodeType {

    /**
     *
   *   (out) No deposit needed.
   *
     */
    NONE("None"),

    /**
     *
   *   (out) Pay the deposit using PayPal, and then
   *   use any of the other specified payment methods to pay the balance.
   *
     */
    OTHER_METHOD("OtherMethod"),

    /**
     *
   *    (out) No longer used.
   *
     */
    FAST_DEPOSIT("FastDeposit"),

    /**
     *
   *   (out) Reserved for internal or future use
   *
     */
    CUSTOM_CODE("CustomCode");

    private final String value;

    DepositTypeCodeType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static DepositTypeCodeType fromValue(String v) {
        if (v != null) {
            for (DepositTypeCodeType c: DepositTypeCodeType.values()) {
                if (c.value.equals(v)) {
                    return c;
                }
            }
        }
        throw new IllegalArgumentException(v);
    }
}


text:
/*
 * SoundBank.h
 *
 *  Created on: 14 Feb 2016
 *      Author: jeremy
 */

#ifndef SOURCE_SOUND_SOUNDBANK_SOUNDBANK_H_
#define SOURCE_SOUND_SOUNDBANK_SOUNDBANK_H_

#include "../Sound.h"

#include <string>
#include <vector>

namespace Sound
{

	class Mixer;

	class SoundBank
	{

	friend class Mixer;

	public:

		explicit SoundBank(const std::string& dataFolder) noexcept;
		virtual ~SoundBank();

		static std::vector<std::string> GetSoundFiles(const std::string& dataFolder);

		int LoadSound(const std::string& filename);
		int LoadSound(const std::string& filename, float volume);
		int AddSound(const std::vector<short>& soundData);
		int AddSound(const std::vector<short>& soundData, float volume);
		int AddSound(Sound&& sound, float volume);
		void DeleteSound(int id);
		void LoopSound(int id, bool s);
		void Clear() noexcept { std::vector<Sound>().swap(sounds); }

		void SetSoundVolume(int id, float volume) { sounds[id].SetVolume(volume); }

		const Sound& GetSound(int id) const { return sounds[id]; }

	private:

		std::string soundBankFolder;
		std::vector<Sound> sounds;

	};

} /* namespace Sound */

#endif /* SOURCE_SOUND_SOUNDBANK_SOUNDBANK_H_ */


text:
const Action = require('./Action');

class GuildSync extends Action {
  handle(data) {
    const client = this.client;

    const guild = client.guilds.get(data.id);
    if (guild) {
      data.presences = data.presences || [];
      for (const presence of data.presences) {
        guild._setPresence(presence.user.id, presence);
      }

      data.members = data.members || [];
      for (const syncMember of data.members) {
        const member = guild.members.get(syncMember.user.id);
        if (member) {
          guild._updateMember(member, syncMember);
        } else {
          guild._addMember(syncMember);
        }
      }
    }
  }
}

module.exports = GuildSync;


text:
<?php

namespace GpsLab\Domain\Event\Bus;

use GpsLab\Domain\Event\Aggregator\AggregateEvents;
use GpsLab\Domain\Event\Event;
use GpsLab\Domain\Event\Listener\Locator\EventListenerLocator;

class ListenerLocatedEventBus implements EventBus
{
    /**
     * @var EventListenerLocator
     */
    private $locator;

    /**
     * @param EventListenerLocator $locator
     */
    public function __construct(EventListenerLocator $locator)
    {
        $this->locator = $locator;
    }

    /**
     * Publishes the event to every listener that wants to.
     *
     * @param Event $event
     */
    public function publish(Event $event)
    {
        foreach ($this->locator->listenersOfEvent($event) as $listener) {
            call_user_func($listener, $event);
        }
    }

    /**
     * @param AggregateEvents $aggregator
     */
    public function pullAndPublish(AggregateEvents $aggregator)
    {
        foreach ($aggregator->pullEvents() as $event) {
            $this->publish($event);
        }
    }
}


text:
import os
import subprocess

on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if on_rtd:
    subprocess.call('cd ..; doxygen', shell=True)

import sphinx_rtd_theme

html_theme = "sphinx_rtd_theme"

html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

def setup(app):
    app.add_stylesheet("main_stylesheet.css")

extensions = ['breathe']
breathe_projects = { 'xsimd': '../xml' }
templates_path = ['_templates']
html_static_path = ['_static']
source_suffix = '.rst'
master_doc = 'index'
project = 'xsimd'
copyright = '2016, Johan Mabille and Sylvain Corlay'
author = 'Johan Mabille and Sylvain Corlay'

html_logo = 'quantstack-white.svg'

exclude_patterns = []
highlight_language = 'c++'
pygments_style = 'sphinx'
todo_include_todos = False
htmlhelp_basename = 'xsimddoc'


text:
namespace java.lang
{
    public partial class NoSuchFieldException : ReflectiveOperationException
    {
        public NoSuchFieldException(){}
        public NoSuchFieldException(String prm1){}
    }
}


text:
import sys

contents = "Hello from make-file.py\n"

open(sys.argv[1], 'wb').write(contents)


text:
class DayTableEnv;
class NativeAppState;

DayTableEnv* NewDayTableAndroidEnv(NativeAppState* state);

#endif  // VIEWFINDER_DAY_TABLE_ENV_H

// local variables:
// mode: c++
// end:


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE416_Use_After_Free__new_delete_array_int64_t_62b.cpp
Label Definition File: CWE416_Use_After_Free__new_delete_array.label.xml
Template File: sources-sinks-62b.tmpl.cpp
*/
/*
 * @description
 * CWE: 416 Use After Free
 * BadSource:  Allocate data using new, initialize memory block, and Deallocate data using delete
 * GoodSource: Allocate data using new and initialize memory block
 * Sinks:
 *    GoodSink: Do nothing
 *    BadSink : Use data after delete[]
 * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE416_Use_After_Free__new_delete_array_int64_t_62
{

#ifndef OMITBAD

void badSource(int64_t * &data)
{
    data = new int64_t[100];
    {
        size_t i;
        for(i = 0; i < 100; i++)
        {
            data[i] = 5LL;
        }
    }
    /* POTENTIAL FLAW: Delete data in the source - the bad sink attempts to use data */
    delete [] data;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
void goodG2BSource(int64_t * &data)
{
    data = new int64_t[100];
    {
        size_t i;
        for(i = 0; i < 100; i++)
        {
            data[i] = 5LL;
        }
    }
    /* FIX: Do not delete data in the source */
}

/* goodB2G() uses the BadSource with the GoodSink */
void goodB2GSource(int64_t * &data)
{
    data = new int64_t[100];
    {
        size_t i;
        for(i = 0; i < 100; i++)
        {
            data[i] = 5LL;
        }
    }
    /* POTENTIAL FLAW: Delete data in the source - the bad sink attempts to use data */
    delete [] data;
}

#endif /* OMITGOOD */

} /* close namespace */


text:
<?php

namespace Synapse\Cmf\Framework\Theme\Content\Tests\Resolver;

use Synapse\Cmf\Framework\Engine\Exception\InvalidContentException;
use Synapse\Cmf\Framework\Theme\ContentType\Entity\ContentType;
use Synapse\Cmf\Framework\Theme\ContentType\Entity\ContentTypeCollection;
use Synapse\Cmf\Framework\Theme\ContentType\Loader\LoaderInterface;
use Synapse\Cmf\Framework\Theme\Content\Entity\Content;
use Synapse\Cmf\Framework\Theme\Content\Model\ContentInterface;
use Synapse\Cmf\Framework\Theme\Content\Provider\ContentProviderInterface;
use Synapse\Cmf\Framework\Theme\Content\Resolver\ContentResolver;

/**
 * Unit test class for ContentResolver service.
 */
class ContentResolverTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Tests resolve() method.
     */
    public function testResolve()
    {
        $contentTypeLoader = $this->prophesize(LoaderInterface::class);
        $contentTypeLoader->retrieveAll()
            ->willReturn(new ContentTypeCollection(array(
                $contentType = (new ContentType())
                    ->setId('synapse.content.type')
                    ->setContentClass(LocalContent::class),
                (new ContentType())
                    ->setId('synapse.content.type2')
                    ->setContentClass(LocalContent::class),
            )))
            ->shouldBeCalled()
        ;

        $contentResolver = new ContentResolver($contentTypeLoader->reveal());
        $localContent = new LocalContent();

        $this->assertEquals(
            new Content($localContent, $contentType),
            $content = $contentResolver->resolve($localContent)
        );
    }

    /**
     * Tests resolve() method with an unsupported content.
     */
    public function testResolveBadContent()
    {
        $contentTypeLoader = $this->prophesize(LoaderInterface::class);
        $contentTypeLoader->retrieveAll()
            ->willReturn(new ContentTypeCollection(array()))
            ->shouldBeCalled()
        ;

        $this->setExpectedException(InvalidContentException::class);

        $contentResolver = new ContentResolver($contentTypeLoader->reveal());
        $contentResolver->resolve(new LocalContent());
    }

    /**
     * Tests resolveContentId() method.
     */
    public function testResolveContentId()
    {
        $contentProvider = $this->prophesize(ContentProviderInterface::class);
        $contentProvider->retrieveContent(42)
            ->willReturn($localContent = new LocalContent())
            ->shouldBeCalled()
        ;

        $contentTypeLoader = $this->prophesize(LoaderInterface::class);
        $contentTypeLoader->retrieve('content_type_id')
            ->willReturn($contentType = (new ContentType())
                ->setId('content_type_id')
                ->setContentClass(LocalContent::class)
                ->setContentLoader($contentProvider->reveal())
            )
            ->shouldBeCalled()
        ;

        $contentResolver = new ContentResolver($contentTypeLoader->reveal());
        $this->assertEquals(
            new Content($localContent, $contentType),
            $content = $contentResolver->resolveContentId('content_type_id', 42)
        );
    }

    /**
     * Test resolveContentId() method with a bad content type.
     */
    public function testResolveContentIdBadContentType()
    {
        $contentTypeLoader = $this->prophesize(LoaderInterface::class);
        $contentTypeLoader->retrieve('content_type_id')->shouldBeCalled();

        $this->setExpectedException(InvalidContentException::class);

        $contentResolver = new ContentResolver($contentTypeLoader->reveal());
        $contentResolver->resolveContentId('content_type_id', 42);
    }

    /**
     * Test resolveContentId() method with a bad content type.
     */
    public function testResolveContentIdContentNotFound()
    {
        $contentProvider = $this->prophesize(ContentProviderInterface::class);
        $contentProvider->retrieveContent(42)
            ->shouldBeCalled()
        ;

        $contentTypeLoader = $this->prophesize(LoaderInterface::class);
        $contentTypeLoader->retrieve('content_type_id')
            ->willReturn($contentType = (new ContentType())
                ->setId('content_type_id')
                ->setContentClass(LocalContent::class)
                ->setContentLoader($contentProvider->reveal())
            )
            ->shouldBeCalled()
        ;

        $this->setExpectedException(InvalidContentException::class);

        $contentResolver = new ContentResolver($contentTypeLoader->reveal());
        $contentResolver->resolveContentId('content_type_id', 42);
    }
}

class LocalContent implements ContentInterface
{
    public function getContentId()
    {
        return 42;
    }
}


text:
TEST(OptionTest, Min)
{
  Option<int> none1 = None();
  Option<int> none2 = None();
  Option<int> value1 = 10;
  Option<int> value2 = 20;
  int value3 = 15;

  Option<int> result = min(none1, none2);
  ASSERT_NONE(result);

  result = min(none1, value1);
  ASSERT_SOME(result);
  EXPECT_EQ(10, result.get());

  result = min(value2, none2);
  ASSERT_SOME(result);
  EXPECT_EQ(20, result.get());

  result = min(value1, value2);
  ASSERT_SOME(result);
  EXPECT_EQ(10, result.get());

  result = min(none1, value3);
  ASSERT_SOME(result);
  EXPECT_EQ(15, result.get());

  result = min(value3, value1);
  ASSERT_SOME(result);
  EXPECT_EQ(10, result.get());
}

TEST(OptionTest, Max)
{
  Option<int> none1 = None();
  Option<int> none2 = None();
  Option<int> value1 = 10;
  Option<int> value2 = 20;
  int value3 = 15;

  Option<int> result = max(none1, none2);
  ASSERT_NONE(result);

  result = max(none1, value1);
  ASSERT_SOME(result);
  EXPECT_EQ(10, result.get());

  result = max(value2, none2);
  ASSERT_SOME(result);
  EXPECT_EQ(20, result.get());

  result = max(value1, value2);
  ASSERT_SOME(result);
  EXPECT_EQ(20, result.get());

  result = max(none1, value3);
  ASSERT_SOME(result);
  EXPECT_EQ(15, result.get());

  result = max(value3, value2);
  ASSERT_SOME(result);
  EXPECT_EQ(20, result.get());
}

TEST(OptionTest, Comparison)
{
  Option<int> none = None();
  EXPECT_NE(none, 1);
  EXPECT_FALSE(none == 1);

  Option<int> one = 1;
  EXPECT_EQ(one, 1);
  EXPECT_NE(none, one);
  EXPECT_FALSE(none == one);
  EXPECT_EQ(one, Option<int>::some(1));

  Option<int> two = 2;
  EXPECT_NE(one, two);

  Option<Option<int> > someNone = Option<Option<int> >::some(None());
  Option<Option<int> > noneNone = Option<Option<int> >::none();
  EXPECT_NE(someNone, noneNone);
  EXPECT_NE(noneNone, someNone);
}


text:
<?xml version="1.0"?>

<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Basic>
    <Title>Title01</Title>
    <Buttons>
      <Button X="0" Y="0" Key="NumPad9" />
      <Button X="0" Y="1" Key="NumPad6" />
      <Button X="0" Y="2" Key="NumPad3" />
      <Button X="0" Y="3" Key="NumPad5" />
    </Buttons>
    <WindowLocation X="99999" Y="0" />
  </Basic>
  <ApplicationGroups>
    <ApplicationGroup Name="CLIP STUDIO PAINT B">
      <MatchingRoule>
        <ExeName>ClipStudioPaint.exe</ExeName>
        <WindowTitlePatterns>
          <Pattern>*CLIP STUDIO PAINT</Pattern>
          <Pattern>ショートカット設定</Pattern>
        </WindowTitlePatterns>
      </MatchingRoule>
      <Banks>
        <Bank Name="">
            <Entry Trigger="NumPad9" LabelText="前景B" BackColor="#FF0000FF">
            <ActionItem ActionType="Send" ActionValue=" B" NextBank="曲線" />
          </Entry>
          <Entry Trigger="NumPad6" LabelText="前景B" BackColor="#FF0000FF">
            <ActionItem ActionType="Key" ActionValue=" "  />
          </Entry>
          <Entry Trigger="NumPad3" LabelText="メニューB" BackColor="#FF0000FF">
            <ActionItem ActionType="Key" ActionValue=" "  />
          </Entry>
        </Bank>
        <Bank Name="ほげ">

        </Bank>
        <Bank Name="ふが"></Bank>
        <Bank Name="曲線">
          <Entry Trigger="S" LabelText="曲線01B" BackColor="#FF0000FF">
            <ActionItem ActionType="Send" ActionValue="SendText" />
          </Entry>
          <Entry Trigger="D" LabelText="曲線02B" >
            <ActionItem ActionType="Send" ActionValue="SendText" />
          </Entry>
        </Bank>
      </Banks>
      <Menus>
        <Menu Name="menu01">
          <MenuItem X="0" Y="0" LabelText="前景" BackColor="#FF0000FF">
            <ActionItem ActionType="None" />
          </MenuItem>
          <MenuItem X="0" Y="0" LabelText="前景" BackColor="#FF0000FF">
            <ActionItem ActionType="None" />
          </MenuItem>
        </Menu>
      </Menus>
    </ApplicationGroup>
  </ApplicationGroups>
</Config>


text:
namespace hobbes {

struct eventcbclosure {
  eventcbclosure(int fd, const std::function<void(int)>& fn) : fd(fd), fn(fn) { }

  int                      fd;
  std::function<void(int)> fn;
};
typedef std::map<int, eventcbclosure*> EventClosures;

void registerEventHandler(int fd, eventhandler fn, void* ud, bool f) {
  registerEventHandler(fd, [fn,ud](int c){fn(c,ud);}, f);
}

#ifdef BUILD_LINUX
thread_local bool           epInitialized = false;
thread_local int            epFD          = 0;
thread_local EventClosures* epClosures    = 0;

struct timer {
  timerfunc func;
  std::chrono::high_resolution_clock::time_point callTime;
  std::chrono::milliseconds interval;
};

bool operator>(const timer& a, const timer& b) {
  return a.callTime > b.callTime;
}

thread_local std::priority_queue<timer, std::vector<timer>, std::greater<timer>> timers;

int threadEPollFD() {
  if (!epInitialized) {
    epFD       = epoll_create(1);
    epClosures = new EventClosures();

    if (epFD < 0) {
      throw std::runtime_error("Failed to allocate epoll FD: " + std::string(strerror(errno)));
    }
    epInitialized = true;
  }
  return epFD;
}

void unregisterEventHandler(int fd) {
  auto ec = epClosures->find(fd);
  if (ec != epClosures->end()) {
    struct epoll_event evt;
    epoll_ctl(threadEPollFD(), EPOLL_CTL_DEL, fd, &evt);
    delete ec->second;
  }
}

void registerEventHandler(int fd, const std::function<void(int)>& fn, bool) {
  int epfd = threadEPollFD();

  eventcbclosure* c = new eventcbclosure(fd, fn);
  (*epClosures)[fd] = c;

  struct epoll_event evt;
  memset(&evt, 0, sizeof(evt));
  evt.events   = EPOLLIN | EPOLLPRI | EPOLLERR;
  evt.data.fd  = fd;
  evt.data.ptr = reinterpret_cast<void*>(c);

  if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &evt) != 0) {
    delete c;
    throw std::runtime_error("Failed to add FD to epoll set: " + std::string(strerror(errno)));
  }
}

void registerInterruptHandler(const std::function<void()>& fn) {
  threadEPollFD();
  auto* c = new eventcbclosure(-1, [fn](int){fn();});
  (*epClosures)[-1] = c;
}

bool stepEventLoop(int timeoutMS) {
  while (true) {
    if (!timers.empty()) {
      auto next = timers.top().callTime;
      auto timeUntilNext = next - std::chrono::high_resolution_clock::now();
      int millis = std::chrono::duration_cast<std::chrono::milliseconds>(timeUntilNext).count();
      timeoutMS = std::max(1, millis);
    }

    struct epoll_event evts[64];
    int fds = epoll_wait(threadEPollFD(), evts, sizeof(evts)/sizeof(evts[0]), timeoutMS);
    bool status = true;
    if (fds > 0) {
      for (int fd = 0; fd < fds; ++fd) {
        eventcbclosure* c = reinterpret_cast<eventcbclosure*>(evts[fd].data.ptr);
        (c->fn)(c->fd);
        resetMemoryPool();
      }
    } else if (fds < 0) {
      if (errno != EINTR) {
        status = false;
      } else if (epClosures) {
        auto f = epClosures->find(-1);
        if (f != epClosures->end()) {
          f->second->fn(-1);
        }
      }
    } else if (!timers.empty()) {
      std::vector<timer> newTimers;

      auto now = std::chrono::high_resolution_clock::now();
      while(!timers.empty() && timers.top().callTime <= now) {
        auto t = timers.top();
        timers.pop();

        bool repeat = t.func();
        resetMemoryPool();

        if(repeat) {
          timer newT;
          newT.callTime = std::chrono::high_resolution_clock::now() + t.interval,
          newT.func = t.func,
          newT.interval = t.interval,

          newTimers.push_back(newT);
        }
      }

      for (auto& timer : newTimers) {
        timers.push(timer);
      }
    }
    return status;
  }
}

void runEventLoop() {
  while (stepEventLoop());
}

void addTimer(timerfunc f, int millisecInterval) {
  timer t;
  t.func = f;
  t.interval = std::chrono::milliseconds(millisecInterval);
  t.callTime = std::chrono::high_resolution_clock::now() + t.interval;

  timers.push(t);
}

void runEventLoop(int microsecondDuration) {
  long t  = hobbes::time();
  long dt = static_cast<long>(microsecondDuration) * 1000L;
  long tf = t + dt;

  do {
    double nsleft = tf-t;
    int timeout = (ceil(nsleft / 1000000.0));
    if (timeout < 0) timeout = 0;

    struct epoll_event evts[64];
    int fds = epoll_wait(threadEPollFD(), evts, sizeof(evts)/sizeof(evts[0]), timeout);
    if (fds > 0) {
      for (int fd = 0; fd < fds; ++fd) {
        eventcbclosure* c = reinterpret_cast<eventcbclosure*>(evts[fd].data.ptr);
        (c->fn)(c->fd);
        resetMemoryPool();
      }
    }
    t = hobbes::time();
  } while (t < tf);
}

#elif defined(BUILD_OSX)

thread_local bool           kqInitialized = false;
thread_local int            kqFD          = 0;
thread_local EventClosures* kqClosures    = 0;

int threadKQFD() {
  if (!kqInitialized) {
    kqFD       = kqueue();
    kqClosures = new EventClosures();

    if (kqFD < 0) {
      throw std::runtime_error("Failed to allocate kqueue: " + std::string(strerror(errno)));
    }
    kqInitialized = true;
  }
  return kqFD;
}

void unregisterEventHandler(int fd) {
  auto ec = kqClosures->find(fd);
  if (ec != kqClosures->end()) {
    struct kevent ke;
    EV_SET(&ke, fd, EVFILT_READ, EV_DELETE, 0, 0, 0);
    kevent(threadKQFD(), &ke, 1, 0, 0, 0);
    delete ec->second;
  }
}

void registerEventHandler(int fd, const std::function<void(int)>& fn, bool vn) {
  int kqfd = threadKQFD();

  eventcbclosure* c = new eventcbclosure(fd, fn);
  (*kqClosures)[fd] = c;

  struct kevent ke;
  if (vn) {
    EV_SET(&ke, fd, EVFILT_VNODE, EV_ADD, NOTE_DELETE | NOTE_WRITE, 0, (void*)c);
  } else {
    EV_SET(&ke, fd, EVFILT_READ, EV_ADD, 0, 0, (void*)c);
  }
  if (kevent(kqfd, &ke, 1, 0, 0, 0) == -1) {
    delete c;
    throw std::runtime_error("Failed to add FD to kqueue: " + std::string(strerror(errno)));
  }
}

void registerInterruptHandler(const std::function<void()>& fn) {
  threadKQFD();
  auto* c = new eventcbclosure(-1, [fn](int){fn();});
  (*kqClosures)[-1] = c;
}

bool stepEventLoop(int timeoutMS) {
  while (true) {
    struct timespec timeout;
    timeout.tv_sec  = timeoutMS / 1000;
    timeout.tv_nsec = (timeoutMS % 1000) * 1000000UL;

    struct kevent evts[64];
    int fds = kevent(threadKQFD(), 0, 0, evts, sizeof(evts)/sizeof(evts[0]), timeoutMS > 0 ? &timeout : 0);
    if (fds > 0) {
      for (size_t fd = 0; fd < fds; ++fd) {
        eventcbclosure* c = (eventcbclosure*)evts[fd].udata;
        (c->fn)(c->fd);
        resetMemoryPool();
      }
      return true;
    } else if (errno != EINTR) {
      return false;
    } else if (kqClosures) {
      auto f = kqClosures->find(-1);
      if (f != kqClosures->end()) {
        f->second->fn(-1);
      }
    }
  }
}

void runEventLoop() {
  while (stepEventLoop());
}

void addTimer(timerfunc f, int millisecInterval) {
  throw std::runtime_error("addTimer nyi for OSX");
}

void runEventLoop(int microsecondDuration) {
  long t  = hobbes::time();
  long dt = ((long)microsecondDuration) * 1000L;
  long tf = t + dt;

  do {
    double nsleft = tf-t;
    int nstimeout = (ceil(nsleft / 1000000.0));
    if (nstimeout < 0) nstimeout = 0;

    struct timespec timeout;
    timeout.tv_sec = 0;
    timeout.tv_nsec = nstimeout;

    struct kevent evts[64];
    int fds = kevent(threadKQFD(), 0, 0, evts, sizeof(evts)/sizeof(evts[0]), &timeout);
    if (fds > 0) {
      for (size_t fd = 0; fd < fds; ++fd) {
        eventcbclosure* c = (eventcbclosure*)evts[fd].udata;
        (c->fn)(c->fd);
        resetMemoryPool();
      }
    }
    t = hobbes::time();
  } while (t < tf);
}

#endif

}


text:
import logging

import pytest

from stp_core.common.util import adict
from plenum.server.node import Node
from plenum.test import waits
from plenum.test.helper import sdk_send_random_and_check
from plenum.test.malicious_behaviors_node import slow_primary
from plenum.test.test_node import getPrimaryReplica
from plenum.test.view_change.helper import provoke_and_wait_for_view_change
from stp_core.common.log import getlogger
from stp_core.loop.eventually import eventually

nodeCount = 7
whitelist = ["discarding message"]

"""
We start with a 7 node consensus pool
Lets call the master instance's primary replica P
make P faulty: slow to send PRE-PREPAREs
verify that throughput has dropped
verify a view change happens
"""

@pytest.fixture
def logger():
    logger = getlogger()
    old_value = logger.getEffectiveLevel()
    logger.root.setLevel(logging.DEBUG)
    yield logger
    logger.root.setLevel(old_value)

# autouse and inject before others in all tests
pytestmark = pytest.mark.usefixtures("logger")

def latestPerfChecks(nodes):
    """
    Returns spylog entry for most recent checkPerformance executions for a set
    of nodes.
    :param nodes: an iterable of Node
    :return: a dictionary of node names to the most recent checkPerformance call
    """
    return {n.name: n.spylog.getLast(Node.checkPerformance) for n in nodes}

def waitForNextPerfCheck(looper, nodes, previousPerfChecks):
    def ensureAnotherPerfCheck():
        # ensure all nodes have run another performance check
        cur = latestPerfChecks(nodes)
        for c in cur:
            if previousPerfChecks[c] is None:
                assert cur[c] is not None
            else:
                assert cur[c].endtime > previousPerfChecks[c].endtime
        return cur

    timeout = waits.expectedPoolNextPerfCheck(nodes)
    newPerfChecks = looper.run(eventually(ensureAnotherPerfCheck,
                                          retryWait=1,
                                          timeout=timeout))
    return newPerfChecks

@pytest.fixture(scope="module")
def step1(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client):
    startedNodes = txnPoolNodeSet
    """
    stand up a pool of nodes and send 5 requests to client
    """
    # the master instance has a primary replica, call it P
    P = getPrimaryReplica(startedNodes)

    sdk_send_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client, 5)
    # profile_this(sendReqsToNodesAndVerifySuffReplies, looper, client1, 5)

    return adict(P=P,
                 nodes=startedNodes,
                 requests=requests)

@pytest.fixture(scope="module")
def step2(step1, looper):
    """
    Sends requests to client and check the ratio of throughput of master
    instance and backup instance must be greater than or equal to Delta and
    verify no view change takes place.
    """
    # record when Node.checkPerformance was last run
    lastPerfChecks = latestPerfChecks(step1.nodes)

    # wait for every node to run another checkPerformance
    newPerfChecks = waitForNextPerfCheck(looper, step1.nodes, lastPerfChecks)

    # verify all nodes say that P is performing OK, and that no view changes
    # have been done
    for n in step1.nodes:
        assert n.viewNo == 0

    # verify Primary is still the same
    assert getPrimaryReplica(step1.nodes) == step1.P

    step1.perfChecks = newPerfChecks
    return step1

@pytest.fixture(scope="module")
def step3(step2):
    # make P (primary replica on master) faulty, i.e., slow to send
    # PRE-PREPAREs
    slow_primary(step2.nodes, 0, 5)
    return step2

@pytest.mark.skip(reason="SOV-1123 - fails intermittently")
def testInstChangeWithLowerRatioThanDelta(looper, step3, sdk_pool_handle, sdk_wallet_client):
    # from plenum.test.test_node import ensureElectionsDone
    # ensureElectionsDone(looper, [])

    sdk_send_random_and_check(looper, step3.nodes, sdk_pool_handle, sdk_wallet_client, 9)
    # wait for every node to run another checkPerformance
    waitForNextPerfCheck(looper, step3.nodes, step3.perfChecks)
    provoke_and_wait_for_view_change(looper, step3.nodes, 1, sdk_pool_handle, sdk_wallet_client)


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.N802.html">

Redirecting to type.N802.html...


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import "MOZUProductTypeOptionURLComponents.h"

@implementation MOZUProductTypeOptionURLComponents

//
#pragma mark -
#pragma mark Get Operations
#pragma mark -
//

+ (MOZUURLComponents *)URLComponentsForGetOptionsOperationWithProductTypeId:(NSInteger)productTypeId {
	NSString *template = @"/api/commerce/catalog/admin/attributedefinition/producttypes/{productTypeId}/Options";
	NSDictionary *params = @{
		@"productTypeId" : @(productTypeId),
	};

	return [[MOZUURLComponents alloc] initWithTemplate:template parameters:params location:MOZUTenantPod useSSL:NO];
}

+ (MOZUURLComponents *)URLComponentsForGetOptionOperationWithProductTypeId:(NSInteger)productTypeId attributeFQN:(NSString *)attributeFQN responseFields:(NSString *)responseFields {
	NSString *template = @"/api/commerce/catalog/admin/attributedefinition/producttypes/{productTypeId}/Options/{attributeFQN}?responseFields={responseFields}";
	NSDictionary *params = @{
		@"productTypeId" : @(productTypeId),
		@"attributeFQN" : attributeFQN,
		@"responseFields" : responseFields ? responseFields : @"",
	};

	return [[MOZUURLComponents alloc] initWithTemplate:template parameters:params location:MOZUTenantPod useSSL:NO];
}

//
#pragma mark -
#pragma mark Post Operations
#pragma mark -
//

+ (MOZUURLComponents *)URLComponentsForAddOptionOperationWithProductTypeId:(NSInteger)productTypeId responseFields:(NSString *)responseFields {
	NSString *template = @"/api/commerce/catalog/admin/attributedefinition/producttypes/{productTypeId}/Options?responseFields={responseFields}";
	NSDictionary *params = @{
		@"productTypeId" : @(productTypeId),
		@"responseFields" : responseFields ? responseFields : @"",
	};

	return [[MOZUURLComponents alloc] initWithTemplate:template parameters:params location:MOZUTenantPod useSSL:NO];
}

//
#pragma mark -
#pragma mark Put Operations
#pragma mark -
//

+ (MOZUURLComponents *)URLComponentsForUpdateOptionOperationWithProductTypeId:(NSInteger)productTypeId attributeFQN:(NSString *)attributeFQN responseFields:(NSString *)responseFields {
	NSString *template = @"/api/commerce/catalog/admin/attributedefinition/producttypes/{productTypeId}/Options/{attributeFQN}?responseFields={responseFields}";
	NSDictionary *params = @{
		@"productTypeId" : @(productTypeId),
		@"attributeFQN" : attributeFQN,
		@"responseFields" : responseFields ? responseFields : @"",
	};

	return [[MOZUURLComponents alloc] initWithTemplate:template parameters:params location:MOZUTenantPod useSSL:NO];
}

//
#pragma mark -
#pragma mark Delete Operations
#pragma mark -
//

+ (MOZUURLComponents *)URLComponentsForDeleteOptionOperationWithProductTypeId:(NSInteger)productTypeId attributeFQN:(NSString *)attributeFQN {
	NSString *template = @"/api/commerce/catalog/admin/attributedefinition/producttypes/{productTypeId}/Options/{attributeFQN}";
	NSDictionary *params = @{
		@"productTypeId" : @(productTypeId),
		@"attributeFQN" : attributeFQN,
	};

	return [[MOZUURLComponents alloc] initWithTemplate:template parameters:params location:MOZUTenantPod useSSL:NO];
}

@end