text:
'use strict';

angular.module('xos.dashboardManager', [
  'ngResource',
  'ngCookies',
  'ui.router',
  'xos.helpers',
  'dndLists'
])
.config(($stateProvider) => {
  $stateProvider
  .state('manage-user-dashboards', {
    url: '/',
    template: '<user-dashboards></user-dashboards>'
  })
  .state('add-dashboards', {
    url: '/add',
    template: '<dashboard-form></dashboard-form>'
  })
  .state('edit-dashboards', {
    url: '/dashboards/:id',
    template: '<dashboard-form></dashboard-form>'
  });
})
.config(function($httpProvider){
  $httpProvider.interceptors.push('NoHyperlinks');
})
.service('UserDashboards', function($http, $q){
  this.query = () => {
    const d = $q.defer();

    $http.get('/api/utility/dashboards')
    .then(res => {
      d.resolve(res.data);
    })
    .catch(err => {
      d.reject(err);
    });

    return {$promise: d.promise};
  }

  this.update = (dashboard) => {
    const d = $q.defer();
    $http.post('/api/utility/dashboards/', dashboard)
    .then(res => {
      d.resolve(res.data);
    })
    .catch(err => {
      d.reject(err);
    });

    return {$promise: d.promise};
  }
});


text:
title: Average Block Size
chart: true
charts:
  - averageBlockSize
---

{{ page.title }}

<canvas id="average-block-size-chart" class="chart" height="150" style="width:100%;"></canvas>

Back to charts

redpajama_set_name: RedPajamaGithub


text:
package org.jasig.cas.support.spnego.web.flow.client;

import javax.validation.constraints.NotNull;
import java.util.regex.Pattern;

/**
 * A simple implementation of {@link BaseSpnegoKnownClientSystemsFilterAction} to allow / skip SPNEGO / KRB /
 * NTLM authentication based on a regex match against a reverse DNS lookup of the requesting
 * system.
 *
 * @author Sean Baker
 * @author Misagh Moayyed
 * @since 4.1
 */
public class HostNameSpnegoKnownClientSystemsFilterAction extends BaseSpnegoKnownClientSystemsFilterAction {
    private final Pattern hostNamePatternString;

    /**
     * Instantiates a new hostname spnego known client systems filter action.
     *
     * @param hostNamePatternString the host name pattern string.
     *                              The pattern to match the retrieved hostname against.
     */
    public HostNameSpnegoKnownClientSystemsFilterAction(@NotNull final String hostNamePatternString) {
        super();
        this.hostNamePatternString = Pattern.compile(hostNamePatternString);
    }

    /**
     * {@inheritDoc}.
     * <p>
     * Checks whether the IP should even be paid attention to,
     * then does a reverse DNS lookup, and if it matches the supplied pattern, performs SPNEGO
     * else skips the process.
     *
     * @param remoteIp The remote ip address to validate
     */
    @Override
    protected boolean shouldDoSpnego(final String remoteIp) {
        final boolean ipCheck = ipPatternCanBeChecked(remoteIp);
        if(ipCheck && !ipPatternMatches(remoteIp)) {
            return false;
        }
        final String hostName = getRemoteHostName(remoteIp);
        logger.debug("Retrieved host name for the remote ip is {}", hostName);
        return this.hostNamePatternString.matcher(hostName).find();
    }
}


text:
<config>
		<funcs>

			<item nodeType="category" name="" text="字符串函数" asPath="false">
				<item nodeType="function" name="justep.String.trim()" text="justep.String.trim(str)--清除前后两端的空白字符" />
				<item nodeType="function" name="justep.String.splitAndTrim()" text="justep.String.splitAndTrim(str, spliter)--用指定的元素分隔成字符串数组, 并对每个元素执行trim" />
				<item nodeType="function" name="justep.String.format()" text="justep.String.format(str, ...)--字符串格式化" />
				<item nodeType="function" name="justep.String.toInt()" text="justep.String.toInt(str, default)--转换成整数" />
				<item nodeType="function" name="justep.String.toFloat()" text="justep.String.toFloat(str, default)--转换成浮点数" />
				<item nodeType="function" name="justep.String.HTMLEncode()" text="justep.String.HTMLEncode(str)--HTML编码" />
				<item nodeType="function" name="justep.String.HTMLDecode()" text="justep.String.HTMLDecode(str)--HTML解码" />
				<item nodeType="function" name="justep.String.zeros()" text="justep.String.zeros(str, len, right)--补零" />
				<item nodeType="function" name="justep.String.Encrypt()" text="justep.String.Encrypt(str, pwd)--字符串加密" />
				<item nodeType="function" name="justep.String.Decrypt()" text="justep.String.Decrypt(str, pwd)--字符串解密" />
				<item nodeType="function" name="justep.String.camelize()" text="justep.String.camelize(str)--首字母转大写" />
			</item>

			<item nodeType="category" name="" text="日期函数" asPath="false">
				<item nodeType="function" name="justep.Date.isLeapYear()" text="justep.Date.isLeapYear(date)--判断是否是闰年" />
				<item nodeType="function" name="justep.Date.fromString()" text="justep.Date.fromString(str, format)--按照给定的日期格式,把字符串转换成日期对象" />
				<item nodeType="property" name="justep.Date.STANDART_FORMAT" text="justep.Date.STANDART_FORMAT--时间格式yyyy-MM-ddThh:mm:ss.fffZ" />
				<item nodeType="property" name="justep.Date.STANDART_FORMAT_SHOT" text="justep.Date.STANDART_FORMAT--时间格式yyyy-MM-dd" />
				<item nodeType="property" name="justep.Date.DEFAULT_FORMAT" text="justep.Date.DEFAULT_FORMAT--时间格式yyyy/MM/dd hh:mm:ss" />
				<item nodeType="property" name="justep.Date.DEFAULT_FORMAT_SHOT" text="justep.Date.DEFAULT_FORMAT_SHOT--时间格式yyyy/MM/dd" />
				<item nodeType="function" name="justep.Date.toString()" text="justep.Date.toString(dateTime, formatStr)--按照给定的日期格式,把日期对象转换成字符串" />
				<item nodeType="function" name="justep.Date.increase" text="justep.Date.increase(dateTime, num, interval)--根据日期的规则,为给定的日期添加指定的时间量。interval表示时间单位,'s'代表秒,'n'代表分钟,'h'代表小时 ,'d'代表天, 'w'代表 周 ,'m'代表月,'q'代表季度,'y'代表年" />
				<item nodeType="function" name="justep.Date.decrease" text="justep.Date.decrease(dateTime, num, interval)--根据日期的规则,为给定的日期减去指定的时间量。interval表示时间单位,'s'代表秒,'n'代表分钟,'h'代表小时 ,'d'代表天, 'w'代表 周 ,'m'代表月,'q'代表季度,'y'代表年" />
				<item nodeType="function" name="justep.Date.diff" text="justep.Date.diff(start, end, interval)--计算两个日期的差。interval表示时间单位,默认是以天为单位,'s'代表秒,'n'代表分钟,'h'代表小时 ,'d'代表天, 'w'代表 周 ,'m'代表月,'q'代表季度,'y'代表年" />
				<item nodeType="function" name="justep.Date.between" text="justep.Date.between(start, end)--计算两个日期相差几天,和diff很相似,返回永远是正整数" />
			</item>

			<item nodeType="category" name="" text="数组函数" asPath="false">
				<item nodeType="function" name="justep.Array.indexOf()" text="justep.Array.indexOf(array, item)--获取元素的序号" />
				<item nodeType="function" name="justep.Array.first()" text="justep.Array.first(array, predicate, predicateOwner)--获取满足条件的第一个元素" />
				<item nodeType="function" name="justep.Array.filter()" text="justep.Array.filter(array, filter)--获取数组中满足指定条件的元素列表" />
			</item>

			<item nodeType="category" name="" text="Base64" asPath="false">
				<item nodeType="function" name="justep.Base64.encode()" text="justep.Base64.encode(input)--Base64编码" />
				<item nodeType="function" name="justep.Base64.decode()" text="justep.Base64.decode(input)--Base64解码" />
			</item>

			<item nodeType="category" name="" text="其他函数" asPath="false">
				<item nodeType="function" name="justep.UUID.createUUID()" text="justep.UUID.createUUID()--返回UUID字符串" />
				<item nodeType="function" name="eval()" text="eval(string)--执行script脚本" />
				<item nodeType="function" name="justep.Browser.isPC()" text="justep.Browser.isPC()--判断是否是PC" />
				<item nodeType="function" name="justep.Browser.isPhone()" text="justep.Browser.isPhone()--判断是否是手机" />
				<item nodeType="function" name="justep.Browser.isPad()" text="justep.Browser.isPad()--判断是否是平板" />
				<item nodeType="function" name="justep.URL.getBSessionID()" text="justep.URL.getBSessionID()--获取bsessionid" />
				<item nodeType="function" name="justep.URL.getSkin()" text="justep.URL.getSkin()--获取皮肤" />
				<item nodeType="function" name="justep.URL.getLanguage()" text="justep.URL.getLanguage()--获取语言" />
				<item nodeType="function" name="justep.Util.isBoolean()" text="justep.Util.isBoolean(value)--判断值的类型是否是Boolean类型" />
				<item nodeType="function" name="justep.Util.isString()" text="justep.Util.isString(value)--判断值的类型是否是String类型" />
				<item nodeType="function" name="justep.Util.isFunction()" text="justep.Util.isFunction(value)--判断是否是函数" />
				<item nodeType="function" name="justep.Util.isArray()" text="justep.Util.isArray(value)--判断是否是数组" />
				<item nodeType="function" name="justep.Util.isObject()" text="justep.Util.isObject(value)--判断值的类型是否是Object" />
				<item nodeType="function" name="justep.Util.toArray()" text="justep.Util.toArray(iterable, start, end)--转换成数组" />
				<item nodeType="function" name="justep.Util.clone()" text="justep.Util.close(value)--对象克隆" />
				<item nodeType="function" name="justep.Util.getCookie()" text="justep.Util.getCookie(name)--获取cookie值" />

			</item>
		</funcs>
	</config>


text:
title: "Secure Hardware Design Guidelines"
---

## Overview

Silicon designs for security devices require special guidelines to protect the
designs against myriad attacks. For OpenTitan, the universe of potential attacks
is described in our threat model. In order to have the most robust defensive
posture, a general approach to secure hardware design should rely on the
concepts of (1) defense in depth, (2) consideration of recovery methods
post-breach, and (3) thinking with an attacker mindset.

In all cases, as designers, we need to think of equalizing the difficulty of any
particular attack for the adversary. If a design has a distribution of attack
vectors (sometimes called the "attack surface" or "attack surface area"), it is
not the strength of the strongest defenses that is particularly of interest but
rather the weakest, since these will be the most likely to be exploited by the
adversary. For example, it's unlikely that an attacker will try to brute-force a
system based on AES-128 encryption, as the difficulty level of such an attack is
high, and our confidence in the estimate of the difficulty is also high. But, if
the security of the AES-128 depends on a global secret, more mundane attacks
like theft or bribery become more likely avenues for the adversary to exploit.

