text:
// Copyright © 2013, 2014 Lénaïc Bagnères, hnc@singularity.fr

// This file is part of hnc.

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

// hnc is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with hnc. If not, see <http://www.gnu.org/licenses/>

#ifndef HNC_ALGO_COMPARE_RANGE_HPP
#define HNC_ALGO_COMPARE_RANGE_HPP

#include <algorithm>

namespace hnc
{
	namespace algo
	{
		/**
		 * @brief Compare two sequences
		 *
		 * @code
		   #include <hnc/algo.hpp>
		   @endcode
		 *
		 * @param[in] first0            Iterator on first element of the first container
		 * @param[in] last0             Iterator on last element of the first container (not included)
		 * @param[in] first1            Iterator on first element of the second container
		 * @param[in] last1_upper_bound Iterator on last element (upper bound) of the second container (not included)
		 * @param[in] comp              Function to compare two elements
		 *
		 * @return true if all comparisons return true, false otherwise
		 *
		 * @note Consider Boost.Range
		 * @note Consider std::equal_range to compare a sequence with one element
		 */
		template <class forward_iterator_t0, class forward_iterator_t1, class compare>
		bool compare_range
		(
			forward_iterator_t0 first0, forward_iterator_t0 const & last0,
			forward_iterator_t1 first1, forward_iterator_t1 const & last1_upper_bound,
			compare comp
		)
		{
			using value_t0 = typename std::iterator_traits<forward_iterator_t0>::value_type;
			using value_t1 = typename std::iterator_traits<forward_iterator_t1>::value_type;
			static_assert(std::is_same<value_t0 , value_t1>::value, "hnc::algo::compare_range invalid call: types of the iterators must be the same");
			// For all elements
			while (first0 != last0)
			{
				// The number of elements between first0 to last0 is greater than the number of elements between first1 and last1_upper_bound
				if (first1 == last1_upper_bound) { return false; }
				// Compare
				if (comp(*first0, *first1) == false) { return false; }
				// Next
				++first0;
				++first1;
			}
			// All comparisons are true
			return true;
		}

		/**
		 * @brief Compare (equality with ==) two sequences
		 *
		 * @code
		   #include <hnc/algo.hpp>
		   @endcode
		 *
		 * @param[in] first0            Iterator on first element of the first container
		 * @param[in] last0             Iterator on last element of the first container (not included)
		 * @param[in] first1            Iterator on first element of the second container
		 * @param[in] last1_upper_bound Iterator on last element (upper bound) of the second container (not included)
		 *
		 * @return true if all comparisons return true, false otherwise
		 *
		 * @note Consider Boost.Range
		 * @note Consider std::equal_range to compare a sequence with one element
		 */
		template <class forward_iterator_t0, class forward_iterator_t1>
		bool compare_range
		(
			forward_iterator_t0 first0, forward_iterator_t0 const & last0,
			forward_iterator_t1 first1, forward_iterator_t1 const & last1_upper_bound
		)
		{
			using value_t0 = typename std::iterator_traits<forward_iterator_t0>::value_type;
			using value_t1 = typename std::iterator_traits<forward_iterator_t1>::value_type;
			static_assert(std::is_same<value_t0 , value_t1>::value, "hnc::algo::compare_range invalid call: types of the iterators must be the same");
			// Compare function (a == b)
			auto comp = [](value_t0 const & a, value_t0 const & b) -> bool { return a == b; };
			// Compare range
			return hnc::algo::compare_range(first0, last0, first1, last1_upper_bound, comp);
		}
	}
}

#endif


text:
/*
 * useradm.c
 *
 * Learn some tricks about user, group and password administration.
 */
#include <stdio.h>
#include <errno.h>
#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>

