text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>obter-nulidade-administrativa-de-registro-de-topografia-de-circuito-integrado</id>
    <dbId>2877</dbId>
    <nome>Obter nulidade administrativa de registro de topografia de circuito integrado</nome>
    <sigla></sigla>
    <descricao>Destina-se à pessoa física ou jurídica com legítimo interesse que entender que a decisão de concessão ou indeferimento de pedido de registro de topografia de circuito integrado deva ser considerada nula total ou parcialmente por infração à Lei nº 11.484, de 31 de maio de 2007. O serviço consiste, basicamente, na instauração do processo administrativo de nulidade, na sua instrução técnica, na emissão de parecer sobre a matéria suscitada e na decisão da Presidência do INPI.</descricao>
    <contato></contato>
    <gratuito>false</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="3458">
            <tipo>Pessoa física ou jurídica</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <nao-estimado-ainda/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="6695">
            <titulo>Pagar taxa</titulo>
            <descricao>Emitir e pagar a Guia de Recolhimento da União (GRU).</descricao>
            <documentos>
                <default>
                    <item id="8828">GRU</item>
                </default>
            </documentos>
            <custos>
                <default>
                    <custo id="579">
                        <descricao>Outras petições (Código 663 da GRU)</descricao>
                        <moeda>R$</moeda>
                        <valor>60,00</valor>
                        <valorVariavel></valorVariavel>
                        <statusCustoVariavel>0</statusCustoVariavel>
                    </custo>
                </default>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="6914" tipo="presencial">
                        <descricao>Rede bancária</descricao>
                    </canal-de-prestacao>
                </default>
                <caso id="803" descricao="Para emissão da GRU">
                    <canal-de-prestacao id="6913" tipo="web">
                        <descricao>https://gru.inpi.gov.br/pag/</descricao>
                    </canal-de-prestacao>
                </caso>
            </canais-de-prestacao>
        </etapa>
        <etapa id="6696">
            <titulo>Solicitar nulidade</titulo>
            <descricao>Apresentar o requerimento em formulário físico.</descricao>
            <documentos>
                <default>
                    <item id="8829">CPF ou CNPJ</item>
                    <item id="8830">Comprovante de endereço</item>
                    <item id="8831">Comprovante de pagamento</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="6915" tipo="presencial">
                        <descricao>Serviço de Protocolo e Expedição (SEPEX): Rua Mayrink Veiga, 9, térreo, Centro, Rio de Janeiro – RJ (CEP 20090-910).</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="6916" tipo="postal">
                        <descricao>Serviço de Protocolo e Expedição (SEPEX): Rua Mayrink Veiga, 9, térreo, Centro, Rio de Janeiro – RJ (CEP 20090-910).</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/382" dbId="36783">
        <nomeOrgao>Instituto Nacional da Propriedade Industrial (INPI)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="1" idServicoSegmento="6577">Cidadãos</item>
        <item idSegmento="3" idServicoSegmento="6578">Empresas</item>
        <item idSegmento="4" idServicoSegmento="6579">Demais segmentos (ONGs, organizações sociais, etc)</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Pesquisa, Ciência, Inovação e Tecnologia</item>
        <item>Pesquisa e Desenvolvimento</item>
        <item>Propriedade Industrial</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="12394">nulidade</item>
        <item id="12395">inpi</item>
        <item id="12396">circuito integrado</item>
    </palavras-chave>
</servico>


text:
import * as jqImpl from './jqueryImpl';

export const doRequest = jqImpl.doRequest;

redpajama_set_name: RedPajamaGithub


text:
namespace System.Activities.Presentation.Internal.PropertyEditing.Model
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Text;

    using System.Activities.Presentation;
    using System.Activities.Presentation.Model;
    using System.Activities.Presentation.PropertyEditing;

    using System.Activities.Presentation.Internal.PropertyEditing.Resources;
    using System.Activities.Presentation.Internal.Properties;
    using System.Activities.Presentation.Internal.PropertyEditing.Editors;

    // <summary>
    // Concrete implementation of PropertyValue that delegates to ModelPropertyEntryBase for
    // all actions.
    // </summary>
    internal class ModelPropertyValue : PropertyValue
    {

        // Object used to mark a property value that should be cleared instead of set
        private static readonly object ClearValueMarker = new object();

        // CultureInfo instance we use for formatting values so that they reflect what is in Xaml
        private static CultureInfo _xamlCultureInfo;

        // <summary>
        // Basic ctor
        // </summary>
        // <param name="parentProperty">Parent ModelPropertyEntryBase</param>
        public ModelPropertyValue(ModelPropertyEntryBase parentProperty) : base(parentProperty)
        {
        }

        // <summary>
        // Returns the source of this property value
        // </summary>
        public override PropertyValueSource Source
        {
            get {
                return ParentModelPropertyEntry.Source;
            }
        }

        // <summary>
        // Returns true if this value represents the default value of the property
        // </summary>
        public override bool IsDefaultValue
        {
            get {
                return Source == DependencyPropertyValueSource.DefaultValue;
            }
        }

        // <summary>
        // Returns true if the value contained by this property is mixed
        // </summary>
        public override bool IsMixedValue
        {
            get {
                return ParentModelPropertyEntry.IsMixedValue;
            }
        }

        // <summary>
        // Returns true if custom TypeConverter exists and if it can convert
        // the value from string.
        // </summary>
        public override bool CanConvertFromString
        {
            get {
                return ParentModelPropertyEntry.Converter != null &&
                    ParentModelPropertyEntry.Converter.CanConvertFrom(typeof(string));
            }
        }

        // <summary>
        // Gets a flag indicating whether this PropertyValue has sub properties
        // </summary>
        public override bool HasSubProperties
        {
            get {
                return ParentModelPropertyEntry.HasSubProperties;
            }
        }

        // <summary>
        // Gets the sub-properties of the PropertyValue
        // </summary>
        public override PropertyEntryCollection SubProperties
        {
            get {
                return ParentModelPropertyEntry.SubProperties;
            }
        }

        // <summary>
        // Gets a flag indicating whether this PropertyValue represents a collection
        // </summary>
        public override bool IsCollection
        {
            get {
                return ParentModelPropertyEntry.IsCollection;
            }
        }

        // <summary>
        // Gets the collection represented by this PropertyValue
        // </summary>
        public override PropertyValueCollection Collection
        {
            get {
                return ParentModelPropertyEntry.Collection;
            }
        }

        // <summary>
        // This is an internal helper to which we can bind and on which we fire PropertyChanged
        // event when the Name sub-property (if one exists) changes.  More-specifically,
        // we bind to this property in CollectionEditor to display the Type as well as the
        // Name of the items in the collection.  This property is accessed from XAML.
        // </summary>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public PropertyValue NameSensitiveInstance
        {
            get {
                return this;
            }
        }

        // <summary>
        // Always catch exceptions
        // </summary>
        protected override bool CatchExceptions
        {
            get {
                return true;
            }
        }

        // <summary>
        // Gets an en-us CultureInfo that ignores user-specified settings
        // </summary>
        private static CultureInfo XamlCultureInfo
        {
            get {
                if (_xamlCultureInfo == null)
                {
                    _xamlCultureInfo = new CultureInfo("en-us", false);
                }

                return _xamlCultureInfo;
            }
        }

        // Convenience accessor
        private ModelPropertyEntryBase ParentModelPropertyEntry
        {
            get {
                return (ModelPropertyEntryBase)this.ParentProperty;
            }
        }

        // <summary>
        // Validates the value using the TypeConverter, if one exists
        // </summary>
        // <param name="valueToValidate">Value to validate</param>
        protected override void ValidateValue(object valueToValidate)
        {
            // Noop.  We used to rely on TypeConverter.IsValid() here, but it turns out
            // that a bunch of standard TypeConverters don't really work (eg. Int32TypeConverter
            // returns true for IsValid("abc") and EnumConverter returns false for
            // IsValid(MyEnum.One | MyEnum.Two) even if MyEnum if adorned with FlagsAttribute)
        }

        // Called when there exists a Name sub-property for this value and it changes
        internal void OnNameSubPropertyChanged()
        {
            // Updates XAML bindings (collection editor item-display-name-template for one)
            this.OnPropertyChanged("NameSensitiveInstance");
        }

        // <summary>
        // Convert the specified string to a value
        // </summary>
        // <param name="stringToConvert"></param>
        // <returns></returns>
        protected override object ConvertStringToValue(string stringToConvert)
        {
            if (this.ParentProperty.PropertyType == typeof(string))
            {
                return stringToConvert;
            }
            else if (string.IsNullOrEmpty(stringToConvert))
            {

                // If the type of this property is string:
                //
                //      StringValue of ''   -> set Value to ''
                //      StringValue of null -> ClearValue()
                //
                // Otherwise
                //
                //      StringValue of ''   -> ClearValue()
                //      StringValue of null -> ClearValue()
                //
                if (stringToConvert != null && typeof(string).Equals(this.ParentProperty.PropertyType))
                {
                    return null;
                }
                else
                {
                    return ClearValueMarker;
                }

            }
            else if (EditorUtilities.IsNullableEnumType(this.ParentProperty.PropertyType) && stringToConvert.Equals(EditorUtilities.NullString, StringComparison.Ordinal))
            {
                // PS 107537: Special case handling when converting a string to a nullable enum type.
                return null;
            }
            else if (this.ParentModelPropertyEntry.Converter != null &&
                this.ParentModelPropertyEntry.Converter.CanConvertFrom(typeof(string)))
            {

                return this.ParentModelPropertyEntry.Converter.ConvertFromString(null, XamlCultureInfo, stringToConvert);
            }

            throw FxTrace.Exception.AsError(new InvalidOperationException(string.Format(
                CultureInfo.CurrentCulture,
                Resources.PropertyEditing_NoStringToValueConversion,
                this.ParentProperty.DisplayName)));
        }

        // <summary>
        // Convert the specified value to a string
        // </summary>
        // <param name="valueToConvert"></param>
        // <returns></returns>
        protected override string ConvertValueToString(object valueToConvert)
        {
            string stringValue = string.Empty;

            if (valueToConvert == null)
            {
                if (typeof(IList).IsAssignableFrom(this.ParentProperty.PropertyType))
                {
                    stringValue = Resources.PropertyEditing_DefaultCollectionStringValue;
                }
                else if (EditorUtilities.IsNullableEnumType(this.ParentProperty.PropertyType))
                {
                    // PS 107537: Special case handling when converting a nullable enum type to a string.
                    return EditorUtilities.NullString;
                }
                return stringValue;
            }
            else if ((stringValue = valueToConvert as string) != null)
            {
                return stringValue;
            }

            TypeConverter typeConverter = this.ParentModelPropertyEntry.Converter;
            if (valueToConvert is Array)
            {
                stringValue = Resources.PropertyEditing_DefaultArrayStringValue;
            }
            else if (valueToConvert is IList
                || valueToConvert is ICollection
                || ModelUtilities.ImplementsICollection(valueToConvert.GetType())
                || ModelUtilities.ImplementsIList(valueToConvert.GetType()))
            {
                stringValue = Resources.PropertyEditing_DefaultCollectionStringValue;
            }
            else if (valueToConvert is IEnumerable)
            {
                stringValue = Resources.PropertyEditing_DefaultEnumerableStringValue;
            }
            else if (typeConverter != null && typeConverter.CanConvertTo(typeof(string)))
            {
                stringValue = typeConverter.ConvertToString(null, XamlCultureInfo, valueToConvert);
            }
            else
            {
                stringValue = valueToConvert.ToString();
            }

            return stringValue ?? string.Empty;
        }

        // <summary>
        // Redirect the call to parent PropertyEntry
        // </summary>
        // <returns></returns>
        protected override object GetValueCore()
        {
            return ParentModelPropertyEntry.GetValueCore();
        }

        // <summary>
        // Redirect the call to parent PropertyEntry
        // </summary>
        // <param name="value"></param>
        protected override void SetValueCore(object value)
        {
            if (value == ClearValueMarker)
            {
                ParentModelPropertyEntry.ClearValue();
            }
            else
            {
                ParentModelPropertyEntry.SetValueCore(value);
            }
        }

        // <summary>
        // Apply the FlowDirection to the resource.
        // </summary>
        private void CheckAndSetFlowDirectionResource()
        {
            // Check if the value being edited is FlowDirection
            // and if so, reset the resource to the current value that the user is setting.
            // This will refresh the property inspector and all the string editors, showing "string" properties,
            // would have their FlowDirection set to the current value.
            if (ParentModelPropertyEntry.PropertyName.Equals(FrameworkElement.FlowDirectionProperty.Name))
            {
                object value = Value;
                if (value != null)
                {
                    PropertyInspectorResources.GetResources()["SelectedControlFlowDirectionRTL"] = value;
                }
            }
        }

        // <summary>
        // Redirect the call to parent PropertyEntry
        // </summary>
        public override void ClearValue()
        {
            ParentModelPropertyEntry.ClearValue();
        }

        // <summary>
        // Fires the appropriate PropertyChanged events
        // </summary>
        public void OnUnderlyingModelChanged()
        {
            CheckAndSetFlowDirectionResource();
            this.NotifyRootValueChanged();
        }

        // <summary>
        // Fires the appropriate PropertyChanged events
        // </summary>
        public void OnUnderlyingSubModelChanged()
        {
            this.NotifySubPropertyChanged();
        }

        // <summary>
        // Called when there is an error setting or getting a PropertyValue.
        // Displays an error dialog.
        // </summary>
        // <param name="e"></param>
        protected override void OnPropertyValueException(PropertyValueExceptionEventArgs e)
        {
            if (e.Source == PropertyValueExceptionSource.Set)
            {
                if (e.Exception != null)
                {
                    Debug.WriteLine(e.Exception.ToString());
                }

                ErrorReporting.ShowErrorMessage(e.Exception.Message);

                base.OnPropertyValueException(e);
            }
            else
            {
                base.OnPropertyValueException(e);
            }
        }

        // <summary>
        // Debuging-friendly ToString()
        // </summary>
        // <returns></returns>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public override string ToString()
        {
            try
            {
                string value;
                if (this.Value == null)
                {
                    value = "{null}";
                }
                else
                {
                    value = this.StringValue;
                    if (string.IsNullOrEmpty(value))
                    {
                        value = "{empty}";
                    }
                }

                return string.Format(CultureInfo.CurrentCulture, "{0} (PropertyValue)", value ?? "{null}");
            }
            catch
            {
                return base.ToString();
            }
        }
    }
}


