text:
package org.apache.hc.core5.http;

import java.io.Serializable;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.ThreadingBehavior;
import org.apache.hc.core5.net.Host;
import org.apache.hc.core5.net.NamedEndpoint;
import org.apache.hc.core5.net.URIAuthority;
import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.LangUtils;
import org.apache.hc.core5.util.TextUtils;

/**
 * Component that holds all details needed to describe an HTTP connection
 * to a host. This includes remote host name, port and protocol scheme.
 *
 * @see org.apache.hc.core5.net.Host
 *
 * @since 4.0
 * @since 5.0 For constructors that take a scheme as an argument, that argument is now the first one.
 */
@Contract(threading = ThreadingBehavior.IMMUTABLE)
public final class HttpHost implements NamedEndpoint, Serializable {

    private static final long serialVersionUID = -7529410654042457626L;

    /** The default scheme is "http". */
    public static final URIScheme DEFAULT_SCHEME = URIScheme.HTTP;

    private final String schemeName;
    private final Host host;
    private final InetAddress address;

    /**
     * Creates a new {@link HttpHost HttpHost}, specifying all values.
     * Constructor for HttpHost.
     * @param scheme    the name of the scheme.
     *                  {@code null} indicates the
     *                  {@link #DEFAULT_SCHEME default scheme}
     * @param address   the inet address. Can be {@code null}
     * @param hostname   the hostname (IP or DNS name)
     * @param port      the port number.
     *                  {@code -1} indicates the scheme default port.
     *
     * @throws IllegalArgumentException
     *             If the port parameter is outside the specified range of valid port values, which is between 0 and
     *             65535, inclusive. {@code -1} indicates the scheme default port.
     *
     * @since 5.0
     */
    public HttpHost(final String scheme, final InetAddress address, final String hostname, final int port) {
        Args.containsNoBlanks(hostname, "Host name");
        this.host = new Host(hostname, port);
        this.schemeName = scheme != null ? TextUtils.toLowerCase(scheme) : DEFAULT_SCHEME.id;
        this.address = address;
    }

    /**
     * Creates {@code HttpHost} instance with the given scheme, hostname and port.
     * @param scheme    the name of the scheme.
     *                  {@code null} indicates the
     *                  {@link #DEFAULT_SCHEME default scheme}
     * @param hostname  the hostname (IP or DNS name)
     * @param port      the port number.
     *                  {@code -1} indicates the scheme default port.
     *
     * @throws IllegalArgumentException
     *             If the port parameter is outside the specified range of valid port values, which is between 0 and
     *             65535, inclusive. {@code -1} indicates the scheme default port.
     */
    public HttpHost(final String scheme, final String hostname, final int port) {
        this(scheme, null, hostname, port);
    }

    /**
     * Creates {@code HttpHost} instance with the default scheme and the given hostname and port.
     *
     * @param hostname  the hostname (IP or DNS name)
     * @param port      the port number.
     *                  {@code -1} indicates the scheme default port.
     *
     * @throws IllegalArgumentException
     *             If the port parameter is outside the specified range of valid port values, which is between 0 and
     *             65535, inclusive. {@code -1} indicates the scheme default port.
     */
    public HttpHost(final String hostname, final int port) {
        this(null, hostname, port);
    }

    /**
     * Creates {@code HttpHost} instance with the given hostname and scheme and the default port for that scheme.
     * @param scheme    the name of the scheme.
     *                  {@code null} indicates the
     *                  {@link #DEFAULT_SCHEME default scheme}
     * @param hostname  the hostname (IP or DNS name)
     *
     * @throws IllegalArgumentException
     *             If the port parameter is outside the specified range of valid port values, which is between 0 and
     *             65535, inclusive. {@code -1} indicates the scheme default port.
     */
    public HttpHost(final String scheme, final String hostname) {
        this(scheme, hostname, -1);
    }

    /**
     * Creates {@code HttpHost} instance from a string. Text may not contain any blanks.
     *
     * @since 4.4
     */
    public static HttpHost create(final String s) throws URISyntaxException {
        Args.notEmpty(s, "HTTP Host");
        String text = s;
        String scheme = null;
        final int schemeIdx = text.indexOf("://");
        if (schemeIdx > 0) {
            scheme = text.substring(0, schemeIdx);
            if (TextUtils.containsBlanks(scheme)) {
                throw new URISyntaxException(s, "scheme contains blanks");
            }
            text = text.substring(schemeIdx + 3);
        }
        final Host host = Host.create(text);
        return new HttpHost(scheme, host);
    }

    /**
     * Creates an {@code HttpHost} instance from the scheme, host, and port from the given URI. Other URI elements are ignored.
     *
     * @param uri scheme, host, and port.
     * @return a new HttpHost
     *
     * @since 5.0
     */
    public static HttpHost create(final URI uri) {
        final String scheme = uri.getScheme();
        return new HttpHost(scheme != null ? scheme : URIScheme.HTTP.getId(), uri.getHost(), uri.getPort());
    }

    /**
     * Creates {@code HttpHost} instance with the default scheme and port and the given hostname.
     *
     * @param hostname  the hostname (IP or DNS name)
     *
     * @throws IllegalArgumentException
     *             If the port parameter is outside the specified range of valid port values, which is between 0 and
     *             65535, inclusive. {@code -1} indicates the scheme default port.
     */
    public HttpHost(final String hostname) {
        this(null, hostname, -1);
    }

    /**
     * Creates {@code HttpHost} instance with the given scheme, inet address and port.
     * @param scheme    the name of the scheme.
     *                  {@code null} indicates the
     *                  {@link #DEFAULT_SCHEME default scheme}
     * @param address   the inet address.
     * @param port      the port number.
     *                  {@code -1} indicates the scheme default port.
     *
     * @throws IllegalArgumentException
     *             If the port parameter is outside the specified range of valid port values, which is between 0 and
     *             65535, inclusive. {@code -1} indicates the scheme default port.
     *
     * @since 5.0
     */
    public HttpHost(final String scheme, final InetAddress address, final int port) {
        this(scheme, Args.notNull(address,"Inet address"), address.getHostName(), port);
    }

    /**
     * Creates {@code HttpHost} instance with the default scheme and the given inet address
     * and port.
     *
     * @param address   the inet address.
     * @param port      the port number.
     *                  {@code -1} indicates the scheme default port.
     *
     * @throws IllegalArgumentException
     *             If the port parameter is outside the specified range of valid port values, which is between 0 and
     *             65535, inclusive. {@code -1} indicates the scheme default port.
     *
     * @since 4.3
     */
    public HttpHost(final InetAddress address, final int port) {
        this(null, address, port);
    }

    /**
     * Creates {@code HttpHost} instance with the default scheme and port and the given inet
     * address.
     *
     * @param address   the inet address.
     *
     * @throws IllegalArgumentException
     *             If the port parameter is outside the specified range of valid port values, which is between 0 and
     *             65535, inclusive. {@code -1} indicates the scheme default port.
     *
     * @since 4.3
     */
    public HttpHost(final InetAddress address) {
        this(null, address, -1);
    }

    /**
     * @throws IllegalArgumentException
     *             If the port parameter is outside the specified range of valid port values, which is between 0 and
     *             65535, inclusive. {@code -1} indicates the scheme default port.
     *
     * @since 5.0
     */
    public HttpHost(final String scheme, final NamedEndpoint namedEndpoint) {
        this(scheme, Args.notNull(namedEndpoint, "Named endpoint").getHostName(), namedEndpoint.getPort());
    }

    /**
     * @since 5.0
     *
     * @deprecated Use {@link HttpHost#HttpHost(String, NamedEndpoint)}
     */
    @Deprecated
    public HttpHost(final URIAuthority authority) {
        this(null, authority);
    }

    /**
     * Returns the host name.
     *
     * @return the host name (IP or DNS name)
     */
    @Override
    public String getHostName() {
        return this.host.getHostName();
    }

    /**
     * Returns the port.
     *
     * @return the host port, or {@code -1} if not set
     */
    @Override
    public int getPort() {
        return this.host.getPort();
    }

    /**
     * Returns the scheme name.
     *
     * @return the scheme name
     */
    public String getSchemeName() {
        return this.schemeName;
    }

    /**
     * Returns the inet address if explicitly set by a constructor,
     *   {@code null} otherwise.
     * @return the inet address
     *
     * @since 4.3
     */
    public InetAddress getAddress() {
        return this.address;
    }

    /**
     * Return the host URI, as a string.
     *
     * @return the host URI
     */
    public String toURI() {
        final StringBuilder buffer = new StringBuilder();
        buffer.append(this.schemeName);
        buffer.append("://");
        buffer.append(this.host.toString());
        return buffer.toString();
    }

    /**
     * Obtains the host string, without scheme prefix.
     *
     * @return  the host string, for example {@code localhost:8080}
     */
    public String toHostString() {
        return this.host.toString();
    }

    @Override
    public String toString() {
        return toURI();
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof HttpHost) {
            final HttpHost that = (HttpHost) obj;
            return this.schemeName.equals(that.schemeName) &&
                    this.host.equals(that.host) &&
                    LangUtils.equals(this.address, that.address);
        }
        return false;
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        int hash = LangUtils.HASH_SEED;
        hash = LangUtils.hashCode(hash, this.schemeName);
        hash = LangUtils.hashCode(hash, this.host);
        hash = LangUtils.hashCode(hash, this.address);
        return hash;
    }

}


text:
/* eslint-disable no-console */
import logClientSide from './client-side.js'
import showTags from './tags.js'
import showChunks from './chunks.js'
import showHighlight from './highlight.js'

function isClientSide() {
  return typeof window !== 'undefined' && window.document
}
//output some helpful stuff to the console
const debug = function (opts = {}) {
  let view = this
  if (typeof opts === 'string') {
    let tmp = {}
    tmp[opts] = true //allow string input
    opts = tmp
  }
  if (isClientSide()) {
    logClientSide(view)
    return view
  }
  if (opts.tags !== false) {
    showTags(view)
    console.log('\n')
  }
  // output chunk-view, too
  if (opts.chunks === true) {
    showChunks(view)
    console.log('\n')
  }
  // highlight match in sentence
  if (opts.highlight === true) {
    showHighlight(view)
    console.log('\n')
  }
  return view
}
export default debug

redpajama_set_name: RedPajamaGithub


text:
package com.google.gerrit.client.admin;

import com.google.gwt.editor.client.IsEditor;
import com.google.gwt.editor.client.adapters.TakesValueEditor;
import com.google.gwt.text.shared.Renderer;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.IntegerBox;
import com.google.gwt.user.client.ui.ValueListBox;
import com.google.gwt.user.client.ui.ValueBoxBase.TextAlignment;

