text:
import { Vector3 } from "../Maths/math.vector";
import type { Nullable } from "../types";
import type { ActionManager } from "../Actions/actionManager";
import type { ISpriteManager, SpriteManager } from "./spriteManager";
import { Color4 } from "../Maths/math.color";
import { Observable } from "../Misc/observable";
import type { IAnimatable } from "../Animations/animatable.interface";
import { ThinSprite } from "./thinSprite";

declare type Animation = import("../Animations/animation").Animation;

/**
 * Class used to represent a sprite
 * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites
 */
export class Sprite extends ThinSprite implements IAnimatable {
    /** Gets or sets the current world position */
    public position: Vector3;
    /** Gets or sets the main color */
    public color: Color4;
    /** Gets or sets a boolean indicating that this sprite should be disposed after animation ends */
    public disposeWhenFinishedAnimating: boolean;
    /** Gets the list of attached animations */
    public animations: Nullable<Array<Animation>> = new Array<Animation>();
    /** Gets or sets a boolean indicating if the sprite can be picked */
    public isPickable = false;
    /** Gets or sets a boolean indicating that sprite texture alpha will be used for precise picking (false by default) */
    public useAlphaForPicking = false;

    /**
     * Gets or sets the associated action manager
     */
    public actionManager: Nullable<ActionManager>;

    /**
     * An event triggered when the control has been disposed
     */
    public onDisposeObservable = new Observable<Sprite>();

    private _manager: ISpriteManager;
    private _onAnimationEnd: Nullable<() => void> = null;

    /**
     * Gets or sets the sprite size
     */
    public get size(): number {
        return this.width;
    }

    public set size(value: number) {
        this.width = value;
        this.height = value;
    }

    /**
     * Gets or sets the unique id of the sprite
     */
    public uniqueId: number;

    /**
     * Gets the manager of this sprite
     */
    public get manager() {
        return this._manager;
    }

    /**
     * Creates a new Sprite
     * @param name defines the name
     * @param manager defines the manager
     */
    constructor(
        /** defines the name */
        public name: string,
        manager: ISpriteManager
    ) {
        super();
        this.color = new Color4(1.0, 1.0, 1.0, 1.0);
        this.position = Vector3.Zero();

        this._manager = manager;
        this._manager.sprites.push(this);
        this.uniqueId = this._manager.scene.getUniqueId();
    }

    /**
     * Returns the string "Sprite"
     * @returns "Sprite"
     */
    public getClassName(): string {
        return "Sprite";
    }

    /** Gets or sets the initial key for the animation (setting it will restart the animation)  */
    public get fromIndex() {
        return this._fromIndex;
    }
    public set fromIndex(value: number) {
        this.playAnimation(value, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd);
    }

    /** Gets or sets the end key for the animation (setting it will restart the animation)  */
    public get toIndex() {
        return this._toIndex;
    }
    public set toIndex(value: number) {
        this.playAnimation(this._fromIndex, value, this._loopAnimation, this._delay, this._onAnimationEnd);
    }

    /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation)  */
    public get loopAnimation() {
        return this._loopAnimation;
    }
    public set loopAnimation(value: boolean) {
        this.playAnimation(this._fromIndex, this._toIndex, value, this._delay, this._onAnimationEnd);
    }

    /** Gets or sets the delay between cell changes (setting it will restart the animation)  */
    public get delay() {
        return Math.max(this._delay, 1);
    }
    public set delay(value: number) {
        this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, value, this._onAnimationEnd);
    }

    /**
     * Starts an animation
     * @param from defines the initial key
     * @param to defines the end key
     * @param loop defines if the animation must loop
     * @param delay defines the start delay (in ms)
     * @param onAnimationEnd defines a callback to call when animation ends
     */
    public playAnimation(from: number, to: number, loop: boolean, delay: number, onAnimationEnd: Nullable<() => void> = null): void {
        this._onAnimationEnd = onAnimationEnd;

        super.playAnimation(from, to, loop, delay, this._endAnimation);
    }

    private _endAnimation = () => {
        if (this._onAnimationEnd) {
            this._onAnimationEnd();
        }
        if (this.disposeWhenFinishedAnimating) {
            this.dispose();
        }
    };

    /** Release associated resources */
    public dispose(): void {
        for (let i = 0; i < this._manager.sprites.length; i++) {
            if (this._manager.sprites[i] == this) {
                this._manager.sprites.splice(i, 1);
            }
        }

        // Callback
        this.onDisposeObservable.notifyObservers(this);
        this.onDisposeObservable.clear();
    }

    /**
     * Serializes the sprite to a JSON object
     * @returns the JSON object
     */
    public serialize(): any {
        const serializationObject: any = {};

        serializationObject.name = this.name;
        serializationObject.position = this.position.asArray();
        serializationObject.color = this.color.asArray();
        serializationObject.width = this.width;
        serializationObject.height = this.height;
        serializationObject.angle = this.angle;
        serializationObject.cellIndex = this.cellIndex;
        serializationObject.cellRef = this.cellRef;
        serializationObject.invertU = this.invertU;
        serializationObject.invertV = this.invertV;
        serializationObject.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating;
        serializationObject.isPickable = this.isPickable;
        serializationObject.isVisible = this.isVisible;
        serializationObject.useAlphaForPicking = this.useAlphaForPicking;

        serializationObject.animationStarted = this.animationStarted;
        serializationObject.fromIndex = this.fromIndex;
        serializationObject.toIndex = this.toIndex;
        serializationObject.loopAnimation = this.loopAnimation;
        serializationObject.delay = this.delay;

        return serializationObject;
    }

    /**
     * Parses a JSON object to create a new sprite
     * @param parsedSprite The JSON object to parse
     * @param manager defines the hosting manager
     * @returns the new sprite
     */
    public static Parse(parsedSprite: any, manager: SpriteManager): Sprite {
        const sprite = new Sprite(parsedSprite.name, manager);

        sprite.position = Vector3.FromArray(parsedSprite.position);
        sprite.color = Color4.FromArray(parsedSprite.color);
        sprite.width = parsedSprite.width;
        sprite.height = parsedSprite.height;
        sprite.angle = parsedSprite.angle;
        sprite.cellIndex = parsedSprite.cellIndex;
        sprite.cellRef = parsedSprite.cellRef;
        sprite.invertU = parsedSprite.invertU;
        sprite.invertV = parsedSprite.invertV;
        sprite.disposeWhenFinishedAnimating = parsedSprite.disposeWhenFinishedAnimating;
        sprite.isPickable = parsedSprite.isPickable;
        sprite.isVisible = parsedSprite.isVisible;
        sprite.useAlphaForPicking = parsedSprite.useAlphaForPicking;

        sprite.fromIndex = parsedSprite.fromIndex;
        sprite.toIndex = parsedSprite.toIndex;
        sprite.loopAnimation = parsedSprite.loopAnimation;
        sprite.delay = parsedSprite.delay;

        if (parsedSprite.animationStarted) {
            sprite.playAnimation(sprite.fromIndex, sprite.toIndex, sprite.loopAnimation, sprite.delay);
        }

        return sprite;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">

<title>IIndexedItemEvent Methods Public Methods</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="generator" content="Doc-O-Matic" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <link rel="STYLESHEET" href="default.css" type="text/css" />

Lightstreamer .Net Adapter 1.8

IIndexedItemEvent Methods Public Methods

IIndexedItemEvent Methods  Legend

Public Methods

Name

Description

GetIndex

Returns the index of a named Field. Returns -1 if such a field is not reported in this event. Lightstreamer Kernel, through the Remote Server, will call this method up to once for every distinct client request of the Item. So, the implementation must be very fast.

GetMaximumIndex

Returns the maximum index for the fields in the event. The event cannot be empty, so the maximum Index must always exist.

GetName

Returns the name of a Field whose index is supplied. Returns null if the Field is not reported in this event.

GetValue

Returns the value of a field whose index is supplied (null is a legal value too). Returns null if the Field is not reported in the Item Event. The value can be expressed as either a String or a byte array, the latter case being the most efficient, though restricted to the ISO-8859-1 (ISO-LATIN-1) character set.

Copyright (C) 2004-2013 Weswit s.r.l.

Contents | Index | Home

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 310657 $ -->
<refentry xml:id="phardata.buildfromiterator" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>PharData::buildFromIterator</refname>
  <refpurpose>Construct a tar or zip archive from an iterator.</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>array</type><methodname>PharData::buildFromIterator</methodname>
   <methodparam><type>Iterator</type><parameter>iter</parameter></methodparam>
   <methodparam choice="opt"><type>string</type><parameter>base_directory</parameter></methodparam>
  </methodsynopsis>
  <para>
   Populate a tar or zip archive from an iterator.  Two styles of iterators are supported,
   iterators that map the filename within the tar/zip to the name of a file on disk,
   and iterators like DirectoryIterator that return
   SplFileInfo objects.  For iterators that return SplFileInfo objects, the second
   parameter is required.
  </para>
 </refsect1>
 <refsect1 role="examples">
  &reftitle.examples;
   <example>
    <title>A <function>PharData::buildFromIterator</function> with SplFileInfo</title>
  <para>
   For most tar/zip archives, the archive will reflect an actual directory layout, and
   the second style is the most useful.  For instance, to create a tar/zip archive
   containing the files in this sample directory layout:
  </para>
  <para>
   <screen>
    <![CDATA[
/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php
    ]]>
   </screen>
  </para>
  <para>
   This code could be used to add these files to the "project.tar" tar archive:
  </para>
  <para>
   <programlisting role="php">
    <![CDATA[
<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new RecursiveDirectoryIterator('/path/to/project')),
    '/path/to/project');
?>
    ]]>
   </programlisting>
  </para>
  <para>
   The file <literal>project.tar</literal> can then be used immediately.  <function>PharData::buildFromIterator</function> does not
   set values such as compression, metadata, and this can be done after creating the
   tar/zip archive.
  </para>
  <para>
   As an interesting note, <function>PharData::buildFromIterator</function> can also be used to
   copy the contents of an existing phar, tar or zip archive, as the PharData object descends
   from <classname>DirectoryIterator</classname>:
  </para>
  <para>
   <programlisting role="php">
    <![CDATA[
<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
     new Phar('/path/to/anotherphar.phar')),
    'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
    ]]>
   </programlisting>
  </para>
  </example>
  <example>
    <title>A <function>PharData::buildFromIterator</function> with other iterators</title>
  <para>
   The second form of the iterator can be used with any iterator that returns
   a key => value mapping, such as an <classname>ArrayIterator</classname>:
  </para>
  <para>
   <programlisting role="php">
    <![CDATA[
<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
    new ArrayIterator(
     array(
        'internal/file.php' => dirname(__FILE__) . '/somefile.php',
        'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
     )));
?>
    ]]>
   </programlisting>
  </para>
  </example>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>iter</parameter></term>
     <listitem>
      <para>
       Any iterator that either associatively maps tar/zip file to location or
       returns SplFileInfo objects
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>base_directory</parameter></term>
     <listitem>
      <para>
       For iterators that return SplFileInfo objects, the portion of each
       file's full path to remove when adding to the tar/zip archive
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>

 </refsect1>
 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   <function>PharData::buildFromIterator</function> returns an associative array
   mapping internal path of file to the full path of the file on the
   filesystem.
  </para>
 </refsect1>

 <refsect1 role="errors">
  &reftitle.errors;
  <para>
   This method returns <classname>UnexpectedValueException</classname> when the
   iterator returns incorrect values, such as an integer key instead of a
   string, a <classname>BadMethodCallException</classname> when an
   SplFileInfo-based iterator is passed without a <parameter>base_directory</parameter>
   parameter, or a <classname>PharException</classname> if there were errors
   saving the phar archive.
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>Phar::buildFromIterator</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package com.spotify.docker.client.messages;

