text:
package com.w11k.lsql.query;

import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.w11k.lsql.*;
import com.w11k.lsql.converter.Converter;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import io.reactivex.subjects.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

import static com.google.common.base.Optional.absent;
import static com.google.common.base.Optional.of;

public abstract class AbstractQuery<T> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final LSql lSql;

    private final PreparedStatement preparedStatement;

    private Map<String, Converter> converters = Maps.newHashMap();

    private boolean ignoreDuplicateColumns = false;

    public AbstractQuery(LSql lSql, PreparedStatement preparedStatement, Map<String, Converter> outConverters) {
        this.lSql = lSql;
        this.preparedStatement = preparedStatement;

        if (outConverters != null) {
            this.setConverters(outConverters);
        }

        Integer defaultQueryTimeoutInSeconds = lSql.getConfig().getDefaultQueryTimeoutInSeconds();
        if (defaultQueryTimeoutInSeconds != null) {
            try {
                preparedStatement.setQueryTimeout(defaultQueryTimeoutInSeconds);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public LSql getlSql() {
        return lSql;
    }

    public AbstractQuery<T> ignoreDuplicateColumns() {
        ignoreDuplicateColumns = true;
        return this;
    }

    public PreparedStatement getPreparedStatement() {
        return preparedStatement;
    }

    public Map<String, Converter> getConverters() {
        return converters;
    }

    public AbstractQuery<T> setConverters(Map<String, Converter> converters) {
        this.converters = converters;
        return this;
    }

    public AbstractQuery<T> addConverter(String columnName, Converter converter) {
        this.converters.put(columnName, converter);
        return this;
    }

    public AbstractQuery<T> setQueryTimeout(int seconds) {
        try {
            this.preparedStatement.setQueryTimeout(seconds);
            return this;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<T> toList() {
        return rx().toList().blockingGet();
    }

    public <R> List<R> toList(Function<T, R> mapper) {
        return rx().map(mapper).toList().blockingGet();
    }

    public abstract List<T> toTree();

    /**
     * Executes the query and returns the first row in the result set. Return absent() if the result set is empty.
     */
    public Optional<T> first() {
        List<T> list = rx().take(1).toList().blockingGet();
        if (list.isEmpty()) {
            return Optional.absent();
        } else {
            return of(list.get(0));
        }
    }

    public <R> Optional<R> first(final Function<T, R> mapper) {
        return this.first().transform(t -> {
            try {
                return mapper.apply(t);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * Turns this query into an Observable.  Each subscription will trigger the underlying database operation.
     *
     * @return the Observable
     */
    public Observable<T> rx() {
        return rxResultSet().map(this::extractEntity);
    }

    /**
     * Turns this query into an Observable. Each subscription will trigger the underlying database operation.
     * <p/>
     * This is a low-level API to directly work with the JDBC ResultSet.
     *
     * @return the Observable
     */
    public Observable<ResultSetWithColumns> rxResultSet() {

        return Subject.create(emitter -> {
            try {
                ResultSetWithColumns resultSetWithColumns = createResultSetWithColumns();
//                checkConformity(resultSetWithColumns.getConverters());

                while (resultSetWithColumns.getResultSet().next() && !emitter.isDisposed()) {
                    emitter.onNext(resultSetWithColumns);
                }
                resultSetWithColumns.getResultSet().close();
                emitter.onComplete();
            } catch (SQLException e) {
                emitter.onError(e);
            }
        });
    }

    public ResultSetWithColumns createResultSetWithColumns() {
        try {
            ResultSet resultSet = this.preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();

            // used to find duplicates
            // or unused converter
            Set<String> processedColumnLabels = Sets.newLinkedHashSet();

            List<ResultSetColumn> resultSetColumns = Lists.newLinkedList();
            LinkedHashMap<String, Converter> converters = Maps.newLinkedHashMap();

            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                Converter converter = null;
                String columnLabel;
                String resultSetColumnName = metaData.getColumnLabel(i);

                // f as "f: type"
                int idxOfColon = resultSetColumnName.indexOf(':');
                if (idxOfColon == -1) {
                    columnLabel = AbstractQuery.this.lSql.convertExternalSqlToInternalSql(resultSetColumnName);
                } else {
                    columnLabel = resultSetColumnName.substring(0, idxOfColon).trim();
                    String typeAnnotation = resultSetColumnName.substring(idxOfColon + 1).trim();
                    if (typeAnnotation.length() > 0) {
                        converter = this.lSql.getConverterForAlias(typeAnnotation);
                    }
                }

                // check duplicates
                if (!this.ignoreDuplicateColumns && processedColumnLabels.contains(columnLabel.toLowerCase())) {
                    throw new IllegalStateException("Duplicate column '" + columnLabel + "' (lower case) in query.");
                }
                processedColumnLabels.add(columnLabel.toLowerCase());

                if (converter == null) {
                    Optional<Converter> converterForResultSetColumn = getConverterForResultSetColumn(metaData, i, columnLabel, false);
                    if (converterForResultSetColumn.isPresent()) {
                        converter = converterForResultSetColumn.get();
                    }
                }

                if (converter != null) {
                    ResultSetColumn resultSetColumn = new ResultSetColumn(i, columnLabel, converter);
                    boolean nullable = metaData.isNullable(i) == ResultSetMetaData.columnNullable;
                    resultSetColumn.setNullable(nullable);
                    resultSetColumns.add(resultSetColumn);
                    converters.put(columnLabel, converter);
                }
            }

            // Check for unused converters
            for (String converterFor : AbstractQuery.this.converters.keySet()) {
                if (!processedColumnLabels.contains(converterFor)) {
                    throw new IllegalArgumentException(
                            "unused converter for column '" + converterFor + "'");
                }
            }

            return new ResultSetWithColumns(resultSet, metaData, resultSetColumns, converters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Optional<Converter> getConverterForResultSetColumn(ResultSetMetaData metaData,
                                                              int position,
                                                              String columnLabel,
                                                              boolean getConverterBySqlType)
            throws SQLException {

        // Check for user provided Converter
        if (converters.containsKey(columnLabel)) {
            Converter converter = converters.get(columnLabel);
            if (converter != null) {
                return of(converter);
            }
        }

        // Determine source table and column from ResultSet
        String javaTableName = lSql.convertExternalSqlToInternalSql(
                lSql.getSqlSchemaAndTableNameFromResultSetMetaData(metaData, position));

        String javaColumnName = lSql.convertExternalSqlToInternalSql(
                lSql.getSqlColumnNameFromResultSetMetaData(metaData, position));

        if (javaTableName != null
                && javaTableName.length() > 0
                && javaColumnName != null
                && javaColumnName.length() > 0) {
            Column column = lSql.table(javaTableName).column(javaColumnName);
            if (column != null) {
                if (!column.isIgnored()) {
                    return of(column.getConverter());
                } else {
                    return absent();
                }
            }
        }

        // Check if the user registered null as a Converter to use a type-based Converter
        // or if the default converter was allowed
        if (getConverterBySqlType
                || (converters.containsKey(columnLabel) && converters.get(columnLabel) == null)) {
            return of(getConverterByColumnType(metaData, position));
        }

        // Error/Warn
        if (lSql.isUseColumnTypeForConverterLookupInQueries()) {
            return of(getConverterByColumnType(metaData, position));
        } else {
            String msg = "Unable to determine a Converter instance for column '" + columnLabel + "'. ";
            msg += "Annotate the query with `col_name as \"col_name: type\"` or " +
                    "register a converter with Query#addConverter() / Query#setConverters().";

            throw new IllegalStateException(msg);
        }
    }

    private Converter getConverterByColumnType(ResultSetMetaData metaData, int position) throws SQLException {
        int columnSqlType = metaData.getColumnType(position);
        return lSql.getConverterForSqlType(columnSqlType);
    }

    private T extractEntity(ResultSetWithColumns resultSetWithColumns) {
        ResultSet resultSet = resultSetWithColumns.getResultSet();
        Collection<ResultSetColumn> columnList = resultSetWithColumns.getColumnsByLabel().values();
        RowDeserializer<T> rowDeserializer = this.getRowDeserializer();
        try {
            T entity = rowDeserializer.createRow();
            for (ResultSetColumn column : columnList) {
                rowDeserializer.deserializeField(
                        this.lSql, entity, column.getConverter(), column.getName(), resultSet, column.getPosition());
            }
            return entity;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected abstract RowDeserializer<T> getRowDeserializer();

}


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

namespace Microsoft.WindowsAzure.Management.ScenarioTest.ServiceManagemenet
{
    using System.Management.Automation;
    using Common;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.WindowsAzure.Management.Test.Utilities;
    using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties;
    using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests;
    using Microsoft.WindowsAzure.Management.ServiceManagement.Model;
    using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;

    [TestClass]
    public class VMProvisionScenarioTests : WindowsAzurePowerShellTest
    {
        public VMProvisionScenarioTests()
            : base("CloudService\\Common.ps1",
                   "ServiceManagemenet\\Common.ps1",
                   "ServiceManagemenet\\VMProvisionTests.ps1"
            )
        {

        }

        [TestMethod]
        [TestCategory(Category.All)]
        [TestCategory(Category.ServiceManagement)]
        [TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureQuickVM,Get-AzureVMImage,Get-AzureVM,Get-AzureLocation,Import-AzurePublishSettingsFile,Get-AzureSubscription,Set-AzureSubscription)")]
        public void NewWindowsAzureQuickVM()
        {
            powershell.Invoke();

            ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper();

            string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false);
            string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false);

            string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM");
            string newAzureQuickVMSvcName = Utilities.GetUniqueShortName("PSTestService");

            vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, newAzureQuickVMSvcName, imageName, "pstestuser", "p@ssw0rd", locationName);

            // Verify
            PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName);
            Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true);

            // Cleanup
            vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName);

            Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProgettoGIA.Model;

namespace ProgettoGIA.Presenter
{
    public partial class AtletiUserControl : UserControl
    {
        Guid _guidAtletaSelezionata;
        AtletaDataGridViewPresenter _atletaDataGridViewPresenter;
        Dictionary<Disciplina, CheckBox> _dictionariDiscipline;

        public AtletiUserControl()
        {
            InitializeComponent();
        }

        //properti
        public DataGridView AtletaDataGrid => _atletiGridView;
        public Dictionary<Disciplina, CheckBox> DizionarioCheckBoxDiscipline => _dictionariDiscipline;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _maschioRadioButton.Enabled = true;
            _atletaDataGridViewPresenter = new AtletaDataGridViewPresenter(_atletiGridView);
            _societàComboBox.Items.Add("");
            foreach (Società s in Gara.GetInstance().Società)
            {
                _societàComboBox.Items.Add(s);
            }
            _societàComboBox.SelectedIndex = 0;

            _atletiGridView.Columns["Guid"].Visible = false;

            _dictionariDiscipline = new Dictionary<Disciplina, CheckBox>();
            _dictionariDiscipline.Add(Disciplina.CNF, _cnfCheckBox);
            _dictionariDiscipline.Add(Disciplina.CWM, _cwmCheckBox);
            _dictionariDiscipline.Add(Disciplina.FIO, _fioCheckBox);
            _dictionariDiscipline.Add(Disciplina.DYM, _dymCheckBox);
            _dictionariDiscipline.Add(Disciplina.DNF, _dnfCheckBox);
            _dictionariDiscipline.Add(Disciplina.DYN, _dynCheckBox);
            _dictionariDiscipline.Add(Disciplina.CWF, _cwfCheckBox);
            _dictionariDiscipline.Add(Disciplina.STA, _staCheckBox);
            _dictionariDiscipline.Add(Disciplina.FIM, _fimCheckBox);
            _dictionariDiscipline.Add(Disciplina.CAM, _camCheckBox);

            foreach (KeyValuePair<Disciplina, CheckBox> kvp in _dictionariDiscipline)
            {
                kvp.Value.Enabled = false;
            }

            _iscrizioneGaraGroupBox.Enabled = false;
            _atletiGridView.CurrentCell = null;

            Gara.GetInstance().Changed += RefreshCheckBoxList;
        }

        private void _addAtletaButton_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(_nomeTextBox.Text) || !String.IsNullOrEmpty(_cognomeTextBox.Text) || !String.IsNullOrEmpty(((Società)_societàComboBox.SelectedItem).ToString()) || !String.IsNullOrEmpty(_codiceFiscaleTextBox.Text))
            {
                Atleta a;
                Società s = Gara.GetInstance().GetSocietàForNomeSede(((Società)_societàComboBox.SelectedItem).ToString()); //porcata!!!!

                if (_maschioRadioButton.Enabled)
                {
                    a = new Atleta(_nomeTextBox.Text, _cognomeTextBox.Text, _codiceFiscaleTextBox.Text, Sesso.MASCHIO, _dataNascitaTimePicker.Value, _istruttoreCheckBox.Checked, s, _scadenzaCertificatoTimePicker.Value, Guid.Empty);
                }
                else
                {
                    a = new Atleta(_nomeTextBox.Text, _cognomeTextBox.Text, _codiceFiscaleTextBox.Text, Sesso.FEMMINA, _dataNascitaTimePicker.Value, _istruttoreCheckBox.Checked, s, _scadenzaCertificatoTimePicker.Value, Guid.Empty);
                }

                if (a.IsEtàInferiore14())
                {
                    MessageBox.Show("L'atleta che si stà tentando di inserire ha meno di 14 anni, quindi l'operazione non può essere completata.", "Atleta con età inferiore a 14 anni", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (a.IsEtàInferiore18())
                {
                    MessageBox.Show("L'atleta che si stà tentando di inserire ha meno di 18 anni, richiedere autorizzazione di un tutore prima di completare l'inserimento.", "Atleta con età inferiore a 18 anni", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                else
                {
                    Gara g = Gara.GetInstance();
                    g.AddAtleta(a);
                }
            }
            else
            {
                MessageBox.Show("Si stà tentando di Aggiungere un utente con dati incompleti, l'operazione non puo essere portata a termine.", "Utente incompleto", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            _nomeTextBox.Clear();
            _cognomeTextBox.Clear();
            _codiceFiscaleTextBox.Clear();
            _societàComboBox.SelectedIndex = 0;
            _dataNascitaTimePicker.Value = DateTime.Now;
            _scadenzaCertificatoTimePicker.Value = DateTime.Now;
            _maschioRadioButton.Select();
            _istruttoreCheckBox.Checked = false;
        }

        private void _removeAtletaButton_Click(object sender, EventArgs e)
        {
            if (_atletiGridView.CurrentCell == null)
            {
                MessageBox.Show("Si sta tentando di eliminare un atleta senza che sia selezionata, ritenta.", "Nessun atleta selezionata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Atleta a = Gara.GetInstance().GetAtletaForID(_guidAtletaSelezionata);

            Gara.GetInstance().RemoveAtleta(a);

            _nomeTextBox.Clear();
            _cognomeTextBox.Clear();
            _codiceFiscaleTextBox.Clear();
            _societàComboBox.SelectedIndex = 0;
            _dataNascitaTimePicker.Value = DateTime.Now;
            _scadenzaCertificatoTimePicker.Value = DateTime.Now;
            _maschioRadioButton.Select();
            _istruttoreCheckBox.Checked = false;

            _atletiGridView.CurrentCell = null;
        }

        private void _editAtletaButton_Click(object sender, EventArgs e)
        {
            if (_atletiGridView.CurrentCell == null)
            {
                MessageBox.Show("Si sta tentando di editare un atleta senza che sia selezionata, ritenta.", "Nessun atleta selezionata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Atleta a = Gara.GetInstance().GetAtletaForID(_guidAtletaSelezionata);

            a.Nome = _nomeTextBox.Text;
            a.Cognome = _cognomeTextBox.Text;
            a.CodiceFiscale = _codiceFiscaleTextBox.Text;

            if (_maschioRadioButton.Checked)
            {
                a.Sesso = Sesso.MASCHIO;
            }
            else
            {
                a.Sesso = Sesso.FEMMINA;
            }
            a.DataDiNascita = _dataNascitaTimePicker.Value;
            a.Istruttore = _istruttoreCheckBox.Checked;
            a.Società = (Società)_societàComboBox.SelectedItem;
            a.ScadenzaCertificato = _scadenzaCertificatoTimePicker.Value;

            _nomeTextBox.Clear();
            _cognomeTextBox.Clear();
            _codiceFiscaleTextBox.Clear();
            _societàComboBox.SelectedIndex = 0;
            _dataNascitaTimePicker.Value = DateTime.Now;
            _scadenzaCertificatoTimePicker.Value = DateTime.Now;
            _maschioRadioButton.Select();
            _istruttoreCheckBox.Checked = false;

            _atletiGridView.CurrentCell = null;
        }

        private void _atletiGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (_atletiGridView.SelectedRows.Count > 0)
            {
                int rowIndex = e.RowIndex;

                if(rowIndex < 0)
                {
                    return;
                }

                DataGridViewRow row = _atletiGridView.Rows[rowIndex];

                _guidAtletaSelezionata = (Guid)row.Cells[0].Value;
                _nomeTextBox.Text = (string)row.Cells[1].Value;
                _cognomeTextBox.Text = (string)row.Cells[2].Value;
                _codiceFiscaleTextBox.Text = (string)row.Cells[3].Value;

                if (((Sesso)row.Cells[4].Value).Equals(Sesso.MASCHIO))
                {
                    _maschioRadioButton.Select();
                }
                else
                {
                    _femminaRadioButton.Select();
                }
                _dataNascitaTimePicker.Value = (DateTime)row.Cells[5].Value;
                _istruttoreCheckBox.Checked = (bool)row.Cells[6].Value;
                _societàComboBox.SelectedItem = (Società)row.Cells[7].Value;
                _scadenzaCertificatoTimePicker.Value = (DateTime)row.Cells[8].Value;

                if (_guidAtletaSelezionata != null) { _iscrizioneGaraGroupBox.Enabled = true; }
            }
        }

        private void _clearButton_Click(object sender, EventArgs e)
        {
            _nomeTextBox.Clear();
            _cognomeTextBox.Clear();
            _codiceFiscaleTextBox.Clear();
            _societàComboBox.SelectedIndex = 0;
            _dataNascitaTimePicker.Value = DateTime.Now;
            _scadenzaCertificatoTimePicker.Value = DateTime.Now;
            _maschioRadioButton.Select();
            _istruttoreCheckBox.Checked = false;
            _iscrizioneGaraGroupBox.Enabled = false;
        }

        private void _aggiungiAtletiAllaGaraButton_Click(object sender, EventArgs e)
        {
            List<Disciplina> temp = new List<Disciplina>();
            Atleta atleta = Gara.GetInstance().GetAtletaForID(_guidAtletaSelezionata);

            if (atleta.ScadenzaCertificato < DateTime.Now)
            {
                MessageBox.Show("Si sta tentando di iscrivere un atleta con certificato medico scaduto.", "Certificato medico scaduto", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (_guidAtletaSelezionata != null)
            {
                foreach (KeyValuePair<Disciplina, CheckBox> kvp in _dictionariDiscipline )
                {
                    if (kvp.Value.Checked)
                    {
                        temp.Add(kvp.Key);
                    }
                }
            }

            Gara.GetInstance().AddAtletaToGara(atleta, temp);
        }

        private void _rimuoviAtletiDallaGaraButton_Click(object sender, EventArgs e)
        {
            if (_guidAtletaSelezionata != null)
            {
                Gara.GetInstance().RemoveAtletaToGara(Gara.GetInstance().GetAtletaForID(_guidAtletaSelezionata));
            }
        }

        private void RefreshCheckBoxList(object sender, EventArgs e)
        {
            foreach (KeyValuePair<Disciplina, CheckBox> kvp in _dictionariDiscipline)
            {
                if (Gara.GetInstance().GetSpecialitàGaraForDisciplina(kvp.Key) != null)
                {
                    kvp.Value.Enabled = true;
                }
                else
                {
                    kvp.Value.Enabled = false;
                }
            }
        }
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="TwitterNotification.cs" company="Patrick 'Ricky' Smith">
//  This file is part of the Twitterizer library (http://www.twitterizer.net)
//
//  Copyright (c) 2010, Patrick "Ricky" Smith (ricky@digitally-born.com)
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are
//  permitted provided that the following conditions are met:
//
//  - Redistributions of source code must retain the above copyright notice, this list
//    of conditions and the following disclaimer.
//  - Redistributions in binary form must reproduce the above copyright notice, this list
//    of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//  - Neither the name of the Twitterizer nor the names of its contributors may be
//    used to endorse or promote products derived from this software without specific
//    prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//  POSSIBILITY OF SUCH DAMAGE.
// </copyright>
// <author>Ricky Smith</author>
// <summary>The twitter notification class.</summary>
//-----------------------------------------------------------------------
namespace Twitterizer
{
    /// <summary>
    /// Provides methods to update a user's preferences on notifications. For example, whether a user will be notified on mention via SMS.
    /// </summary>
    public static class TwitterNotification
    {
        /// <summary>
        /// Enables device notifications for updates from the specified user. Returns the specified user when successful.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="userId">The user id.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public static TwitterResponse<TwitterUser> Follow(OAuthTokens tokens, decimal userId, OptionalProperties options)
        {
            Commands.NotificationFollowCommand command = new Commands.NotificationFollowCommand(tokens, userId, string.Empty, options);

            return Core.CommandPerformer.PerformAction(command);
        }

        /// <summary>
        /// Enables device notifications for updates from the specified user. Returns the specified user when successful.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="userId">The user id.</param>
        /// <returns></returns>
        public static TwitterResponse<TwitterUser> Follow(OAuthTokens tokens, decimal userId)
        {
            return Follow(tokens, userId, null);
        }

        /// <summary>
        /// Enables device notifications for updates from the specified user. Returns the specified user when successful.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="screenName">The user's screen name.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public static TwitterResponse<TwitterUser> Follow(OAuthTokens tokens, string screenName, OptionalProperties options)
        {
            Commands.NotificationFollowCommand command = new Commands.NotificationFollowCommand(tokens, 0, screenName, options);

            return Core.CommandPerformer.PerformAction(command);
        }

        /// <summary>
        /// Enables device notifications for updates from the specified user. Returns the specified user when successful.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="screenName">The user's screen name.</param>
        /// <returns></returns>
        public static TwitterResponse<TwitterUser> Follow(OAuthTokens tokens, string screenName)
        {
            return Follow(tokens, screenName, null);
        }

        /// <summary>
        /// Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="userId">The user id.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public static TwitterResponse<TwitterUser> Leave(OAuthTokens tokens, decimal userId, OptionalProperties options)
        {
            Commands.NotificationLeaveCommand command = new Commands.NotificationLeaveCommand(tokens, userId, string.Empty, options);

            return Core.CommandPerformer.PerformAction(command);
        }

        /// <summary>
        /// Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="userId">The user id.</param>
        /// <returns></returns>
        public static TwitterResponse<TwitterUser> Leave(OAuthTokens tokens, decimal userId)
        {
            return Follow(tokens, userId, null);
        }

        /// <summary>
        /// Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="screenName">The user's screen name.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public static TwitterResponse<TwitterUser> Leave(OAuthTokens tokens, string screenName, OptionalProperties options)
        {
            Commands.NotificationLeaveCommand command = new Commands.NotificationLeaveCommand(tokens, 0, screenName, options);

            return Core.CommandPerformer.PerformAction(command);
        }

        /// <summary>
        /// Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
        /// </summary>
        /// <param name="tokens">The tokens.</param>
        /// <param name="screenName">The user's screen name.</param>
        /// <returns></returns>
        public static TwitterResponse<TwitterUser> Leave(OAuthTokens tokens, string screenName)
        {
            return Follow(tokens, screenName, null);
        }
    }
}


text:
void DetectionPlayList::types(QStringList &list) {
	list << "Play List";
}

// --------------------------------------------------------------------

bool DetectionPlayList::isType(const QFileInfo &fi, QString &type, QString &subtype) {
	QString sSuffix = fi.suffix().toUpper();
	QString sPath = fi.canonicalFilePath().toUpper();
	QString sName = fi.fileName().toUpper();
	// TODO: look inside file (search structure)
	bool bType = (sSuffix == "M3U");
	if (bType) {
		type = "Play List";
		subtype = "todo"; // version and another information
	}
	return bType;
}


text:
> This is a stub

See [prototype-based inheritance][concept-prototype-inheritance] and the general [`date` type][type-date].

[concept-prototype-inheritance]: ../info/prototype_inheritance.md
[type-date]: https://github.com/exercism/v3/blob/main/reference/types/date.md


text:
package com.zmb.sunshine;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.zmb.sunshine.sync.SunshineSyncAdapter;

public class MainActivity extends Activity implements ForecastFragment.Callback {

    private boolean mIsTwoPaneUi = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fm = getFragmentManager();

        // check if we're in two pane UI or single pane
        if (findViewById(R.id.weather_detail_container) != null) {
            mIsTwoPaneUi = true;

            // show the detail view in this activity
            // (we only need to restore the detail fragment if
            // it wasn't already saved off)
            if (savedInstanceState== null) {
                fm.beginTransaction()
                        .replace(R.id.weather_detail_container, new DetailFragment())
                        .commit();
            }
        } else {
            mIsTwoPaneUi = false;
        }

        ForecastFragment ff = (ForecastFragment)(fm.findFragmentById(R.id.fragment_forecast));
        ff.setUseEnhancedTodayView(!mIsTwoPaneUi);

        SunshineSyncAdapter.initialize(this);
        SunshineSyncAdapter.syncNow(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Intent i = new Intent(this, SettingsActivity.class);
            startActivity(i);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Called when a particular day is selected from the forecast list.
     * @param date
     */
    @Override
    public void onItemSelected(String date) {
        if (mIsTwoPaneUi) {
            // on tablets, we replace the detail fragment
            DetailFragment details = new DetailFragment();
            Bundle dateBundle = new Bundle();
            dateBundle.putString(DetailFragment.DATE_KEY, date);
            details.setArguments(dateBundle);
            getFragmentManager().beginTransaction()
                    .replace(R.id.weather_detail_container, details)
                    .commit();
        } else {
            // on phones, we launch the detail activity
            Intent intent = new Intent(this, DetailActivity.class);
            intent.putExtra(DetailFragment.DATE_KEY, date);
            startActivity(intent);
        }
    }
}


text:
import collections
from functools import wraps

from django import forms
from django.core.exceptions import ValidationError
from django.db.models.fields.related import ManyToOneRel
from django.contrib import admin
from django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget, ForeignKeyRawIdWidget, ManyToManyRawIdWidget, AdminDateWidget, AdminTimeWidget, AdminSplitDateTime
from django.utils import dateparse

class Field(object):

    form_class = forms.CharField

    widget = None

    @classmethod
    def clean_type_params(cls, **type_params):
        """Validates and cleans the type params supplied by the FieldForm."""
        if type_params:
            raise ValidationError("Unknown parameter '{name}'.".format(
                name = type_params.keys()[0],
            ))
        return {}

    def __init__(self, **type_params):
        if type_params:
            raise ValueError("Unexpected type params {type_params!r}.".format(
                type_params = type_params,
            ))

    def form_field(self, **kwargs):
        """Returns an instantiated form field."""
        form_class = kwargs.pop("form_class", self.form_class)
        kwargs.setdefault("widget", self.widget)
        return form_class(**kwargs)

    def serialize(self, value):
        """
        Serializes the value to a json representation.

        The value will be of the type returned by the form field's clean() method.
        """
        return value

    def deserialize(self, value):
        """
        Unserializes the value from a json representation.

        The returned value must be parseable by the form_field.
        """
        return value

class RequiredFieldMixin(object):

    """A field that has a 'required' parameter, defaulting to true."""

    @classmethod
    def clean_type_params(cls, **type_params):
        required = type_params.pop("required", True)
        if not isinstance(required, bool):
            raise ValidationError("Parameter 'required' should be a boolean.")
        type_params = super(RequiredFieldMixin, cls).clean_type_params(**type_params)
        type_params["required"] = required
        return type_params

    def __init__(self, required, **type_params):
        self.required = required
        super(RequiredFieldMixin, self).__init__(**type_params)

    def form_field(self, **kwargs):
        kwargs.setdefault("required", self.required)
        return super(RequiredFieldMixin, self).form_field(**kwargs)

class ChoiceFieldMixin(object):

    """A field that takes an optional 'choices' parameter."""

    @classmethod
    def clean_type_params(cls, **type_params):
        choices = type_params.pop("choices", None)
        # Validate the choices.
        if choices is not None:
            if not isinstance(choices, (tuple, list)):
                raise ValidationError("Parameter 'choices' should be a list.")
            for choice in choices:
                if not isinstance(choice, (tuple, list)) and not len(choice) == 2:
                    raise ValidationError("Each choice should be a list containing [value, label].")
        # All done!
        type_params = super(ChoiceFieldMixin, cls).clean_type_params(**type_params)
        type_params["choices"] = choices
        return type_params

    def __init__(self, choices=None, **type_params):
        self.choices = choices
        super(ChoiceFieldMixin, self).__init__(**type_params)

    def form_field(self, **kwargs):
        if self.choices is not None:
            kwargs.setdefault("form_class", forms.ChoiceField)
            kwargs.setdefault("choices", self.choices)
        return super(ChoiceFieldMixin, self).form_field(**kwargs)

def ignores_none(func):
    @wraps(func)
    def do_ignores_none(self, value):
        if value is None:
            return None
        return func(self, value)
    return do_ignores_none

# Simple fields.

class TextField(RequiredFieldMixin, ChoiceFieldMixin, Field):

    widget = AdminTextInputWidget

class LongTextField(RequiredFieldMixin, Field):

    widget = AdminTextareaWidget

class IntegerField(RequiredFieldMixin, ChoiceFieldMixin, Field):

    form_class = forms.IntegerField

class FloatField(RequiredFieldMixin, Field):

    form_class = forms.FloatField

class DateField(RequiredFieldMixin, Field):

    form_class = forms.DateField

    widget = AdminDateWidget

    @ignores_none
    def deserialize(self, value):
        value = super(DateField, self).deserialize(value)
        return dateparse.parse_date(value)

    @ignores_none
    def serialize(self, value):
        value = super(DateField, self).serialize(value)
        return value.isoformat()

class TimeField(RequiredFieldMixin, Field):

    form_class = forms.TimeField

    widget = AdminTimeWidget

    @ignores_none
    def deserialize(self, value):
        value = super(TimeField, self).deserialize(value)
        return dateparse.parse_time(value)

    @ignores_none
    def serialize(self, value):
        value = super(TimeField, self).serialize(value)
        return value.isoformat()

class DateTimeField(RequiredFieldMixin, Field):

    form_class = forms.DateTimeField

    widget = AdminSplitDateTime

    @ignores_none
    def deserialize(self, value):
        value = super(DateTimeField, self).deserialize(value)
        return dateparse.parse_datetime(value)

    @ignores_none
    def serialize(self, value):
        value = super(DateTimeField, self).serialize(value)
        return value.isoformat()

class BooleanField(Field):

    form_class = forms.BooleanField

    def form_field(self, **kwargs):
        kwargs.setdefault("required", False)
        return super(BooleanField, self).form_field(**kwargs)

# File fields.

class FileField(RequiredFieldMixin, Field):

    form_class = forms.ModelChoiceField

    widget = ForeignKeyRawIdWidget

    def form_field(self, **kwargs):
        from data.models import File
        # Create the widget.
        widget = self.widget(
            rel = ManyToOneRel(
                field = None,
                to = File,
                field_name = "id",
            ),
            admin_site = admin.site,
        )
        kwargs["widget"] = widget
        # Add in extra required arguments.
        kwargs["queryset"] = File.objects.all()
        # All done!
        return super(FileField, self).form_field(**kwargs)

    @ignores_none
    def deserialize(self, value):
        from data.models import File
        value = super(FileField, self).deserialize(value)
        storage = File._meta.get_field("file").storage
        root = storage.url("")
        try:
            # HACK: Converting a stored URL into a file name.
            # Not elegant, but allows a denormalized file to be
            # stored in the JSON.
            return File.objects.filter(file=value[len(root):])[0]
        except IndexError:
            return None

    @ignores_none
    def serialize(self, value):
        value = super(FileField, self).serialize(value)
        return value.file.url

# Relations.

class ModelField(RequiredFieldMixin, Field):

    form_class = forms.ModelChoiceField

    widget = ForeignKeyRawIdWidget

    @classmethod
    def clean_type_params(cls, **type_params):
        from data.models import Model
        # Get the model ID.
        try:
            model_id = type_params.pop("model_id")
        except KeyError:
            raise ValidationError("Required parameter 'model_id' not provided.")
        # Validate the model ID.
        try:
            if isinstance(model_id, int):
                model = Model.objects.get(id=model_id)
            elif isinstance(model_id, basestring):
                model = Model.objects.get(external_id=model_id)
            else:
                raise ValidationError("Required parameter 'model_id' should be a number or a string.")
        except Model.DoesNotExist:
            raise ValidationError("Unknown model_id.")
        # Validate remaining type params.
        type_params = super(ModelField, cls).clean_type_params(**type_params)
        # Update type params.
        type_params["model_id"] = model.id
        return type_params

    def __init__(self, model_id, **type_params):
        super(ModelField, self).__init__(**type_params)
        self.model_id = model_id

    def form_field(self, **kwargs):
        from data.models import Instance
        kwargs.setdefault("queryset", Instance.objects.all().filter(
            model__id = self.model_id,
        ))
        # Create the widget.
        widget = self.widget(
            rel = ManyToOneRel(
                field = None,
                to = Instance,
                field_name = "id",
            ),
            admin_site = admin.site,
        )
        kwargs["widget"] = widget
        # HACK: Override URL parameters on widget.
        base_url_parameters = widget.url_parameters
        def url_parameters():
            params = base_url_parameters()
            params["model"] = self.model_id
            return params
        widget.url_parameters = url_parameters
        return super(ModelField, self).form_field(**kwargs)

    @ignores_none
    def serialize(self, value):
        return super(ModelField, self).serialize(value.external_id)

    @ignores_none
    def deserialize(self, value):
        from data.models import Instance
        try:
            return Instance.objects.get(
                model_id = self.model_id,
                external_id = super(ModelField, self).deserialize(value),
            )
        except Instance.DoesNotExist:
            return None

class MultiModelField(ModelField):

    form_class = forms.ModelMultipleChoiceField

    widget = ManyToManyRawIdWidget

    def deserialize(self, value):
        return filter(None, map(super(MultiModelField, self).deserialize, value or ()))

    def serialize(self, value):
        return filter(None, map(super(MultiModelField, self).serialize, value or ()))

fields = collections.OrderedDict((
    ("text", TextField),
    ("integer", IntegerField),
    ("float", FloatField),
    ("date", DateField),
    ("time", TimeField),
    ("datetime", DateTimeField),
    ("boolean", BooleanField),
    ("file", FileField),
    ("long text", LongTextField),
    ("model", ModelField),
    ("multi model", MultiModelField),
))


text:
Pony is an open-source, object-oriented, actor-model, capabilities-secure, high-performance programming language.

## Status

Pony is still pre-1.0 and as such, semi-regularly introduces breaking changes. These changes are usually fairly easy to adapt to. Applications written in Pony are currently used in production environments.

## Supported platforms

### Operating Systems

* FreeBSD
* Linux
* macOS
* Windows 10

### CPUs

* Full support for 64-bit platforms
  * x86, ARM and RISC-V CPUs only
* Partial support for 32-bit platforms
  * The `arm` and `armhf` architectures are tested via CI (Continuous
    Integration testing)

## More Information

* [Installation](INSTALL.md)
* [Building from source](BUILD.md)
* [Docker images](INSTALL_DOCKER.md)
* [Editor support](EDITORS.md)

## Resources

* [Learn more about Pony](https://www.ponylang.io/discover/)
* [Start learning Pony](https://www.ponylang.io/learn/)
  * [Getting help](https://www.ponylang.io/learn/#getting-help)
* [Try Pony online](https://playground.ponylang.io)
* [Frequently Asked Questions](https://www.ponylang.io/faq/)
* [Community](https://www.ponylang.io/community/)

## Contributing

We welcome contributions to Pony. Please read through [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to get started.

## License

Pony is distributed under the terms of the [2-Clause BSD License](https://opensource.org/licenses/BSD-2-Clause). See [LICENSE](LICENSE) for details.


text:
<?xml version="1.0" encoding="UTF-8" ?>
<phpdoc>
    <title>Ektu</title>
    <parser>
        <markers>
            <item>@todo</item>
            <item>@fixme</item>
        </markers>
        <target>docs</target>
        <extensions>
            <extension>php</extension>
            <extension>inc</extension>
        </extensions>
    </parser>
    <transformer>
      <target>docs</target>
    </transformer>
    <files>
      <directory>src</directory>
    </files>
</phpdoc>


text: default['xdebug']['directives'] = {}


text:
/**
 * @fileoverview DOM utility methods.
 *
 * @see https://google.github.io/styleguide/javascriptguide.xml
 * @see https://developers.google.com/closure/compiler/docs/js-for-compiler
 * @module glize/dom
 */

import * as cookies from './cookies.js';
import * as template from './template.js';

export { cookies, template };

/**
 * Gets default document charset.
 * @return {string} Returns default document charset.
 * @method
 */
export const getCharset = () => {
 const doc = getDocument();
 const charset = doc && (doc.charset || doc.characterSet);
 return (charset || 'utf-8').toLowerCase();
};

/**
 * Loads script.
 * @param {string} src The script source to load.
 * @param {number=} [timeout=1000] The maximum execution timeout in seconds.
 * @return {!Promise} Returns the result as a Promise object.
 * @method
 */
export const loadScript = (src, timeout = 1E4) => {
  return new Promise((resolve, reject) => {
    const doc = getDocument();

    if (doc) {
      const script = makeNode('SCRIPT');
      const cleanup = (fn) => {
        timer && clearTimeout(timer);
        script.onload = script.onerror = null;
        deleteNode(script);
        fn();
      };

      script.onload = () => cleanup(resolve);
      script.onerror = () => cleanup(reject);
      script.async = true;
      appendNode(doc.body, script).src = src;

      const timer = setTimeout(() => cleanup(reject), timeout);
    } else {
      reject();
    }
  });
};

/**
 * Gets root context object, Window for browsers
 *   and global obkect for Node.
 * @return {!Window|!Object} Returns root context object.
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window
 * @see https://nodejs.org/api/globals.html#globals_global
 * @method
 */
export const getRootContext = () => {
  const context =
    ('object' === typeof self && self.self === self && self) ||
    ('object' === typeof global && global.global === global && global);
  return /** @type {!Window|!Object} */ (context);
};

/**
 * Gets HTML document object.
 * @return {?HTMLDocument} Returns HTML document object.
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Document
 * @method
 */
export const getDocument = () => {
  const ctx = getRootContext();
  const doc = ctx.document;

  return /** @type {?HTMLDocument} */ (doc);
};

/**
 * Removes the object from the document hierarchy.
 * @param {?Node} element The element to remove.
 * @see https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
 * @see https://msdn.microsoft.com/en-us/library/ms536708%28v=vs.85%29.aspx
 * @method
 */
 export const deleteNode = (element) => {
  element && element.parentNode && element.parentNode.removeChild(element);
};

/**
 * Alias of W3C element.appendChild.
 * Used to reduce size after code compilation.
 * @param {?Node|?Element} parent The parent element.
 * @param {?Node|?Element} child The child element.
 * @return {!Node} Returns a reference to the child that
 *     is appended to the parent.
 * @method
 */
 export const appendNode = (parent, child) => parent.appendChild(child);

/**
 * Alias of W3C document.createElement.
 * Used to reduce size after code compilation.
 * @param {string} tagName Tag name.
 * @return {?Element} Returns created element.
 * @method
 */
export const makeNode = (tagName) => getDocument().createElement(tagName);

/**
 * Alias of W3C document.getElementById.
 * Used to reduce size after code compilation.
 * @param {string} id A case-sensitive string representing the unique ID of the
 *     element being sought.
 * @return {?Element} Returns reference to an Element object, or null if an
 *     element with the specified ID is not in the document.
 * @method
 */
export const getElement = (id) => getDocument().getElementById(id);

/**
 * Alias of W3C element.getElementsByTagName.
 * Used to reduce size after code compilation.
 * @param {!Element|!Node} element Element to search tags.
 * @param {string} tagName Tag name.
 * @return {?NodeList} Returns list of found elements in the
 *     order they appear in the tree.
 * @method
 */
export const getElementsByTag = (element, tagName) => {
  return element && element.getElementsByTagName(tagName);
};

/**
 * Alias of W3C element.getElementsByClassName.
 * Used to reduce size after code compilation.
 * @param {!Element|!Node} element Element to start searching.
 * @param {string} className Class name to match.
 * @return {?NodeList} Array of found elements.
 * @method
 */
export const getElementsByClass = (element, className) => {
  return element && element.getElementsByClassName(className);
};

/**
 * Alias of W3C element.querySelectorAll.
 * Used to reduce size after code compilation.
 * @param {!Element|!DocumentFragment} element Element to start searching.
 * @param {string} selectors One or more CSS selectors separated by commas.
 * @return {?NodeList} Returns a list of the elements within the document that
 *     match the specified group of selectors.
 * @see https://www.w3.org/TR/selectors-api/#queryselectorall
 * @method
 */
export const getElementsBySelectors = (element, selectors) => {
  return element && element.querySelectorAll(selectors);
};

/**
 * Alias of W3C element.querySelector.
 * Used to reduce size after code compilation.
 * @param {!Element|!DocumentFragment} element Element to start searching.
 * @param {string} selectors One or more CSS selectors separated by commas.
 * @return {?Element} Returns the first element that is a descendant of the
 *     element on which it is invoked that matches the specified group of
 *     selectors.
 * @see https://www.w3.org/TR/selectors-api/#queryselector
 * @method
 */
export const getElementBySelectors = (element, selectors) => {
  return element && element.querySelector(selectors);
};

/**
 * Alias of W3C element.addEventListener.
 * Used to reduce size after code compilation.
 * @param {!Element|!Node|!Window} element Element to which attach event.
 * @param {string} type Type of event.
 * @param {function(!Event, ...)} listener Event listener.
 * @method
 */
export const addEvent = (element, type, listener) => {
  element && element.addEventListener(type, listener, false);
};


text:
package rx.internal.operators;

import rx.Observable.Operator;
import rx.Subscriber;
import rx.functions.Func1;
import rx.functions.Func2;

/**
 * Skips any emitted source items as long as the specified condition holds true. Emits all further source items
 * as soon as the condition becomes false.
 */
public final class OperatorSkipWhile<T> implements Operator<T, T> {
    private final Func2<? super T, Integer, Boolean> predicate;

    public OperatorSkipWhile(Func2<? super T, Integer, Boolean> predicate) {
        this.predicate = predicate;
    }
    @Override
    public Subscriber<? super T> call(final Subscriber<? super T> child) {
        return new Subscriber<T>(child) {
            boolean skipping = true;
            int index;
            @Override
            public void onNext(T t) {
                if (!skipping) {
                    child.onNext(t);
                } else {
                    if (!predicate.call(t, index++)) {
                        skipping = false;
                        child.onNext(t);
                    } else {
                        request(1);
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                child.onError(e);
            }

            @Override
            public void onCompleted() {
                child.onCompleted();
            }
        };
    }
    /**
     * Convert to Func2 type predicate.
     * @param <T> t
     * @param predicate predicate
     * @return something
     */
    public static <T> Func2<T, Integer, Boolean> toPredicate2(final Func1<? super T, Boolean> predicate) {
        return new Func2<T, Integer, Boolean>() {

            @Override
            public Boolean call(T t1, Integer t2) {
                return predicate.call(t1);
            }
        };
    }
}


text:
package com.example.yz.postassistant;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class addMessageModelActivity extends AppCompatActivity {

    private EditText newMessageModel;
    private Button next;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_messagemodel);

        newMessageModel = (EditText)findViewById(R.id.new_message_model);
        next = (Button)findViewById(R.id.next);

        next.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                String mm = newMessageModel.getText().toString();
                Intent intent = new Intent();
                intent.putExtra("messageModel",mm);
                setResult(1,intent);
                finish();
            }
        });
    }
}


text:
using System;

namespace PassedOrFailed
{
    class Program
    {
        static void Main()
        {
            double grade = double.Parse(Console.ReadLine());

            Console.WriteLine(GetScore(grade));
        }

        private static string GetScore(double grade)
        {
            if (grade >= 3.00)
            {
                return "Passed!";
            }
            else
            {
                return "Failed!";
            }
        }
    }
}


text:
package expo.modules.notifications.notifications.channels.managers;

import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import expo.modules.core.arguments.MapArguments;
import expo.modules.core.arguments.ReadableArguments;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationManagerCompat;
import expo.modules.notifications.notifications.SoundResolver;
import expo.modules.notifications.notifications.channels.InvalidVibrationPatternException;
import expo.modules.notifications.notifications.enums.AudioContentType;
import expo.modules.notifications.notifications.enums.AudioUsage;
import expo.modules.notifications.notifications.enums.NotificationVisibility;

import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.AUDIO_ATTRIBUTES_CONTENT_TYPE_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.AUDIO_ATTRIBUTES_FLAGS_ENFORCE_AUDIBILITY_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.AUDIO_ATTRIBUTES_FLAGS_HW_AV_SYNC_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.AUDIO_ATTRIBUTES_FLAGS_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.AUDIO_ATTRIBUTES_USAGE_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.BYPASS_DND_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.DESCRIPTION_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.ENABLE_LIGHTS_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.ENABLE_VIBRATE_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.GROUP_ID_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.LIGHT_COLOR_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.LOCKSCREEN_VISIBILITY_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.SHOW_BADGE_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.SOUND_AUDIO_ATTRIBUTES_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.SOUND_KEY;
import static expo.modules.notifications.notifications.channels.serializers.NotificationsChannelSerializer.VIBRATION_PATTERN_KEY;

public class AndroidXNotificationsChannelManager implements NotificationsChannelManager {
  private final NotificationManagerCompat mNotificationManager;
  private NotificationsChannelGroupManager mNotificationsChannelGroupManager;
  private final SoundResolver mSoundResolver;

  public AndroidXNotificationsChannelManager(Context context, NotificationsChannelGroupManager groupManager) {
    mNotificationManager = NotificationManagerCompat.from(context);
    mSoundResolver = new SoundResolver(context);
    mNotificationsChannelGroupManager = groupManager;
  }

  @Nullable
  @Override
  @RequiresApi(api = Build.VERSION_CODES.O)
  public NotificationChannel getNotificationChannel(@NonNull String channelId) {
    return mNotificationManager.getNotificationChannel(channelId);
  }

  @NonNull
  @Override
  @RequiresApi(api = Build.VERSION_CODES.O)
  public List<NotificationChannel> getNotificationChannels() {
    return mNotificationManager.getNotificationChannels();
  }

  @Override
  @RequiresApi(api = Build.VERSION_CODES.O)
  public void deleteNotificationChannel(@NonNull String channelId) {
    mNotificationManager.deleteNotificationChannel(channelId);
  }

  @Override
  @RequiresApi(api = Build.VERSION_CODES.O)
  public NotificationChannel createNotificationChannel(@NonNull String channelId, CharSequence name, int importance, ReadableArguments channelOptions) {
    NotificationChannel channel = new NotificationChannel(channelId, name, importance);
    configureChannelWithOptions(channel, channelOptions);
    mNotificationManager.createNotificationChannel(channel);
    return channel;
  }

  // Processing options
  @RequiresApi(api = Build.VERSION_CODES.O)
  protected void configureChannelWithOptions(Object maybeChannel, ReadableArguments args) {
    // We cannot use NotificationChannel in the signature of the method
    // since it's a class available only on newer OSes and the adapter iterates
    // through all the methods and triggers the NoClassDefFoundError.
    if (!(maybeChannel instanceof NotificationChannel)) {
      return;
    }
    NotificationChannel channel = (NotificationChannel) maybeChannel;
    if (args.containsKey(BYPASS_DND_KEY)) {
      channel.setBypassDnd(args.getBoolean(BYPASS_DND_KEY));
    }
    if (args.containsKey(DESCRIPTION_KEY)) {
      channel.setDescription(args.getString(DESCRIPTION_KEY));
    }
    if (args.containsKey(LIGHT_COLOR_KEY)) {
      channel.setLightColor(Color.parseColor(args.getString(LIGHT_COLOR_KEY)));
    }
    if (args.containsKey(GROUP_ID_KEY)) {
      String groupId = args.getString(GROUP_ID_KEY);
      NotificationChannelGroup group = mNotificationsChannelGroupManager.getNotificationChannelGroup(groupId);
      if (group == null) {
        group = mNotificationsChannelGroupManager.createNotificationChannelGroup(groupId, groupId, new MapArguments());
      }
      channel.setGroup(group.getId());
    }
    if (args.containsKey(LOCKSCREEN_VISIBILITY_KEY)) {
      NotificationVisibility visibility = NotificationVisibility.fromEnumValue(args.getInt(LOCKSCREEN_VISIBILITY_KEY));
      if (visibility != null) {
        channel.setLockscreenVisibility(visibility.getNativeValue());
      }
    }
    if (args.containsKey(SHOW_BADGE_KEY)) {
      channel.setShowBadge(args.getBoolean(SHOW_BADGE_KEY));
    }
    if (args.containsKey(SOUND_KEY) || args.containsKey(SOUND_AUDIO_ATTRIBUTES_KEY)) {
      Uri soundUri = createSoundUriFromArguments(args);
      AudioAttributes soundAttributes = createAttributesFromArguments(args.getArguments(SOUND_AUDIO_ATTRIBUTES_KEY));
      channel.setSound(soundUri, soundAttributes);
    }
    if (args.containsKey(VIBRATION_PATTERN_KEY)) {
      channel.setVibrationPattern(createVibrationPatternFromList(args.getList(VIBRATION_PATTERN_KEY)));
    }
    if (args.containsKey(ENABLE_LIGHTS_KEY)) {
      channel.enableLights(args.getBoolean(ENABLE_LIGHTS_KEY));
    }
    if (args.containsKey(ENABLE_VIBRATE_KEY)) {
      channel.enableVibration(args.getBoolean(ENABLE_VIBRATE_KEY));
    }
  }

  @Nullable
  protected Uri createSoundUriFromArguments(ReadableArguments args) {
    // The default is... the default sound.
    if (!args.containsKey(SOUND_KEY)) {
      return Settings.System.DEFAULT_NOTIFICATION_URI;
    }
    // "null" means "no sound"
    String filename = args.getString(SOUND_KEY);
    if (filename == null) {
      return null;
    }
    // Otherwise it should be a sound filename
    return mSoundResolver.resolve(filename);
  }

  @Nullable
  protected long[] createVibrationPatternFromList(@Nullable List patternRequest) throws InvalidVibrationPatternException {
    if (patternRequest == null) {
      return null;
    }

    long[] pattern = new long[patternRequest.size()];
    for (int i = 0; i < patternRequest.size(); i++) {
      if (patternRequest.get(i) instanceof Number) {
        pattern[i] = ((Number) patternRequest.get(i)).longValue();
      } else {
        throw new InvalidVibrationPatternException(i, patternRequest.get(i));
      }
    }
    return pattern;
  }

  @Nullable
  protected AudioAttributes createAttributesFromArguments(@Nullable ReadableArguments args) {
    if (args == null) {
      return null;
    }

    AudioAttributes.Builder attributesBuilder = new AudioAttributes.Builder();
    if (args.containsKey(AUDIO_ATTRIBUTES_USAGE_KEY)) {
      attributesBuilder.setUsage(AudioUsage.fromEnumValue(args.getInt(AUDIO_ATTRIBUTES_USAGE_KEY)).getNativeValue());
    }
    if (args.containsKey(AUDIO_ATTRIBUTES_CONTENT_TYPE_KEY)) {
      attributesBuilder.setContentType(AudioContentType.fromEnumValue(args.getInt(AUDIO_ATTRIBUTES_CONTENT_TYPE_KEY)).getNativeValue());
    }
    if (args.containsKey(AUDIO_ATTRIBUTES_FLAGS_KEY)) {
      int flags = 0;
      ReadableArguments flagsArgs = args.getArguments(AUDIO_ATTRIBUTES_FLAGS_KEY);
      if (flagsArgs.getBoolean(AUDIO_ATTRIBUTES_FLAGS_ENFORCE_AUDIBILITY_KEY)) {
        flags |= AudioAttributes.FLAG_AUDIBILITY_ENFORCED;
      }
      if (flagsArgs.getBoolean(AUDIO_ATTRIBUTES_FLAGS_HW_AV_SYNC_KEY)) {
        flags |= AudioAttributes.FLAG_HW_AV_SYNC;
      }
      attributesBuilder.setFlags(flags);
    }
    return attributesBuilder.build();
  }
}


text:
<!DOCTYPE html>

  <link href="/normalize.css" rel="stylesheet">
  <link href="Jeff's_Blog.css" rel="stylesheet" type="text/css">

Jeff's Blog

About Me

Best Poems

Worst Poems

VHS umami pop-up trust fund

Marfa church-key kitsch bicycle rights, 8-bit mixtape cardigan gentrify Echo Park. Street art swag brunch, next level roof party Schlitz hella organic keffiyeh selfies. You probably haven't heard of them polaroid hashtag +1, meggings biodiesel Portland High Life cray tumblr retro.

    <button>Like</button>

Sartorial synth Echo Park, roof party

chambray you probably haven't heard of them pour-over viral selvage umami skateboard VHS post-ironic selfies. Wes Anderson gentrify fanny pack twee, bicycle rights bitters blog keffiyeh plaid flannel. Tonx irony cliche sustainable mlkshk bitters. Four loko leggings chambray Vice.

    <button>Like</button>

Forage food truck keytar master cleanse

ethical thundercats sustainable locavore quinoa Neutra. Aesthetic Cosby sweater single-origin coffee, bicycle rights organic lo-fi street art american apparel ennui four loko ethnic Brooklyn small batch. Forage YOLO polaroid

    <button>Like</button>


text:
namespace chromeos {
namespace libassistant {

class AssistantClient;

// Observer informed when the |AssistantClient| is created or destroyed.
// This is used internally in our mojom service implementation, to allow our
// different components to know when they can use the Libassistant objects.
class AssistantClientObserver : public base::CheckedObserver {
 public:
  // Called when the |AssistantClient| has been created, but not started yet.
  // The pointers are guaranteed to remain valid until after
  // OnDestroyingAssistantClient() is called.
  virtual void OnAssistantClientCreated(AssistantClient* assistant_client) {}

  // Called when Start() has been called on the |AssistantClient|.  The
  // pointers are guaranteed to remain valid until after
  // OnDestroyingAssistantClient() is called.
  virtual void OnAssistantClientStarted(AssistantClient* assistant_client) {}

  // Called when |AssistantClient| has finished its start logic and is ready
  // to handle queries.
  // The pointers are guaranteed to remain valid until after
  // OnDestroyingAssistantClient() is called.
  virtual void OnAssistantClientRunning(AssistantClient* assistant_client) {}

  // Called just before the |AssistantClient| will be destroyed. They should
  // not be used anymore after this has been called. The pointers passed in are
  // guaranteed to be the same as passed to the last call to
  // OnAssistantClientCreated() (and are just passed in again for the
  // implementer's convenience).
  virtual void OnDestroyingAssistantClient(AssistantClient* assistant_client) {}

  // Called when the |AssistantClient| has been destroyed.
  virtual void OnAssistantClientDestroyed() {}

 protected:
  ~AssistantClientObserver() override = default;
};

}  // namespace libassistant
}  // namespace chromeos

#endif  // CHROMEOS_SERVICES_LIBASSISTANT_GRPC_ASSISTANT_CLIENT_OBSERVER_H_


text:
package com.thoughtworks.go.config.materials.perforce;

import java.io.Serializable;

import com.thoughtworks.go.config.Validatable;
import com.thoughtworks.go.config.ValidationContext;
import com.thoughtworks.go.domain.ConfigErrors;

import static com.thoughtworks.go.util.ExceptionUtils.bombIfNull;

public class P4MaterialView implements Serializable, Validatable {
    private String value;
    private static final String CLIENT_RENAME_REGEX = "//(.+?)\\s+(\"?)//(.+?)/(.+)";
    private static final String SPACE_BEFORE_DEPOT_REGEX = "\\s*(\"?[+\\-]?//.+?//)";
    private ConfigErrors configErrors = new ConfigErrors();

    public P4MaterialView() { }

    public P4MaterialView(String view) {
        bombIfNull(view, "null view");
        this.value = view;
    }

    public String viewUsing(String clientName) {
        String fromClientName = value.replaceAll(CLIENT_RENAME_REGEX, "//$1 $2//" + clientName + "/$4");
        return fromClientName.replaceAll(SPACE_BEFORE_DEPOT_REGEX, "\n\t$1");
    }

    public String getValue() {
        return value;
    }

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        P4MaterialView view = (P4MaterialView) o;

        if (value != null ? !value.equals(view.value) : view.value != null) {
            return false;
        }

        return true;
    }

    public int hashCode() {
        return (value != null ? value.hashCode() : 0);
    }

    public void validate(ValidationContext validationContext) {
    }

    public ConfigErrors errors() {
        return configErrors;
    }

    public void addError(String fieldName, String message) {
        configErrors.add(fieldName, message);
    }
}


text:
package k12.revere.frc.s2014.util;

import k12.revere.frc.s2014.Robot;

/**
 *
 * @author Vince
 */
public class Ticker {

    private final int targetTicksPerSecond;
    private final int tickLengthMillis;
    private final float tickLengthSeconds;

    private int globalTickCount;
    private int modeTickCount;
    private long lastTickMillis;

    private int cantKeepUpTicks;

    public Ticker(int targetTicksPerSecond) {
        this.targetTicksPerSecond = targetTicksPerSecond;
        tickLengthSeconds = 1F / (float) targetTicksPerSecond;
        tickLengthMillis = 1000 / targetTicksPerSecond;

        if (targetTicksPerSecond <= 0) {
            throw new IllegalArgumentException("Target ticks per second cannot be less than 1.");
        }
        if (targetTicksPerSecond > 1000) {
            throw new IllegalArgumentException("Target ticks per second cannot exceed 1000.");
        }
        if (tickLengthMillis == 0) {
            throw new IllegalStateException("tickLengthMillis cannot be equal to zero!");
        }
        cantKeepUpTicks = 0;
        modeTickCount = 0;
        globalTickCount = 0;
        lastTickMillis = System.currentTimeMillis();
    }

    public void waitAndTick() {
        long currTime = System.currentTimeMillis();
        long diff = currTime - lastTickMillis;
        if (diff < 0) {
            throw new IllegalStateException("TIME SHOULDN'T GO BACKWARDS.");
        }
        diff = tickLengthMillis - diff;
        if (diff > 0) {
            cantKeepUpTicks = 0;
            try {
                Thread.sleep(diff);
            } catch (InterruptedException e) {
                //  Don't care
            }
        } else {
            if(cantKeepUpTicks % secondsToTicks(1F) == 0) {
                Robot.logger.severe("Can't keep up! Behind by " + -diff + " ms");
            }
            cantKeepUpTicks++;
        }
        globalTickCount++;
        modeTickCount++;
        lastTickMillis = System.currentTimeMillis();
    }

    public void resetModeTickCount() {
        modeTickCount = 0;
    }

    public int getModeTickCount() {
        return modeTickCount;
    }

    public int getGlobalTickCount() {
        return globalTickCount;
    }

    public int getTargetTicksPerSecond() {
        return targetTicksPerSecond;
    }

    public int getTickLengthMillis() {
        return tickLengthMillis;
    }

    public float getTickLengthSeconds() {
        return tickLengthSeconds;
    }

    public int secondsToTicks(float sec) {
        return (int)(sec * targetTicksPerSecond);
    }

    public float ticksToSeconds(int ticks) {
        return tickLengthSeconds * ticks;
    }

    public int ticksToMillis(int ticks) {
        return tickLengthMillis * ticks;
    }

    public boolean hasTimeElapsedSinceTick(int tick, int ticksElapse) {
        return globalTickCount - tick >= ticksElapse;
    }

    public boolean hasModeTimeElapsed(int ticksElapse) {
        return modeTickCount >= ticksElapse;
    }

    public boolean hasModeTimeElapsedSinceTick(int tick, int ticksElapse) {
        return modeTickCount - tick >= ticksElapse;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.core.preference;

import java.io.Serializable;
import java.util.Objects;

/**
 *
 * @author Gonza
 */
public class DifferentialPricing implements Serializable{

    private Integer id;

    public DifferentialPricing() {
    }

    public DifferentialPricing(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 71 * hash + Objects.hashCode(this.id);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final DifferentialPricing other = (DifferentialPricing) obj;
        if (!Objects.equals(this.id, other.id)) {
            return false;
        }
        return true;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Manatee.Trello.Internal;
using Manatee.Trello.Internal.DataAccess;
using Manatee.Trello.Internal.Synchronization;
using Manatee.Trello.Internal.Validation;
using Manatee.Trello.Json;

namespace Manatee.Trello
{
	/// <summary>
	/// Represents the permission level a member has on an organization.
	/// </summary>
	public class OrganizationMembership : IOrganizationMembership, IMergeJson<IJsonOrganizationMembership>, IBatchRefresh, IHandleSynchronization
	{
		private readonly Field<Member> _member;
		private readonly Field<OrganizationMembershipType?> _memberType;
		private readonly Field<bool?> _isUnconfirmed;
		private readonly OrganizationMembershipContext _context;
		private DateTime? _creation;

		/// <summary>
		/// Gets the creation date of the membership.
		/// </summary>
		public DateTime CreationDate
		{
			get
			{
				if (_creation == null)
					_creation = Id.ExtractCreationDate();
				return _creation.Value;
			}
		}
		/// <summary>
		/// Gets the membership definition's ID.
		/// </summary>
		public string Id { get; private set; }
		/// <summary>
		/// Gets whether the member has accepted the invitation to join Trello.
		/// </summary>
		public bool? IsUnconfirmed => _isUnconfirmed.Value;
		/// <summary>
		/// Gets the member.
		/// </summary>
		public IMember Member => _member.Value;
		/// <summary>
		/// Gets the membership's permission level.
		/// </summary>
		public OrganizationMembershipType? MemberType
		{
			get { return _memberType.Value; }
			set { _memberType.Value = value; }
		}

		internal IJsonOrganizationMembership Json
		{
			get { return _context.Data; }
			set { _context.Merge(value); }
		}
		TrelloAuthorization IBatchRefresh.Auth => _context.Auth;

		/// <summary>
		/// Raised when data on the membership is updated.
		/// </summary>
		public event Action<IOrganizationMembership, IEnumerable<string>> Updated;

		internal OrganizationMembership(IJsonOrganizationMembership json, string ownerId, TrelloAuthorization auth)
		{
			Id = json.Id;
			_context = new OrganizationMembershipContext(Id, ownerId, auth);
			_context.Synchronized.Add(this);

			_member = new Field<Member>(_context, nameof(Member));
			_memberType = new Field<OrganizationMembershipType?>(_context, nameof(MemberType));
			_memberType.AddRule(NullableHasValueRule<OrganizationMembershipType>.Instance);
			_memberType.AddRule(EnumerationRule<OrganizationMembershipType?>.Instance);
			_isUnconfirmed = new Field<bool?>(_context, nameof(IsUnconfirmed));

			if (auth != TrelloAuthorization.Null)
				TrelloConfiguration.Cache.Add(this);

			_context.Merge(json);
		}

		/// <summary>
		/// Refreshes the organization membership data.
		/// </summary>
		/// <param name="force">Indicates that the refresh should ignore the value in <see cref="TrelloConfiguration.RefreshThrottle"/> and make the call to the API.</param>
		/// <param name="ct">(Optional) A cancellation token for async processing.</param>
		public Task Refresh(bool force = false, CancellationToken ct = default)
		{
			return _context.Synchronize(force, ct);
		}

		/// <summary>Returns a string that represents the current object.</summary>
		/// <returns>A string that represents the current object.</returns>
		public override string ToString()
		{
			return $"{Member} ({MemberType})";
		}

		void IHandleSynchronization.HandleSynchronized(IEnumerable<string> properties)
		{
			Id = _context.Data.Id;
			var handler = Updated;
			handler?.Invoke(this, properties);
		}

		void IMergeJson<IJsonOrganizationMembership>.Merge(IJsonOrganizationMembership json, bool overwrite)
		{
			_context.Merge(json, overwrite);
		}

		Endpoint IBatchRefresh.GetRefreshEndpoint()
		{
			return _context.GetRefreshEndpoint();
		}

		void IBatchRefresh.Apply(string content)
		{
			var json = TrelloConfiguration.Deserializer.Deserialize<IJsonOrganizationMembership>(content);
			_context.Merge(json);
		}
	}
}


text:
module PuppetX
  module Cisco
    # PuppetX::Cisco::Utils: - Common helper methods shared by any Type/Provider
    # rubocop:disable Metrics/ClassLength
    class Utils
      require 'ipaddr'

      TACACS_SERVER_ENC_NONE = 0
      TACACS_SERVER_ENC_CISCO_TYPE_7 = 7
      TACACS_SERVER_ENC_UNKNOWN = 8

      # Helper utility method for ip/prefix format networks.
      # For ip/prefix format '1.1.1.1/24' or '2000:123:38::34/64',
      # we need to mask the address using the prefix length so that they
      # are converted to '1.1.1.0/24' or '2000:123:38::/64'
      def self.process_network_mask(network)
        mask = network.split('/')[1]
        address = IPAddr.new(network).to_s
        network = address + '/' + mask unless mask.nil?
        network
      end

      # Convert boolean symbols to strings
      def self.bool_sym_to_s(val)
        return val unless val == :true || val == :false
        (val == :true)
      end

      # Special handling for boolean properties.
      # This helper method returns true if the property
      # flush contains a TrueClass or FalseClass value.
      def self.flush_boolean?(prop)
        prop.is_a?(TrueClass) || prop.is_a?(FalseClass)
      end

      # normalize_range_array
      #
      # Given a list of ranges, merge any overlapping ranges and normalize the
      # them as a string that can be used directly on the switch.
      #
      # Note: The ranges are converted to ruby ranges for easy merging,
      # then converted back to a cli-syntax ranges.
      #
      # Accepts an array or string:
      #   ["2-5", "9", "4-6"]  -or-  '2-5, 9, 4-6'  -or-  ["2-5, 9, 4-6"]
      # Returns a merged and ordered range:
      #   ["2-6", "9"]
      #
      def self.normalize_range_array(range, type=:array)
        return range if range.nil? || range.empty?

        # This step is puppet only
        return range if range[0] == :default

        # Handle string within an array: ["2-5, 9, 4-6"] to '2-5, 9, 4-6'
        range = range.shift if range.is_a?(Array) && range.length == 1

        # Handle string only: '2-5, 9, 4-6' to ["2-5", "9", "4-6"]
        range = range.split(',') if range.is_a?(String)

        # Convert to ruby-syntax ranges
        range = dash_range_to_ruby_range(range)

        # Sort & Merge
        merged = merge_range(range)

        # Convert back to cli dash-syntax
        ruby_range_to_dash_range(merged, type)
      end

      def self.normalize_range_string(range)
        range = range.to_s
        return normalize_range_array(range, :string) if range[/[-,]/]
        range
      end

      # Convert a cli-dash-syntax range to ruby-range. This is useful for
      # preparing inputs to merge_range().
      #
      # Inputs an array or string of dash-syntax ranges -> returns an array
      # of ruby ranges.
      #
      # Accepts an array or string: ["2-5", "9", "4-6"] or '2-5, 9, 4-6'
      # Returns an array of ranges: [2..5, 9..9, 4..6]
      #
      def self.dash_range_to_ruby_range(range)
        range = range.split(',') if range.is_a?(String)
        # [["45", "7-8"], ["46", "9,10"]]
        range.map! do |rng|
          if rng[/-/]
            # '2-5' -> 2..5
            rng.split('-').inject { |a, e| a.to_i..e.to_i }
          else
            # '9' -> 9..9
            rng.to_i..rng.to_i
          end
        end
        range
      end

      # Convert a ruby-range to cli-dash-syntax.
      #
      # Inputs an array of ruby ranges -> returns an array or string of
      # dash-syntax ranges.
      #
      # when (:array)  [2..6, 9..9]  ->  ['2-6', '9']
      #
      # when (:string)  [2..6, 9..9]  ->  '2-6, 9'
      #
      def self.ruby_range_to_dash_range(range, type=:array)
        range.map! do |r|
          if r.first == r.last
            # 9..9 -> '9'
            r.first.to_s
          else
            # 2..6 -> '2-6'
            r.first.to_s + '-' + r.last.to_s
          end
        end
        return range.join(',') if type == :string
        range
      end

      # Merge overlapping ranges.
      #
      # Inputs an array of ruby ranges:         [2..5, 9..9, 4..6]
      # Returns an array of merged ruby ranges: [2..6, 9..9]
      #
      def self.merge_range(range)
        # sort to lowest range 'first' values:
        #    [2..5, 9..9, 4..6]  ->  [2..5, 4..6, 9..9]
        range = range.sort_by(&:first)

        *merged = range.shift
        range.each do |r|
          lastr = merged[-1]
          if lastr.last >= r.first - 1
            merged[-1] = lastr.first..[r.last, lastr.last].max
          else
            merged.push(r)
          end
        end
        merged
      end # merge_range

      # TBD: Investigate replacing fail_array_overlap() and range_summarize()
      # with above methods.

      # Helper utility for checking if arrays are overlapping in a
      # give list.
      # For ex: if the list has '2-10,32,42,44-89' and '11-33'
      # then this will fail as they overlap
      def self.fail_array_overlap(list)
        array = []
        list.each do |range, _val|
          larray = range.split(',')
          larray.each do |elem|
            if elem.include?('-')
              elema = elem.split('-').map { |d| Integer(d) }
              ele = elema[0]..elema[1]
              if (array & ele.to_a).empty?
                array << ele.to_a
                array = array.flatten
              else
                fail 'overlapping arrays not allowed'
              end
            else
              elema = []
              elema << elem.to_i
              if (array & elema).empty?
                array << elema
                array = array.flatten
              else
                fail 'overlapping arrays not allowed'
              end
            end
          end
        end
      end

      # Helper utility method for range summarization of VLAN and BD ranges
      # Input is a range string. For example: '10-20, 30, 14, 100-105, 21'
      # Output should be: '10-21,30,100-105'
      def self.range_summarize(range_str, sort=true)
        ranges = []
        range_str.split(/,/).each do |elem|
          if elem =~ /\d+\s*\-\s*\d+/
            range_limits = elem.split(/\-/).map { |d| Integer(d) }
            ranges << (range_limits[0]..range_limits[1])
          else
            ranges << Integer(elem)
          end
        end
        # nrange array below will expand the ranges and get a single list
        nrange = []
        ranges.each do |item|
          # OR operations below will get rid of duplicates
          if item.class == Range
            nrange |= item.to_a
          else
            nrange |= [item]
          end
        end
        nrange.sort! if sort
        ranges = []
        left = nrange.first
        right = nil
        nrange.each do |obj|
          if right && obj != right.succ
            # obj cannot be included in the current range, end this range
            if left != right
              ranges << Range.new(left, right)
            else
              ranges << left
            end
            left = obj # start of new range
          end
          right = obj # move right to point to obj
        end
        if left != right
          ranges << Range.new(left, right)
        else
          ranges << left
        end
        ranges.join(',').gsub('..', '-')
      end

      # fretta check
      def self.check_slot_pid(inv)
        inv.each do |_x, slot|
          return true if slot['pid'][/-R/]
        end
        false
      end

      def self.product_tag
        data = Facter.value('cisco')
        case data['inventory']['chassis']['pid']
        when /N3/
          tag = check_slot_pid(data['inventory']) ? 'n3k-f' : 'n3k'
        when /N5/
          tag = 'n5k'
        when /N6/
          tag = 'n6k'
        when /N7/
          tag = 'n7k'
        when /N9/
          tag = check_slot_pid(data['inventory']) ? 'n9k-f' : 'n9k'
        else
          fail "Unrecognized product_id: #{data['inventory']['chassis']['pid']}"
        end
        tag
      end

      # Convert encryption type to symbol
      def self.enc_type_to_sym(type)
        case type
        when TACACS_SERVER_ENC_UNKNOWN
          :none
        when TACACS_SERVER_ENC_NONE
          :clear
        when TACACS_SERVER_ENC_CISCO_TYPE_7
          :encrypted
        end
      end

      # Convert encryption symbol to type
      def self.enc_sym_to_type(sym)
        case sym
        when :none
          TACACS_SERVER_ENC_UNKNOWN
        when :clear, :default
          TACACS_SERVER_ENC_NONE
        when :encrypted
          TACACS_SERVER_ENC_CISCO_TYPE_7
        end
      end

      # Convert return values to their specified ruby type
      #
      # Accepts the Resource API context and array of return values
      #
      # Returns the array of return values with individual values
      # correctly converted to their ruby type eg. Integer
      def self.enforce_simple_types(context, return_value)
        return_value.each do |individual_value_hash|
          individual_value_hash.each do |k, v|
            type_to_use = context.type.definition[:attributes][k][:type]
            if type_to_use.downcase =~ %r{^integer} || type_to_use.downcase =~ %r{^optional\[integer}
              individual_value_hash[k] = v.to_i
            end
            if type_to_use.downcase =~ %r{^string} || type_to_use.downcase =~ %r{^optional\[string}
              individual_value_hash[k] = v.to_s
            end
            next unless type_to_use.downcase =~ %r{^boolean} || type_to_use.downcase =~ %r{^optional\[boolean}
            individual_value_hash[k] = if v.to_s.casecmp('true').zero?
                                         true
                                       else
                                         false
                                       end
          end
        end
        return_value
      end
    end # class Utils
    # rubocop:enable Metrics/ClassLength

    # PuppetX::Cisco::BgpUtil - Common BGP methods used by BGP Types/Providers
    class BgpUtils
      def self.process_asnum(asnum)
        err_msg = "BGP asnum must be either a 'String' or an" \
                  " 'Integer' object"
        fail ArgumentError, err_msg unless asnum.is_a?(Integer) ||
                                           asnum.is_a?(String)
        if asnum.is_a? String
          # Match ASDOT '1.5' or ASPLAIN '55' strings
          fail ArgumentError unless /^(\d+|\d+\.\d+)$/.match(asnum)
          asnum = dot_to_big(asnum) if /\d+\.\d+/.match(asnum)
        end
        asnum.to_i
      end

      # Convert BGP ASN ASDOT+ to ASPLAIN
      def self.dot_to_big(dot_str)
        fail ArgumentError unless dot_str.is_a? String
        return dot_str unless /\d+\.\d+/.match(dot_str)
        mask = 0b1111111111111111
        high = dot_str.to_i
        low = 0
        low_match = dot_str.match(/\.(\d+)/)
        low = low_match[1].to_i if low_match
        high_bits = (mask & high) << 16
        low_bits = mask & low
        high_bits + low_bits
      end
    end
  end
end


text:
<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * GymAdmin model
 *
 * @property integer $id
 * @property string $username
 * @property string $access_token
 * @property string $access_token_expire_at
 * @property string $password_hash
 * @property string $email
 * @property integer $is_email_verified
 * @property string $phone
 * @property integer $is_phone_verified
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $password write-only password
 */
class GymAdmin extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    public $access_token_during = 2592000; // 30 * 24 * 3600s

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%gym_admin}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],

            ['is_email_verified', 'default', 'value' => 0],
            ['is_email_verified', 'in', 'range' => [0, 1]],

            ['is_phone_verified', 'default', 'value' => 0],
            ['is_phone_verified', 'in', 'range' => [0, 1]],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        if ($token) {
            return static::find()
                ->where(['access_token' => $token])
                ->andWhere(['>=', 'access_token_expire_at', time()])
                ->andWhere(['status' => self::STATUS_ACTIVE])
                ->one();
        }

        return null;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    // TODO:
    public function generateAccessToken($isNull = false)
    {
        if ($isNull) {
            $this->access_token = null;
            $this->access_token_expire_at = 0;
            return;
        }

        $s1 = time();
        $s2 = $this->username;
        $s3 = $this->phone != null ? $this->phone : '';
        $s4 = $this->email != null ? $this->email : '';
        $s5 = $this->password_hash;
        $s6 = Yii::$app->security->generateRandomString();
        $s7 = hash('sha1', $s1 . $s2 . $s3 . $s4 . $s5, false);
        $this->access_token = hash('sha256', $s6 . $s7, false);
        $this->access_token_expire_at = time() + $this->access_token_during;
    }

    public static function findByEmail($email)
    {
        return static::findOne(['email' => $email, 'status' => self::STATUS_ACTIVE]);
    }

    public static function findByPhone($phone)
    {
        return static::findOne(['phone' => $phone, 'status' => self::STATUS_ACTIVE]);
    }

    public static function findByUsernameOrEmailOrPhone($loginName)
    {
        if (empty($loginName)) {
            return null;
        }

        return static::find()
            ->where(['and', ['status' => self::STATUS_ACTIVE], [
                'or', ['username' => $loginName], [
                    'or', ['email' => $loginName], ['phone' => $loginName]]]])
            ->one();
    }

    public function getGyms()
    {
        return $this->hasMany(Gym::className(), ['gym_admin_id' => 'id'])
            ->where(['not', ['status' => Gym::STATUS_DELETED]])
            ->orderBy('id');
    }
}