import java.io.IOException;

abstract class RangeBox extends Composite implements
    IsEditor<TakesValueEditor<Integer>> {
  static final RangeRenderer rangeRenderer = new RangeRenderer();

  private static class RangeRenderer implements Renderer<Integer> {
    @Override
    public String render(Integer object) {
      if (0 <= object) {
        return "+" + object;
      } else {
        return String.valueOf(object);
      }
    }

    @Override
    public void render(Integer object, Appendable appendable)
        throws IOException {
      appendable.append(render(object));
    }
  }

  static class List extends RangeBox {
    final ValueListBox<Integer> list;

    List() {
      list = new ValueListBox<Integer>(rangeRenderer);
      initWidget(list);
    }

    @Override
    void setEnabled(boolean on) {
      DOM.setElementPropertyBoolean(list.getElement(), "disabled", !on);
    }

    @Override
    public TakesValueEditor<Integer> asEditor() {
      return list.asEditor();
    }
  }

  static class Box extends RangeBox {
    private final IntegerBox box;

    Box() {
      box = new IntegerBox();
      box.setVisibleLength(10);
      box.setAlignment(TextAlignment.RIGHT);
      initWidget(box);
    }

    @Override
    void setEnabled(boolean on) {
      DOM.setElementPropertyBoolean(box.getElement(), "disabled", !on);
    }

    @Override
    public TakesValueEditor<Integer> asEditor() {
      return box.asEditor();
    }
  }

  abstract void setEnabled(boolean on);
}


text:
package org.apache.ignite.internal.processors.cache.persistence.wal.aware;

import java.util.Map;
import java.util.TreeMap;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.jetbrains.annotations.Nullable;

import static org.apache.ignite.configuration.DataStorageConfiguration.UNLIMITED_WAL_ARCHIVE;

/**
 * Storage WAL archive size.
 * Allows to track the exceeding of the maximum archive size.
 */
class SegmentArchiveSizeStorage {
    /** Logger. */
    private final IgniteLogger log;

    /** Current WAL archive size in bytes. Guarded by {@code this}. */
    private long walArchiveSize;

    /** Flag of interrupt waiting on this object. Guarded by {@code this}. */
    private boolean interrupted;

    /** Minimum size of the WAL archive in bytes. */
    private final long minWalArchiveSize;

    /** Maximum size of the WAL archive in bytes. */
    private final long maxWalArchiveSize;

    /** WAL archive size unlimited. */
    private final boolean walArchiveUnlimited;

    /** Automatically release segments. Guarded by {@code this}. */
    private boolean autoRelease;

    /**
     * Segment sizes. Mapping: segment idx -> size in bytes. Guarded by {@code this}.
     * {@code null} if {@link #walArchiveUnlimited} == {@code true}.
     */
    @Nullable private final Map<Long, Long> segmentSizes;

    /**
     * Segment reservations storage.
     * {@code null} if {@link #walArchiveUnlimited} == {@code true}.
     */
    @Nullable private final SegmentReservationStorage reservationStorage;

    /**
     * Constructor.
     *
     * @param minWalArchiveSize Minimum size of the WAL archive in bytes.
     * @param maxWalArchiveSize Maximum size of the WAL archive in bytes
     *      or {@link DataStorageConfiguration#UNLIMITED_WAL_ARCHIVE}.
     * @param reservationStorage Segment reservations storage.
     */
    public SegmentArchiveSizeStorage(
        IgniteLogger log,
        long minWalArchiveSize,
        long maxWalArchiveSize,
        SegmentReservationStorage reservationStorage
    ) {
        this.log = log;

        this.minWalArchiveSize = minWalArchiveSize;
        this.maxWalArchiveSize = maxWalArchiveSize;

        if (maxWalArchiveSize != UNLIMITED_WAL_ARCHIVE) {
            walArchiveUnlimited = false;

            segmentSizes = new TreeMap<>();
            this.reservationStorage = reservationStorage;
        }
        else {
            walArchiveUnlimited = true;

            segmentSizes = null;
            this.reservationStorage = null;
        }
    }

    /**
     * Adds or updates information about size of a WAL segment in archive.
     *
     * @param idx Absolut segment index.
     * @param sizeChange Segment size in bytes. Could be positive (if segment is added to the archive)
     *                   or negative (e.g. when it is removed from the archive).
     */
    void changeSize(long idx, long sizeChange) {
        T2<Long, Integer> forceReleaseSegments = null;

        synchronized (this) {
            walArchiveSize += sizeChange;

            if (!walArchiveUnlimited) {
                segmentSizes.compute(idx, (i, size) -> {
                    long res = (size == null ? 0 : size) + sizeChange;

                    return res == 0 ? null : res;
                });
            }

            if (sizeChange > 0) {
                forceReleaseSegments = calcForceReleaseSegments();

                notifyAll();
            }
        }

        if (forceReleaseSegments != null)
            forceReleaseSegments(forceReleaseSegments.get1(), forceReleaseSegments.get2());
    }

    /**
     * Reset the current and reserved WAL archive sizes.
     */
    synchronized void resetSizes() {
        walArchiveSize = 0;

        if (!walArchiveUnlimited)
            segmentSizes.clear();
    }

    /**
     * Waiting for exceeding the maximum WAL archive size.
     * To track size of WAL archive, need to use {@link #changeSize}.
     *
     * @param max Maximum WAL archive size in bytes.
     * @throws IgniteInterruptedCheckedException If it was interrupted.
     */
    synchronized void awaitExceedMaxSize(long max) throws IgniteInterruptedCheckedException {
        try {
            while (max - walArchiveSize > 0 && !interrupted)
                wait();
        }
        catch (InterruptedException e) {
            throw new IgniteInterruptedCheckedException(e);
        }

        if (interrupted)
            throw new IgniteInterruptedCheckedException("Interrupt waiting of exceed max archive size");
    }

    /**
     * Interrupt waiting on this object.
     */
    synchronized void interrupt() {
        interrupted = true;

        notifyAll();
    }

    /**
     * Reset interrupted flag.
     */
    synchronized void reset() {
        interrupted = false;
    }

    /**
     * Getting current WAL archive size in bytes.
     *
     * @return Size in bytes.
     */
    synchronized long currentSize() {
        return walArchiveSize;
    }

    /**
     * Getting the size of the WAL segment of the archive in bytes.
     *
     * @return Size in bytes or {@code null} if the segment is absent or the archive is unlimited.
     */
    @Nullable Long segmentSize(long idx) {
        if (walArchiveUnlimited)
            return null;
        else {
            synchronized (this) {
                return segmentSizes.get(idx);
            }
        }
    }

    /**
     * Start automatically releasing segments when reaching {@link DataStorageConfiguration#getMaxWalArchiveSize()}.
     */
    void startAutoReleaseSegments() {
        if (!walArchiveUnlimited) {
            T2<Long, Integer> forceReleaseSegments = null;

            synchronized (this) {
                autoRelease = true;

                forceReleaseSegments = calcForceReleaseSegments();
            }

            if (forceReleaseSegments != null)
                forceReleaseSegments(forceReleaseSegments.get1(), forceReleaseSegments.get2());
        }
    }

    /**
     * Calculation of the segments for which the forced release of the segments will be performed.
     *
     * @return Pair: Absolute segment index up (and including) to which the segments will be released, segment count.
     */
    @Nullable private synchronized T2<Long, Integer> calcForceReleaseSegments() {
        if (!walArchiveUnlimited && autoRelease && walArchiveSize >= maxWalArchiveSize) {
            long releaseIdx = -1;
            int releaseCnt = 0;

            long size = 0;

            for (Map.Entry<Long, Long> e : segmentSizes.entrySet()) {
                releaseIdx = e.getKey();
                releaseCnt++;

                if (walArchiveSize - (size += e.getValue()) < minWalArchiveSize)
                    break;
            }

            return releaseIdx == -1 ? null : new T2<>(releaseIdx, releaseCnt);
        }
        else
            return null;
    }