import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;

import com.google.common.collect.ImmutableList;
import java.util.List;
import javax.annotation.Nullable;

@AutoValue
@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE)
public abstract class VolumeList {

  @Nullable
  @JsonProperty("Volumes")
  public abstract ImmutableList<Volume> volumes();

  @Nullable
  @JsonProperty("Warnings")
  public abstract ImmutableList<String> warnings();

  @JsonCreator
  static VolumeList create(
      @JsonProperty("Volumes") final List<Volume> volumes,
      @JsonProperty("Warnings") final List<String> warnings) {
    final ImmutableList<Volume> volumesCopy = volumes == null
                                               ? null : ImmutableList.copyOf(volumes);
    final ImmutableList<String> warningsCopy = warnings == null
                                               ? null : ImmutableList.copyOf(warnings);
    return new AutoValue_VolumeList(volumesCopy, warningsCopy);
  }
}


text:
using UnityEngine;

[RequireComponent(typeof(AudioSource))]

//-------------------------------------------------------------------------------------
// ***** OVRLipSyncContext
//
/// <summary>
/// OVRLipSyncContext interfaces into the Oculus phoneme recognizer.
/// This component should be added into the scene once for each Audio Source.
///
/// </summary>
public class OVRLipSyncContext : OVRLipSyncContextBase
{
    // * * * * * * * * * * * * *
    // Public members

    [Tooltip("Allow capturing of keyboard input to control operation.")]
    public bool enableKeyboardInput = false;
    [Tooltip("Register a mouse/touch callback to control loopback and gain (requires script restart).")]
    public bool enableTouchInput = false;
    [Tooltip("Play input audio back through audio output.")]
    public bool audioLoopback = false;
    [Tooltip("Key to toggle audio loopback.")]
    public KeyCode loopbackKey = KeyCode.L;
    [Tooltip("Show viseme scores in an OVRLipSyncDebugConsole display.")]
    public bool showVisemes = false;
    [Tooltip("Key to toggle viseme score display.")]
    public KeyCode debugVisemesKey = KeyCode.D;
    [Tooltip("Skip data from the Audio Source. Use if you intend to pass audio data in manually.")]
    public bool skipAudioSource = false;
    [Tooltip("Adjust the linear audio gain multiplier before processing lipsync")]
    public float gain = 1.0f;

    private bool hasDebugConsole = false;

    public KeyCode debugLaughterKey = KeyCode.H;
    public bool showLaughter = false;
    public float laughterScore = 0.0f;

    // * * * * * * * * * * * * *
    // Private members

    /// <summary>
    /// Start this instance.
    /// Note: make sure to always have a Start function for classes that have editor scripts.
    /// </summary>
    void Start()
    {
        // Add a listener to the OVRTouchpad for touch events
        if (enableTouchInput)
        {
            OVRTouchpad.AddListener(LocalTouchEventCallback);
        }

        // Find console
        OVRLipSyncDebugConsole[] consoles = FindObjectsOfType<OVRLipSyncDebugConsole>();
        if (consoles.Length > 0)
        {
            hasDebugConsole = consoles[0];
        }
    }