Defense in depth means having multiple layers of defenses/controls acting
independently. Classically in information security, these are grouped into three
main categories: physical, technical and administrative[^1]. We map these into
slightly different elements when considering secure hardware design:

*   Physical security typically maps to sensors and shields, but also separation
    of critical information into different locations on the die.
*   Technical security includes techniques like encrypting data-at-rest,
    scrambling buses for data-in-motion, and integrity checking for all kinds of
    data.
*   Administrative security encompasses architectural elements like permissions,
    lifecycle states, and key splits (potentially also linked to physical
    security).

Consideration of recovery methods means assuming that some or all of the
defenses will fail, with an eye to limiting the extent of the resulting system
failure/compromise. If an adversary gains control over a sub-block, but cannot
use this to escalate to full-chip control, we have succeeded. If control over a
sub-block is detected, but an alert is generated that ultimately causes a device
reset or other de-escalation sequence, we have created a recovery strategy. If
the software is compromised but access to keys/secrets is prevented by hardware
controls, we have succeeded. If compromise of secrets from a single device
cannot be leveraged into attacks on other (or all) devices, again we have
succeeded. If compromised devices can be identified and quarantined when
enrolled into a larger system, then we have a successful recovery strategy.

Thinking with an attacker mindset means "breaking the rules" or violating
assumptions: what if two linked state machines no longer are "in sync" - how
will they operate, and how can they recover? What happens if the adversary
manipulates an internal value (fault injection)? What happens if the adversary
can learn some or all of a secret value (side channel leakage)? This document
will primarily try to give generic guidance for defense against the latter two
attacks (fault injection, and side channel information leakage). It also
discusses ways to either prevent attacks, mitigate them, or alert of their
existence. Other attack vectors (especially software compromises or operational
security failures) are not in the scope of this document, or will be addressed
at a later stage.

