text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>2003</year><year>2017</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>Errors and Error Handling</title>
    <prepared></prepared>
    <docno></docno>
    <date></date>
    <rev></rev>
    <file>errors.xml</file>

    <title>Terminology</title>

Errors can roughly be divided into four different types:

    <taglist>
      <tag>Compile-time errors</tag>
      <item>When the compiler fails to compile the program, for example a syntax error.</item>
      <tag>Logical errors</tag>
      <item>When a program does not behave as intended, but does not crash.
        An example is that nothing happens when a button in a graphical user
        interface is clicked.</item>
      <tag><marker id="run-time-errors"/>Run-time errors</tag>
      <item>When a crash occurs. An example is
        when an operator is applied to arguments of the wrong type.
        The Erlang programming language has built-in features for
        handling of run-time errors. A run-time error can also be
        emulated by calling <seemfa marker="erts:erlang#error/1">
        <c>error(Reason)</c></seemfa>. Run-time errors are exceptions of
        class <c>error</c>.</item>
      <tag><marker id="generated-errors"/>Generated errors</tag>
      <item>When the code itself calls <seemfa marker="erts:erlang#exit/1">
        <c>exit/1</c></seemfa> or <seemfa marker="erts:erlang#throw/1">
        <c>throw/1</c></seemfa>. Generated errors are exceptions of
        class <c>exit</c> or <c>throw</c>.</item>
    </taglist>

When an exception occurs in Erlang, execution of the process that
      evaluated the erroneous expression is stopped. This is referred to as a
      failure, that execution or evaluation fails, or that the
      process fails, terminates, or exits. Notice that
      a process can terminate/exit for other reasons than a failure.

A process that terminates emits an exit signal with
      an exit reason that describes why the process terminated.
      Normally, some information about any erroneous termination is printed
      to the terminal. See <seeguide marker="processes#term">
      Process Termination</seeguide> in the Processes chapter for more details
      on termination.

    <title>Exceptions</title>

Exceptions are <seeguide marker="#run-time-errors">run-time errors</seeguide> or
      <seeguide marker="#generated-errors">generated errors</seeguide> and
      are of three different classes, with different origins. The
      <seeguide marker="expressions#try">try</seeguide> expression
      can distinguish between the different classes, whereas the
      <seeguide marker="expressions#catch">catch</seeguide>
      expression cannot. <c>try</c> and <c>catch</c> are described in
      <seeguide marker="expressions">Expressions</seeguide>.

      <row>
        <cell align="left" valign="middle">Class</cell>
        <cell align="left" valign="middle">Origin</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>error</c></cell>
        <cell align="left" valign="middle">Run-time error,
        for example, <c>1+a</c>, or the process called
        <c>error/1,2</c></cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>exit</c></cell>
        <cell align="left" valign="middle">The process called <c>exit/1</c></cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>throw</c></cell>
        <cell align="left" valign="middle">The process called <c>throw/1</c></cell>
      </row>
      <tcaption>Exception Classes.</tcaption>

All of the above exceptions can also be generated by calling
      <seemfa marker="erts:erlang#raise/3"><c>erlang:raise/3</c></seemfa>.

An exception consists of its class, an exit reason
      (see <seeguide marker="#exit_reasons">Exit Reason</seeguide>),
      and a stack trace (which aids in finding the code location of
      the exception).

The stack trace can be bound to a variable from within a <c>try</c>
      expression for any exception class, or as part of the exit reason when
      a run-time error is caught by a <c>catch</c>. Example:

> <input>{'EXIT',{test,Stacktrace}} = (catch error(test)), Stacktrace.</input>
[{shell,apply_fun,3,[]},
 {erl_eval,do_apply,6,[]},
 ...]
> <input>try throw(test) catch Class:Reason:Stacktrace -> Stacktrace end.</input>
[{shell,apply_fun,3,[]},
 {erl_eval,do_apply,6,[]},
 ...]

	<marker id="stacktrace"></marker>
	<title>The call-stack back trace (stacktrace)</title>

The stack back-trace
          (<seetype marker="erts:erlang#stacktrace">stacktrace</seetype>)
          is a list contains <c>{Module, Function, Arity, ExtraInfo}</c>
          and/or <c>{Fun, Arity, ExtraInfo}</c> tuples. The field <c>Arity</c> in the
          tuple can be the argument list of that function call instead of an
          arity integer, depending on the exception.

<c>ExtraInfo</c> is a (possibly empty) list of two-element tuples
	  in any order that provides additional information about the exception.
	  The first element is an atom describing the type of
	  information in the second element. The following items can
	  occur:

	<taglist>
          <tag><c>error_info</c></tag>
          <item>The second element of the tuple is a map
	  providing additional information about what caused the
	  exception. This information can be created by calling
          <seemfa marker="erts:erlang#error/3"><c>error/3</c></seemfa>
          and is used by
          <seemfa marker="stdlib:erl_error#format_exception/4">
            <c>erl_error:format_exception/4</c></seemfa>.
          </item>
          <tag><c>file</c></tag>
          <item>The second element of the tuple is a string (list of
          characters) representing the filename of the source file
          of the function.
          </item>
          <tag><c>line</c></tag>
          <item>The second element of the tuple is the line number
          (an integer > 0) in the source file
          where the exception occurred or the function was called.
          </item>
	</taglist>
	<warning>
Developers should rely on stacktrace entries only for
	debugging purposes.

The VM performs tail call optimization, which
	does not add new entries to the stacktrace, and also limits stacktraces
	to a certain depth. Furthermore, compiler options, optimizations and
	future changes may add or remove stacktrace entries, causing any code
	that expects the stacktrace to be in a certain order or contain specific
	items to fail.

The only exception to this rule is the class <c>error</c> with the
	reason <c>undef</c> which is guaranteed to include the <c>Module</c>,
	<c>Function</c> and <c>Arity</c> of the attempted
	function as the first stacktrace entry.

	</warning>

    <title>Handling of Run-time Errors in Erlang</title>

      <title>Error Handling Within Processes</title>

It is possible to prevent run-time errors and other
        exceptions from causing the process to terminate by using <c>catch</c> or
        <c>try</c>, see <seeguide marker="expressions">
        Expressions</seeguide> about
        <seeguide marker="expressions#catch">catch</seeguide>
        and <seeguide marker="expressions#try">try</seeguide>.

      <title>Error Handling Between Processes</title>

Processes can monitor other processes and detect process
        terminations, see
        <seeguide marker="processes#errors">Processes</seeguide>.

    <marker id="exit_reasons"></marker>
    <title>Exit Reasons</title>

When a run-time error occurs, that is an exception of class <c>error</c>.
      The exit reason is a tuple <c>{Reason,Stack}</c>, where
      <c>Reason</c> is a term indicating the type of error:

      <row>
        <cell align="left" valign="middle">Reason</cell>
        <cell align="left" valign="middle">Type of Error</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>badarg</c></cell>
        <cell align="left" valign="middle">Bad argument. The argument is of wrong data type, or is otherwise badly formed.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>badarith</c></cell>
        <cell align="left" valign="middle">Bad argument in an arithmetic expression.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>{badmatch,V}</c></cell>
        <cell align="left" valign="middle">Evaluation of a match expression failed. The value <c>V</c> did not match.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>function_clause</c></cell>
        <cell align="left" valign="middle">No matching function clause is found when evaluating a function call.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>{case_clause,V}</c></cell>
        <cell align="left" valign="middle">No matching branch is found when evaluating a <c>case</c> expression. The value <c>V</c> did not match.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>if_clause</c></cell>
        <cell align="left" valign="middle">No true branch is found when evaluating an <c>if</c> expression.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>{try_clause,V}</c></cell>
        <cell align="left" valign="middle">No matching branch is found when evaluating the of-section of a <c>try</c> expression. The value <c>V</c> did not match.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>undef</c></cell>
        <cell align="left" valign="middle">The function cannot be found when evaluating a function call.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>{badfun,F}</c></cell>
        <cell align="left" valign="middle">Something is wrong with a fun <c>F</c>.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>{badarity,F}</c></cell>
        <cell align="left" valign="middle">A fun is applied to the wrong number of arguments. <c>F</c> describes the fun and the arguments.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>timeout_value</c></cell>
        <cell align="left" valign="middle">The timeout value in a <c>receive..after</c> expression is evaluated to something else than an integer or <c>infinity</c>.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>noproc</c></cell>
        <cell align="left" valign="middle">Trying to link or monitor to a non-existing process or port.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>noconnection</c></cell>
        <cell align="left" valign="middle">A link or monitor to a remote process was broken because a connection between the nodes could not be established or was severed.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>{nocatch,V}</c></cell>
        <cell align="left" valign="middle">Trying to evaluate a <c>throw </c>outside a <c>catch</c>. <c>V</c> is the thrown term.</cell>
      </row>
      <row>
        <cell align="left" valign="middle"><c>system_limit</c></cell>
        <cell align="left" valign="middle">A system limit has been reached.
        See <seeguide marker="system/efficiency_guide:advanced">
        Efficiency Guide</seeguide> for information about system limits.
        </cell>
      </row>
      <tcaption>Exit Reasons</tcaption>

<c>Stack</c> is the stack of function calls being evaluated
      when the error occurred, given as a list of tuples
      <c>{Module,Name,Arity,ExtraInfo}</c> with the most recent function call
      first. The most recent function call tuple can in some
      cases be <c>{Module,Name,[Arg],ExtraInfo}</c>.

</chapter>


text:
URL
===
URL parsing done reasonably.