    /// <summary>
    /// Handle keyboard input
    /// </summary>
    void HandleKeyboard()
    {
        // Turn loopback on/off
        if (Input.GetKeyDown(loopbackKey))
        {
            ToggleAudioLoopback();
        }
        else if (Input.GetKeyDown(debugVisemesKey))
        {
            showVisemes = !showVisemes;

            if (showVisemes)
            {
                if (hasDebugConsole)
                {
                    Debug.Log("DEBUG SHOW VISEMES: ENABLED");
                }
                else
                {
                    Debug.LogWarning("Warning: No OVRLipSyncDebugConsole in the scene!");
                    showVisemes = false;
                }
            }
            else
            {
                if (hasDebugConsole)
                {
                    OVRLipSyncDebugConsole.Clear();
                }
                Debug.Log("DEBUG SHOW VISEMES: DISABLED");
            }
        }
        else if (Input.GetKeyDown(debugLaughterKey))
        {
            showLaughter = !showLaughter;

            if (showLaughter)
            {
                if (hasDebugConsole)
                {
                    Debug.Log("DEBUG SHOW LAUGHTER: ENABLED");
                }
                else
                {
                    Debug.LogWarning("Warning: No OVRLipSyncDebugConsole in the scene!");
                    showLaughter = false;
                }
            }
            else
            {
                if (hasDebugConsole)
                {
                    OVRLipSyncDebugConsole.Clear();
                }
                Debug.Log("DEBUG SHOW LAUGHTER: DISABLED");
            }
        }
        else if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            gain -= 1.0f;
            if (gain < 1.0f) gain = 1.0f;

            string g = "LINEAR GAIN: ";
            g += gain;

            if (hasDebugConsole)
            {
                OVRLipSyncDebugConsole.Clear();
                OVRLipSyncDebugConsole.Log(g);
                OVRLipSyncDebugConsole.ClearTimeout(1.5f);
            }
        }
        else if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            gain += 1.0f;
            if (gain > 15.0f)
                gain = 15.0f;

            string g = "LINEAR GAIN: ";
            g += gain;

            if (hasDebugConsole)
            {
                OVRLipSyncDebugConsole.Clear();
                OVRLipSyncDebugConsole.Log(g);
                OVRLipSyncDebugConsole.ClearTimeout(1.5f);
            }
        }
    }

    /// <summary>
    /// Run processes that need to be updated in our game thread
    /// </summary>
    void Update()
    {
        if (enableKeyboardInput)
        {
            HandleKeyboard();
        }
        laughterScore = this.Frame.laughterScore;
        DebugShowVisemesAndLaughter();
    }

    /// <summary>
    /// Preprocess F32 PCM audio buffer
    /// </summary>
    /// <param name="data">Data.</param>
    /// <param name="channels">Channels.</param>
    public void PreprocessAudioSamples(float[] data, int channels)
    {
        // Increase the gain of the input
        for (int i = 0; i < data.Length; ++i)
        {
            data[i] = data[i] * gain;
        }
    }

    /// <summary>
    /// Postprocess F32 PCM audio buffer
    /// </summary>
    /// <param name="data">Data.</param>
    /// <param name="channels">Channels.</param>
    public void PostprocessAudioSamples(float[] data, int channels)
    {
        // Turn off output (so that we don't get feedback from mics too close to speakers)
        if (!audioLoopback)
        {
            for (int i = 0; i < data.Length; ++i)
                data[i] = data[i] * 0.0f;
        }
    }

    /// <summary>
    /// Pass F32 PCM audio buffer to the lip sync module
    /// </summary>
    /// <param name="data">Data.</param>
    /// <param name="channels">Channels.</param>
    public void ProcessAudioSamplesRaw(float[] data, int channels)
    {
        // Send data into Phoneme context for processing (if context is not 0)
        lock (this)
        {
            if (Context == 0 || OVRLipSync.IsInitialized() != OVRLipSync.Result.Success)
            {
                return;
            }
            var frame = this.Frame;
            OVRLipSync.ProcessFrame(Context, data, frame, channels == 2);
        }
    }

    /// <summary>
    /// Pass S16 PCM audio buffer to the lip sync module
    /// </summary>
    /// <param name="data">Data.</param>
    /// <param name="channels">Channels.</param>
    public void ProcessAudioSamplesRaw(short[] data, int channels)
    {
        // Send data into Phoneme context for processing (if context is not 0)
        lock (this)
        {
            if (Context == 0 || OVRLipSync.IsInitialized() != OVRLipSync.Result.Success)
            {
                return;
            }
            var frame = this.Frame;
            OVRLipSync.ProcessFrame(Context, data, frame, channels == 2);
        }
    }

    /// <summary>
    /// Process F32 audio sample and pass it to the lip sync module for computation
    /// </summary>
    /// <param name="data">Data.</param>
    /// <param name="channels">Channels.</param>
    public void ProcessAudioSamples(float[] data, int channels)
    {
        // Do not process if we are not initialized, or if there is no
        // audio source attached to game object
        if ((OVRLipSync.IsInitialized() != OVRLipSync.Result.Success) || audioSource == null)
        {
            return;
        }
        PreprocessAudioSamples(data, channels);
        ProcessAudioSamplesRaw(data, channels);
        PostprocessAudioSamples(data, channels);
    }

    /// <summary>
    /// Raises the audio filter read event.
    /// </summary>
    /// <param name="data">Data.</param>
    /// <param name="channels">Channels.</param>
    void OnAudioFilterRead(float[] data, int channels)
    {
        if (!skipAudioSource)
        {
            ProcessAudioSamples(data, channels);
        }
    }

    /// <summary>
    /// Print the visemes and laughter score to game window
    /// </summary>
    void DebugShowVisemesAndLaughter()
    {
        if (hasDebugConsole)
        {
            string seq = "";
            if (showLaughter)
            {
                seq += "Laughter:";
                int count = (int)(50.0f * this.Frame.laughterScore);
                for (int c = 0; c < count; c++)
                    seq += "*";
                seq += "\n";
            }
            if (showVisemes)
            {
                for (int i = 0; i < this.Frame.Visemes.Length; i++)
                {
                    seq += ((OVRLipSync.Viseme)i).ToString();
                    seq += ":";

                    int count = (int)(50.0f * this.Frame.Visemes[i]);
                    for (int c = 0; c < count; c++)
                        seq += "*";

                    seq += "\n";
                }
            }

            OVRLipSyncDebugConsole.Clear();

            if (seq != "")
            {
                OVRLipSyncDebugConsole.Log(seq);
            }
        }
    }

    void ToggleAudioLoopback()
    {
        audioLoopback = !audioLoopback;

        if (hasDebugConsole)
        {
            OVRLipSyncDebugConsole.Clear();
            OVRLipSyncDebugConsole.ClearTimeout(1.5f);

            if (audioLoopback)
                OVRLipSyncDebugConsole.Log("LOOPBACK MODE: ENABLED");
            else
                OVRLipSyncDebugConsole.Log("LOOPBACK MODE: DISABLED");
        }
    }

    // LocalTouchEventCallback
    void LocalTouchEventCallback(OVRTouchpad.TouchEvent touchEvent)
    {
        string g = "LINEAR GAIN: ";

        switch (touchEvent)
        {
            case (OVRTouchpad.TouchEvent.SingleTap):
                ToggleAudioLoopback();
                break;

            case (OVRTouchpad.TouchEvent.Up):
                gain += 1.0f;
                if (gain > 15.0f)
                    gain = 15.0f;

                g += gain;

                if (hasDebugConsole)
                {
                    OVRLipSyncDebugConsole.Clear();
                    OVRLipSyncDebugConsole.Log(g);
                    OVRLipSyncDebugConsole.ClearTimeout(1.5f);
                }

                break;

            case (OVRTouchpad.TouchEvent.Down):
                gain -= 1.0f;
                if (gain < 1.0f) gain = 1.0f;

                g += gain;

                if (hasDebugConsole)
                {
                    OVRLipSyncDebugConsole.Clear();
                    OVRLipSyncDebugConsole.Log(g);
                    OVRLipSyncDebugConsole.ClearTimeout(1.5f);
                }

                break;
        }
    }
}


text:
package org.cyclops.integrateddynamics.core.client.gui.container;

import com.google.common.collect.Lists;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import org.cyclops.cyclopscore.client.gui.container.ContainerScreenExtended;
import org.cyclops.cyclopscore.client.gui.image.Images;
import org.cyclops.cyclopscore.helper.L10NHelpers;
import org.cyclops.cyclopscore.helper.StringHelpers;

import javax.annotation.Nullable;
import java.awt.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * A component for displaying errors.
 * @author rubensworks
 */
public class DisplayErrorsComponent {

