text:
package org.cyclops.colossalchests;

import org.apache.logging.log4j.Level;
import org.cyclops.cyclopscore.config.ConfigurableProperty;
import org.cyclops.cyclopscore.config.ConfigurableType;
import org.cyclops.cyclopscore.config.ConfigurableTypeCategory;
import org.cyclops.cyclopscore.config.extendedconfig.DummyConfig;
import org.cyclops.cyclopscore.init.ModBase;
import org.cyclops.cyclopscore.tracking.Analytics;
import org.cyclops.cyclopscore.tracking.Versions;

/**
 * A config with general options for this mod.
 * @author rubensworks
 *
 */
public class GeneralConfig extends DummyConfig {

    /**
     * The current mod version, will be used to check if the player's config isn't out of date and
     * warn the player accordingly.
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "Config version for " + Reference.MOD_NAME +".\nDO NOT EDIT MANUALLY!", showInGui = false)
    public static String version = Reference.MOD_VERSION;

    /**
     * If the debug mode should be enabled. @see Debug
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "Set 'true' to enable development debug mode. This will result in a lower performance!", requiresMcRestart = true)
    public static boolean debug = false;

    /**
     * If the recipe loader should crash when finding invalid recipes.
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If the recipe loader should crash when finding invalid recipes.", requiresMcRestart = true)
    public static boolean crashOnInvalidRecipe = false;

    /**
     * If mod compatibility loader should crash hard if errors occur in that process.
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If mod compatibility loader should crash hard if errors occur in that process.", requiresMcRestart = true)
    public static boolean crashOnModCompatCrash = false;

    /**
     * If an anonymous mod startup analytics request may be sent to our analytics service.
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If an anonymous mod startup analytics request may be sent to our analytics service.")
    public static boolean analytics = true;

    /**
     * If the version checker should be enabled.
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If the version checker should be enabled.")
    public static boolean versionChecker = true;

    /**
     * If items should be ejected from the chests if one of the structure blocks are removed.
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "If items should be ejected from the chests if one of the structure blocks are removed.")
    public static boolean ejectItemsOnDestroy = false;

    /**
     * If the higher tier metal variants can be crafted.
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "If the higher tier metal variants can be crafted.")
    public static boolean metalVariants = true;

    /**
     * Maximum buffer byte size for adaptive inventory slots fragmentation.
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "Maximum buffer byte size for adaptive inventory slots fragmentation.")
    public static int maxPacketBufferSize = 20000;

    /**
     * If the interface input overlay should always be rendered on chests.
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "If the interface input overlay should always be rendered on chests.", isCommandable = true)
    public static boolean alwaysShowInterfaceOverlay = true;

    /**
     * Always create full creative-mode chests when formed. Should not be used in survival worlds!
     */
    @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "Always create full creative-mode chests when formed. Should not be used in survival worlds!", isCommandable = true)
    public static boolean creativeChests = false;

    /**
     * The type of this config.
     */
    public static ConfigurableType TYPE = ConfigurableType.DUMMY;

    /**
     * Create a new instance.
     */
    public GeneralConfig() {
        super(ColossalChests._instance, true, "general", null, GeneralConfig.class);
    }

    @Override
    public void onRegistered() {
        // Check version of config file
        if(!version.equals(Reference.MOD_VERSION)) {
            getMod().log(Level.WARN, "The config file of " + Reference.MOD_NAME + " is out of date and might cause problems, please remove it so it can be regenerated.");
        }

        getMod().putGenericReference(ModBase.REFKEY_CRASH_ON_INVALID_RECIPE, GeneralConfig.crashOnInvalidRecipe);
        getMod().putGenericReference(ModBase.REFKEY_DEBUGCONFIG, GeneralConfig.debug);
        getMod().putGenericReference(ModBase.REFKEY_CRASH_ON_MODCOMPAT_CRASH, GeneralConfig.crashOnModCompatCrash);

        if(analytics) {
            Analytics.registerMod(getMod(), Reference.GA_TRACKING_ID);
        }
        if(versionChecker) {
            Versions.registerMod(getMod(), ColossalChests._instance, Reference.VERSION_URL);
        }
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}


text:
module Fayde.Time {
    export var Library = TypeManager.resolveLibrary("lib://fayde.time");
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import
import datetime
import uuid

from oslo_config import cfg
from st2tests.base import DbTestCase
from st2common.util import isotime
from st2common.util import date as date_utils
from st2common.exceptions.auth import TokenNotFoundError
from st2common.persistence.auth import Token
from st2common.services import access
from st2common.exceptions.auth import TTLTooLargeException
import st2tests.config as tests_config

USERNAME = "manas"

class AccessServiceTest(DbTestCase):
    @classmethod
    def setUpClass(cls):
        super(AccessServiceTest, cls).setUpClass()
        tests_config.parse_args()

    def test_create_token(self):
        token = access.create_token(USERNAME)
        self.assertIsNotNone(token)
        self.assertIsNotNone(token.token)
        self.assertEqual(token.user, USERNAME)

    def test_create_token_fail(self):
        try:
            access.create_token(None)
            self.assertTrue(False, "Create succeeded was expected to fail.")
        except ValueError:
            self.assertTrue(True)

    def test_delete_token(self):
        token = access.create_token(USERNAME)
        access.delete_token(token.token)
        try:
            token = Token.get(token.token)
            self.assertTrue(False, "Delete failed was expected to pass.")
        except TokenNotFoundError:
            self.assertTrue(True)

    def test_delete_non_existent_token(self):
        token = uuid.uuid4().hex
        self.assertRaises(TokenNotFoundError, Token.get, token)
        access.delete_token(token)

    def test_create_token_ttl_ok(self):
        ttl = 10
        token = access.create_token(USERNAME, 10)
        self.assertIsNotNone(token)
        self.assertIsNotNone(token.token)
        self.assertEqual(token.user, USERNAME)
        expected_expiry = date_utils.get_datetime_utc_now() + datetime.timedelta(
            seconds=ttl
        )
        expected_expiry = date_utils.add_utc_tz(expected_expiry)
        self.assertLess(isotime.parse(token.expiry), expected_expiry)

    def test_create_token_ttl_capped(self):
        ttl = cfg.CONF.auth.token_ttl + 10
        expected_expiry = date_utils.get_datetime_utc_now() + datetime.timedelta(
            seconds=ttl
        )
        expected_expiry = date_utils.add_utc_tz(expected_expiry)
        token = access.create_token(USERNAME, 10)
        self.assertIsNotNone(token)
        self.assertIsNotNone(token.token)
        self.assertEqual(token.user, USERNAME)
        self.assertLess(isotime.parse(token.expiry), expected_expiry)

    def test_create_token_service_token_can_use_arbitrary_ttl(self):
        ttl = 10000 * 24 * 24

        # Service token should support arbitrary TTL
        token = access.create_token(USERNAME, ttl=ttl, service=True)
        expected_expiry = date_utils.get_datetime_utc_now() + datetime.timedelta(
            seconds=ttl
        )
        expected_expiry = date_utils.add_utc_tz(expected_expiry)

        self.assertIsNotNone(token)
        self.assertEqual(token.user, USERNAME)
        self.assertLess(isotime.parse(token.expiry), expected_expiry)

        # Non service token should throw on TTL which is too large
        self.assertRaises(
            TTLTooLargeException, access.create_token, USERNAME, ttl=ttl, service=False
        )


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = toggleLocationServices;
/**
 *
 * Switch the state (enabled/disabled) of the location service.
 *
 * <example>
    :toggleLocationServices.js
    browser.toggleLocationServices();
 * </example>
 *
 * @type mobile
 * @for android
 *
 */

function toggleLocationServices() {
    return this.requestHandler.create({
        path: '/session/:sessionId/appium/device/toggle_location_services',
        method: 'POST'
    });
}
module.exports = exports['default'];


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('cmsplugin_filer_link', '0003_auto_20160224_1453'),
    ]

    operations = [
        migrations.AlterField(
            model_name='filerlinkplugin',
            name='url',
            field=models.CharField(max_length=2000, null=True, verbose_name='url', blank=True),
        ),
    ]


text:
import os
import sys

from Bio import SeqIO

from StrongHold import Algorithm

def main(*args, **kwargs):
    fpath = os.path.join(os.getcwd(), args[-1])

    seqs = list(SeqIO.parse(fpath, 'fasta'))

    seq1 = str(seqs[0].seq)
    seq2 = str(seqs[1].seq)

    res = Algorithm.longest_common_subsequence(seq1, seq2)
    print res

if __name__ == '__main__':
    main(*sys.argv)


text:
(function() {
    var Ext = window.Ext4 || window.Ext;

    Ext.define('Rally.ui.combobox.FieldOptionsCombobox', {
        requires: [],
        extend: 'Rally.ui.combobox.FieldComboBox',
        alias: 'widget.tsfieldoptionscombobox',

        _isNotHidden: function(field) {
            //We want dropdown fields, iteration, release, state?
            var allowedFields = ['Iteration','Release'];

            if (field  && Ext.Array.contains(allowedFields, field.name)){
                return true;
            }

            if (field && field.attributeDefinition &&
                field.attributeDefinition.AttributeType === 'STRING'){
                return true;
            }
            return false;
        },
        _populateStore: function() {
            if (!this.store) {
                return;
            }
            var data = _.sortBy(
                _.map(
                    _.filter(this.model.getFields(), this._isNotHidden),
                    this._convertFieldToLabelValuePair,
                    this
                ),
                'name'
            );

            if (this.allowNoEntry){
                data.unshift({name: this.noEntryText, value: null});
            }
            this.store.loadRawData(data);
            this.setDefaultValue();
            this.onReady();
        }
    });
})();


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Proc. K. Ned. Akad. Wet. , Ser. C, Biol. Med. Sci. 90(3): 314 (1987)

#### Original name
Craterium reticulatum Nann.-Bremek. & Y. Yamam., 1987

### Remarks
null


text:
package com.poepoemyintswe.popularmovies.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;

/**
 * Created by poepoe on 11/7/15.
 */
public class Movie {

  @Expose private Integer page;
  @Expose private ArrayList<Result> results = new ArrayList<>();
  @SerializedName("total_pages") @Expose private Integer totalPages;
  @SerializedName("total_results") @Expose private Integer totalResults;

  /**
   * @return The page
   */
  public Integer getPage() {
    return page;
  }

  /**
   * @param page The page
   */
  public void setPage(Integer page) {
    this.page = page;
  }

  /**
   * @return The results
   */
  public ArrayList<Result> getResults() {
    return results;
  }

  /**
   * @param results The results
   */
  public void setResults(ArrayList<Result> results) {
    this.results = results;
  }

  /**
   * @return The totalPages
   */
  public Integer getTotalPages() {
    return totalPages;
  }

  /**
   * @param totalPages The total_pages
   */
  public void setTotalPages(Integer totalPages) {
    this.totalPages = totalPages;
  }

  /**
   * @return The totalResults
   */
  public Integer getTotalResults() {
    return totalResults;
  }

  /**
   * @param totalResults The total_results
   */
  public void setTotalResults(Integer totalResults) {
    this.totalResults = totalResults;
  }
}