[![Build Status](https://secure.travis-ci.org/seomoz/url-py.png)](http://travis-ci.org/seomoz/url-py)
![Status: Production](https://img.shields.io/badge/status-production-green.svg?style=flat)
![Team: Big Data](https://img.shields.io/badge/team-big_data-green.svg?style=flat)
![Scope: External](https://img.shields.io/badge/scope-external-green.svg?style=flat)
![Open Source: MIT](https://img.shields.io/badge/open_source-MIT-green.svg?style=flat)
![Critical: Yes](https://img.shields.io/badge/critical-yes-red.svg?style=flat)

Moz crawls. We crawl lots. In fact, you might say that crawling is our
business.

The internet's also a messy place. We've encountered some pretty crazy
implementations and servers and URLs and HTML. Over the course of this
discovery, we've found ourselves repeating certain URL sanitization tasks over
and over, so we've put them in a repo to share with the world.

At the heart of the `url` package is the `URL` object. You can get one by
passing in a unicode or string object into the top-level `parse` method. If the
string is encoded, you can provide that encoding (otherwise it's assumed to be
utf-8):

    import url

    # It knows about unicode
    myurl = url.parse(u'http://foo.com')

    # It knows about other encodings that Python supports
    myurl = url.parse(..., 'some encoding')

Internally, everything is stored as UTF-8 until you ask for a string back. The
workflow is that you'll chain a number of permutations together to get the type
of URL you're after, and then call a final method to give you a string.

    # Defrag, remove some parameters and give me a unicode string
    url.parse(...).defrag().deparam(['utm_source']).unicode()

    # Escape the path, and punycode the host, and give me a UTF-8 string
    url.parse(...).escape().punycode().utf8

    # Give me the absolute path url as some encoding
    url.parse(...).abspath().encode('some encoding')

URL Equivalence
===============
URL objects compared with `==` are interpreted very strictly, but for a more
lax interpretation, consider using `equiv` to test if two urls are functionally
equivalent:

    a = url.parse('https://föo.com:443/a/../b/.?b=2&&&&&&a=1')
    b = url.parse('https://xn--fo-fka.COM/b/?a=1&b=2')

    # These urls are not equal
    assert(a != b)
    # But they are equivalent
    assert(a.equiv(b))
    assert(b.equiv(a))

This equivalence test takes default ports for common schemes into account (so
if both urls are the same scheme, but one explicitly specifies the default
port), punycoding, case of the host name, and parameter order.

Absolute URLs
=============
You can perform many operations on relative urls (those without a hostname),
but punycoding and unpunycoding are not among them. You can also tell whether
or not a url is absolute:

    a = url.parse('foo/bar.html')
    assert(not a.absolute())

Chaining
========
Many of the methods on the `URL` class can be chained to produce a number of
effects in sequence:

    import url

    # Create a url object
    myurl = url.URL.parse('http://www.FOO.com/bar?utm_source=foo#what')
    # Remove some parameters and the fragment, spit out utf-8
    print myurl.defrag().deparam(['utm_source']).utf8

In fact, unless the function explicitly returns a string, then the method may
be chained:

`strip`
-------
Removes semantically meaningless excess '?', '&', and ';' characters from query and
params:

    >>> url.parse('http://example.com/????query=param&&&&foo=bar').strip().utf8
    'http://example.com/?query=param&foo=bar'

`canonical`
-----------
According to the RFC, the order of parameters is not supposed to matter. In
practice, it can (depending on how the server matches URL routes), but it's
also helpful to be able to put parameters in a canonical ordering. This
ordering happens to be alphabetical order:

    >>> url.parse('http://foo.com/?b=2&a=1&d=3').canonical().utf8
    'http://foo.com/?a=1&b=2&d=3'

`defrag`
--------
Remove any fragment identifier from the url. This isn't part of the reuqest
that gets sent to an HTTP server, and so it's often useful to remove the
fragment when doing url comparisons.

    >>> url.parse('http://foo.com/#foo').defrag().utf8
    'http://foo.com/'

`deparam`
---------
Some parameters are commonly added to urls that we may not be interested in. Or
they may be misleading. Common examples include referrering pages, `utm_source`
and session ids. To strip out all such parameters from your url:

    >>> url.parse('http://foo.com/?do=1&not=2&want=3&this=4').deparam(['do', 'not', 'want']).utf8
    'http://foo.com/?this=4'

`abspath`
---------
Like its `os.path` namesake, this makes sure that the path of the url is
absolute. This includes removing redundant forward slashes, `.` and `..`.

    >>> url.parse('http://foo.com/foo/./bar/../a/b/c/../../d').abspath().utf8
    'http://foo.com/foo/a/d'

`escape`
--------
Non-ASCII characters in the path are typically encoded as UTF-8 and then
escaped as `%HH` where `H` are hexidecimal values. It's important to note that
the `escape` function is idempotent, and can be called repeatedly

    >>> url.parse(u'http://foo.com/ümlaut').escape().utf8
    'http://foo.com/%C3%BCmlaut'
    >>> url.parse(u'http://foo.com/ümlaut').escape().escape().utf8
    'http://foo.com/%C3%BCmlaut'

`unescape`
----------
If you have a URL that might have been escaped before it was given to you, but
you'd like to display something a little more meaningful than `%C3%BCmlaut`,
you can unescape the path:

    >>> print url.parse('http://foo.com/%C3%BCmlaut').unescape().unicode()
    http://foo.com/ümlaut

`relative`
----------
Evaluate a relative path given a base url:

    >>> url.parse('http://foo.com/a/b/c').relative('../foo').utf8
    'http://foo.com/a/foo'

`punycode`
----------
For non-ASCII hostnames, they must be punycoded before a DNS request is made
for them. To this end, there's the punycode function:

    >>> url.parse('http://ümlaut.com').punycode().utf8
    'http://xn--mlaut-jva.com/'

`unpunycode`
------------
If a url may have been punycoded before it's been handed to you, and you'd like
to be able to display something nicer than `http://xn--mlaut-jva.com/`:

    >>> print url.parse('http://xn--mlaut-jva.com/').unpunycode().utf8
    http://ümlaut.com/

Other Functions
===============
Not all functions are chainable -- some return a value other than a `URL` object:

- `encode(...)` -- return a version of the url in an arbitrary encoding

Public Suffix List
==================
This library comes bundled with a version of the public suffix list. However, it may not
suit your needs (whether you need to stay pinned to an old list, or need to update to a
new list). As such, you can provide the PSL you'd like to use, as a `UTF-8` string:

```python
import url

# Read it from a file
with open('path/to/my/psl') as fin:
    url.set_psl(fin.read())

# Grab it from the PSL site
import requests
url.set_psl(requests.get('https://publicsuffix.org/list/public_suffix_list.dat').content)
```

Properties
==========
Many attributes are available on URL objects:

- `scheme` -- empty string if URL is relative
- `host` -- `None` if URL is relative
- `hostname` -- like `host`, but empty string if URL is relative
- `pld` -- the [pay-level domain](https://moz.com/blog/what-the-heck-should-we-call-domaincom),
    or an empty string if URL is relative
- `tld` -- the [top-level domain](https://en.wikipedia.org/wiki/Top-level_domain),
    or an empty string if URL is relative
- `port` -- `None` if absent (or removed)
- `path` -- always with a leading `/`
- `params` -- string of params following the `;` (with extra `;`'s removed)
- `query` -- string of queries following the `?` (with extra `?`'s and `&`'s removed)
- `fragment` -- empty string if absent
- `absolute` -- a `bool` indicating whether the URL is absolute
- `unicode` -- a unicode version of the URL
- `utf8` -- a utf-8 verison of the URL

Contentious Issues
==================
Some questions that I still have outstanding:

Strip ?'s From Query Names?
---------------------------
If I have a query string `?a=1&?b=2`, and I sanitize the params, should the
resulting query string be `?a=1&?b=2` or `?a=1&b=2` (note the missing `?`
before the `b` in the second version).

If not in the above example, what about in `?????a=1`? Should the resulting
query string be a mere `?a=1`?

Properties
----------
I'd like to support lazily-evaluated properties like `hostname`, `netloc`, etc.

Dictionary Access
-----------------
I'd like to support dictionary-style access to parameters and query arguments,
though I'm not sure how to best to do it. My current thinking is that there will
be one way of getting params, one for queries, and then one for either.

Authors
=======
This represents code samples, unit tests and functions from Mozzers,
including:

- David Barts
- Brandon Forehand
- Dan Lecocq

redpajama_set_name: RedPajamaGithub


text:
package edu.uci.ics.asterix.runtime.aggregates.std;

import java.io.IOException;

import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
import edu.uci.ics.asterix.om.base.ANull;
import edu.uci.ics.asterix.om.types.ATypeTag;
import edu.uci.ics.asterix.om.types.BuiltinType;
import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;
import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider;

public class SqlSumAggregateFunction extends AbstractSumAggregateFunction {
    private final boolean isLocalAgg;

    public SqlSumAggregateFunction(ICopyEvaluatorFactory[] args, IDataOutputProvider provider, boolean isLocalAgg)
            throws AlgebricksException {
        super(args, provider);
        this.isLocalAgg = isLocalAgg;
    }

    @Override
    protected void processNull() {
    }

    @Override
    protected void processSystemNull() throws AlgebricksException {
        // For global aggregates simply ignore system null here,
        // but if all input value are system null, then we should return
        // null in finish().
        if (isLocalAgg) {
            throw new AlgebricksException("Type SYSTEM_NULL encountered in local aggregate.");
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void finishSystemNull() throws IOException {
        // Empty stream. For local agg return system null. For global agg return null.
        if (isLocalAgg) {
            out.writeByte(ATypeTag.SYSTEM_NULL.serialize());
        } else {
            serde = AqlSerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ANULL);
            serde.serialize(ANull.NULL, out);
        }
    }
}


text:
package com.asakusafw.compiler.operator.model;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Writable;

import com.asakusafw.runtime.model.DataModel;
import com.asakusafw.runtime.model.DataModelKind;
import com.asakusafw.runtime.model.PropertyOrder;
import com.asakusafw.runtime.value.IntOption;
import com.asakusafw.vocabulary.model.Joined;
import com.asakusafw.vocabulary.model.Key;
/**
 * A data model class that represents mock_joined.
 */
@DataModelKind("DMDL")@Joined(terms = {@Joined.Term(source = MockHoge.class, mappings = {@Joined.Mapping(source =
                "value", destination = "hogeValue")}, shuffle = @Key(group = {"value"})),@Joined.Term(source = MockFoo.
            class, mappings = {@Joined.Mapping(source = "value", destination = "fooValue")}, shuffle = @Key(group = {
                "value"}))})@PropertyOrder({"hoge_value", "foo_value"}) public class MockJoined implements DataModel<
        MockJoined>, Writable {
    private final IntOption hogeValue = new IntOption();
    private final IntOption fooValue = new IntOption();
    @Override@SuppressWarnings("deprecation") public void reset() {
        this.hogeValue.setNull();
        this.fooValue.setNull();
    }
    @Override@SuppressWarnings("deprecation") public void copyFrom(MockJoined other) {
        this.hogeValue.copyFrom(other.hogeValue);
        this.fooValue.copyFrom(other.fooValue);
    }
    /**
     * Returns hoge_value.
     * @return hoge_value
     * @throws NullPointerException if hoge_value is null
     */
    public int getHogeValue() {
        return this.hogeValue.get();
    }
    /**
     * Sets hoge_value.
     * @param value the value
     */
    @SuppressWarnings("deprecation") public void setHogeValue(int value) {
        this.hogeValue.modify(value);
    }
    /**
     * Returns hoge_value which may be represent null.
     * @return hoge_value
     */
    public IntOption getHogeValueOption() {
        return this.hogeValue;
    }
    /**
     * Sets hoge_value.
     * @param option the value, or null to set this property to null
     */
    @SuppressWarnings("deprecation") public void setHogeValueOption(IntOption option) {
        this.hogeValue.copyFrom(option);
    }
    /**
     * Returns foo_value.
     * @return foo_value
     * @throws NullPointerException if foo_value is null
     */
    public int getFooValue() {
        return this.fooValue.get();
    }
    /**
     * Sets foo_value.
     * @param value the value
     */
    @SuppressWarnings("deprecation") public void setFooValue(int value) {
        this.fooValue.modify(value);
    }
    /**
     * Returns foo_value which may be represent null.
     * @return foo_value
     */
    public IntOption getFooValueOption() {
        return this.fooValue;
    }
    /**
     * Sets foo_value.
     * @param option the value, or null to set this property to null
     */
    @SuppressWarnings("deprecation") public void setFooValueOption(IntOption option) {
        this.fooValue.copyFrom(option);
    }
    @Override public String toString() {
        StringBuilder result = new StringBuilder();
        result.append("{");
        result.append("class=mock_joined");
        result.append(", hogeValue=");
        result.append(this.hogeValue);
        result.append(", fooValue=");
        result.append(this.fooValue);
        result.append("}");
        return result.toString();
    }
    @Override public int hashCode() {
        int prime = 31;
        int result = 1;
        result = prime * result + hogeValue.hashCode();
        result = prime * result + fooValue.hashCode();
        return result;
    }
    @Override public boolean equals(Object obj) {
        if(this == obj) {
            return true;
        }
        if(obj == null) {
            return false;
        }
        if(this.getClass() != obj.getClass()) {
            return false;
        }
        MockJoined other = (MockJoined) obj;
        if(this.hogeValue.equals(other.hogeValue) == false) {
            return false;
        }
        if(this.fooValue.equals(other.fooValue) == false) {
            return false;
        }
        return true;
    }
    @Override public void write(DataOutput out) throws IOException {
        hogeValue.write(out);
        fooValue.write(out);
    }
    @Override public void readFields(DataInput in) throws IOException {
        hogeValue.readFields(in);
        fooValue.readFields(in);
    }
}


text:
path=`pwd`
wget https://raw.githubusercontent.com/xiongziliang/ZLToolKit/master/build_for_linux.sh -O ./toolkit_build.sh
sudo chmod +x ./toolkit_build.sh
./toolkit_build.sh
sudo apt-get install libx264-dev
sudo apt-get install libfaac-dev
sudo apt-get install libmp4v2-dev
#sudo apt-get install libsdl-dev
#sudo apt-get install libavcodec-dev
#sudo apt-get install libavutil-dev
cd $path
cd ..
git clone --depth=50 https://github.com/xiongziliang/ZLMediaKit.git
cd ZLMediaKit
mkdir -p linux_build
cd linux_build
cmake ..
make -j4
sudo make install


text:
using System;
using System.Globalization;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using AnglicanGeek.MarkdownMailer;
using Elmah;
using NuGetGallery.Authentication;
using NuGetGallery.Configuration;

namespace NuGetGallery
{
    public class MessageService : IMessageService
    {
        public IMailSender MailSender { get; protected set; }
        public IAppConfiguration Config { get; protected set; }
        public AuthenticationService AuthService { get; protected set; }

        protected MessageService() { }

        public MessageService(IMailSender mailSender, IAppConfiguration config, AuthenticationService authService) :this()
        {
            MailSender = mailSender;
            Config = config;
            AuthService = authService;
        }

        public void ReportAbuse(ReportPackageRequest request)
        {
            string subject = "[{GalleryOwnerName}] Support Request for '{Id}' version {Version} (Reason: {Reason})";
            subject = request.FillIn(subject, Config);

            const string bodyTemplateUnauthenticated = @"
**Email:** {Name} ({Address})

**Package:** {Id}
{PackageUrl}

**Version:** {Version}
{VersionUrl}

**Owners:**
{OwnerList}

**Reason:**
{Reason}

**Has the package owner been contacted?:**
{AlreadyContactedOwners}

**Message:**
{Message}
";

            const string bodyTemplateAuthenticated = @"
**Email:** {Name} ({Address})

**Package:** {Id}
{PackageUrl}

**Version:** {Version}
{VersionUrl}

**Owners:**
{OwnerList}

**User:** {Username} ({UserAddress})
{UserUrl}

**Reason:**
{Reason}

**Has the package owner been contacted?:**
{AlreadyContactedOwners}

**Message:**
{Message}
";

            string bodyTemplate = request.RequestingUser != null ?
                bodyTemplateAuthenticated :
                bodyTemplateUnauthenticated;

            var body = new StringBuilder("");
            body.Append(request.FillIn(bodyTemplate, Config));
            body.AppendFormat(CultureInfo.InvariantCulture, @"

*Message sent from {0}*", Config.GalleryOwner.DisplayName);

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body.ToString();
                mailMessage.From = Config.GalleryOwner;
                mailMessage.ReplyToList.Add(request.FromAddress);
                mailMessage.To.Add(mailMessage.From);
                SendMessage(mailMessage);
            }
        }

        public void ReportMyPackage(ReportPackageRequest request)
        {
            string subject = "[{GalleryOwnerName}] Owner Support Request for '{Id}' version {Version} (Reason: {Reason})";
            subject = request.FillIn(subject, Config);

            const string bodyTemplate = @"
**Email:** {Name} ({Address})

**Package:** {Id}
{PackageUrl}

**Version:** {Version}
{VersionUrl}

**Owners:**
{OwnerList}

**User:** {Username} ({UserAddress})
{UserUrl}

**Reason:**
{Reason}

**Message:**
{Message}
";

            var body = new StringBuilder();
            body.Append(request.FillIn(bodyTemplate, Config));
            body.AppendFormat(CultureInfo.InvariantCulture, @"

*Message sent from {0}*", Config.GalleryOwner.DisplayName);

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body.ToString();
                mailMessage.From = Config.GalleryOwner;
                mailMessage.ReplyToList.Add(request.FromAddress);
                mailMessage.To.Add(Config.GalleryOwner);
                SendMessage(mailMessage);
            }
        }

        public void SendContactOwnersMessage(MailAddress fromAddress, PackageRegistration packageRegistration, string message, string emailSettingsUrl)
        {
            string subject = "[{0}] Message for owners of the package '{1}'";
            string body = @"_User {0} <{1}> sends the following message to the owners of Package '{2}'._

{3}

-----------------------------------------------
<em style=""font-size: 0.8em;"">
    To stop receiving contact emails as an owner of this package, sign in to the {4} and
    [change your email notification settings]({5}).
</em>";

            body = String.Format(
                CultureInfo.CurrentCulture,
                body,
                fromAddress.DisplayName,
                fromAddress.Address,
                packageRegistration.Id,
                message,
                Config.GalleryOwner.DisplayName,
                emailSettingsUrl);

            subject = String.Format(CultureInfo.CurrentCulture, subject, Config.GalleryOwner.DisplayName, packageRegistration.Id);

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;
                mailMessage.ReplyToList.Add(fromAddress);

                AddOwnersToMailMessage(packageRegistration, mailMessage);
                if (mailMessage.To.Any())
                {
                    SendMessage(mailMessage);
                }
            }
        }

        public void SendNewAccountEmail(MailAddress toAddress, string confirmationUrl)
        {
            string body = @"Thank you for registering with the {0}.
We can't wait to see what packages you'll upload.

So we can be sure to contact you, please verify your email address and click the following link:

[{1}]({2})

Thanks,
The {0} Team";

            body = String.Format(
                CultureInfo.CurrentCulture,
                body,
                Config.GalleryOwner.DisplayName,
                HttpUtility.UrlDecode(confirmationUrl),
                confirmationUrl);

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = String.Format(CultureInfo.CurrentCulture, "[{0}] Please verify your account.", Config.GalleryOwner.DisplayName);
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;

                mailMessage.To.Add(toAddress);
                SendMessage(mailMessage);
            }
        }

        public void SendEmailChangeConfirmationNotice(MailAddress newEmailAddress, string confirmationUrl)
        {
            string body = @"You recently changed your {0} email address.

To verify your new email address, please click the following link:

[{1}]({2})

Thanks,
The {0} Team";

            body = String.Format(
                CultureInfo.CurrentCulture,
                body,
                Config.GalleryOwner.DisplayName,
                HttpUtility.UrlDecode(confirmationUrl),
                confirmationUrl);

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = String.Format(
                    CultureInfo.CurrentCulture, "[{0}] Please verify your new email address.", Config.GalleryOwner.DisplayName);
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;

                mailMessage.To.Add(newEmailAddress);
                SendMessage(mailMessage);
            }
        }

        public void SendEmailChangeNoticeToPreviousEmailAddress(User user, string oldEmailAddress)
        {
            string body = @"Hi there,

The email address associated to your {0} account was recently
changed from _{1}_ to _{2}_.

Thanks,
The {0} Team";

            body = String.Format(
                CultureInfo.CurrentCulture,
                body,
                Config.GalleryOwner.DisplayName,
                oldEmailAddress,
                user.EmailAddress);

            string subject = String.Format(CultureInfo.CurrentCulture, "[{0}] Recent changes to your account.", Config.GalleryOwner.DisplayName);
            using (
                var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;

                mailMessage.To.Add(new MailAddress(oldEmailAddress, user.Username));
                SendMessage(mailMessage);
            }
        }

        public void SendPasswordResetInstructions(User user, string resetPasswordUrl, bool forgotPassword)
        {
            string body = String.Format(
                CultureInfo.CurrentCulture,
                forgotPassword ? Strings.Emails_ForgotPassword_Body : Strings.Emails_SetPassword_Body,
                Constants.DefaultPasswordResetTokenExpirationHours,
                resetPasswordUrl,
                Config.GalleryOwner.DisplayName);

            string subject = String.Format(CultureInfo.CurrentCulture, forgotPassword ? Strings.Emails_ForgotPassword_Subject : Strings.Emails_SetPassword_Subject, Config.GalleryOwner.DisplayName);
            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;

                mailMessage.To.Add(user.ToMailAddress());
                SendMessage(mailMessage);
            }
        }

        public void SendPackageOwnerRequest(User fromUser, User toUser, PackageRegistration package, string confirmationUrl)
        {
            if (!toUser.EmailAllowed)
            {
                return;
            }

            const string subject = "[{0}] The user '{1}' wants to add you as an owner of the package '{2}'.";

            string body = @"The user '{0}' wants to add you as an owner of the package '{1}'.
If you do not want to be listed as an owner of this package, simply delete this email.

To accept this request and become a listed owner of the package, click the following URL:

[{2}]({2})

Thanks,
The {3} Team";

            body = String.Format(CultureInfo.CurrentCulture, body, fromUser.Username, package.Id, confirmationUrl, Config.GalleryOwner.DisplayName);

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = String.Format(CultureInfo.CurrentCulture, subject, Config.GalleryOwner.DisplayName, fromUser.Username, package.Id);
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;
                mailMessage.ReplyToList.Add(fromUser.ToMailAddress());

                mailMessage.To.Add(toUser.ToMailAddress());
                SendMessage(mailMessage);
            }
        }

        public void SendCredentialRemovedNotice(User user, Credential removed)
        {
            SendCredentialChangeNotice(
                user,
                removed,
                Strings.Emails_CredentialRemoved_Body,
                Strings.Emails_CredentialRemoved_Subject);
        }

        public void SendCredentialAddedNotice(User user, Credential added)
        {
            SendCredentialChangeNotice(
                user,
                added,
                Strings.Emails_CredentialAdded_Body,
                Strings.Emails_CredentialAdded_Subject);
        }

        private void SendCredentialChangeNotice(User user, Credential changed, string bodyTemplate, string subjectTemplate)
        {
            // What kind of credential is this?
            var credViewModel = AuthService.DescribeCredential(changed);
            string name = credViewModel.AuthUI == null ? credViewModel.TypeCaption : credViewModel.AuthUI.AccountNoun;

            string body = String.Format(
                CultureInfo.CurrentCulture,
                bodyTemplate,
                name);
            string subject = String.Format(
                CultureInfo.CurrentCulture,
                subjectTemplate,
                Config.GalleryOwner.DisplayName,
                name);
            SendSupportMessage(user, body, subject);
        }

        private void SendSupportMessage(User user, string body, string subject)
        {
            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.From = Config.GalleryOwner;

                mailMessage.To.Add(user.ToMailAddress());
                SendMessage(mailMessage);
            }
        }

        private void SendMessage(MailMessage mailMessage)
        {
            try
            {
                MailSender.Send(mailMessage);
            }
            catch (SmtpException ex)
            {
                // Log but swallow the exception
                ErrorSignal.FromCurrentContext().Raise(ex);
            }
        }

        private static void AddOwnersToMailMessage(PackageRegistration packageRegistration, MailMessage mailMessage)
        {
            foreach (var owner in packageRegistration.Owners.Where(o => o.EmailAllowed))
            {
                mailMessage.To.Add(owner.ToMailAddress());
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <committees>
      <billCommittees>
        <item>
          <type>Standing</type>
          <activities>
            <item>
              <name>Referred to</name>
              <date>2017-05-04T13:02:40Z</date>
            </item>
          </activities>
          <chamber>House</chamber>
          <subcommittees>
            <item>
              <activities>
                <item>
                  <name>Referred to</name>
                  <date>2017-05-05T20:23:05Z</date>
                </item>
              </activities>
              <name>Energy and Power Subcommittee</name>
              <systemCode>hsif03</systemCode>
            </item>
          </subcommittees>
          <name>Energy and Commerce Committee</name>
          <systemCode>hsif00</systemCode>
        </item>
      </billCommittees>
    </committees>
    <notes />
    <titles>
      <item>
        <chamberName />
        <parentTitleType />
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <title>Energy Savings and Building Efficiency Act of 2017</title>
        <chamberCode />
      </item>
      <item>
        <chamberName />
        <parentTitleType />
        <titleType>Short Titles as Introduced</titleType>
        <title>Energy Savings and Building Efficiency Act of 2017</title>
        <chamberCode />
      </item>
      <item>
        <chamberName />
        <parentTitleType />
        <titleType>Official Title as Introduced</titleType>
        <title>To promote energy savings in residential and commercial buildings and industry, and for other purposes.</title>
        <chamberCode />
      </item>
      <item>
        <chamberName />
        <parentTitleType />
        <titleType>Display Title</titleType>
        <title>Energy Savings and Building Efficiency Act of 2017</title>
        <chamberCode />
      </item>
    </titles>
    <billNumber>2361</billNumber>
    <version>1.0.0</version>
    <calendarNumbers />
    <sponsors>
      <item>
        <party>R</party>
        <bioguideId>B001243</bioguideId>
        <middleName />
        <state>TN</state>
        <identifiers>
          <bioguideId>B001243</bioguideId>
          <lisID>1748</lisID>
          <gpoId>8154</gpoId>
        </identifiers>
        <district>7</district>
        <byRequestType />
        <firstName>Marsha</firstName>
        <fullName>Rep. Blackburn, Marsha [R-TN-7]</fullName>
        <lastName>Blackburn</lastName>
      </item>
    </sponsors>
    <title>Energy Savings and Building Efficiency Act of 2017</title>
    <laws />
    <actions>
      <actionTypeCounts>
        <placeholderTextForH>1</placeholderTextForH>
        <billReferrals>1</billReferrals>
        <introducedInHouse>1</introducedInHouse>
        <introducedInTheHouse>1</introducedInTheHouse>
      </actionTypeCounts>
      <item>
        <actionDate>2017-05-05</actionDate>
        <committee>
          <systemCode>hsif03</systemCode>
          <name>Energy and Power Subcommittee</name>
        </committee>
        <links />
        <sourceSystem>
          1
          <name>House committee actions</name>
        </sourceSystem>
        <text>Referred to the Subcommittee on Energy.</text>
        <type>Committee</type>
      </item>
      <item>
        <sourceSystem>
          2
          <name>House floor actions</name>
        </sourceSystem>
        <actionDate>2017-05-04</actionDate>
        <type>IntroReferral</type>
        <text>Referred to the House Committee on Energy and Commerce.</text>
        <committee>
          <systemCode>hsif00</systemCode>
          <name>Energy and Commerce Committee</name>
        </committee>
        <actionCode>H11100</actionCode>
        <links />
      </item>
      <item>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionDate>2017-05-04</actionDate>
        <type>IntroReferral</type>
        <text>Introduced in House</text>
        <committee />
        <actionCode>Intro-H</actionCode>
        <links />
      </item>
      <item>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionDate>2017-05-04</actionDate>
        <type>IntroReferral</type>
        <text>Introduced in House</text>
        <committee />
        <actionCode>1000</actionCode>
        <links />
      </item>
      <actionByCounts>
        <houseOfRepresentatives>4</houseOfRepresentatives>
      </actionByCounts>
    </actions>
    <introducedDate>2017-05-04</introducedDate>
    <relatedBills />
    <billType>HR</billType>
    <cboCostEstimates />
    <originChamber>House</originChamber>
    <cosponsors>
      <item>
        <lastName>Schrader</lastName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>S001180</bioguideId>
        <middleName />
        <sponsorshipDate>2017-05-04</sponsorshipDate>
        <state>OR</state>
        <identifiers>
          <bioguideId>S001180</bioguideId>
          <lisID>1950</lisID>
          <gpoId>8118</gpoId>
        </identifiers>
        <firstName>Kurt</firstName>
        <fullName>Rep. Schrader, Kurt [D-OR-5]</fullName>
        <district>5</district>
        <party>D</party>
        <sponsorshipWithdrawnDate />
      </item>
    </cosponsors>
    <congress>115</congress>
    <recordedVotes />
    <updateDate>2017-09-11T02:46:30Z</updateDate>
    <latestAction>
      <text>Referred to the Subcommittee on Energy.</text>
      <links />
      <actionDate>2017-05-05</actionDate>
    </latestAction>
    <summaries>
      <billSummaries />
    </summaries>
    <createDate>2017-05-05T03:11:54Z</createDate>
    <committeeReports />
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Mrs. BLACKBURN:H.R. 2361.Congress has the power to enact this legislation pursuantto the following:Article I, Section 8, Clause 18: The Necessary and ProperClause[Page H4179]
]]></constitutionalAuthorityStatementText>
    <policyArea>
      <name>Energy</name>
    </policyArea>
    <amendments />
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Building construction</name>
          </item>
          <item>
            <name>Congressional oversight</name>
          </item>
          <item>
            <name>Education programs funding</name>
          </item>
          <item>
            <name>Employment and training programs</name>
          </item>
          <item>
            <name>Energy efficiency and conservation</name>
          </item>
          <item>
            <name>Environmental technology</name>
          </item>
          <item>
            <name>Federal-Indian relations</name>
          </item>
          <item>
            <name>Government studies and investigations</name>
          </item>
          <item>
            <name>Higher education</name>
          </item>
          <item>
            <name>Housing industry and standards</name>
          </item>
          <item>
            <name>Industrial facilities</name>
          </item>
          <item>
            <name>Lighting and heating</name>
          </item>
          <item>
            <name>State and local government operations</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Energy</name>
        </policyArea>
      </billSubjects>
    </subjects>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
"""Tests for symbolic.xc_functionals."""

import copy
from unittest import mock

from absl.testing import absltest
from absl.testing import parameterized
import jax
import numpy as np

from symbolic_functionals.syfes.symbolic import enhancement_factors
from symbolic_functionals.syfes.symbolic import evaluators
from symbolic_functionals.syfes.symbolic import xc_functionals
from symbolic_functionals.syfes.xc import gga
from symbolic_functionals.syfes.xc import lda
from symbolic_functionals.syfes.xc import mgga
from symbolic_functionals.syfes.xc import xc

jax.config.update('jax_enable_x64', True)

def _get_expected_e_xc_unpolarized(rho_and_derivs, xc_name):
  """Gets expected XC energy density from unpolarized rho and derivatives."""
  rho, grad_x, grad_y, grad_z, _, tau = rho_and_derivs
  sigma = grad_x ** 2 + grad_y ** 2 + grad_z ** 2
  if xc_name == 'B97':
    return (gga.e_x_b97_unpolarized(rho, sigma)
            + gga.e_c_b97_unpolarized(rho, sigma))
  elif xc_name == 'wB97M-V':
    return mgga.e_xc_wb97mv_unpolarized(rho, sigma, tau)
  else:
    raise ValueError

def _get_expected_e_xc_polarized(rho_and_derivs, xc_name):
  """Gets expected XC energy density from spin polarized rho and derivatives."""
  rho_a, grad_x_a, grad_y_a, grad_z_a, _, tau_a = rho_and_derivs[0]
  rho_b, grad_x_b, grad_y_b, grad_z_b, _, tau_b = rho_and_derivs[1]
  sigma_aa = grad_x_a ** 2 + grad_y_a ** 2 + grad_z_a ** 2
  sigma_ab = grad_x_a * grad_x_b + grad_y_a * grad_y_b + grad_z_a * grad_z_b
  sigma_bb = grad_x_b ** 2 + grad_y_b ** 2 + grad_z_b ** 2
  if xc_name == 'B97':
    return (gga.e_x_b97_polarized(rho_a, rho_b, sigma_aa, sigma_ab, sigma_bb)
            + gga.e_c_b97_polarized(rho_a, rho_b, sigma_aa, sigma_ab, sigma_bb))
  elif xc_name == 'wB97M-V':
    return mgga.e_xc_wb97mv_polarized(
        rho_a, rho_b, sigma_aa, sigma_ab, sigma_bb, tau_a, tau_b)
  else:
    raise ValueError

class XCFunctionalTest(parameterized.TestCase):

  @parameterized.parameters(False, True)
  def test_eval_exc_with_b97_u(self, use_jax):
    rho_and_derivs = np.random.rand(6, 5)

    quantities, lda_energies = evaluators.parse_rho_and_derivs(
        0.5 * rho_and_derivs, omega=0., polarized=False)  # 0.5: spin factor
    parameters = copy.deepcopy(xc_functionals.B97_PARAMETERS)
    u_x = gga.u_b97(
        np.sqrt(quantities['x2']),
        gamma=parameters['parameters_x'].pop('gamma'),
        polarized=True)
    u_css = gga.u_b97(
        np.sqrt(quantities['x2']),
        gamma=parameters['parameters_css'].pop('gamma'),
        polarized=True)
    u_cos = gga.u_b97(
        np.sqrt(quantities['x2']),
        gamma=parameters['parameters_cos'].pop('gamma'),
        polarized=True)

    e_xc = xc_functionals.b97_u.eval_exc(
        **parameters,
        e_lda_x=lda_energies['x'],
        e_lda_css=lda_energies['css'],
        e_lda_cos=lda_energies['cos'],
        features_x={'u': u_x},
        features_css={'u': u_css},
        features_cos={'u': u_cos},
        use_jax=use_jax
    )

    np.testing.assert_allclose(
        e_xc, _get_expected_e_xc_unpolarized(rho_and_derivs, xc_name='B97'))

  @parameterized.parameters(
      (xc_functionals.b97_x2, xc_functionals.B97_PARAMETERS, False),
      (xc_functionals.b97_x2, xc_functionals.B97_PARAMETERS, True),
      (xc_functionals.b97_x2_short,
       xc_functionals.B97_PARAMETERS_UTRANSFORM,
       False),
      (xc_functionals.b97_x2_short,
       xc_functionals.B97_PARAMETERS_UTRANSFORM,
       True),
      )
  def test_eval_exc_with_b97_x2_unpolarized(self, b97_x2, parameters, use_jax):
    rho_and_derivs = np.random.rand(6, 5)
    quantities, lda_energies = evaluators.parse_rho_and_derivs(
        0.5 * rho_and_derivs, omega=0., polarized=False)  # 0.5: spin factor

    e_xc = b97_x2.eval_exc(
        **parameters,
        e_lda_x=lda_energies['x'],
        e_lda_css=lda_energies['css'],
        e_lda_cos=lda_energies['cos'],
        features={'x2': quantities['x2']},
        use_jax=use_jax
    )

    np.testing.assert_allclose(
        e_xc, _get_expected_e_xc_unpolarized(rho_and_derivs, xc_name='B97'))

  @parameterized.parameters(
      (xc_functionals.b97_x2, xc_functionals.B97_PARAMETERS, False),
      (xc_functionals.b97_x2, xc_functionals.B97_PARAMETERS, True),
      (xc_functionals.b97_x2_short,
       xc_functionals.B97_PARAMETERS_UTRANSFORM,
       False),
      (xc_functionals.b97_x2_short,
       xc_functionals.B97_PARAMETERS_UTRANSFORM,
       True),
      )
  def test_eval_exc_with_b97_x2_polarized(self, b97_x2, parameters, use_jax):
    rho_and_derivs = np.random.rand(2, 6, 5)
    quantities, lda_energies = evaluators.parse_rho_and_derivs(
        rho_and_derivs, omega=0., polarized=True)

    e_xc = np.sum(b97_x2.eval_exc(
        **parameters,
        e_lda_x=lda_energies['x'],
        e_lda_css=lda_energies['css'],
        e_lda_cos=lda_energies['cos'],
        features={'x2': quantities['x2']},
        use_jax=use_jax
    ).reshape(-1, 3), axis=1)

    np.testing.assert_allclose(
        e_xc, _get_expected_e_xc_polarized(rho_and_derivs, xc_name='B97'))

  @parameterized.parameters(
      (xc_functionals.wb97mv, xc_functionals.WB97MV_PARAMETERS),
      (xc_functionals.wb97mv_short, xc_functionals.WB97MV_PARAMETERS_UTRANSFORM)
      )
  def test_eval_exc_with_wb97mv_unpolarized(self, wb97mv_form, parameters):
    rho_and_derivs = np.random.rand(6, 5)
    quantities, lda_energies = evaluators.parse_rho_and_derivs(
        0.5 * rho_and_derivs, omega=0.3, polarized=False)  # 0.5: spin factor

    e_xc = wb97mv_form.eval_exc(
        **parameters,
        e_lda_x=lda_energies['x'],
        e_lda_css=lda_energies['css'],
        e_lda_cos=lda_energies['cos'],
        features={'w': quantities['w'], 'x2': quantities['x2']},
    )

    np.testing.assert_allclose(
        e_xc, _get_expected_e_xc_unpolarized(rho_and_derivs, xc_name='wB97M-V'))

  @parameterized.parameters(
      (xc_functionals.wb97mv, xc_functionals.WB97MV_PARAMETERS),
      (xc_functionals.wb97mv_short, xc_functionals.WB97MV_PARAMETERS_UTRANSFORM)
      )
  def test_eval_exc_with_wb97mv_polarized(self, wb97mv_form, parameters):
    rho_and_derivs = np.random.rand(2, 6, 5)
    quantities, lda_energies = evaluators.parse_rho_and_derivs(
        rho_and_derivs, omega=0.3, polarized=True)

    e_xc = np.sum(wb97mv_form.eval_exc(
        **parameters,
        e_lda_x=lda_energies['x'],
        e_lda_css=lda_energies['css'],
        e_lda_cos=lda_energies['cos'],
        features={'w': quantities['w'], 'x2': quantities['x2']},
    ).reshape(-1, 3), axis=1)

    np.testing.assert_allclose(
        e_xc, _get_expected_e_xc_polarized(rho_and_derivs, xc_name='wB97M-V'))

  def test_convert_xc_functional_to_and_from_dict(self):
    self.assertEqual(
        xc_functionals.b97_u,
        xc_functionals.XCFunctional.from_dict(
            xc_functionals.b97_u.to_dict()))

  def test_make_isomorphic_copy_of_wb97mv_short(self):
    feature_names = ['rho', 'x2', 'w']
    num_shared_parameters = 10
    num_variables = 10

    wb97mv_copy = xc_functionals.wb97mv_short.make_isomorphic_copy(
        feature_names_x=feature_names,
        feature_names_css=feature_names,
        feature_names_cos=feature_names,
        num_shared_parameters=num_shared_parameters,
        num_variables=num_variables)

    self.assertEqual(
        wb97mv_copy.f_x,
        enhancement_factors.f_x_wb97mv_short.make_isomorphic_copy(
            feature_names=feature_names,
            num_shared_parameters=num_shared_parameters,
            num_variables=num_variables))
    self.assertEqual(
        wb97mv_copy.f_css,
        enhancement_factors.f_css_wb97mv_short.make_isomorphic_copy(
            feature_names=feature_names,
            num_shared_parameters=num_shared_parameters,
            num_variables=num_variables))
    self.assertEqual(
        wb97mv_copy.f_cos,
        enhancement_factors.f_cos_wb97mv_short.make_isomorphic_copy(
            feature_names=feature_names,
            num_shared_parameters=num_shared_parameters,
            num_variables=num_variables))

  @parameterized.parameters(
      list(range(len(xc_functionals.XCFunctional._signature_features['rho']))))
  def test_get_signature_of_lda(self, rho_index):
    rho = xc_functionals.XCFunctional._signature_features['rho'][rho_index]
    expected_e_xc = (lda.e_x_lda_unpolarized(2 * rho)  # 2: spin factor
                     + lda.e_c_lda_unpolarized(2 * rho))

    mock_random_state = mock.Mock()
    mock_random_state.choice = mock.Mock(side_effect=[[rho_index]])
    e_xc = xc_functionals.lda_functional.get_signature(
        {}, {}, {},
        num_feature_samples=1,
        signature='e_xc',
        random_state=mock_random_state)

    np.testing.assert_allclose(e_xc, expected_e_xc)

  @parameterized.parameters((0, 1.), (1, 10.))
  def test_get_signature_of_b97(self, rho_index, sigma):
    rho = xc_functionals.XCFunctional._signature_features['rho'][rho_index]
    x2 = (.5 * np.sqrt(sigma) / rho ** (4 / 3)) ** 2  # .5: spin factor
    expected_e_xc = (gga.e_x_b97_unpolarized(2 * rho, sigma)
                     + gga.e_c_b97_unpolarized(2 * rho, sigma))

    mock_random_state = mock.Mock()
    mock_random_state.choice = mock.Mock(
        side_effect=[[rho_index], np.array([x2])])
    e_xc = xc_functionals.b97_x2.get_signature(
        **xc_functionals.B97_PARAMETERS,
        num_feature_samples=1,
        signature='e_xc',
        random_state=mock_random_state)

    np.testing.assert_allclose(e_xc, expected_e_xc)

  def test_equivalent_functional_forms_have_identical_fingerprint(self):
    self.assertEqual(
        xc_functionals.wb97mv.get_fingerprint(),
        xc_functionals.wb97mv_short.get_fingerprint())

  @parameterized.parameters(
      (xc_functionals.empty_functional, xc_functionals.b97x_u_short),
      (xc_functionals.b97x_u_short, xc_functionals.b97_u),
      (xc_functionals.b97_u, xc_functionals.b97_x2),
      (xc_functionals.b97_x2, xc_functionals.wb97mv),)
  def test_different_functional_forms_have_different_fingerprint(
      self, functional1, functional2):
    self.assertNotEqual(
        functional1.get_fingerprint(), functional2.get_fingerprint())

  def test_get_fingerprint_with_unsupported_feature(self):
    with self.assertRaisesRegex(
        ValueError, 'Evaluating signature is not supported for feature t'):
      xc_functionals.empty_functional.make_isomorphic_copy(
          feature_names_x=['t']).get_signature({}, {}, {})

  @parameterized.parameters(
      ('b97', 0.0,
       xc_functionals.b97_x2,
       xc_functionals.B97_PARAMETERS),
      ('b97', 0.0,
       xc_functionals.b97_x2_short,
       xc_functionals.B97_PARAMETERS_UTRANSFORM),
      ('wb97m_v', 0.3,
       xc_functionals.wb97mv,
       xc_functionals.WB97MV_PARAMETERS),
      ('wb97m_v', 0.3,
       xc_functionals.wb97mv_short,
       xc_functionals.WB97MV_PARAMETERS_UTRANSFORM),
      )
  def test_make_eval_exc_unpolarized(self, xc_name, omega, xc_fun, parameters):
    rho_and_derivs = np.random.rand(6, 5)
    eval_xc_ref = xc.make_eval_xc(xc_name)
    eval_xc = xc_fun.make_eval_xc(omega=omega, **parameters)

    eps_xc, (vrho, vsigma, _, vtau), _, _ = eval_xc(
        '', rho_and_derivs, spin=0, relativity=0, deriv=1, verbose=None)
    eps_xc_ref, (vrho_ref, vsigma_ref, _, vtau_ref), _, _ = eval_xc_ref(
        '', rho_and_derivs, spin=0, relativity=0, deriv=1, verbose=None)

    np.testing.assert_allclose(eps_xc, eps_xc_ref)
    np.testing.assert_allclose(vrho, vrho_ref)
    np.testing.assert_allclose(vsigma, vsigma_ref)
    np.testing.assert_allclose(vtau, vtau_ref)

  @parameterized.parameters(
      ('b97', 0.0,
       xc_functionals.b97_x2,
       xc_functionals.B97_PARAMETERS),
      ('b97', 0.0,
       xc_functionals.b97_x2_short,
       xc_functionals.B97_PARAMETERS_UTRANSFORM),
      ('wb97m_v', 0.3,
       xc_functionals.wb97mv,
       xc_functionals.WB97MV_PARAMETERS),
      ('wb97m_v', 0.3,
       xc_functionals.wb97mv_short,
       xc_functionals.WB97MV_PARAMETERS_UTRANSFORM),
      )
  def test_make_eval_exc_polarized(self, xc_name, omega, xc_fun, parameters):
    rho_and_derivs = np.random.rand(2, 6, 5)
    eval_xc_ref = xc.make_eval_xc(xc_name)
    eval_xc = xc_fun.make_eval_xc(omega=omega, **parameters)

    eps_xc, (vrho, vsigma, _, vtau), _, _ = eval_xc(
        '', rho_and_derivs, spin=1, relativity=0, deriv=1, verbose=None)
    eps_xc_ref, (vrho_ref, vsigma_ref, _, vtau_ref), _, _ = eval_xc_ref(
        '', rho_and_derivs, spin=1, relativity=0, deriv=1, verbose=None)

    np.testing.assert_allclose(eps_xc, eps_xc_ref)
    np.testing.assert_allclose(vrho, vrho_ref)
    np.testing.assert_allclose(vsigma, vsigma_ref)
    np.testing.assert_allclose(vtau, vtau_ref)

if __name__ == '__main__':
  absltest.main()


text:
from . import api
from .views import show
from django.conf import settings
from django.http import Http404
from django.db import connection

class URLRouterFallbackMiddleware(object):
    def process_response(self, request, response):
        if response.status_code != 404:
            return response # Pass through non-404 responses
        try:
            # TODO/XXX: Workaround for bug in Django. TemplateResponse.render()
            # isn't called after process_response().
            new_response = show(request, request.path_info)

            if hasattr(new_response, 'render') and callable(new_response.render):
                new_response = new_response.render()
            return new_response
        # Return the original response if any errors happened. Because this
        # is a middleware, we can't assume the errors will be caught elsewhere.
        except Http404:
            return response
        except:
            if settings.DEBUG:
                raise
            return response


text:
'''
Raw  matches from LOL API using RiotWatcher.

Deprecated. Use `collector.py` instead.
'''
import os
import os.path
import time
import logging
import json
from riotwatcher.riotwatcher import RiotWatcher, BRAZIL, LoLException
import config

def last_match(dump_dir):
    '''
    Returns last dumped match ID from DUMP_DIR
    '''
    matches = [m for m in os.listdir(dump_dir) if m.endswith('.json')]

    if len(matches) == 0:
        return None

    return max([int(m.split('.')[0]) for m in matches])

# Minimal log setting
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# LOL api wrapper
wrapper = RiotWatcher(key=config.API_KEY, default_region=BRAZIL)

# First match to be dumped
starting_match_id = last_match(config.DUMP_DIR) or config.STARTING_MATCH_ID

n = 10000  # total n matches to dump
counter = 0  # total matches dumped
i = 0  # matches iterator

while counter < n:
    try:
        # Next match to dump
        match_id = starting_match_id + i

        filename = '%s%d%s' % (config.DUMP_DIR, match_id, ".json")

        if os.path.isfile(filename):
            logger.info('%s: Match already exists.', match_id)
            continue

        # Get match from Riot API
        match = wrapper.get_match(match_id=match_id)

        # Dumping
        with open(filename, 'w') as f:
            json.dump(match, f)
            logger.info('%s: Match saved.', match_id)

        counter += 1

    except LoLException as e:
        logger.info('LoLException Error: %s: %s', match_id, e)

        if str(e) == 'Too many requests':
            logger.info('Sleeping way...')
            time.sleep(10)   # connection time-out for get_match
    finally:
        i += 1


text:
{-# LANGUAGE ExistentialQuantification #-}

module Rad.QL.Query where

import qualified Data.Aeson          as JSON
import qualified Data.ByteString     as B
import           Data.ByteString.Builder
import qualified Data.HashMap.Strict as HashMap
import           Data.Maybe          (fromMaybe, mapMaybe)
import           Data.Monoid         ((<>))
import qualified Data.Scientific     as Scientific
import qualified Data.Trie           as Trie
import qualified Data.Text           as T
import qualified Data.Text.Encoding  as TE

import Rad.QL.AST

-- A processed query must be evaluated with respect to a schema

type TypeDict = Trie.Trie TypeDef
data Schema m = (Monad m) => Schema
  { typeDict      :: TypeDict
  , rootQuery     :: QSelectionSet -> m (Builder, [ B.ByteString ])
  , rootQueryType :: TypeDef
  }

-- Processed query, note that directives and fragment definitions are compiled away

data QNode = QQuery    QSelectionSet
           | QMutation QSelectionSet

type QSelectionSet = [ QSelection ]

data QSelection = QSelectionField  QField
                | QSelectionSpread QCond QSelectionSet

data QField  = QField  Alias Name QArgs QSelectionSet

type QCond = ObjectTypeDef -> Bool

newtype QArgs = QArgs (Trie.Trie QValue) deriving (Eq, Show)

qArgsEmpty :: QArgs
qArgsEmpty = QArgs Trie.empty

qArgs :: [(Name, QValue)] -> QArgs
qArgs = QArgs . Trie.fromList

qArgsLookup :: Name -> QArgs -> Maybe QValue
qArgsLookup n (QArgs trie) = Trie.lookup n trie

data QValue = QInt    Int
            | QFloat  Double
            | QBool   Bool
            | QString B.ByteString -- enums will check for exact bytestring matches
            | QList   [QValue]
            | QObj    QArgs
            | QEmpty
            deriving (Eq, Show)

type ValidationErr = B.ByteString

process :: Schema m -> JSON.Value -> Document -> Either ValidationErr QNode
process schema values (Document defs) = do
    -- extract singular operation
    op <- case [o | DefOperation o <- defs] of
               [o] -> Right o
               _   -> Left "Rad.QL wants exactly one operation"
    -- extract value definitions
    vals <- case values of
                 JSON.Null      -> Right qArgsEmpty
                 JSON.Object o  -> Right $ processObject o
                 JSON.String "" -> Right qArgsEmpty
                 _              -> Left "Invalid variable definitions provided"
   -- extract node from operation
    let Node _ vds _ ss = -- for now we ignore query directives
          case op of
               Query n    -> n
               Mutation n -> n
    -- process variables
    vars <- qArgs <$> traverse (readVal vals) vds
    -- walk tree
    return $ packOp op $ walk vars ss
  where tdict = typeDict schema
        frags = Trie.fromList [ (n, f) | DefFragment f@(FragmentDef n _ _ _) <- defs ]
        -- NOTE: this is currently incorrect!
        -- validations should be performed here, not deferred until field evaluation
        readVal vals (VariableDef (Variable n) t d) =
          case Trie.lookup (typeRefName t) tdict of
               Nothing -> Left  $ "Variable \"$" <> n <> "\" is of unknown type: \"" <> typeRefName t <> "\""
               _       -> Right $ (n, qArgsLookup n vals |?| processLiteral <$> d)
        getTypeCondition (NamedType n) =
          case Trie.lookup n tdict of
               Just (TypeDefObject    o) -> Just (o ==)
               Just (TypeDefInterface i) -> Just $ \(ObjectTypeDef _ _ ifs _) -> i `elem` ifs
               Just (TypeDefUnion (UnionTypeDef _ _ odefs)) -> Just $ \o      -> o `elem` odefs
               _ -> Nothing
        -- walk and process the trie
        -- TODO: handle errors instead of just ignoring them
        walk vals = mapMaybe visit
          where visit (SelectionField (Field a n args ds ss)) = applyDirectives ds
                  (QSelectionField (QField a n (processArgs vals args) (mapMaybe visit ss)))
                visit (SelectionFragmentSpread (FragmentSpread n ds)) = do
                  FragmentDef n tc ds' ss <- Trie.lookup n frags
                  typeCondition <- getTypeCondition tc
                  applyDirectives (ds <> ds') $
                    QSelectionSpread typeCondition (mapMaybe visit ss)
                visit (SelectionInlineFragment (InlineFragment tc ds ss)) = do
                  typeCondition <- getTypeCondition tc
                  applyDirectives ds $
                    QSelectionSpread typeCondition (mapMaybe visit ss)
                applyDirectives [] = Just
                applyDirectives (Directive "include" [Argument "if" v] : ds)
                  | processValue vals v == QBool True  = applyDirectives ds
                  | otherwise                          = \_ -> Nothing
                applyDirectives (Directive "skip"    [Argument "if" v] : ds)
                  | processValue vals v == QBool False = applyDirectives ds
                  | otherwise                          = \_ -> Nothing
                applyDirectives _ = \_ -> Nothing
        -- repack operation
        packOp (Query    _) ss = QQuery    ss
        packOp (Mutation _) ss = QMutation ss

execute :: (Monad m) => Schema m -> JSON.Value -> Document -> m (Builder, [ B.ByteString ])
execute s v d =
  case process s v d of
       Right (QQuery    n) -> rootQuery s n
       Right (QMutation n) -> pure (byteString "null", [ "not defined" ])
       Left  e             -> pure (byteString "null", [e])

-- helpers
processLiteral :: Value -> QValue
processLiteral (ValueVariable v) = QEmpty
processLiteral (ValueInt      v) = QInt    v
processLiteral (ValueFloat    v) = QFloat  v
processLiteral (ValueBoolean  v) = QBool   v
processLiteral (ValueString   v) = QString v
processLiteral (ValueEnum     v) = QString v
processLiteral (ValueList (ListValue vs))     = QList $ map processLiteral  vs
processLiteral (ValueObject (ObjectValue fs)) = QObj $ qArgs
  [ (n, processLiteral v) | ObjectField n v <- fs ]

processValue :: QArgs -> Value -> QValue
processValue _ (ValueInt      v) = QInt    v
processValue _ (ValueFloat    v) = QFloat  v
processValue _ (ValueBoolean  v) = QBool   v
processValue _ (ValueString   v) = QString v
processValue _ (ValueEnum     v) = QString v
processValue dict (ValueList (ListValue vs)) = QList $ map (processValue dict) vs
processValue dict (ValueObject (ObjectValue fs)) = QObj . QArgs $ Trie.fromList
  [ (n, processValue dict v) | ObjectField n v <- fs ]
processValue dict (ValueVariable (Variable n)) = fromMaybe QEmpty $ qArgsLookup n dict

processArgs :: QArgs -> [Argument] -> QArgs
processArgs dict args = qArgs [ (n, processValue dict v) | Argument n v <- args ]

processVar :: JSON.Value -> QValue
processVar  JSON.Null      = QEmpty
processVar (JSON.String t) = QString $ TE.encodeUtf8 t
processVar (JSON.Bool   b) = QBool b
processVar (JSON.Number n) = either QFloat QInt $ Scientific.floatingOrInteger n
processVar (JSON.Array  a) = QList []
processVar (JSON.Object o) = QObj $ processObject o

processObject :: HashMap.HashMap T.Text JSON.Value -> QArgs
processObject o = qArgs [(TE.encodeUtf8 k, processVar v) | (k, v) <- HashMap.toList o]

infixl 3 |?|
(|?|) :: Maybe QValue -> Maybe QValue -> QValue
(Just QEmpty) |?| v = fromMaybe QEmpty v
(Just v     ) |?| _ = v
Nothing       |?| v = fromMaybe QEmpty v


text:
module Saml
  module ComplexTypes
    module EndpointType
      extend ActiveSupport::Concern
      include Saml::Base

      included do
        namespace 'md'

        attribute :binding, String, tag: "Binding"
        attribute :location, String, tag: "Location"
        attribute :response_location, String, tag: "ResponseLocation"

        validates :binding, :location, presence: true
      end
    end
  end
end


text:
package ductive.config;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;

import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.health.jvm.ThreadDeadlockHealthCheck;

import ductive.commons.Names;

public class DefaultHealthChecks {

	@Autowired private HealthCheckRegistry healthCheckRegistry;

	@PostConstruct
	public void init() {
		healthCheckRegistry.register(Names.from(ThreadDeadlockHealthCheck.class),new ThreadDeadlockHealthCheck());
	}

}


text:
namespace Opserver.Security
{
    /// <summary>
    /// Security settings for configuring the <see cref="ActiveDirectoryProvider"/>.
    /// </summary>
    public class ActiveDirectorySecuritySettings : SecuritySettings
    {
        /// <summary>
        /// Gets or sets the server to bind to in order to authenticate users.
        /// </summary>
        public string Server { get; set; }
        /// <summary>
        /// Gets or sets the username used to bind to AD in order to authenticate users.
        /// </summary>
        public string AuthUser { get; set; }
        /// <summary>
        /// Gets or sets the password used to bind to AD in order to authenticate users.
        /// </summary>
        public string AuthPassword { get; set; }
    }
}


text:
# -*- coding: utf-8 -*-
from __future__ import with_statement

from django.test import TestCase

import jinja2

from compressor.conf import settings
from compressor.tests.test_base import css_tag

class TestJinja2CompressorExtension(TestCase):
    """
    Test case for jinja2 extension.

    .. note::
       At tests we need to make some extra care about whitespace. Please note
       that we use jinja2 specific controls (*minus* character at block's
       beginning or end). For more information see jinja2 documentation.
    """

    def assertStrippedEqual(self, result, expected):
        self.assertEqual(result.strip(), expected.strip(), "%r != %r" % (
            result.strip(), expected.strip()))

    def setUp(self):
        from compressor.contrib.jinja2ext import CompressorExtension
        self.env = jinja2.Environment(extensions=[CompressorExtension])

    def test_error_raised_if_no_arguments_given(self):
        self.assertRaises(jinja2.exceptions.TemplateSyntaxError,
            self.env.from_string, '{% compress %}Foobar{% endcompress %}')

    def test_error_raised_if_wrong_kind_given(self):
        self.assertRaises(jinja2.exceptions.TemplateSyntaxError,
            self.env.from_string, '{% compress foo %}Foobar{% endcompress %}')

    def test_error_raised_if_wrong_mode_given(self):
        self.assertRaises(jinja2.exceptions.TemplateSyntaxError,
            self.env.from_string, '{% compress css foo %}Foobar{% endcompress %}')

    def test_compress_is_disabled(self):
        org_COMPRESS_ENABLED = settings.COMPRESS_ENABLED
        settings.COMPRESS_ENABLED = False
        tag_body = '\n'.join([
            '<link rel="stylesheet" href="css/one.css" type="text/css" charset="utf-8">',
            '<style type="text/css">p { border:5px solid green;}</style>',
            '<link rel="stylesheet" href="css/two.css" type="text/css" charset="utf-8">',
        ])
        template_string = '{% compress css %}' + tag_body + '{% endcompress %}'
        template = self.env.from_string(template_string)
        self.assertEqual(tag_body, template.render())
        settings.COMPRESS_ENABLED = org_COMPRESS_ENABLED

    def test_empty_tag(self):
        template = self.env.from_string(u"""{% compress js %}{% block js %}
        {% endblock %}{% endcompress %}""")
        context = {'STATIC_URL': settings.COMPRESS_URL}
        self.assertEqual(u'', template.render(context))

    def test_css_tag(self):
        template = self.env.from_string(u"""{% compress css -%}
        <link rel="stylesheet" href="{{ STATIC_URL }}css/one.css" type="text/css" charset="utf-8">
        <style type="text/css">p { border:5px solid green;}</style>
        <link rel="stylesheet" href="{{ STATIC_URL }}css/two.css" type="text/css" charset="utf-8">
        {% endcompress %}""")
        context = {'STATIC_URL': settings.COMPRESS_URL}
        out = css_tag("/static/CACHE/css/e41ba2cc6982.css")
        self.assertEqual(out, template.render(context))

    def test_nonascii_css_tag(self):
        template = self.env.from_string(u"""{% compress css -%}
        <link rel="stylesheet" href="{{ STATIC_URL }}css/nonasc.css" type="text/css" charset="utf-8">
        <style type="text/css">p { border:5px solid green;}</style>
        {% endcompress %}""")
        context = {'STATIC_URL': settings.COMPRESS_URL}
        out = css_tag("/static/CACHE/css/799f6defe43c.css")
        self.assertEqual(out, template.render(context))

    def test_js_tag(self):
        template = self.env.from_string(u"""{% compress js -%}
        <script src="{{ STATIC_URL }}js/one.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">obj.value = "value";</script>
        {% endcompress %}""")
        context = {'STATIC_URL': settings.COMPRESS_URL}
        out = u'<script type="text/javascript" src="/static/CACHE/js/066cd253eada.js"></script>'
        self.assertEqual(out, template.render(context))

    def test_nonascii_js_tag(self):
        template = self.env.from_string(u"""{% compress js -%}
        <script src="{{ STATIC_URL }}js/nonasc.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">var test_value = "\u2014";</script>
        {% endcompress %}""")
        context = {'STATIC_URL': settings.COMPRESS_URL}
        out = u'<script type="text/javascript" src="/static/CACHE/js/e214fe629b28.js"></script>'
        self.assertEqual(out, template.render(context))

    def test_nonascii_latin1_js_tag(self):
        template = self.env.from_string(u"""{% compress js -%}
        <script src="{{ STATIC_URL }}js/nonasc-latin1.js" type="text/javascript" charset="latin-1"></script>
        <script type="text/javascript">var test_value = "\u2014";</script>
        {% endcompress %}""")
        context = {'STATIC_URL': settings.COMPRESS_URL}
        out = u'<script type="text/javascript" src="/static/CACHE/js/be9e078b5ca7.js"></script>'
        self.assertEqual(out, template.render(context))

    def test_css_inline(self):
        template = self.env.from_string(u"""{% compress css, inline -%}
        <link rel="stylesheet" href="{{ STATIC_URL }}css/one.css" type="text/css" charset="utf-8">
        <style type="text/css">p { border:5px solid green;}</style>
        {% endcompress %}""")
        context = {'STATIC_URL': settings.COMPRESS_URL}
        out = '\n'.join([
            '<style type="text/css">body { background:#990; }',
            'p { border:5px solid green;}</style>',
        ])
        self.assertEqual(out, template.render(context))

    def test_js_inline(self):
        template = self.env.from_string(u"""{% compress js, inline -%}
        <script src="{{ STATIC_URL }}js/one.js" type="text/css" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">obj.value = "value";</script>
        {% endcompress %}""")
        context = {'STATIC_URL': settings.COMPRESS_URL}
        out = '<script type="text/javascript">obj={};obj.value="value";</script>'
        self.assertEqual(out, template.render(context))

    def test_nonascii_inline_css(self):
        org_COMPRESS_ENABLED = settings.COMPRESS_ENABLED
        settings.COMPRESS_ENABLED = False
        template = self.env.from_string(u'{% compress css %}'
                                        u'<style type="text/css">'
                                        u'/* русский текст */'
                                        u'</style>{% endcompress %}')
        out = u'<link rel="stylesheet" href="/static/CACHE/css/b2cec0f8cb24.css" type="text/css" />'
        settings.COMPRESS_ENABLED = org_COMPRESS_ENABLED
        context = {'STATIC_URL': settings.COMPRESS_URL}
        self.assertEqual(out, template.render(context))


text:
package com.mytwitter.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.twitter.sdk.android.tweetcomposer.TweetUploadService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Manish on 5/7/2016.
 */
public class MyResultReceiver extends BroadcastReceiver {

    private static Logger logger = LoggerFactory.getLogger("c*.m*.r*.MyResult*");

    @Override
    public void onReceive(Context context, Intent intent) {
        logger.debug("inside MyResultReceiver");
        if (TweetUploadService.UPLOAD_SUCCESS.equals(intent.getAction())) {
            // success
            final Long tweetId = intent.getExtras().getLong(TweetUploadService.EXTRA_TWEET_ID);
            Toast.makeText(context, "Tweet posted Successfully.", Toast.LENGTH_LONG).show();
        } else {
            // failure
            final Intent retryIntent = intent.getExtras().getParcelable(TweetUploadService.EXTRA_RETRY_INTENT);
            Toast.makeText(context, "Tweet posted Failed.", Toast.LENGTH_LONG).show();
        }
    }
}


text:
package com.javarush.task.task13.task1320;

/*
Neo
1. Реализовать интерфейс DBObject в классе User.
2. Реализовать метод initializeIdAndName так, чтобы программа работала и выводила на экран «User has name Neo, id = 1«.
3. Метод toString и метод main менять нельзя.
4. Подумай, что должен возвращать метод initializeIdAndName в классе User.
*/

public class Solution {
    public static void main(String[] args) throws Exception {
        System.out.println(Matrix.NEO);
    }

    static class Matrix {
        public static DBObject NEO = new User().initializeIdAndName(1, "Neo");
    }

    interface DBObject {
        DBObject initializeIdAndName(long id, String name);
    }

    static class User implements DBObject{
        long id;
        String name;

        @Override
        public String toString() {
            return String.format("User has name %s, id = %d", name, id);
        }

        @Override
        public User initializeIdAndName(long id, String name) {
            this.id = id;
            this.name = name;
            return this;
        }
    }
}


text:
layout: page
title: "About: ISKIRK.NET"
header: /assets/img/about.jpg
---

![This is me!](/assets/icons/200x200.png)

Welcome to iskirk.net. I'm Kirk and I'm an avid astronomy enthusiast. This is my place on the web to post some things that interest me and may interest someone else also.

<center>

## Keep in Touch

</center>