    public void drawForeground(PoseStack matrixStack, @Nullable List<MutableComponent> errors, int errorX, int errorY, int mouseX, int mouseY, ContainerScreenExtended<?> gui, int guiLeft, int guiTop) {
        if(errors != null && !errors.isEmpty()) {
            if(gui.isHovering(errorX, errorY, Images.ERROR.getSheetWidth(), Images.ERROR.getSheetHeight(), mouseX, mouseY)) {
                List<Component> lines = Lists.newLinkedList();
                for(Component error : errors) {
                    lines.addAll(StringHelpers.splitLines(error.getString(), L10NHelpers.MAX_TOOLTIP_LINE_LENGTH,
                            ChatFormatting.RED.toString())
                            .stream()
                            .map(Component::literal)
                            .collect(Collectors.toList()));
                }
                gui.drawTooltip(lines, matrixStack, mouseX - guiLeft, mouseY - guiTop);
            }
        }
    }

    public void drawBackground(PoseStack matrixStack, @Nullable List<MutableComponent> errors, int errorX, int errorY, int okX, int okY, ContainerScreenExtended<?> gui, int guiLeft, int guiTop, boolean okCondition) {
        // Render error symbol
        if(errors != null && !errors.isEmpty()) {
            Images.ERROR.draw(gui, matrixStack, guiLeft + errorX, guiTop + errorY);
        } else if(okCondition) {
            Images.OK.draw(gui, matrixStack, guiLeft + okX, guiTop + okY);
        }
    }

}


text:
package reo7sp.boardpp.ui

import reo7sp.boardpp.board.{BoardSession, BoardRule, BoardPage}
import javax.swing._
import java.awt.BorderLayout
import java.awt.event._
import reo7sp.boardpp.util.Colors
import javax.swing.event.{DocumentEvent, DocumentListener, ChangeEvent, ChangeListener}
import reo7sp.boardpp.board.brul.{ShowMsgOnLineRule, ShowMsgOnClickRule}
import reo7sp.boardpp.ui.widgets.awt.{FancyButton, FancyTextField}
import reo7sp.boardpp.Rules
import reo7sp.boardpp.ui.ShapeGetter.ShapeListener

/**
 * Created by reo7sp on 1/3/14 at 1:15 AM
 */
case class BoardRulesEditor(page: BoardPage) extends JFrame("Редактирование правил") {
  var curBtnID = -1
  var curRule: BoardRule = null

  val rulesList = new JPanel
  rulesList.setLayout(new BoxLayout(rulesList, BoxLayout.PAGE_AXIS))
  add(new JScrollPane(rulesList))

  for (rule <- BoardSession.board.curPage.rules) addRule(rule)

  val buttonsPanel = new JPanel
  add(buttonsPanel, BorderLayout.SOUTH)

  val addButton = new FancyButton
  addButton.setIcon(ImageFactory.getAwtIcon("new.png"))
  addButton.setToolTipText("Добавить")
  addButton.addActionListener(new ActionListener {
    def actionPerformed(p1: ActionEvent): Unit = BoardRulesEditor.showAdder(BoardRulesEditor.this)
  })
  buttonsPanel.add(addButton)

  val editButton = new FancyButton
  editButton.setIcon(ImageFactory.getAwtIcon("edit.png"))
  editButton.setToolTipText("Изменить")
  editButton.addActionListener(new ActionListener {
    def actionPerformed(p1: ActionEvent): Unit = if (curRule != null) {
      BoardRulesEditor.showEditor(BoardRulesEditor.this, curRule)
    }
  })
  buttonsPanel.add(editButton)

  val deleteButton = new FancyButton
  deleteButton.setIcon(ImageFactory.getAwtIcon("delete.png"))
  deleteButton.setToolTipText("Удалить")
  deleteButton.addActionListener(new ActionListener {
    def actionPerformed(p1: ActionEvent): Unit = if (curRule != null) {
      page -= curRule
      rulesList.remove(curBtnID)
      validate()
      curRule = null
      curBtnID = -1
      updBtns()
    }
  })
  buttonsPanel.add(deleteButton)

  setSize(800, 600)
  setLocationRelativeTo(null)
  setVisible(true)

  def addRule(rule: BoardRule) = {
    val btnID = rulesList.getComponentCount
    val btn = new FancyButton
    btn.setText("Если " + rule.conditionString + ", тогда " + rule.actionString)
    if (curBtnID == -1) {
      curBtnID = btnID
      curRule = rule
      updBtns()
    }
    btn.setAlignmentX(0.5F)
    btn.addActionListener(new ActionListener {
      def actionPerformed(p1: ActionEvent): Unit = {
        curBtnID = btnID
        curRule = rule
        updBtns()
      }
    })
    rulesList.add(btn)
    validate()
    repaint()
    btn
  }

  def updBtns(): Unit = {
    var i = 0
    for (c <- rulesList.getComponents) {
      c.setBackground(Colors.toAwt(if (i == curBtnID) Colors.blue else Colors.gray))
      i += 1
    }
    repaint()
  }
}

object BoardRulesEditor {
  private def showAdder(window: BoardRulesEditor): Unit = {
    window.setVisible(false)

    val frame = new JFrame("Выберите тип правила")
    frame.setSize(800, 600)
    frame.setLocationRelativeTo(null)

    def onRuleIDFound(ruleID: Int): Unit = {
      frame.dispose()
      window.setVisible(true)
      val rule = ruleID match {
        case -1 => null
        case Rules.showMsgOnClickRule => new ShowMsgOnClickRule(window.page.lastRuleID + 1)
        case Rules.showMsgOnLineRule => new ShowMsgOnLineRule(window.page.lastRuleID + 1)
      }
      if (rule == null) return

      if (window.curRule != rule) window.curBtnID = -1
      var btn: JButton = if (window.curBtnID == -1) null else window.rulesList.getComponent(window.curBtnID).asInstanceOf[JButton]
      if (btn == null) {
        window.page += rule
        btn = window.addRule(rule)
      }
      btn.setText("Если " + rule.conditionString + ", тогда " + rule.actionString)
      window.updBtns()

      showEditor(window, rule)
    }

    val rulesList = new JPanel
    rulesList.setLayout(new BoxLayout(rulesList, BoxLayout.PAGE_AXIS))
    frame.add(new JScrollPane(rulesList))

    var i = 1
    for (s <- Rules.stringArray) {
      val ruleID = i
      val btn = new FancyButton
      btn.setText(s)
      btn.setAlignmentX(0.5F)
      btn.addActionListener(new ActionListener {
        def actionPerformed(p1: ActionEvent): Unit = onRuleIDFound(ruleID)
      })
      rulesList.add(btn)
      i += 1
    }

    val cancelButton = new FancyButton
    cancelButton.setText("Отмена")
    cancelButton.addActionListener(new ActionListener {
      def actionPerformed(p1: ActionEvent): Unit = {
        frame.dispose()
        window.setVisible(true)
      }
    })
    frame.add(cancelButton, BorderLayout.SOUTH)

    frame.setVisible(true)
  }

  private def showEditor(window: BoardRulesEditor, rule: BoardRule): Unit = BoardRuleEditor(window, rule)