    /**
     * Forces the release of reserved segments.
     *
     * @param absIdx Absolute segment index up (and including) to which the segments will be released.
     * @param cnt Segment count.
     */
    private void forceReleaseSegments(long absIdx, int cnt) {
        if (log.isInfoEnabled()) {
            log.info("Maximum size of the WAL archive exceeded, the segments will be forcibly released [" +
                "maxWalArchiveSize=" + U.humanReadableByteCount(maxWalArchiveSize) + ", releasedSegmentCnt=" +
                cnt + ", lastReleasedSegmentIdx=" + absIdx + ']');
        }

        reservationStorage.forceRelease(absIdx);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="zend.ldap.usage"><info><title>Szenarien der Verwendung</title></info>

    <section xml:id="zend.ldap.usage.authentication"><info><title>Szenarien der Authentifizierung</title></info>

        <section xml:id="zend.ldap.usage.authentication.openldap"><info><title>OpenLDAP</title></info>

            <para/>
        </section>

        <section xml:id="zend.ldap.usage.authentication.activedirectory"><info><title>ActiveDirectory</title></info>

            <para/>
        </section>
    </section>

    <section xml:id="zend.ldap.usage.basic"><info><title>Grundsätzliche CRUD Operationen</title></info>

        <section xml:id="zend.ldap.usage.basic.retrieve"><info><title>Daten von LDAP empfangen</title></info>

            <example xml:id="zend.ldap.usage.basic.retrieve.dn"><info><title>Einen Eintrag durch seinen DN erhalten</title></info>

                <programlisting language="php"><![CDATA[
$options = array(/* ... */);
$ldap = new Zend_Ldap($options);
$ldap->bind();
$hm = $ldap->getEntry('cn=Hugo Müller,ou=People,dc=my,dc=local');
/*
$hm is an array of the following structure
array(
    'dn'          => 'cn=Hugo Müller,ou=People,dc=my,dc=local',
    'cn'          => array('Hugo Müller'),
    'sn'          => array('Müller'),
    'objectclass' => array('inetOrgPerson', 'top'),
    ...
)
*/
]]></programlisting>
            </example>

            <example xml:id="zend.ldap.usage.basic.retrieve.exists"><info><title>Die Existenz eines angegebenen DN prüfen</title></info>

                <programlisting language="php"><![CDATA[
$options = array(/* ... */);
$ldap = new Zend_Ldap($options);
$ldap->bind();
$isThere = $ldap->exists('cn=Hugo Müller,ou=People,dc=my,dc=local');
]]></programlisting>
            </example>

            <example xml:id="zend.ldap.usage.basic.retrieve.counting-children"><info><title>Kinder eines angegebenen DN zählen</title></info>

                <programlisting language="php"><![CDATA[
$options = array(/* ... */);
$ldap = new Zend_Ldap($options);
$ldap->bind();
$childrenCount = $ldap->countChildren(
                            'cn=Hugo Müller,ou=People,dc=my,dc=local');
]]></programlisting>
            </example>

            <example xml:id="zend.ldap.usage.basic.retrieve.search"><info><title>Im LDAP Baum suchen</title></info>

                <programlisting language="php"><![CDATA[
$options = array(/* ... */);
$ldap = new Zend_Ldap($options);
$ldap->bind();
$result = $ldap->search('(objectclass=*)',
                        'ou=People,dc=my,dc=local',
                        Zend_Ldap_Ext::SEARCH_SCOPE_ONE);
foreach ($result as $item) {
    echo $item["dn"] . ': ' . $item['cn'][0] . PHP_EOL;
}
]]></programlisting>
            </example>
        </section>

        <section xml:id="zend.ldap.usage.basic.add"><info><title>Daten zu LDAP hinzufügen</title></info>

            <example><info><title>Einen neuen Eintrag zu LDAP hinzufügen</title></info>

                <programlisting language="php"><![CDATA[
$options = array(/* ... */);
$ldap = new Zend_Ldap($options);
$ldap->bind();
$entry = array();
Zend_Ldap_Attribute::setAttribute($entry, 'cn', 'Hans Meier');
Zend_Ldap_Attribute::setAttribute($entry, 'sn', 'Meier');
Zend_Ldap_Attribute::setAttribute($entry, 'objectClass', 'inetOrgPerson');
$ldap->add('cn=Hans Meier,ou=People,dc=my,dc=local', $entry);
]]></programlisting>
            </example>
        </section>

        <section xml:id="zend.ldap.usage.basic.delete"><info><title>In LDAP löschen</title></info>

            <example><info><title>Einen existierenden Eintrag von LDAP löschen</title></info>

                <programlisting language="php"><![CDATA[
$options = array(/* ... */);
$ldap = new Zend_Ldap($options);
$ldap->bind();
$ldap->delete('cn=Hans Meier,ou=People,dc=my,dc=local');
]]></programlisting>
            </example>
        </section>

        <section xml:id="zend.ldap.usage.basic.update"><info><title>LDAP aktualisieren</title></info>

            <example><info><title>Einen existierenden Eintrag in LDAP aktualisieren</title></info>

                <programlisting language="php"><![CDATA[
$options = array(/* ... */);
$ldap = new Zend_Ldap($options);
$ldap->bind();
$hm = $ldap->getEntry('cn=Hugo Müller,ou=People,dc=my,dc=local');
Zend_Ldap_Attribute::setAttribute($hm, 'mail', 'mueller@my.local');
Zend_Ldap_Attribute::setPassword($hm,
                                 'newPa$$w0rd',
                                 Zend_Ldap_Attribute::PASSWORD_HASH_SHA1);
$ldap->update('cn=Hugo Müller,ou=People,dc=my,dc=local', $hm);
]]></programlisting>
            </example>
        </section>
    </section>

    <section xml:id="zend.ldap.usage.extended"><info><title>Erweiterte Operationen</title></info>

        <section xml:id="zend.ldap.usage.extended.copy-and-move"><info><title>Kopieren und Verschieben von Einträgen in LDAP</title></info>

            <example xml:id="zend.ldap.usage.extended.copy-and-move.copy"><info><title>Einen LDAP Eintrag mit allen seinen Abhängigkeiten rekursiv kopieren</title></info>

                <programlisting language="php"><![CDATA[
$options = array(/* ... */);
$ldap = new Zend_Ldap($options);
$ldap->bind();
$ldap->copy('cn=Hugo Müller,ou=People,dc=my,dc=local',
            'cn=Hans Meier,ou=People,dc=my,dc=local',
            true);
]]></programlisting>
            </example>

            <example xml:id="zend.ldap.usage.extended.copy-and-move.move-to-subtree"><info><title>
                    Einen LDAP Eintrag rekursiv in einen anderen Unterbaum verschieben mit allen
                    seinen Abhängigkeiten
                </title></info>

                <programlisting language="php"><![CDATA[
$options = array(/* ... */);
$ldap = new Zend_Ldap($options);
$ldap->bind();
$ldap->moveToSubtree('cn=Hugo Müller,ou=People,dc=my,dc=local',
                     'ou=Dismissed,dc=my,dc=local',
                     true);
]]></programlisting>
            </example>
        </section>
    </section>
</section>


text:
namespace Telerik
{
	namespace UI
	{
		namespace Drawing
		{
			[Windows::UI::Xaml::Data::Bindable]
			public ref class D2DSolidColorBrush sealed : D2DBrush
			{
			public:
				D2DSolidColorBrush(void);

				property Windows::UI::Color Color
				{
					Windows::UI::Color get() { return this->color; }
					void set(Windows::UI::Color value)
					{
						this->color = value;
					}
				};

			internal:
				virtual D2DBrush^ Clone() override;
				virtual ComPtr<ID2D1Resource> CreateNativeResource(D2DRenderContext^ context) override;

			private:
				Windows::UI::Color color;
			};
		}
	}
}


text:
#include "Main/OculusHMDImpl.h"
#include "Utils/Exception.h"

#include <cassert>

/**
 * @brief Constructor - finds the Oculus Rift and its sensor, or throw en exception.
 */
OculusHMDImpl::OculusHMDImpl() :
    mLog("OculusHMD"),
    mPredictionLookaheadMs(30) {

    // Those vars are reference counted; no need to keep them around explicitly,
    // they will be freed when Sensor & SensorFusion will be cleared (in OculusHMDImpl destructor)
    OVR::Ptr<OVR::DeviceManager>    mManagerPtr;        ///< Device Manager provides access to devices supported by OVR
    OVR::Ptr<OVR::HMDDevice>        mHMDPtr;            ///< Represents an Oculus HMD device unit
    OVR::Ptr<OVR::Profile>          mUserProfilePtr;    ///< Profile of the user (Eye height, IPD...)

    // LibOVR core system: needs to be Initialized before any OVR Kernel use
//  OVR::System::Init(OVR::Log::ConfigureDefaultLog(OVR::LogMask_All)); // done by mSystem constructor

    // Access to the first Oculus HMD device found
    mManagerPtr = *(OVR::DeviceManager::Create());
    mHMDPtr = *(mManagerPtr->EnumerateDevices<OVR::HMDDevice>().CreateDevice());
    if (mHMDPtr) {
        // Get detailed information about the device and its capabilities
        bool bHasInfo = mHMDPtr->GetDeviceInfo(&mHMDInfo);
        if (bHasInfo) {
            mStereoConfig.SetHMDInfo(mHMDInfo);
            mLog.info() << "HMD '" << mHMDInfo.ProductName << "' found, on screen '"
                        << mHMDInfo.DisplayDeviceName << "' ("
                        << mHMDInfo.HResolution << "x" << mHMDInfo.VResolution << ")";

            // Retrieve user profile settings
            mUserProfilePtr = mHMDPtr->GetProfile();
            if (mUserProfilePtr) {
                mLog.info() << "User profile Height=" << mUserProfilePtr->GetPlayerHeight()
                            << " EyeHeight=" << mUserProfilePtr->GetEyeHeight()
                            << " IPD=" << mUserProfilePtr->GetIPD();
                mStereoConfig.SetIPD(mUserProfilePtr->GetIPD());

                mLog.info() << "Calculated appropriate FOV: " << mStereoConfig.GetYFOVDegrees() << "deg";
                mLog.info() << "Calculated screen center offset: " << mStereoConfig.GetProjectionCenterOffset() << "m";

                // Access sensor interface of the HMD device
                mSensorPtr = *(mHMDPtr->GetSensor());
                if (mSensorPtr) {
                    // Create an object to accumulate data from Gyro/Accelero/Magneto to keep track of orientation
                    mSensorFusionPtr.reset(new OVR::SensorFusion());

                    // Attach Sensor to SensorFusion object for it to receive frame messages and update orientation.
                    mSensorFusionPtr->AttachToSensor(mSensorPtr);

                    // Enable prediction with the default delta of 30ms (0.03s)
                 // mSensorFusionPtr->SetPredictionEnabled(true);
                    setPrediction(mPredictionLookaheadMs);
                } else {
                    mLog.error() << "No sensor found";
                    throw Utils::Exception("error: No sensor found");
                }
                mUserProfilePtr.Clear();
            } else {
                mLog.error() << "No user profile";
                throw Utils::Exception("error: No user profile");
            }
        } else {
            mLog.error() << "No HMD info";
            throw Utils::Exception("error: No HMD info");
        }
        mHMDPtr.Clear();
    } else {
        mLog.notice() << "No HMD found";
        throw Utils::Exception("note: No HMD found");
    }
    mManagerPtr.Clear();
}

/**
 * @brief Destructor
 */
OculusHMDImpl::~OculusHMDImpl() {
    mSensorPtr.Clear();
    mSensorFusionPtr.reset();

//  OVR::System::Destroy(); // done by mSystem destructor
}

/**
 * @brief Load default HMD information to fake its presence for development purpose
 *
 * @note Not used any more
 */
void OculusHMDImpl::fakeInfo() {
    mHMDInfo.HResolution = 1280;
    mHMDInfo.VResolution = 800;
    mHMDInfo.HScreenSize = 0.149759993f;
    mHMDInfo.VScreenSize = 0.0935999975f;
    mHMDInfo.VScreenCenter = 0.0467999987f;
    mHMDInfo.EyeToScreenDistance    = 0.0410000011f;
    mHMDInfo.LensSeparationDistance = 0.0635000020f;
    mHMDInfo.InterpupillaryDistance = 0.0640000030f;
    mHMDInfo.DistortionK[0] = 1.00000000f;
    mHMDInfo.DistortionK[1] = 0.219999999f;
    mHMDInfo.DistortionK[2] = 0.239999995f;
    mHMDInfo.DistortionK[3] = 0.000000000f;
    mHMDInfo.ChromaAbCorrection[0] = 0.995999992f;
    mHMDInfo.ChromaAbCorrection[1] = -0.00400000019f;
    mHMDInfo.ChromaAbCorrection[2] = 1.01400006f;
    mHMDInfo.ChromaAbCorrection[3] = 0.000000000f;
    mHMDInfo.DesktopX = 0;
    mHMDInfo.DesktopY = 0;
}

/**
 * @brief Set prediction lookahead in miliseconds
 *
 * @param[in] aPredictionDeltaMs    prediction lookahead amount in miliseconds
 */
void OculusHMDImpl::setPrediction(int aPredictionDeltaMs) {
    assert(mSensorPtr && mSensorFusionPtr);

    mPredictionLookaheadMs = aPredictionDeltaMs;
    // Enable prediction with the provided delta (default is 30ms 0.03s)
    mSensorFusionPtr->SetPrediction(0.001f * aPredictionDeltaMs);
    mLog.info() << "SetPrediction(" << aPredictionDeltaMs << "ms) = " << (0.001f * aPredictionDeltaMs);
}

/**
 * @brief Increment/decrement prediction lookahead by some miliseconds
 *
 * @param[in] aOffset Offset to add/remove to the lookahead in miliseconds
 */
void OculusHMDImpl::incrPrediction(int aOffset) {
    if (100 > mPredictionLookaheadMs) {
        mPredictionLookaheadMs += aOffset;
        setPrediction(mPredictionLookaheadMs);
    }
}

/**
 * @brief Reset orientation of the HMD
 */
void OculusHMDImpl::resetOrientation() {
    assert(mSensorFusionPtr);

    mSensorFusionPtr->Reset();
}

/**
 * @brief Get quaternion of orientation of the HMD
 *
 * @return A GLM quaternion of orientation
 */
glm::fquat OculusHMDImpl::getOrientation() const {
    assert(mSensorFusionPtr);

    OVR::Quatf hmdOrientation = mSensorFusionPtr->GetOrientation();
    return glm::fquat(hmdOrientation.w, hmdOrientation.x, hmdOrientation.y, hmdOrientation.z);
}


text:
package com.facebook.litho;

import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import androidx.core.view.AccessibilityDelegateCompat;
import com.facebook.litho.annotations.Event;

/**
 * Components should implement an event of this type in order to receive callbacks to {@link
 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
 */
@Event(returnType = boolean.class)
public class DispatchPopulateAccessibilityEventEvent {
  public View host;
  public AccessibilityEvent event;
  public AccessibilityDelegateCompat superDelegate;
}


text:
"""See README for more information"""

from optparse import OptionParser
import os
import re
import sys
import unittest

# Our modules
try:
    from patman import checkpatch, command, gitutil, patchstream, \
        project, settings, terminal, test
except ImportError:
    import checkpatch
    import command
    import gitutil
    import patchstream
    import project
    import settings
    import terminal
    import test

parser = OptionParser()
parser.add_option('-H', '--full-help', action='store_true', dest='full_help',
       default=False, help='Display the README file')
parser.add_option('-c', '--count', dest='count', type='int',
       default=-1, help='Automatically create patches from top n commits')
parser.add_option('-i', '--ignore-errors', action='store_true',
       dest='ignore_errors', default=False,
       help='Send patches email even if patch errors are found')
parser.add_option('-m', '--no-maintainers', action='store_false',
       dest='add_maintainers', default=True,
       help="Don't cc the file maintainers automatically")
parser.add_option('-n', '--dry-run', action='store_true', dest='dry_run',
       default=False, help="Do a dry run (create but don't email patches)")
parser.add_option('-p', '--project', default=project.DetectProject(),
                  help="Project name; affects default option values and "
                  "aliases [default: %default]")
parser.add_option('-r', '--in-reply-to', type='string', action='store',
                  help="Message ID that this series is in reply to")
parser.add_option('-s', '--start', dest='start', type='int',
       default=0, help='Commit to start creating patches from (0 = HEAD)')
parser.add_option('-t', '--ignore-bad-tags', action='store_true',
                  default=False, help='Ignore bad tags / aliases')
parser.add_option('--test', action='store_true', dest='test',
                  default=False, help='run tests')
parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
       default=False, help='Verbose output of errors and warnings')
parser.add_option('--cc-cmd', dest='cc_cmd', type='string', action='store',
       default=None, help='Output cc list for patch file (used by git)')
parser.add_option('--no-check', action='store_false', dest='check_patch',
                  default=True,
                  help="Don't check for patch compliance")
parser.add_option('--no-tags', action='store_false', dest='process_tags',
                  default=True, help="Don't process subject tags as aliaes")
parser.add_option('-T', '--thread', action='store_true', dest='thread',
                  default=False, help='Create patches as a single thread')

parser.usage += """

Create patches from commits in a branch, check them and email them as
specified by tags you place in the commits. Use -n to do a dry run first."""

# Parse options twice: first to get the project and second to handle
# defaults properly (which depends on project).
(options, args) = parser.parse_args()
settings.Setup(parser, options.project, '')
(options, args) = parser.parse_args()

if __name__ != "__main__":
    pass

# Run our meagre tests
elif options.test:
    import doctest
    import func_test