text:
const crypto = require('crypto');
const async = require('async');
const nodemailer = require('nodemailer');
const dotenv = require('dotenv').config();
const User = require('../models/user');

function sendVerificationEmail(user, origin, finalCB) {
  async.waterfall([
    function (done) {
      crypto.randomBytes(20, function (err, buf) {
        const token = buf.toString('hex');
        done(err, token);
      });
    },
    function (token, done) {
      user.verifyEmailToken = token;
      // Make token expire in 24 hours
      user.verifyEmailTokenExpires = Date.now() + 3600000 * 24;

      user.save(function (err) {
        done(err, user);
      });
    },
    function (user, done) {
      const transporter = nodemailer.createTransport({
        service: 'SendGrid',
        auth: {
          user: process.env.SENDGRID_USER,
          pass: process.env.SENDGRID_PASSWORD,
        },
      });
      const mailOptions = {
        from: 'support@demo.com',
        to: user.email,
        subject: 'Verify Email',
        text: `Hey placeholdername,
          Please click the link below to verify your account:
          ${origin}/verify-email/${user.verifyEmailToken}\n
          Thanks,
          Demo Team`,
      };
      transporter.sendMail(mailOptions, function (err) {
        done(err, 'done');
      });
    },
  ], (err) => {
    if (err) {
      console.log(`Could not send welcome email to: ${user.email}`);
      console.error(err);
      if (finalCB) {
        finalCB({
          message: `Could not send welcome email to: ${user.email}`,
        });
      } else {
        if (finalCB) {
          finalCB();
        }
      }
    }
  });
}

function sendForgotPasswordEmail(user, origin, finalCB) {
  async.waterfall([
    function (done) {
      crypto.randomBytes(20, function (err, buf) {
        const token = buf.toString('hex');
        done(err, token);
      });
    },
    function (token, done) {
      user.resetPasswordToken = token;
      // Token expires in 1 hour
      user.resetPasswordTokenExpires = Date.now() + 3600000;

      user.save(function (err) {
        done(err, user);
      });
    },
    function (user, done) {
      const transporter = nodemailer.createTransport({
        service: 'SendGrid',
        auth: {
          user: process.env.SENDGRID_USER,
          pass: process.env.SENDGRID_PASSWORD,
        },
      });
      const mailOptions = {
        from: 'support@demo.com',
        to: user.email,
        subject: 'Password reset request',
        text: `You are receiving this because you (or someone else) have requested the reset of the password for your account.
          Please click on the following link, or paste this into your browser to complete the process:
          ${origin}/reset/${user.resetPasswordToken}
          If you did not request this, please ignore this email and your password will remain unchanged.`,
      };
      transporter.sendMail(mailOptions, (err) => {
        done(err, 'done');
      });
    },
  ], (err) => {
    if (err) {
      console.log(`Could not send welcome email to: ${user.email}`);
      console.error(err);
      if (finalCB) {
        finalCB({
          message: `Could not send welcome email to: ${user.email}`,
        });
      } else {
        if (finalCB) {
          finalCB();
        }
      }
    }
  });
}

function sendPasswordHasBeenChangedEmail(user) {
  const transporter = nodemailer.createTransport({
    service: 'SendGrid',
    auth: {
      user: process.env.SENDGRID_USER,
      pass: process.env.SENDGRID_PASSWORD,
    },
  });
  const mailOptions = {
    to: user.email,
    from: 'support@demo.com',
    subject: 'Your password has been changed',
    text: `Hello,\n
    This is a confirmation that the password for your account ${user.email} has just been changed.\n`,
  };
  transporter.sendMail(mailOptions);
}

module.exports = {
  sendVerificationEmail,
  sendForgotPasswordEmail,
  sendPasswordHasBeenChangedEmail,
};


text:
// Attributes2Impl.java - extended AttributesImpl
// http://www.saxproject.org
// Public Domain: no warranty.
// $Id: Attributes2Impl.java,v 1.5 2004/03/08 13:01:01 dmegginson Exp $

using Lucene.Net.Support;
using Sax.Helpers;
using System;

namespace Sax.Ext
{
    ///
    /// SAX2 extension helper for additional Attributes information,
    /// implementing the <see cref="Attributes2"/> interface.
    ///
    /// <remarks>
    /// This module, both source code and documentation, is in the
    /// Public Domain, and comes with NO WARRANTY.
    /// <para/>
    /// This is not part of core-only SAX2 distributions.
    /// <para/>
    /// The specified flag for each attribute will always
    /// be true, unless it has been set to false in the copy constructor
    /// or using <see cref="SetSpecified(int, bool)"/>.
    /// Similarly, the declared flag for each attribute will
    /// always be false, except for defaulted attributes (specified
    /// is false), non-CDATA attributes, or when it is set to true using
    /// <see cref="SetDeclared(int, bool)"/>.
    /// If you change an attribute's type by hand, you may need to modify
    /// its declared flag to match.
    /// </remarks>
    /// <since>SAX 2.0 (extensions 1.1 alpha)</since>
    /// <author>David Brownell</author>
    /// <version>TBS</version>
    public class Attributes2 : Attributes, IAttributes2
    {
        private bool[] declared;
        private bool[] specified;

        ///
        /// Construct a new, empty <see cref="Attributes2"/> object.
        ///
        public Attributes2() { }

        ///
        /// Copy an existing Attributes or Attributes2 object.
        /// If the object implements Attributes2, values of the
        /// specified and declared flags for each
        /// attribute are copied.
        /// Otherwise the flag values are defaulted to assume no DTD was used,
        /// unless there is evidence to the contrary (such as attributes with
        /// type other than CDATA, which must have been declared).
        ///
This constructor is especially useful inside a
        /// <see cref="IContentHandler.StartElement(string, string, string, IAttributes)"/> event.

        ///
        /// <param name="atts">The existing <see cref="IAttributes"/> object.</param>
        public Attributes2(IAttributes atts)
            : base(atts)
        {
        }

        ////////////////////////////////////////////////////////////////////
        // Implementation of Attributes2
        ////////////////////////////////////////////////////////////////////

        ///
        /// Returns the current value of the attribute's "declared" flag.
        ///
        // javadoc mostly from interface
        public bool IsDeclared(int index)
        {
            if (index < 0 || index >= Length)
                throw new IndexOutOfRangeException(
                "No attribute at index: " + index);
            return declared[index];
        }

        ///
        /// Returns the current value of the attribute's "declared" flag.
        ///
        // javadoc mostly from interface
        public bool IsDeclared(string uri, string localName)
        {
            int index = GetIndex(uri, localName);

            if (index < 0)
                throw new ArgumentException(
                "No such attribute: local=" + localName
                + ", namespace=" + uri);
            return declared[index];
        }

        ///
        /// Returns the current value of the attribute's "declared" flag.
        ///
        // javadoc mostly from interface
        public bool IsDeclared(string qName)
        {
            int index = GetIndex(qName);

            if (index < 0)
                throw new ArgumentException(
                "No such attribute: " + qName);
            return declared[index];
        }

        ///
        /// Returns the current value of an attribute's "specified" flag.
        ///
        /// <param name="index">The attribute index (zero-based).</param>
        /// <returns>current flag value</returns>
        /// <exception cref="IndexOutOfRangeException">When the supplied index does not identify an attribute.</exception>
        public bool IsSpecified(int index)
        {
            if (index < 0 || index >= Length)
                throw new IndexOutOfRangeException(
                "No attribute at index: " + index);
            return specified[index];
        }

        ///
        /// Returns the current value of an attribute's "specified" flag.
        ///
        /// <param name="uri">The Namespace URI, or the empty string if the name has no Namespace URI.</param>
        /// <param name="localName">The attribute's local name.</param>
        /// <returns>current flag value</returns>
        /// <exception cref="ArgumentException">When the supplied names do not identify an attribute.</exception>
        public bool IsSpecified(string uri, string localName)
        {
            int index = GetIndex(uri, localName);

            if (index < 0)
                throw new ArgumentException(
                "No such attribute: local=" + localName
                + ", namespace=" + uri);
            return specified[index];
        }

        ///
        /// Returns the current value of an attribute's "specified" flag.
        ///
        /// <param name="qName">The XML qualified (prefixed) name.</param>
        /// <returns>current flag value</returns>
        /// <exception cref="ArgumentException">When the supplied name does not identify an attribute.</exception>
        public bool IsSpecified(string qName)
        {
            int index = GetIndex(qName);

            if (index < 0)
                throw new ArgumentException(
                "No such attribute: " + qName);
            return specified[index];
        }

        ////////////////////////////////////////////////////////////////////
        // Manipulators
        ////////////////////////////////////////////////////////////////////

        ///
        /// Copy an entire Attributes object.  The "specified" flags are
        /// assigned as true, and "declared" flags as false (except when
        /// an attribute's type is not CDATA),
        /// unless the object is an Attributes2 object.
        /// In that case those flag values are all copied.
        ///
        /// <seealso cref="Attributes.SetAttributes(IAttributes)"/>
        public override void SetAttributes(IAttributes atts)
        {
            int length = atts.Length;

            base.SetAttributes(atts);
            declared = new bool[length];
            specified = new bool[length];

            if (atts is Attributes2 a2)
            {
                for (int i = 0; i < length; i++)
                {
                    declared[i] = a2.IsDeclared(i);
                    specified[i] = a2.IsSpecified(i);
                }
            }
            else
            {
                for (int i = 0; i < length; i++)
                {
                    declared[i] = !"CDATA".Equals(atts.GetType(i), StringComparison.Ordinal);
                    specified[i] = true;
                }
            }
        }

        ///
        /// Add an attribute to the end of the list, setting its
        /// "specified" flag to true.  To set that flag's value
        /// to false, use <see cref="SetSpecified(int, bool)"/>.
        /// <para/>
        /// Unless the attribute type is CDATA, this attribute
        /// is marked as being declared in the DTD.  To set that flag's value
        /// to true for CDATA attributes, use <see cref="SetDeclared(int, bool)"/>.
        ///
        /// <seealso cref="Attributes.AddAttribute(string, string, string, string, string)"/>
        public override void AddAttribute(string uri, string localName, string qName,
                      string type, string value)
        {
            base.AddAttribute(uri, localName, qName, type, value);

            int length = Length;

            if (length < specified.Length)
            {
                bool[] newFlags;

                newFlags = new bool[length];
                Arrays.Copy(declared, 0, newFlags, 0, declared.Length);
                declared = newFlags;

                newFlags = new bool[length];
                Arrays.Copy(specified, 0, newFlags, 0, specified.Length);
                specified = newFlags;
            }

            specified[length - 1] = true;
            declared[length - 1] = !"CDATA".Equals(type, StringComparison.Ordinal);
        }

        // javadoc entirely from superclass
        public override void RemoveAttribute(int index)
        {
            int origMax = Length - 1;

            base.RemoveAttribute(index);
            if (index != origMax)
            {
                Arrays.Copy(declared, index + 1, declared, index,
                    origMax - index);
                Arrays.Copy(specified, index + 1, specified, index,
                    origMax - index);
            }
        }