  private case class BoardRuleEditor(window: BoardRulesEditor, rule: BoardRule) {
    window.setVisible(false)

    val frame = new JFrame("Редактирование правила")
    frame.addWindowListener(new WindowAdapter {
      override def windowClosing(e: WindowEvent): Unit = window.setVisible(true)
    })
    frame.setSize(400, 600)
    frame.setLocationRelativeTo(null)

    rule match {
      case brul: ShowMsgOnClickRule => showEditor(brul)
      case brul: ShowMsgOnLineRule => showEditor(brul)
    }

    val buttonsPanel = new JPanel
    frame.add(buttonsPanel, BorderLayout.SOUTH)

    val cancelButton = new FancyButton
    cancelButton.setIcon(ImageFactory.getAwtIcon("cancel.png"))
    cancelButton.setToolTipText("Отмена")
    cancelButton.addActionListener(new ActionListener {
      def actionPerformed(p1: ActionEvent): Unit = {
        frame.dispose()
        window.setVisible(true)
      }
    })
    buttonsPanel.add(cancelButton)

    val saveButton = new FancyButton
    saveButton.setIcon(ImageFactory.getAwtIcon("ok.png"))
    saveButton.setToolTipText("Сохранить")
    saveButton.addActionListener(new ActionListener {
      def actionPerformed(p1: ActionEvent): Unit = {
        update()
        frame.dispose()
        window.setVisible(true)
      }
    })
    buttonsPanel.add(saveButton)

    frame.setVisible(true)

    def update(): Unit = {
      if (window.curRule != rule) window.curBtnID = -1
      var btn: JButton = if (window.curBtnID == -1) null else window.rulesList.getComponent(window.curBtnID).asInstanceOf[JButton]
      if (btn == null) {
        window.page += rule
        btn = window.addRule(rule)
      }
      btn.setText("Если " + rule.conditionString + ", тогда " + rule.actionString)
      window.updBtns()
    }

    def showEditor(brul: ShowMsgOnClickRule): Unit = {
      val msgEdit = new FancyTextField
      msgEdit.setText(brul.msg)
      msgEdit.getDocument.addDocumentListener(new DocumentListener {
        def insertUpdate(p1: DocumentEvent): Unit = brul.msg = msgEdit.getText

        def changedUpdate(p1: DocumentEvent): Unit = brul.msg = msgEdit.getText

        def removeUpdate(p1: DocumentEvent): Unit = brul.msg = msgEdit.getText
      })
      frame.add(msgEdit, BorderLayout.NORTH)

      val coordsPanel = new JPanel
      coordsPanel.setLayout(null)
      frame.add(coordsPanel)

      // ---

      val x1Label = new JLabel("X1:")
      x1Label.setBounds(40, 10, 50, 25)
      coordsPanel.add(x1Label)

      val x1Text = new JSpinner(new SpinnerNumberModel(brul.x1, 0, 9999, 10))
      x1Text.setBounds(100, 10, 50, 25)
      x1Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.x1 = x1Text.getValue.toString.toInt
      })
      coordsPanel.add(x1Text)

      val y1Label = new JLabel("Y1:")
      y1Label.setBounds(200, 10, 50, 25)
      coordsPanel.add(y1Label)

      val y1Text = new JSpinner(new SpinnerNumberModel(brul.y1, 0, 9999, 10))
      y1Text.setBounds(260, 10, 50, 25)
      y1Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.y1 = y1Text.getValue.toString.toInt
      })
      coordsPanel.add(y1Text)

      // ---

      val x2Label = new JLabel("X2:")
      x2Label.setBounds(40, 60, 50, 25)
      coordsPanel.add(x2Label)

      val x2Text = new JSpinner(new SpinnerNumberModel(brul.x2, 0, 9999, 10))
      x2Text.setBounds(100, 60, 50, 25)
      x2Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.x2 = x2Text.getValue.toString.toInt
      })
      coordsPanel.add(x2Text)

      val y2Label = new JLabel("Y2:")
      y2Label.setBounds(200, 60, 50, 25)
      coordsPanel.add(y2Label)

      val y2Text = new JSpinner(new SpinnerNumberModel(brul.y2, 0, 9999, 10))
      y2Text.setBounds(260, 60, 50, 25)
      y2Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.y2 = y2Text.getValue.toString.toInt
      })
      coordsPanel.add(y2Text)

      // ---

      val rectButton = new FancyButton
      rectButton.setIcon(ImageFactory.getAwtIcon("cursor.png"))
      rectButton.setBounds(320, 40, 50, 50)
      rectButton.addActionListener(new ActionListener {
        def actionPerformed(p1: ActionEvent): Unit = {
          frame.setVisible(false)

          ShapeGetter.+=(new ShapeListener {
            def onRect(x1: Int, y1: Int, x2: Int, y2: Int): Unit = {
              x1Text.setValue(x1)
              y1Text.setValue(y1)
              x2Text.setValue(x2)
              y2Text.setValue(y2)

              brul.x1 = x1Text.getValue.toString.toInt
              brul.y1 = y1Text.getValue.toString.toInt
              brul.x2 = x2Text.getValue.toString.toInt
              brul.y2 = y2Text.getValue.toString.toInt

              frame.setVisible(true)
            }
          })
        }
      })
      coordsPanel.add(rectButton)
    }

    def showEditor(brul: ShowMsgOnLineRule): Unit = {
      val msgEdit = new FancyTextField
      msgEdit.setText(brul.msg)
      msgEdit.getDocument.addDocumentListener(new DocumentListener {
        def insertUpdate(p1: DocumentEvent): Unit = brul.msg = msgEdit.getText

        def changedUpdate(p1: DocumentEvent): Unit = brul.msg = msgEdit.getText

        def removeUpdate(p1: DocumentEvent): Unit = brul.msg = msgEdit.getText
      })
      frame.add(msgEdit, BorderLayout.NORTH)

      val coordsPanel = new JPanel
      coordsPanel.setLayout(null)
      frame.add(coordsPanel)

      // ---

      val x11Label = new JLabel("X1:")
      x11Label.setBounds(40, 10, 50, 25)
      coordsPanel.add(x11Label)

      val x11Text = new JSpinner(new SpinnerNumberModel(brul.x11, 0, 9999, 10))
      x11Text.setBounds(100, 10, 50, 25)
      x11Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.x11 = x11Text.getValue.toString.toInt
      })
      coordsPanel.add(x11Text)

      val y11Label = new JLabel("Y1:")
      y11Label.setBounds(200, 10, 50, 25)
      coordsPanel.add(y11Label)

      val y11Text = new JSpinner(new SpinnerNumberModel(brul.y11, 0, 9999, 10))
      y11Text.setBounds(260, 10, 50, 25)
      y11Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.y11 = y11Text.getValue.toString.toInt
      })
      coordsPanel.add(y11Text)

      // ---

      val x12Label = new JLabel("X2:")
      x12Label.setBounds(40, 60, 50, 25)
      coordsPanel.add(x12Label)

      val x12Text = new JSpinner(new SpinnerNumberModel(brul.x12, 0, 9999, 10))
      x12Text.setBounds(100, 60, 50, 25)
      x12Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.x12 = x12Text.getValue.toString.toInt
      })
      coordsPanel.add(x12Text)

      val y12Label = new JLabel("Y2:")
      y12Label.setBounds(200, 60, 50, 25)
      coordsPanel.add(y12Label)

      val y12Text = new JSpinner(new SpinnerNumberModel(brul.y12, 0, 9999, 10))
      y12Text.setBounds(260, 60, 50, 25)
      y12Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.y12 = y12Text.getValue.toString.toInt
      })
      coordsPanel.add(y12Text)

      // ---

      val rect1Button = new FancyButton
      rect1Button.setIcon(ImageFactory.getAwtIcon("cursor.png"))
      rect1Button.setBounds(320, 40, 50, 50)
      rect1Button.addActionListener(new ActionListener {
        def actionPerformed(p1: ActionEvent): Unit = {
          frame.setVisible(false)

          ShapeGetter.+=(new ShapeListener {
            def onRect(x1: Int, y1: Int, x2: Int, y2: Int): Unit = {
              x11Text.setValue(x1)
              y11Text.setValue(y1)
              x12Text.setValue(x2)
              y12Text.setValue(y2)

              brul.x11 = x11Text.getValue.toString.toInt
              brul.y11 = y11Text.getValue.toString.toInt
              brul.x12 = x12Text.getValue.toString.toInt
              brul.y12 = y12Text.getValue.toString.toInt

              frame.setVisible(true)
            }
          })
        }
      })
      coordsPanel.add(rect1Button)

      // ---

      val x21Label = new JLabel("X1:")
      x21Label.setBounds(40, 210, 50, 25)
      coordsPanel.add(x21Label)

      val x21Text = new JSpinner(new SpinnerNumberModel(brul.x21, 0, 9999, 10))
      x21Text.setBounds(100, 210, 50, 25)
      x21Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.x21 = x21Text.getValue.toString.toInt
      })
      coordsPanel.add(x21Text)

      val y21Label = new JLabel("Y1:")
      y21Label.setBounds(200, 210, 50, 25)
      coordsPanel.add(y21Label)

      val y21Text = new JSpinner(new SpinnerNumberModel(brul.y21, 0, 9999, 10))
      y21Text.setBounds(260, 210, 50, 25)
      y21Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.y21 = y21Text.getValue.toString.toInt
      })
      coordsPanel.add(y21Text)

      // ---

      val x22Label = new JLabel("X2:")
      x22Label.setBounds(40, 260, 50, 25)
      coordsPanel.add(x22Label)

      val x22Text = new JSpinner(new SpinnerNumberModel(brul.x22, 0, 9999, 10))
      x22Text.setBounds(100, 260, 50, 25)
      x22Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.x22 = x22Text.getValue.toString.toInt
      })
      coordsPanel.add(x22Text)

      val y22Label = new JLabel("Y2:")
      y22Label.setBounds(200, 260, 50, 25)
      coordsPanel.add(y22Label)

      val y22Text = new JSpinner(new SpinnerNumberModel(brul.y22, 0, 9999, 10))
      y22Text.setBounds(260, 260, 50, 25)
      y22Text.addChangeListener(new ChangeListener {
        def stateChanged(p1: ChangeEvent): Unit = brul.y22 = y22Text.getValue.toString.toInt
      })
      coordsPanel.add(y22Text)

      // ---

      val rect2Button = new FancyButton
      rect2Button.setIcon(ImageFactory.getAwtIcon("cursor.png"))
      rect2Button.setBounds(320, 240, 50, 50)
      rect2Button.addActionListener(new ActionListener {
        def actionPerformed(p1: ActionEvent): Unit = {
          frame.setVisible(false)

          ShapeGetter.+=(new ShapeListener {
            def onRect(x1: Int, y1: Int, x2: Int, y2: Int): Unit = {
              x21Text.setValue(x1)
              y21Text.setValue(y1)
              x22Text.setValue(x2)
              y22Text.setValue(y2)

              brul.x21 = x21Text.getValue.toString.toInt
              brul.y21 = y21Text.getValue.toString.toInt
              brul.x22 = x22Text.getValue.toString.toInt
              brul.y22 = y22Text.getValue.toString.toInt

              frame.setVisible(true)
            }
          })
        }
      })
      coordsPanel.add(rect2Button)
    }
  }

}