    sys.argv = [sys.argv[0]]
    result = unittest.TestResult()
    for module in (test.TestPatch, func_test.TestFunctional):
        suite = unittest.TestLoader().loadTestsFromTestCase(module)
        suite.run(result)

    for module in ['gitutil', 'settings']:
        suite = doctest.DocTestSuite(module)
        suite.run(result)

    # TODO: Surely we can just 'print' result?
    print(result)
    for test, err in result.errors:
        print(err)
    for test, err in result.failures:
        print(err)

# Called from git with a patch filename as argument
# Printout a list of additional CC recipients for this patch
elif options.cc_cmd:
    fd = open(options.cc_cmd, 'r')
    re_line = re.compile('(\S*) (.*)')
    for line in fd.readlines():
        match = re_line.match(line)
        if match and match.group(1) == args[0]:
            for cc in match.group(2).split(', '):
                cc = cc.strip()
                if cc:
                    print(cc)
    fd.close()

elif options.full_help:
    pager = os.getenv('PAGER')
    if not pager:
        pager = 'more'
    fname = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])),
                         'README')
    command.Run(pager, fname)

# Process commits, produce patches files, check them, email them
else:
    gitutil.Setup()

    if options.count == -1:
        # Work out how many patches to send if we can
        options.count = gitutil.CountCommitsToBranch() - options.start

    col = terminal.Color()
    if not options.count:
        str = 'No commits found to process - please use -c flag'
        sys.exit(col.Color(col.RED, str))

    # Read the metadata from the commits
    if options.count:
        series = patchstream.GetMetaData(options.start, options.count)
        cover_fname, args = gitutil.CreatePatches(options.start, options.count,
                series)

    # Fix up the patch files to our liking, and insert the cover letter
    patchstream.FixPatches(series, args)
    if cover_fname and series.get('cover'):
        patchstream.InsertCoverLetter(cover_fname, series, options.count)

    # Do a few checks on the series
    series.DoChecks()

    # Check the patches, and run them through 'git am' just to be sure
    if options.check_patch:
        ok = checkpatch.CheckPatches(options.verbose, args)
    else:
        ok = True

    cc_file = series.MakeCcFile(options.process_tags, cover_fname,
                                not options.ignore_bad_tags,
                                options.add_maintainers)

    # Email the patches out (giving the user time to check / cancel)
    cmd = ''
    its_a_go = ok or options.ignore_errors
    if its_a_go:
        cmd = gitutil.EmailPatches(series, cover_fname, args,
                options.dry_run, not options.ignore_bad_tags, cc_file,
                in_reply_to=options.in_reply_to, thread=options.thread)
    else:
        print(col.Color(col.RED, "Not sending emails due to errors/warnings"))

    # For a dry run, just show our actions as a sanity check
    if options.dry_run:
        series.ShowActions(args, cmd, options.process_tags)
        if not its_a_go:
            print(col.Color(col.RED, "Email would not be sent"))

    os.remove(cc_file)


text:
'''
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

Example:

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Note:

Only constant extra memory is allowed.
You may not alter the values in the list's nodes, only nodes itself may be changed.
'''

'''
For every k nodes, break it from the original list, reverse it and
then add the part back. If fewer than k remaining, do nothing.
'''

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        def reverseLinkedList(node):
            prev, curr = None, node
            while curr is not None:
                tmp = curr.next
                curr.next = prev
                prev = curr
                curr = tmp
            return prev, node

        def getKNodes(node, k):
            curr = node
            while k > 1 and curr is not None:
                k -= 1
                curr = curr.next
            if curr is None:
                return False, curr
            return True, curr

        if k < 2:
            return head
        nh = ListNode(None)
        nh.next = head
        curr = nh
        while curr is not None:
            part_head = curr.next
            can_take, part_tail = getKNodes(part_head, k)
            if not can_take:
                break
            next_head = part_tail.next
            part_tail.next = None
            rh, rt = reverseLinkedList(part_head)
            curr.next = rh
            curr = rt
            curr.next = next_head
        return nh.next


text:
package messagebus

import (
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"net/url"
	"sync/atomic"
	"time"

	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/route-registrar/config"
	"github.com/nats-io/nats.go"
)

//go:generate counterfeiter . MessageBus

type MessageBus interface {
	Connect(servers []config.MessageBusServer, tlsConfig *tls.Config) error
	SendMessage(subject string, host string, route config.Route, privateInstanceId string) error
	Close()
}

type msgBus struct {
	natsHost *atomic.Value
	natsConn *nats.Conn
	logger   lager.Logger
}

type Message struct {
	URIs                []string          `json:"uris"`
	Host                string            `json:"host"`
	Port                *int              `json:"port,omitempty"`
	TLSPort             *int              `json:"tls_port,omitempty"`
	Tags                map[string]string `json:"tags"`
	RouteServiceUrl     string            `json:"route_service_url,omitempty"`
	PrivateInstanceId   string            `json:"private_instance_id"`
	ServerCertDomainSAN string            `json:"server_cert_domain_san,omitempty"`
}

func NewMessageBus(logger lager.Logger) MessageBus {
	return &msgBus{
		logger:   logger,
		natsHost: &atomic.Value{},
	}
}