In general, when thinking of protecting against fault injection attacks, the
designer should consider the consequences of any particular net/node being
inverted or forced by an adversary. State of the art fault attacks can stimulate
two nodes in close succession; robustness to this type of attack depends on the
declared threat model. Designers need to be well aware of the power of an attack
like SIFA [[15](#ref-15)], which can bypass "conventional" fault countermeasures (e.g.
redundancy/detectors) and requires only modest numbers of traces.

For increased resistance against side channel leakage (typically: power,
electromagnetic radiation, or timing), designs in general should ensure that the
creation or transmission of *secret material* is handled in such a way as to not
work with "small" subsets of bits of sensitive information. Attacks like DPA are
very powerful because they are able to "divide and conquer" an AES operation
(regardless of key size) into its 8-bit S-Boxes and enumerate all 256 possible
values to evaluate hypotheses. Evaluating/processing information in 32-bit
quanta (or larger) will make these kinds of enumerations much more difficult;
operating on a single bit at a time makes them almost trivial.

Below we will go deeper into these recommendations for general design practices.
Individual module guidance for particular IP (processor, AES, SHA, etc) will be
handled in addenda to this document.

## General Module Level Design Guidance

These guidelines are for sub-block / module level design. System architecture,
identity management, and protocol design are outside the scope of this document,
but may create some dependencies here. For general reading, the slides of [[10](#ref-10)]
are considered a useful companion to these guidelines.

### **Recommendation 1**: Identify sensitive/privileged operations

Identify any sensitive/privileged operations performed by the module
(non-exhaustive list of examples: working with secret keys, writing to OTP,
potentially writing to flash, enabling debug functionality, lifting/releasing
access restrictions, changing lifecycle state)

1.  Having these operations documented helps to analyze the potential issues of
    any attack discussed below.
2.  Subsequent design/verification reviews can use these sensitive operations as
    focus areas or even coverage points.

### **Recommendation 2**: Side-channel leakage considerations

Consider side-channel leakage of any secret information (side channels include
timing, power, EM radiation, caches, and micro-architectural state, among
others)

1.  Process secret information in at least a 32-bit wide datapath
2.  Use fixed/constant time operations when handling secrets (see [[6](#ref-6)] and [[11](#ref-11)])
3.  Don't branch/perform conditional operations based on secret values
4.  Incorporate temporal randomness (example: add delay cycles based on LFSR
    around critical operations, see [[9](#ref-9)])
5.  Cryptographic operations should incorporate entropy (via masking/blinding,
    see [[9](#ref-9)]), especially if the key is long-lived, or a global/class-wide value.
    Short-lived keys may not require this, but careful study of the information
    leakage rate is necessary
6.  Noise generation - run other "chaff" switching actions in parallel with
    sensitive calculations, if power budget permits (see [[9](#ref-9)])
7.  Secrets should not be stored in a processor cache (see [[3](#ref-3)])
8.  Speculative execution in a processor can lead to leakage of secrets via
    micro-architectural state (see [[4](#ref-4)]/[[5](#ref-5)])
9.  When clearing secrets, use an LFSR to wipe values to prevent a Hamming
    weight leakage that would occur if clearing to zero. For secrets stored in
    multiple shares, use different permutations (or separate LFSRs) to perform
    the clearing of the shares.

### **Recommendation 3**: Fault injection countermeasures

Consider defenses to fault injection / glitching attacks (survey and overview of
attacks, see [[12](#ref-12)] and [[13](#ref-13)])

1.  Initially assume that the adversary can glitch any node arbitrarily, and
    determine the resulting worst-case scenario. This is a very conservative
    approach and might lead to over-pessimism, but serves to highlight potential
    issues. Then, to ease implementation burden, assume the adversary can glitch
    to all-1's or all-0's (since these are considered "easier" to reach), and
    that reset can be asserted semi-arbitrarily.
2.  Use parity/ECC on memories and data paths (note here that ECC is not true
    integrity, have to use hash to prevent forgery, see [[1](#ref-1)]). For memories, ECC
    is helpful to protect instruction streams or values that can cause
    "branching control flows" that redirect execution flow. Parity is
    potentially helpful if detection of corruption is adequate (though
    double-glitch fault injection can fool parity, so Hsiao or other
    detect-2-error codes can be used, even without correction circuitry
    implemented). When committing to an irrevocable action (e.g. burning into
    OTP, unlocking part of the device/increasing permissions), ECC is probably
    more appropriate.
    1.  When selecting a specific ECC implementation, the error detection
        properties are likely more important than error correction (assuming
        memory lifetime retention/wear are not considered). For a good example
        of how to consider the effectiveness of error correction, see
        [this PR comment](https://github.com/lowRISC/opentitan/pull/3899#issuecomment-716799810).
3.  State machines:
    1.  Have a minimum Hamming distance for state machine transitions, to make
        single bit faults non-effective
    2.  Use a
        [sparsely populated state encoding](https://github.com/lowRISC/opentitan/blob/master/util/design/sparse-fsm-encode.py),
        with all others marked invalid - see 11.1 about optimization concerns
        when doing this though
    3.  All states could have the same Hamming weight, then can constantly check
        for this property (or use ECC-type coding on state variable and check
        this)
    4.  If waiting for a counter to expire to transition to the next state,
        better if the terminal count that causes the transition is not
        all-0/all-1. One could use an LFSR instead of a binary counter, but
        debugging this can be a bit painful then
4.  Maintain value-and-its-complement throughout datapath (sometimes called
    "dual rail" logic), especially if unlocking/enabling something sensitive,
    and continually check for validity/consistency of representation
5.  Incorporate temporal randomness where possible (example: add delay cycles
    based on LFSR around sensitive operations)
6.  Run-it-twice and compare results for sensitive calculations
7.  Redundancy - keep/store multiple copies of sensitive checks/data
8.  For maximum sensitivity, compare combinational and sequential paths with
    hair-trigger/one-shot latch of miscompare
9.  Empty detection for OTP/flash (if needed, but especially for lifecycle
    determination)
10. Avoid local resets / prefer larger reset domains, since a glitch on this
    larger reset keeps more of the design "in sync." But, consider the
    implications of any block with more than one reset domain (see also 9.1).
11. Similar to the "mix in" idea of 4.4, in any case where multiple contributing
    "votes" are going to an enable/unlock decision, consider mixing them into
    some cryptographic structure over time that will be diverted from its path
    by attempts to glitch each vote. (Note: if the final outcome of this is
    simply a wide-compare that produces a single-bit final unlock/enable vote
    then this is only marginally helpful - since that vote is now the glitch
    target. Finding a way to bind the final cryptographic result to the vote is
    preferred, but potentially very difficult / impossible, depending on the
    situation.)
12. When checking/creating a signal to
    permit some sensitive
    operation, prefer that the checking logic is maximally volatile (e.g.
    performs a lot of the calculation in a single cycle after a register), such
    that a glitch prevents the operation. Whereas, when checking to
    deny a sensitive operation,
    prefer that the checking logic is minimally volatile (is directly following
    a register with minimal combinational logic), such that a glitch will be
    recovered on the next clock and the denial will be continued/preserved.
13. CFI (control flow integrity) hardware can help protect a processor /
    programmable peripheral from some types of glitch attacks. This topic is
    very involved and beyond the scope of these guidelines, consult [[2](#ref-2)]
    for an introduction to previous techniques.
14. Analog sensors (under/over-voltage, laser light, mesh breach, among others)
    can be used to generate SoC-level alerts and/or inhibit sensitive
    operations. Many of these sensors require calibration/trimming, or require
    hysteresis circuits to prevent false-positives, so they may not be usable in
    fast-reacting situations.
15. Running an operation (e.g. AES or KMAC) to completion, even with a detected
    fault, is sometimes useful since it suppresses information for the adversary
    about the success/failure of the attempted fault, and minimizes any timing
    side channel. However, for some operations (e.g. ECDSA sign), operations on
    faulty inputs can have catastrophic consequences. These guidelines cannot
    recommend a default-safe posture, but each decision about handling detected
    faults should be carefully considered.
16. For request-acknowledge interfaces, monitor the acknowledge line for
    spurious pulses at all times (not only when pending request) and use this
    as a glitch/fault detector to escalate locally and/or generate alerts.
17. When arbitrating between two or more transaction sources with different
    privilege/access levels, consider how to protect a request from one source
    being glitched/forged to masquerade as being sourced from another
    higher-privilege source (for example, to return side-loaded
    hardware-visible-only data via a software read path). At a minimum,
    redundant arbitration and multiple-bit encoding of the arbitration "winner"
    can help to mitigate this type of attack.

### **Recommendation 4**: Handling of secrets

1.  Diversify types/sources of secrets (e.g. use combination of RTL constants +
    OTP + flash) to prevent a single compromise from being effective
2.  Rather than "check an unlock value directly" - use a hash function with a
    user-supplied input, and check the output of the hash matches. This way the
    unlock value is not contained in the netlist.
3.  Qualify operations with allowed lifecycle state (even if redundant with
    other checks)
4.  Where possible, mix in operating modes to calculation of derived secrets to
    create parallel/non-substitutable operating/keying domains. (i.e. mixing in
    devmode, lifecycle state)
    1.  If defenses can be bypassed for debugging/recovery, considering mixing
        in activation vector/bypass bits of defenses as well, consider this like
        small-scale attestation of device state
5.  Encrypt (or at least scramble) any secrets stored at-rest in flash/OTP, to
    reduce risks of static/offline inspection.

### **Recommendation 5**: Alerts

1.  Generate alerts on any detected anomaly (need to define what
    priority/severity should be assigned)
2.  Where possible, prefer to take a local action (clearing/randomizing state,
    cease processing) in addition to generating the alert

### **Recommendation 6**: Safe default values

1.  All case statements, if statements, and ternaries should consider what the
    safest default value is. Having an "invalid" state/value is nice to have for
    this purpose, but isn't always possible.
2.  Operate in a general policy/philosophy of starting with lowest allowed
    privilege and augmenting by approvals/unlocks.
3.  Implement enforcement of inputs on CSRs - qualify/force data attempted to be
    written based on lifecycle state, peripheral state, or other values. The
    designer must determine the safest remapping, e.g. write --> read, read -->
    nop, write --> nop and so forth. Blanket implementation of input enforcement
    complicates verification, so this style of design should be chosen only
    where the inputs are particularly sensitive (requests to unlock, privilege
    increase requests, debug mode enables, etc).

### **Recommendation 7**: DFT issues

1.  Entry and exit from scan mode should cause a reset to prevent insertion or
    exfiltration of sensitive values
2.  Ensure that when in production (e.g. not in lab debug) environments, scan
    chains are disabled
3.  Processor debug paths (via JTAG) may need to be disabled in production modes
4.  Beware of self-repair or redundant-row/columns schemes for memories (SRAM
    and OTP), as they can be exploited to misdirect reads to
    adversary-controlled locations

### **Recommendation 8**: Power management issues

1.  If module is not in an always-on power domain, consider that a sleep/wake
    sequence can be used to force a re-derivation of secrets needed in the
    module, as many times as desired by the adversary
2.  Fine-grained clock gating should never be used for any module that processes
    secret data, only coarse-grained (module-level) gating is acceptable. (Fine
    grained gates essentially compute `clock_gate = D ^ Q` which often acts as
    an SCA "amplifier").

### **Recommendation 9**: "Synchronization" (consistency) issues

1.  If a module interacts with other modules in a stateful way (think of two
    data-transfer counters moving in ~lockstep, but the counts are not sent back
    and forth for performance optimization), what happens if:
    1.  One side is reset and the other is not
    2.  One side is clock-gated and the other is not
    3.  One side is power-gated and the other is not
    4.  The counter on one side is glitched
2.  Generally these kind of blind lockstep situations should be avoided where
    possible, and current module/interface status should exchanged in both
    directions and constantly checked for validity/consistency

### **Recommendation 10**: Recovery mechanism considerations

1.  What happens if a security mechanism fails? (Classic problem of this variety
    is on-die sensors being too sensitive and resetting the chip) Traditionally,
    fuses can disable some mechanisms if they are faulty.
2.  Could an adversary exploit a recovery mechanism? (If a sensor can be
    fuse-disabled, wouldn't the adversary just do that? See 4.4 above.)

### **Recommendation 11**: Optimization concerns

1.  Sometimes synthesis will optimize away redundant (but necessary for
    security) logic - `dont_touch` or `size_only` attributes may sometimes be
    needed, or even more aggressive preservation strategies. Example: when using
    the sparse FSM encoding, use the `prim_flop` component for the state vector
    register.
2.  Value-and-complement strategies can also be optimized away, or partially
    disconnected such that only half of the datapath is contributing to the
    logic, or a single register with both Q & Qbar outputs becomes the source of
    both values to save area.
3.  Retiming around pipeline registers can create DPA issues, due to inadvertent
    combination of shares, or intra-cycle glitchy evaluation. For DPA-resistant
    logic, explicitly declare functions and registers using `prim_*` components,
    and make sure that pipeline retiming is not enabled in synthesis.

### **Recommendation 12**: Entropy concerns

1.  Verify that all nonces are truly only used once
2.  If entropy is broadcast, verify list of consumers and arbitration scheme to
    prevent reuse / duplicate use of entropy in sensitive calculations
3.  Seeds for local LFSRs need to be unique/diversified

### **Recommendation 13**: Global secrets

1.  Avoid if at all possible
2.  If not possible, have a process to generate/re-generate them; make sure this
    process is used/tested many times before final netlist; process must be
    repeatable/deterministic given some set of inputs
3.  If architecturally feasible, install a device-specific secret to override
    the global secret once boot-strapped (and disable the global secret)

### **Recommendation 14**: Sensors

1.  Sensors need to be adjusted/tweaked so that they actually fire. It is
    challenging to set the sensors at levels that detect "interesting"
    glitches/environmental effects, but don't fire constantly or cause yield
    issues. Security team should work with the silicon supplier to determine the
    best course of action here.
2.  Sensor configuration / calibration data should be integrity-protected.

## References and further reading

[1]: Overview of checksums and hashes -
https://cybergibbons.com/reverse-engineering-2/checksums-hashes-and-security/

[2]: A Survey of hardware-based Control Flow Integrity -
https://arxiv.org/pdf/1706.07257.pdf

[3]: Cache-timing attacks on AES -
https://cr.yp.to/antiforgery/cachetiming-20050414.pdf

[4]: Meltdown: Reading Kernel Memory from User Space -
https://meltdownattack.com/meltdown.pdf

[5]: Spectre Attacks: Exploiting Speculative Execution -
https://spectreattack.com/spectre.pdf

[6]: Timing Attacks on Implementations of Diffie-Hellman, RSA, DSS, and Other
Systems - https://www.rambus.com/wp-content/uploads/2015/08/TimingAttacks.pdf

[7]: Differential Power Analysis -
https://paulkocher.com/doc/DifferentialPowerAnalysis.pdf

[8]: SoC it to EM: electromagnetic side-channel attacks on a complex
system-on-chip - https://www.iacr.org/archive/ches2015/92930599/92930599.pdf

[9]: Introduction To differential power analysis -
https://link.springer.com/content/pdf/10.1007/s13389-011-0006-y.pdf

[10]: Principles of Secure Processor Architecture Design -
https://caslab.csl.yale.edu/tutorials/hpca2019/ and
https://caslab.csl.yale.edu/tutorials/hpca2019/tutorial_principles_sec_arch_20190217.pdf

[11]: Time Protection - https://ts.data61.csiro.au/projects/TS/timeprotection/

[12]: Fault Attacks on Secure Embedded Software: Threats, Design and Evaluation -
https://arxiv.org/pdf/2003.10513.pdf

[13]: The Sorcerer's Apprentice Guide to Fault Attacks -
https://eprint.iacr.org/2004/100.pdf

[14]: Fault Mitigation Patterns -
https://www.riscure.com/uploads/2020/05/Riscure_Whitepaper_Fault_Mitigation_Patterns_final.pdf

[15]: SIFA: Exploiting Ineffective Fault Inductions on Symmetric Cryptography -
https://eprint.iacr.org/2018/071.pdf

## Notes

[^1]: In other OpenTitan documents, the combination of technical and
    administrative defense are often referred to as "logical security"


text:
package com.thaiopensource.validate.rng;

import org.xml.sax.ErrorHandler;

import com.thaiopensource.relaxng.parse.sax.SAXParseReceiver;
import com.thaiopensource.resolver.xml.sax.SAXResolver;
import com.thaiopensource.util.PropertyMap;
import com.thaiopensource.validate.Option;
import com.thaiopensource.validate.ResolverFactory;
import com.thaiopensource.validate.ValidateProperty;
import com.thaiopensource.validate.auto.SchemaReceiver;
import com.thaiopensource.validate.auto.SchemaReceiverFactory;
import com.thaiopensource.validate.prop.rng.RngProperty;
import com.thaiopensource.validate.rng.impl.SchemaReceiverImpl;
import com.thaiopensource.xml.util.WellKnownNamespaces;

public class SAXSchemaReceiverFactory implements SchemaReceiverFactory
{
  public SchemaReceiver createSchemaReceiver (final String namespaceUri, final PropertyMap properties)
  {
    // XXX allow namespaces with incorrect version
    if (!WellKnownNamespaces.RELAX_NG.equals (namespaceUri))
      return null;
    final SAXResolver resolver = ResolverFactory.createResolver (properties);
    final ErrorHandler eh = properties.get (ValidateProperty.ERROR_HANDLER);
    return new SchemaReceiverImpl (new SAXParseReceiver (resolver, eh), properties);
  }

  public Option getOption (final String uri)
  {
    return RngProperty.getOption (uri);
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>pymatgen.io.cube module — pymatgen 2022.3.24 documentation</title>
      <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
      <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
      <link rel="stylesheet" href="_static/css/custom.css" type="text/css" />
    <link rel="canonical" href="https://pymatgen.orgpymatgen.io.cube.html"/>

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="pymatgen.io.fiesta module" href="pymatgen.io.fiesta.html" />
    <link rel="prev" title="pymatgen.io.cssr module" href="pymatgen.io.cssr.html" />

             pymatgen

                2022.3.24

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Introduction

Installation

Change log

Compatibility

Contributing

Usage

Development Team

References

API Docs

pymatgen namespace

Subpackages

pymatgen.alchemy package

pymatgen.analysis namespace

pymatgen.apps package

pymatgen.cli package

pymatgen.command_line package

pymatgen.core package

pymatgen.electronic_structure package

pymatgen.entries package

pymatgen.ext namespace

pymatgen.io namespace

pymatgen.optimization package

pymatgen.phonon package

pymatgen.symmetry package

pymatgen.transformations package

pymatgen.util package

pymatgen.vis package

Submodules

          pymatgen

 »

pymatgen »

pymatgen namespace »

pymatgen.io namespace »

pymatgen.io.cube module

               Edit on GitHub

pymatgen.io.cube module

Module for reading Gaussian cube files, which have become one of the standard file formats
for volumetric data in quantum chemistry and solid state physics software packages
(VASP being an exception).

Some basic info about cube files
(abridged info from http://paulbourke.net/dataformats/cube/ by Paul Bourke)

The file consists of a header which includes the atom information and the size as well
as orientation of the volumetric data. The first two lines of the header are comments. The
third line has the number of atoms included in the file followed by the position of the
origin of the volumetric data. The next three lines give the number of voxels along each axis
(x, y, z) followed by the axis vector. The last section in the header is one line for each
atom consisting of 5 numbers, the first is the atom number, the second is the charge, and
the last three are the x,y,z coordinates of the atom center. The volumetric data is straightforward,
one floating point number for each volumetric element.

Example
In the following example the volumetric data is a 40 by 40 by 40 grid, each voxel is 0.283459 units
wide and the volume is aligned with the coordinate axis. There are three atoms.

CPMD CUBE FILE.
OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z

3    0.000000    0.000000    0.000000

40    0.283459    0.000000    0.000000
40    0.000000    0.283459    0.000000
40    0.000000    0.000000    0.283459

8    0.000000    5.570575    5.669178    5.593517
1    0.000000    5.562867    5.669178    7.428055
1    0.000000    7.340606    5.669178    5.111259

-0.25568E-04  0.59213E-05  0.81068E-05  0.10868E-04  0.11313E-04  0.35999E-05

:             :             :           :            :            :
:             :             :           :            :            :
:             :             :           :            :            :

In this case there will be 40 x 40 x 40 floating point values

:             :             :           :            :            :
:             :             :           :            :            :
:             :             :           :            :            :

class Cube(fname)[source]

Bases: object

Class to read Gaussian cube file formats for volumetric data.

Cube files are, by default, written in atomic units, and this
class assumes that convention.

Initialize the cube object and store the data as self.data

Parameters

fname (str) – filename of the cube to read

get_atomic_site_averages(atomic_site_radii)[source]

Get the average value around each atomic site.

Parameters

atomic_site_radii (dict) – dictionary determining the cutoff radius (in Angstroms)
for averaging around atomic sites (e.g. {'Li': 0.97, 'B': 0.77, …}. If
not provided, then the

Returns

Array of site averages, [Average around site 1, Average around site 2, …]

get_atomic_site_totals(atomic_site_radii)[source]

Get the integrated total in a sphere around each atomic site.

Parameters

atomic_site_radii (dict) – dictionary determining the cutoff radius (in Angstroms)
for averaging around atomic sites (e.g. {'Li': 0.97, 'B': 0.77, …}. If
not provided, then the

Returns

Array of site averages, [Average around site 1, Average around site 2, …]

get_average_along_axis(ind)[source]

Modified from pymatgen.io.vasp.outputs

Get the averaged total of the volumetric data a certain axis direction.
For example, useful for visualizing Hartree Potentials.

Parameters

ind (int) – Index of axis.

Returns

Average total along axis

get_axis_grid(ind)[source]

Modified from pymatgen.io.vasp.outputs

Returns the grid for a particular axis.

Parameters

ind (int) – Axis index.

mask_sphere(radius, cx, cy, cz)[source]

Create a mask for a sphere with radius=radius, centered at cx, cy, cz.

Parameters

radius – (float) of the mask (in Angstroms)

cx – (float) the fractional coordinates of the center of the sphere

cy – (float) the fractional coordinates of the center of the sphere

cz – (float) the fractional coordinates of the center of the sphere

© Copyright 2011, Pymatgen Development Team.

  Built with Sphinx using a
    theme
    provided by Read the Docs.

This page uses
Google Analytics to collect statistics. You can disable it by blocking
the JavaScript coming from www.google-analytics.com.


text:
/*
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 */

#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>

#include "hid-ids.h"

static const struct hid_device_id speedlink_devices[] = {
	{ HID_USB_DEVICE(USB_VENDOR_ID_X_TENSIONS, USB_DEVICE_ID_SPEEDLINK_VAD_CEZANNE)},
	{ }
};

static int speedlink_input_mapping(struct hid_device *hdev,
		struct hid_input *hi,
		struct hid_field *field, struct hid_usage *usage,
		unsigned long **bit, int *max)
{
	/*
	 * The Cezanne mouse has a second "keyboard" USB endpoint for it is
	 * able to map keyboard events to the button presses.
	 * It sends a standard keyboard report descriptor, though, whose
	 * LEDs we ignore.
	 */
	switch (usage->hid & HID_USAGE_PAGE) {
	case HID_UP_LED:
		return -1;
	}
	return 0;
}

static int speedlink_event(struct hid_device *hdev, struct hid_field *field,
		struct hid_usage *usage, __s32 value)
{
	/* No other conditions due to usage_table. */

	/* This fixes the "jumpy" cursor occuring due to invalid events sent
	 * by the device. Some devices only send them with value==+256, others
	 * don't. However, catching abs(value)>=256 is restrictive enough not
	 * to interfere with devices that were bug-free (has been tested).
	 */
	if (abs(value) >= 256)
		return 1;
	/* Drop useless distance 0 events (on button clicks etc.) as well */
	if (value == 0)
		return 1;

	return 0;
}

MODULE_DEVICE_TABLE(hid, speedlink_devices);

static const struct hid_usage_id speedlink_grabbed_usages[] = {
	{ HID_GD_X, EV_REL, 0 },
	{ HID_GD_Y, EV_REL, 1 },
	{ HID_ANY_ID - 1, HID_ANY_ID - 1, HID_ANY_ID - 1}
};

static struct hid_driver speedlink_driver = {
	.name = "speedlink",
	.id_table = speedlink_devices,
	.usage_table = speedlink_grabbed_usages,
	.input_mapping = speedlink_input_mapping,
	.event = speedlink_event,
};
module_hid_driver(speedlink_driver);

MODULE_LICENSE("GPL");


text:
<?php

/**
 * PayPal Direct Payment method xml renderer
 *
 * @category    Mage
 * @package     Mage_XmlConnect
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_XmlConnect_Block_Checkout_Payment_Method_Paypal_Direct
    extends Mage_XmlConnect_Block_Checkout_Payment_Method_Paypal_Payflow
{
    /**
     * Prevent any rendering
     *
     * @return string
     */
    protected function _toHtml()
    {
        return '';
    }

    /**
     * Retrieve payment method model
     *
     * @return Mage_Payment_Model_Method_Abstract
     */
    public function getMethod()
    {
        $method = $this->getData('method');
        if (!$method) {
            $method = Mage::getModel('paypal/direct');
            $this->setData('method', $method);
        }

        return $method;
    }
}


text:
require 'spec_helper'
require 'erb'
require 'yaml'

describe 'db:grant' do
end

describe Openbanana do
  before :each do
    Rails = double('rails')
    Rails.stub(:root).and_return('dummy_root')
  end

  describe '#load_yml' do
    it 'should load the database.yml file on Rails.root/config' do
      File.should_receive(:read).with(Rails.root + '/config/database.yml').and_return("")
      YAML.should_receive(:load).and_return({})
      Openbanana.load_yml
    end

    it 'should load the shards.yml file on Rails.root/config' do
      File.should_receive(:read).with(Rails.root + '/config/shards.yml').and_return("")
      YAML.should_receive(:load).and_return({})
      Openbanana.load_yml('shards.yml')
    end
  end

  describe '#config' do
    let(:config) do
      { 'database' => 'test_db',
        'username' => 'test_user',
        'password' => 'test_password'}
    end

    context 'with development configuration' do
      before :each do
        Openbanana.should_receive(:load_yml).and_return({'development' => config})
        Rails.stub(:env).and_return('development')
      end

      it 'should return the proper configuration for this environment' do
        result = Openbanana.config
        result.should == config
      end
    end
  end

  describe '#shard_config' do
    let(:config) do
      { 'database' => 'test_db',
        'username' => 'test_user',
        'password' => 'test_password'}
    end

    context 'with development configuration' do
      before :each do
        Openbanana.should_receive(:load_yml).and_return({'octopus' => {'development' => {'shards' => config}}})
        Rails.stub(:env).and_return('development')
      end

      it 'should return the proper configuration for this environment' do
        result = Openbanana.shard_config
        result.should == config
      end
    end
  end

  describe '#grants' do
    before :each do
      Openbanana.should_receive(:config).and_return(config)
    end

    context 'in production' do
      describe 'with networks' do
        let(:config) do
          { 'database' => 'test_db',
            'username' => 'test_user',
            'password' => 'test_password',
            'networks' => ['127.0.0.0/24']}
        end

        it 'should have networks' do
          result = Openbanana.grants
          result.should include("GRANT ALL PRIVILEGES ON test_db.* TO 'test_user'@'127.0.0.0/24' IDENTIFIED BY 'test_password';")
        end
      end
    end

    context 'on shards' do
      describe 'with multiple shards' do
        let(:config) do
          {
            'shard1' => {
              'database' => 'test_db1',
              'username' => 'test_user',
              'password' => 'test_password'
            },
            'shard2' => {
              'database' => 'test_db2',
              'username' => 'test_user',
              'password' => 'test_password'
            }
          }
        end

        it 'should have both shards' do
          result = Openbanana.grants
          result.should include("GRANT ALL PRIVILEGES ON test_db1.* TO 'test_user'@'%' IDENTIFIED BY 'test_password';")
          result.should include("GRANT ALL PRIVILEGES ON test_db2.* TO 'test_user'@'%' IDENTIFIED BY 'test_password';")
        end
      end
    end

    context 'grants should' do
      let(:config) do
        { 'database' => 'test_db',
          'username' => 'test_user',
          'password' => 'test_password'}
      end

      subject { Openbanana.grants }

      it 'should generate a create database call' do
        should include("CREATE DATABASE test_db;")
      end
      it 'should generate a grant for the user on that database for %' do
        should include("GRANT ALL PRIVILEGES ON test_db.* TO 'test_user'@'%' IDENTIFIED BY 'test_password';")
      end
      it 'should generate a grant for the user on that database for localhost' do
        should include("GRANT ALL PRIVILEGES ON test_db.* TO 'test_user'@'localhost' IDENTIFIED BY 'test_password';")
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="eltos.simpledialogfragments">

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".FlatFragmentActivity"/>
    </application>

</manifest>


text:
param(
    [parameter (Mandatory=$true)]
    [string] $Path
)

$check = Check-VagrantHyperVAccess -Path $Path
$result = @{
    root_dir = ($Path -split '\\')[0,1] -join '\';
    result = $check
}

Write-OutputMessage $(ConvertTo-Json $result)


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// 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 MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// 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 DAMAGE.

package com.google.protobuf;

import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder;

import junit.framework.TestCase;

import java.util.Collections;
import java.util.List;

/**
 * Tests for {@link RepeatedFieldBuilder}. This tests basic functionality.
 * More extensive testing is provided via other tests that exercise the
 * builder.
 *
 * @author jonp@google.com (Jon Perlow)
 */
public class RepeatedFieldBuilderTest extends TestCase {

  public void testBasicUse() {
    TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
    RepeatedFieldBuilder<TestAllTypes, TestAllTypes.Builder,
        TestAllTypesOrBuilder> builder = newRepeatedFieldBuilder(mockParent);
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
    assertEquals(0, builder.getMessage(0).getOptionalInt32());
    assertEquals(1, builder.getMessage(1).getOptionalInt32());

    List<TestAllTypes> list = builder.build();
    assertEquals(2, list.size());
    assertEquals(0, list.get(0).getOptionalInt32());
    assertEquals(1, list.get(1).getOptionalInt32());
    assertIsUnmodifiable(list);

    // Make sure it doesn't change.
    List<TestAllTypes> list2 = builder.build();
    assertSame(list, list2);
    assertEquals(0, mockParent.getInvalidationCount());
  }

  public void testGoingBackAndForth() {
    TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
    RepeatedFieldBuilder<TestAllTypes, TestAllTypes.Builder,
        TestAllTypesOrBuilder> builder = newRepeatedFieldBuilder(mockParent);
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
    assertEquals(0, builder.getMessage(0).getOptionalInt32());
    assertEquals(1, builder.getMessage(1).getOptionalInt32());

    // Convert to list
    List<TestAllTypes> list = builder.build();
    assertEquals(2, list.size());
    assertEquals(0, list.get(0).getOptionalInt32());
    assertEquals(1, list.get(1).getOptionalInt32());
    assertIsUnmodifiable(list);

    // Update 0th item
    assertEquals(0, mockParent.getInvalidationCount());
    builder.getBuilder(0).setOptionalString("foo");
    assertEquals(1, mockParent.getInvalidationCount());
    list = builder.build();
    assertEquals(2, list.size());
    assertEquals(0, list.get(0).getOptionalInt32());
      assertEquals("foo", list.get(0).getOptionalString());
    assertEquals(1, list.get(1).getOptionalInt32());
    assertIsUnmodifiable(list);
    assertEquals(1, mockParent.getInvalidationCount());
  }

  public void testVariousMethods() {
    TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
    RepeatedFieldBuilder<TestAllTypes, TestAllTypes.Builder,
        TestAllTypesOrBuilder> builder = newRepeatedFieldBuilder(mockParent);
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(2).build());
    builder.addBuilder(0, TestAllTypes.getDefaultInstance())
        .setOptionalInt32(0);
    builder.addBuilder(TestAllTypes.getDefaultInstance()).setOptionalInt32(3);

    assertEquals(0, builder.getMessage(0).getOptionalInt32());
    assertEquals(1, builder.getMessage(1).getOptionalInt32());
    assertEquals(2, builder.getMessage(2).getOptionalInt32());
    assertEquals(3, builder.getMessage(3).getOptionalInt32());

    assertEquals(0, mockParent.getInvalidationCount());
    List<TestAllTypes> messages = builder.build();
    assertEquals(4, messages.size());
    assertSame(messages, builder.build()); // expect same list

    // Remove a message.
    builder.remove(2);
    assertEquals(1, mockParent.getInvalidationCount());
    assertEquals(3, builder.getCount());
    assertEquals(0, builder.getMessage(0).getOptionalInt32());
    assertEquals(1, builder.getMessage(1).getOptionalInt32());
    assertEquals(3, builder.getMessage(2).getOptionalInt32());

    // Remove a builder.
    builder.remove(0);
    assertEquals(1, mockParent.getInvalidationCount());
    assertEquals(2, builder.getCount());
    assertEquals(1, builder.getMessage(0).getOptionalInt32());
    assertEquals(3, builder.getMessage(1).getOptionalInt32());

    // Test clear.
    builder.clear();
    assertEquals(1, mockParent.getInvalidationCount());
    assertEquals(0, builder.getCount());
    assertTrue(builder.isEmpty());
  }

  public void testLists() {
    TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
    RepeatedFieldBuilder<TestAllTypes, TestAllTypes.Builder,
        TestAllTypesOrBuilder> builder = newRepeatedFieldBuilder(mockParent);
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
    builder.addMessage(0,
        TestAllTypes.newBuilder().setOptionalInt32(0).build());
    assertEquals(0, builder.getMessage(0).getOptionalInt32());
    assertEquals(1, builder.getMessage(1).getOptionalInt32());

    // Use list of builders.
    List<TestAllTypes.Builder> builders = builder.getBuilderList();
    assertEquals(0, builders.get(0).getOptionalInt32());
    assertEquals(1, builders.get(1).getOptionalInt32());
    builders.get(0).setOptionalInt32(10);
    builders.get(1).setOptionalInt32(11);

    // Use list of protos
    List<TestAllTypes> protos = builder.getMessageList();
    assertEquals(10, protos.get(0).getOptionalInt32());
    assertEquals(11, protos.get(1).getOptionalInt32());

    // Add an item to the builders and verify it's updated in both
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(12).build());
    assertEquals(3, builders.size());
    assertEquals(3, protos.size());
  }

  private void assertIsUnmodifiable(List<?> list) {
    if (list == Collections.emptyList()) {
      // OKAY -- Need to check this b/c EmptyList allows you to call clear.
    } else {
      try {
        list.clear();
        fail("List wasn't immutable");
      } catch (UnsupportedOperationException e) {
        // good
      }
    }
  }

  private RepeatedFieldBuilder<TestAllTypes, TestAllTypes.Builder,
      TestAllTypesOrBuilder>
      newRepeatedFieldBuilder(GeneratedMessage.BuilderParent parent) {
    return new RepeatedFieldBuilder<TestAllTypes, TestAllTypes.Builder,
        TestAllTypesOrBuilder>(Collections.<TestAllTypes>emptyList(), false,
        parent, false);
  }
}


text:
classdef PPRateTransition < DrakeSystem
% PIECEWISE-POLYNOMIAL RATE TRANSITION SYSTEM
% Some systems, such as a trajectory planner running as a
% model-predictive controller, run at low sample rates, but
% think enough about the future to be able to produce continuous
% outputs.  This class is intended as the solution to that.
% The output of the planning controller can be the parameters
% of a piecewise polynomial, which are fed (via zero-order hold)
% into the input of this PPRateTransition block.  This block
% will then produce the smooth, continuous output described by
% that polynomial.

  methods
    function obj = PPRateTransition(num_pieces,order,dimension)
      % PPRateTransition(num_pieces,order,dimension)
      % parameters mimic the mkpp and unmkpp syntax
      % @param num_pieces the number of breaks is num_pieces+1
      % @param order one + the degree of each piecewise polynomial
      %       (a cubic polynomial has order=4)
      % @param dimension the length of the vector output

      % the input to the system is
      %  [breaks(:); coeffs(:)]
      obj = obj@DrakeSystem(0,0,(num_pieces+1)+(num_pieces*order*dimension),dimension,true,false);
      obj.num_pieces = num_pieces;
      obj.order = order;
      obj.dimension = dimension;

      obj = setSampleTime(obj,[0;0]);
    end

    function y = output(obj,t,x,u)
      breaks = u(1:(obj.num_pieces+1));
      coefs = reshape(u((obj.num_pieces+2):end),obj.dimension,obj.num_pieces,obj.order);
      pp = mkpp(breaks,coefs,obj.dimension);
      y = ppvalSafe(pp,t,false,false);
    end
  end

  properties
    num_pieces
    order
    dimension
  end
end


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

// Brazilian Portuguese
var strings = {
  prefixAgo: 'há',
  prefixFromNow: 'em',
  suffixAgo: null,
  suffixFromNow: null,
  seconds: 'alguns segundos',
  minute: 'um minuto',
  minutes: '%d minutos',
  hour: 'uma hora',
  hours: '%d horas',
  day: 'um dia',
  days: '%d dias',
  month: 'um mês',
  months: '%d meses',
  year: 'um ano',
  years: '%d anos'
};
exports.default = strings;


text:
module Distributable
  VERSION = "0.1.0"
end


text:
.PHONY: clean-pyc clean-build docs clean

help:
	@echo "clean - remove all build, test, coverage and Python artifacts"
	@echo "clean-build - remove build artifacts"
	@echo "clean-pyc - remove Python file artifacts"
	@echo "clean-test - remove test and coverage artifacts"
	@echo "lint - check style with pylint"
	@echo "test - run tests quickly with nosetests"
	@echo "test-all - run tests on every Python version with tox"
	@echo "coverage - check code coverage quickly with nosetests"
	@echo "docs - generate Sphinx HTML documentation, including API docs"
	@echo "release - package and upload a release"
	@echo "dist - package"
	@echo "install - install the package to the active Python's site-packages"

clean: clean-build clean-pyc clean-test

clean-build:
	rm -fr build/
	rm -fr dist/
	rm -fr .eggs/
	find . -name '*.egg-info' -exec rm -fr {} +
	find . -name '*.egg' -exec rm -f {} +

clean-pyc:
	find . -name '*.pyc' -exec rm -f {} +
	find . -name '*.pyo' -exec rm -f {} +
	find . -name '*~' -exec rm -f {} +
	find . -name '__pycache__' -exec rm -fr {} +

clean-test:
	rm -fr .tox/
	rm -f .coverage
	rm -fr htmlcov/

lint:
	@if ! which pep8 >/dev/null; then echo "pep8 not installed.\nRun:\n    pip install pep8" && false; fi
	@if ! which pylint >/dev/null; then echo "pylint not installed.\nRun:\n    pip install pylint" && false; fi
	-pep8 vld tests
	-find vld -name "*.py" -exec pylint {} +
	-find tests -name "*.py" -exec pylint {} +

test: test-deps clean-pyc
	python setup.py nosetests

test-cover: test-deps clean-pyc
	python setup.py nosetests --with-coverage --cover-package=vld

test-all: test-deps clean-pyc
	@if ! which tox >/dev/null; then echo "tox not installed.\nRun:\n    pip install tox" && false; fi
	tox

test-deps:
	pip install -r requirements/test.txt

coverage: test-deps clean-pyc
	coverage run --source vld setup.py nosetests
	make coverage-show

coverage-all:
	coverage erase
	make test-all
	make coverage-show

coverage-show:
	coverage report
	coverage html
	see htmlcov/index.html

docs: docs-deps
	rm -f docs/vld.rst
	rm -f docs/modules.rst
	sphinx-apidoc -o docs/ vld
	$(MAKE) -C docs clean
	$(MAKE) -C docs html
	see docs/_build/html/index.html

docs-deps:
	pip install -r requirements/docs.txt

release: clean dist-deps
	python setup.py sdist upload
	python setup.py bdist_wheel upload

dist: clean dist-deps
	python setup.py sdist
	python setup.py bdist_wheel
	ls -l dist

dist-deps:
	pip install -r requirements/dist.txt

install: clean
	python setup.py install

yapf:
	find vld -name "*.py" -exec echo {} \; -exec yapf --diff {} \;


text:
#include <gmp.h>
#include "gmp-impl.h"

/* Multiply the natural numbers u (pointed to by UP, with USIZE limbs)
   and v (pointed to by VP, with VSIZE limbs), and store the result at
   PRODP.  USIZE + VSIZE limbs are always stored, but if the input
   operands are normalized.  Return the most significant limb of the
   result.

   NOTE: The space pointed to by PRODP is overwritten before finished
   with U and V, so overlap is an error.

   Argument constraints:
   1. USIZE >= VSIZE.
   2. PRODP != UP and PRODP != VP, i.e. the destination
      must be distinct from the multiplier and the multiplicand.  */

/* If KARATSUBA_THRESHOLD is not already defined, define it to a
   value which is good on most machines.  */
#ifndef KARATSUBA_THRESHOLD
#define KARATSUBA_THRESHOLD 32
#endif

mp_limb_t
#if __STDC__
mpn_mul (mp_ptr prodp,
	 mp_srcptr up, mp_size_t usize,
	 mp_srcptr vp, mp_size_t vsize)
#else
mpn_mul (prodp, up, usize, vp, vsize)
     mp_ptr prodp;
     mp_srcptr up;
     mp_size_t usize;
     mp_srcptr vp;
     mp_size_t vsize;
#endif
{
  mp_ptr prod_endp = prodp + usize + vsize - 1;
  mp_limb_t cy;
  mp_ptr tspace;
  TMP_DECL (marker);

  if (vsize < KARATSUBA_THRESHOLD)
    {
      /* Handle simple cases with traditional multiplication.

	 This is the most critical code of the entire function.  All
	 multiplies rely on this, both small and huge.  Small ones arrive
	 here immediately.  Huge ones arrive here as this is the base case
	 for Karatsuba's recursive algorithm below.  */
      mp_size_t i;
      mp_limb_t cy_limb;
      mp_limb_t v_limb;

      if (vsize == 0)
	return 0;

      /* Multiply by the first limb in V separately, as the result can be
	 stored (not added) to PROD.  We also avoid a loop for zeroing.  */
      v_limb = vp[0];
      if (v_limb <= 1)
	{
	  if (v_limb == 1)
	    MPN_COPY (prodp, up, usize);
	  else
	    MPN_ZERO (prodp, usize);
	  cy_limb = 0;
	}
      else
	cy_limb = mpn_mul_1 (prodp, up, usize, v_limb);

      prodp[usize] = cy_limb;
      prodp++;

      /* For each iteration in the outer loop, multiply one limb from
	 U with one limb from V, and add it to PROD.  */
      for (i = 1; i < vsize; i++)
	{
	  v_limb = vp[i];
	  if (v_limb <= 1)
	    {
	      cy_limb = 0;
	      if (v_limb == 1)
		cy_limb = mpn_add_n (prodp, prodp, up, usize);
	    }
	  else
	    cy_limb = mpn_addmul_1 (prodp, up, usize, v_limb);

	  prodp[usize] = cy_limb;
	  prodp++;
	}
      return cy_limb;
    }

  TMP_MARK (marker);

  tspace = (mp_ptr) TMP_ALLOC (2 * vsize * BYTES_PER_MP_LIMB);
  MPN_MUL_N_RECURSE (prodp, up, vp, vsize, tspace);

  prodp += vsize;
  up += vsize;
  usize -= vsize;
  if (usize >= vsize)
    {
      mp_ptr tp = (mp_ptr) TMP_ALLOC (2 * vsize * BYTES_PER_MP_LIMB);
      do
	{
	  MPN_MUL_N_RECURSE (tp, up, vp, vsize, tspace);
	  cy = mpn_add_n (prodp, prodp, tp, vsize);
	  mpn_add_1 (prodp + vsize, tp + vsize, vsize, cy);
	  prodp += vsize;
	  up += vsize;
	  usize -= vsize;
	}
      while (usize >= vsize);
    }

  /* True: usize < vsize.  */

  /* Make life simple: Recurse.  */

  if (usize != 0)
    {
      mpn_mul (tspace, vp, vsize, up, usize);
      cy = mpn_add_n (prodp, prodp, tspace, vsize);
      mpn_add_1 (prodp + vsize, tspace + vsize, usize, cy);
    }

  TMP_FREE (marker);
  return *prod_endp;
}


text:
from __future__ import absolute_import

# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
_version_major = 0
_version_minor = 2
_version_micro = ''  # use '' for first of series, number for 1 and above
_version_extra = 'dev17'
# _version_extra = ''  # Uncomment this for full releases

# Construct full version string from these.
_ver = [_version_major, _version_minor]
if _version_micro:
    _ver.append(_version_micro)
if _version_extra:
    _ver.append(_version_extra)

__version__ = '.'.join(map(str, _ver))

CLASSIFIERS = ["Development Status :: 2 - Pre-Alpha",
               "Environment :: Console",
               "Intended Audience :: Science/Research",
               "License :: OSI Approved :: MIT License",
               "Operating System :: OS Independent",
               "Programming Language :: Python",
               "Topic :: Scientific/Engineering :: Information Analysis"]

# Description should be a one-liner:
description = "An interactive data exploration tool for json structured ionic\
        liquid data from ILThermo (NIST)"
# Long description will go up on the pypi page
long_description = """

salty
========
To get started using these components in your own software, please go to the
repository README_.
.. _README: https://github.com/wesleybeckner/afm-miner/README.md

License
=======
``salty`` is licensed under the terms of the MIT license. See the file
"LICENSE" for information on the history of this software, terms & conditions
for usage, and a DISCLAIMER OF ALL WARRANTIES.
All trademarks referenced herein are property of their respective holders.
Copyright (c) 2015--, Wesley Beckner, The University of Washington
eScience Institute.
"""

NAME = "salty-ilthermo"
MAINTAINER = "Wesley Beckner"
MAINTAINER_EMAIL = "wesleybeckner@gmail.com"
DESCRIPTION = description
LONG_DESCRIPTION = long_description
URL = "http://github.com/wesleybeckner/salty"
DOWNLOAD_URL = ""
LICENSE = "MIT"
AUTHOR = "Wesley Beckner"
AUTHOR_EMAIL = "wesleybeckner@gmail.com"
PLATFORMS = "OS Independent"
MAJOR = _version_major
MINOR = _version_minor
MICRO = _version_micro
VERSION = __version__
PACKAGE_DATA = {'salty': ['data/*']}
REQUIRES = ["numpy"]


text:
package com.github.hobbe.android.openkarotz.activity;

import android.app.Activity;
import android.os.Bundle;

import com.github.hobbe.android.openkarotz.fragment.KarotzSettingsFragment;

/**
 * Settings activity.
 */
public class SettingsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Display the fragment as the main content.
        getFragmentManager().beginTransaction().replace(android.R.id.content, new KarotzSettingsFragment()).commit();

    }

    /** Key for Karotz hostname preference. */
    public static final String KEY_PREF_KAROTZ_HOST = "prefKarotzHost";

}


text:
package org.calrissian.accumulorecipes.metricsstore.normalizer;

import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.Combiner;
import org.calrissian.accumulorecipes.metricsstore.domain.Metric;
import org.calrissian.accumulorecipes.metricsstore.exception.InvalidMetricException;

public interface MetricNormalizer<T extends Metric> {

    String name();

    Value getValue(T metric);

    T getMetric(Value value) throws InvalidMetricException;

    Class<T> normalizes();

    Class<? extends Combiner> combinerClass();

    void setSpecificIteratorOptions(IteratorSetting is);
}


text:
return function (loader)

  local Default = loader.load "cosy.configuration.layers".default

  Default.token = {
    algorithm = "HS256",
    secret    = nil,
  }

  Default.expiration = {
    identification = 99 * 365 * 24 * 3600, -- 99 years
    validation     = 1 * 3600, -- 1 hour
    authentication = 30 * 24 * 3600, -- 1 month
    administration = 99 * 365 * 24 * 3600, -- 99 years
  }

end


text:
import {DomFingerprint} from './utils/dom-fingerprint';
import {Services} from './services';
import {dict} from './utils/object.js';
import {experimentToggles, isCanary} from './experiments';
import {getLengthNumeral} from './layout';
import {getModeObject} from './mode-object';
import {getPageLayoutBoxBlocking} from './utils/page-layout-box';
import {internalRuntimeVersion} from './internal-version';
import {urls} from './config';

/**
 * Produces the attributes for the ad template.
 * @param {!Window} parentWindow
 * @param {!AmpElement} element
 * @param {string} sentinel
 * @param {!JsonObject=} attributes
 * @return {!JsonObject}
 */
export function getContextMetadata(
  parentWindow,
  element,
  sentinel,
  attributes
) {
  const startTime = Date.now();
  const width = element.getAttribute('width');
  const height = element.getAttribute('height');
  attributes = attributes ? attributes : dict();
  attributes['width'] = getLengthNumeral(width);
  attributes['height'] = getLengthNumeral(height);
  if (element.getAttribute('title')) {
    attributes['title'] = element.getAttribute('title');
  }
  let locationHref = parentWindow.location.href;
  // This is really only needed for tests, but whatever. Children
  // see us as the logical origin, so telling them we are about:srcdoc
  // will fail ancestor checks.
  if (locationHref == 'about:srcdoc') {
    locationHref = parentWindow.parent.location.href;
  }

  const ampdoc = Services.ampdoc(element);
  const docInfo = Services.documentInfoForDoc(element);
  const viewer = Services.viewerForDoc(element);
  const referrer = viewer.getUnconfirmedReferrerUrl();

  const layoutRect = getPageLayoutBoxBlocking(element);

  // Use JsonObject to preserve field names so that ampContext can access
  // values with name
  // ampcontext.js and this file are compiled in different compilation unit

  // Note: Field names can by perserved by using JsonObject, or by adding
  // perserved name to extern. We are doing both right now.
  // Please also add new introduced variable
  // name to the extern list.
  attributes['_context'] = dict({
    'ampcontextVersion': internalRuntimeVersion(),
    'ampcontextFilepath': `${
      urls.thirdParty
    }/${internalRuntimeVersion()}/ampcontext-v0.js`,
    'sourceUrl': docInfo.sourceUrl,
    'referrer': referrer,
    'canonicalUrl': docInfo.canonicalUrl,
    'pageViewId': docInfo.pageViewId,
    'location': {
      'href': locationHref,
    },
    'startTime': startTime,
    'tagName': element.tagName,
    'mode': getModeObject(),
    'canary': isCanary(parentWindow),
    'hidden': !ampdoc.isVisible(),
    'initialLayoutRect': layoutRect
      ? {
          'left': layoutRect.left,
          'top': layoutRect.top,
          'width': layoutRect.width,
          'height': layoutRect.height,
        }
      : null,
    'domFingerprint': DomFingerprint.generate(element),
    'experimentToggles': experimentToggles(parentWindow),
    'sentinel': sentinel,
  });
  const adSrc = element.getAttribute('src');
  if (adSrc) {
    attributes['src'] = adSrc;
  }
  return attributes;
}


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

#include "context_gl_x11.h"

#ifdef X11_ENABLED
#if defined(OPENGL_ENABLED)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define GLX_GLXEXT_PROTOTYPES
#include <GL/glx.h>
#include <GL/glxext.h>

#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092

typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *);

struct ContextGL_X11_Private {

	::GLXContext glx_context;
};

void ContextGL_X11::release_current() {

	glXMakeCurrent(x11_display, None, NULL);
}

void ContextGL_X11::make_current() {

	glXMakeCurrent(x11_display, x11_window, p->glx_context);
}

void ContextGL_X11::swap_buffers() {

	glXSwapBuffers(x11_display, x11_window);
}

static bool ctxErrorOccurred = false;
static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) {
	ctxErrorOccurred = true;
	return 0;
}

static void set_class_hint(Display *p_display, Window p_window) {
	XClassHint *classHint;

	/* set the name and class hints for the window manager to use */
	classHint = XAllocClassHint();
	if (classHint) {
		classHint->res_name = (char *)"Godot_Engine";
		classHint->res_class = (char *)"Godot";
	}
	XSetClassHint(p_display, p_window, classHint);
	XFree(classHint);
}

Error ContextGL_X11::initialize() {

	//const char *extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display));

	GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB");

	ERR_FAIL_COND_V(!glXCreateContextAttribsARB, ERR_UNCONFIGURED);

	static int visual_attribs[] = {
		GLX_RENDER_TYPE, GLX_RGBA_BIT,
		GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
		GLX_DOUBLEBUFFER, true,
		GLX_RED_SIZE, 1,
		GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1,
		GLX_DEPTH_SIZE, 24,
		None
	};

	static int visual_attribs_layered[] = {
		GLX_RENDER_TYPE, GLX_RGBA_BIT,
		GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
		GLX_DOUBLEBUFFER, true,
		GLX_RED_SIZE, 8,
		GLX_GREEN_SIZE, 8,
		GLX_BLUE_SIZE, 8,
		GLX_ALPHA_SIZE, 8,
		GLX_DEPTH_SIZE, 24,
		None
	};

	int fbcount;
	GLXFBConfig fbconfig = 0;
	XVisualInfo *vi = NULL;

	XSetWindowAttributes swa;
	swa.event_mask = StructureNotifyMask;
	swa.border_pixel = 0;
	unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;

	if (OS::get_singleton()->is_layered_allowed()) {
		GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs_layered, &fbcount);
		ERR_FAIL_COND_V(!fbc, ERR_UNCONFIGURED);

		for (int i = 0; i < fbcount; i++) {
			vi = (XVisualInfo *)glXGetVisualFromFBConfig(x11_display, fbc[i]);
			if (!vi)
				continue;

			XRenderPictFormat *pict_format = XRenderFindVisualFormat(x11_display, vi->visual);
			if (!pict_format) {
				XFree(vi);
				vi = NULL;
				continue;
			}

			fbconfig = fbc[i];
			if (pict_format->direct.alphaMask > 0) {
				break;
			}
		}
		ERR_FAIL_COND_V(!fbconfig, ERR_UNCONFIGURED);

		swa.background_pixmap = None;
		swa.background_pixel = 0;
		swa.border_pixmap = None;
		valuemask |= CWBackPixel;

	} else {
		GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
		ERR_FAIL_COND_V(!fbc, ERR_UNCONFIGURED);

		vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);

		fbconfig = fbc[0];
	}

	int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&ctxErrorHandler);

	switch (context_type) {
		case OLDSTYLE: {

			p->glx_context = glXCreateContext(x11_display, vi, 0, GL_TRUE);
			ERR_FAIL_COND_V(!p->glx_context, ERR_UNCONFIGURED);
		} break;
		case GLES_2_0_COMPATIBLE: {

			p->glx_context = glXCreateNewContext(x11_display, fbconfig, GLX_RGBA_TYPE, 0, true);
			ERR_FAIL_COND_V(!p->glx_context, ERR_UNCONFIGURED);
		} break;
		case GLES_3_0_COMPATIBLE: {

			static int context_attribs[] = {
				GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
				GLX_CONTEXT_MINOR_VERSION_ARB, 3,
				GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
				GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB /*|GLX_CONTEXT_DEBUG_BIT_ARB*/,
				None
			};

			p->glx_context = glXCreateContextAttribsARB(x11_display, fbconfig, NULL, true, context_attribs);
			ERR_FAIL_COND_V(ctxErrorOccurred || !p->glx_context, ERR_UNCONFIGURED);
		} break;
	}

	swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone);
	x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa);

	ERR_FAIL_COND_V(!x11_window, ERR_UNCONFIGURED);
	set_class_hint(x11_display, x11_window);
	XMapWindow(x11_display, x11_window);

	XSync(x11_display, False);
	XSetErrorHandler(oldHandler);

	glXMakeCurrent(x11_display, x11_window, p->glx_context);

	XFree(vi);

	return OK;
}

int ContextGL_X11::get_window_width() {

	XWindowAttributes xwa;
	XGetWindowAttributes(x11_display, x11_window, &xwa);

	return xwa.width;
}

int ContextGL_X11::get_window_height() {
	XWindowAttributes xwa;
	XGetWindowAttributes(x11_display, x11_window, &xwa);

	return xwa.height;
}

void ContextGL_X11::set_use_vsync(bool p_use) {
	static bool setup = false;
	static PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = NULL;
	static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalMESA = NULL;
	static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = NULL;

	if (!setup) {
		setup = true;
		String extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display));
		if (extensions.find("GLX_EXT_swap_control") != -1)
			glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalEXT");
		if (extensions.find("GLX_MESA_swap_control") != -1)
			glXSwapIntervalMESA = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalMESA");
		if (extensions.find("GLX_SGI_swap_control") != -1)
			glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalSGI");
	}
	int val = p_use ? 1 : 0;
	if (glXSwapIntervalMESA) {
		glXSwapIntervalMESA(val);
	} else if (glXSwapIntervalSGI) {
		glXSwapIntervalSGI(val);
	} else if (glXSwapIntervalEXT) {
		GLXDrawable drawable = glXGetCurrentDrawable();
		glXSwapIntervalEXT(x11_display, drawable, val);
	} else
		return;
	use_vsync = p_use;
}
bool ContextGL_X11::is_using_vsync() const {

	return use_vsync;
}

ContextGL_X11::ContextGL_X11(::Display *p_x11_display, ::Window &p_x11_window, const OS::VideoMode &p_default_video_mode, ContextType p_context_type) :
		x11_window(p_x11_window) {

	default_video_mode = p_default_video_mode;
	x11_display = p_x11_display;

	context_type = p_context_type;

	double_buffer = false;
	direct_render = false;
	glx_minor = glx_major = 0;
	p = memnew(ContextGL_X11_Private);
	p->glx_context = 0;
	use_vsync = false;
}

ContextGL_X11::~ContextGL_X11() {
	release_current();
	glXDestroyContext(x11_display, p->glx_context);
	memdelete(p);
}

#endif
#endif


text:
<?php

namespace App\Http\Logics;

use Validator;

class FleetConfigLogic extends Logic
{
    public function check(Array $array)
    {
        $validator = Validator::make($array, [
            'style' => 'required|in:1,2',
        ]);

        $this->validCore($validator);
    }
}


text:
BEGIN_EXTERN_C()
/* {{{ Enums registration function */
void <?=strtolower($header_define)?>_enums(INIT_FUNC_ARGS)
{
    zend_class_entry ce;


text:
function h = HessianRFbase(policy, data, gamma)
% Computes the Hessian of a policy wrt its parameters using the optimal
% baseline.
% H is a [D x D x R] matrix, where D is the length of the policy parameters
% and R is the number of immediate rewards received at each time step. Each
% page of H corresponds to the Hessian wrt an objective.
%
% =========================================================================
% REFERENCE
% S Parisi, M Pirotta, M Restelli
% Multi-objective Reinforcement Learning through Continuous Pareto Manifold
% Approximation (2016)

actions = [data.a];
states = [data.s];
dlogpi = policy.dlogPidtheta(states,actions);
hlogpi = policy.hlogPidtheta(states,actions);
episodeslength = [data.length];
totstep = sum(episodeslength);
totepisodes = numel(data);
dreward = size(data(1).r,1);

sumdlog = cumsumidx(dlogpi,cumsum(episodeslength));
sumdlog2 = bsxfun(@times,permute(sumdlog,[1 3 2]),permute(sumdlog,[3 1 2]));
sumhlog = cumsumidx3(hlogpi,cumsum(episodeslength));
gammar = bsxfun(@times, [data.r], gamma.^([data.t]-1));
sumrew = cumsumidx(gammar,cumsum(episodeslength));

% Compute the optimal baseline
tmp = (sumdlog2 + sumhlog).^2;
bden = sum(tmp,3);
bden = repmat(bden,1,1,dreward);
bnum = squeeze( sum( bsxfun(@times, tmp, reshape(sumrew',[1 1 size(sumrew')])), 3) );
b = bnum ./ bden;
b(isnan(b)) = 0; % When 0 / 0

% Compute the Hessian
rewb = bsxfun(@plus, -b, reshape(sumrew,[1 1 size(sumrew)]));
sumhd = sumdlog2 + sumhlog;
h = squeeze( sum( repmat(sumhd,1,1,1,dreward).*permute(rewb,[1 2 4 3]), 3) );

if gamma == 1
    h = h / totstep;
else
    h = h / totepisodes;
end

end


text:
class SpreadBuilder {
  var count : Integer = 0

  var spread : Spread = null

  def of (op : Option): Spread = {
    require(count != 0, "SpreadBuilder without count provided")

    if (spread == null) {
      op.costBasis *= count
      new Spread and (op contracts count)
    } else {
      op.costBasis *= count
      spread and (op contracts count)
    }
  }
}


text:
using NHibernate.Mapping.ByCode.Conformist;

namespace Google.Cloud.Spanner.NHibernate.Tests.Entities
{
    public class Teacher : Person
    {
        public virtual string Code { get; set; }
    }

    public class TeacherMapping : SubclassMapping<Teacher>
    {
        public TeacherMapping()
        {
            DiscriminatorValue("Teacher");
            DynamicUpdate(true);
            Property(x => x.Code);
        }
    }
}


text:
package org.dasein.cloud.zimory;

/**
 * Simple error representing a failure to set up a configuration.
 *
Created by George Reese: 10/30/12 1:10 PM

 * @author George Reese
 * @version 2012.09 initial version
 * @since 2012.09
 */
public class NoContextException extends ZimoryConfigurationException {
    public NoContextException() { super("No context was set for this request"); }
}


text:
/* eslint-disable no-underscore-dangle */
import { createLogger } from 'redux-logger'
import Immutable from 'immutable'
import { createBrowserHistory } from 'history';
import { connectRouter, routerMiddleware } from 'connected-react-router/immutable';
import { compose, createStore, applyMiddleware } from 'redux'
import createSagaMiddleware, { END } from 'redux-saga'
import { fromJSON } from 'transit-immutable-js'
import { rehydrate } from 'glamor'
import storage from 'redux-persist/lib/storage'
import { persistCombineReducers } from 'redux-persist'
import immutableTransform from 'redux-persist-transform-immutable'

import * as reducers from './reducers'
import rootSaga from './sagas'

const ENV = require('../env');

const whitelist = ['authentication', 'editor', 'gui', 'profile']

const persistConfig = { // configuration object for redux-persist
  transforms: [immutableTransform()],
  key: 'root',
  storage,
  whitelist,
}
export const browserHistory = createBrowserHistory();
// eslint-disable-next-line max-len
const persistReducers = history => persistCombineReducers(persistConfig, { router: connectRouter(history), ...reducers });

// Always take the reducedState from rehydrate since the inboundState
// seems to be a subset of what is actually returned from the rehydrate action

const createElloStore = (passedInitialState = {}) => {
  const logConfig = {
    collapsed: true,
    predicate: () => ENV.APP_DEBUG,
  }
  if (ENV.NODE_ENV === 'development') {
    logConfig.stateTransformer = (state) => {
      const newState = {}
      Object.keys(state).forEach((key) => {
        newState[key] = state[key].toJS()
      })
      return newState
    }
  }
  if (ENV.APP_DEBUG) {
    window.Pam = r => fromJSON(JSON.parse(localStorage.getItem(`reduxPersist:${r}`))).toJS()
  }
  const logger = createLogger(logConfig)
  const sagaMiddleware = createSagaMiddleware()
  const serverInitState = window.__INITIAL_STATE__
  if (serverInitState) {
    Object.keys(serverInitState).forEach((key) => {
      serverInitState[key] = Immutable.fromJS(serverInitState[key])
    })
  }
  const initialState = serverInitState || passedInitialState
  // react-router-redux doesn't know how to serialize
  // query params from server-side rendering, so we just kill it
  // and let the browser reconstruct the router state
  initialState.router = Immutable.Map()

  if (window.__GLAM__) { rehydrate(window.__GLAM__) }

  const store = createStore(
    persistReducers(browserHistory),
    {},
    compose(applyMiddleware(routerMiddleware(browserHistory), sagaMiddleware, logger)),
  );
  store.close = () => store.dispatch(END)

  store.sagaTask = sagaMiddleware.run(rootSaga)
  return store;
}

export default createElloStore()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _05_NumberComparer
{
    class Program
    {
        static void Main(string[] args)
        {
            double A = double.Parse(Console.ReadLine());
            double B = double.Parse(Console.ReadLine());
            Console.WriteLine(A > B ? A : B);

        }
    }
}


text:
<?php

namespace Spatie\MediaLibrary\UrlGenerator;

class S3UrlGenerator extends BaseUrlGenerator
{
    /**
     * Get the url for the profile of a media item.
     *
     * @return string
     */
    public function getUrl() : string
    {
        return config('laravel-medialibrary.s3.domain').'/'.$this->getPathRelativeToRoot();
    }
}


text:
<?php

declare(strict_types=1);

namespace Humbug\PhpScoper\Patcher;

use PHPUnit\Framework\TestCase;

/**
 * @covers \Humbug\PhpScoper\Patcher\SymfonyPatcher
 *
 * @internal
 */
class SymfonyPatcherTest extends TestCase
{
    /**
     * @dataProvider provideFiles
     */
    public function test_patch_the_symfony_dependency_injection_container_php_dumper(string $filePath, string $contents, string $expected): void
    {
        $actual = (new SymfonyPatcher())->__invoke($filePath, 'Humbug', $contents);

        self::assertSame($expected, $actual);
    }

    public static function provideFiles(): iterable
    {
        $validPaths = [
            'src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php',
            'symfony/dependency-injection/Dumper/PhpDumper.php',
            'vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php',
            'vendor/symfony/dependency-injection/Dumper/PhpDumper.php',
        ];

        $invalidPaths = [
            'DependencyInjection/Dumper/PhpDumper.php',
            'dependency-injection/Dumper/PhpDumper.php',
            'Dumper/PhpDumper.php',
        ];

        foreach (self::provideCodeSamples() as [$input, $scopedOutput]) {
            foreach ($validPaths as $path) {
                yield [$path, $input, $scopedOutput];
            }

            foreach ($invalidPaths as $path) {
                yield [$path, $input, $input];
            }
        }
    }

    private static function provideCodeSamples(): iterable
    {
        yield [
            <<<'PHP'
                    private function startClass(string $class, string $baseClass, string $baseClassWithNamespace): string
                    {
                        $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : '';

                        $code = <<<EOF
                <?php
                $namespaceLine
                use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
                use Symfony\Component\DependencyInjection\ContainerInterface;
                use Symfony\Component\DependencyInjection\Container;
                use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
                use Symfony\Component\DependencyInjection\Exception\LogicException;
                use Symfony\Component\DependencyInjection\Exception\RuntimeException;
                use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

                /*{$this->docStar}
                 * This class has been auto-generated
                 * by the Symfony Dependency Injection Component.
                 *
                 * @final since Symfony 3.3
                 */
                class $class extends $baseClass
                {
                    private \$parameters;
                    private \$targetDirs = array();

                    /*{$this->docStar}
                     * @internal but protected for BC on cache:clear
                     */
                    protected \$privates = array();

                    public function __construct()
                    {

                EOF;
                PHP,
            <<<'PHP'
                    private function startClass(string $class, string $baseClass, string $baseClassWithNamespace): string
                    {
                        $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : '';

                        $code = <<<EOF
                <?php
                $namespaceLine
                use Humbug\Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
                use Humbug\Symfony\Component\DependencyInjection\ContainerInterface;
                use Humbug\Symfony\Component\DependencyInjection\Container;
                use Humbug\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
                use Humbug\Symfony\Component\DependencyInjection\Exception\LogicException;
                use Humbug\Symfony\Component\DependencyInjection\Exception\RuntimeException;
                use Humbug\Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

                /*{$this->docStar}
                 * This class has been auto-generated
                 * by the Symfony Dependency Injection Component.
                 *
                 * @final since Symfony 3.3
                 */
                class $class extends $baseClass
                {
                    private \$parameters;
                    private \$targetDirs = array();

                    /*{$this->docStar}
                     * @internal but protected for BC on cache:clear
                     */
                    protected \$privates = array();

                    public function __construct()
                    {

                EOF;
                PHP,
        ];

        yield [
            <<<'PHP'
                    private function startClass(string $class, string $baseClass, string $baseClassWithNamespace): string
                    {
                        $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : '';

                        $code = <<<EOF
                <?php
                $namespaceLine
                use Symfony\\Component\\DependencyInjection\\Argument\\RewindableGenerator;
                use Symfony\\Component\\DependencyInjection\\ContainerInterface;
                use Symfony\\Component\\DependencyInjection\\Container;
                use Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException;
                use Symfony\\Component\\DependencyInjection\\Exception\\LogicException;
                use Symfony\\Component\\DependencyInjection\\Exception\\RuntimeException;
                use Symfony\\Component\\DependencyInjection\\ParameterBag\\FrozenParameterBag;

                /*{$this->docStar}
                 * This class has been auto-generated
                 * by the Symfony Dependency Injection Component.
                 *
                 * @final since Symfony 3.3
                 */
                class $class extends $baseClass
                {
                    private \$parameters;
                    private \$targetDirs = array();

                    /*{$this->docStar}
                     * @internal but protected for BC on cache:clear
                     */
                    protected \$privates = array();

                    public function __construct()
                    {

                EOF;
                PHP,
            <<<'PHP'
                    private function startClass(string $class, string $baseClass, string $baseClassWithNamespace): string
                    {
                        $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : '';

                        $code = <<<EOF
                <?php
                $namespaceLine
                use Humbug\\Symfony\\Component\\DependencyInjection\\Argument\\RewindableGenerator;
                use Humbug\\Symfony\\Component\\DependencyInjection\\ContainerInterface;
                use Humbug\\Symfony\\Component\\DependencyInjection\\Container;
                use Humbug\\Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException;
                use Humbug\\Symfony\\Component\\DependencyInjection\\Exception\\LogicException;
                use Humbug\\Symfony\\Component\\DependencyInjection\\Exception\\RuntimeException;
                use Humbug\\Symfony\\Component\\DependencyInjection\\ParameterBag\\FrozenParameterBag;

                /*{$this->docStar}
                 * This class has been auto-generated
                 * by the Symfony Dependency Injection Component.
                 *
                 * @final since Symfony 3.3
                 */
                class $class extends $baseClass
                {
                    private \$parameters;
                    private \$targetDirs = array();

                    /*{$this->docStar}
                     * @internal but protected for BC on cache:clear
                     */
                    protected \$privates = array();

                    public function __construct()
                    {

                EOF;
                PHP,
        ];

        yield [
            <<<'PHP'
                    private function startClass(string $class, string $baseClass, string $baseClassWithNamespace): string
                    {
                        $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : '';

                        $code = <<<EOF
                <?php
                $namespaceLine
                use Humbug\Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
                use Humbug\Symfony\Component\DependencyInjection\ContainerInterface;
                use Humbug\Symfony\Component\DependencyInjection\Container;
                use Humbug\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
                use Humbug\Symfony\Component\DependencyInjection\Exception\LogicException;
                use Humbug\Symfony\Component\DependencyInjection\Exception\RuntimeException;
                use Humbug\Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

                /*{$this->docStar}
                 * This class has been auto-generated
                 * by the Symfony Dependency Injection Component.
                 *
                 * @final since Symfony 3.3
                 */
                class $class extends $baseClass
                {
                    private \$parameters;
                    private \$targetDirs = array();

                    /*{$this->docStar}
                     * @internal but protected for BC on cache:clear
                     */
                    protected \$privates = array();

                    public function __construct()
                    {

                EOF;
                PHP,
            <<<'PHP'
                    private function startClass(string $class, string $baseClass, string $baseClassWithNamespace): string
                    {
                        $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : '';

                        $code = <<<EOF
                <?php
                $namespaceLine
                use Humbug\Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
                use Humbug\Symfony\Component\DependencyInjection\ContainerInterface;
                use Humbug\Symfony\Component\DependencyInjection\Container;
                use Humbug\Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
                use Humbug\Symfony\Component\DependencyInjection\Exception\LogicException;
                use Humbug\Symfony\Component\DependencyInjection\Exception\RuntimeException;
                use Humbug\Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

                /*{$this->docStar}
                 * This class has been auto-generated
                 * by the Symfony Dependency Injection Component.
                 *
                 * @final since Symfony 3.3
                 */
                class $class extends $baseClass
                {
                    private \$parameters;
                    private \$targetDirs = array();

                    /*{$this->docStar}
                     * @internal but protected for BC on cache:clear
                     */
                    protected \$privates = array();

                    public function __construct()
                    {

                EOF;
                PHP,
        ];
    }
}


text:
#ifndef __PROX_H
#define __PROX_H

#include "misc/cppwrap.h"

struct operator_p_s;
extern const struct operator_p_s* prox_leastsquares_create(unsigned int N, const long dims[__VLA(N)], float lambda, const _Complex float* y);
extern const struct operator_p_s* prox_l2norm_create(unsigned int N, const long dims[__VLA(N)], float lambda);
extern const struct operator_p_s* prox_l2ball_create(unsigned int N, const long dims[__VLA(N)], float eps, const _Complex float* center);
extern const struct operator_p_s* prox_zero_create(unsigned int N, const long dims[__VLA(N)]);
extern const struct operator_p_s* prox_lesseq_create(unsigned int N, const long dims[__VLA(N)], const _Complex float* b);
extern const struct operator_p_s* prox_greq_create(unsigned int N, const long dims[__VLA(N)], const _Complex float* b);
extern const struct operator_p_s* prox_rvc_create(unsigned int N, const long dims[__VLA(N)]);
extern const struct operator_p_s* prox_nonneg_create(unsigned int N, const long dims[__VLA(N)]);
extern const struct operator_p_s* prox_zsmax_create(unsigned int N, const long dims[__VLA(N)], float a);

#include "misc/cppwrap.h"
#endif