text:
package com.google.api.codegen.util;

import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

/**
 * Represents a simple or complex type and keeps track of the aliases for the contributing types.
 */
public class TypeName {
  private final TypeAlias topLevelAlias;
  private final String pattern;
  private final List<TypeName> innerTypeNames;

  /** Constructs a TypeName where the full name and nickname are the same. */
  public TypeName(String name) {
    this(name, name);
  }

  /** Creates a type alias with the given fullName and nickname. */
  public TypeName(String fullName, String nickname) {
    this(TypeAlias.create(fullName, nickname));
  }

  /** Creates a type alias for a static inner type with the given fullName and nickname. */
  public TypeName(String fullName, String nickname, String parentTypeName) {
    this(TypeAlias.create(fullName, nickname, parentTypeName));
  }

  /** Creates a TypeName with a given TypeAlias. */
  public TypeName(TypeAlias typeAlias) {
    this.topLevelAlias = typeAlias;
    this.pattern = null;
    this.innerTypeNames = Arrays.asList();
  }

  /**
   * Constructs a composite TypeName with a special string pattern to render the type, and a list of
   * inner TypeName instances that parameterize the type.
   *
   * @param fullName full name
   * @param nickname nickname
   * @param pattern Use the pattern %s for self and %i for inner types, one for each inner type in
   *     the order that they are provided. If this is null, then the type name of the outer type is
   *     used, and inner type names are ignored.
   * @param innerTypeNames
   */
  public TypeName(String fullName, String nickname, String pattern, TypeName... innerTypeNames) {
    this.topLevelAlias = TypeAlias.create(fullName, nickname);
    this.pattern = pattern;
    this.innerTypeNames = Arrays.asList(innerTypeNames);
  }

  /** Renders the fully-qualified name of this type given its pattern. */
  public String getFullName() {
    if (pattern == null) {
      return topLevelAlias.getFullName();
    }
    String result = StringUtils.replaceOnce(pattern, "%s", topLevelAlias.getFullName());
    for (TypeName innerTypeName : innerTypeNames) {
      result = StringUtils.replaceOnce(result, "%i", innerTypeName.getFullName());
    }
    return result;
  }

  /** Renders the short name of this type given its pattern. */
  public String getNickname() {
    if (pattern == null) {
      return topLevelAlias.getNickname();
    }
    String result = StringUtils.replaceOnce(pattern, "%s", topLevelAlias.getNickname());
    for (TypeName innerTypeName : innerTypeNames) {
      result = StringUtils.replaceOnce(result, "%i", innerTypeName.getNickname());
    }
    return result;
  }

  /**
   * Renders the short name of this type given its pattern, and adds any necessary nicknames to the
   * given type table.
   */
  public String getAndSaveNicknameIn(TypeTable typeTable) {
    String topLevelNickname = typeTable.getAndSaveNicknameFor(topLevelAlias);
    if (pattern == null) {
      return topLevelNickname;
    }
    String result = StringUtils.replaceOnce(pattern, "%s", topLevelNickname);
    for (TypeName innerTypeName : innerTypeNames) {
      result = StringUtils.replaceOnce(result, "%i", innerTypeName.getAndSaveNicknameIn(typeTable));
    }
    return result;
  }
}


text:
<?php

set_time_limit(0);

//
// Refresh Youtuber subs/views count.php
//
$startTime = time();
$require_login = false;
$require_config = true;
include_once($_SERVER['DOCUMENT_ROOT'] . "/init.php");

// People
$youtubeChannels = $db->query("SELECT * FROM youtuber WHERE lastpostedon_updatedon < " . (time()-3600) . " AND removed = 0;");
$num_youtubeChannels = count($youtubeChannels);