        ///
        /// Assign a value to the "declared" flag of a specific attribute.
        /// This is normally needed only for attributes of type CDATA,
        /// including attributes whose type is changed to or from CDATA.
        ///
        /// <param name="index">The index of the attribute (zero-based).</param>
        /// <param name="value">The desired flag value.</param>
        /// <exception cref="IndexOutOfRangeException">When the supplied index does not identify an attribute.</exception>
        public virtual void SetDeclared(int index, bool value)
        {
            if (index < 0 || index >= Length)
                throw new IndexOutOfRangeException(
                "No attribute at index: " + index);
            declared[index] = value;
        }

        ///
        /// Assign a value to the "specified" flag of a specific attribute.
        /// This is the only way this flag can be cleared, except clearing
        /// by initialization with the copy constructor.
        ///
        /// <param name="index">The index of the attribute (zero-based).</param>
        /// <param name="value">The desired flag value.</param>
        /// <exception cref="IndexOutOfRangeException">When the supplied index does not identify an attribute.</exception>
        public virtual void SetSpecified(int index, bool value)
        {
            if (index < 0 || index >= Length)
                throw new IndexOutOfRangeException(
                "No attribute at index: " + index);
            specified[index] = value;
        }
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>posix::descriptor_base::~descriptor_base</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../posix__descriptor_base.html" title="posix::descriptor_base">
<link rel="prev" href="wait_type.html" title="posix::descriptor_base::wait_type">
<link rel="next" href="../posix__stream_descriptor.html" title="posix::stream_descriptor">

posix::descriptor_base::~descriptor_base

Protected destructor to prevent deletion
          through this type.

~descriptor_base();

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
using System;
using System.Collections.Generic;

[Serializable]
public class CardsDealtMessage : BaseServerToClientMessage
{
    public List<StandardEnums.CardEnum> cardIDs;
}


text:
#import "QCView.h"

@interface QCView (IBInspectorIntegration)
- (unsigned long long)eventForwarding;
- (void)setEventForwarding:(id)arg1;
- (void)drawRect:(struct CGRect)arg1;
@end


text:
require 'spec_helper'
require './fever_api'

describe FeverAPI do
  include Rack::Test::Methods

  def app
    FeverAPI::Endpoint
  end

  let(:api_key) { 'apisecretkey' }
  let(:story_one) { StoryFactory.build }
  let(:story_two) { StoryFactory.build }
  let(:feed) { FeedFactory.build }
  let(:stories) { [story_one, story_two] }
  let(:answer) { { api_version: 3, auth: 1, last_refreshed_on_time: Time.now.to_i } }
  let(:headers) { { api_key: api_key } }

  before do
    user = stub(api_key: api_key)
    User.stub(:first).and_return(user)
  end

  describe "authentication" do
    it "authenticates request with correct api_key" do
      get "/", headers
      last_response.should be_ok
    end

    it "does not authenticate request with incorrect api_key" do
      get "/", api_key: 'foo'
      last_response.should_not be_ok
    end

    it "does not authenticate request when api_key is not provided" do
      get "/"
      last_response.should_not be_ok
    end
  end

  describe "#get" do
    def make_request(extra_headers = {})
      get "/", headers.merge(extra_headers)
    end

    it "returns standart answer" do
      make_request
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "returns groups and feeds by groups when 'groups' header is provided" do
      FeedRepository.stub(:list).and_return([feed])
      make_request({ groups: nil })
      answer.merge!({ groups: [{ id: 1, title: "All items" }], feeds_groups: [{ group_id: 1, feed_ids: feed.id.to_s }] })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "returns feeds and feeds by groups when 'feeds' header is provided" do
      Feed.stub(:all).and_return([feed])
      FeedRepository.stub(:list).and_return([feed])
      make_request({ feeds: nil })
      answer.merge!({ feeds: [feed.as_fever_json], feeds_groups: [{ group_id: 1, feed_ids: feed.id.to_s }] })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "returns favicons hash when 'favicons' header provided" do
      make_request({ favicons: nil })
      answer.merge!({ favicons: [{ id: 0, data: "image/gif;base64,R0lGODlhAQABAIAAAObm5gAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" }] })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "returns stories when 'items' header is provided along with 'since_id'" do
      StoryRepository.should_receive(:unread_since_id).with('5').and_return([story_one])
      StoryRepository.should_receive(:unread).and_return([story_one, story_two])
      make_request({ items: nil, since_id: 5 })
      answer.merge!({ items: [story_one.as_fever_json], total_items: 2 })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "returns stories when 'items' header is provided without 'since_id'" do
      StoryRepository.should_receive(:unread).twice.and_return([story_one, story_two])
      make_request({ items: nil })
      answer.merge!({ items: [story_one.as_fever_json, story_two.as_fever_json], total_items: 2 })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "returns stories ids when 'items' header is provided along with 'with_ids'" do
      StoryRepository.should_receive(:fetch_by_ids).twice.with(['5']).and_return([story_one])
      make_request({ items: nil, with_ids: 5 })
      answer.merge!({ items: [story_one.as_fever_json], total_items: 1 })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "returns links as empty array when 'links' header is provided" do
      make_request({ links: nil })
      answer.merge!({ links: [] })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "returns unread items ids when 'unread_item_ids' header is provided" do
      StoryRepository.should_receive(:unread).and_return([story_one, story_two])
      make_request({ unread_item_ids: nil })
      answer.merge!({ unread_item_ids: [story_one.id,story_two.id].join(',') })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "returns starred items when 'saved_item_ids' header is provided" do
      Story.should_receive(:where).with({ is_starred: true }).and_return([story_one, story_two])
      make_request({ saved_item_ids: nil })
      answer.merge!({ saved_item_ids: [story_one.id,story_two.id].join(',') })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end
  end

  describe "#post" do
    def make_request(extra_headers = {})
      post "/", headers.merge(extra_headers)
    end

    it "commands to mark story as read" do
      MarkAsRead.should_receive(:new).with('10').and_return(stub(mark_as_read: true))
      make_request({ mark: 'item', as: 'read', id: 10 })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "commands to mark story as unread" do
      MarkAsUnread.should_receive(:new).with('10').and_return(stub(mark_as_unread: true))
      make_request({ mark: 'item', as: 'unread', id: 10 })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "commands to save story" do
      MarkAsStarred.should_receive(:new).with('10').and_return(stub(mark_as_starred: true))
      make_request({ mark: 'item', as: 'saved', id: 10 })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "commands to unsave story" do
      MarkAsUnstarred.should_receive(:new).with('10').and_return(stub(mark_as_unstarred: true))
      make_request({ mark: 'item', as: 'unsaved', id: 10 })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end

    it "commands to mark group as read" do
      MarkGroupAsRead.should_receive(:new).with('10', '1375080946').and_return(stub(mark_group_as_read: true))
      make_request({ mark: 'group', as: 'read', id: 10, before: 1375080946 })
      last_response.should be_ok
      last_response.body.should == answer.to_json
    end
  end
end


text:
title: Entropy
id: 599d15309e88c813a40baf58
challengeType: 5
videoUrl: ''
localeTitle: Entropía
---

## Description

 Tarea:
 Calcule la entropía H de Shannon de una cadena de entrada dada.

 Dada la discreta variable aleatoria $ X $ que es una cadena de $ N $ "símbolos" (caracteres totales) que consta de $ n $ caracteres diferentes (n = 2 para binario), la entropía de X de Shannon en bits / símbolo es:

 $ H_2 (X) = - \ sum_ {i = 1} ^ n \ frac {count_i} {N} \ log_2 \ left (\ frac {count_i} {N} \ right) $

 donde $ count_i $ es el conteo del carácter $ n_i $.

## Instructions

## Tests

```yml
tests:
  - text: <code>entropy</code> es una función.
    testString: 'assert(typeof entropy === "function", "<code>entropy</code> is a function.");'
  - text: <code>entropy("0")</code> debe devolver <code>0</code>
    testString: 'assert.equal(entropy("0"), 0, "<code>entropy("0")</code> should return <code>0</code>");'
  - text: <code>entropy("01")</code> debe devolver <code>1</code>
    testString: 'assert.equal(entropy("01"), 1, "<code>entropy("01")</code> should return <code>1</code>");'
  - text: <code>entropy("0123")</code> debe devolver <code>2</code>
    testString: 'assert.equal(entropy("0123"), 2, "<code>entropy("0123")</code> should return <code>2</code>");'
  - text: <code>entropy("01234567")</code> debe devolver <code>3</code>
    testString: 'assert.equal(entropy("01234567"), 3, "<code>entropy("01234567")</code> should return <code>3</code>");'
  - text: <code>entropy("0123456789abcdef")</code> debe devolver <code>4</code>
    testString: 'assert.equal(entropy("0123456789abcdef"), 4, "<code>entropy("0123456789abcdef")</code> should return <code>4</code>");'
  - text: <code>entropy("1223334444")</code> debe devolver <code>1.8464393446710154</code>
    testString: 'assert.equal(entropy("1223334444"), 1.8464393446710154, "<code>entropy("1223334444")</code> should return <code>1.8464393446710154</code>");'

```

## Challenge Seed

```js
function entropy (s) {
  // Good luck!
}

```

## Solution

```js
// solution required
```


text:
env GOOS=linux go build stocks.go
docker build -t quay.io/sevii/ll-stocks:latest .
#docker run -p 8075:8075 -d quay.io/sevii/ll-stocks
docker push quay.io/sevii/ll-stocks


text:
var tpj=jQuery;
tpj.noConflict();

tpj(document).ready(function() {

  var apiRevoSlider = tpj('.tp-banner').show().revolution(
  {
    sliderType:"standard",
    jsFileLocation:"include/rs-plugin/js/",
    sliderLayout:"fullscreen",
    dottedOverlay:"none",
    delay:9000,
    responsiveLevels:[1200,992,768,480,320],
    startwidth:1140,
    startheight:600,
    hideThumbs:200,

    thumbWidth:100,
    thumbHeight:50,
    thumbAmount:3,

    navigation: {
      keyboardNavigation:"off",
      keyboard_direction: "horizontal",
      mouseScrollNavigation:"off",
      onHoverStop:"off",
      touch:{
        touchenabled:"on",
        swipe_threshold: 75,
        swipe_min_touches: 1,
        swipe_direction: "horizontal",
        drag_block_vertical: false
      },
      arrows: {
                        style: "hermes",
                        enable: true,
                        hide_onmobile: false,
                        hide_onleave: false,
                        tmp: '

{{title}}

',
                        left: {
                            h_align: "left",
                            v_align: "center",
                            h_offset: 10,
                            v_offset: 0
                        },
                        right: {
                            h_align: "right",
                            v_align: "center",
                            h_offset: 10,
                            v_offset: 0
                        }
                    }
    },

    touchenabled:"on",
    onHoverStop:"on",

    swipe_velocity: 0.7,
    swipe_min_touches: 1,
    swipe_max_touches: 1,
    drag_block_vertical: false,

    parallax:"mouse",
    parallaxBgFreeze:"on",
    parallaxLevels:[8,7,6,5,4,3,2,1],
    parallaxDisableOnMobile:"on",

    keyboardNavigation:"on",

    shadow:0,
    fullWidth:"off",
    fullScreen:"on",

    spinner:"spinner0",

    stopLoop:"off",
    stopAfterLoops:-1,
    stopAtSlide:-1,

    shuffle:"off",

    forceFullWidth:"off",
    fullScreenAlignForce:"off",
    minFullScreenHeight:"400",

    hideThumbsOnMobile:"off",
    hideNavDelayOnMobile:1500,
    hideBulletsOnMobile:"off",
    hideArrowsOnMobile:"off",
    hideThumbsUnderResolution:0,

    hideSliderAtLimit:0,
    hideCaptionAtLimit:0,
    hideAllCaptionAtLilmit:0,
    startWithSlide:0,
    fullScreenOffset:"0px"
  });

  apiRevoSlider.bind("revolution.slide.onchange",function (e,data) {
    if( $(window).width() > 992 ) {
      if( $('#slider ul > li').eq(data.slideIndex-1).hasClass('dark') ){
        $('#header.transparent-header:not(.sticky-header,.semi-transparent)').addClass('dark');
        $('#header.transparent-header.sticky-header,#header.transparent-header.semi-transparent.sticky-header').removeClass('dark');
        $('#header-wrap').removeClass('not-dark');
      } else {
        if( $('body').hasClass('dark') ) {
          $('#header.transparent-header:not(.semi-transparent)').removeClass('dark');
          $('#header.transparent-header:not(.sticky-header,.semi-transparent)').find('#header-wrap').addClass('not-dark');
        } else {
          $('#header.transparent-header:not(.semi-transparent)').removeClass('dark');
          $('#header-wrap').removeClass('not-dark');
        }
      }
      SEMICOLON.header.logo();
    }
  });

}); //ready


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

<TITLE>
GnuDHKeyPairGenerator (GNU cryptographic primitives and tools)
</TITLE>
<META NAME="keywords" CONTENT="gnu.crypto.key.dh.GnuDHKeyPairGenerator,GnuDHKeyPairGenerator class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

For the latest news and information visit
The GNU Crypto project

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY:  NESTED | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

gnu.crypto.key.dh

Class GnuDHKeyPairGenerator

java.lang.Object
  |
  +--gnu.crypto.key.dh.GnuDHKeyPairGenerator

All Implemented Interfaces:
IKeyPairGenerator

public class GnuDHKeyPairGenerator
extends java.lang.Object
implements IKeyPairGenerator

An implementation of a Diffie-Hellman keypair generator.

Reference:

Diffie-Hellman Key
    Agreement Method