int main( int argc, char *argv[] ) {
  int myid; /* my ID */
  int myeid; /* my effective ID */
  int gid; /* group ID */
  int egid; /* effective group ID */
  struct passwd *pwp;

  myid = getuid();
  myeid = geteuid();
  gid = getgid();
  egid = getegid();

  printf( "My ID is %d\n", myid );
  printf( "My effective ID is %d\n", myeid );
  printf( "Group ID is %d", gid );
  printf( "Effective Group ID is %d\n", egid );

  /**
   * Get information about user and its password, through
   * function getpsent().
   * It seems that getpwent() function doesn't need to release
   * space.
   */
  errno = 0;
  /*
   * Here, structure pointer is returned value, thus you don't have
   * to worry about it. the function is reponsible for allocating
   * spaces for structure pointer. and freeing it after using is your
   * responsibility.
   */
  pwp = getpwent(); /* get password entry */
  while ( (pwp = getpwent()) != NULL ) {
    /* everything is OK */
    printf( "Here is the inforamtion of the first record in password\n"
	    " database\n" );
    printf( "User name: '%s'\n", pwp->pw_name );
    printf( "User password: '%s'\n", pwp->pw_passwd );
    printf( "User ID: %d\n", pwp->pw_uid );
    printf( "Group ID: %d\n", pwp->pw_gid );
    printf( "Comment field: '%s'\n", pwp->pw_gecos );
    printf( "Home dir: '%s'\n", pwp->pw_dir );
    printf( "Shell: '%s'\n\n", pwp->pw_shell );
  }
  /* error occured or EOF reached */
  if ( errno != 0 ) {
    /* error occured */
    perror( "getpwent() failed" );
    return 1;
  } else {
    printf( "EOF reached\n" );
  }

  /**
   * user function getpwuid() function to get password entry by
   * inputing its ID as arguments.
   */
  /* first we need to rewind file pointer to bof */
  setpwent();
  myid = getuid();
  pwp = getpwuid( myid );
  if ( pwp != NULL ) {
    printf( "User name is '%s'\n", pwp->pw_name );
    printf( "other infor has been omitted\n" );
  } else {
    if ( errno != 0 ) {
      perror( "No password entry found!" );
      return 0;
    }
  }

  /**
   * get password entry through function getpwnam(),
   * inputing argutment is user name.
   * then its password entry will be returned.
   */
  pwp = getpwnam( "root" );
  if ( pwp != NULL ) {
    printf( "User shell is '%s'\n", pwp->pw_shell );
    printf( "other infor omitted \n" );
  }

  endpwent(); /* close the password file */
  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorService = void 0;
const util = require("util");
class ErrorService {
    /**
     *
     * @param code error code
     * @param extra error extra message
     */
    getError(code, extra) {
        let msg = this.errors[code];
        if (extra && typeof extra === 'string') {
            extra = [extra];
        }
        if (msg && extra) {
            msg = util.format(msg, ...extra);
        }
        return { code, msg };
    }
}
exports.ErrorService = ErrorService;


text:
/**
 * Created by saint on 7/24/14.
 */

var api = {
    method:'jingdong.logistics.otherInstore.add',
    authorization:true,
    check:{
        instore_type:{
            type:'String',
            required:true
        },
        po_no:{
            type:'String',
            required:true
        },
        expected_date:{
            type:'String',
            required:false
        },
        approver:{
            type:'String',
            required:false
        },
        warehouse_no:{
            type:'String',
            required:true
        },
        goods_no:{
            type:'StringArray',
            required:false
        },
        isv_goods_no:{
            type:'StringArray',
            required:false
        },
        expected_qty:{
            type:'NumberArray',
            required:true
        },
        goods_status:{
            type:'StringArray',
            required:true
        }
    }
};

module.exports = api;


text:
Updated for Postgres 14 and PHP 8.1. The major version is incremented due to a few BC breaks.

### Changed
* Methods working with OIDs (e.g. `TypeConverterFactory::getConverterForTypeOID()`)
  no longer have `int` typehints: OIDs are *unsigned* 32-bit integers and
  may be out of range of PHP's *signed* `int` type on 32-bit builds.
* `converters\ConnectionAware` interface now defines a `setConnection()` method accepting an instance of
  `Connection` instead of `setConnectionResource()` method accepting an underlying resource. This was done to
  prevent the need for boilerplate code checking whether the passed value is a resource (before PHP 8.1) or
  an instance of `\Pgsql\Connection` (PHP 8.1+) in implementations of `ConnectionAware`.
* `ServerException::fromConnection()` now accepts an instance of `Connection` rather than an underlying resource,
  this was done mostly for the same reasons as above.
* `ConnectionException` extends `ServerException` so that it is now possible to specify `SQLSTATE` error code for it
  (e.g. `ServerException::ADMIN_SHUTDOWN`).

### Added
* As `pgsql` functions in PHP 8.1 now return and accept objects instead of resources, added checks for these objects
  alongside `is_resource` checks for earlier PHP versions.
* Full support for multirange types added in Postgres 14, with `types\Multirange` and its descendants to
  represent the values on PHP side and `converters\containers\MultiRangeConverter` to transform the values
  to and from DB string representation.
* New error code defined in Postgres 14.
* Support for infinite values in `NumericConverter` (numeric type in Postgres 14 allows these).
* `Connection::getLastError()` method.

### Fixed
Missing bounds in range types are always marked as exclusive, this follows PostgreSQL's behaviour.

## [1.0.0] - 2021-06-26

### Changed
`ResultSet` caches the last fetched row: e.g. accessing `$result[0]['field2']` after `$result[0]['field1']`
will no longer cause an additional `pg_fetch_array()` call with subsequent type conversions

### Removed
`DefaultTypeConverterFactory` no longer registers converters for obsolete `abstime` and `reltime` types, those were
removed in Postgres 12

## [1.0.0-beta.4] - 2021-02-15

### Changed
* Objects representing Postgres types are now immutable.
* `ResultSet::current()` and `ResultSet::offsetGet()` will return `null` rather than `false` for non-existent offsets.
* `Connection::execute()`, `Connection::executeParams()`, `PreparedStatement::execute()` will now consistently return `ResultSet` instead of
  `ResultSet|int|bool`. Number of affected rows for DML queries is available via new `ResultSet::getAffectedRows()` method.
* `ext-pgsql` is a suggested dependency rather than required, so that type converters may be used with e.g. PDO

### Added
* Tested and supported on PHP 8
* Static analysis with phpstan and psalm
* Package `Exception` interface now extends `\Throwable`

### Fixed
* Lots of minor issues caught by static analysis
  * Added sanity checks to `BaseDateTimeConverter` when working with connection resource (e.g. it will no longer try to get `DateStyle` setting from closed connection).
  * Added tests for `FloatConverter` and `NumericConverter` that check behaviour with locales having `','` as a decimal separator.
  * `ByteaConverter` will reject non-strings.
  * `HstoreConverter` will properly error on invalid input.
  * Additional checks for `pg_*()` functions returning `false`.

## [1.0.0-beta.3] - 2020-09-18

### Changed
* Date and time converters will return `\DateTimeImmutable` instances instead of `\DateTime`.
* `DateTimeRange` bounds are now instances of `\DateTimeImmutable` instead of `\DateTime`.
  It accepts all `\DateTimeInterface` implementations for bounds but will convert them to `\DateTimeImmutable`.
* Disallow subsequent `setConnection()` calls on `TypeConverterFactory` implementations with
  different `Connection` instances.

### Fixed
* Date and time converters will accept instances of `\DateTimeInterface`, not just `\DateTime`.
* `StubConverter::output()` will convert a non-null value to string.
* `DefaultTypeConverterFactory::setConnection()` properly updates the existing converters.

## [1.0.0-beta.2] - 2020-07-19

### Fixed
Namespaced `BadMethodCallException` now extends  SPL's `BadMethodCallException` rather than `InvalidArgumentException`

## [1.0.0-beta] - 2020-07-18

### Added
* Types array in `DefaultTypeConverterFactory` is pre-populated with built-in data types of PostgreSQL. Loading
  metadata from DB / cache will now only be needed if using custom types.
* `Connection::atomic()` method which accepts a callable and executes it atomically, opening a transaction
  and creating savepoints for nested `atomic()` calls as needed. It will automatically commit if callback executes
  successfully and rollback if it throws an exception. It is possible to register callbacks to execute after
  the final commit or rollback.
* `Connection::quoteIdentifier()` method.

### Changed
* Requires at least PHP 7.2
* Requires at least PostgreSQL 9.3
* Split `TypeConverterFactory::getConverter()` method into
  * `getConverterForTypeOID()` - returns a converter for the database type OID, used by `ResultSet` to
    find converters for result columns,
  * `getConverterForTypeSpecification()` - returns a converter for a user-supplied type specification
    (e.g. type name or array describing fields of the composite type).
* Removed `Connection::guessOutputFormat()`, added `TypeConverterFactory::getConverterForPHPValue()` instead.
  Made it possible to specify mapping between PHP classes and type converters in `DefaultTypeConverterFactory`
  so that its `getConverterForPHPValue()` implementation can process new custom types.
* Methods `beginTransaction()`, `commit()`, `rollback()` no longer work with savepoints, separate methods
  `createSavepoint()`, `releaseSavepoint()`, `rollbackToSavepoint()` added
* Renamed `InvalidQueryException` to `ServerException` and added several subclasses for that. If a query fails:
  * `ConnectionException` is thrown when connection to server failed.
  * Subclass of `ServerException` is thrown based on `SQLSTATE` error code when said code is available.

### Removed
* Support for `mbstring.func_overload`, which was deprecated in PHP 7.2
* `fsec` field from custom `DateInterval` class, as native `f` field for fractional seconds
  is available since PHP 7.1.

### Fixed
* Optimized type converter for interval fields quite a bit.
* Sub-converters of container converters (array, composite and range) that implement `ConnnectionAware` now
  properly receive the connection resource.
* `Connection::quote()` now uses recommended `pg_escape_literal()` under the hood.
* Connection is automatically established only the first time it is needed, not after an explicit `disconnect()` call.

## [0.2.2] - 2017-09-18

### Fixed
Constructor of `PreparedStatement` should skip `null` values `$paramTypes` like it did before 0.2.1

## [0.2.1] - 2017-09-12

### Added
* Manual `prepare()` / `deallocate()` methods to `PreparedStatement`
* Allow cloning a `Connection` object, but force opening a different connection.

### Removed
* Removed unused `BadMethodCallException` class

### Fixed
* `RangeConverter` could enter an infinite loop on some invalid input.
* Field index in `ResultSet` was checked against wrong property.
* Types specified for query parameters and results as `TypeConverter` instances will *always* be passed through `TypeConverterFactory::getConverter()` so that converters implementing `ConnectionAware` can be properly configured. Previous behaviour was inconsistent.
* When a `TypeConverter` instance is passed to `StubTypeConverterFactory::getConverter()` it will be returned instead of `StubConverter`. Converter implementing `ConnectionAware` will be configured with current connection, like with `DefaultTypeConverterFactory`.

## [0.2.0] - 2017-09-04

### Added
* It is now possible to cache composite types' structure and automatically load structure of free-standing composite types.
* New `converters\StubConverter` and `converters\StubTypeConverterFactory` allow to essentially switch off type conversion. Instance of the former is also now returned instead of `converters\StringConverter` when a proper converter cannot be determined.

### Changed
* Removed `MetadataCache` interface and its implementations. The package can now use any PSR-6 compatible cache implementation for metadata.
* `TypeConverterFactory` is now an interface. Previous class is renamed `converters\DefaultTypeConverterFactory` and implements said interface.
* Features depending on classes from `sad_spirit\pg_builder` package were removed from `DefaultTypeConverterFactory`, will now be available in `sad_spirit\pg_builder`.

### Fixed
* `converters\containers\CompositeConverter` changed to not use `each()` construct deprecated in PHP 7.2

## [0.1.0] - 2014-09-28

Initial release on GitHub

[0.1.0]: https://github.com/sad-spirit/pg-wrapper/releases/tag/v0.1.0
[0.2.0]: https://github.com/sad-spirit/pg-wrapper/compare/v0.1.0...v0.2.0
[0.2.1]: https://github.com/sad-spirit/pg-wrapper/compare/v0.2.0...v0.2.1
[0.2.2]: https://github.com/sad-spirit/pg-wrapper/compare/v0.2.1...v0.2.2
[1.0.0-beta]: https://github.com/sad-spirit/pg-wrapper/compare/v0.2.2...v1.0.0-beta
[1.0.0-beta.2]: https://github.com/sad-spirit/pg-wrapper/compare/v1.0.0-beta...v1.0.0-beta.2
[1.0.0-beta.3]: https://github.com/sad-spirit/pg-wrapper/compare/v1.0.0-beta.2...v1.0.0-beta.3
[1.0.0-beta.4]: https://github.com/sad-spirit/pg-wrapper/compare/v1.0.0-beta.3...v1.0.0-beta.4
[1.0.0]: https://github.com/sad-spirit/pg-wrapper/compare/v1.0.0-beta.4...v1.0.0
[2.0.0-beta]: https://github.com/sad-spirit/pg-wrapper/compare/v1.0.0...v2.0.0-beta


text:
package org.artifactory.rest.resource.search.fields;

/**
 * Date: 5/16/14 10:18 AM
 *
 * @author freds
 */
public abstract class FieldNameHelper {
}


text:
package org.openmuc.framework.datalogger.sql;

import java.sql.SQLException;

public class DbAccessTestable extends DbAccess {

    public DbAccessTestable(DbConnector connector) throws SQLException {
        // super(connector);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Isidium stalactiticum Bory

### Remarks
null


text:
package org.keycloak.models;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public interface UserModel {
    public static final String USERNAME = "username";
    public static final String LAST_NAME = "lastName";
    public static final String FIRST_NAME = "firstName";
    public static final String EMAIL = "email";
    public static final String LOCALE = "locale";

    String getId();

    String getUsername();

    void setUsername(String username);

    /**
     * Get timestamp of user creation. May be null for old users created before this feature introduction.
     */
    Long getCreatedTimestamp();

    void setCreatedTimestamp(Long timestamp);

    boolean isEnabled();

    boolean isTotp();

    void setEnabled(boolean enabled);

    /**
     * Set single value of specified attribute. Remove all other existing values
     *
     * @param name
     * @param value
     */
    void setSingleAttribute(String name, String value);

    void setAttribute(String name, List<String> values);

    void removeAttribute(String name);

    /**
     * @param name
     * @return null if there is not any value of specified attribute or first value otherwise. Don't throw exception if there are more values of the attribute
     */
    String getFirstAttribute(String name);

    /**
     * @param name
     * @return list of all attribute values or empty list if there are not any values. Never return null
     */
    List<String> getAttribute(String name);

    Map<String, List<String>> getAttributes();

    Set<String> getRequiredActions();

    void addRequiredAction(String action);

    void removeRequiredAction(String action);

    void addRequiredAction(RequiredAction action);

    void removeRequiredAction(RequiredAction action);

    String getFirstName();

    void setFirstName(String firstName);

    String getLastName();

    void setLastName(String lastName);

    String getEmail();

    void setEmail(String email);

    boolean isEmailVerified();

    void setEmailVerified(boolean verified);

    void setTotp(boolean totp);

    void updateCredential(UserCredentialModel cred);

    List<UserCredentialValueModel> getCredentialsDirectly();

    void updateCredentialDirectly(UserCredentialValueModel cred);

    Set<RoleModel> getRealmRoleMappings();
    Set<RoleModel> getClientRoleMappings(ClientModel app);
    boolean hasRole(RoleModel role);
    void grantRole(RoleModel role);
    Set<RoleModel> getRoleMappings();
    void deleteRoleMapping(RoleModel role);

    String getFederationLink();
    void setFederationLink(String link);

    void addConsent(UserConsentModel consent);
    UserConsentModel getConsentByClient(String clientInternalId);
    List<UserConsentModel> getConsents();
    void updateConsent(UserConsentModel consent);
    boolean revokeConsentForClient(String clientInternalId);

    public static enum RequiredAction {
        VERIFY_EMAIL, UPDATE_PROFILE, CONFIGURE_TOTP, UPDATE_PASSWORD
    }
}


text:
filesystems
###########

Types
-----

 - **structure_filesystem**
    - Description: Filestystem definition
    - *structure_filesystem/block_device*
        - Required
        - Type: string
    - *structure_filesystem/format*
        - Required
        - Type: boolean
    - *structure_filesystem/preserve*
        - Required
        - Type: boolean
    - *structure_filesystem/mountpoint*
        - Required
        - Type: string
    - *structure_filesystem/mount*
        - Required
        - Type: boolean
    - *structure_filesystem/mountopts*
        - Required
        - Type: string
        - Default value: defaults
    - *structure_filesystem/type*
        - Required
        - Type: string
    - *structure_filesystem/quota*
        - Optional
        - Type: long
    - *structure_filesystem/freq*
        - Required
        - Type: long
        - Default value: 0
    - *structure_filesystem/pass*
        - Required
        - Type: long
        - Default value: 0
    - *structure_filesystem/mkfsopts*
        - Optional
        - Type: string
    - *structure_filesystem/tuneopts*
        - Optional
        - Type: string
    - *structure_filesystem/label*
        - Optional
        - Type: string
    - *structure_filesystem/ksfsformat*
        - Optional
        - Type: boolean
    - *structure_filesystem/aii*
        - Description: When defined and false, AII will ignore this filesystem
        - Optional
        - Type: boolean

Functions
---------

 - filesystems_uniq_paths
    - Description: check that no duplicate mountpoints or blockdevices are used
    - Arguments:
        - array of structure_filesystem, from quattor/types/system


text:
package restful

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"strings"
	"time"
)

var (
	errConnectionRefused = errors.New("Cannot connect to the restful server")
	// Version indicate api version
	Version              = "1"
)

// Client construct a restful request initiator
type Client struct {
	// proto holds the client protocol i.e. unix.
	proto string
	// addr holds the client address.
	addr string
	// keyFile holds the key file as a string.
	keyFile string
	// tlsConfig holds the TLS configuration for the client, and will
	// set the scheme to https in NewClient if present.
	tlsConfig *tls.Config
	// scheme holds the scheme of the client i.e. https.
	scheme string
	// transport holds the client transport instance.
	transport *http.Transport
	// default headers
	HTTPDefaultHeaders map[string]string
	// user agent string
	UserAgent string
}

func NewClient(keyFile string, proto, addr string, tlsConfig *tls.Config) *Client {
	scheme := "http"
	if tlsConfig != nil {
		scheme = "https"
	}

	// The transport is created here for reuse during the client session.
	tr := &http.Transport{
		TLSClientConfig: tlsConfig,
	}

	configureTCPTransport(tr, proto, addr)

	return &Client{
		proto:     proto,
		addr:      addr,
		keyFile:   keyFile,
		tlsConfig: tlsConfig,
		scheme:    scheme,
		transport: tr,
	}
}

func configureTCPTransport(tr *http.Transport, proto, addr string) {
	// Why 32? See https://github.com/docker/docker/pull/8035.
	timeout := 32 * time.Second
	if proto == "unix" {
		// No need for compression in local communications.
		tr.DisableCompression = true
		tr.Dial = func(_, _ string) (net.Conn, error) {
			return net.DialTimeout(proto, addr, timeout)
		}
	} else {
		tr.Proxy = http.ProxyFromEnvironment
		tr.Dial = (&net.Dialer{Timeout: timeout}).Dial
	}
}

func (c *Client) Call(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
	params, err := c.encodeData(data)
	if err != nil {
		return nil, nil, -1, err
	}

	if data != nil {
		if headers == nil {
			headers = make(map[string][]string)
		}
		headers["Content-Type"] = []string{"application/json"}
	}

	body, hdr, statusCode, err := c.clientRequest(method, path, params, headers)
	return body, hdr, statusCode, err
}

func (c *Client) encodeData(data interface{}) (*bytes.Buffer, error) {
	params := bytes.NewBuffer(nil)
	if data != nil {
		if err := json.NewEncoder(params).Encode(data); err != nil {
			return nil, err
		}
	}
	return params, nil
}

func (c *Client) httpClient() *http.Client {
	return &http.Client{Transport: c.transport}
}

func (c *Client) clientRequest(method, path string, in io.Reader, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
	expectedPayload := (method == "POST" || method == "PUT")
	if expectedPayload && in == nil {
		in = bytes.NewReader([]byte{})
	}
	req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", Version, path), in)
	if err != nil {
		return nil, nil, -1, err
	}

	// Add Config's HTTP Headers
	for k, v := range c.HTTPDefaultHeaders {
		req.Header.Set(k, v)
	}

	if len(c.UserAgent) != 0 {
		req.Header.Set("User-Agent", c.UserAgent)
	}
	req.URL.Host = c.addr
	req.URL.Scheme = c.scheme

	if headers != nil {
		for k, v := range headers {
			req.Header[k] = v
		}
	}

	if expectedPayload && req.Header.Get("Content-Type") == "" {
		req.Header.Set("Content-Type", "text/plain")
	}

	resp, err := c.httpClient().Do(req)
	statusCode := -1
	if resp != nil {
		statusCode = resp.StatusCode
	}
	if err != nil {
		if strings.Contains(err.Error(), "connection refused") {
			return nil, nil, statusCode, errConnectionRefused
		}

		if c.tlsConfig == nil {
			return nil, nil, statusCode, fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err)
		}
		return nil, nil, statusCode, fmt.Errorf("An error occurred trying to connect: %v", err)
	}

	if statusCode < 200 || statusCode >= 400 {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, nil, statusCode, err
		}
		if len(body) == 0 {
			return nil, nil, statusCode, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(statusCode), req.URL)
		}
		return nil, nil, statusCode, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body))
	}

	return resp.Body, resp.Header, statusCode, nil
}