$twittersUpdated = 0;
$subscriptionsUpdated = 0;
for($i = 0; $i < $num_youtubeChannels; $i++)
{
	$youtubeChannel = $youtubeChannels[$i]['channel'];
	// echo $youtubeChannel;
	if (strlen($youtubeChannel) > 0)
	{
		$youtubeDetails = youtube_v3_getInformation($youtubeChannel);
		$youtubeUploads = youtube_v3_getUploads($youtubeChannels[$i]['youtubeUploadsPlaylistId']);

		//echo $youtubeDetails . " | " . $youtubeUploads . "
";

		if ($youtubeDetails != 0 && $youtubeUploads != 0) {
			/*echo "updated " . $content['entry']['title']['$t'] . "
";
			$result = array(
				"name" => $content['entry']['title']['$t'],
				"description" => strip_tags($content['entry']['content']['$t']),
				"lastpostedon" => strtotime($content['entry']['updated']['$t']),
				"iconurl" => $content['entry']['media$thumbnail']['url'],
				"subscribers" => $content['entry']['yt$statistics']['subscriberCount'],
				"views" => $content['entry']['yt$statistics']['totalUploadViews']
			);*/

			$lastPostedOn = 0;
			foreach($youtubeUploads as $video) {
				$postedOn = strtotime($video['publishedOn']);
				if ($postedOn > $lastPostedOn) {
					$lastPostedOn = $postedOn;
				}
			}

			$db->exec("UPDATE youtuber
							SET
								lastpostedon = '" . $lastPostedOn . "',
								lastpostedon_updatedon = '" . time() . "',
								subscribers = '" . $youtubeDetails['subscribers'] . "',
								views = '" . $youtubeDetails['views'] . "'
							WHERE id = '" . $youtubeChannels[$i]['id'] . "';");
			$subscriptionsUpdated++;
			sleep(1);
		}
	}

	// echo "
";
}

//header("Location: /");
//die();
echo "num youtubers: " . $num_youtubeChannels . "
";
//echo "updated " . $twittersUpdated . " twitter accounts
";
echo "updated " . $subscriptionsUpdated . " youtuber subscriptions
";
echo "done!
";
$endTime = time();
echo "took " . ($endTime - $startTime) . " seconds.";

?>


text:
import unittest

from card_framework.v2.annotation import Annotation, SlashCommandMetadata, UserMentionMetadata
from card_framework.v2.user import User

class AnnotationTest(unittest.TestCase):
  def test_render_slash_command(self) -> None:
    a = Annotation(type=Annotation.AnnotationType.SLASH_COMMAND)
    s = SlashCommandMetadata()
    s.type = SlashCommandMetadata.SlashCommandMetadataType.INVOKE
    s.command_id = 1
    s.command_name = '/tothepain'
    a.slash_command = s

    self.assertDictEqual(
        a.render(),
        {'annotation': {'slashCommand': {'commandId': 1,
                                         'commandName': '/tothepain',
                                         'type': 'INVOKE'},
                        'type': 'SLASH_COMMAND'}}
    )

  def test_render_user_mention(self) -> None:
    a = Annotation(Annotation.AnnotationType.USER_MENTION)
    u = UserMentionMetadata()
    u.type = UserMentionMetadata.UserMentionMetadataType.MENTION
    user = User()
    user.type = User.UserType.HUMAN
    user.name = 'westley'
    user.display_name = 'Dread Pirate Roberts'
    u.user = user
    a.user_mention = u

    self.assertDictEqual(
        a.render(),
        {'annotation': {
            'type': 'USER_MENTION',
            'userMention': {
                'type': 'MENTION',
                'user': {
                    'displayName': 'Dread Pirate Roberts',
                    'name': 'westley',
                    'type': 'HUMAN'
                }
            }
        }
        })


text:
package org.apache.poi.xdgf.extractor;

import java.io.IOException;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xdgf.usermodel.XDGFPage;
import org.apache.poi.xdgf.usermodel.XmlVisioDocument;
import org.apache.poi.xdgf.usermodel.shape.ShapeTextVisitor;

/**
 * Helper class to extract text from an OOXML Visio File
 */
public class XDGFVisioExtractor extends POIXMLTextExtractor {

    protected final XmlVisioDocument document;

    public XDGFVisioExtractor(XmlVisioDocument document) {
        super(document);
        this.document = document;
    }

    public XDGFVisioExtractor(OPCPackage openPackage) throws IOException {
        this(new XmlVisioDocument(openPackage));
    }

    public String getText() {
        ShapeTextVisitor visitor = new ShapeTextVisitor();

        for (XDGFPage page: document.getPages()) {
            page.getContent().visitShapes(visitor);
        }

        return visitor.getText().toString();
    }

    public static void main(String [] args) throws IOException {
        if (args.length < 1) {
            System.err.println("Use:");
            System.err.println("  XDGFVisioExtractor <filename.vsdx>");
            System.exit(1);
        }
        POIXMLTextExtractor extractor =
                new XDGFVisioExtractor(POIXMLDocument.openPackage(
                        args[0]
                ));
        System.out.println(extractor.getText());
        extractor.close();
    }
}


text:
import applyDefaults from './encode/defaults';
import entry from './encode/entry';
import rule from './encode/rule';

import {parseExpression} from 'vega-functions';
import {extend, isArray} from 'vega-util';

export default function(encode, type, role, style, scope, params) {
  const enc = {};
  params = params || {};
  params.encoders = {$encode: enc};

  encode = applyDefaults(encode, type, role, style, scope.config);
  for (const key in encode) {
    enc[key] = parseBlock(encode[key], type, params, scope);
  }

  return params;
}

function parseBlock(block, marktype, params, scope) {
  const channels = {},
        fields = {};

  for (const name in block) {
    if (block[name] != null) { // skip any null entries
      channels[name] = parse(expr(block[name]), scope, params, fields);
    }
  }

  return {
    $expr:   {marktype, channels},
    $fields: Object.keys(fields),
    $output: Object.keys(block)
  };
}

function expr(enc) {
  return isArray(enc) ? rule(enc) : entry(enc);
}

function parse(code, scope, params, fields) {
  const expr = parseExpression(code, scope);
  expr.$fields.forEach(name => fields[name] = 1);
  extend(params, expr.$params);
  return expr.$expr;
}


text:
package com.vtence.molecule.routing;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

public class DynamicPath implements WithBoundParameters, Predicate<String> {

    private final Path pattern;
    private final boolean fullMatch;

    public DynamicPath(String pattern) {
        this(pattern, false);
    }

    public DynamicPath(String pattern, boolean fullMatch) {
        this.pattern = new Path(pattern);
        this.fullMatch = fullMatch;
    }

    public static DynamicPath equalTo(String pattern) {
        return new DynamicPath(pattern, true);
    }

    public static DynamicPath startingWith(String pattern) {
        return new DynamicPath(pattern, false);
    }

    public boolean test(String actual) {
        var path = new Path(actual);
        if (pattern.longerThan(path)) return false;
        if (fullMatch && path.longerThan(pattern)) return false;

        for (int i = 0; i < pattern.segmentCount(); i++) {
            if (!isDynamic(pattern.segment(i)) && !pattern.segment(i).equals(path.segment(i)))
                return false;
        }
        return true;
    }

    private boolean isDynamic(String segment) {
        return segment.startsWith(":");
    }

    public Map<String, String> parametersBoundTo(String path) {
        var p = new Path(path);
        var boundParameters = new HashMap<String, String>();

        for (int i = 0; i < pattern.segmentCount(); i++) {
            String segment = pattern.segment(i);
            if (isDynamic(segment)) {
                boundParameters.put(stripLeadingColon(segment), p.segment(i));
            }
        }
        return boundParameters;
    }

    private String stripLeadingColon(String segment) {
        return segment.substring(1);
    }

    public static class Path {
        private final String path;

        public Path(String path) {
            this.path = path;
        }

        public String[] segments() {
            return removeEmptyParts(path.split("/"));
        }

        private static String[] removeEmptyParts(String[] parts) {
            var segments = new ArrayList<String>();
            for (String part : parts) {
                if (!part.isEmpty()) segments.add(part);
            }
            return segments.toArray(new String[0]);
        }

        public boolean longerThan(Path other) {
            return segments().length > other.segments().length;
        }

        public String segment(int index) {
            return segments()[index];
        }

        public int segmentCount() {
            return segments().length;
        }
    }
}


text:
/**
 *
 */
package nz.co.example.dev.domain.logic;

import java.util.List;

import nz.co.example.dev.domain.model.Circuit;
import nz.co.example.dev.mvc.CircuitForm;

/**
 * Provides domain logic for the sip models.
 *
 * @author nivanov
 *
 */
public interface SipDomainLogic {

    /**
     * Retrieves all of the {@link Circuit} elements.
     * @return
     */
    List<Circuit> getAllCircuits();

    /**
     * Creates a {@link CircuitForm} from a given {@link Circuit}.
     *
     * @param circuit
     * @return circuitForm
     */
    CircuitForm createCircuitForm(Circuit circuit);

    /**
     * Creates a {@link Circuit} from a given {@link CircuitForm}.
     *
     * @param circuitForm
     * @return circuit
     */
    Circuit createCircuit(CircuitForm circuitForm);

    /**
     * Checks whether a circuit with a given key exists.
     *
     * @param circuitKey - the region and the access vlan
     * @return whether a circuit with a given key exists.
     */
    boolean circuitWithKeyExists(String circuitKey);

    /**
     * Adds a circuit.
     *
     * @param circuit - the circuit to add.
     */
    void addCircuit(Circuit circuit);

    /**
     * Modifies a circuit.
     *
     * @param circuit - the old circuit details.
     * @param circuit - the new circuit details.
     */
    void modifyCircuit(Circuit oldCircuit, Circuit newCircuit);

    /**
     * Removes a circuit.
     *
     * @param circuit - the circuit to remove.
     */
    void removeCircuit(Circuit circuit);

}


text:
package automaton

import (
	"bytes"
	"fmt"
	"sort"
	"strconv"
)

// util/automaton/SortedIntSet.java

// If we hold more than this many states, we swtich from O(N*2)
// linear ops to O(N log(N)) TreeMap
const TREE_MAP_CUTOVER = 30

/*
Just holds a set of []int states, plus a corresponding []int count
per state. Used by determinize().

I have to disable hashCode and use string key to mimic Lucene's
custom hashing function here.
*/
type SortedIntSet struct {
	values []int
	counts []int
	// hashCode   int
	dict       map[int]int // keys need sort
	useTreeMap bool
	state      int
}

func newSortedIntSet(capacity int) *SortedIntSet {
	return &SortedIntSet{
		values: make([]int, 0, capacity),
		counts: make([]int, 0, capacity),
	}
}

// Adds this state ot the set
func (sis *SortedIntSet) incr(num int) {
	if sis.useTreeMap {
		val, ok := sis.dict[num]
		if !ok {
			sis.dict[num] = 1
		} else {
			sis.dict[num] = 1 + val
		}
		return
	}

	for i, v := range sis.values {
		if v == num {
			sis.counts[i]++
			return
		} else if num < v {
			// insert here
			sis.values = append(sis.values[:i], append([]int{num}, sis.values[i:]...)...)
			sis.counts = append(sis.counts[:i], append([]int{1}, sis.counts[i:]...)...)
			return
		}
	}

	// append
	sis.values = append(sis.values, num)
	sis.counts = append(sis.counts, 1)

	if len(sis.values) == TREE_MAP_CUTOVER {
		sis.useTreeMap = true
		for i, v := range sis.values {
			sis.dict[v] = sis.counts[i]
		}
	}
}

// Removes the state from the set, if count decrs to 0
func (sis *SortedIntSet) decr(num int) {
	if sis.useTreeMap {
		count, ok := sis.dict[num]
		assert(ok)
		if count == 1 {
			delete(sis.dict, num)
			// Fall back to simple arrays once we touch zero again
			if len(sis.dict) == 0 {
				sis.useTreeMap = false
				sis.values = sis.values[:0] // reuse slice
				sis.counts = sis.counts[:0] // reuse slice
			}
		} else {
			sis.dict[num] = count - 1
		}
		return
	}

	for i, v := range sis.values {
		if v == num {
			sis.counts[i]--
			if sis.counts[i] == 0 {
				limit := len(sis.values) - 1
				if i < limit {
					sis.values = append(sis.values[:i], sis.values[i+1:]...)
					sis.counts = append(sis.counts[:i], sis.counts[i+1:]...)
				} else {
					sis.values = sis.values[:i]
					sis.counts = sis.counts[:i]
				}
			}
			return
		}
	}

	panic("should not be here!")
}

func (sis *SortedIntSet) computeHash() *FrozenIntSet {
	// do nothing related to hash
	if sis.useTreeMap {
		if size := len(sis.dict); size > len(sis.values) {
			sis.values = make([]int, 0, size)
			sis.counts = make([]int, 0, size)
		}
		for state, _ := range sis.dict {
			sis.values = append(sis.values, state)
		}
		sort.Ints(sis.values) // keys in map are not sorted
	} else {
		// do nothing
	}
	return sis.freeze(sis.state)
}

func (sis *SortedIntSet) freeze(state int) *FrozenIntSet {
	c := make([]int, len(sis.values))
	copy(c, sis.values)
	return newFrozenIntSet(c, state)
}

func (sis *SortedIntSet) String() string {
	var b bytes.Buffer
	b.WriteRune('[')
	for i, v := range sis.values {
		if i > 0 {
			b.WriteRune(' ')
		}
		fmt.Fprintf(&b, "%v:%v", v, sis.counts[i])
	}
	b.WriteRune(']')
	return b.String()
}

type FrozenIntSet struct {
	values []int
	state  int
}

func newFrozenIntSet(values []int, state int) *FrozenIntSet {
	return &FrozenIntSet{values, state}
}

func newFrozenIntSetOf(num, state int) *FrozenIntSet {
	return &FrozenIntSet{
		values: []int{num},
		state:  state,
	}
}

func (fis *FrozenIntSet) String() string {
	var b bytes.Buffer
	b.WriteRune('[')
	for i, v := range fis.values {
		if i > 0 {
			b.WriteRune(' ')
		}
		b.WriteString(strconv.Itoa(v))
	}
	b.WriteRune(']')
	return b.String()
}


text:
param (
    [Parameter(Mandatory=$true)][string]$pfxFileName,
    [Parameter(Mandatory=$true)][string]$pfxPassword,
    [Parameter(Mandatory=$true)][string]$domainName
)

. ./New-SelfSignedCertificateEx.ps1

#[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")]
New-SelfsignedCertificateEx -Subject "CN=*.$($domainName)" -EKU "1.3.6.1.5.5.7.3.1" -Path ".\$($pfxFileName)" -Password (ConvertTo-SecureString $pfxPassword -AsPlainText -Force) -Exportable


text:
package com.github.cxfplus.jaxws.interceptors;

import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.github.cxfplus.core.util.XMLUtils;
import com.github.cxfplus.jmx.CXFPlus;

/**
 * JAX-WS标准的SOAP拦截器,用于输出XML报文信息
 * @author jiyi
 *
 */
public class TraceHandler implements SOAPHandler<SOAPMessageContext> {
	private static Logger log=LoggerFactory.getLogger(TraceHandler.class);

	private static TraceHandler instance=new TraceHandler();

	private TraceHandler(){
	}

	public static TraceHandler getSingleton(){
		return instance;
	}

	public Set<QName> getHeaders() {
		return null;
	}

	public boolean handleMessage(SOAPMessageContext arg0) {
		if(CXFPlus.getSingleton().isTrace()){
			trace(arg0);
		}
		return true;
	}

	public boolean handleFault(SOAPMessageContext arg0) {
		if(CXFPlus.getSingleton().isTrace()){
			trace(arg0);
		}
		return true;
	}

	public void close(MessageContext arg0) {
		log.debug("close: {}", arg0);
	}

	private void trace(SOAPMessageContext messageContext) {
		Boolean outMessageIndicator =  (Boolean)messageContext.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		StringBuilderWriter output=new StringBuilderWriter(512);
		if (outMessageIndicator.booleanValue())
			output.append("\nOutbound SOAP:");
		else {
			output.append("\nInbound SOAP:");
		}
		SOAPMessage message = messageContext.getMessage();

		try {
			if (CXFPlus.getSingleton().isTracePrettyFormat()) {
				Document doc = XMLUtils.newDocument();
				Element ele = doc.createElement("soap:Envelope");
				doc.appendChild(ele);
				ele.setAttribute("xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/");
				if (message.getSOAPHeader() != null)
					ele.appendChild(doc.importNode(message.getSOAPHeader(), true));
				if (message.getSOAPBody() != null)
					ele.appendChild(doc.importNode(message.getSOAPBody(), true));
				XMLUtils.output(ele, output, null, true);
			} else {
				message.writeTo(new WriterOutputStream(output));
				output.write("\r\n");
			}
			log.info(output.toString());
		} catch (Exception exp) {
			log.error("Exception in TraceHandler:trace(messageContext) : ", exp);
		}
	}
}