func (m *msgBus) Connect(servers []config.MessageBusServer, tlsConfig *tls.Config) error {

	var natsServers []string
	var natsHosts []string
	for _, server := range servers {
		natsServers = append(
			natsServers,
			fmt.Sprintf("nats://%s:%s@%s", server.User, server.Password, server.Host),
		)
		natsHosts = append(natsHosts, server.Host)
	}

	opts := nats.DefaultOptions
	opts.Servers = natsServers
	opts.TLSConfig = tlsConfig
	opts.PingInterval = 20 * time.Second

	opts.ClosedCB = func(conn *nats.Conn) {
		m.logger.Error("nats-connection-closed", errors.New("unexpected nats conn closed"), lager.Data{"nats-host": m.natsHost.Load()})
	}

	opts.DisconnectedCB = func(conn *nats.Conn) {
		m.logger.Info("nats-connection-disconnected", lager.Data{"nats-host": m.natsHost.Load()})
	}

	opts.ReconnectedCB = func(conn *nats.Conn) {
		natsHost, err := parseNatsUrl(conn.ConnectedUrl())
		if err != nil {
			m.logger.Error("nats-url-parse-failed", err, lager.Data{"nats-host": natsHost})
		}
		m.natsHost.Store(natsHost)
		m.logger.Info("nats-connection-reconnected", lager.Data{"nats-host": m.natsHost.Load()})
	}

	natsConn, err := opts.Connect()
	if err != nil {
		m.logger.Error("nats-connection-failed", err, lager.Data{"nats-hosts": natsHosts})
		return err
	}

	natsHost, err := parseNatsUrl(natsConn.ConnectedUrl())
	if err != nil {
		m.logger.Error("nats-url-parse-failed", err, lager.Data{"nats-host": natsHost})
	}

	m.natsHost.Store(natsHost)
	m.logger.Info("nats-connection-successful", lager.Data{"nats-host": m.natsHost.Load()})
	m.natsConn = natsConn

	return nil
}

func (m msgBus) SendMessage(subject string, host string, route config.Route, privateInstanceId string) error {
	m.logger.Debug("creating-message", lager.Data{"subject": subject, "host": host, "route": route, "privateInstanceId": privateInstanceId})

	msg := &Message{
		URIs:                route.URIs,
		Host:                host,
		Port:                route.Port,
		TLSPort:             route.TLSPort,
		Tags:                route.Tags,
		RouteServiceUrl:     route.RouteServiceUrl,
		ServerCertDomainSAN: route.ServerCertDomainSAN,
		PrivateInstanceId:   privateInstanceId,
	}

	json, err := json.Marshal(msg)
	if err != nil {
		// Untested as we cannot force json.Marshal to return error.
		return err
	}

	m.logger.Debug("publishing-message", lager.Data{"msg": string(json)})

	return m.natsConn.Publish(subject, json)
}

func (m msgBus) Close() {
	m.natsConn.Close()
}

func parseNatsUrl(natsUrl string) (string, error) {
	natsURL, err := url.Parse(natsUrl)
	natsHostStr := ""
	if err != nil {
		return "", err
	} else {
		natsHostStr = natsURL.Host
	}

	return natsHostStr, nil
}


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

namespace Linq2TwitterDemos_Console
{
    public class UserDemos
    {
        internal static async Task RunAsync(TwitterContext twitterCtx)
        {
            char key;

            do
            {
                ShowMenu();

                key = Console.ReadKey(true).KeyChar;

                switch (key)
                {
                    case '0':
                        Console.WriteLine("\n\tLooking...\n");
                        await LookupUsersAsync(twitterCtx);
                        break;
                    case '1':
                        Console.WriteLine("\n\tShowing...\n");
                        await ShowUserDetailsAsync(twitterCtx);
                        break;
                    case '2':
                        Console.WriteLine("\n\tSearching...\n");
                        await FindUsersAsync(twitterCtx);
                        break;
                    case '3':
                        Console.WriteLine("\n\tShowing...\n");
                        await GetContributeesAsync(twitterCtx);
                        break;
                    case '4':
                        Console.WriteLine("\n\tSearching...\n");
                        await GetContributorsAsync(twitterCtx);
                        break;
                    case '5':
                        Console.WriteLine("\n\tGetting...\n");
                        await GetBannerSizesAsync(twitterCtx);
                        break;
                    case '6':
                        Console.WriteLine("\n\tGetting...\n");
                        await GetUsersInSuggestedCategoriesAsync(twitterCtx);
                        break;
                    case '7':
                        Console.WriteLine("\n\tGetting  ...\n");
                        await GetSuggestedCategoryListQueryAsync(twitterCtx);
                        break;
                    case '8':
                        Console.WriteLine("\n\tGetting...\n");
                        await ShowUsersInCategoryAsync(twitterCtx);
                        break;
                    case '9':
                        Console.WriteLine("\n\tReport spammer...\n");
                        await ReportSpammerAsync(twitterCtx);
                        break;
                    case 'q':
                    case 'Q':
                        Console.WriteLine("\nReturning...\n");
                        break;
                    default:
                        Console.WriteLine(key + " is unknown");
                        break;
                }

            } while (char.ToUpper(key) != 'Q');
        }

        static void ShowMenu()
        {
            Console.WriteLine("\nUser Demos - Please select:\n");

            Console.WriteLine("\t 0. Lookup Users");
            Console.WriteLine("\t 1. Show User Info");
            Console.WriteLine("\t 2. Search for Users");
            Console.WriteLine("\t 3. Contributee Accounts");
            Console.WriteLine("\t 4. Account Contributors");
            Console.WriteLine("\t 5. Get Profile Banner Sizes");
            Console.WriteLine("\t 6. Get Suggested Users");
            Console.WriteLine("\t 7. Get Suggestion Categories");
            Console.WriteLine("\t 8. Get Suggested User Tweets");
            Console.WriteLine("\t 9. Report Spammer");
            Console.WriteLine();
            Console.Write("\t Q. Return to Main menu");
        }

        static async Task LookupUsersAsync(TwitterContext twitterCtx)
        {
            var userResponse =
                await
                (from user in twitterCtx.User
                 where user.Type == UserType.Lookup &&
                       user.ScreenNameList == "JoeMayo,Linq2Twitr" &&
                       user.TweetMode == TweetMode.Extended
                 select user)
                .ToListAsync();

            if (userResponse != null)
                userResponse.ForEach(user =>
                    Console.WriteLine("Name: " + user.ScreenNameResponse));
        }

        static async Task ShowUserDetailsAsync(TwitterContext twitterCtx)
        {
            string screenName = "JoeMayo";
            var user =
                await
                (from usr in twitterCtx.User
                 where usr.Type == UserType.Show &&
                       usr.ScreenName == screenName &&
                       usr.TweetMode == TweetMode.Extended
                 select usr)
                .SingleOrDefaultAsync();

            if (user != null)
            {
                var name = user.ScreenNameResponse;
                var lastStatus =
                    user.Status == null ? "No Status" : user.Status.Text;

                Console.WriteLine();
                Console.WriteLine(
                    "Name: {0}, Last Tweet: {1}\n", name, lastStatus);
            }
        }

        static async Task FindUsersAsync(TwitterContext twitterCtx)
        {
            var foundUsers =
                await
                (from user in twitterCtx.User
                 where user.Type == UserType.Search &&
                       user.Query == "JoeMayo" &&
                       user.TweetMode == TweetMode.Extended
                 select user)
                .ToListAsync();

            if (foundUsers != null)
                foundUsers.ForEach(user =>
                    Console.WriteLine("User: " + user.ScreenNameResponse));
        }

        static async Task GetContributeesAsync(TwitterContext twitterCtx)
        {
            try
            {
                var users =
                    await
                    (from user in twitterCtx.User
                     where user.Type == UserType.Contributees &&
                           user.ScreenName == "biz"
                     select user)
                    .ToListAsync();

                if (users != null)
                    users.ForEach(user =>
                        Console.WriteLine("User: " + user.ScreenNameResponse));
            }
            catch (TwitterQueryException tqEx) when (tqEx.ErrorCode == 220)
            {
                Console.WriteLine("Unable to query - Reason: " + tqEx.ReasonPhrase);
            }
        }

        static async Task GetContributorsAsync(TwitterContext twitterCtx)
        {
            try
            {
                var users =
                    await
                    (from user in twitterCtx.User
                     where user.Type == UserType.Contributors &&
                           user.ScreenName == "twitter"
                     select user)
                    .ToListAsync();

                if (users != null)
                    users.ForEach(user =>
                        Console.WriteLine("User: " + user.ScreenNameResponse));
            }
            catch (TwitterQueryException tqEx) when (tqEx.ErrorCode == 220)
            {
                Console.WriteLine("Unable to query - Reason: " + tqEx.ReasonPhrase);
            }
        }

        static async Task GetBannerSizesAsync(TwitterContext twitterCtx)
        {
            var user =
                await
                (from usr in twitterCtx.User
                 where usr.Type == UserType.BannerSizes &&
                       usr.ScreenName == "JoeMayo"
                 select usr)
                .SingleOrDefaultAsync();

            if (user != null && user.BannerSizes != null)
                user.BannerSizes.ForEach(size =>
                    Console.WriteLine(
                        "Label: {0}, W: {1} H: {2} URL: {3}",
                        size.Label, size.Width, size.Height, size.Url));
        }

        static async Task GetUsersInSuggestedCategoriesAsync(TwitterContext twitterCtx)
        {
            var userResponse =
                await
                (from user in twitterCtx.User
                 where user.Type == UserType.Category &&
                       user.Slug == "Funny"
                 select user)
                .SingleOrDefaultAsync();

            if (userResponse != null &&
                userResponse.Categories != null &&
                userResponse.Categories.Any() &&
                userResponse.Categories.First().Users != null)
            {
                List<User> users = userResponse.Categories.First().Users;

                users.ForEach(user =>
                    Console.WriteLine("User: " + user.ScreenNameResponse));
            }
        }

        static async Task GetSuggestedCategoryListQueryAsync(TwitterContext twitterCtx)
        {
            var user =
                await
                (from tweet in twitterCtx.User
                 where tweet.Type == UserType.Categories
                 select tweet)
                .SingleOrDefaultAsync();

            if (user != null && user.Categories != null)
                user.Categories.ForEach(cat =>
                    Console.WriteLine("Category: " + cat.Name));
        }

        static async Task ShowUsersInCategoryAsync(TwitterContext twitterCtx)
        {
            var catUsers =
                await
                (from user in twitterCtx.User
                 where user.Type == UserType.CategoryStatus &&
                       user.Slug == "Technology"
                 select user)
                .ToListAsync();

            if (catUsers != null)
            {
                Console.WriteLine("Tweets: \n");

                catUsers.ForEach(user =>
                {
                    if (user != null && user.Status != null)
                        Console.WriteLine(
                            "User: {0}\nTweet: {1}\n",
                            user.ScreenNameResponse,
                            user.Status == null ?
                                "<Tweet not available.>" :
                                user.Status.Text);
                });
            }
        }

        static async Task ReportSpammerAsync(TwitterContext twitterCtx)
        {
            const string SpammerScreenName = "realDonaldTrump";

            User spammer = await twitterCtx.ReportSpamAsync(SpammerScreenName, performBlock: true);

            Console.WriteLine("You just reported {0} as a spammer.", spammer.ScreenNameResponse);
        }
    }
}