text: Tweets unsupervised/semi-supervised clustering using word2vec


text:
"""Session objects."""

from sqlalchemy import orm

class Session(orm.Session):
    """Provides support to context."""

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()


text:
require 'spec_helper'

describe YaMap::MappingObject do
  let(:mo) {YaMap::MappingObject.new}
  it "should java scriptify Hash" do
    mo.javascriptify_variable(:icon_content => 'icon').should eql('{iconContent:"icon"}')
  end
  it "should java scriptify Array" do
    mo.javascriptify_variable([:a, 'icon']).should eql('[a,"icon"]')
  end
  it "should java scriptify Nil" do
    mo.javascriptify_variable(nil).should eql('undefined')
  end
  it "should javascriptify method name" do
    mo.javascriptify_method('icon_content').should eql('iconContent')
  end
  it "should return binding JS variable" do
    mo.binding_name.should match(/mapping_object_\d*/i)
    class NewObject < YaMap::MappingObject;end
    NewObject.new.binding_name.should match(/new_object_\d*/i)
  end
end


text:
#ifndef _assignStyleDialog_h
#define _assignStyleDialog_h

//
// assignStyleDialog.h
//------------------------------------------
// header for assignStyleDialog class
//

// INCLUDE FILES

#ifndef  _gt_h
#include <gt.h>
#endif
#ifndef  _gtLabel_h
#include <gtLabel.h>
#endif
#ifndef  _gtStringEd_h
#include <gtStringEd.h>
#endif
#ifndef  _gtTextEd_h
#include <gtTextEd.h>
#endif
#ifndef  _gtPushButton_h
#include <gtPushButton.h>
#endif
#ifndef  _gtFrame_h
#include <gtFrame.h>
#endif
#ifndef  _gtForm_h
#include <gtForm.h>
#endif
#ifndef  _gtDlgTemplate_h
#include <gtDlgTemplate.h>
#endif
#ifndef  _gtAppShell_h
#include <gtAppShell.h>
#endif
#ifndef  _gtList_h
#include <gtList.h>
#endif

// include Xm.h goes with include viewerShell,
// to work around "unreasonable include nesting" error from cpp
#ifndef _Xm_h
#define XTFUNCPROTO
#define Object XObject
#include <Xm/Xm.h>
#undef Object
#endif
#ifndef  _viewerShell_h
#include <viewerShell.h>
#endif

#ifndef  _genString_h
#include <genString.h>
#endif

// CLASS DEFINITIONS

class assignStyleDialog
//
// Assign Style dialog box, to associate a style with "the selected" (?) text string
//
// based on gtDialogTemplate
//
// individual member functions are documented in assignStyleDialog.h.C
//
{
  public:

    assignStyleDialog(gtBase* parent, viewerShell* parent_vs);
    ~assignStyleDialog();

  private:

    // callbacks
    static void 	ok_CB     	(gtPushButton*, gtEventPtr, void*, gtReason);
    static void  	apply_CB  	(gtPushButton*, gtEventPtr, void*, gtReason);
    static void 	cancel_CB	(gtPushButton*, gtEventPtr, void*, gtReason);
    //                  help_CB         none; n/a for gtDialogTemplate help buttons

    // data members
    gtDialogTemplate*	dialog_template;	// "backbone" widget
    gtLabel*		description;	      	// holds 1-line description of dialog box
    gtList*		style_list;
    viewerShell*	parent_vs;		// vs from which the box was created
						// (and on which it acts?)
};

#endif // _assignStyleDialog_h


text:
/*
 * 1. Cross compile this file on the NachOS cross compiler without
 *    assembling or linking.
 *
 * 2. Then remove the "jal __main" line from the generated .s file
 *
 * 3. Now the .s file will run on SPIM
 */

#define NULL 0

typedef struct Array {
    int length;
	int *addr;

    // Integers or Addresses (strings/hashes)
    int type;
} Array;

Array *initArray(int type, int length)
{
	//Working under the assumption that addresses are 4-bytes and so are integers
	Array *arrayPtr = (Array *)alloc(sizeof(Array));
	arrayPtr->addr = (int *)alloc(length*4);

	if (arrayPtr != NULL) {
		arrayPtr->length = length;
		arrayPtr->type = type;
	}
    return arrayPtr;
}

int lengthOfArray(Array *arrayPtr)
{
	if (arrayPtr != NULL) {
		return arrayPtr->length;
	} else {
		return 0;
	}
}