    Eric Rescorla.

Field Summary

static java.lang.String
DH_PARAMETERS

          Property name of an optional DHGenParameterSpec instance to use
 for this generator.

static java.lang.String
EXPONENT_SIZE

          Property name of the size in bits (Integer) of the private exponent (x).

static java.lang.String
PRIME_SIZE

          Property name of the size in bits (Integer) of the public prime (p).

static java.lang.String
SOURCE_OF_RANDOMNESS

          Property name of an optional SecureRandom instance to use.

Constructor Summary

GnuDHKeyPairGenerator()

Method Summary

 java.security.KeyPair
generate()

          Generates a new keypair based on the attributes used to configure the
 instance.

 java.lang.String
name()

          Returns the canonical name of this keypair generator.

 void
setup(java.util.Map attributes)

          [Re]-initialises this instance for use with a given set of attributes.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

SOURCE_OF_RANDOMNESS

public static final java.lang.String SOURCE_OF_RANDOMNESS

Property name of an optional SecureRandom instance to use. The
 default is to use a classloader singleton from PRNG.

See Also:
Constant Field Values

DH_PARAMETERS

public static final java.lang.String DH_PARAMETERS

Property name of an optional DHGenParameterSpec instance to use
 for this generator.

See Also:
Constant Field Values

PRIME_SIZE

public static final java.lang.String PRIME_SIZE

Property name of the size in bits (Integer) of the public prime (p).

See Also:
Constant Field Values

EXPONENT_SIZE

public static final java.lang.String EXPONENT_SIZE

Property name of the size in bits (Integer) of the private exponent (x).

See Also:
Constant Field Values

Constructor Detail

GnuDHKeyPairGenerator

public GnuDHKeyPairGenerator()

Method Detail

name

public java.lang.String name()

Description copied from interface: IKeyPairGenerator

Returns the canonical name of this keypair generator.

Specified by:
name in interface IKeyPairGenerator

Returns:
the canonical name of this instance.

setup

public void setup(java.util.Map attributes)

Description copied from interface: IKeyPairGenerator

[Re]-initialises this instance for use with a given set of attributes.

Specified by:
setup in interface IKeyPairGenerator

Parameters:
attributes - a map of name/value pairs to use for setting up the
 instance.

generate

public java.security.KeyPair generate()

Description copied from interface: IKeyPairGenerator

Generates a new keypair based on the attributes used to configure the
 instance.

Specified by:
generate in interface IKeyPairGenerator

Returns:
a new keypair.

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

For the latest news and information visit
The GNU Crypto project

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY:  NESTED | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 2001, 2002, 2003, 2004 Free Software Foundation, Inc.


text:
@implementation PlusButton

//+ (id)plusButton {
//    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
//    [button setImage:[UIImage imageNamed:@"blank"] forState:UIControlStateNormal];
//    [button setFrame:CGRectMake(0, 0, 30, 50)];
//    return button;
//}
//
//+ (NSUInteger)indexOfPlusButtonInTabBar {
//    return 2;
//}
//+ (UIViewController *)plusChildViewController {
//    return [[TreeViewController alloc] init];
//}
//
//- (void)plusChildViewControllerButtonClicked:(UIButton<CYLPlusButtonSubclassing> *)sender{
//    NSLog(@"----");
//}
@end


text:
package gogen

import (
	"fmt"
	"io"
	"sort"
	"strings"

	"github.com/antlr/antlr4/runtime/Go/antlr"
	"github.com/sirkon/gotify"

	"github.com/sirkon/ldetool/internal/generator"
	"github.com/sirkon/ldetool/internal/generator/gogen/internal/srcobj"
	"github.com/sirkon/ldetool/internal/types"
)

// Name provides a link between token and string
type Name struct {
	name  string
	token antlr.Token
}

var _ generator.Generator = &Generator{}

// Generator implementation of generator.Generator
// for Go target
type Generator struct {
	useString bool
	rules     map[string]antlr.Token // Register rule names to check duplication
	comment   []string               // Set of comments in the current rule

	consts         map[string]string // string constants for reuse
	fields         map[string]Name   // Field names obviously should have different names
	vars           map[string]string // Function local variables
	imports        map[string]string // Set of import paths
	scopeAbandoned map[string]bool   // Set check if the current scope was abandoned due to mismatch

	uniqueLabels map[string]struct{} // Map to track label names to avoid duplicates
	labelName    string              // Current label name, set on scope enter and add field actions
	labels       []string            // stack of labels

	namespaces []string // Stack of namespaces (each item is a name of optional area)

	critical     bool           // Treat mismatch errors as critical
	silenceDepth int            // When silenceDepth > 0 even decoding errors are ignored
	goish        *gotify.Gotify // identifier gotification service

	platformType generator.PlatformType

	// gravity is not used yet, planned for mismatch position  clarification against the rule, something like
	// "Could not find string `name=` right before Parameter.Name field" or
	// "Could not find string 'FETCH' between Time and Timeout fields", etc
	gravity []string

	// Source object representation primitives
	file              *srcobj.File    // File image
	body              *srcobj.Body    // Current method image
	obj               []*srcobj.Strct // Image of the structure
	optgetters        *srcobj.Body    // Option getters for current structure
	vargen            *srcobj.Vars    // Function variables image
	decoderMap        map[string]func(src srcobj.Source, dest string)
	decimalDecoderMap map[string]func(src srcobj.Source, dest string, precision, scale int)

	ruleName string // Name of currently processing rule

	curField     Name
	curFieldType string

	rulePassCounter int // how many passes there in current rule. To be reset on a new one.

	externalTypes map[string]types.TypeRegistration
}

// PlatformType holds an information what type of platform to generate code for:
//    1. Little endiant
//    2. Big endian
//    3. Crossplatform
// There's a difference for fast short (up to 8 bytes) prefix checks in strings.
func (g *Generator) PlatformType(t generator.PlatformType) {
	g.platformType = t
}

// ErrorToken message
func (g *Generator) ErrorToken(token antlr.Token, format string, params ...interface{}) error {
	return fmt.Errorf(
		"%d:%d: %s",
		token.GetLine(),
		token.GetColumn()+1,
		fmt.Sprintf(format, params...),
	)
}

// NewGenerator constructor
func NewGenerator(useString bool, goish *gotify.Gotify, externalTypes map[string]types.TypeRegistration) *Generator {
	res := &Generator{
		useString: useString,
		rules:     map[string]antlr.Token{},
		consts:    map[string]string{},
		imports:   map[string]string{},

		critical: false,
		vars:     map[string]string{},
		goish:    goish,
		gravity:  nil,

		file:     srcobj.NewFile(useString),
		ruleName: "",

		platformType:  generator.Universal,
		externalTypes: externalTypes,
	}

	res.decoderMap = map[string]func(src srcobj.Source, dest string){
		"int":     res.decodeInt,
		"int8":    res.decodeInt8,
		"int16":   res.decodeInt16,
		"int32":   res.decodeInt32,
		"int64":   res.decodeInt64,
		"uint":    res.decodeUint,
		"uint8":   res.decodeUint8,
		"uint16":  res.decodeUint16,
		"uint32":  res.decodeUint32,
		"uint64":  res.decodeUint64,
		"hex":     res.decodeHex,
		"hex8":    res.decodeHex8,
		"hex16":   res.decodeHex16,
		"hex32":   res.decodeHex32,
		"hex64":   res.decodeHex64,
		"oct":     res.decodeOct,
		"oct8":    res.decodeOct8,
		"oct16":   res.decodeOct16,
		"oct32":   res.decodeOct32,
		"oct64":   res.decodeOct64,
		"float32": res.decodeFloat32,
		"float64": res.decodeFloat64,
		"string":  res.decodeString,
		"str":     res.decodeStr,
	}
	res.decimalDecoderMap = map[string]func(src srcobj.Source, dest string, precision, scale int){
		"dec32":  res.decodeDec32,
		"dec64":  res.decodeDec64,
		"dec128": res.decodeDec128,
	}
	return res
}

func (g *Generator) valid() string {
	return "p." + strings.Join(g.namespaces, ".") + ".Valid"
}

func (g *Generator) regLabel() {
	namespaces := make([]string, len(g.namespaces))
	for i, chunk := range g.namespaces {
		if len(chunk) == 0 {
			namespaces[i] = "AnonymousArea"
		} else {
			namespaces[i] = chunk
		}
	}
	suffix := ""
	i := 1
	for {
		labelName := g.goish.Private(strings.Join(namespaces, "_")+"_label") + suffix
		labelName = g.goish.Private(g.goish.Package(g.ruleName) + "_" + labelName)
		if _, ok := g.uniqueLabels[labelName]; !ok {
			g.labelName = labelName
			break
		}
		i++
		suffix = fmt.Sprintf("%d", i)
	}
	g.uniqueLabels[g.labelName] = struct{}{}
	g.labels = append(g.labels, g.labelName)
}

func (g *Generator) label() string {
	return g.labelName
}

func (g *Generator) dropLabel() {
	if len(g.labels) > 0 {
		g.labels = g.labels[:len(g.labels)-1]
	}
	if len(g.labels) > 0 {
		g.labelName = g.labels[len(g.labels)-1]
	}
}

func (g *Generator) curObj() *srcobj.Strct {
	return g.obj[len(g.obj)-1]
}

func (g *Generator) varName(name string) string {
	return "p." + strings.Join(append(g.namespaces, name), ".")
}

func (g *Generator) anonymous() bool {
	return len(g.namespaces) > 0 && len(g.namespaces[len(g.namespaces)-1]) == 0
}

// UseRule ...
func (g *Generator) UseRule(comment []string, t antlr.Token, name string) error {
	if len(g.ruleName) != 0 {
		return fmt.Errorf("attempt to use rule `%s` while the previous one (%s) was not pushed", name, g.ruleName)
	}
	if prev, ok := g.rules[name]; ok {
		return fmt.Errorf("%d: redeclaration of rule `%s` which has already been defined at line %d", t.GetLine(), name, prev)
	}
	g.comment = comment
	g.rules[name] = t
	g.fields = map[string]Name{}
	g.scopeAbandoned = map[string]bool{}
	g.uniqueLabels = map[string]struct{}{}
	g.vars = map[string]string{}
	g.namespaces = nil
	g.labels = nil
	g.ruleName = name
	g.obj = []*srcobj.Strct{g.file.AddExtractor(g.comment, name, g)}
	g.curObj().AddString(nil, "Rest")
	g.body = g.file.AddExtract(name).Body()
	g.body.Append(srcobj.LineAssign{
		Receiver: "p.Rest",
		Expr:     srcobj.Raw("line"),
	})
	g.optgetters = srcobj.NewBody()
	g.vargen = srcobj.NewVars()
	g.body.Append(g.vargen)
	g.rulePassCounter = 0
	return nil
}

func (g *Generator) lookForExternal(fieldType string) (types.TypeRegistration, bool) {
	res, ok := g.externalTypes[strings.TrimLeft(fieldType, "*")]
	return res, ok
}

// AddField ...
func (g *Generator) AddField(comment []string, name string, t antlr.Token, fieldType string) error {
	g.addField(name, t)
	reg := g.curObj()
	var field types.Field
	if types.IsBuiltin(fieldType) {
		field = types.Builtin(name, fieldType)
	} else {
		extType, ok := g.lookForExternal(fieldType)
		var err error
		if !ok {
			ok, err = types.NeedCustomUnmarshaler(fieldType)
			if ok {
				extType = types.LocalType{
					Name: strings.TrimLeft(fieldType, "$"),
				}
				g.externalTypes[fieldType] = extType
			}
			if extType.String() == "str" {
				extType = types.LocalType{
					Name: "string",
				}
			}
			if err != nil {
				return g.ErrorToken(t, "%s", err)
			}
		}
		if !ok {
			// Last chance, it can a request for custom unmarshaler (with $)

			typeAvailablePrep := types.Declarables()
			var typeAvailable []string
			for _, typeName := range typeAvailablePrep {
				switch typeName {
				case "dec32", "dec64", "dec128":
				default:
					typeAvailable = append(typeAvailable, typeName)
				}
			}
			typeAvailable = append(typeAvailable, "decX.Y")
			for typeName := range g.externalTypes {
				typeAvailable = append(typeAvailable, typeName)
			}
			sort.Strings(typeAvailable)
			for i, typeName := range typeAvailable {
				typeAvailable[i] = fmt.Sprintf("\033[1m%s\033[0m", typeName)
			}
			return g.ErrorToken(t, "unsupported type `\033[1m%s\033[0m`, must be one of %s",
				fieldType, strings.Join(typeAvailable, ", "))
		}
		field = types.FieldCustom{
			FieldName: name,
			Type:      extType,
		}
	}
	field.Register(comment, reg)
	return nil
}

func (g *Generator) failure(format string, params ...srcobj.Source) (res srcobj.Source) {
	if len(g.namespaces) > 0 {
		g.abandon()
		var pre srcobj.Source
		if g.anonymous() {
			pre = srcobj.Raw("")
		} else {
			pre = srcobj.Assign(g.valid(), srcobj.False)
		}
		res = srcobj.NewBody(
			pre,
			srcobj.Semicolon,
			srcobj.Goto(g.label()),
		)
	} else if g.critical {
		g.RegImport("", "fmt")
		res = srcobj.ReturnError(format, params...)
	} else {
		res = srcobj.ReturnFail
	}
	return
}

func (g *Generator) rest() srcobj.Source {
	return srcobj.Raw(g.curRestVar())
}

func (g *Generator) indent() *srcobj.Body {
	g.body.Append(srcobj.Raw("\n"))
	return g.body
}

func (g *Generator) RestLengthCheck(operator string, length int) error {
	var operatorAction func(srcobj.Source, srcobj.Source) srcobj.Source
	var errorFormat string
	var charsLit string
	if length > 1 {
		charsLit = "characters"
	} else {
		charsLit = "character"
	}
	var comment string
	switch operator {
	case "<":
		operatorAction = srcobj.OperatorGE
		errorFormat = "rest is longer than required (%d symbols)"
		comment = fmt.Sprintf("checks if the rest is less than %d %s long", length, charsLit)
	case "==":
		operatorAction = srcobj.OperatorNEq
		errorFormat = "rest is not %d symbols long"
		comment = fmt.Sprintf("checks if the rest is exactly %d %s long", length, charsLit)
	case ">":
		operatorAction = srcobj.OperatorLE
		errorFormat = "rest is shorter than required (%d symbols)"
		comment = fmt.Sprintf("checks if the rest is more than %d %s long", length, charsLit)
	}
	g.body.Append(srcobj.Literal("\n"))
	g.body.Append(srcobj.Comment(comment))
	g.body.Append(
		srcobj.If{
			Expr: operatorAction(
				srcobj.NewCall("len", g.rest()),
				srcobj.Literal(length),
			),
			Then: g.failure(
				errorFormat,
				srcobj.Literal(length),
			),
		},
	)
	return nil
}

// PassN passes first N characters if they are there, otherwise signal a error
func (g *Generator) PassN(n int) error {
	g.body.Append(srcobj.Literal("\n"))
	g.body.Append(srcobj.Comment(fmt.Sprintf("Pass first N symbols in the rest")))
	g.body.Append(
		srcobj.If{
			Expr: srcobj.OperatorGE(
				srcobj.NewCall(
					"len",
					g.rest(),
				),
				srcobj.Literal(n),
			),
			Then: srcobj.Assign(
				g.curRestVar(),
				srcobj.SliceFrom(g.rest(), srcobj.Literal(n)),
			),
			Else: g.failure(
				"cannot skip first %d symbols: only %d left in the rest",
				srcobj.Literal(n),
				srcobj.NewCall("len", g.rest()),
			),
		},
	)
	return nil
}

func (g *Generator) PassHeadCharacters(char string) error {
	const (
		counter = "headPassCounter"
		value   = "headPassValue"
	)
	if err := g.regVar(counter, "int"); err != nil {
		return err
	}
	itemType := "byte"
	if g.useString {
		itemType = "rune"
	}
	if err := g.regVar(value, itemType); err != nil {
		return err
	}
	g.body.Append(srcobj.Literal("\n"))
	g.body.Append(srcobj.Comment(fmt.Sprintf("Pass all characters %s at the rest start", char)))
	if g.rulePassCounter > 0 {
		g.body.Append(srcobj.Assign(counter, srcobj.Literal(0)))
		g.body.Append(srcobj.Literal("\n"))
	}
	g.rulePassCounter++
	rest := g.rest()
	if g.useString {
		rest = srcobj.NewCall("string", rest)
	}
	g.body.Append(
		srcobj.For{
			I:         counter,
			Value:     value,
			Container: rest,
			Body: srcobj.If{
				Expr: srcobj.OperatorNEq(srcobj.Raw(value), srcobj.Raw(char)),
				Then: srcobj.Break,
			},
			DontAssign: true,
		},
	)
	g.body.Append(srcobj.If{
		Expr: srcobj.OperatorGT(srcobj.Raw(counter), srcobj.Literal(0)),
		Then: srcobj.OperatorAssign(g.rest(), srcobj.SliceFrom(g.rest(), srcobj.Raw(counter))),
	})
	return nil
}

// Stress mismatches should be treated as critical errors
func (g *Generator) Stress() {
	g.critical = true
}

// Relax ...
func (g *Generator) Relax() {
	g.critical = false
}

// Generate writes into io.Writer
func (g *Generator) Generate(pkgName string, dest io.Writer) error {
	g.file.PkgName(pkgName)
	if err := g.file.Dump(dest); err != nil {
		return err
	}
	return nil
}

// Push pushes data
func (g *Generator) Push() error {
	if len(g.ruleName) == 0 {
		return fmt.Errorf("no rule has been set up to push it now")
	}

	g.indent()
	g.body.Append(srcobj.ReturnOK)
	g.file.Append(g.optgetters)

	g.Relax()
	g.vars = map[string]string{}
	g.fields = map[string]Name{}
	g.scopeAbandoned = map[string]bool{}
	g.ruleName = ""
	return nil
}

// RegGravity registers center of gravity
func (g *Generator) RegGravity(name string) error {
	g.gravity = append(g.gravity, name)
	return nil
}

// AtEnd checks if the rest is empty
func (g *Generator) AtEnd() error {
	g.body.Append(srcobj.Raw("\n"))
	g.body.Append(srcobj.Comment("Check if the rest is empty"))
	g.body.Append(
		srcobj.If{
			Expr: srcobj.OperatorNEq(
				srcobj.NewCall("len", g.rest()),
				srcobj.Literal(0),
			),
			Then: g.failure(
				"The rest is not empty: %s",
				srcobj.NewCall("string", g.rest()),
			),
		},
	)
	return nil
}


text:
layout: global
title: Identifiers
displayTitle: Identifiers
license: |
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
---

### Description

An identifier is a string used to identify a database object such as a table, view, schema, column, etc. Spark SQL has regular identifiers and delimited identifiers, which are enclosed within backticks. Both regular identifiers and delimited identifiers are case-insensitive.

### Syntax

#### Regular Identifier

```sql
{ letter | digit | '_' } [ , ... ]
```
**Note:** If `spark.sql.ansi.enabled` is set to true, ANSI SQL reserved keywords cannot be used as identifiers. For more details, please refer to [ANSI Compliance](sql-ref-ansi-compliance.html).

#### Delimited Identifier

```sql
`c [ ... ]`
```

### Parameters

* **letter**