text:
Rework CSS transform which removes unused class rules and optionally can
compress class names.

## Installation

    % npm install rework-classmap

## Usage

    var rework        = require('rework');
    var makeClassmap  = require('rework-classmap');

    var classmap = makeClassmap({
      'SomeClass': true,
      'AnotherClass': true
    });

    var transformed = rework(src).use(classmap).toString();


text:
[Versión en castellano](#castellano)

APLAB lets you check whether there are free

##Synopsis
Last assignment for the "Ética, Legislación y Profesión" course (Ethics, Legislation and Professional Practice) at the Faculty of Computer Sciences (FDI), Complutense University of Madrid.
APLAB lets you see the current availability of the Faculty laboratories, allowing you to filter by day, hour, subject and installed software.
To that end, it gathers data by scraping two existing pages,
[status](https://web.fdi.ucm.es/labs/estado_lab.asp) and [time table](https://web.fdi.ucm.es/Docencia/Horarios.aspx?AulaLab_Cod=%s&fdicurso=%s).

##Resources used

* For the design, we used HTML, CSS and JavaScript along with the Bootstrap Theme template [Grayscale](https://blackrockdigital.github.io/startbootstrap-grayscale/).
* Dev tools: [Gradle](https://gradle.org/), [Spark Framework](http://sparkjava.com/) and Java with [Eclipse](https://eclipse.org/).

##Motivation

APLAB is a much-needed project for the FDI. Currently, the status information for our labs is scattered over several pages and it is really difficult for students to access it.
With APLAB, users can easily check the status of every lab just by selecting the lab number, day, hour or installed software.

##Getting the code

The code is organized as a Gradle project for Eclipse.

**Open project with Eclipse**
* Clone repo
* File -> Import -> Gradle Project
* On src/main/java/Main.java -> Right click -> Run As Java Application

**View the app**
* Open a web browser, then visit "localhost:4567"

##Participants

* Alberto Velazquez Alonso - [velazq](https://github.com/velazq)
* Jonathan Sánchez Paredes - [JoniSanchez](https://github.com/JoniSanchez)
* Kurosh Dabbagh Escalante - [KuroshDa](https://github.com/KuroshDa)
* Lorena Jiménez Corta     - [lorejico](https://github.com/lorejico)
* Pablo Capa		   - [pabloCapa](https://github.com/pabloCapa)

##Code license

MIT License
Copyright (c) 2016-2017 the APLAB developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
More information in "LICENSE.txt" file

##Media license

All images and any other media files are under the [Creative Commons CC-BY-NC-SA license](https://creativecommons.org/licenses/by-nc-sa/3.0/).

---

##Sinopsis
Proyecto final de la asignatura Ética, Legislación y Profesión de la Facultad de Informática - UCM.
APLAB permite conocer la disponibilidad de los laboratorios de FDI realizando filtrados por dia, hora, asignatura y software disponible.
Para ello se recolecta datos mediante scraping de dos páginas webs de
[estado](https://web.fdi.ucm.es/labs/estado_lab.asp) y [horarios](https://web.fdi.ucm.es/Docencia/Horarios.aspx?AulaLab_Cod=%s&fdicurso=%s)
de los laboratorios.

##Recursos utilizados

* Para el diseño de la aplicación se ha utilizado html, css y javascript sobre una plantilla de Bootstrap Theme [Grayscale](https://blackrockdigital.github.io/startbootstrap-grayscale/).
* Herramientas de programación: [Gradle](https://gradle.org/), [Spark Framework](http://sparkjava.com/) y Java en entorno [Eclipse](https://eclipse.org/).

##Motivación

APLAB es un proyecto necesario para FDI. Actualmente la información del estado de los laboratorios se encuentra muy dispersa y es muy dificil para los usuarios acceder a ella.
Con APLAB los usuarios tienen una gran facilidad para consultar el estado de los laboratorios simplemente seleccionando el laboratorio, dia, hora o software disponible.

##Instalación

Proyecto Java haciendo uso de la herramienta Gradle.

**Instalación en Eclipse**
* Descargar respositorio.
* File -> Import -> Gradle Project
* En src/main/java/Main.java -> Click derecho -> Run As Java Application

**Abrir la aplicación**
* Ir a un navegador y consultar "localhost:4567"

##Participantes

* Alberto Velazquez Alonso - [velazq](https://github.com/velazq)
* Jonathan Sánchez Paredes - [JoniSanchez](https://github.com/JoniSanchez)
* Kurosh Dabbagh Escalante - [KuroshDa](https://github.com/KuroshDa)
* Lorena Jiménez Corta     - [lorejico](https://github.com/lorejico)
* Pablo Capa		   - [pabloCapa](https://github.com/pabloCapa)

##Licencia del código

MIT License
Copyright (c) 2016-2017 the APLAB developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
More information in "LICENSE.txt" file

##Licencia de imágenes

Todas las imágenes y otros archivos están bajo la licencia [Creative Commons CC-BY-NC-SA](https://creativecommons.org/licenses/by-nc-sa/3.0/es/).


text:
/*jslint node: true */
'use strict';

var
  figuier = require('../lib/figuier'),
  config;

// Get a new config object with initial data
config  = figuier({
  demo: [
    {
      foo: 'bar'
    }
  ]
});

// set multiple properties at once
config.set({
  meaningOfLife:  42,
  interpolation:  'foo: <%= demo.0.foo %>, baz: <%= demo.0.baz %>',
  reference: {
    foo:  config.ref('demo.0.foo'),
    none: config.ref('demo.1.foo', 'Placeholder for undefined property')
  },
  use: config.use(function () {
    return this.get('meaningOfLife') / 2;
  })
});

// set a path property (previously referenced)
config.set('demo.0.baz', 'qux');

console.log(config.get());
/*
  Output:
  =======

  {
    demo: [{
      foo: 'bar',
      baz: 'qux'
    }],
    meaningOfLife: 42,
    interpolation: 'foo: bar, baz: qux',
    reference: {
      foo: 'bar',
      none: 'Placeholder for undefined property'
    },
    use: 21
  }
*/


text:
import cv2
import numpy as np
import argparse
import copy
from PIL import Image
#construct argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help= "Path to the image")
args = vars(ap.parse_args())

#load the image, clone it for output, and convert to grayscale
image = cv2.imread(args["image"])
y = copy.copy(image)
gray= cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

#detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100)

#ensure at least some circles were found
if circles is not None:
	#convert the (x,y) coordinates and radius of the circles
	circles = np.round(circles[0, :]).astype("int")

	#loop over the (x,y) coordinates and radius of the circles
	for (x,y,r) in circles:
		#draw the circle in the output image, then draw a rectangle
		#corresponding to the center of the circle
		tmp = np.hstack([image, y])
		img = Image.fromarray(np.hstack([image, y]), 'RGB')
		cv2.imshow("y", img)
		cv2.waitKey(0)


text:
package com.android.internal.widget;

import java.lang.ref.WeakReference;

import com.android.internal.widget.LockScreenWidgetCallback;
import com.android.internal.widget.LockScreenWidgetInterface;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.RemoteControlClient;
import android.media.IRemoteControlDisplay;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.internal.R;

public class TransportControlView extends FrameLayout implements OnClickListener,
        LockScreenWidgetInterface {

    private static final int MSG_UPDATE_STATE = 100;
    private static final int MSG_SET_METADATA = 101;
    private static final int MSG_SET_TRANSPORT_CONTROLS = 102;
    private static final int MSG_SET_ARTWORK = 103;
    private static final int MSG_SET_GENERATION_ID = 104;
    private static final int MAXDIM = 512;
    private static final int DISPLAY_TIMEOUT_MS = 5000; // 5s
    protected static final boolean DEBUG = false;
    protected static final String TAG = "TransportControlView";

    private ImageView mAlbumArt;
    private TextView mTrackTitle;
    private ImageView mBtnPrev;
    private ImageView mBtnPlay;
    private ImageView mBtnNext;
    private int mClientGeneration;
    private Metadata mMetadata = new Metadata();
    private boolean mAttached;
    private PendingIntent mClientIntent;
    private int mTransportControlFlags;
    private int mCurrentPlayState;
    private AudioManager mAudioManager;
    private LockScreenWidgetCallback mWidgetCallbacks;
    private IRemoteControlDisplayWeak mIRCD;

    /**
     * The metadata which should be populated into the view once we've been attached
     */
    private Bundle mPopulateMetadataWhenAttached = null;

    // This handler is required to ensure messages from IRCD are handled in sequence and on
    // the UI thread.
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_UPDATE_STATE:
                if (mClientGeneration == msg.arg1) updatePlayPauseState(msg.arg2);
                break;

            case MSG_SET_METADATA:
                if (mClientGeneration == msg.arg1) updateMetadata((Bundle) msg.obj);
                break;

            case MSG_SET_TRANSPORT_CONTROLS:
                if (mClientGeneration == msg.arg1) updateTransportControls(msg.arg2);
                break;

            case MSG_SET_ARTWORK:
                if (mClientGeneration == msg.arg1) {
                    if (mMetadata.bitmap != null) {
                        mMetadata.bitmap.recycle();
                    }
                    mMetadata.bitmap = (Bitmap) msg.obj;
                    mAlbumArt.setImageBitmap(mMetadata.bitmap);
                }
                break;

            case MSG_SET_GENERATION_ID:
                if (msg.arg2 != 0) {
                    // This means nobody is currently registered. Hide the view.
                    if (mWidgetCallbacks != null) {
                        mWidgetCallbacks.requestHide(TransportControlView.this);
                    }
                }
                if (DEBUG) Log.v(TAG, "New genId = " + msg.arg1 + ", clearing = " + msg.arg2);
                mClientGeneration = msg.arg1;
                mClientIntent = (PendingIntent) msg.obj;
                break;

            }
        }
    };

    /**
     * This class is required to have weak linkage to the current TransportControlView
     * because the remote process can hold a strong reference to this binder object and
     * we can't predict when it will be GC'd in the remote process. Without this code, it
     * would allow a heavyweight object to be held on this side of the binder when there's
     * no requirement to run a GC on the other side.
     */
    private static class IRemoteControlDisplayWeak extends IRemoteControlDisplay.Stub {
        private WeakReference<Handler> mLocalHandler;

        IRemoteControlDisplayWeak(Handler handler) {
            mLocalHandler = new WeakReference<Handler>(handler);
        }

        public void setPlaybackState(int generationId, int state, long stateChangeTimeMs) {
            Handler handler = mLocalHandler.get();
            if (handler != null) {
                handler.obtainMessage(MSG_UPDATE_STATE, generationId, state).sendToTarget();
            }
        }

        public void setMetadata(int generationId, Bundle metadata) {
            Handler handler = mLocalHandler.get();
            if (handler != null) {
                handler.obtainMessage(MSG_SET_METADATA, generationId, 0, metadata).sendToTarget();
            }
        }

        public void setTransportControlFlags(int generationId, int flags) {
            Handler handler = mLocalHandler.get();
            if (handler != null) {
                handler.obtainMessage(MSG_SET_TRANSPORT_CONTROLS, generationId, flags)
                        .sendToTarget();
            }
        }

        public void setArtwork(int generationId, Bitmap bitmap) {
            Handler handler = mLocalHandler.get();
            if (handler != null) {
                handler.obtainMessage(MSG_SET_ARTWORK, generationId, 0, bitmap).sendToTarget();
            }
        }

        public void setAllMetadata(int generationId, Bundle metadata, Bitmap bitmap) {
            Handler handler = mLocalHandler.get();
            if (handler != null) {
                handler.obtainMessage(MSG_SET_METADATA, generationId, 0, metadata).sendToTarget();
                handler.obtainMessage(MSG_SET_ARTWORK, generationId, 0, bitmap).sendToTarget();
            }
        }

        public void setCurrentClientId(int clientGeneration, PendingIntent mediaIntent,
                boolean clearing) throws RemoteException {
            Handler handler = mLocalHandler.get();
            if (handler != null) {
                handler.obtainMessage(MSG_SET_GENERATION_ID,
                    clientGeneration, (clearing ? 1 : 0), mediaIntent).sendToTarget();
            }
        }
    };

    public TransportControlView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (DEBUG) Log.v(TAG, "Create TCV " + this);
        mAudioManager = new AudioManager(mContext);
        mCurrentPlayState = RemoteControlClient.PLAYSTATE_NONE; // until we get a callback
        mIRCD = new IRemoteControlDisplayWeak(mHandler);
    }

    private void updateTransportControls(int transportControlFlags) {
        mTransportControlFlags = transportControlFlags;
    }

    @Override
    public void onFinishInflate() {
        super.onFinishInflate();
        mTrackTitle = (TextView) findViewById(R.id.title);
        mTrackTitle.setSelected(true); // enable marquee
        mAlbumArt = (ImageView) findViewById(R.id.albumart);
        mBtnPrev = (ImageView) findViewById(R.id.btn_prev);
        mBtnPlay = (ImageView) findViewById(R.id.btn_play);
        mBtnNext = (ImageView) findViewById(R.id.btn_next);
        final View buttons[] = { mBtnPrev, mBtnPlay, mBtnNext };
        for (View view : buttons) {
            view.setOnClickListener(this);
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mPopulateMetadataWhenAttached != null) {
            updateMetadata(mPopulateMetadataWhenAttached);
            mPopulateMetadataWhenAttached = null;
        }
        if (!mAttached) {
            if (DEBUG) Log.v(TAG, "Registering TCV " + this);
            mAudioManager.registerRemoteControlDisplay(mIRCD);
        }
        mAttached = true;
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mAttached) {
            if (DEBUG) Log.v(TAG, "Unregistering TCV " + this);
            mAudioManager.unregisterRemoteControlDisplay(mIRCD);
        }
        mAttached = false;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int dim = Math.min(MAXDIM, Math.max(getWidth(), getHeight()));
//        Log.v(TAG, "setting max bitmap size: " + dim + "x" + dim);
//        mAudioManager.remoteControlDisplayUsesBitmapSize(mIRCD, dim, dim);
    }

    class Metadata {
        private String artist;
        private String trackTitle;
        private String albumTitle;
        private Bitmap bitmap;

        public String toString() {
            return "Metadata[artist=" + artist + " trackTitle=" + trackTitle + " albumTitle=" + albumTitle + "]";
        }
    }

    private String getMdString(Bundle data, int id) {
        return data.getString(Integer.toString(id));
    }

    private void updateMetadata(Bundle data) {
        if (mAttached) {
            mMetadata.artist = getMdString(data, MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST);
            mMetadata.trackTitle = getMdString(data, MediaMetadataRetriever.METADATA_KEY_TITLE);
            mMetadata.albumTitle = getMdString(data, MediaMetadataRetriever.METADATA_KEY_ALBUM);
            populateMetadata();
        } else {
            mPopulateMetadataWhenAttached = data;
        }
    }

    /**
     * Populates the given metadata into the view
     */
    private void populateMetadata() {
        StringBuilder sb = new StringBuilder();
        int trackTitleLength = 0;
        if (!TextUtils.isEmpty(mMetadata.trackTitle)) {
            sb.append(mMetadata.trackTitle);
            trackTitleLength = mMetadata.trackTitle.length();
        }
        if (!TextUtils.isEmpty(mMetadata.artist)) {
            if (sb.length() != 0) {
                sb.append(" - ");
            }
            sb.append(mMetadata.artist);
        }
        if (!TextUtils.isEmpty(mMetadata.albumTitle)) {
            if (sb.length() != 0) {
                sb.append(" - ");
            }
            sb.append(mMetadata.albumTitle);
        }
        mTrackTitle.setText(sb.toString(), TextView.BufferType.SPANNABLE);
        Spannable str = (Spannable) mTrackTitle.getText();
        if (trackTitleLength != 0) {
            str.setSpan(new ForegroundColorSpan(0xffffffff), 0, trackTitleLength,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            trackTitleLength++;
        }
        if (sb.length() > trackTitleLength) {
            str.setSpan(new ForegroundColorSpan(0x7fffffff), trackTitleLength, sb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        mAlbumArt.setImageBitmap(mMetadata.bitmap);
        final int flags = mTransportControlFlags;
        setVisibilityBasedOnFlag(mBtnPrev, flags, RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS);
        setVisibilityBasedOnFlag(mBtnNext, flags, RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
        setVisibilityBasedOnFlag(mBtnPlay, flags,
                RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_STOP);

        updatePlayPauseState(mCurrentPlayState);
    }

    private static void setVisibilityBasedOnFlag(View view, int flags, int flag) {
        if ((flags & flag) != 0) {
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.GONE);
        }
    }

    private void updatePlayPauseState(int state) {
        if (DEBUG) Log.v(TAG,
                "updatePlayPauseState(), old=" + mCurrentPlayState + ", state=" + state);
        if (state == mCurrentPlayState) {
            return;
        }
        final int imageResId;
        final int imageDescId;
        boolean showIfHidden = false;
        switch (state) {
            case RemoteControlClient.PLAYSTATE_ERROR:
                imageResId = com.android.internal.R.drawable.stat_sys_warning;
                // TODO use more specific image description string for warning, but here the "play"
                //      message is still valid because this button triggers a play command.
                imageDescId = com.android.internal.R.string.lockscreen_transport_play_description;
                break;

            case RemoteControlClient.PLAYSTATE_PLAYING:
                imageResId = com.android.internal.R.drawable.ic_media_pause;
                imageDescId = com.android.internal.R.string.lockscreen_transport_pause_description;
                showIfHidden = true;
                break;

            case RemoteControlClient.PLAYSTATE_BUFFERING:
                imageResId = com.android.internal.R.drawable.ic_media_stop;
                imageDescId = com.android.internal.R.string.lockscreen_transport_stop_description;
                showIfHidden = true;
                break;

            case RemoteControlClient.PLAYSTATE_PAUSED:
            default:
                imageResId = com.android.internal.R.drawable.ic_media_play;
                imageDescId = com.android.internal.R.string.lockscreen_transport_play_description;
                showIfHidden = false;
                break;
        }
        mBtnPlay.setImageResource(imageResId);
        mBtnPlay.setContentDescription(getResources().getString(imageDescId));
        if (showIfHidden && mWidgetCallbacks != null && !mWidgetCallbacks.isVisible(this)) {
            mWidgetCallbacks.requestShow(this);
        }
        mCurrentPlayState = state;
    }

    static class SavedState extends BaseSavedState {
        boolean wasShowing;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.wasShowing = in.readInt() != 0;
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(this.wasShowing ? 1 : 0);
        }

        public static final Parcelable.Creator<SavedState> CREATOR
                = new Parcelable.Creator<SavedState>() {
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

    @Override
    public Parcelable onSaveInstanceState() {
        if (DEBUG) Log.v(TAG, "onSaveInstanceState()");
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);
        ss.wasShowing = mWidgetCallbacks != null && mWidgetCallbacks.isVisible(this);
        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        if (DEBUG) Log.v(TAG, "onRestoreInstanceState()");
        if (!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        if (ss.wasShowing && mWidgetCallbacks != null) {
            mWidgetCallbacks.requestShow(this);
        }
    }

    public void onClick(View v) {
        int keyCode = -1;
        if (v == mBtnPrev) {
            keyCode = KeyEvent.KEYCODE_MEDIA_PREVIOUS;
        } else if (v == mBtnNext) {
            keyCode = KeyEvent.KEYCODE_MEDIA_NEXT;
        } else if (v == mBtnPlay) {
            keyCode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;

        }
        if (keyCode != -1) {
            sendMediaButtonClick(keyCode);
            if (mWidgetCallbacks != null) {
                mWidgetCallbacks.userActivity(this);
            }
        }
    }

    private void sendMediaButtonClick(int keyCode) {
        if (mClientIntent == null) {
            // Shouldn't be possible because this view should be hidden in this case.
            Log.e(TAG, "sendMediaButtonClick(): No client is currently registered");
            return;
        }
        // use the registered PendingIntent that will be processed by the registered
        //    media button event receiver, which is the component of mClientIntent
        KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
        Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
        try {
            mClientIntent.send(getContext(), 0, intent);
        } catch (CanceledException e) {
            Log.e(TAG, "Error sending intent for media button down: "+e);
            e.printStackTrace();
        }

        keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
        intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
        try {
            mClientIntent.send(getContext(), 0, intent);
        } catch (CanceledException e) {
            Log.e(TAG, "Error sending intent for media button up: "+e);
            e.printStackTrace();
        }
    }

    public void setCallback(LockScreenWidgetCallback callback) {
        mWidgetCallbacks = callback;
    }

    public boolean providesClock() {
        return false;
    }

    private boolean wasPlayingRecently(int state, long stateChangeTimeMs) {
        switch (state) {
            case RemoteControlClient.PLAYSTATE_PLAYING:
            case RemoteControlClient.PLAYSTATE_FAST_FORWARDING:
            case RemoteControlClient.PLAYSTATE_REWINDING:
            case RemoteControlClient.PLAYSTATE_SKIPPING_FORWARDS:
            case RemoteControlClient.PLAYSTATE_SKIPPING_BACKWARDS:
            case RemoteControlClient.PLAYSTATE_BUFFERING:
                // actively playing or about to play
                return true;
            case RemoteControlClient.PLAYSTATE_NONE:
                return false;
            case RemoteControlClient.PLAYSTATE_STOPPED:
            case RemoteControlClient.PLAYSTATE_PAUSED:
            case RemoteControlClient.PLAYSTATE_ERROR:
                // we have stopped playing, check how long ago
                if (DEBUG) {
                    if ((SystemClock.elapsedRealtime() - stateChangeTimeMs) < DISPLAY_TIMEOUT_MS) {
                        Log.v(TAG, "wasPlayingRecently: time < TIMEOUT was playing recently");
                    } else {
                        Log.v(TAG, "wasPlayingRecently: time > TIMEOUT");
                    }
                }
                return ((SystemClock.elapsedRealtime() - stateChangeTimeMs) < DISPLAY_TIMEOUT_MS);
            default:
                Log.e(TAG, "Unknown playback state " + state + " in wasPlayingRecently()");
                return false;
        }
    }
}


text:
<?php
// This file was auto-generated from sdk-root/src/data/ecr-public/2020-10-30/examples-1.json
return [ 'version' => '1.0', 'examples' => [],];


text:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace ClipUp.Windows.Forms
{
    public partial class UploadProgress : Form
    {
        protected override bool ShowWithoutActivation => true;

        public int Progress
        {
            get { return this.progressBar.Value; }
            set { this.progressBar.Value = value; }
        }

        public UploadProgress()
        {
            this.InitializeComponent();
        }

        private void UploadProgress_Load(object sender, EventArgs e)
        {
            var screenBounds = Screen.PrimaryScreen.WorkingArea;

            this.Location = new Point(screenBounds.Left + screenBounds.Width - this.Width, screenBounds.Top + screenBounds.Height - this.Height);
        }
    }
}


text:
package goodsbase.model;

import goodsbase.qserver.QRequest;

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**Describes application user
 * @author Daria
 *
 */
public class User {

	public static final String ADMIN = "admin";
	public static final String WH_MANAGER = "whmanager";
	public static final String SAL_MANAGER = "salesmanager";

	/**
	 * @throws NoSuchAlgorithmException
	 *
	 */
	public User(String username, char[] password, String role) throws NoSuchAlgorithmException {
		this.setUsername(username);
		this.setPassword(password);
		this.setRole(role);
	}

	private User(){}

	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}
	/**
	 * @param username the username to set
	 * @throws NullPointerException if username is null
	 */
	public void setUsername(String username) {
		if(username == null) throw new NullPointerException("username can't be null");
		if(username.equals("")) throw new IllegalArgumentException("username can't be empty");
		this.username = username;
	}

	/**
	 * @param password the password to set. Will be overwritten after method invocation
	 * @throws NoSuchAlgorithmException if md5 algorithm is not available
	 */
	public void setPassword(char[] password) throws NoSuchAlgorithmException {
		try {
			this.password = toMd5Hex(password);
		} finally {
		Arrays.fill(password, '\u0000'); //clear sensitive data
		}
	}

	/**
	 * @return the role
	 */
	public String getRole() {
		return role;
	}

	/**
	 * @param role the role to set
	 * @throws NullPointerException if role is null
	 */
	public void setRole(String role) {
		if(role == null) throw new NullPointerException("role can't be null");
		this.role = role;
	}

	public static boolean createUser(User user) throws DataLoadException{
		String query = "INSERT INTO USERS (USERNAME, PASSWORD, ROLE) VALUES ('"+user.username
				+"', '"+ user.password +"', '"+user.role +"');";
		int result = DataExecutor.executeUpdate(query);
		if (result == QRequest.OK_CODE)
			return true;
		return false;
	}

	public static boolean updateUser(User user) throws DataLoadException {
		String query = "UPDATE USERS SET username='"+user.username
				+ "', password ='" +user.password +"', role='"+user.role+"'"
						+ "where id="+user.id+");";
		int result = DataExecutor.executeUpdate(query);
		if (result == QRequest.OK_CODE)
			return true;
		return false;
	}

	public static int getUsersCount() throws DataLoadException, XPathExpressionException {
		String query = "SELECT COUNT(*) AS NUM FROM users";
		Document doc = DataExecutor.executeSelect(query);
		if (doc != null && doc.getChildNodes().getLength()>0) {
			XPathFactory fact = XPathFactory.newInstance();
			XPath xpath = fact.newXPath();
			String num = xpath.evaluate("result/line/NUM", doc);
			return Integer.valueOf(num);
		}
		return -1;
	}

	public static User getUser(String username, char[] password) throws NoSuchAlgorithmException, DataLoadException, XPathExpressionException {
		String query = "SELECT * FROM USERS WHERE username='" + username
				+"' AND password='"+ toMd5Hex(password) +"';";
		try {
			Document doc = DataExecutor.executeSelect(query);
			if (doc != null && doc.getChildNodes().getLength()>0)  {
				XPathFactory fact = XPathFactory.newInstance();
				XPath xpath = fact.newXPath();
				Node n = (Node) xpath.evaluate("result/line", doc, XPathConstants.NODE);
				if(n!=null  && n.getChildNodes().getLength()>0)
					return parseUser(n, xpath);
			}
			return null;
		} finally {
			Arrays.fill(password, '\u0000');
		}
	}

	private static User parseUser(Node node, XPath xpath) throws NumberFormatException, XPathExpressionException {
		int id = Integer.valueOf(xpath.evaluate("USER_ID", node));
		String username = xpath.evaluate("USERNAME", node);
		String password = xpath.evaluate("PASSWORD", node);
		String role = xpath.evaluate("ROLE", node);
		User user = new User();
		user.id =id;
		user.setUsername(username);
		user.password = password;
		user.role = role;
		return user;
	}

	private static String toMd5Hex(char[] password) throws NoSuchAlgorithmException {
		byte[] pass = toBytes(password);
	    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
	    messageDigest.reset();
	    messageDigest.update(pass);
	    byte[] digest = messageDigest.digest();
	    BigInteger integer = new BigInteger(digest);
	    return integer.toString(16);
	}

	private static byte[] toBytes(char[] chars) {
	    CharBuffer charBuffer = CharBuffer.wrap(chars);
	    ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
	    byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
	            byteBuffer.position(), byteBuffer.limit());
	    Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
	    Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
	    return bytes;
	}

	private String username;
	private String password;
	private String role;
	private int id;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lichen sordidus Pers.

### Remarks
null


text:
require './lib/dsa_scraper'
require './lib/twilio_notifier'

check = DSAScraper.new(Date.parse(ENV['DSATESTDATE']))

if check.newer_date_available?
  puts "Newer test date availble! Date is #{check.available_date}."
  TwilioNotifier.notify(check.available_date)
end


text:
package org.apache.carbondata.processing.surrogatekeysgenerator.dbbased;

import java.io.Serializable;
import java.util.Arrays;

public class IntArrayWrapper implements Serializable, Comparable<IntArrayWrapper> {

  /**
   * serialVersionUID
   */
  private static final long serialVersionUID = 1L;

  private int[] data;

  private int primaryKey;

  public IntArrayWrapper(int[] data, int primaryKey) {
    initialize(data);
    this.primaryKey = primaryKey;
  }

  /**
   * This method is used to initialize data array
   *
   * @param data
   */
  public void initialize(int[] data) {
    if (data == null) {
      throw new IllegalArgumentException(" Data Array is NUll");
    }
    this.data = data;
  }

  /**
   * This method will be used check to ArrayWrapper object is equal or not
   *
   * @return boolean
   * equal or not
   */
  @Override public boolean equals(Object other) {
    if (other instanceof IntArrayWrapper) {
      return Arrays.equals(data, ((IntArrayWrapper) other).data);
    }
    return false;
  }

  /**
   * This method will be used to get the hascode, this will be used to the
   * index for inserting ArrayWrapper object as a key in Map
   *
   * @return hascode
   */
  @Override public int hashCode() {
    return Arrays.hashCode(data);
  }

  /**
   * This method will be used to get the long array surrogate keys
   *
   * @return data
   */
  public int[] getData() {
    return data;
  }

  /**
   * Compare method for ArrayWrapper class this will used to compare Two
   * ArrayWrapper data object, basically it will compare two surrogate keys
   * array to check which one is greater
   *
   * @param other ArrayWrapper Object
   */
  @Override public int compareTo(IntArrayWrapper other) {
    for (int i = 0; i < data.length; i++) {
      if (data[i] > other.data[i]) {
        return 1;
      } else if (data[i] < other.data[i]) {
        return -1;
      }
    }
    return 0;
  }

  public int getPrimaryKey() {
    return primaryKey;
  }

  public void setPrimaryKey(int primaryKey) {
    this.primaryKey = primaryKey;
  }
}


text:
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser.test.util;

import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPageFinishedHelper;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPageStartedHelper;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnReceivedErrorHelper;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsObserver;

/**
 * The default WebContentsObserver used by ContentView tests. The below callbacks can be
 * accessed by using {@link TestCallbackHelperContainer} or extending this class.
 */
public class TestWebContentsObserver extends WebContentsObserver {

    private final OnPageStartedHelper mOnPageStartedHelper;
    private final OnPageFinishedHelper mOnPageFinishedHelper;
    private final OnReceivedErrorHelper mOnReceivedErrorHelper;

    public TestWebContentsObserver(WebContents webContents) {
        super(webContents);
        mOnPageStartedHelper = new OnPageStartedHelper();
        mOnPageFinishedHelper = new OnPageFinishedHelper();
        mOnReceivedErrorHelper = new OnReceivedErrorHelper();
    }

    public OnPageStartedHelper getOnPageStartedHelper() {
        return mOnPageStartedHelper;
    }

    public OnPageFinishedHelper getOnPageFinishedHelper() {
        return mOnPageFinishedHelper;
    }

    public OnReceivedErrorHelper getOnReceivedErrorHelper() {
        return mOnReceivedErrorHelper;
    }

    /**
     * ATTENTION!: When overriding the following methods, be sure to call
     * the corresponding methods in the super class. Otherwise
     * {@link CallbackHelper#waitForCallback()} methods will
     * stop working!
     */
    @Override
    public void didStartLoading(String url) {
        super.didStartLoading(url);
        mOnPageStartedHelper.notifyCalled(url);
    }

    @Override
    public void didStopLoading(String url) {
        super.didStopLoading(url);
        mOnPageFinishedHelper.notifyCalled(url);
    }

    @Override
    public void didFailLoad(boolean isProvisionalLoad, boolean isMainFrame,
            int errorCode, String description, String failingUrl, boolean wasIgnoredByHandler) {
        super.didFailLoad(isProvisionalLoad, isMainFrame, errorCode, description, failingUrl,
                wasIgnoredByHandler);
        mOnReceivedErrorHelper.notifyCalled(errorCode, description, failingUrl);
    }
}


text:
package com.ptoceti.osgi.modbus.impl.connection;

import com.ptoceti.osgi.modbus.ModbusDriver;
import com.ptoceti.osgi.modbus.impl.Activator;
import com.ptoceti.osgi.modbus.impl.message.ModbusMessageResponse;
import com.ptoceti.osgi.modbus.impl.message.ModbusMessageRequest;
import com.ptoceti.osgi.modbus.impl.utils.ModbusUtils;

import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import org.osgi.service.log.LogService;

import gnu.io.CommPortIdentifier;
import gnu.io.RXTXCommDriver;
import gnu.io.RXTXVersion;
import gnu.io.SerialPortEventListener;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPort;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;

/**
 * Handle a connection with framing ASCII framing style. In this style, every byte is sent as 2 hex digits,
 * and there iss defined chars for start and end of frame.
 *
 * @author Laurent Thil
 * @version 1.0b
 */

public class ModbusSerialASCIIConnection extends ModbusSerialConnection implements SerialPortEventListener {

	static final byte FRAME_START = 0x3A; // :
	static final byte FRAME_END_1 = 0x0D; //CR
	static final byte FRAME_END_2 = 0x0A; //LF

	// this buffer is used to recived the hex chqrs from the serial link
	ByteArrayOutputStream bytesInHex = new ByteArrayOutputStream();
	// this buffer contains the last message received from the serial link, converted back into binary.
	ByteArrayOutputStream bytesIn = new ByteArrayOutputStream();
	// this buffer contains the next message in hex to send over the link.
	ByteArrayOutputStream bytesOutHex = new ByteArrayOutputStream();
	// this buffer contains the raw bytes of the next message to send.
	ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();

	// flag to indicate that a new frame has arrived.
	boolean hasNewFrame = false;
	// flag to indicate that a special "start of frame" char has been received.
	boolean foundFrameStart = false;
	// flag to indicate that a special "end of frame" char has been received.
	boolean foundFrameEnd1 = false;

	/**
	 * Constructor. Try to create and open the serial connection to modbus from the given arguments.
	 * The serial port is amso configured to use 7 bits data, default for Ascii framing. If the connection
	 * is open successfully, the class registers itself as an listener to even from the serial port and
	 * get hold of the input and pitput streams.
	 *
	 *
	 * @param portName: name of the serial port to use to access the serial port, eg "/dev/tty01"
	 * @param baudRate: baud rate to used on the serial link: 9600 to 19200.
	 * @param usesParity: state whether to send the parity bit on the serial link.
	 * @param evenParity: state whether to use even or odd parity.
	 * @param echo: state whether to expect receivng the echo of a broadcasted message back on the receiver channel.
	 *
	 * @exception Exception is thrown if probmems creating the serial connection.
	 */

	public ModbusSerialASCIIConnection( String portName, int baudRate, boolean usesParity, boolean evenParity, boolean echo ) throws Exception {

		Enumeration portList;
		CommPortIdentifier portID;
		boolean hasFoundPort = false;

		this.portName = portName;

		try {

				portID = CommPortIdentifier.getPortIdentifier(portName);
				if( portID.getPortType() == CommPortIdentifier.PORT_SERIAL) {
					// if this is the port we want,
					if( portID.getName().equals( portName )) {
						// try to get hold of this port. If not successfull within 1 second, throws an exception.
						serialPort = (SerialPort) portID.open( this.getClass().getName(), (int)1000 );
						// if the parity bit is not used, the  port is configured to send two stop bits.
						if( usesParity == true )
							serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_7,
								SerialPort.STOPBITS_1, ( evenParity ? SerialPort.PARITY_EVEN : SerialPort.PARITY_ODD ));
						else
							serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_7,
								SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
						// set itself to listen to data available events.
						serialPort.addEventListener(this);
						serialPort.notifyOnDataAvailable(true);
						// get hold of the inputs and outputs streams.
						inStream = serialPort.getInputStream();
						outStream = serialPort.getOutputStream();
						// success ! we got our port !
						hasFoundPort = true;
						// remember whether to expect the echo of broadcasted frames.
						usesEcho = echo;
					}
				}
			// We did not found the port in the list of ports availables. throw an exception.
			if( hasFoundPort == false ) throw new Exception("Could not find port with name: " + portName + ".");

		} catch ( PortInUseException e) { throw new Exception("Port " + portName + " is already in use."); }
			catch (UnsupportedCommOperationException e) { throw new Exception("Port does not support this operation."); }
			catch (TooManyListenersException e) { throw new Exception("Could not create listener on port: " + portName + "."); }
			catch (IOException e) { throw new Exception("Could not open input or output streams on port: " + portName + "."); }

	}

	public void close() {

		serialPort.close();
		inStream = null;
		outStream = null;
	}

	/**
	 * This method send a ModbusMessageRequest to a slave device over the modbus serial bu.
	 * The method handle the conversion of the bytes to two hex chars, and the framing with
	 * start and end chars.
	 *
	 *
	 * @param msg :  the message to send to a slave device over the bus.
	 * @return the response message. Null if no reply is sent over.
	 */
	public synchronized ModbusMessageResponse sendMessage( ModbusMessageRequest msg ) {

		ModbusMessageResponse response = null;

		try {
			bytesOut.reset();
			bytesOutHex.reset();
			msg.writeTo( bytesOut); // write unitID, functionID + message data
			ModbusUtils.writeHex(bytesOut.toByteArray(), 0, bytesOut.size(), bytesOutHex); // convert the message to hexadecimal.
			// now; calculate the lrc on the asciii message, and add the result byte as two asci hex chars.
			byte lrc  = ModbusUtils.calculateLRC(bytesOutHex.toByteArray(), bytesOutHex.size());
			ModbusUtils.writeHex(lrc, bytesOutHex);

			Activator.log(LogService.LOG_DEBUG, "Sending frame: " + bytesOutHex.toString());

			if( outStream != null){

				outStream.write( FRAME_START); // write start of frame byte in hex
				outStream.write( bytesOutHex.toByteArray());
				outStream.write( FRAME_END_1 ); // add CR
				outStream.write( FRAME_END_2 ); // add LF
				outStream.flush(); // be sure everything in the buffer is send.
				// update statistics counter
				incrementFrameSentCounter();
				// wait for incoming response.
				try {
					if( usesEcho ) {
						if ( hasNewFrame == false ) wait( 10 );
						if ( hasNewFrame == true ) {
							Activator.log(LogService.LOG_DEBUG, "Received echo frame:" + ModbusUtils.writeHex( bytesIn.toByteArray()));
						}
						else {
							Activator.log(LogService.LOG_DEBUG, "Missing echo frame.");
							return response;
						}
					}
					if ( hasNewFrame == false ) wait( 1000 );
					if ( hasNewFrame == true ) {
						// and ask the embedded response message to parse the raw response to a ModbusMessageResponse.
						ModbusMessageResponse respMessage = msg.getResponseMessage();
						// if parsing was successfull, we can return the response message.
						if( respMessage.readFrom( new ByteArrayInputStream(bytesIn.toByteArray())) == true ) response = respMessage;
					}
				} catch (InterruptedException e) {}
			} else {
				Activator.log(LogService.LOG_DEBUG, "Port output stream not open");
			}

		} catch (IOException e) {
			// if we could not send the message, update the appropriate statistic counter.
			incrementBadFramesSentCounter();
		}

		return response;
	}

	public String getEncodingType(){
		return ModbusDriver.ASCII_ENCODING;
	}

	/**
	 * This	method wait till the FrameDetector has recognised a frame on the incoming channel.
	 * This method should be used by the ModbusSlave object. Upon receiving the frame, a new
	 * ModbusRequestMessage is build around it and returned. The method block till a incoming
	 * frame is received.
	 *
	 */
	public synchronized void waitForRequest(){

		try {
			if( hasNewFrame == false ) wait();

			try {
				Activator.log(LogService.LOG_DEBUG, "Received requestframe: " + ModbusUtils.writeHex( bytesIn.toByteArray()));
			} catch (IOException e ) {}

		} catch (InterruptedException e ) {}

		hasNewFrame = false;

	}

	/**
	 * Convert the frame in hex contained in BytesInHex to a binary frame and
	 * saves it in bytesIn. Also check the LRC validity.
	 * Also notify any waiting thread on this object's lock that we have received a frame.
	 *
	 */
	private synchronized void checkNewIncomingMessage() {

		byte[] buff = bytesInHex.toByteArray();
		// recalculate the LRC on the whole received hex message - less the last 2 bytes that are the sent LRC
		byte calculatedLrc = ModbusUtils.calculateLRC( buff, buff.length - 2 );
		// extract the LRC sent over with the frame. It is ent over as two hex char. So we need to convert it back to a single byte
		int hexWord = ( buff[buff.length - 2] << 8 ) + buff[buff.length - 1];
		byte receivedLrc = ModbusUtils.hexWordToByte( hexWord );

		// if the received lrc equals the newly calculated, we consider that the frame is intact.
		if( calculatedLrc == receivedLrc ) {
			try {
				// reset the bytesIn buffer. this in fact clears it of any previous content.
				bytesIn.reset();
				// convert the hex char to plain bytes. Stores result in bytesIn
				ModbusUtils.readHex(buff, 0, buff.length - 2, bytesIn );
				// flag that in.
				hasNewFrame = true;
				// update the statistic counter
				incrementFramesReceivedCounter();
				// and notify any waiting thread that we got a new frame
				notify();
			} catch (IOException e ) {}
		}
		else {
			hasNewFrame = false;
			// update the statistic counter.
			incrementBadFramesReceivedCounter();
			Activator.log(LogService.LOG_DEBUG, "Bad LRC on received frame: " + bytesInHex.toString());
		}
	}

	/**
	 * Serial port's SerialPortEventistener. When a event is produced by the SerialPort class,
	 * is is sent to this method. This mechanism is used to listen to incoming bytes on the serial bus.
	 * Once the start and end special chars are received, the incoming bytes are packed as a proper frame
	 * and passed on to be converted back to binary ( from the hex bytes ).
	 *
	 * @param event : the SerialPortEvent event.
	 */
	public void serialEvent( SerialPortEvent event ) {

		int inByte = 0;
		// at present we are only listening to DATA_AVAILABLE events, which that new incoming bytes
		// have received on the serial port.
		if( event.getEventType() == SerialPortEvent.DATA_AVAILABLE ) {
			try {
			while (inStream.available() > 0 ) {
					// we are working on every received byte ( there may be more than one byte on the input
					// stream ). We also do no want to block the current thread by attempting a read() with
					// no available bytes.

					inByte = inStream.read();
					// if we receive a start of frame byte, flag it and reset the hex buffer.
					if( inByte == FRAME_START ) {
						foundFrameStart = true;
						bytesInHex.reset();
					}
					// if we received the first end frame byte (there is two in succession), then ..
					else if( inByte == FRAME_END_1 ) {
						// if we already found the frame start byte, the frame is complete, so flag it.
						if( foundFrameStart == true ) {
							foundFrameEnd1 = true;
						}
						else {
						// we did not received the frame start byte, so the frame is incomplete, reset everything.
							foundFrameStart = false;
							bytesInHex.reset();
						}
					}
					// if we eceived the second end of frame byte, ..
					else if( inByte == FRAME_END_2 ) {
						// and if we received the start and first end of frame chars, the frame is complete.
						if(( foundFrameEnd1 == true ) && ( foundFrameStart == true )){
							// we can convert the whole frame from hex to binary and save it.
							checkNewIncomingMessage();
						}
						foundFrameStart = false;
						foundFrameEnd1 = false;
					}
					// this is just a norma byte, so if we received the start of frame, but not yet the end
					// of frame char, we just record it.
					else if(( foundFrameStart == true ) && ( foundFrameEnd1 == false )) {
							// write the hex byte into the hex buffer.
							bytesInHex.write(inByte);
						}
					// we gave not received the start of frame, then we just discard the byte and reset everything.
					else {
							foundFrameStart = false;
							foundFrameEnd1 = false;
							bytesInHex.reset();
					}

				}

			} catch (IOException e ) {}
		}

	}

}


text:
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.

namespace Narvalo.Reliability
{
    using System;

    public sealed class RequestCounter : IReliabilitySentinel, IReliabilityMonitor
    {
        public long FailureCount { get; private set; } = 0;

        public long RequestCount { get; private set; } = 0;

        public long SuccessCount { get; private set; } = 0;

        public void Invoke(Action action)
        {
            Require.NotNull(action, nameof(action));

            RecordRequest();

            try
            {
                action.Invoke();
            }
            catch (ReliabilityException)
            {
                throw;
            }
            catch
            {
                RecordFailure();
                throw;
            }

            RecordSuccess();
        }

        public void RecordFailure() => FailureCount++;

        public void RecordRequest() => RequestCount++;

        public void RecordSuccess() => SuccessCount++;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
de.poaceae.SPG.basic Class Hierarchy
</TITLE>

<META NAME="date" CONTENT="2011-12-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package de.poaceae.SPG.basic

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

de.poaceae.SPG.basic.Main

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Progress = function (_React$Component) {
  _inherits(Progress, _React$Component);

  function Progress() {
    _classCallCheck(this, Progress);

    return _possibleConstructorReturn(this, (Progress.__proto__ || Object.getPrototypeOf(Progress)).apply(this, arguments));
  }

  _createClass(Progress, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          label = _props.label,
          title = _props.title,
          text = _props.text;

      var percent = this._getPercent();
      return _react2.default.createElement(
        'div',
        { className: 'reframe-progress' },
        _react2.default.createElement(
          'div',
          { className: 'pie p' + percent },
          _react2.default.createElement(
            'span',
            null,
            label || percent + '%'
          ),
          _react2.default.createElement(
            'div',
            { className: 'slice' },
            _react2.default.createElement('div', { className: 'bar' }),
            _react2.default.createElement('div', { className: 'fill' })
          )
        ),
        title && _react2.default.createElement(
          'h3',
          null,
          title
        ),
        text && _react2.default.createElement(
          'p',
          null,
          text
        )
      );
    }
  }, {
    key: '_getPercent',
    value: function _getPercent() {
      var percent = this.props.percent;

      return parseInt(percent);
    }
  }]);

  return Progress;
}(_react2.default.Component);

Progress.propTypes = {
  label: _propTypes2.default.string,
  percent: _propTypes2.default.number,
  text: _propTypes2.default.string,
  title: _propTypes2.default.string
};
exports.default = Progress;


text:
class AnalyticsSSE < Sinatra::Base
  include Sinatra::SSE
  get '/' do
    sse_stream do |out|
      number = 0
      EM.add_periodic_timer(2) do
        number = 10 + rand(50)
        out.push :event => 'FOOBAR', :data => number.to_s
      end
    end
  end
end


text:
<?php

namespace Spiral\Commands\Reactor;

use Spiral\Commands\Reactor\Prototypes\AbstractCommand;
use Spiral\Reactor\Generators\MiddlewareGenerator;
use Spiral\Reactor\Reactor;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

/**
 * Generate empty http middleware.
 */
class MiddlewareCommand extends AbstractCommand
{
    /**
     * Generator class to be used.
     */
    const GENERATOR = MiddlewareGenerator::class;

    /**
     * Generation type to be used.
     */
    const TYPE = 'middleware';

    /**
     * {@inheritdoc}
     */
    protected $name = 'create:middleware';

    /**
     * {@inheritdoc}
     */
    protected $description = 'Generate new http middleware.';

    /**
     * {@inheritdoc}
     */
    protected $arguments = [
        ['name', InputArgument::REQUIRED, 'Middleware name.'],
    ];

    /**
     * Perform command.
     *
     * @param Reactor $reactor
     */
    public function perform(Reactor $reactor)
    {
        /**
         * @var MiddlewareGenerator $generator
         */
        if (empty($generator = $this->getGenerator())) {
            return;
        }

        foreach ($this->option('depends') as $service) {
            if (empty($class = $reactor->findClass('service', $service))) {
                $this->writeln(
                    "<fg=red>Unable to locate service class for '{$service}'.</fg=red>"
                );

                return;
            }

            $generator->addDependency($service, $class);
        }

        //Generating
        $generator->render();

        $filename = basename($generator->getFilename());
        $this->writeln("<info>Http middleware was successfully created:</info> {$filename}");
        $this->writeln("You register your middleware by assigning it to Route or via http config.");
    }

    /**
     * {@inheritdoc}
     */
    protected function defineOptions()
    {
        return [
            [
                'depends',
                'd',
                InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
                'Add service dependency to middleware. Declare dependency in short form.'
            ],
            [
                'comment',
                null,
                InputOption::VALUE_OPTIONAL,
                'Optional comment to add as class header.'
            ]
        ];
    }
}


text:
<?php

declare(strict_types=1);

namespace Yansongda\Pay\Tests\Plugin\Unipay\Shortcut;

use Yansongda\Pay\Exception\Exception;
use Yansongda\Pay\Exception\InvalidParamsException;
use Yansongda\Pay\Plugin\Unipay\QrCode\PosNormalPlugin;
use Yansongda\Pay\Plugin\Unipay\QrCode\PosPreAuthPlugin;
use Yansongda\Pay\Plugin\Unipay\Shortcut\PosShortcut;
use Yansongda\Pay\Tests\TestCase;

class PosShortcutTest extends TestCase
{
    protected $plugin;

    protected function setUp(): void
    {
        parent::setUp();

        $this->plugin = new PosShortcut();
    }

    public function testDefault()
    {
        self::assertEquals([
            PosNormalPlugin::class,
        ], $this->plugin->getPlugins([]));
    }

    public function testPreAuth()
    {
        self::assertEquals([
            PosPreAuthPlugin::class,
        ], $this->plugin->getPlugins(['_type' => 'pre_auth']));
    }

    public function testFoo()
    {
        self::expectException(InvalidParamsException::class);
        self::expectExceptionCode(Exception::SHORTCUT_MULTI_TYPE_ERROR);
        self::expectExceptionMessage('Pos type [fooPlugins] not supported');

        $this->plugin->getPlugins(['_type' => 'foo']);
    }
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>reveal.js - The HTML Presentation Framework</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/black.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Controlling a Step Motor with a Raspberry PI

Types

standard

servo

step

							StepperMotor by Wapcaplet; Teravolt. GFDL via Wikimedia Commons

							github.com/kidoman/embd


text:
package v1

import (
	"fmt"

	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"

	"knative.dev/pkg/apis"
	av1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1"
	"knative.dev/serving/pkg/apis/config"
	"knative.dev/serving/pkg/apis/serving"
)

const (
	// ReasonContainerMissing defines the reason for marking container healthiness status
	// as false if the a container image for the revision is missing.
	ReasonContainerMissing = "ContainerMissing"

	// ReasonDeploying defines the reason for marking revision availability status as
	// unknown if the revision is still deploying.
	ReasonDeploying = "Deploying"

	// ReasonNotOwned defines the reason for marking revision availability status as
	// false due to resource ownership issues.
	ReasonNotOwned = "NotOwned"

	// ReasonProgressDeadlineExceeded defines the reason for marking revision availability
	// status as false if progress has exceeded the deadline.
	ReasonProgressDeadlineExceeded = "ProgressDeadlineExceeded"
)

var revisionCondSet = apis.NewLivingConditionSet(
	RevisionConditionResourcesAvailable,
	RevisionConditionContainerHealthy,
)

// GetGroupVersionKind returns the GroupVersionKind.
func (r *Revision) GetGroupVersionKind() schema.GroupVersionKind {
	return SchemeGroupVersion.WithKind("Revision")
}

// IsReady returns if the revision is ready to serve the requested configuration.
func (rs *RevisionStatus) IsReady() bool {
	return revisionCondSet.Manage(rs).IsHappy()
}

// GetContainerConcurrency returns the container concurrency. If
// container concurrency is not set, the default value will be returned.
// We use the original default (0) here for backwards compatibility.
// Previous versions of Knative equated unspecified and zero, so to avoid
// changing the value used by Revisions with unspecified values when a different
// default is configured, we use the original default instead of the configured
// default to remain safe across upgrades.
func (rs *RevisionSpec) GetContainerConcurrency() int64 {
	if rs.ContainerConcurrency == nil {
		return config.DefaultContainerConcurrency
	}
	return *rs.ContainerConcurrency
}

// InitializeConditions sets the initial values to the conditions.
func (rs *RevisionStatus) InitializeConditions() {
	revisionCondSet.Manage(rs).InitializeConditions()
}

// MarkActiveTrue marks Active status on revision as True
func (rs *RevisionStatus) MarkActiveTrue() {
	revisionCondSet.Manage(rs).MarkTrue(RevisionConditionActive)
}

// MarkActiveFalse marks Active status on revision as False
func (rs *RevisionStatus) MarkActiveFalse(reason, message string) {
	revisionCondSet.Manage(rs).MarkFalse(RevisionConditionActive, reason, message)
}

// MarkActiveUnknown marks Active status on revision as Unknown
func (rs *RevisionStatus) MarkActiveUnknown(reason, message string) {
	revisionCondSet.Manage(rs).MarkUnknown(RevisionConditionActive, reason, message)
}

// MarkContainerHealthyTrue marks ContainerHealthy status on revision as True
func (rs *RevisionStatus) MarkContainerHealthyTrue() {
	revisionCondSet.Manage(rs).MarkTrue(RevisionConditionContainerHealthy)
}

// MarkContainerHealthyFalse marks ContainerHealthy status on revision as False
func (rs *RevisionStatus) MarkContainerHealthyFalse(reason, message string) {
	revisionCondSet.Manage(rs).MarkFalse(RevisionConditionContainerHealthy, reason, message)
}

// MarkContainerHealthyUnknown marks ContainerHealthy status on revision as Unknown
func (rs *RevisionStatus) MarkContainerHealthyUnknown(reason, message string) {
	revisionCondSet.Manage(rs).MarkUnknown(RevisionConditionContainerHealthy, reason, message)
}

// MarkResourcesAvailableTrue marks ResourcesAvailable status on revision as True
func (rs *RevisionStatus) MarkResourcesAvailableTrue() {
	revisionCondSet.Manage(rs).MarkTrue(RevisionConditionResourcesAvailable)
}

// MarkResourcesAvailableFalse marks ResourcesAvailable status on revision as False
func (rs *RevisionStatus) MarkResourcesAvailableFalse(reason, message string) {
	revisionCondSet.Manage(rs).MarkFalse(RevisionConditionResourcesAvailable, reason, message)
}

// MarkResourcesAvailableUnknown marks ResourcesAvailable status on revision as Unknown
func (rs *RevisionStatus) MarkResourcesAvailableUnknown(reason, message string) {
	revisionCondSet.Manage(rs).MarkUnknown(RevisionConditionResourcesAvailable, reason, message)
}

// PropagateDeploymentStatus takes the Deployment status and applies its values
// to the Revision status.
func (rs *RevisionStatus) PropagateDeploymentStatus(original *appsv1.DeploymentStatus) {
	ds := serving.TransformDeploymentStatus(original)
	cond := ds.GetCondition(serving.DeploymentConditionReady)
	if cond == nil {
		return
	}

	m := revisionCondSet.Manage(rs)
	switch cond.Status {
	case corev1.ConditionTrue:
		m.MarkTrue(RevisionConditionResourcesAvailable)
	case corev1.ConditionFalse:
		m.MarkFalse(RevisionConditionResourcesAvailable, cond.Reason, cond.Message)
	case corev1.ConditionUnknown:
		m.MarkUnknown(RevisionConditionResourcesAvailable, cond.Reason, cond.Message)
	}
}

// PropagateAutoscalerStatus propagates autoscaler's status to the revision's status.
func (rs *RevisionStatus) PropagateAutoscalerStatus(ps *av1alpha1.PodAutoscalerStatus) {
	// Propagate the service name from the PA.
	rs.ServiceName = ps.ServiceName

	// Reflect the PA status in our own.
	cond := ps.GetCondition(av1alpha1.PodAutoscalerConditionReady)
	if cond == nil {
		rs.MarkActiveUnknown("Deploying", "")
		return
	}

	switch cond.Status {
	case corev1.ConditionUnknown:
		rs.MarkActiveUnknown(cond.Reason, cond.Message)
	case corev1.ConditionFalse:
		rs.MarkActiveFalse(cond.Reason, cond.Message)
	case corev1.ConditionTrue:
		rs.MarkActiveTrue()

		// Precondition for PA being active is SKS being active and
		// that entices that |service.endpoints| > 0.
		rs.MarkResourcesAvailableTrue()
		rs.MarkContainerHealthyTrue()
	}
}

// ResourceNotOwnedMessage constructs the status message if ownership on the
// resource is not right.
func ResourceNotOwnedMessage(kind, name string) string {
	return fmt.Sprintf("There is an existing %s %q that we do not own.", kind, name)
}

// ExitCodeReason constructs the status message from an exit code
func ExitCodeReason(exitCode int32) string {
	return fmt.Sprintf("ExitCode%d", exitCode)
}

// RevisionContainerExitingMessage constructs the status message if a container
// fails to come up.
func RevisionContainerExitingMessage(message string) string {
	return fmt.Sprintf("Container failed with: %s", message)
}

// RevisionContainerMissingMessage constructs the status message if a given image
// cannot be pulled correctly.
func RevisionContainerMissingMessage(image string, message string) string {
	return fmt.Sprintf("Unable to fetch image %q: %s", image, message)
}


text:
'use strict';
/*global angular: false */

var app = angular.module('Services', []);

// This example shows five ways to define a service.

// #1: Using a constant
// This is for primitives and objects that only contain data, not functions.
app.constant('startingValue', 3);

// #2: Using a primitive, function or object (may contain functions) value
// Services can't be injected into these functions.
app.value('doubleIt', function (n) { return n * 2; });

// #3: Using a "factory" function
// Can inject services when defined this way (ex. $log).
app.factory('factorySvc', function ($log) {
  $log.log('factorySvc entered');
  var svc = {};
  svc.double = function (number) { return number * 2; };
  return svc;
});

// #4: Using a constructor function
// Can inject services when defined this way (ex. $log).
function Doubler($log) {
  $log.log('constructor entered');
  this.double = function (number) { return number * 2; };
}
app.service('ctorSvc', Doubler);

// #5: Using a "provider" function
// Can inject services when defined this way (ex. $log).
app.provider('configurableSvc', function () {
  this.multiplier = 2;
  this.setMultiplier = function (multiplier) {
    this.multiplier = multiplier;
  };
  this.$get = function ($log) {
    $log.log('$get entered');
    var m = this.multiplier;
    return {
      double: function (n) { return n * m; }
    };
  };
});

// The service "configurableSvcProvider"
// is created automatically by app.provider.
app.config(function (configurableSvcProvider) {
  configurableSvcProvider.setMultiplier(3);
});

// Each of the five types of services defined above
// is injected into this controller.
app.controller('MyCtrl',
  function ($scope, startingValue,
    doubleIt, factorySvc, ctorSvc, configurableSvc) {

  $scope.number = startingValue;

  $scope.double = function () {
    //$scope.number = doubleIt($scope.number);
    //$scope.number = factorySvc.double($scope.number);
    //$scope.number = ctorSvc.double($scope.number);
    $scope.number = configurableSvc.double($scope.number);
  };
});


text:
using System;
using System.IO;
using Xemio.GameLibrary.Content;
using Xemio.GameLibrary.Network.Packages;
using Xemio.GameLibrary.Plugins.Implementations;

namespace Xemio.GameLibrary.Network.Protocols.Streamed
{
    public class BufferedSerializer
    {
        #region Fields
        private readonly object _writeSemaphore = new object();
        private readonly object _readSemaphore = new object();
        #endregion

        #region Methods
        /// <summary>
        /// Serializes the specified package.
        /// </summary>
        /// <param name="package">The package.</param>
        /// <param name="stream">The stream.</param>
        protected void Serialize(Package package, Stream stream)
        {
            var buffer = new MemoryStream();
            var writer = new BinaryWriter(buffer);
            var serializer = XGL.Components.Require<SerializationManager>();

            writer.Write(package.Id);
            serializer.Save(package, buffer);

            byte[] data = buffer.ToArray();
            lock (this._writeSemaphore)
            {
                stream.Write(data, 0, data.Length);
            }
        }
        /// <summary>
        /// Deserializes a package from the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        protected Package Deserialize(Stream stream)
        {
            var reader = new BinaryReader(stream);
            var implementations = XGL.Components.Require<IImplementationManager>();
            var serializer = XGL.Components.Require<SerializationManager>();

            int packageId = reader.ReadInt32();
            Type type = implementations.GetType<int, Package>(packageId);

            lock (this._readSemaphore)
            {
                return (Package)serializer.Load(type, stream);
            }
        }
        #endregion
    }
}


text:
#import "AbstractReportElement.h"

@class Person;
@class AddressElementLine;

@interface AddressElement:AbstractReportElement
{
    Person	*person;
    NSString	*personName;
    NSRect	personNameRect;
    BOOL 	displayPersonName;
    float	addressWidth;
    float	phoneWidth;
    float	phoneSpaceDown;
    NSMutableArray *lines;
    AbstractReportPanel *panel;
    AbstractReportView *view;
}

- initPerson:(Person *)aPerson panel:(AbstractReportPanel *)aPanel view:(AbstractReportView *)aView;
- (Person *)person;
- (void)addLine:(NSString *)buf tag:(int)tag;
- (void)setWidth:(float)aWidth phoneWidth:(float)phoneNumberWidth;
- (void)setDisplayPersonName:(BOOL)flag;
- (void)set;				// calculate the widths and heights
- (float)height;
- (NSString *)personName;

#define ADDRESS_INDEX 0
#define PHONE_INDEX 1
#define PHONEWITHLABEL_INDEX 2

@end