text:
<?php require_once __DIR__ . '/../../vendor/autoload.php'; ?>
<?php $minifier = (new \Minifine\Factory())->build(__DIR__, true); ?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Advanced usage - Documentation - Minifine</title>
        <?= $minifier->css(['/css/bootstrap.min.css', '/css/custom.css'], '/css/styles.min.css'); ?>

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>
                    Minifine

                            Documentation

Installation

Basic usage

Advanced usage(current)

Contributing

Development environment example

Production environment example

Project on GitHub

Advanced usage

Minifine exposes a public API for more advanced usages. This may include using different minification schemes or even chaining together several minifion schemes.

Using different minification schemes

To use different minificators (instead of the default ones provided by Minifine) all you have to do is setup the Minifine object using the different minificators:

$minifier = new \Minifine\Minifine('/path/to/resources');
$minifier->appendJsMinifier(new \CustomJsMinifier());
$minifier->appendCssMinifier(new \CustomCssMinifier());

The minifier can now be used using the custom minifiers for CSS and javascript files.

All (custom) minifiers must implement the Minifine\Minifier\Minifier interface which has a single method with a single parameter:

                        Minifine\Minifier\Minifier::minify(string $data)

The $data parameter is the actual data that needs to be minified.

Chaining minifcations

To chain minifications the public API contains four methods being appendJsMinifier(), prependJsMinifier(), appendCssMinifier() and prependCssMinifier()

When multiple minifiers are defined for a specific type of resource (CSS or javascript) they will be chained together and ran after eachother.

All (custom) minifiers must implement the Minifine\Minifier\Minifier interface which has a single method with a single parameter:

                        Minifine\Minifier\Minifier::minify(string $data)

The $data parameter is the actual data that needs to be minified.

        <?= $minifier->js(['/js/jquery-1.11.2.min.js', '/js/bootstrap.min.js', '/js/custom.js'], '/js/main.min.js'); ?>


text:
#include "IntegralConstant.h"
#include "BasicTypes.h"

#include "../LanguageVersion.h"

//
// Rank
//

namespace Ardutils
{
	// C++11
	template< typename T >
	struct Rank : IntegralConstant< SizeT, 0 > {};

	template< typename T >
	struct Rank< T[] > : IntegralConstant< SizeT, Rank< T >::Value + 1 > {};

	template< typename T, SizeT N >
	struct Rank< T[N] > : IntegralConstant< SizeT, Rank< T >::Value + 1 > {};

	// C++17
	// C++14 is needed for template variables
#if	AT_LEAST_CPP_14

	template< typename T >
	constexpr SizeT RankV = Rank< T >::Value;

#endif
}


text:
from django import forms
from django.utils.translation import ugettext as _
from wagtail.wagtailcore.models import Page
from django.utils.safestring import mark_safe

class CustomModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        bits = []
        for ancestor in obj.get_ancestors(inclusive=True).exclude(depth=1):
            bits.append(ancestor.title)
        return mark_safe(''.join(bits))

class ParentChooserForm(forms.Form):
    parent_page = CustomModelChoiceField(
        label=_('Put it under'),
        required=True,
        empty_label=None,
        queryset=Page.objects.none(),
        widget=forms.RadioSelect(),
    )

    def __init__(self, valid_parents_qs, *args, **kwargs):
        self.valid_parents_qs = valid_parents_qs
        super(ParentChooserForm, self).__init__(*args, **kwargs)
        self.fields['parent_page'].queryset = self.valid_parents_qs


text:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Codeplex.Data;
using System.Windows;

namespace ruche.datas.textureAtlas.loaders
{
    /// <summary>
    /// Unity等で使われるJSON形式ファイルからテクスチャアトラスを作成するクラス。
    /// </summary>
    public sealed class JsonHashTextureAtlasLoader : ITextureAtlasLoader
    {
        /// <summary>
        /// コンストラクタ。
        /// </summary>
        public JsonHashTextureAtlasLoader() { }

        #region ITextureAtlasLoader 実装

        /// <summary>
        /// ファイルからのテクスチャアトラス作成をサポートするか否かを取得する。
        /// </summary>
        /// <remarks>常に true を返す。</remarks>
        public bool CanLoadFile
        {
            get { return true; }
        }

        /// <summary>
        /// ディレクトリからのテクスチャアトラス作成をサポートするか否かを取得する。
        /// </summary>
        /// <remarks>常に false を返す。</remarks>
        public bool CanLoadDirectory
        {
            get { return false; }
        }

        /// <summary>
        /// ソースとして一般的なパスであるか否かを取得する。
        /// </summary>
        /// <param name="path">ファイルまたはディレクトリのパス。</param>
        /// <returns>
        /// 拡張子が ".json" または ".txt" であるならば true 。そうでなければ false 。
        /// </returns>
        public bool IsTypicalSourcePath(string path)
        {
            if (path != null)
            {
                var ext = Path.GetExtension(path).ToLower();
                return (ext == ".json" || ext == ".txt");
            }
            return false;
        }

        /// <summary>
        /// JSON形式ファイルからテクスチャアトラスを作成する。
        /// </summary>
        /// <param name="path">ファイルパス。</param>
        /// <returns>テクスチャアトラス。作成できない場合は null 。</returns>
        public TextureAtlas Load(string path)
        {
            try
            {
                var jsonText = File.ReadAllText(path, Encoding.Default);
                var json = DynamicJson.Parse(jsonText);

                string imgFileName = json.meta.image;
                Size imgSize = new Size(json.meta.size.w, json.meta.size.h);

                var frames = new List<TextureAtlasFrame>();
                foreach (KeyValuePair<string, dynamic> kv in json.frames)
                {
                    var f = kv.Value;
                    var frameRect =
                        new Rect(f.frame.x, f.frame.y, f.frame.w, f.frame.h);
                    var rotated = (bool)f.rotated;
                    var srcSize = new Size(f.sourceSize.w, f.sourceSize.h);
                    var trimPos =
                        new Point(f.spriteSourceSize.x, f.spriteSourceSize.y);
                    var frame =
                        TextureAtlasFrame.Create(
                            frameRect.Size,
                            frameRect.Location,
                            rotated,
                            srcSize,
                            trimPos);
                    frames.Add(frame);
                }

                return new TextureAtlas(imgFileName, imgSize, frames);
            }
            catch { }

            return null;
        }

        #endregion
    }
}


text:
package me.dablakbandit.dabcore.sql;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.bukkit.plugin.java.JavaPlugin;