    Any letter from A-Z or a-z.

* **digit**

    Any numeral from 0 to 9.

* **c**

    Any character from the character set. Use <code>`</code> to escape special characters (e.g., <code>`</code>).

### Examples

```sql
-- This CREATE TABLE fails with ParseException because of the illegal identifier name a.b
CREATE TABLE test (a.b int);
org.apache.spark.sql.catalyst.parser.ParseException:
Syntax error at or near '.': extra input '.'(line 1, pos 20)

-- This CREATE TABLE works
CREATE TABLE test (`a.b` int);

-- This CREATE TABLE fails with ParseException because special character ` is not escaped
CREATE TABLE test1 (`a`b` int);
org.apache.spark.sql.catalyst.parser.ParseException:
Syntax error at or near '`'(line 1, pos 23)

-- This CREATE TABLE works
CREATE TABLE test (`a``b` int);
```


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, settled, waitFor } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import { INSIGHTS_INTERVALS } from 'travis/services/insights';
import { setupMirage } from 'ember-cli-mirage/test-support';

module('Integration | Component | build-count', function (hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  hooks.beforeEach(function () {
    const user = this.server.create('user');
    this.setProperties({
      ownerData: user,
      private: true,
    });
  });

  test('builds stats', async function (assert) {
    this.set('interval', INSIGHTS_INTERVALS.MONTH);

    this.server.createList('insight-metric', 15);

    await render(hbs`{{build-count interval=interval owner=ownerData private=private}}`);
    await settled();

    assert.dom('.insights-glance').doesNotHaveClass('insights-glance--loading');
    assert.dom('.insights-glance__title').hasText('Total Builds');
    assert.dom('.insights-glance__stat').hasText('448');
    assert.dom('.insights-glance-delta').hasAttribute('data-dir', '+');
    assert.dom('.insights-glance-delta').hasAttribute('title', '120 builds the previous month');
    assert.dom('.insights-glance-delta__stat').hasText('273.3%');
    assert.dom('.insights-glance__chart .chart-component').exists();
  });

  test('loading state renders', async function (assert) {
    this.set('interval', INSIGHTS_INTERVALS.WEEK);

    render(hbs`{{build-count interval=interval owner=ownerData private=private}}`);
    await waitFor('.insights-glance--loading');

    assert.dom('.insights-glance').hasClass('insights-glance--loading');
    assert.dom('.insights-glance__title').hasText('Total Builds');
    assert.dom('.insights-glance__stat').hasText('');
    assert.dom('.insights-glance-delta').doesNotExist();
    assert.dom('.insights-glance__chart .chart-component').doesNotExist();
    assert.dom('.insights-glance__chart-placeholder').exists();
  });
});


text:
def prog_iterate(it, verbosity=100, key=repr, estimate=None, persec=True):
    """An iterator that yields everything from `it', but prints progress
       information along the way, including time-estimates if
       possible"""
    from itertools import islice
    from datetime import datetime
    import sys

    now = start = datetime.now()
    elapsed = start - start

    # try to guess at the estimate if we can
    if estimate is None:
        try:
            estimate = len(it)
        except:
            pass

    def timedelta_to_seconds(td):
        return td.days * (24*60*60) + td.seconds + (float(td.microseconds) / 1000000)
    def format_timedelta(td, sep=''):
        ret = []
        s = timedelta_to_seconds(td)
        if s < 0:
            neg = True
            s *= -1
        else:
            neg = False

        if s >= (24*60*60):
            days = int(s//(24*60*60))
            ret.append('%dd' % days)
            s -= days*(24*60*60)
        if s >= 60*60:
            hours = int(s//(60*60))
            ret.append('%dh' % hours)
            s -= hours*(60*60)
        if s >= 60:
            minutes = int(s//60)
            ret.append('%dm' % minutes)
            s -= minutes*60
        if s >= 1:
            seconds = int(s)
            ret.append('%ds' % seconds)
            s -= seconds

        if not ret:
            return '0s'

        return ('-' if neg else '') + sep.join(ret)
    def format_datetime(dt, show_date=False):
        if show_date:
            return dt.strftime('%Y-%m-%d %H:%M')
        else:
            return dt.strftime('%H:%M:%S')
    def deq(dt1, dt2):
        "Indicates whether the two datetimes' dates describe the same (day,month,year)"
        d1, d2 = dt1.date(), dt2.date()
        return (    d1.day   == d2.day
                and d1.month == d2.month
                and d1.year  == d2.year)

    sys.stderr.write('Starting at %s\n' % (start,))

    # we're going to islice it so we need to start an iterator
    it = iter(it)

    seen = 0
    while True:
        this_chunk = 0
        thischunk_started = datetime.now()

        # the simple bit: just iterate and yield
        for item in islice(it, verbosity):
            this_chunk += 1
            seen += 1
            yield item

        if this_chunk < verbosity:
            # we're done, the iterator is empty
            break

        now = datetime.now()
        elapsed = now - start
        thischunk_seconds = timedelta_to_seconds(now - thischunk_started)

        if estimate:
            # the estimate is based on the total number of items that
            # we've processed in the total amount of time that's
            # passed, so it should smooth over momentary spikes in
            # speed (but will take a while to adjust to long-term
            # changes in speed)
            remaining = ((elapsed/seen)*estimate)-elapsed
            completion = now + remaining
            count_str = ('%d/%d %.2f%%'
                         % (seen, estimate, float(seen)/estimate*100))
            completion_str = format_datetime(completion, not deq(completion,now))
            estimate_str = (' (%s remaining; completion %s)'
                            % (format_timedelta(remaining),
                               completion_str))
        else:
            count_str = '%d' % seen
            estimate_str = ''

        if key:
            key_str = ': %s' % key(item)
        else:
            key_str = ''

        # unlike the estimate, the persec count is the number per
        # second for *this* batch only, without smoothing
        if persec and thischunk_seconds > 0:
            persec_str = ' (%.1f/s)' % (float(this_chunk)/thischunk_seconds,)
        else:
            persec_str = ''

        sys.stderr.write('%s%s, %s%s%s\n'
                         % (count_str, persec_str,
                            format_timedelta(elapsed), estimate_str, key_str))

    now = datetime.now()
    elapsed = now - start
    elapsed_seconds = timedelta_to_seconds(elapsed)
    if persec and seen > 0 and elapsed_seconds > 0:
        persec_str = ' (@%.1f/sec)' % (float(seen)/elapsed_seconds)
    else:
        persec_str = ''
    sys.stderr.write('Processed %d%s items in %s..%s (%s)\n'
                     % (seen,
                        persec_str,
                        format_datetime(start, not deq(start, now)),
                        format_datetime(now, not deq(start, now)),
                        format_timedelta(elapsed)))


text:
slug: Agnes-Harkness-Winking
template_id: 586
title: Agnes Harkness Winking
wiki: https://en.meming.world/wiki/Agnes_Harkness_Winking
---


text:
angular.module('dinnerDecisionApp')
.controller('resultController', function ($scope, $location, $routeParams, modelService) {

    var restaurants = modelService.getRestaurants();

    $scope.winningRestaurant = {};
    $scope.tiedWinningRestaurants = [];

    var determineWinner = function () {
        var restaurantScores = [];

        restaurants.forEach(function (element, index, array) {
            var totalScore = element.votes.sum();
            var numLoves = Math.floor(totalScore / 10000);
            var numLikes = totalScore % 10000;

            restaurantScores.push({
                restaurantIndex: index,
                totalScore: totalScore,
                numLoves: numLoves,
                numLikes: numLikes,
                numLovesPlusLikes: numLoves + numLikes
            });
        });

        // Weight Hates really low
        restaurantScores.sort(function (a, b) {
            if (a.numLovesPlusLikes > b.numLovesPlusLikes) {
                return -1;
            }
            if (a.numLovesPlusLikes < b.numLovesPlusLikes) {
                return 1;
            }
            if (a.totalScore > b.totalScore) {
                return -1;
            }
            if (a.totalScore < b.totalScore) {
                return 1;
            }
            return 0;
        });

        var bestScore = restaurantScores[0].totalScore;

        $scope.tiedWinningRestaurants = [];

        $scope.tiedWinningRestaurants.push(restaurants[restaurantScores[0].restaurantIndex]);

        for (var i = 1; i < restaurantScores.length; i++) {
            if (restaurantScores[i].totalScore == bestScore) {
                $scope.tiedWinningRestaurants.push(restaurants[restaurantScores[i].restaurantIndex]);
            } else {
                break;
            }
        }

        $scope.winningRestaurant = $scope.tiedWinningRestaurants[Math.floor(Math.random() * $scope.tiedWinningRestaurants.length)];
        $scope.mapUrl = "maps://maps.apple.com/?q=" + $scope.winningRestaurant.formattedAddress;
        $scope.mapUrlTest = "maps://maps.apple.com/?q=4404 voss hills pl, dallas, tx 75287";
    };

    $scope.openMaps = function () {
        // TODO: configure for Android.
        window.location = "maps://maps.apple.com/?q=" + $scope.winningRestaurant.formattedAddressForMaps;
    }

    $scope.openPhone = function () {
        window.location = "tel:" + $scope.winningRestaurant.formattedPhone;
    }

    determineWinner();
});


text:
title: Iterating Rows
page_title: Iterating Rows - WinForms GridView Control
description: Learn how to iterate all rows in a regular and hierarchical WinForms GridView.
slug: winforms/gridview/rows/iterating-rows
tags: iterating,rows
published: True
position: 1
previous_url: gridview-rows-iterating-rows
---

# Iterating Rows

You can iterate through grid rows using the __Rows__ collection of __GridViewRowInfo__ objects. The example below selects the last row, then iterates looking for selected rows. When the selected row is found, the __GridViewRowInfo.EnsureVisible()__ method scrolls the row into the view:

{{source=..\SamplesCS\GridView\Rows\IteratingRows.cs region=iteratingRows}}
{{source=..\SamplesVB\GridView\Rows\IteratingRows.vb region=iteratingRows}}

````C#
GridViewRowInfo lastRow1 = radGridView1.Rows[radGridView1.Rows.Count - 1];
lastRow1.IsSelected = true;
foreach (GridViewRowInfo rowInfo in radGridView1.Rows)
{
    if (rowInfo.IsSelected)
    {
        rowInfo.EnsureVisible();
    }
}

````
````VB.NET
Dim lastRow As GridViewRowInfo = RadGridView1.Rows(RadGridView1.Rows.Count - 1)
lastRow.IsSelected = True
For Each rowInfo As GridViewRowInfo In RadGridView1.Rows
    If rowInfo.IsSelected Then
        rowInfo.EnsureVisible()
    End If
Next

````

{{endregion}}

## Finding a grid row by a value of one of its cells

You could search for a specific value in __RadGridView__ by iterating through the rows and compare cells value. In the example below, you search for __searchedStr__ in __MyColumnName__ column:

{{source=..\SamplesCS\GridView\Rows\IteratingRows.cs region=findAGridRowByCellValue}}
{{source=..\SamplesVB\GridView\Rows\IteratingRows.vb region=findAGridRowByCellValue}}

````C#
string searchedStr = "Picture 2";
for (int r = 0; r < radGridView1.RowCount; r++)
{
    if (radGridView1.Rows[r].Cells["Picture Name"].Value.ToString().ToUpper().Equals(searchedStr.ToUpper()))
    {
        MessageBox.Show("Found a match");
        //do something
    }
}

````
````VB.NET
Dim searchedStr As String = "Picture 2"
For row As Integer = 0 To RadGridView1.RowCount - 1
    If RadGridView1.Rows(row).Cells("Picture Name").Value.ToString().ToUpper().Equals(searchedStr.ToUpper()) Then
        'do something
        MessageBox.Show("Found a match")
    End If
Next

````

{{endregion}}

## Iterating all rows in a self-reference hierarchy

When you have a hierarchical grid with many templates you can use a recursive method to iterate trough all rows:

{{source=..\SamplesCS\GridView\Rows\IteratingRows.cs region=hierarchy}}
{{source=..\SamplesVB\GridView\Rows\IteratingRows.vb region=hierarchy}}

````C#
public void IterateAllRows(IEnumerable<GridViewRowInfo> rowsCollection)
{
    foreach (GridViewDataRowInfo row in rowsCollection)
    {
        Debug.WriteLine(row.Cells[0].Value);//This rows is used for demonstration only!
        if (row.HasChildRows())
        {
            IterateAllRows(row.ChildRows);
        }
    }
}

````
````VB.NET
Public Sub IterateAllRows(rowsCollection As IEnumerable(Of GridViewRowInfo))
    For Each row As GridViewDataRowInfo In rowsCollection
        Debug.WriteLine(row.Cells(0).Value)
        If row.HasChildRows() Then
            IterateAllRows(row.ChildRows)
        End If
    Next
End Sub

````

{{endregion}}

## Iterating hierarchical grid.

You can iterate through grid rows using the __Rows__ collection of __RadGridView__ objects. The example below cycles through the rows of the grid, modifies the values for certain cells in the different hierarchy levels and counts the rows and cells in the whole **RadGridView**.

{{source=..\SamplesCS\GridView\Rows\IteratingRows.cs region=IteratingHierarchicalRows}}
{{source=..\SamplesVB\GridView\Rows\IteratingRows.vb region=IteratingHierarchicalRows}}

````C#
private void radButton1_Click(object sender, EventArgs e)
{
    int count = 0;
    int i = 0;
    foreach (GridViewDataRowInfo dataRow in this.GetAllRows(this.radGridView1.MasterTemplate))
    {
        count++;
        foreach (GridViewCellInfo cell in dataRow.Cells)
        {
            if (cell.ColumnInfo.Name == "CompanyName" || cell.ColumnInfo.Name == "ShipCountry")
            {
                cell.Value = "TEST";
            }
            if (cell.ColumnInfo.Name == "UnitPrice")
            {
                cell.Value = 1.11111;
            }
            i++;
        }
    }
}
public List<GridViewRowInfo> GetAllRows(GridViewTemplate template)
{
    List<GridViewRowInfo> allRows = new List<GridViewRowInfo>();
    allRows.AddRange(template.Rows);
    foreach (GridViewTemplate childTemplate in template.Templates)
    {
        List<GridViewRowInfo> childRows = this.GetAllRows(childTemplate);
        allRows.AddRange(childRows);
    }
    return allRows;
}

````
````VB.NET
Private Sub radButton1_Click(sender As Object, e As EventArgs)
    Dim count As Integer = 0
    Dim i As Integer = 0
    For Each dataRow As GridViewDataRowInfo In Me.GetAllRows(Me.RadGridView1.MasterTemplate)
        count += 1
        For Each cell As GridViewCellInfo In dataRow.Cells
            If cell.ColumnInfo.Name = "CompanyName" OrElse cell.ColumnInfo.Name = "ShipCountry" Then
                cell.Value = "TEST"
            End If
            If cell.ColumnInfo.Name = "UnitPrice" Then
                cell.Value = 1.11111
            End If
            i += 1
        Next
    Next
End Sub
Public Function GetAllRows(template As GridViewTemplate) As List(Of GridViewRowInfo)
    Dim allRows As New List(Of GridViewRowInfo)()
    allRows.AddRange(template.Rows)
    For Each childTemplate As GridViewTemplate In template.Templates
        Dim childRows As List(Of GridViewRowInfo) = Me.GetAllRows(childTemplate)
        allRows.AddRange(childRows)
    Next
    Return allRows
End Function

````

{{endregion}}
# See Also
* [Adding and Inserting Rows]({%slug winforms/gridview/rows/adding-and-inserting-rows%})

* [Conditional Formatting Rows]({%slug winforms/gridview/rows/conditional-formatting-rows%})

* [Creating custom rows]({%slug winforms/gridview/rows/creating-custom-rows%})

* [Drag and Drop]({%slug winforms/gridview/rows/drag-and-drop%})

* [Formatting Rows]({%slug winforms/gridview/rows/formatting-rows%})

* [GridViewRowInfo]({%slug winforms/gridview/rows/gridviewrowinfo%})

* [New Row]({%slug winforms/gridview/rows/new-row%})

* [Painting Rows]({%slug winforms/gridview/rows/painting-rows%})


text:
package org.commonjava.indy.subsys.prefetch;

import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Qualifier used to supply "prefetch-cache" cache in infinispan.xml.
 */
@Qualifier
@Target( {ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention( RetentionPolicy.RUNTIME)
@Documented
public @interface PrefetchCache
{
}


text:
#ifndef LIBGOLLE_ERRORS_H
#define LIBGOLLE_ERRORS_H

#include "platform.h"

GOLLE_BEGIN_C

/*!
 * \file golle/errors.h
 * \brief Error constants
 */

/*!
 * Error codes and return values.
 */
typedef enum golle_error {
  GOLLE_OK = 0, /*!< Success */

  GOLLE_ERROR = -1, /*!< General error code. */
  GOLLE_EMEM = -2, /*!< Out of memory or resources. */
  GOLLE_EEXISTS = -3, /*!< The specified element already exists. */
  GOLLE_ENOTFOUND = -4, /*!< The specified element does not exist. */
  GOLLE_EEMPTY = -5, /*!< The container has no elements. */
  GOLLE_EOUTOFRANGE = -6, /*!< The given size or index is invalid. */
  GOLLE_ETOOFEW = -7, /*!< There are not enough elements available. */
  GOLLE_EINVALID = -8, /*!< Requested an invalid operation. */
  GOLLE_ENOTPRIME = -9, /*!< The given number failed the test for primality. */
  GOLLE_ENOCOMMIT = -10, /*!< The given commitment failed. */
  GOLLE_ECRYPTO = -11, /*!< An error occurred during cryptography. */
  GOLLE_EABORT = -12, /*!< The operation should abort. */
  GOLLE_ECOLLISION = -13, /*!< A collision between two selections occured. */

  GOLLE_END = 1, /*!< An iterator has reached the end of a sequence. */

  GOLLE_COMMIT_PASSED = 1, /*!< Bit commitment verification passed. */
  GOLLE_COMMIT_FAILED = 0, /*!< Bit commitment verification failed. */

  GOLLE_PROBABLY_PRIME = 1, /*!< The number has passed the primality test. */
  GOLLE_NOT_PRIME = 0 /*!< The number is definitely not prime. */

} golle_error;

/*!
 * A shorthand way of stating assertions.
 * Only use inside a function which returns non-void.
 */
#define GOLLE_ASSERT(x,r) do { if ((x) == 0) { return (r); } } while(0)

/*!
 * Avoid compile-time warnings about unused parameters.
 */
#define GOLLE_UNUSED(x) (void)(x)

GOLLE_END_C

#endif


text:
package main

import (
	"encoding/json"
	"errors"
	"github.com/streadway/amqp"
	"log"
	"time"
)

var (
	AMQPChannel *amqp.Channel
)

type AMQPConf struct {
	Queue      string
	Exchange   string
	RoutingKey string
}

func pushToAMQP(task *TaskRequest, aconf *AMQPConf) *MyError {
	// Pushes the given TaskRequest in JSON-form to the given AMQP-queue.
	// On error retries three times before giving up

	msgBody, err := json.Marshal(task)
	if err != nil {
		log.Println("Error while Marshalling: ", err)
		return &MyError{Error: err, Code: ERR_OTHER_RECOVERABLE}
	}
	pub := amqp.Publishing{DeliveryMode: amqp.Persistent, ContentType: "text/plain", Body: msgBody}
	log.Printf("Pushing to %s: \x1b[0;32m%s\x1b[0m\n", aconf.Exchange, msgBody)
	err = AMQPChannel.Publish(aconf.Exchange, aconf.RoutingKey, false, false, pub)

	if err != nil {
		log.Println("Error while pushing to transport: ", err)
		// try to recover three times
		try := 0
		for try < 3 {
			try++
			log.Println("Trying to restore the connection... #", try)
			err = connectAMQP()
			if err == nil {
				break
			}
			// sleep 3 seconds
			time.Sleep(time.Duration(3000000000))
		}
		if err != nil {
			// could not recover the connection after third try => give up
			return &MyError{Error: err, Code: ERR_OTHER_RECOVERABLE}
		}
		log.Println("Connection restored")

		// retry pushing
		err = AMQPChannel.Publish(aconf.Exchange, aconf.RoutingKey, false, false, pub)
		if err != nil {
			return &MyError{Error: err, Code: ERR_OTHER_RECOVERABLE}
		}
	}
	return nil
}

func connectAMQP() error {
	// Create connection to AMQP-server in config
	// Create all Queues and Exchanges from the config

	conn, err := amqp.Dial(conf.AMQP)
	if err != nil {
		return errors.New("Failed to connect to AMQPMQ: " + err.Error())
	}
	//defer conn.Close()

	AMQPChannel, err = conn.Channel()
	if err != nil {
		return errors.New("Failed to open a channel: " + err.Error())
	}
	//defer AMQPChannel.Close()
	addAMQPConf(conf.AMQPDefault)

	for c := range conf.AMQPSplitting {
		err = addAMQPConf(conf.AMQPSplitting[c])
		if err != nil {
			return err
		}
	}

	log.Println("Connected to AMQP")
	return nil
}

func addAMQPConf(c AMQPConf) error {
	// Create Queue and Exchange, and bind Queue to Exchange

	queue, err := AMQPChannel.QueueDeclare(
		c.Queue, //name
		true,    // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)
	if err != nil {
		return errors.New("Failed to declare a queue: " + err.Error())
	}

	err = AMQPChannel.ExchangeDeclare(
		c.Exchange, // name
		"topic",    // type
		true,       // durable
		false,      // auto-deleted
		false,      // internal
		false,      // no-wait
		nil,        // arguments
	)
	if err != nil {
		return errors.New("Failed to declare an exchange: " + err.Error())
	}

	err = AMQPChannel.QueueBind(
		queue.Name,   // queue name
		c.RoutingKey, // routing key
		c.Exchange,   // exchange
		false,        // nowait
		nil,          // arguments
	)
	if err != nil {
		return errors.New("Failed to bind queue: " + err.Error())
	}
	return nil
}


text:
module MyJohnDeere
  class SingleResource < Requestable
    include RESTMethods
    include JSONAttributes
    attr_accessor :deleted

    def initialize(json_object, access_token = nil)
      super(json_object, access_token)
      setup_attributes(json_object)
      self.deleted = self.links.any? { |link_hash| link_hash["rel"] == "delete" }
    end
  end
end


text:
package hu.davidp.player.lastfm.similar.artist;

import lombok.Data;

@Data
public class Links {
    private Link link;

}


text:
package predictions.auth;

import com.google.common.io.BaseEncoding;
import io.dropwizard.auth.AuthFilter;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.basic.BasicCredentialAuthFilter;
import io.dropwizard.auth.basic.BasicCredentials;

import javax.annotation.Nullable;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.SecurityContext;
import java.nio.charset.StandardCharsets;
import java.security.Principal;

@Priority(Priorities.AUTHENTICATION)
public class CommunityBasicCredentialAuthFilter
 extends AuthFilter<CommunityBasicCredentials, P> {

    private String defaultCommunity;

    private CommunityBasicCredentialAuthFilter(String defaultCommunity) {
        this.defaultCommunity = defaultCommunity;
    }

    @Override
    public void filter(ContainerRequestContext requestContext) {
       	String community = CommunityFilter.extractCommunity(requestContext.getUriInfo().getRequestUri().getHost(), defaultCommunity);
        final CommunityBasicCredentials credentials = getCredentials(community, requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION));
        if (!authenticate(requestContext, credentials, SecurityContext.BASIC_AUTH)) {
            throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));
        }
    }

    /**
     * Parses a Base64-encoded value of the `Authorization` header
     * in the form of `Basic dXNlcm5hbWU6cGFzc3dvcmQ=`.
     *
     * @param header the value of the `Authorization` header
     * @return a username and a password as {@link BasicCredentials}
     */
    @Nullable
    private CommunityBasicCredentials getCredentials(String community, String header) {
        if (header == null) {
            return null;
        }

        final int space = header.indexOf(' ');
        if (space <= 0) {
            return null;
        }

        final String method = header.substring(0, space);
        if (!prefix.equalsIgnoreCase(method)) {
            return null;
        }

        final String decoded;
        try {
            decoded = new String(BaseEncoding.base64().decode(header.substring(space + 1)), StandardCharsets.UTF_8);
        } catch (IllegalArgumentException e) {
            logger.warn("Error decoding credentials", e);
            return null;
        }

        // Decoded credentials is 'username:password'
        final int i = decoded.indexOf(':');
        if (i <= 0) {
            return null;
        }

        final String username = decoded.substring(0, i);
        final String password = decoded.substring(i + 1);
        return new CommunityBasicCredentials(community, username, password);
    }

    /**
     * Builder for {@link BasicCredentialAuthFilter}.
     *
An {@link Authenticator} must be provided during the building process.

     *
     * @param
 the principal
     */
    public static class Builder
 extends
            AuthFilterBuilder<CommunityBasicCredentials, P, CommunityBasicCredentialAuthFilter
> {

        private String defaultCommunity;

        public Builder(String defaultCommunity) {
            this.defaultCommunity = defaultCommunity;
        }

        @Override
        protected CommunityBasicCredentialAuthFilter
 newInstance() {
            return new CommunityBasicCredentialAuthFilter<>(defaultCommunity);
        }
    }
}


text:
from dpa.action import Action, ActionError
from dpa.shell.output import Output, Style, Fg, Bg
from dpa.product import Product, ProductError
from dpa.ptask.area import PTaskArea
from dpa.ptask.spec import PTaskSpec

# -----------------------------------------------------------------------------
class ProductInfoAction(Action):
    """Print information about a product."""

    name = "info"
    target_type = "product"

    # -------------------------------------------------------------------------
    @classmethod
    def setup_cl_args(cls, parser):

        parser.add_argument(
            "spec",
            nargs="?",
            default="",
            help="Print info for this product spec.",
        )

    # -------------------------------------------------------------------------
    def __init__(self, spec):
        super(ProductInfoAction, self).__init__(spec)
        self._spec = spec

    # -------------------------------------------------------------------------
    def execute(self):

        if not self.product:
            print "\nCould not determine product.\n"

        self._info_product()
        self._info_versions()

    # -------------------------------------------------------------------------
    def undo(self):
        pass

    # -------------------------------------------------------------------------
    def validate(self):

        cur_spec = PTaskArea.current().spec
        full_spec = PTaskSpec.get(self.spec, relative_to=cur_spec)

        if full_spec:
            try:
                product = Product.get(full_spec)
            except ProductError as e:
                # fall back to input spec
                try:
                    product = Product.get(self.spec)
                except ProductError:
                    raise ActionError(
                        'Could not determine product from: "{s}"'.format(
                            s=self.spec
                        )
                    )
        else:
            product = None

        self._product = product

    # -------------------------------------------------------------------------
    @property
    def spec(self):
        return self._spec

    # -------------------------------------------------------------------------
    @property
    def product(self):
        return self._product

    # -------------------------------------------------------------------------
    def _info_product(self):

        # fields:
        name = "Name"
        category = "Category"
        description = "Description"
        official = "Official"
        created = "Created"
        creator = "Creator"
        ptask = "PTask"

        output = Output()
        output.header_names = [
            name,
            category,
            description,
            official,
            created,
            creator,
            ptask,
        ]

        output.add_item(
            {
                name: self.product.name,
                category: self.product.category,
                description: self.product.description,
                official: self.product.official_version_number_padded \
                    if self.product.official_version_number != 0 else 'None',
                creator: self.product.creator_username,
                created: _datetime_format(self.product.created),
                ptask: self.product.ptask_spec,
            },
            color_all=Style.bright,
        )

        # build the title
        title = " {p.spec} ".format(p=self.product)
        output.title = title

        # dump the output as a list of key/value pairs
        output.dump()

    # -------------------------------------------------------------------------
    def _info_versions(self):

        self._versions = self.product.versions

        if len(self._versions) == 0:
            print "Found no versions for product!\n"
            return

        number = "Ver"
        published = "P"
        deprecated = "D"
        note = "Release note"
        reps = "Reps"
        creator = "Creator"
        created = "Created"

        output = Output()
        output.vertical_padding = 0
        output.vertical_separator = None
        output.table_header_separator="-"
        output.header_names = [
            published,
            number,
            note,
            reps,
            creator,
            created,
        ]

        output.set_header_alignment({
            number: "right",
            published: "right",
        })

        for version in sorted(self._versions, key=lambda v: v.number):

            is_official = version.number == self.product.official_version_number
            is_published = version.published
            is_deprecated = version.deprecated

            style = Style.dim
            if is_official or is_published:
                style = Style.normal

            output.add_item(
                {
                    number: version.number_padded,
                    note: version.release_note,
                    published: _published(is_published, is_official),
                    reps: _representations(version),
                    creator: version.creator_username,
                    created: _datetime_format(version.created),
                },
                colors={
                    published: _published_color(
                        is_published, is_official, is_deprecated),
                    number: _published_color(
                        is_published, is_official, is_deprecated),
                    note: style,
                    reps: style,
                    creator: style,
                    created: style,
                }
            )

        output.dump(output_format='table')

        print ""

# -----------------------------------------------------------------------------
def _datetime_format(datetime):
    return datetime.strftime("%Y/%m/%d %H:%M:%S")

# -----------------------------------------------------------------------------
def _published(value, official):

    if not value:
        return ""
    else:
        if official:
            indicator = ">>>"
        else:
            indicator = "*"

    return indicator

# -----------------------------------------------------------------------------
def _published_color(published, official, deprecated):

    if deprecated:
        return Fg.red + Style.dim
    elif official:
        return Fg.green + Style.bright
    elif published:
        return Fg.reset + Style.bright
    else:
        return Fg.reset + Style.dim

# -----------------------------------------------------------------------------
def _representations(version):

    reps = []
    for rep in version.representations:
        rep_str = rep.spec.replace(version.spec, "")
        reps.append(rep_str.lstrip("=").rstrip("=none"))

    return ",".join(reps)


text:
package com.bitdubai.fermat_dap_api.layer.dap_transaction.asset_issuing.exceptions;

import com.bitdubai.fermat_api.layer.DAPException;

/**
 * Created by Manuel Perez (darkpriestrelative@gmail.com) on 20/09/15.
 */
public class CantStartDigitalAssetTransactionAgentException extends DAPException {
    public static final String DEFAULT_MESSAGE = "CAN'T START DIGITAL ASSET TRANSACTION MONITOR AGENT";

    public CantStartDigitalAssetTransactionAgentException(final String message, final Exception cause, final String context, final String possibleReason) {
        super(message, cause, context, possibleReason);
    }

    public CantStartDigitalAssetTransactionAgentException(final String message, final Exception cause) {
        this(message, cause, "", "");
    }

    public CantStartDigitalAssetTransactionAgentException(final String message) {
        this(message, null);
    }

    public CantStartDigitalAssetTransactionAgentException() {
        this(DEFAULT_MESSAGE);
    }
}


text:
class PagesController < ApplicationController
  def index
    @time = Time.now
    hellos = ["Hello", "Bonjour", "Cześć", "Ciao", "Hola", "你好", "Aloha", "Salut", "Hi", "Hi there", "Hello"]
    actions = ["let's get building", "let's get moving", "let's learn together", "let's change the world", "let's build something beautiful", "let's make something meaningful", "let's shake things up"]
    @greeting = hellos[rand(hellos.length)]
    @action = actions[rand(actions.length)]
  end
end


text:
package workers

import (
	"github.com/8tomat8/GoRepost/counter"
	"github.com/8tomat8/GoRepost/task"
	"strings"
	"github.com/golang/glog"
	"github.com/8tomat8/GoRepost/logging"
)

// Handler of all incoming tasks
func Handler(t *task.Task) {
	c := counter.GetCounter()
	c.JobStarted()
	defer c.JobFinished()
	for social := range t.Destinations {
		switch social = strings.ToLower(social); social {
		case "vk":
			vk(t)
		case "fb":
		case "gp":
		case "tw":
		}
	}

	err := logging.WriteLog(t)
	if err != nil {
		glog.Error(err, t)
	}
}


text:
import { combineReducers } from 'redux';

import forms from './formsReducer';

const appReducer = combineReducers({
    forms
});

const combinedModules = (state, action) => {
    if (action.type === 'CLEAR_MODULES') {
        return appReducer(undefined, action);
    }
    return appReducer(state, action);
};

export default combinedModules;


text:
TOPDIR=../..

TESTS=errorp

# do not invoke the test program, test is run by the POSTBUILD script
TEST_TOOL=true

#----------------------------------------

errorp_TYPE=exe

errorp_SRC=errorp

errorp_LIBS=butils

errorp_POSTBUILD=./run.sh

#----------------------------------------

include $(TOPDIR)/rules.make