void *accessIndex(Array *arrayPtr, int index, char *message)
{
        if (index >= arrayPtr->length) {
                //Working under the assumption that addresses are 4-bytes and so are integers
                int *newAddr = (int *)alloc(2*(index+1)*4);
                if (newAddr != NULL) {
                        int it;
                        //Copy from old memory to new memory
                        for (it=0; it < arrayPtr->length; it++) {
                                newAddr[it] = (arrayPtr->addr)[it];
                        }

                        arrayPtr->length = 2*(index+1);
                        arrayPtr->addr = newAddr;
                } else {
                        // Raise an exception
                        ExitWithMessage(message, index);
                }
        }

        return (void *)((arrayPtr->addr) + index);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YetAnotherListApp.Exceptions;
using YetAnotherListApp.Models.Basket;

namespace YetAnotherListApp.Services
{
    public class BasketManager
    {
        private BasketRepository Repository { get; }

        private BasketOptions Options { get; }

        public BasketManager(BasketRepository repository, BasketOptions options)
        {
            Repository = repository;
            Options = options;
        }

        /// <summary>
        /// Gets baskets for the specified user.
        /// </summary>
        /// <param name="userName">Identifies the user.</param>
        /// <returns>Baskets for the specified user.</returns>
        public async Task<UserBasketCollectionViewModel> GetBasketsAsync(string userName)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            return await Repository.GetBasketsAsync(userName);
        }

        /// <summary>
        /// Creates baskets for the specified user.
        /// </summary>
        /// <param name="userName">Identifies the user.</param>
        /// <param name="friendlyUserName">Friendly user name.</param>
        /// <param name="basketNames">New basket names.</param>
        /// <returns>Baskets for the specified user.</returns>
        public async Task<UserBasketCollectionViewModel> CreateBasketsAsync(string userName, string friendlyUserName, params string[] basketNames)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (friendlyUserName == null)
            {
                throw new ArgumentNullException(nameof(friendlyUserName));
            }

            var baskets = new UserBasketCollectionViewModel {UserName = friendlyUserName};

            foreach (var name in basketNames)
            {
                var basket = CreateNewBasket(name);
                baskets.Baskets.Add(basket);
            }

            await SaveBasketsAsync(userName, baskets);

            return baskets;
        }

        /// <summary>
        /// Creates a new basketfor the specified user.
        /// </summary>
        /// <param name="userName">Identifies the user.</param>
        /// <param name="name">Basket name</param>
        /// <returns>Identifies the new basket.</returns>
        public async Task<Tuple<string, UserBasketCollectionViewModel>> CreateNewBasketAsync(string userName, string name)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            var baskets = await Repository.GetBasketsAsync(userName);
            if (baskets == null)
            {
                throw new NoBasketsFoundException(userName);
            }

            if (!(baskets.Baskets.Count < Options.MaxNumberOfBaskets))
            {
                throw new BusinessRuleException($"Sorry, the maximum number of lists is {Options.MaxNumberOfBaskets} :(");
            }

            var basket = CreateNewBasket(name);
            baskets.Baskets.Add(basket);

            await SaveBasketsAsync(userName, baskets);

            return new Tuple<string, UserBasketCollectionViewModel>(basket.Id, baskets);
        }

        /// <summary>
        /// Deletes baskets owned by the specified user.
        /// </summary>
        /// <param name="userName">Identifies the user.</param>
        /// <param name="identifiers">Identifies baskets to be deleted.</param>
        /// <returns>Identifies the active basket after the operation.</returns>
        public async Task<Tuple<string, UserBasketCollectionViewModel>> DeleteBasketsAsync(string userName, string[] identifiers)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (identifiers == null)
            {
                throw new ArgumentNullException(nameof(identifiers));
            }

            if (identifiers.Length == 0)
            {
                throw new BusinessRuleException("Please select items to delete.");
            }

            var baskets = await Repository.GetBasketsAsync(userName);
            if (baskets == null)
            {
                throw new NoBasketsFoundException(userName);
            }

            var items = new List<UserBasketCollectionViewModel.Basket>(baskets.Baskets);
            foreach (var id in identifiers)
            {
                var item = items.FirstOrDefault(x => x.Id == id);
                if (item != null)
                {
                    items.Remove(item);
                }
            }

            if (!items.Any())
            {
                items.Add(CreateNewBasket(Options.DefaultBasketName));
            }

            baskets.Baskets.Clear();
            baskets.Baskets.AddRange(items);

            await SaveBasketsAsync(userName, baskets);

            return new Tuple<string, UserBasketCollectionViewModel>(baskets.Baskets.Last().Id, baskets);
        }

        /// <summary>
        /// Renames a basket.
        /// </summary>
        /// <param name="userName">Identifies the user.</param>
        /// <param name="basketId">Identifies the basket.</param>
        /// <param name="name">A new basket name.</param>
        /// <returns>-</returns>
        public async Task<UserBasketCollectionViewModel> RenameBasketAsync(string userName, string basketId, string name)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (basketId == null)
            {
                throw new ArgumentNullException(nameof(basketId));
            }

            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            var baskets = await Repository.GetBasketsAsync(userName);
            if (baskets == null)
            {
                throw new NoBasketsFoundException(userName);
            }

            var basket = baskets.Baskets.FirstOrDefault(x => x.Id == basketId);
            if (basket == null)
            {
                throw new BusinessRuleException("Could not find the item to rename.");
            }

            basket.Name = name;
            basket.Version = basket.Version + 1;

            await SaveBasketsAsync(userName, baskets);

            return baskets;
        }

        public async Task<UserBasketCollectionViewModel> AddBasketItemAsync(string userName, string basketId, string value)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (basketId == null)
            {
                throw new ArgumentNullException(nameof(basketId));
            }

            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            var baskets = await Repository.GetBasketsAsync(userName);
            if (baskets == null)
            {
                throw new NoBasketsFoundException(userName);
            }

            var basket = baskets.Baskets.FirstOrDefault(x => x.Id == basketId);
            if (basket == null)
            {
                throw new BusinessRuleException("Could not find the target list.");
            }

            basket.Items.Add(new UserBasketCollectionViewModel.BasketItem {Id = Guid.NewGuid().ToString(), Value = value});
            basket.Version = basket.Version + 1;

            var historyItem = baskets.ItemHistories.FirstOrDefault(x => x.Value == value);
            if (historyItem == null)
            {
                baskets.ItemHistories.Add(new UserBasketCollectionViewModel.BasketItemHistory {Value = value, Points = 1});
            }
            else
            {
                historyItem.Points = historyItem.Points + 1;
            }

            SortItemHistories(baskets);

            await SaveBasketsAsync(userName, baskets);

            return baskets;
        }

        public async Task<UserBasketCollectionViewModel> RemoveBasketItemAsync(string userName, string basketId, string itemId)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (basketId == null)
            {
                throw new ArgumentNullException(nameof(basketId));
            }

            if (itemId == null)
            {
                throw new ArgumentNullException(nameof(itemId));
            }

            var baskets = await Repository.GetBasketsAsync(userName);
            if (baskets == null)
            {
                throw new NoBasketsFoundException(userName);
            }

            var basket = baskets.Baskets.FirstOrDefault(x => x.Id == basketId);
            if (basket == null)
            {
                return baskets;
            }

            var item = basket.Items.FirstOrDefault(x => x.Id == itemId);
            if (item == null)
            {
                return baskets;
            }

            basket.Items.Remove(item);
            basket.Version = basket.Version + 1;

            var historyItem = baskets.ItemHistories.FirstOrDefault(x => x.Value == item.Value);
            if (historyItem != null)
            {
                historyItem.Points = historyItem.Points - 1;
                if (historyItem.Points > 0)
                {
                    SortItemHistories(baskets);
                }
                else
                {
                    baskets.ItemHistories.Remove(historyItem);
                }
            }

            await SaveBasketsAsync(userName, baskets);

            return baskets;
        }

        public async Task<UserBasketCollectionViewModel> SwitchBasketItemStatusAsync(string userName, string basketId, string itemId)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (basketId == null)
            {
                throw new ArgumentNullException(nameof(basketId));
            }

            if (itemId == null)
            {
                throw new ArgumentNullException(nameof(itemId));
            }

            var baskets = await Repository.GetBasketsAsync(userName);
            if (baskets == null)
            {
                throw new NoBasketsFoundException(userName);
            }

            var basket = baskets.Baskets.FirstOrDefault(x => x.Id == basketId);
            if (basket == null)
            {
                return baskets;
            }

            var item = basket.Items.FirstOrDefault(x => x.Id == itemId);
            if (item == null)
            {
                return baskets;
            }

            item.IsDone = !item.IsDone;

            basket.Version = basket.Version + 1;

            await SaveBasketsAsync(userName, baskets);

            return baskets;
        }

        public async Task<UserBasketCollectionViewModel> MarkBasketAsDoneAsync(string userName, string basketId)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (basketId == null)
            {
                throw new ArgumentNullException(nameof(basketId));
            }

            var baskets = await Repository.GetBasketsAsync(userName);
            if (baskets == null)
            {
                throw new NoBasketsFoundException(userName);
            }

            var basket = baskets.Baskets.FirstOrDefault(x => x.Id == basketId);
            if (basket == null)
            {
                throw new BusinessRuleException("Could not find the target list.");
            }

            foreach (var item in basket.Items.Where(item => item.IsDone).ToArray())
            {
                basket.Items.Remove(item);
            }

            basket.Version = basket.Version + 1;

            await SaveBasketsAsync(userName, baskets);

            return baskets;
        }

        public async Task<UserBasketCollectionViewModel> RenameBasketItemAsync(string userName, string basketId, string itemId, string value)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (basketId == null)
            {
                throw new ArgumentNullException(nameof(basketId));
            }

            if (itemId == null)
            {
                throw new ArgumentNullException(nameof(itemId));
            }

            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            var baskets = await Repository.GetBasketsAsync(userName);
            if (baskets == null)
            {
                throw new NoBasketsFoundException(userName);
            }

            var basket = baskets.Baskets.FirstOrDefault(x => x.Id == basketId);
            if (basket == null)
            {
                return baskets;
            }

            var item = basket.Items.FirstOrDefault(x => x.Id == itemId);
            if (item == null)
            {
                return baskets;
            }

            basket.Version = basket.Version + 1;

            var historyItem1 = baskets.ItemHistories.FirstOrDefault(x => x.Value == item.Value);
            if (historyItem1 != null)
            {
                historyItem1.Points = historyItem1.Points - 1;
                if (!(historyItem1.Points > 0))
                {
                    baskets.ItemHistories.Remove(historyItem1);
                }
            }

            item.Value = value;

            var historyItem2 = baskets.ItemHistories.FirstOrDefault(x => x.Value == item.Value);
            if (historyItem2 != null)
            {
                historyItem2.Points = historyItem2.Points + 1;
            }
            else
            {
                baskets.ItemHistories.Add(new UserBasketCollectionViewModel.BasketItemHistory {Points = 1, Value = value});
            }

            SortItemHistories(baskets);

            await SaveBasketsAsync(userName, baskets);

            return baskets;
        }

        private static UserBasketCollectionViewModel.Basket CreateNewBasket(string name)
        {
            return new UserBasketCollectionViewModel.Basket
            {
                Id = Guid.NewGuid().ToString(),
                Name = name,
                Version = 1
            };
        }

        private async Task SaveBasketsAsync(string userName, UserBasketCollectionViewModel baskets)
        {
            baskets.Version++;
            await Repository.SaveBasketsAsync(userName, baskets);
        }

        private static void SortItemHistories(UserBasketCollectionViewModel baskets)
        {
            baskets.ItemHistories.Sort(delegate (UserBasketCollectionViewModel.BasketItemHistory item1, UserBasketCollectionViewModel.BasketItemHistory item2)
            {
                var comp = item2.Points.CompareTo(item1.Points);
                if (comp == 0)
                {
                    comp = String.Compare(item2.Value, item1.Value, StringComparison.CurrentCulture);
                }
                return comp;
            });
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Rawr.UI
{
    public partial class CharProfLoadDialog : ChildWindow
    {
        static CharProfLoadDialog()
        {
            // Nothing to do here
        }

		public Character Character { get; private set; }

        public CharProfLoadDialog()
        {
            InitializeComponent();

            if (Rawr.Properties.RecentSettings.Default.RecentCharProfiler == null) {
                Rawr.Properties.RecentSettings.Default.RecentCharProfiler =
                    "C:\\Program Files\\World of Warcraft\\WTF\\Account\\";
            }
            TB_FilePath.Text = Rawr.Properties.RecentSettings.Default.RecentCharProfiler;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            // TODO: Run Load Character from Profiler action
            try
            {
                CharacterProfilerData characterList = new CharacterProfilerData(TB_FilePath.Text);

                FormChooseCharacter form = new FormChooseCharacter(characterList);

                form.Show();
                if (form.DialogResult == true)
                {
                    //StartProcessing();
                    //BackgroundWorker bw = new BackgroundWorker();
                    //bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_LoadCharacterProfilerComplete);
                    //bw.DoWork += new DoWorkEventHandler(bw_LoadCharacterProfiler);
                    //bw.RunWorkerAsync(form.Character);
                    new ErrorWindow() { Message = "Not Yet Implemented" }.Show();
                }

                //form.Dispose();
            }
            catch (InvalidDataException ex)
            {
                MessageBox.Show("Unable to parse saved variable file: " + ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error reading saved variable file: " + ex.Message);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Character Profiler Saved Variables Files  (*.lua)|*.lua";
            ofd.Multiselect = false;
            if (ofd.ShowDialog().GetValueOrDefault(false))
            {
                //System.IO.FileStream file = ofd.File.OpenRead();
                //System.IO.Stream file = ofd.File.OpenRead();
                System.IO.FileInfo file = ofd.File;

                try
                {
                    TB_FilePath.Text = file.FullName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error reading saved variable file: " + ex.Message);
                }
            }
        }
	}
}


text:
                View Received Items

                View Stored Items

                    Truck ID
                    Truck Status
                    Number of Items
                    Action

                    {{pdt.truckID}}
                    {{pdt.status}}
                    {{pdt.noOfItems}}
                    View Items


text:
var PowerMate = require('./powermate');

var powerMate;
for (var i = 0; i < PowerMate.deviceCount(); i++) {

    console.log('opening powermate', i);

    powerMate = new PowerMate.PowerMate(i);

    powerMate.on('buttonDown', function () {
	    console.log('button down');
	    this.position = 0;
	});

    powerMate.on('buttonUp', function () {
	    console.log('button up');
	});

    powerMate.on('turn', function (delta, position) {
	    console.log('delta', delta, 'position', position);
	    this.setLed(position % 256);
	});
}


text:
package org.apache.sis.test;

import java.util.Set;
import java.util.Map;
import java.util.Objects;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.LinkedHashMap;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.swing.tree.TreeNode;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.apache.sis.util.Utilities;
import org.apache.sis.util.CharSequences;
import org.apache.sis.util.ComparisonMode;
import org.apache.sis.util.Exceptions;
import org.apache.sis.util.Classes;

/**
 * Assertion methods used by the SIS project in addition of the JUnit and GeoAPI assertions.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @author  Alexis Manin (Geomatys)
 * @version 0.8
 * @since   0.3
 * @module
 */
public strictfp class Assert extends org.opengis.test.Assert {
    /**
     * For subclass constructor only.
     */
    protected Assert() {
    }

    /**
     * Asserts that the two given objects are not equal.
     * This method tests all {@link ComparisonMode} except {@code DEBUG}.
     *
     * @param  o1  the first object.
     * @param  o2  the second object.
     */
    public static void assertNotDeepEquals(final Object o1, final Object o2) {
        assertNotSame("same", o1, o2);
        assertFalse("equals",                      Objects  .equals    (o1, o2));
        assertFalse("deepEquals",                  Objects  .deepEquals(o1, o2));
        assertFalse("deepEquals(STRICT)",          Utilities.deepEquals(o1, o2, ComparisonMode.STRICT));
        assertFalse("deepEquals(BY_CONTRACT)",     Utilities.deepEquals(o1, o2, ComparisonMode.BY_CONTRACT));
        assertFalse("deepEquals(IGNORE_METADATA)", Utilities.deepEquals(o1, o2, ComparisonMode.IGNORE_METADATA));
        assertFalse("deepEquals(APPROXIMATIVE)",   Utilities.deepEquals(o1, o2, ComparisonMode.APPROXIMATIVE));
    }

    /**
     * Asserts that the two given objects are approximatively equal, while slightly different.
     * More specifically, this method asserts that the given objects are equal according the
     * {@link ComparisonMode#APPROXIMATIVE} criterion, but not equal according the
     * {@link ComparisonMode#IGNORE_METADATA} criterion.
     *
     * @param  expected  the expected object.
     * @param  actual    the actual object.
     */
    public static void assertAlmostEquals(final Object expected, final Object actual) {
        assertFalse("Shall not be strictly equals",          Utilities.deepEquals(expected, actual, ComparisonMode.STRICT));
        assertFalse("Shall be slightly different",           Utilities.deepEquals(expected, actual, ComparisonMode.IGNORE_METADATA));
        assertTrue ("Shall be approximatively equals",       Utilities.deepEquals(expected, actual, ComparisonMode.DEBUG));
        assertTrue ("DEBUG inconsistent with APPROXIMATIVE", Utilities.deepEquals(expected, actual, ComparisonMode.APPROXIMATIVE));
    }

    /**
     * Asserts that the two given objects are equal ignoring metadata.
     * See {@link ComparisonMode#IGNORE_METADATA} for more information.
     *
     * @param  expected  the expected object.
     * @param  actual    the actual object.
     */
    public static void assertEqualsIgnoreMetadata(final Object expected, final Object actual) {
        assertTrue("Shall be approximatively equals",       Utilities.deepEquals(expected, actual, ComparisonMode.DEBUG));
        assertTrue("DEBUG inconsistent with APPROXIMATIVE", Utilities.deepEquals(expected, actual, ComparisonMode.APPROXIMATIVE));
        assertTrue("Shall be equal, ignoring metadata",     Utilities.deepEquals(expected, actual, ComparisonMode.IGNORE_METADATA));
    }

    /**
     * Asserts that the two given arrays contains objects that are equal ignoring metadata.
     * See {@link ComparisonMode#IGNORE_METADATA} for more information.
     *
     * @param  expected  the expected objects (array can be {@code null}).
     * @param  actual    the actual objects (array can be {@code null}).
     *
     * @since 0.7
     */
    public static void assertArrayEqualsIgnoreMetadata(final Object[] expected, final Object[] actual) {
        if (expected != actual) {
            if (expected == null) {
                assertNull("Expected null array.", actual);
            } else {
                assertNotNull("Expected non-null array.", actual);
                final int length = StrictMath.min(expected.length, actual.length);
                for (int i=0; i<length; i++) try {
                    assertEqualsIgnoreMetadata(expected[i], actual[i]);
                } catch (AssertionError e) {
                    throw new AssertionError(Exceptions.formatChainedMessages(null, "Comparison failure at index "
                            + i + " (a " + Classes.getShortClassName(actual[i]) + ").", e), e);
                }
                assertEquals("Unexpected array length.", expected.length, actual.length);
            }
        }
    }

    /**
     * Asserts that two strings are equal, ignoring the differences in EOL characters.
     * The comparisons is performed one a line-by-line basis. For each line, trailing
     * spaces (but not leading spaces) are ignored.
     *
     * @param  expected  the expected string.
     * @param  actual    the actual string.
     */
    public static void assertMultilinesEquals(final CharSequence expected, final CharSequence actual) {
        assertMultilinesEquals(null, expected, actual);
    }

    /**
     * Asserts that two strings are equal, ignoring the differences in EOL characters.
     * The comparisons is performed one a line-by-line basis. For each line, trailing
     * spaces (but not leading spaces) are ignored.
     *
     * @param  message   the message to print in case of failure, or {@code null} if none.
     * @param  expected  the expected string.
     * @param  actual    the actual string.
     */
    public static void assertMultilinesEquals(final String message, final CharSequence expected, final CharSequence actual) {
        final CharSequence[] expectedLines = CharSequences.splitOnEOL(expected);
        final CharSequence[] actualLines   = CharSequences.splitOnEOL(actual);
        final int length = StrictMath.min(expectedLines.length, actualLines.length);
        final StringBuilder buffer = new StringBuilder(message != null ? message : "Line").append('[');
        final int base = buffer.length();
        for (int i=0; i<length; i++) {
            CharSequence e = expectedLines[i];
            CharSequence a = actualLines[i];
            e = e.subSequence(0, CharSequences.skipTrailingWhitespaces(e, 0, e.length()));
            a = a.subSequence(0, CharSequences.skipTrailingWhitespaces(a, 0, a.length()));
            assertEquals(buffer.append(i).append(']').toString(), e, a);
            buffer.setLength(base);
        }
        if (expectedLines.length > actualLines.length) {
            fail(buffer.append(length).append("] missing line: ").append(expectedLines[length]).toString());
        }
        if (expectedLines.length < actualLines.length) {
            fail(buffer.append(length).append("] extraneous line: ").append(actualLines[length]).toString());
        }
    }

    /**
     * Asserts that the given set contains the same elements, ignoring order.
     * In case of failure, this method lists the missing or unexpected elements.
     *
     *
The given collections are typically instances of {@link Set}, but this is not mandatory.

     *
     * @param  expected  the expected set, or {@code null}.
     * @param  actual    the actual set, or {@code null}.
     */
    public static void assertSetEquals(final Collection<?> expected, final Collection<?> actual) {
        if (expected != null && actual != null && !expected.isEmpty()) {
            final Set<Object> r = new LinkedHashSet<Object>(expected);
            assertTrue("The two sets are disjoint.",                 r.removeAll(actual));
            assertTrue("The set is missing elements: " + r,          r.isEmpty());
            assertTrue("The set unexpectedly became empty.",         r.addAll(actual));
            assertTrue("The two sets are disjoint.",                 r.removeAll(expected));
            assertTrue("The set contains unexpected elements: " + r, r.isEmpty());
        }
        if (expected instanceof Set<?> && actual instanceof Set<?>) {
            assertEquals("Set.equals(Object) failed:", expected, actual);
        }
    }

    /**
     * Asserts that the given map contains the same entries.
     * In case of failure, this method lists the missing or unexpected entries.
     *
     * @param  expected  the expected map, or {@code null}.
     * @param  actual    the actual map, or {@code null}.
     */
    public static void assertMapEquals(final Map<?,?> expected, final Map<?,?> actual) {
        if (expected != null && actual != null && !expected.isEmpty()) {
            final Map<Object,Object> r = new LinkedHashMap<Object,Object>(expected);
            for (final Map.Entry<?,?> entry : actual.entrySet()) {
                final Object key = entry.getKey();
                if (!r.containsKey(key)) {
                    fail("Unexpected entry for key " + key);
                }
                final Object ve = r.remove(key);
                final Object va = entry.getValue();
                if (!Objects.equals(ve, va)) {
                    fail("Wrong value for key " + key + ": expected " + ve + " but got " + va);
                }
            }
            if (!r.isEmpty()) {
                fail("The map is missing entries: " + r);
            }
            r.putAll(actual);
            for (final Map.Entry<?,?> entry : expected.entrySet()) {
                final Object key = entry.getKey();
                if (!r.containsKey(key)) {
                    fail("Missing an entry for key " + key);
                }
                final Object ve = entry.getValue();
                final Object va = r.remove(key);
                if (!Objects.equals(ve, va)) {
                    fail("Wrong value for key " + key + ": expected " + ve + " but got " + va);
                }
            }
            if (!r.isEmpty()) {
                fail("The map contains unexpected elements:" + r);
            }
        }
        assertEquals("Map.equals(Object) failed:", expected, actual);
    }

    /**
     * Ensures that a tree is equals to an other tree.
     * This method invokes itself recursively for every child nodes.
     *
     * @param  expected  the expected tree, or {@code null}.
     * @param  actual    the tree to compare with the expected one, or {@code null}.
     * @return the number of nodes.
     */
    public static int assertTreeEquals(final TreeNode expected, final TreeNode actual) {
        if (expected == null) {
            assertNull(actual);
            return 0;
        }
        int n = 1;
        assertNotNull(actual);
        assertEquals("isLeaf()",            expected.isLeaf(),            actual.isLeaf());
        assertEquals("getAllowsChildren()", expected.getAllowsChildren(), actual.getAllowsChildren());
        assertEquals("getChildCount()",     expected.getChildCount(),     actual.getChildCount());
        @SuppressWarnings("unchecked") final Enumeration<? extends TreeNode> ec = expected.children();
        @SuppressWarnings("unchecked") final Enumeration<? extends TreeNode> ac = actual  .children();

        int childIndex = 0;
        while (ec.hasMoreElements()) {
            assertTrue("hasMoreElements()", ac.hasMoreElements());
            final TreeNode nextExpected = ec.nextElement();
            final TreeNode nextActual   = ac.nextElement();
            final String message = "getChildAt(" + childIndex + ')';
            assertSame(message, nextExpected, expected.getChildAt(childIndex));
            assertSame(message, nextActual,   actual  .getChildAt(childIndex));
            assertSame("getParent()", expected, nextExpected.getParent());
            assertSame("getParent()", actual,   nextActual  .getParent());
            assertSame("getIndex(TreeNode)", childIndex, expected.getIndex(nextExpected));
            assertSame("getIndex(TreeNode)", childIndex, actual  .getIndex(nextActual));
            n += assertTreeEquals(nextExpected, nextActual);
            childIndex++;
        }
        assertFalse("hasMoreElements()", ac.hasMoreElements());
        assertEquals("toString()", expected.toString(), actual.toString());
        return n;
    }

    /**
     * Parses two XML trees as DOM documents, and compares the nodes.
     * The inputs given to this method can be any of the following types:
     *
     *

     *
{@link org.w3c.dom.Node}: used directly without further processing.

     *
{@link java.io.File}, {@link java.net.URL} or {@link java.net.URI}: the
     *       stream is opened and parsed as a XML document.

     *
{@link String}: The string content is parsed directly as a XML document.

     *

     *
     * The comparison will ignore comments and the optional attributes given in arguments.
     *
     *
Ignored attributes substitution

     * For convenience, this method replaces some well known prefixes in the {@code ignoredAttributes}
     * array by their full namespace URLs. For example this method replaces{@code "xsi:schemaLocation"}
     * by {@code "http://www.w3.org/2001/XMLSchema-instance:schemaLocation"}.
     * If such substitution is not desired, consider using {@link XMLComparator} directly instead.
     *
     *
The current substitution map is as below (may be expanded in any future SIS version):

     *
     *

     *
Predefined prefix mapping

     *
Prefix	 URL

     *
xmlns	  {@code "http://www.w3.org/2000/xmlns"}

     *
xlink	  {@value org.apache.sis.xml.Namespaces#XLINK}

     *
xsi	    {@value org.apache.sis.xml.Namespaces#XSI}

     *
gml	    {@value org.apache.sis.xml.Namespaces#GML}

     *
gmd	    {@value org.apache.sis.xml.Namespaces#GMD}

     *
gmx	    {@value org.apache.sis.xml.Namespaces#GMX}

     *
gmi	    {@value org.apache.sis.xml.Namespaces#GMI}

     *
gco	    {@value org.apache.sis.xml.Namespaces#GCO}

     *

     *
     *
For example in order to ignore the namespace, type and schema location declaration,
     * the following strings can be given to the {@code ignoredAttributes} argument:

     *
     * {@preformat text
     *   "xmlns:*", "xsi:schemaLocation", "xsi:type"
     * }
     *
     * @param  expected           the expected XML document.
     * @param  actual             the XML document to compare.
     * @param  ignoredAttributes  the fully-qualified names of attributes to ignore
     *                            (typically {@code "xmlns:*"} and {@code "xsi:schemaLocation"}).
     *
     * @see XMLComparator
     */
    public static void assertXmlEquals(final Object expected, final Object actual, final String... ignoredAttributes) {
        assertXmlEquals(expected, actual, TestCase.STRICT, null, ignoredAttributes);
    }

    /**
     * Parses two XML trees as DOM documents, and compares the nodes with the given tolerance
     * threshold for numerical values. The inputs given to this method can be any of the types
     * documented {@linkplain #assertXmlEquals(Object, Object, String[]) above}. This method
     * will ignore comments and the optional attributes given in arguments as documented in the
     * above method.
     *
     * @param  expected           the expected XML document.
     * @param  actual             the XML document to compare.
     * @param  tolerance          the tolerance threshold for comparison of numerical values.
     * @param  ignoredNodes       the fully-qualified names of the nodes to ignore, or {@code null} if none.
     * @param  ignoredAttributes  the fully-qualified names of attributes to ignore
     *                            (typically {@code "xmlns:*"} and {@code "xsi:schemaLocation"}).
     *
     * @see XMLComparator
     */
    public static void assertXmlEquals(final Object expected, final Object actual,
            final double tolerance, final String[] ignoredNodes, final String[] ignoredAttributes)
    {
        final XMLComparator comparator;
        try {
            comparator = new XMLComparator(expected, actual);
        } catch (IOException | ParserConfigurationException | SAXException e) {
            // We don't throw directly those exceptions since failing to parse the XML file can
            // be considered as part of test failures and the JUnit exception for such failures
            // is AssertionError. Having no checked exception in "assert" methods allow us to
            // declare the checked exceptions only for the library code being tested.
            throw new AssertionError(e);
        }
        comparator.tolerance = tolerance;
        comparator.ignoreComments = true;
        if (ignoredNodes != null) {
            for (final String node : ignoredNodes) {
                comparator.ignoredNodes.add(XMLComparator.substitutePrefix(node));
            }
        }
        if (ignoredAttributes != null) {
            for (final String attribute : ignoredAttributes) {
                comparator.ignoredAttributes.add(XMLComparator.substitutePrefix(attribute));
            }
        }
        comparator.compare();
    }

    /**
     * Serializes the given object in memory, deserializes it and ensures that the deserialized
     * object is equals to the original one. This method does not write anything to the disk.
     *
     *
If the serialization fails, then this method throws an {@link AssertionError}
     * as do the other JUnit assertion methods.

     *
     * @param  <T>     the type of the object to serialize.
     * @param  object  the object to serialize.
     * @return the deserialized object.
     */
    public static <T> T assertSerializedEquals(final T object) {
        final Object deserialized;
        try {
            final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {
                out.writeObject(object);
            }
            // Now reads the object we just serialized.
            final byte[] data = buffer.toByteArray();
            try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
                try {
                    deserialized = in.readObject();
                } catch (ClassNotFoundException e) {
                    throw new AssertionError(e);
                }
            }
        } catch (IOException e) {
            throw new AssertionError(e.toString(), e);
        }
        // Compares with the original object and returns it.
        @SuppressWarnings("unchecked")
        final Class<? extends T> type = (Class<? extends T>) object.getClass();
        assertEquals("Deserialized object not equal to the original one.", object, deserialized);
        assertEquals("Deserialized object has a different hash code.",
                object.hashCode(), deserialized.hashCode());
        return type.cast(deserialized);
    }
}


text:
layout: horoscopo_chino_anual
title: Liebre Horóscopo Chino 2022
permalink: /año-nuevo-chino/liebre/
amplink: /año-nuevo-chino/amp/liebre/
redirect_from: /p/horoscopo-chino-liebre-2015.html
description: En comparación con 2021, 2022 (año del Tigre) será un año mejor para el Conejo. El Conejo seguirá encontrando algunos problemas, pero no son graves y se resolverán rápidamente. Se espera una vida más tranquila.
ogimg: /images/liebre_anual.png
sitemap:
 priority: 1
 changefreq: 'yearly'
 lastmod: 2022-02-01
---

En comparación con 2021, 2022 (año del Tigre) será un año mejor para el Conejo. El Conejo seguirá encontrando algunos problemas, pero no son graves y se resolverán rápidamente. Se espera una vida más tranquila.

2022 es un buen año para que el Conejo se case, compre una casa o dé a luz a un bebé. Hacer algunos cambios en la vida traerá suerte a la familia y a los negocios.

## Años de Nacimiento del Conejo
 - Conejo de Tierra: 1939, 1999
 - Conejo de Metal: 1951, 2011
 - Conejo de Agua: 1963, 2023
 - Conejo de Madera: 1975
 - Conejo de Fuego: 1987

## Amor
Después de experimentar relaciones infructuosas en la etapa anterior, los Conejos tendrán suerte en el amor en 2022, y sus posibilidades de casarse serán muy altas. Conocerá a una pareja cuya educación, personalidad y otros atributos le resulten muy adecuados.

Conejos, si su estado de soltería no ha cambiado durante mucho tiempo, puede pedir a sus mayores que le ayuden a presentar a un miembro del sexo opuesto. Las posibilidades de éxito de una cita a ciegas serán muy altas.

Los Conejos solteros tendrán una relación breve.

Los Conejos casados, ante la tentación del sexo opuesto, deben ser firmes en su corazón y no ser infieles a su otra mitad.

## Trabajo
Gente de conejo, la suerte de su carrera será bastante buena este año, y su estatus acabará por subir, pero debe ceñirse a su papel y hacer bien sus propias tareas en previsión.

Si quiere cambiar de trabajo este año, se recomienda encontrar su próximo hogar antes de dejar su trabajo. La inestabilidad de la suerte puede interferir en sus planes, por lo que debe reflexionar cuidadosamente antes de tomar cualquier decisión.

## Salud
Conejos, este año su socialización será constante. Además del trabajo y la socialización, los buenos amigos se reunirán durante tres días, comiendo, bebiendo y divirtiéndose, cada uno hablando libremente y revelando a sus amigos su infelicidad en la vida y el trabajo. Un tiempo de descanso insuficiente afectará a su eficacia laboral. Es necesario ajustar adecuadamente el tiempo que dedica a comer y descansar y mantener la energía para completar mejor las tareas que le asignen sus dirigentes.

Es posible que este año tenga una operación menor, pero no tendrá mucha repercusión. Mientras cuide su cuerpo y se tome las cosas con calma, se recuperará poco a poco.

Conejos conductores, este año deben conducir con precaución y respetar las normas de tráfico. No debe saltarse un semáforo en rojo cuando tenga prisa para evitar el riesgo de detracción de puntos y multas.


text:
GIRL

Let me tell you something.

GUY

I don't wanna.


text:
package com.faforever.client.game;

import com.faforever.client.fx.Controller;
import com.faforever.client.fx.JavaFxUtil;
import com.faforever.client.preferences.PreferencesService;
import com.faforever.client.theme.UiService;
import com.google.common.annotations.VisibleForTesting;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.WeakChangeListener;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.WeakListChangeListener;
import javafx.scene.Node;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.FlowPane;
import lombok.Getter;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
public class GamesTilesContainerController implements Controller<Node> {

  private final UiService uiService;
  private final ListChangeListener<Game> gameListChangeListener;
  private final PreferencesService preferencesService;
  public FlowPane tiledFlowPane;
  public ScrollPane tiledScrollPane;
  private final ChangeListener<? super TilesSortingOrder> sortingListener;
  private ObjectProperty<Game> selectedGame;
  private Comparator<Node> appliedComparator;
  @VisibleForTesting
  Map<Integer, Node> uidToGameCard;

  @Inject
  public GamesTilesContainerController(UiService uiService, PreferencesService preferencesService) {
    this.uiService = uiService;
    this.preferencesService = preferencesService;
    selectedGame = new SimpleObjectProperty<>();

    sortingListener = (observable, oldValue, newValue) -> {
      if (newValue == null) {
        return;
      }
      preferencesService.getPreferences().setGameTileSortingOrder(newValue);
      preferencesService.storeInBackground();
      appliedComparator = newValue.getComparator();
      sortNodes();
    };

    gameListChangeListener = change -> Platform.runLater(() -> {
      synchronized (change.getList()) {
        while (change.next()) {
          change.getRemoved().forEach(gameInfoBean -> tiledFlowPane.getChildren().remove(uidToGameCard.remove(gameInfoBean.getId())));
          change.getAddedSubList().forEach(GamesTilesContainerController.this::addGameCard);
        }
        sortNodes();
      }
    });
  }

  private void sortNodes() {
    ObservableList<Node> sortedChildren = tiledFlowPane.getChildren().sorted(appliedComparator);
    tiledFlowPane.getChildren().setAll(sortedChildren);
  }

  public void initialize() {
    JavaFxUtil.fixScrollSpeed(tiledScrollPane);
  }

  ReadOnlyObjectProperty<Game> selectedGameProperty() {
    return this.selectedGame;
  }

  @VisibleForTesting
  void createTiledFlowPane(ObservableList<Game> games, ChoiceBox<TilesSortingOrder> choseSortingTypeChoiceBox) {
    initializeChoiceBox(choseSortingTypeChoiceBox);
    uidToGameCard = new HashMap<>();
    games.forEach(this::addGameCard);
    games.addListener(new WeakListChangeListener<>(gameListChangeListener));
    selectFirstGame();
    sortNodes();
  }

  private void initializeChoiceBox(ChoiceBox<TilesSortingOrder> choseSortingTypeChoiceBox) {
    choseSortingTypeChoiceBox.setVisible(true);
    choseSortingTypeChoiceBox.getItems().addAll(TilesSortingOrder.values());
    choseSortingTypeChoiceBox.getSelectionModel().selectedItemProperty().addListener(new WeakChangeListener<>(sortingListener));
    choseSortingTypeChoiceBox.getSelectionModel().select(preferencesService.getPreferences().getGameTileSortingOrder());
  }

  private void selectFirstGame() {
    ObservableList<Node> cards = tiledFlowPane.getChildren();
    if (!cards.isEmpty()) {
      selectedGame.set((Game) cards.get(0).getUserData());
    }
  }

  private void addGameCard(Game game) {
    GameTileController gameTileController = uiService.loadFxml("theme/play/game_card.fxml");
    gameTileController.setGame(game);
    gameTileController.setOnSelectedListener(selection -> selectedGame.set(selection));

    Node root = gameTileController.getRoot();
    root.setUserData(game);
    tiledFlowPane.getChildren().add(root);
    uidToGameCard.put(game.getId(), root);
  }

  public Node getRoot() {
    return tiledScrollPane;
  }

  public enum TilesSortingOrder {
    PLAYER_DES(Comparator.comparingInt(o -> ((Game) o.getUserData()).getNumPlayers()), true, "tiles.comparator.playersDescending"),
    PLAYER_ASC(Comparator.comparingInt(o -> ((Game) o.getUserData()).getNumPlayers()), false, "tiles.comparator.playersAscending"),
    NAME_DES(Comparator.comparing(o -> ((Game) o.getUserData()).getTitle().toLowerCase(Locale.US)), true, "tiles.comparator.nameDescending"),
    NAME_ASC(Comparator.comparing(o -> ((Game) o.getUserData()).getTitle().toLowerCase(Locale.US)), false, "tiles.comparator.nameAscending");

    @Getter
    private final Comparator<Node> comparator;
    @Getter
    private final String displayNameKey;

    TilesSortingOrder(Comparator<Node> comparator, boolean reversed, String displayNameKey) {
      this.displayNameKey = displayNameKey;
      this.comparator = reversed ? comparator.reversed() : comparator;
    }
  }

}


text:
using namespace __xray;
using namespace __sanitizer;

template <class T> static T *allocRaw(size_t N) {
  // TODO: Report errors?
  // We use MAP_NORESERVE on platforms where it's supported to ensure that the
  // pages we're allocating for XRay never end up in pages that can be swapped
  // in/out. We're doing this because for FDR mode, we want to ensure that
  // writes to the buffers stay resident in memory to prevent XRay itself from
  // causing swapping/thrashing.
  //
  // In the case when XRay pages cannot be swapped in/out or there's not enough
  // RAM to back these pages, we're willing to cause a segmentation fault
  // instead of introducing latency in the measurement. We assume here that
  // there are enough pages that are swappable in/out outside of the buffers
  // being used by FDR mode (which are bounded and configurable anyway) to allow
  // us to keep using always-resident memory.
  //
  // TODO: Make this configurable?
  void *A = reinterpret_cast<void *>(
      internal_mmap(NULL, N * sizeof(T), PROT_WRITE | PROT_READ,
                    MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE, -1, 0));
  return (A == MAP_FAILED) ? nullptr : reinterpret_cast<T *>(A);
}

template <class T> static void deallocRaw(T *ptr, size_t N) {
  // TODO: Report errors?
  if (ptr != nullptr)
    internal_munmap(ptr, N);
}

template <class T> static T *initArray(size_t N) {
  auto A = allocRaw<T>(N);
  if (A != nullptr)
    while (N > 0)
      new (A + (--N)) T();
  return A;
}

BufferQueue::BufferQueue(size_t B, size_t N, bool &Success)
    : BufferSize(B), Buffers(initArray<BufferQueue::BufferRep>(N)),
      BufferCount(N), Finalizing{0}, OwnedBuffers(initArray<void *>(N)),
      Next(Buffers), First(Buffers), LiveBuffers(0) {
  if (Buffers == nullptr) {
    Success = false;
    return;
  }
  if (OwnedBuffers == nullptr) {
    // Clean up the buffers we've already allocated.
    for (auto B = Buffers, E = Buffers + BufferCount; B != E; ++B)
      B->~BufferRep();
    deallocRaw(Buffers, N);
    Success = false;
    return;
  };

  for (size_t i = 0; i < N; ++i) {
    auto &T = Buffers[i];
    void *Tmp = allocRaw<char>(BufferSize);
    if (Tmp == nullptr) {
      Success = false;
      return;
    }
    auto *Extents = allocRaw<BufferExtents>(1);
    if (Extents == nullptr) {
      Success = false;
      return;
    }
    auto &Buf = T.Buff;
    Buf.Data = Tmp;
    Buf.Size = B;
    Buf.Extents = Extents;
    OwnedBuffers[i] = Tmp;
  }
  Success = true;
}

BufferQueue::ErrorCode BufferQueue::getBuffer(Buffer &Buf) {
  if (atomic_load(&Finalizing, memory_order_acquire))
    return ErrorCode::QueueFinalizing;
  SpinMutexLock Guard(&Mutex);
  if (LiveBuffers == BufferCount)
    return ErrorCode::NotEnoughMemory;

  auto &T = *Next;
  auto &B = T.Buff;
  Buf = B;
  T.Used = true;
  ++LiveBuffers;

  if (++Next == (Buffers + BufferCount))
    Next = Buffers;

  return ErrorCode::Ok;
}

BufferQueue::ErrorCode BufferQueue::releaseBuffer(Buffer &Buf) {
  // Blitz through the buffers array to find the buffer.
  bool Found = false;
  for (auto I = OwnedBuffers, E = OwnedBuffers + BufferCount; I != E; ++I) {
    if (*I == Buf.Data) {
      Found = true;
      break;
    }
  }
  if (!Found)
    return ErrorCode::UnrecognizedBuffer;

  SpinMutexLock Guard(&Mutex);

  // This points to a semantic bug, we really ought to not be releasing more
  // buffers than we actually get.
  if (LiveBuffers == 0)
    return ErrorCode::NotEnoughMemory;

  // Now that the buffer has been released, we mark it as "used".
  First->Buff = Buf;
  First->Used = true;
  Buf.Data = nullptr;
  Buf.Size = 0;
  --LiveBuffers;
  if (++First == (Buffers + BufferCount))
    First = Buffers;

  return ErrorCode::Ok;
}

BufferQueue::ErrorCode BufferQueue::finalize() {
  if (atomic_exchange(&Finalizing, 1, memory_order_acq_rel))
    return ErrorCode::QueueFinalizing;
  return ErrorCode::Ok;
}

BufferQueue::~BufferQueue() {
  for (auto I = Buffers, E = Buffers + BufferCount; I != E; ++I) {
    auto &T = *I;
    auto &Buf = T.Buff;
    deallocRaw(Buf.Data, Buf.Size);
    deallocRaw(Buf.Extents, 1);
  }
  for (auto B = Buffers, E = Buffers + BufferCount; B != E; ++B)
    B->~BufferRep();
  deallocRaw(Buffers, BufferCount);
  deallocRaw(OwnedBuffers, BufferCount);
}


text:
package org.apache.causeway.core.metamodel.facets.object.projection.ident;

import java.util.function.BiConsumer;

import org.apache.causeway.core.metamodel.facetapi.FacetHolder;
import org.apache.causeway.core.metamodel.facets.members.cssclass.CssClassFacet;
import org.apache.causeway.core.metamodel.facets.members.cssclass.CssClassFacetAbstract;
import org.apache.causeway.core.metamodel.facets.object.projection.ProjectionFacet;
import org.apache.causeway.core.metamodel.object.ManagedObject;

import lombok.val;

public class CssClassFacetFromProjectionFacet
extends CssClassFacetAbstract {

    private final ProjectionFacet projectionFacet;

    public CssClassFacetFromProjectionFacet(
            final ProjectionFacet projectionFacet,
            final FacetHolder holder) {
        super(holder);
        this.projectionFacet = projectionFacet;
    }

    @Override
    public String cssClass(final ManagedObject targetAdapter) {
        val projectedAdapter = projectionFacet.projected(targetAdapter);
        val cssClassFacet = projectedAdapter.getSpecification().getFacet(CssClassFacet.class);
        return cssClassFacet != null
                ? cssClassFacet.cssClass(projectedAdapter)
                : null;
    }

    @Override
    public void visitAttributes(final BiConsumer<String, Object> visitor) {
        super.visitAttributes(visitor);
        visitor.accept("projectionFacet", projectionFacet.getClass().getName());
    }

}


text:
import numpy as np
import os
import pickle
import networkx as nx
from matplotlib import pyplot as plt
import argparse

def parse_cmdline_args():
    parser = argparse.ArgumentParser(description='Parser for location phrase generation')
    parser.add_argument('--input_pred_dir', type = str,
                        default = '/data/zekunl/text_linking/pred_scripts/predictions_v1_20_od/') # output from the step2
    parser.add_argument('--vision_api_result_dir', type = str,
                        default = '/data/zekunl/Geolocalizer/google_grouping/') # dir that stores word list
    parser.add_argument('--IF_WCC', action = 'store_true') # use weakly connected component or strongly connected componnet
    parser.add_argument('--output_phrases_dir', type = str, default = 'phrases_v1_20_od/') # output folder for step3
    return (parser.parse_args())

# remove empty prediction
def remove_empty_neighbors(predictions):
    preds = {}
    for anchor_idx, pred in predictions.items():
        pred = list(pred)
        if anchor_idx in pred:
            pred.remove(anchor_idx)
        if len(pred) != 0:
            preds[anchor_idx] = pred
    return preds

# remove itself from prediction
def remove_self_neighbors(predictions):
    preds = {}
    for anchor_idx, pred in predictions.items():
        pred = list(pred)
        if anchor_idx in pred:
            pred.remove(anchor_idx)

        preds[anchor_idx] = pred
    return preds

def construct_graph_cc_from_neighbor_dict(neighbor_dict, IF_WCC):
    #neighbors = remove_empty_neighbors(neighbor_dict) # neighbor is still a dictionary with empty neighbors removed
    neighbors = remove_self_neighbors(neighbor_dict) # dictionary with itself removed from neighbor list
    #neighbors = neighbor_dict

    G = nx.DiGraph()
    G.add_nodes_from(neighbors.keys())

    #print neighbors.keys()
    for anchor_idx, nei in neighbors.items():
        for n in nei:
            G.add_edge(anchor_idx, n)

    '''
    print("Nodes of graph: ")
    print(G.nodes())
    print("Edges of graph: ")
    print(G.edges())
    '''
    if IF_WCC:
        components = nx.weakly_connected_components(G)
    else:
        components = nx.strongly_connected_components(G)

    cc = []
    for nodes in components:
        cc.append(list(nodes))

    return G, cc

def show_cc(pred_cc):
    for com in pred_cc:
        for i in range(len(com)):
            plt.subplot(1, len(com), i+1)
            plt.imshow(img[com[i]])

        plt.show()

def give_phrase_baseline(loc_array, text_content, pred_cc):
    pred_names = []
    for com in pred_cc:
        # sort according to x and y
        x_list, y_list = [],[]
        for i in range(len(com)):
            x,y = loc_array[i]
            x_list.append(x)
            y_list.append(y)

        x_indices = np.argsort(x_list)
        y_indices = np.argsort(y_list)

        #print x_indices
        #print y_indices
        #print np.array(x_list)[x_indices]

        cur_name = []
        for i in range(len(com)):
            cur_name.append(text_content[com[x_indices[i]]])
        cur_name = " ".join(cur_name)
        pred_names.append(cur_name)

    return pred_names

def give_phrase_indices_baseline(loc_array, pred_cc):
    pred_names = []
    for com in pred_cc:
        # sort according to x and y
        x_list, y_list = [],[]
        for i in range(len(com)):
            x,y = loc_array[i]
            x_list.append(x)
            y_list.append(y)

        x_indices = np.argsort(x_list)
        y_indices = np.argsort(y_list)

        cur_name = []
        for i in range(len(com)):
            #print text_content[com[x_indices[i]]]
            cur_name.append(com[x_indices[i]])
        pred_names.append(cur_name)

    return pred_names

def main(args):

    input_pred_dir = args.input_pred_dir
    vision_api_result_dir = args.vision_api_result_dir
    IF_WCC = args.IF_WCC # compute weakly connected component or strongly connected component
    output_phrases_dir = args.output_phrases_dir

    if not os.path.isdir(output_phrases_dir):
        os.makedirs(output_phrases_dir)

    map_names_list = [os.path.basename(a)[11:-4] for a in os.listdir(input_pred_dir)] # remove 'step2_pred_' prefix
    for map_name in map_names_list:
        pred_path = input_pred_dir + 'step2_pred_' + map_name + '.pkl'
        #gt_path = '/home/zekunl/preprocess_map/neighbors_dict_v3/neighbors_' + map_name + '.pkl'
        #text_path = '/home/zekunl/preprocess_map/text_dict_v3/text_' + map_name + '.pkl'
        #loc_path = '/home/zekunl/preprocess_map/loc_dict_v3/loc_' + map_name + '.pkl'
        pred_text_content_path = vision_api_result_dir + '/word_list/'
        pred_loc_array = vision_api_result_dir + '/word_coords_list/'
        phrase_path = '/home/zekunl/preprocess_map/location_names/phrase_' + map_name + '.pkl'
        output_path = output_phrases_dir  + map_name + '.pkl'

        print 'map_name', map_name

        with open(pred_path, 'r') as f:
            predictions = pickle.load(f)

        #with open(gt_path, 'r') as f:
        #    ground_truths = pickle.load(f)

        #with open(text_path, 'r') as f:
        #    text_content =  pickle.load(f)

        #with open(loc_path, 'r') as f:
        #    loc_array =  pickle.load(f)

        with open(phrase_path, 'r') as f:
            phrase_list = pickle.load(f)

        with open(pred_text_content_path + 'pkl2_'+ map_name + '.pkl', 'rb') as f:
            pred_text_content = pickle.load(f)

        with open(pred_loc_array +'pkl2_'+ map_name + '.pkl', 'rb') as f:
            pred_bbox_array = pickle.load(f)
        assert len(pred_text_content) == len(pred_bbox_array)

        pred_loc_array = []
        for bbox in pred_bbox_array:
            cur_point = np.array(bbox)
            c_x,c_y = np.mean(cur_point, axis = 0)
            pred_loc_array.append([c_x,c_y])

        # generate gt phrase
        loc_strings = []
        for phrase in phrase_list:
            loc_str = " ".join( phrase)
            loc_strings.append(loc_str)

        print 'loc_strings',loc_strings

        # In[182]:

        print 'number of location names', len(loc_strings)

        pred_G, pred_cc = construct_graph_cc_from_neighbor_dict(predictions, IF_WCC)
        #gt_G, gt_cc = construct_graph_cc_from_neighbor_dict(ground_truths, IF_WCC)

        pred_names = give_phrase_baseline(pred_loc_array, pred_text_content,pred_cc)
        #pred_indices = give_phrase_indices_baseline(loc_array,pred_cc)

        print pred_names
        '''
        #intersection_sets = set(tuple(cc) for cc in pred_cc).intersection(set(tuple(cc) for cc in gt_cc))
        #print 'unordered set recall', 1. *len(intersection_sets)/len(gt_cc), 'numbers:', len(intersection_sets)

        # In[189]:

        #intersection_sets = set(tuple(cc) for cc in pred_indices).intersection(set(tuple(cc) for cc in gt_cc))
        #print 'phrase precision', 1. *len(intersection_sets)/len(pred_indices), 'numbers:', len(intersection_sets)
        #print 'phrase recall', 1. *len(intersection_sets)/len(gt_cc), 'numbers:', len(intersection_sets)

        # Statistics
        #max_len = max([len(pred_ind) for pred_ind in pred_indices]) # get the maximum length of the location string

        #correct_cnt = [] # finally should have length == max_len, keep the number of correct predictions for all lengths
        #gt_cnt = []

        gt_lens = [len(gcc) for gcc in gt_cc] # length of each string in GT
        correct_lens = [len(inter_str) for inter_str in intersection_sets] # length of each string in prediction
        for le in range(1, max_len+1):
            pred_cur_cnt = len(np.where(np.array(correct_lens) == le)[0])
            gt_cur_cnt = len(np.where(np.array(gt_lens) == le)[0])
            correct_cnt.append(pred_cur_cnt)
            gt_cnt.append(gt_cur_cnt)

        #print correct_cnt
        #:qprint gt_cnt

        for i in range(0, len(correct_cnt) ):
            print 'length == ' + str(i+1)
            if gt_cnt[i] == 0:
                print '# gt = 0'
                break

            print '# correct pred / # gt = ', str(correct_cnt[i]) + ' / '+ str(gt_cnt[i]) +' = ' + str(1. * correct_cnt[i]/gt_cnt[i])

        # In[137]:

        # statistic about missing and adding
        cnt_missing = 0
        cnt_adding = 0
        cnt_len_missing = [0 for i in range(10)]
        cnt_len_adding =[0 for i in range(10)]
        wrong_pred_names = list(set(tuple(cc) for cc in pred_indices) - intersection_sets)
        print 'wrong pred names', wrong_pred_names
        for wrong_cc in wrong_pred_names:
            for gcc in set(tuple(cc) for cc in gt_cc) :
                if set(wrong_cc).issubset(set(gcc)):
                    cnt_missing += 1
                    len_missing = len(gcc) - len(wrong_cc)
                    cnt_len_missing[len_missing-1] += 1
                    print " ".join([text_content[c] for c in wrong_cc]), wrong_cc, '\tmissing '+ str(len_missing) + ' word in\t', " ".join([text_content[c] for c in gcc]),gcc
                    continue
                if set(gcc).issubset( set(wrong_cc)):
                    cnt_adding += 1
                    len_adding = len(wrong_cc) - len(gcc)
                    cnt_len_adding[len_adding -1]+= 1
                    print " ".join([text_content[c] for c in wrong_cc]), wrong_cc, '\tadding ' + str(len_adding) + ' word in\t', " ".join([text_content[c] for c in gcc]), gcc
                    continue

        print 'cnt_missing',cnt_missing
        print 'cnt_adding', cnt_adding
        print 'cnt_len_missing', cnt_len_missing
        print 'cnt_len_adding', cnt_len_adding

        '''

        inter_string = set(pred_names).intersection(set(loc_strings))
        print 'inter string',inter_string

        # In[125]:

        print 'GT distinct # location names', len(set(loc_strings))
        print 'Pred distinct # location names', len(set(pred_names))
        print 'Pred correct # location names', len(inter_string)
        print 'Precision in distinct', 1. * len(inter_string) / len(set(pred_names))
        print 'Recall in distinct', 1. * len(inter_string) / len(set(loc_strings))

        print '\n\n\n'
        with open(output_path, 'wb') as f:
            pickle.dump(pred_names, f)

if __name__ == '__main__':
    args = parse_cmdline_args()
    print (args)
    main(args)


text:
<?php

namespace zzzzbov\pleb;

interface IParser {
    public static function parse($text);
    public static function stringify($obj);
}


text:
#pragma once
#include <aws/workdocs/WorkDocs_EXPORTS.h>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace WorkDocs
{
namespace Model
{
  class AWS_WORKDOCS_API DeleteCustomMetadataResult
  {
  public:
    DeleteCustomMetadataResult();
    DeleteCustomMetadataResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DeleteCustomMetadataResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

  };

} // namespace Model
} // namespace WorkDocs
} // namespace Aws


text:
Numeric extension
=================

Overview
--------

*TODO*


text:
/*this is how to inject pictures into those funny jumbotrons*/
/*LOGIN PAGE*/
.jumbotron {
	align-self: flex-end;
	background: transparent;
	color: #fff;
}
.login {
	background: url("../images/login-page.png") no-repeat;
	min-height: 100vh;
	margin: 0;
	padding: 200px 0 100px;
	color: black;
	background-size: 150%;
}