public class SQLite
extends Database
{

	private JavaPlugin plugin;
	private final String database;
	private Connection connection;

	public SQLite(String database){
		this(null, database);
	}

	public SQLite(JavaPlugin plugin, String database)
	{
		this.plugin = plugin;
		this.database = database;
		this.connection = null;
	}

	public Connection openConnection()
	{
		try
		{
			Class.forName("org.sqlite.JDBC");
			File f = (plugin==null?new File(database) : new File(plugin.getDataFolder(), database));
			if(!f.getParentFile().exists())f.getParentFile().mkdirs();
			if(!f.exists())f.createNewFile();
			this.connection = DriverManager.getConnection("jdbc:sqlite:" + f);
		}
		catch (SQLException e)
		{
			System.out.print(e.getMessage());
			closeConnection();
		}
		catch (ClassNotFoundException e)
		{
			System.out.print("JDBC Driver not found!");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return this.connection;
	}

	public boolean checkConnection()
	{
		return this.connection != null;
	}

	public Connection getConnection()
	{
		return this.connection;
	}

	public void closeConnection()
	{
		if (this.connection != null) {
			try
			{
				this.connection.close();
			}
			catch (SQLException e)
			{
				System.out.print("Error closing the SQLite Connection!");
				e.printStackTrace();
			}
		}
	}

	public ResultSet querySQL(String query)
	{
		Connection c = null;
		if (checkConnection()) {
			c = getConnection();
		} else {
			c = openConnection();
		}
		Statement s = null;
		try
		{
			s = c.createStatement();
		}
		catch (SQLException e1)
		{
			e1.printStackTrace();
		}
		ResultSet ret = null;
		try
		{
			ret = s.executeQuery(query);
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		return ret;
	}

	public void updateSQL(String update)
	{
		Connection c = null;
		if (checkConnection()) {
			c = getConnection();
		} else {
			c = openConnection();
		}
		Statement s = null;
		try
		{
			s = c.createStatement();
			s.executeUpdate(update);
		}
		catch (SQLException e1)
		{
			e1.printStackTrace();
		}
	}
}


text:
package org.kie.pmml.models.regression.model;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

import org.kie.pmml.api.iinterfaces.SerializableFunction;

public abstract class KiePMMLRegressionTable implements Serializable {

    private static final long serialVersionUID = -7899446939844650691L;
    protected Map<String, SerializableFunction<Double, Double>> numericFunctionMap = new HashMap<>();
    protected Map<String, SerializableFunction<Object, Double>> categoricalFunctionMap = new HashMap<>();
    protected Map<String, Object> outputFieldsMap = new HashMap<>();
    protected Map<String, SerializableFunction<Map<String, Object>, Double>> predictorTermsFunctionMap = new HashMap<>();
    protected double intercept;
    protected String targetField;

    public abstract Object getTargetCategory();

    public Object evaluateRegression(Map<String, Object> input) {
        final AtomicReference<Double> result = new AtomicReference<>(intercept);
        final Map<String, Double> resultMap = new HashMap<>();
        for (Map.Entry<String, SerializableFunction<Double, Double>> entry : numericFunctionMap.entrySet()) {
            String key = entry.getKey();
            if (input.containsKey(key)) {
                resultMap.put(key, entry.getValue().apply(((Number) input.get(key)).doubleValue()));
            }
        }
        for (Map.Entry<String, SerializableFunction<Object, Double>> entry : categoricalFunctionMap.entrySet()) {
            String key = entry.getKey();
            if (input.containsKey(key)) {
                resultMap.put(key, entry.getValue().apply(input.get(key)));
            }
        }
        for (Map.Entry<String, SerializableFunction<Map<String, Object>, Double>> entry : predictorTermsFunctionMap.entrySet()) {
            resultMap.put(entry.getKey(), entry.getValue().apply(input));
        }
        resultMap.values().forEach(value -> result.accumulateAndGet(value, Double::sum));
        updateResult(result);
        return result.get();
    }

    public Map<String, Object> getOutputFieldsMap() {
        return outputFieldsMap;
    }

    public String getTargetField() {
        return targetField;
    }

    public Map<String, SerializableFunction<Double, Double>> getNumericFunctionMap() {
        return numericFunctionMap;
    }

    public Map<String, SerializableFunction<Object, Double>> getCategoricalFunctionMap() {
        return categoricalFunctionMap;
    }

    public Map<String, SerializableFunction<Map<String, Object>, Double>> getPredictorTermsFunctionMap() {
        return predictorTermsFunctionMap;
    }

    public double getIntercept() {
        return intercept;
    }

    public LinkedHashMap<String, Double> getProbabilityResultMap() {
        return new LinkedHashMap<>();
    }

    protected abstract void updateResult(final AtomicReference<Double> toUpdate);

}


text:
<?php

use Tygh\Registry;

if (!defined('BOOTSTRAP')) { die('Access denied'); }

function fn_required_products_get_products(&$params, &$fields, &$sortings, &$condition, &$join, &$sorting, &$group_by)
{
    if (!empty($params['for_required_product'])) {
        $join .= " LEFT JOIN ?:product_required_products ON products.product_id = ?:product_required_products.required_id";
        $condition .= db_quote(" AND ?:product_required_products.product_id = ?i", $params['for_required_product']);
    }

}

function fn_required_products_get_product_data_post(&$product, &$auth)
{
    if (!empty($product['product_id'])) {

        list($required) = fn_get_products(array('for_required_product' => $product['product_id']));

        if (count($required)) {
            $product['have_required'] = 'Y';

            $ids = array ();
            foreach ($required as $entry) {
                $ids[] = $entry['product_id'];
            }

            $have = fn_required_products_get_existent($auth, $ids, false);

            $product['required_products'] = array ();

            fn_gather_additional_products_data($required, array('get_icon' => true, 'get_detailed' => true, 'get_options' => true, 'get_discounts' => true));

            foreach ($required as $entry) {
                $id = $entry['product_id'];

                $product['required_products'][$id] = $entry;
                $product['required_products'][$id]['bought'] = ($have && in_array($id, $have)) ? 'Y' : 'N';
            }

            if (!empty($have) && count($have) >= count($ids)) {
                $product['can_add_to_cart'] = 'Y';
            } else {
                $product['can_add_to_cart'] = 'N';
            }
        } else {
            $product['have_required'] = 'N';
        }
    }
}

function fn_required_products_in_cart($auth, $ids)
{
    $data = array ();

    if (!empty($_SESSION['cart']) && !empty($_SESSION['cart']['products'])) {
        foreach ($ids as $id) {
            foreach ($_SESSION['cart']['products'] as $entry) {
                if ($entry['product_id'] == $id) {
                    $data[] = $id;
                }
            }
        }
    }

    $data = array_unique($data);

    return $data;
}

function fn_required_products_get_existent($auth, $ids, $look_in_cart = true)
{
    if (empty($ids)) {
        return false;
    }

    if (!empty($auth['user_id'])) {
        $data = db_get_fields('SELECT ?:order_details.product_id FROM ?:orders LEFT JOIN ?:order_details ON ?:orders.order_id = ?:order_details.order_id WHERE ?:orders.status IN (?a) AND ?:orders.user_id = ?i AND ?:order_details.product_id IN (?n) GROUP BY ?:order_details.product_id', array ('P', 'C'), $auth['user_id'], $ids);
    } else {
        $data = array();
    }

    if ($look_in_cart) {
        $data = array_merge($data, fn_required_products_in_cart($auth, $ids));
        $data = array_unique($data);
    }

    return $data;
}

/**
 * Gets required products for products
 *
 * @param int $product_id Product identifier
 * @return array Reuired products identifiers
 */
function fn_get_required_products_ids($product_id)
{
    $join = db_quote(' LEFT JOIN ?:products ON req_prod.required_id = ?:products.product_id');
    $condition = db_quote(' req_prod.product_id = ?i AND ?:products.status != ?s', $product_id, 'D');

    if (fn_allowed_for('ULTIMATE') && Registry::get('runtime.company_id')) {
        $join .= db_quote(' LEFT JOIN ?:products_categories ON req_prod.required_id = ?:products_categories.product_id');
        $join .= db_quote(' LEFT JOIN ?:categories ON ?:products_categories.category_id = ?:categories.category_id');
        $condition .= fn_get_company_condition('?:categories.company_id');
    }

    $ids = db_get_fields("SELECT req_prod.required_id FROM ?:product_required_products as req_prod $join WHERE $condition GROUP BY req_prod.required_id");

    return $ids;
}

/**
 * Checks product list and adds required products
 *
 * @param array $product_data Products data
 * @param mixed $auth Array with authorization data
 * @param array $cart
 * @param array $added_products Products that are checked for further products that need to be added
 * @return bool False if some products were removed, otherwise - true
 */
function fn_check_added_required_products(&$product_data, $auth, &$cart, $added_products = array())
{
    $result = true;

    foreach ($product_data as $key => $entry) {
        if (!empty($entry['amount']) && !empty($key)) {
            $product_id = !empty($entry['product_id']) ? $entry['product_id'] : $key;
            $added_products[$product_id] = $entry;

            $ids = fn_get_required_products_ids($product_id);

            if (!empty($ids)) {
                $have = fn_required_products_get_existent($auth, $ids);

                if (empty($have) || count($have) != count($ids)) {
                    $products_to_cart = array_diff($ids, $have);
                    $out_of_stock = array();
                    $check_products = array();
                    foreach ($products_to_cart as $id) {
                        if (!empty($added_products[$id])) {
                            continue;
                        }

                        $amount = fn_check_amount_in_stock($id, 1, fn_get_default_product_options($id), 0, 'N', 0, $cart);

                        if (!$amount) {
                            $out_of_stock[] = $id;
                        } else {
                            $check_products[$id] = array('product_id' => $id, 'amount' => $amount);
                        }
                    }

                    if (empty($out_of_stock) && fn_check_added_required_products($check_products, $auth, $cart, $added_products)) {
                        $cart['change_cart_products'] = true;
                        $msg = __('required_products_added');

                        foreach ($check_products as $id => $v) {
                            if (empty($added_products[$id])) {
                                $added_products[$id] = $v;
                                $product_data[$id] = $v;
                                $msg .= "
" . fn_get_product_name($id);

                                $cart['amount'] = !isset($cart['amount']) ? $v['amount'] : $cart['amount'] + $v['amount'];
                            }
                        }
                    } else {
                        unset($product_data[$key]);
                        unset($added_products[$product_id]);
                        $result = false;
                        $msg = __('required_products_out_of_stock');
                        foreach ($out_of_stock as $id) {
                            $msg .= "
" . fn_get_product_name($id);
                        }
                    }
                    fn_set_notification('N', __('notice'), $msg);
                }
            }
        }
    }

    return $result;
}

function fn_required_products_pre_add_to_cart(&$product_data, &$cart, &$auth, &$update)
{
    fn_check_added_required_products($product_data, $auth, $cart);

    return true;
}

/**
 * Checks if any products should be deleted from cart with the deleted cart product
 *
 * @param array $cart Array of the cart contents and user information necessary for purchase
 * @param int $cart_id Deleted product identifier
 * @return bool Always true
 */
function fn_check_deleted_required_products(&$cart, $cart_id)
{
    $auth = !empty($_SESSION['auth']['user_id']) ? $_SESSION['auth']['user_id'] : array();

    if (!empty($cart_id) && !empty($cart['products'][$cart_id])) {
        $product_id = $cart['products'][$cart_id]['product_id'];

        $products = db_get_fields('SELECT product_id FROM ?:product_required_products WHERE required_id = ?i', $product_id);

        if (count($products)) {
            foreach ($cart['products'] as $key => $product) {
                if (in_array($product['product_id'], $products)) {
                    $haved = fn_required_products_get_existent($auth, array($product_id), false);

                    if (!empty($haved)) {
                        fn_check_deleted_required_products($cart, $key);
                        unset($cart['products'][$key]);
                        foreach ($cart['product_groups'] as $key_group => $group) {
                            if (in_array($key, array_keys($group['products']))) {
                                unset($cart['product_groups'][$key_group]['products'][$key]);
                            }
                        }
                    }
                }
            }
        }
    }

    return true;
}

function fn_required_products_delete_cart_product(&$cart, &$cart_id, &$full_erase)
{
    fn_check_deleted_required_products($cart, $cart_id);

    return true;
}

function fn_required_products_delete_product_post($product_id)
{
    if (!empty($product_id)) {
        db_query('DELETE FROM ?:product_required_products WHERE product_id = ?i OR required_id = ?i', $product_id, $product_id);
    }

    return true;
}

/**
 * Checks required products on recalculation
 *
 * @param array $cart Array of the cart contents and user information necessary for purchase
 * @param array $cart_products Cart products
 * @param array $auth Array of user authentication data (e.g. uid, usergroup_ids, etc.)
 * @return bool Always true
 */
function fn_check_calculated_required_products(&$cart, &$cart_products, $auth)
{
    if (!empty($cart['products'])) {
        foreach ($cart['products'] as $key => $entry) {
            if (!empty($entry['product_id'])) {
                $ids = fn_get_required_products_ids($entry['product_id']);

                if (!empty($ids)) {
                    $have = fn_required_products_get_existent($auth, $ids);
                    if (empty($have) || count($have) != count($ids)) {
                        if (empty($entry['extra']['parent'])) {
                            $cart['amount'] -= $entry['amount'];
                        }
                        unset($cart['products'][$key]);
                        unset($cart_products[$key]);
                        foreach ($cart['product_groups'] as $key_group => $group) {
                            if (in_array($key, array_keys($group['products']))) {
                                unset($cart['product_groups'][$key_group]['products'][$key]);
                            }
                        }
                        fn_check_calculated_required_products($cart, $cart_products, $auth);
                    }
                }
            }
        }
    }

    return true;
}

function fn_required_products_calculate_cart_items(&$cart, &$cart_products, &$auth)
{
    fn_check_calculated_required_products($cart, $cart_products, $auth);
}


text:
'use strict';

import AnimatedNode from './AnimatedNode';
import AnimatedTransform from './AnimatedTransform';
import AnimatedWithChildren from './AnimatedWithChildren';
import NativeAnimatedHelper from '../NativeAnimatedHelper';
import StyleSheet from '../../../../exports/StyleSheet';
var flattenStyle = StyleSheet.flatten;

function createAnimatedStyle(inputStyle) {
  var style = flattenStyle(inputStyle);
  var animatedStyles = {};

  for (var key in style) {
    var value = style[key];

    if (key === 'transform') {
      animatedStyles[key] = new AnimatedTransform(value);
    } else if (value instanceof AnimatedNode) {
      animatedStyles[key] = value;
    } else if (value && !Array.isArray(value) && typeof value === 'object') {
      animatedStyles[key] = createAnimatedStyle(value);
    }
  }

  return animatedStyles;
}

class AnimatedStyle extends AnimatedWithChildren {
  constructor(style) {
    super();
    this._inputStyle = style;
    this._style = createAnimatedStyle(style);
  } // Recursively get values for nested styles (like iOS's shadowOffset)

  _walkStyleAndGetValues(style) {
    var updatedStyle = {};

    for (var key in style) {
      var value = style[key];

      if (value instanceof AnimatedNode) {
        if (!value.__isNative) {
          // We cannot use value of natively driven nodes this way as the value we have access from
          // JS may not be up to date.
          updatedStyle[key] = value.__getValue();
        }
      } else if (value && !Array.isArray(value) && typeof value === 'object') {
        // Support animating nested values (for example: shadowOffset.height)
        updatedStyle[key] = this._walkStyleAndGetValues(value);
      } else {
        updatedStyle[key] = value;
      }
    }

    return updatedStyle;
  }

  __getValue() {
    return [this._inputStyle, this._walkStyleAndGetValues(this._style)];
  } // Recursively get animated values for nested styles (like iOS's shadowOffset)

  _walkStyleAndGetAnimatedValues(style) {
    var updatedStyle = {};

    for (var key in style) {
      var value = style[key];

      if (value instanceof AnimatedNode) {
        updatedStyle[key] = value.__getAnimatedValue();
      } else if (value && !Array.isArray(value) && typeof value === 'object') {
        // Support animating nested values (for example: shadowOffset.height)
        updatedStyle[key] = this._walkStyleAndGetAnimatedValues(value);
      }
    }

    return updatedStyle;
  }

  __getAnimatedValue() {
    return this._walkStyleAndGetAnimatedValues(this._style);
  }

  __attach() {
    for (var key in this._style) {
      var value = this._style[key];

      if (value instanceof AnimatedNode) {
        value.__addChild(this);
      }
    }
  }

  __detach() {
    for (var key in this._style) {
      var value = this._style[key];

      if (value instanceof AnimatedNode) {
        value.__removeChild(this);
      }
    }

    super.__detach();
  }

  __makeNative() {
    for (var key in this._style) {
      var value = this._style[key];

      if (value instanceof AnimatedNode) {
        value.__makeNative();
      }
    }

    super.__makeNative();
  }

  __getNativeConfig() {
    var styleConfig = {};

    for (var styleKey in this._style) {
      if (this._style[styleKey] instanceof AnimatedNode) {
        var style = this._style[styleKey];

        style.__makeNative();

        styleConfig[styleKey] = style.__getNativeTag();
      }
    }

    NativeAnimatedHelper.validateStyles(styleConfig);
    return {
      type: 'style',
      style: styleConfig
    };
  }

}

export default AnimatedStyle;


text:
<?php

// # Get Invoice Sample
// This sample code demonstrate how you can retrieve
// an invoice.

/** @var Invoice $invoice */
$invoice = require 'CreateInvoice.php';
use PayPal\Api\Invoice;

$invoiceId = $invoice->getId();

// ### Retrieve Invoice
// Retrieve the invoice object by calling the
// static `get` method
// on the Invoice class by passing a valid
// Invoice ID
// (See bootstrap.php for more on `ApiContext`)
try {
    $invoice = Invoice::get($invoiceId, $apiContext);
} catch (Exception $ex) {
    // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
    ResultPrinter::printError("Get Invoice", "Invoice", $invoice->getId(), $invoiceId, $ex);
    exit(1);
}

// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
 ResultPrinter::printResult("Get Invoice", "Invoice", $invoice->getId(), $invoiceId, $invoice);

return $invoice;


text:
*Access an embedded minikube instance or remote a Kubernetes cluster from inside a dev container. Includes kubectl, Helm, minikube, and the Docker.*

| Metadata | Value |
|----------|-------|
| *Contributors* | The VS Code team |
| *Categories* | Other |
| *Definition type* | Dockerfile |
| *Works in Codespaces* | Yes |
| *Container host OS support* | Linux, macOS, Windows |
| *Container OS* | Debian |
| *Languages, platforms* | Any |

## Description

> **Note:** If you're looking to reuse a local Kubernetes instance from Remote - Containers, you may find the [Kubernetes - Local Configuration](../kubernetes-helm) definition more interesting.

Dev containers can be useful for all types of applications including those that also deploy into a container based-environment. While you can directly build and run the application inside the dev container you create, you may also want to test it by deploying a built container image into a local minikube or remote [Kubernetes](https://kubernetes.io/) cluster without affecting your dev container.

This example illustrates how you can do this by using CLIs ([kubectl](https://kubernetes.io/docs/reference/kubectl/overview/), [Helm](https://helm.sh), Docker), the [Kubernetes extension](https://marketplace.visualstudio.com/items?itemName=ms-kubernetes-tools.vscode-kubernetes-tools), and the [Docker extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-docker) right from inside your dev container.  This definition builds up from the [docker-in-docker](../docker-in-docker) container definition along with a [minikube](https://minikube.sigs.k8s.io/docs/) installation that can run right inside the container. It installs the Docker and Kubernetes extensions inside the container so you can use its full feature set with your project.

## Using this definition with an existing folder

A few notes on the definition:

* The included `.devcontainer/Dockerfile` can be altered to work with other Debian/Ubuntu-based container images such as `node` or `python`. Just, update the `FROM` statement to reference the new base image. For example:

    ```Dockerfile
    FROM node:lts
    ```

* If you want minikube to automatically start when the dev container starts, uncomment the following line:

    ```json
    "postStartCommand": "nohup bash -c 'minikube start &' > minikube.log 2>&1",
    ```

    This will log minikube output to `minikube.log` in your workspace folder, but you can update that part of the line above to a different path if you wish (e.g. `/tmp/minikube.log`).

Beyond that, just follow these steps to use the definition:

1. If this is your first time using a development container, please see getting started information on [setting up](https://aka.ms/vscode-remote/containers/getting-started) Remote-Containers or [creating a codespace](https://aka.ms/ghcs-open-codespace) using GitHub Codespaces.

2. Start VS Code and open your project folder or connect to a codespace.

3. Press F1 select and **Add Development Container Configuration Files...** command for **Remote-Containers** or **Codespaces**.

   > **Note:** If needed, you can drag-and-drop the `.devcontainer` folder from this sub-folder in a locally cloned copy of this repository into the VS Code file explorer instead of using the command.

4. Select this definition. You may also need to select **Show All Definitions...** for it to appear.

5. Finally, press F1 and run **Remote-Containers: Reopen Folder in Container** or **Codespaces: Rebuild Container** to start using the definition.

## License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License. See [LICENSE](https://github.com/microsoft/vscode-dev-containers/blob/main/LICENSE).


text:
//
//  PepperTalkConstants.h
//  PepperTalk
//
//  Created by HIMANSHU RETAREKAR on 05/12/14.
//  Copyright (c) 2014 Espreccino. All rights reserved.
//

#ifndef PepperTalk_PepperTalkConstants_h
#define PepperTalk_PepperTalkConstants_h

/**
 Reserved keys which are used to get values from NSDictionary returned by unreadNotificationCount calls
 */
extern NSString *const PTUnreadCountQueryTotalUnreadCountKey;
extern NSString *const PTUnreadCountQueryParticipantsKey;
extern NSString *const PTUnreadCountQueryTopicsKey;

//================================================Notifications Related================================================//

/**
 Notification with name PTUnreadCountUpdateNotification is posted to notify observers about unread count updates. Notification userInfo has following format:
 {
     PTUnreadCountQueryTopicsKey : {
         # topic id : # unread count for the topic,
         # topic id : # unread count for the topic,
     }
     PTUnreadCountQueryTotalUnreadCountKey : # id of participant
 }
 */
extern NSString *const PTUnreadCountUpdateNotification;
extern NSString *const PTUnreadCountUpdateNotification_ParticipantKey;
extern NSString *const PTUnreadCountUpdateNotification_TopicIdKey;
extern NSString *const PTUnreadCountUpdateNotification_UnreadCountKey;

/**
 Notification with name PTReceivedCustomDataNotification is posted to notify observers about incoming custom data. Notification userInfo has the following format:
 {
     PTReceivedCustomDataNotification_MsgDataKey : {
        PTReceivedCustomDataNotification_MsgData_ToKey : # custom data receipient id
        PTReceivedCustomDataNotification_MsgData_FromKey : # custom data sender id
        PTReceivedCustomDataNotification_MsgData_TimestampKey : # custom data timestamp in epoch milliseconds
        PTReceivedCustomDataNotification_MsgData_TopicIdKey : # topic id
        PTReceivedCustomDataNotification_MsgData_TopicTitleKey : topic title
     }
     PTReceivedCustomDataNotification_CustomDataKey : # actual custom data from other end in form of NSDictionary
 }
 */
extern NSString *const PTReceivedCustomDataNotification;
extern NSString *const PTReceivedCustomDataNotification_MsgDataKey;
extern NSString *const PTReceivedCustomDataNotification_MsgData_ToKey;
extern NSString *const PTReceivedCustomDataNotification_MsgData_FromKey;
extern NSString *const PTReceivedCustomDataNotification_MsgData_TimestampKey;
extern NSString *const PTReceivedCustomDataNotification_MsgData_TopicIdKey;
extern NSString *const PTReceivedCustomDataNotification_MsgData_TopicTitleKey;
extern NSString *const PTReceivedCustomDataNotification_CustomDataKey;

#endif


text:
@interface ViewController : UIViewController <PAPasscodeViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *passcodeLabel;
@property (weak, nonatomic) IBOutlet UISwitch *simpleSwitch;

- (IBAction)setPasscode:(id)sender;
- (IBAction)enterPasscode:(id)sender;
- (IBAction)changePasscode:(id)sender;

@end


text:
export { default as AudioMutedIndicator } from './AudioMutedIndicator';
export { default as DominantSpeakerIndicator } from './DominantSpeakerIndicator';
export { default as Filmstrip } from './Filmstrip';
export { default as ModeratorIndicator } from './ModeratorIndicator';
export { default as RaisedHandIndicator } from './RaisedHandIndicator';
export { default as StatusIndicators } from './StatusIndicators';
export { default as VideoMutedIndicator } from './VideoMutedIndicator';


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

[assembly: System.Reflection.AssemblyCompany("Exxeleron GmbH")]
[assembly: System.Reflection.AssemblyTitle("qXL")]
[assembly: System.Reflection.AssemblyProduct("qXL")]
[assembly: System.Reflection.AssemblyCopyright("Copyright © Exxeleron GmbH 2015")]
[assembly: System.Reflection.AssemblyVersion("1.0.1.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.0.1.0")]