text:
package tools;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tenforce.exception.TenforceException;
import com.tenforce.sesame.template.SesameDatasource;
import eu.esco.demo.jobcvmatching.root.SemicRdfModel;
import eu.esco.demo.jobcvmatching.root.SemicRootConfiguration;
import eu.esco.demo.jobcvmatching.root.SparqlQuery;
import eu.esco.demo.jobcvmatching.root.service.DataService;
import eu.esco.demo.jobcvmatching.sesame.StatementIterable;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.DCTERMS;
import org.openrdf.model.vocabulary.FOAF;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.model.vocabulary.SKOS;
import org.openrdf.query.BindingSet;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

import javax.inject.Inject;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class ExportToJson {
  public static void main(String[] args) throws Exception {
    ExportToJson exportToJson = new ExportToJson();
    try (ConfigurableApplicationContext context = new SpringApplicationBuilder(SemicRootConfiguration.class).web(false).run(args)) {
      context.getAutowireCapableBeanFactory().autowireBean(exportToJson);
      exportToJson.doIt();
    }
  }

  @Inject
  @SparqlQuery(SparqlQuery.Value.allCvForCache)
  public String allCvForCacheSparqlQuery;
  @Inject
  @SparqlQuery(SparqlQuery.Value.allJvForCache)
  public String allJvForCacheSparqlQuery;
  @Inject
  private DataService dataService;
  @Inject
  private SesameDatasource sesameDatasource;

  private Map<String, Map<Object, Object>> skills = new HashMap<>();
  //  private Map<String, Map<Object, Object>> occupationsV0 = new HashMap<>();
  private Map<String, Map<Object, Object>> occupationsV1 = new HashMap<>();
  private Map<String, Map<Object, Object>> naces = new HashMap<>();

  public void doIt() throws Exception {
    Map<Object, Object> cvs = getCVs();
    Map<Object, Object> jvs = getJVs();

//    fillSkillsFromOccupations(occupationsV0, SKOS.RELATED.stringValue());
    fillSkillsFromOccupations(occupationsV1, "http://data.europa.eu/esco/model#relatedEssentialSkill");
//    occupationsV0.putAll(occupationsV1);

    fillLabels(skills);
//    fillLabels(occupationsV0);
    fillLabels(occupationsV1);
    fillLabels(naces);

    Map<String, Object> jsonObject = new HashMap<>();
    jsonObject.put("cvs", cvs);
    jsonObject.put("jvs", jvs);
    jsonObject.put("skills", skills);
    jsonObject.put("occupations", occupationsV1);
    jsonObject.put("naces", naces);

    File file = new File("C:\\Projects\\ESCO\\semic\\cache.json");
    new ObjectMapper().writeValue(file, jsonObject);

  }

  public Map<Object, Object> getJVs() {
    DataService.ConstructQueryHandler<Map<Object, Object>> handler = new DataService.ConstructQueryHandler<Map<Object, Object>>() {
      @Override
      public Map<Object, Object> handle(RepositoryConnection data, ValueFactory vf) throws Exception {
        Map<Object, Object> result = new HashMap<>();
        for (Statement statement : new StatementIterable(data.getStatements(null, RDF.TYPE, vf.createURI(SemicRdfModel.typeJV), false))) {
          Map<Object, Object> map = new HashMap<>();
          boolean hasData = updateJob(map, data, statement.getSubject());
          if (hasData) result.put(statement.getSubject().stringValue(), map);
        }
        return result;
      }
    };
    return dataService.doConstructQuery(handler, allJvForCacheSparqlQuery);
  }

  public Map<Object, Object> getCVs() {
    DataService.ConstructQueryHandler<Map<Object, Object>> handler = new DataService.ConstructQueryHandler<Map<Object, Object>>() {
      @Override
      public Map<Object, Object> handle(RepositoryConnection data, ValueFactory vf) throws Exception {
        Map<Object, Object> result = new HashMap<>();
        for (Statement statement : new StatementIterable(data.getStatements(null, RDF.TYPE, vf.createURI(SemicRdfModel.typeCV), false))) {
          Map<Object, Object> map = new HashMap<>();
          updateCV(map, data, statement.getSubject());
          result.put(statement.getSubject().stringValue(), map);
        }
        return result;
      }
    };
    return dataService.doConstructQuery(handler, allCvForCacheSparqlQuery);
  }

  private void fillLabels(final Map<String, Map<Object, Object>> map) throws Exception {
    ValueFactory vf = sesameDatasource.getValueFactory();
    DataService.SelectQueryHandler<Void> handler = new DataService.SelectQueryHandler<Void>() {
      @Override
      public void handleRow(BindingSet bindingSet, ValueFactory valueFactory) throws Exception {
        String uri = bindingSet.getValue("uri").stringValue();
        Map<Object, Object> values = map.get(uri);
        values.put("fallbackLabel", bindingSet.getValue("fallbackLabel").stringValue());
        Literal prefLabel = (Literal) bindingSet.getValue("prefLabel");
        values.put("prefLabel" + prefLabel.getLanguage(), prefLabel.getLabel());
      }

      @Override
      public Void getResult() {
        return null;
      }
    };
    String query = "select ?uri ?fallbackLabel ?prefLabel ?parent where {" +
                   "  ?uri <" + SemicRdfModel.escoPropertyFallbackLabel + "> ?fallbackLabel . " +
                   "  ?uri <" + SKOS.PREF_LABEL + "> ?prefLabel . " +
                   "}";

    for (Map.Entry<String, Map<Object, Object>> entry : map.entrySet()) {
      dataService.doSelectQuery(handler, query, new ImmutablePair<String, Value>("uri", vf.createURI(entry.getKey())));
    }
  }

  private void fillSkillsFromOccupations(final Map<String, Map<Object, Object>> occupationMap, String property) throws Exception {
    for (Map<Object, Object> occupationInfo : occupationMap.values()) {
      occupationInfo.put("skills", new HashSet());
    }
    ValueFactory vf = sesameDatasource.getValueFactory();
    DataService.SelectQueryHandler<Void> handler = new DataService.SelectQueryHandler<Void>() {
      @Override
      public void handleRow(BindingSet bindingSet, ValueFactory valueFactory) throws Exception {
        String occupationUri = bindingSet.getValue("occupation").stringValue();
        String skillUri = patchSkillUri(bindingSet.getValue("skill").stringValue());
        if (!skills.containsKey(skillUri)) skills.put(skillUri, new HashMap<>());

        Map<Object, Object> occupationInfoMap = occupationMap.get(occupationUri);
        ((Collection) occupationInfoMap.get("skills")).add(skillUri);
      }

      @Override
      public Void getResult() {
        return null;
      }
    };

    String query = "select ?occupation ?skill where {" +
                   "  ?occupation <" + property + "> ?skill . " +
                   "  ?skill <" + RDF.TYPE + "> <" + SemicRdfModel.escoTypeSkill + "> . " +
                   "}";
    for (String occupationUri : occupationMap.keySet()) {
      dataService.doSelectQuery(handler, query, new ImmutablePair<String, Value>("occupation", vf.createURI(occupationUri)));
    }
  }

  private String getFirstValue(RepositoryConnection data, Resource resource, URI property, String fallback) {
    try {
      RepositoryResult<Statement> statements = data.getStatements(resource, property, null, false);
      return statements.hasNext() ? statements.next().getObject().stringValue() : fallback;
    }
    catch (RepositoryException e) {
      throw new TenforceException(e);
    }
  }

  private String patchSkillUri(String uri) {
    if (uri.startsWith("http://data.europa.eu/esco/skill/367288;facet")) {
      return uri.replace("http://data.europa.eu/esco/skill/367288;facet", "http://data.europa.eu/esco/skill/SCG.TS.3.m.1;facet");
    }
    return uri;
  }
  private List<String> getAllValues(RepositoryConnection data, Resource resource, URI property, Map<String, Map<Object, Object>> addValuesTo) {
    List<String> result = new ArrayList<>();
    for (Statement statement : StatementIterable.list(data, resource, property, null)) {
      String value = patchSkillUri(statement.getObject().stringValue());

      result.add(value);
      if (null != addValuesTo && !addValuesTo.containsKey(value)) addValuesTo.put(value, new HashMap<>());
    }
    return result;
  }

  public void updateCV(Map<Object, Object> map, RepositoryConnection data, Resource cvURI) throws Exception {
    ValueFactory vf = data.getValueFactory();
    map.put("givenName", getFirstValue(data, cvURI, FOAF.GIVEN_NAME, StringUtils.substringAfterLast(cvURI.stringValue(), "/")));
    map.put("description", getFirstValue(data, cvURI, DCTERMS.DESCRIPTION, ""));
//    map.put("skillV0", getAllValues(data, cvURI, vf.createURI(SemicRdfModel.propertyHasSkill_v0), skills));
    map.put("skillV1", getAllValues(data, cvURI, vf.createURI(SemicRdfModel.propertyHasSkill_v1), skills));
//    map.put("occupationV0", getAllValues(data, cvURI, vf.createURI(SemicRdfModel.propertyHasOccupation_v0), occupationsV0));
    map.put("occupationV1", getAllValues(data, cvURI, vf.createURI(SemicRdfModel.propertyHasOccupation_v1), occupationsV1));
  }

  public boolean updateJob(Map<Object, Object> map, RepositoryConnection data, Resource jvURI) throws Exception {
    ValueFactory vf = data.getValueFactory();
    map.put("label", getFirstValue(data, jvURI, SKOS.PREF_LABEL, ""));
    map.put("nace", getAllValues(data, jvURI, vf.createURI(SemicRdfModel.propertyHasNace), naces));
    map.put("hiringOrganizationName", getFirstValue(data, jvURI, vf.createURI(SemicRdfModel.propertyHiringOrganizationName), ""));
    map.put("employmentType", getFirstValue(data, jvURI, vf.createURI(SemicRdfModel.propertyEmploymentType), ""));
    map.put("experienceLevel", getFirstValue(data, jvURI, vf.createURI(SemicRdfModel.propertyExperienceLevel), ""));
    map.put("geonameUri", getFirstValue(data, jvURI, vf.createURI(SemicRdfModel.propertyGeonameUri), ""));
    map.put("geonameLabel", getFirstValue(data, jvURI, vf.createURI(SemicRdfModel.propertyGeoname), ""));
    map.put("occupationalCategory", getFirstValue(data, jvURI, vf.createURI(SemicRdfModel.propertyOccupationalCategory), ""));
    map.put("description", getFirstValue(data, jvURI, DCTERMS.DESCRIPTION, ""));

//    List<String> skillsV0 = getAllValues(data, jvURI, vf.createURI(SemicRdfModel.propertyHasSkill_v0), skills);
    List<String> skillsV1 = getAllValues(data, jvURI, vf.createURI(SemicRdfModel.propertyHasSkill_v1), skills);
//    List<String> occupationsV0 = getAllValues(data, jvURI, vf.createURI(SemicRdfModel.propertyHasOccupation_v0), this.occupationsV0);
    List<String> occupationsV1 = getAllValues(data, jvURI, vf.createURI(SemicRdfModel.propertyHasOccupation_v1), this.occupationsV1);
//    map.put("skillV0", skillsV0);
    map.put("skillV1", skillsV1);
//    map.put("occupationV0", occupationsV0);
    map.put("occupationV1", occupationsV1);

//    return !skillsV0.isEmpty() && !skillsV1.isEmpty();
    return !skillsV1.isEmpty();
//    return !skillsV0.isEmpty() || !skillsV1.isEmpty() || !occupationsV0.isEmpty() || !occupationsV1.isEmpty();
  }

}


text:
<?php

namespace Webiny\Htpl\Processor;

use Webiny\Htpl\Htpl;

/**
 * Template class is the result of the Compiler class.
 *
 * @package Webiny\Htpl\Processor
 */
class Template
{
    /**
     * @var Htpl Current htpl instance
     */
    private $htpl;

    /**
     * @var string Compiled template string.
     */
    private $template;

    /**
     * @param Htpl   $htpl     Current Htpl instance.
     * @param string $template Compiled template string.
     */
    public function __construct(Htpl $htpl, $template)
    {
        $this->htpl = $htpl;
        $this->template = $template;
    }

    /**
     * Callback method used from within the compiled template to retrieve the variable value.
     *
     * @param string $key     Variable name.
     * @param array  $context Context from where the variable should be retrieved.
     *
     * @return null|mixed
     */
    public function getVar($key, $context)
    {
        if (!empty($context[$key])) {
            return $context[$key];
        } else if (strpos($key, '.') !== false) {
            $keyData = explode('.', $key);
            $value = $context;
            foreach ($keyData as $kd) {
                if(is_array($value) && is_object($value[$kd])){
                    $value = $value[$kd];
                    continue;
                }else{
                    if(is_array($value) && !empty($value[$kd])){
                        $value = $value[$kd];
                        continue;
                    }else if(is_object($value)){
                        if(!empty($value->$kd)){
                            $value = $value->$kd;
                            continue;
                        }else{
                            if(method_exists($value, 'get'.$kd)){
                                $method ='get'.$kd;
                                $value = $value->$method();
                                continue;
                            }
                            // else null
                            return null;
                        }
                    }else{
                        return null;
                    }
                }
            }
        }

        return $value;
    }

    /**
     * Get the current Htpl instance.
     *
     * @return Htpl
     */
    public function getHtplInstance()
    {
        return $this->htpl;
    }

    /**
     * Display the template.
     * Note: template scope is set to $this as it's executed within the scope of this class.
     */
    public function display()
    {
        echo $this->fetch();
    }

    /**
     * Returns the template output as a string.
     *
     * @return string
     */
    public function fetch()
    {
        // we need to assign the latest variables from within the htpl instance, just before we build the output
        $this->vars = $this->getHtplInstance()->getVars();

        ob_start();
        eval('?>' . $this->template);

        return ob_get_clean();
    }

    public function getSource()
    {
        return $this->template;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "ConstantsAndMacros.h"

typedef enum
{
	NO_SCALING,
	FIT_X,
	FIT_Y,
	FIT_XY
} eSCALING;

typedef struct
{
	GLuint widthImage;
	GLuint widthTexture;
	GLuint heightImage;
	GLuint heightTexture;
	GLfloat scaleModelX;
	GLfloat scaleModelY;
	GLfloat scaleTextureX;
	GLfloat scaleTextureY;
	GLuint bytesPerPixel;
	GLenum format;
	GLenum type;
	void* data;
	GLuint identifier;
	enum {INVALID, GENERATED, SENT_TO_GPU} state;
} Texture;

@interface OpenGLSprite : NSObject {
@private
	CGSize		screenSize;
	Vertex3D	position;
	Rotation3D	rotation;
	Scale3D		scale;
	CGSize		oldSize;
	unsigned int oldBytesPerPixel;

@protected
	UIImage*	image;
	void		*default_image;
	eSCALING	scaling;
	Texture		texture;
}
@property (nonatomic, assign) Vertex3D	position;
@property (nonatomic, assign) Rotation3D rotation;
@property (nonatomic, assign) Scale3D	scale;

- (id)initWithPath:(NSString *)path withScaling:(eSCALING)_scaling withScreenSize:(CGSize)size;
- (BOOL)ResetTexture;
- (void)drawSelfIfNeeded:(BOOL)needed;

@end


text:
package com.korotkin.lakecombine.example;

import com.korotkin.lakecombine.common.LakeData;
import com.korotkin.lakecombine.common.LakeDataChunk;

public class LakeDataExample extends LakeData<String> {
	private int max=10;
	private int i = 0;
	private int maxChunk = 10;
	public LakeDataExample(int max,int maxChunk) {
		this.max = max;
		this.maxChunk = maxChunk;
	}
	public boolean hasNext() {
		return (i<max);
	}

	public LakeDataChunk<String> next() {
		i++;
		return new LakeDataChunkExample(maxChunk);
	}
}


text:
"use strict";

module.exports = LotOpen;

const q        = require("q"),
      _        = require("lodash"),
      Bidding  = require("./bidding"),
      TurnOver = require("./turn-over");

function LotOpen(gameData, choiceProvider, player) {
  let self = this;

  function go() {
    if(_.size(player.cars) === 0)
      return q(doneState());

    return choiceProvider.allowBids(player).then(nextState);
  }
  this.go = go;

  function nextState(offer) {
    if(offer.car) {
      let returnState = self;
      return new Bidding(gameData, choiceProvider, offer,
                          returnState);
    } else {
      return doneState();
    }
  }

  function doneState() {
    return new TurnOver(gameData, choiceProvider, player);
  }
}


text:
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Billing.Models;
using Azure.ResourceManager.Resources;

namespace Azure.ResourceManager.Billing
{
    /// <summary>
    /// A Class representing a BillingSubscription along with the instance operations that can be performed on it.
    /// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="BillingSubscriptionResource" />
    /// from an instance of <see cref="ArmClient" /> using the GetBillingSubscriptionResource method.
    /// Otherwise you can get one from its parent resource <see cref="TenantResource" /> using the GetBillingSubscription method.
    /// </summary>
    public partial class BillingSubscriptionResource : ArmResource
    {
        /// <summary> Generate the resource identifier of a <see cref="BillingSubscriptionResource"/> instance. </summary>
        public static ResourceIdentifier CreateResourceIdentifier(string billingAccountName, string billingSubscriptionName)
        {
            var resourceId = $"/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}";
            return new ResourceIdentifier(resourceId);
        }

        private readonly ClientDiagnostics _billingSubscriptionClientDiagnostics;
        private readonly BillingSubscriptionsRestOperations _billingSubscriptionRestClient;
        private readonly BillingSubscriptionData _data;

        /// <summary> Initializes a new instance of the <see cref="BillingSubscriptionResource"/> class for mocking. </summary>
        protected BillingSubscriptionResource()
        {
        }

        /// <summary> Initializes a new instance of the <see cref = "BillingSubscriptionResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="data"> The resource that is the target of operations. </param>
        internal BillingSubscriptionResource(ArmClient client, BillingSubscriptionData data) : this(client, data.Id)
        {
            HasData = true;
            _data = data;
        }

        /// <summary> Initializes a new instance of the <see cref="BillingSubscriptionResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="id"> The identifier of the resource that is the target of operations. </param>
        internal BillingSubscriptionResource(ArmClient client, ResourceIdentifier id) : base(client, id)
        {
            _billingSubscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Billing", ResourceType.Namespace, Diagnostics);
            TryGetApiVersion(ResourceType, out string billingSubscriptionApiVersion);
            _billingSubscriptionRestClient = new BillingSubscriptionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, billingSubscriptionApiVersion);
#if DEBUG
			ValidateResourceId(Id);
#endif
        }

        /// <summary> Gets the resource type for the operations. </summary>
        public static readonly ResourceType ResourceType = "Microsoft.Billing/billingAccounts/billingSubscriptions";

        /// <summary> Gets whether or not the current instance has data. </summary>
        public virtual bool HasData { get; }

        /// <summary> Gets the data representing this Feature. </summary>
        /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
        public virtual BillingSubscriptionData Data
        {
            get
            {
                if (!HasData)
                    throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
                return _data;
            }
        }

        internal static void ValidateResourceId(ResourceIdentifier id)
        {
            if (id.ResourceType != ResourceType)
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
        }

        /// <summary>
        /// Gets a subscription by its ID. The operation is currently supported for billing accounts with agreement type Microsoft Customer Agreement, Microsoft Partner Agreement and Microsoft Online Services Program.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}
        /// Operation Id: BillingSubscriptions_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<BillingSubscriptionResource>> GetAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Get");
            scope.Start();
            try
            {
                var response = await _billingSubscriptionRestClient.GetAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new BillingSubscriptionResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Gets a subscription by its ID. The operation is currently supported for billing accounts with agreement type Microsoft Customer Agreement, Microsoft Partner Agreement and Microsoft Online Services Program.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}
        /// Operation Id: BillingSubscriptions_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<BillingSubscriptionResource> Get(CancellationToken cancellationToken = default)
        {
            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Get");
            scope.Start();
            try
            {
                var response = _billingSubscriptionRestClient.Get(Id.Parent.Name, Id.Name, cancellationToken);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new BillingSubscriptionResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Cancels a billing subscription.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}
        /// Operation Id: BillingSubscriptions_Delete
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
        {
            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Delete");
            scope.Start();
            try
            {
                var response = await _billingSubscriptionRestClient.DeleteAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
                var operation = new BillingArmOperation(_billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateDeleteRequest(Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Cancels a billing subscription.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}
        /// Operation Id: BillingSubscriptions_Delete
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default)
        {
            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Delete");
            scope.Start();
            try
            {
                var response = _billingSubscriptionRestClient.Delete(Id.Parent.Name, Id.Name, cancellationToken);
                var operation = new BillingArmOperation(_billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateDeleteRequest(Id.Parent.Name, Id.Name).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletionResponse(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Updates the properties of a billing subscription.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}
        /// Operation Id: BillingSubscriptions_Update
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="data"> Request parameters that are provided to the update billing subscription operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual async Task<ArmOperation<BillingSubscriptionResource>> UpdateAsync(WaitUntil waitUntil, BillingSubscriptionData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Update");
            scope.Start();
            try
            {
                var response = await _billingSubscriptionRestClient.UpdateAsync(Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false);
                var operation = new BillingArmOperation<BillingSubscriptionResource>(new BillingSubscriptionOperationSource(Client), _billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateUpdateRequest(Id.Parent.Name, Id.Name, data).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Updates the properties of a billing subscription.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}
        /// Operation Id: BillingSubscriptions_Update
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="data"> Request parameters that are provided to the update billing subscription operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual ArmOperation<BillingSubscriptionResource> Update(WaitUntil waitUntil, BillingSubscriptionData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Update");
            scope.Start();
            try
            {
                var response = _billingSubscriptionRestClient.Update(Id.Parent.Name, Id.Name, data, cancellationToken);
                var operation = new BillingArmOperation<BillingSubscriptionResource>(new BillingSubscriptionOperationSource(Client), _billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateUpdateRequest(Id.Parent.Name, Id.Name, data).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletion(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Moves a subscription's charges to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}/move
        /// Operation Id: BillingSubscriptions_Move
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="content"> Request parameters that are provided to the move subscription operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual async Task<ArmOperation<BillingSubscriptionResource>> MoveAsync(WaitUntil waitUntil, BillingSubscriptionMoveContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Move");
            scope.Start();
            try
            {
                var response = await _billingSubscriptionRestClient.MoveAsync(Id.Parent.Name, Id.Name, content, cancellationToken).ConfigureAwait(false);
                var operation = new BillingArmOperation<BillingSubscriptionResource>(new BillingSubscriptionOperationSource(Client), _billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateMoveRequest(Id.Parent.Name, Id.Name, content).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Moves a subscription's charges to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}/move
        /// Operation Id: BillingSubscriptions_Move
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="content"> Request parameters that are provided to the move subscription operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual ArmOperation<BillingSubscriptionResource> Move(WaitUntil waitUntil, BillingSubscriptionMoveContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Move");
            scope.Start();
            try
            {
                var response = _billingSubscriptionRestClient.Move(Id.Parent.Name, Id.Name, content, cancellationToken);
                var operation = new BillingArmOperation<BillingSubscriptionResource>(new BillingSubscriptionOperationSource(Client), _billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateMoveRequest(Id.Parent.Name, Id.Name, content).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletion(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}/validateMoveEligibility
        /// Operation Id: BillingSubscriptions_ValidateMoveEligibility
        /// </summary>
        /// <param name="content"> Request parameters that are provided to the validate move eligibility operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual async Task<Response<BillingSubscriptionValidateMoveEligibilityResult>> ValidateMoveEligibilityAsync(BillingSubscriptionMoveContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.ValidateMoveEligibility");
            scope.Start();
            try
            {
                var response = await _billingSubscriptionRestClient.ValidateMoveEligibilityAsync(Id.Parent.Name, Id.Name, content, cancellationToken).ConfigureAwait(false);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}/validateMoveEligibility
        /// Operation Id: BillingSubscriptions_ValidateMoveEligibility
        /// </summary>
        /// <param name="content"> Request parameters that are provided to the validate move eligibility operation. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual Response<BillingSubscriptionValidateMoveEligibilityResult> ValidateMoveEligibility(BillingSubscriptionMoveContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.ValidateMoveEligibility");
            scope.Start();
            try
            {
                var response = _billingSubscriptionRestClient.ValidateMoveEligibility(Id.Parent.Name, Id.Name, content, cancellationToken);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Merges the billing subscription provided in the request with a target billing subscription.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}/merge
        /// Operation Id: BillingSubscriptions_Merge
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="content"> Request parameters that are provided to merge the two billing subscriptions. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual async Task<ArmOperation<BillingSubscriptionResource>> MergeAsync(WaitUntil waitUntil, BillingSubscriptionMergeContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Merge");
            scope.Start();
            try
            {
                var response = await _billingSubscriptionRestClient.MergeAsync(Id.Parent.Name, Id.Name, content, cancellationToken).ConfigureAwait(false);
                var operation = new BillingArmOperation<BillingSubscriptionResource>(new BillingSubscriptionOperationSource(Client), _billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateMergeRequest(Id.Parent.Name, Id.Name, content).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Merges the billing subscription provided in the request with a target billing subscription.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}/merge
        /// Operation Id: BillingSubscriptions_Merge
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="content"> Request parameters that are provided to merge the two billing subscriptions. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual ArmOperation<BillingSubscriptionResource> Merge(WaitUntil waitUntil, BillingSubscriptionMergeContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Merge");
            scope.Start();
            try
            {
                var response = _billingSubscriptionRestClient.Merge(Id.Parent.Name, Id.Name, content, cancellationToken);
                var operation = new BillingArmOperation<BillingSubscriptionResource>(new BillingSubscriptionOperationSource(Client), _billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateMergeRequest(Id.Parent.Name, Id.Name, content).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletion(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Splits a subscription into a new subscription with quantity less than current subscription quantity and not equal to 0.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}/split
        /// Operation Id: BillingSubscriptions_Split
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="content"> Request parameters that are provided to split the billing subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual async Task<ArmOperation<BillingSubscriptionResource>> SplitAsync(WaitUntil waitUntil, BillingSubscriptionSplitContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Split");
            scope.Start();
            try
            {
                var response = await _billingSubscriptionRestClient.SplitAsync(Id.Parent.Name, Id.Name, content, cancellationToken).ConfigureAwait(false);
                var operation = new BillingArmOperation<BillingSubscriptionResource>(new BillingSubscriptionOperationSource(Client), _billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateSplitRequest(Id.Parent.Name, Id.Name, content).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Splits a subscription into a new subscription with quantity less than current subscription quantity and not equal to 0.
        /// Request Path: /providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{billingSubscriptionName}/split
        /// Operation Id: BillingSubscriptions_Split
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="content"> Request parameters that are provided to split the billing subscription. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
        public virtual ArmOperation<BillingSubscriptionResource> Split(WaitUntil waitUntil, BillingSubscriptionSplitContent content, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(content, nameof(content));

            using var scope = _billingSubscriptionClientDiagnostics.CreateScope("BillingSubscriptionResource.Split");
            scope.Start();
            try
            {
                var response = _billingSubscriptionRestClient.Split(Id.Parent.Name, Id.Name, content, cancellationToken);
                var operation = new BillingArmOperation<BillingSubscriptionResource>(new BillingSubscriptionOperationSource(Client), _billingSubscriptionClientDiagnostics, Pipeline, _billingSubscriptionRestClient.CreateSplitRequest(Id.Parent.Name, Id.Name, content).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletion(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
    }
}


text:
namespace FakeItEasy
{
    internal interface IArgumentConstraintManagerFactory
    {
        IArgumentConstraintManager<T> Create<T>();
    }
}


text:
'use strict';
var setup = require('../common/data-setup');

describe('The players in a world', function () {
  describe('when there are no players', function () {
    beforeEach(function (done) {
      setup.purgeData()
        .then(browser.get('playersMap'))
        .then(done);
      setup.addWorld('Tiger', 'Tiger')
        .then(browser.get('worlds/Tiger/players'));
      element(by.model('newPlayer.name')).sendKeys('Nancy');
      element(by.model('newPlayer.email')).sendKeys('nancy@gmail.com');

    });

    it('can add a new team member', function () {
      element(by.model('newPlayer._team')).sendKeys('/teamA');
      element(by.id('addPlayer')).click();

      var players = element.all(by.repeater('player in players'));

      expect(players.count()).toEqual(1);
    });

    it('will not save if team url is not valid', function () {
      element(by.model('newPlayer._team')).sendKeys('/');
      element(by.id('addPlayer')).click();

      var players = element.all(by.repeater('player in players'));

      expect(players.count()).toEqual(0);
    });

    it('will not update team url if not valid', function () {
      element(by.model('newPlayer._team')).sendKeys('/teamA');
      element(by.id('addPlayer')).click();
      var players = element.all(by.repeater('player in players'));

      expect(players.count()).toEqual(1);

      element(by.model('player._team')).click().clear().sendKeys('/');
      element(by.id('updatePlayer')).click();

      expect(element(by.className('message ng-binding error')).getText()).toBe('Check team url of player. Update not successful.')
    });
  });
});


text:
from __future__ import unicode_literals
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db import models

class ArticlesManager(models.Manager):
    """Manager for posts. handle articles."""

    def requested_objects(self, request, page=None, queryset=None):
        if not queryset:
            queryset = self.all()
        posts_list = queryset.filter(status=self.model.PUBLISHED).order_by('-created')
        paginator = Paginator(posts_list, 5)
        if page is None:
            page = request.GET.get('page')
        try:
            posts = paginator.page(page)
        except PageNotAnInteger:
            posts = paginator.page(1)
        except EmptyPage:
            posts = paginator.page(paginator.num_pages)
        return posts


text:
package water.api;

import water.H2O;
import water.Iced;
import water.TimeLine;
import water.api.schemas3.TimelineV3;
import water.init.TimelineSnapshot;

/** UDP Timeline
 * Created by tomasnykodym on 6/5/14.
 */
public class TimelineHandler extends Handler {
  public static final class Timeline extends Iced {
    public TimelineSnapshot snapshot;
  }

  // TODO: should return a base class for TimelineVx
  @SuppressWarnings("unused") // called through reflection by RequestServer
  public TimelineV3 fetch(int version, TimelineV3 s) {
    Timeline t = s.createAndFillImpl();
    t.snapshot = new TimelineSnapshot(H2O.CLOUD,TimeLine.system_snapshot());
    return s.fillFromImpl(t);
  }
}


text:
//
//  HMHomeViewController.m
//  黑马微博
//
//  Created by apple on 14-7-3.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import "HMHomeViewController.h"
#import "HMOneViewController.h"
#import "HMTitleButton.h"
#import "HMPopMenu.h"
#import "HMAccountTool.h"
#import "HMAccount.h"
#import "UIImageView+WebCache.h"
#import "HMStatus.h"
#import "HMStatusFrame.h"
#import "HMUser.h"
#import "MJExtension.h"
#import "HMLoadMoreFooter.h"
#import "HMStatusTool.h"
#import "HMUserTool.h"
#import "HMStatusCell.h"

@interface HMHomeViewController () <HMPopMenuDelegate>
/**
 *  微博数组(存放着所有的微博frame数据)
 */
@property (nonatomic, strong) NSMutableArray *statusFrames;

@property (nonatomic, weak) UIRefreshControl *refreshControl;
@property (nonatomic, weak) HMLoadMoreFooter *footer;
@property (nonatomic, weak) HMTitleButton *titleButton;
@end

@implementation HMHomeViewController

#pragma mark - 初始化
- (NSMutableArray *)statusFrames
{
    if (_statusFrames == nil) {
        _statusFrames = [NSMutableArray array];
    }
    return _statusFrames;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.backgroundColor = HMColor(211, 211, 211);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    // 设置导航栏的内容
    [self setupNavBar];

    // 集成刷新控件
    [self setupRefresh];

    // 获得用户信息
    [self setupUserInfo];
}

/**
 *  获得用户信息
 */
- (void)setupUserInfo
{
    // 1.封装请求参数
    HMUserInfoParam *param = [HMUserInfoParam param];
    param.uid = [HMAccountTool account].uid;

    // 2.加载用户信息
    [HMUserTool userInfoWithParam:param success:^(HMUserInfoResult *user) {
         // 设置用户的昵称为标题
         [self.titleButton setTitle:user.name forState:UIControlStateNormal];

         // 存储帐号信息
         HMAccount *account = [HMAccountTool account];
         account.name = user.name;
         [HMAccountTool save:account];
    } failure:^(NSError *error) {
        HMLog(@"请求失败-------%@", error);
    }];
}

/**
 *  设置导航栏的内容
 */
- (void)setupNavBar
{
    // 设置导航栏按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" highImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendSearch)];

    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_pop" highImageName:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];

    // 设置导航栏中间的标题按钮
    HMTitleButton *titleButton = [[HMTitleButton alloc] init];
    // 设置尺寸
    titleButton.height = 35;
    // 设置文字
    NSString *name = [HMAccountTool account].name;
    [titleButton setTitle:name ? name : @"首页" forState:UIControlStateNormal];
    // 设置图标
    [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    // 设置背景
    [titleButton setBackgroundImage:[UIImage resizedImage:@"navigationbar_filter_background_highlighted"] forState:UIControlStateHighlighted];
    // 监听按钮点击
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleButton;
    self.titleButton = titleButton;
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.添加下拉刷新控件
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [self.tableView addSubview:refreshControl];
    self.refreshControl = refreshControl;

    // 2.监听状态
    [refreshControl addTarget:self action:@selector(refreshControlStateChange:) forControlEvents:UIControlEventValueChanged];

    // 3.让刷新控件自动进入刷新状态
    [refreshControl beginRefreshing];

    // 4.加载数据
    [self refreshControlStateChange:refreshControl];

    // 5.添加上拉加载更多控件
    HMLoadMoreFooter *footer = [HMLoadMoreFooter footer];
    self.tableView.tableFooterView = footer;
    self.footer = footer;
}

/**
 *  当下拉刷新控件进入刷新状态(转圈圈)的时候会自动调用
 */
- (void)refreshControlStateChange:(UIRefreshControl *)refreshControl
{
    [self loadNewStatuses:refreshControl];
}

#pragma mark - 刷新
- (void)refresh:(BOOL)fromSelf
{
    if (self.tabBarItem.badgeValue) { // 有数字
        // 转圈圈
        [self.refreshControl beginRefreshing];

        // 刷新数据
        [self loadNewStatuses:self.refreshControl];
    } else if (fromSelf) { // 没有数字
        // 让表格回到最顶部
        NSIndexPath *firstRow = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView scrollToRowAtIndexPath:firstRow atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

#pragma mark - 加载微博数据

/**
 *  根据微博模型数组 转成 微博frame模型数据
 *
 *  @param statuses 微博模型数组
 *
 */
- (NSArray *)statusFramesWithStatuses:(NSArray *)statuses
{
    NSMutableArray *frames = [NSMutableArray array];
    for (HMStatus *status in statuses) {
        HMStatusFrame *frame = [[HMStatusFrame alloc] init];
        // 传递微博模型数据,计算所有子控件的frame
        frame.status = status;
        [frames addObject:frame];
    }
    return frames;
}

/**
 *  加载最新的微博数据
 */
- (void)loadNewStatuses:(UIRefreshControl *)refreshControl
{
    // 1.封装请求参数
    HMHomeStatusesParam *param = [HMHomeStatusesParam param];
    HMStatusFrame *firstStatusFrame =  [self.statusFrames firstObject];
    HMStatus *firstStatus = firstStatusFrame.status;
    if (firstStatus) {
        param.since_id = @([firstStatus.idstr longLongValue]);
    }

    // 2.加载微博数据
    [HMStatusTool homeStatusesWithParam:param success:^(HMHomeStatusesResult *result) {
        // 获得最新的微博frame数组
        NSArray *newFrames = [self statusFramesWithStatuses:result.statuses];

         // 将新数据插入到旧数据的最前面
         NSRange range = NSMakeRange(0, newFrames.count);
         NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
         [self.statusFrames insertObjects:newFrames atIndexes:indexSet];

         // 重新刷新表格
         [self.tableView reloadData];

         // 让刷新控件停止刷新(恢复默认的状态)
         [refreshControl endRefreshing];

         // 提示用户最新的微博数量
         [self showNewStatusesCount:newFrames.count];
    } failure:^(NSError *error) {
         HMLog(@"请求失败--%@", error);
         // 让刷新控件停止刷新(恢复默认的状态)
         [refreshControl endRefreshing];
    }];
}

/**
 *  加载更多的微博数据
 */
- (void)loadMoreStatuses
{
    // 1.封装请求参数
    HMHomeStatusesParam *param = [HMHomeStatusesParam param];
    HMStatusFrame *lastStatusFrame =  [self.statusFrames lastObject];
    HMStatus *lastStatus = lastStatusFrame.status;
    if (lastStatus) {
        param.max_id = @([lastStatus.idstr longLongValue] - 1);
    }

    // 2.加载微博数据
    [HMStatusTool homeStatusesWithParam:param success:^(HMHomeStatusesResult *result) {
        // 获得最新的微博frame数组
        NSArray *newFrames = [self statusFramesWithStatuses:result.statuses];

         // 将新数据插入到旧数据的最后面
         [self.statusFrames addObjectsFromArray:newFrames];

         // 重新刷新表格
         [self.tableView reloadData];

         // 让刷新控件停止刷新(恢复默认的状态)
         [self.footer endRefreshing];
    } failure:^(NSError *error) {
        HMLog(@"请求失败--%@", error);
        // 让刷新控件停止刷新(恢复默认的状态)
        [self.footer endRefreshing];
    }];
}

/**
 *  提示用户最新的微博数量
 *
 *  @param count 最新的微博数量
 */
- (void)showNewStatusesCount:(int)count
{
    // 0.清零提醒数字
    [UIApplication sharedApplication].applicationIconBadgeNumber -= self.tabBarItem.badgeValue.intValue;
    self.tabBarItem.badgeValue = nil;

    // 1.创建一个UILabel
    UILabel *label = [[UILabel alloc] init];

    // 2.显示文字
    if (count) {
        label.text = [NSString stringWithFormat:@"共有%d条新的微博数据", count];
    } else {
        label.text = @"没有最新的微博数据";
    }

    // 3.设置背景
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithName:@"timeline_new_status_background"]];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];

    // 4.设置frame
    label.width = self.view.width;
    label.height = 35;
    label.x = 0;
    label.y = 64 - label.height;

    // 5.添加到导航控制器的view
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];

    // 6.动画
    CGFloat duration = 0.75;
    [UIView animateWithDuration:duration animations:^{
        // 往下移动一个label的高度
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
    } completion:^(BOOL finished) { // 向下移动完毕

        // 延迟delay秒后,再执行动画
        CGFloat delay = 1.0;

        [UIView animateWithDuration:duration delay:delay options:UIViewAnimationOptionCurveEaseInOut animations:^{
            // 恢复到原来的位置
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {

            // 删除控件
            [label removeFromSuperview];
        }];
    }];
}

#pragma mark - 弹出菜单协议
- (void)popMenuDidDismissed:(HMPopMenu *)popMenu
{
    HMTitleButton *titleButton = (HMTitleButton *)self.navigationItem.titleView;
    [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
}

#pragma mark - 私有方法
/**
 *  点击标题点击
 */
- (void)titleClick:(UIButton *)titleButton
{
    // 换成箭头向上
    [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_up"] forState:UIControlStateNormal];

    // 弹出菜单
    UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
    button.backgroundColor = [UIColor blueColor];

    HMPopMenu *menu = [[HMPopMenu alloc ] initWithContentView:nil];
    menu.delegate = self;
    menu.arrowPosition = HMPopMenuArrowPositionCenter;
    //    menu.dimBackground = YES;
    [menu showInRect:CGRectMake(100, 0, 200, 480)];
}

/**
 *  点击了遮盖
 */
- (void)coverClick
{
    HMLog(@"coverClick---");
}

- (void)friendSearch
{
    HMLog(@"friendSearch---");

    HMOneViewController *one = [[HMOneViewController alloc] init];
    one.title = @"OneVc";
    [self.navigationController pushViewController:one animated:YES];
}

- (void)pop
{
    HMLog(@"pop---");

    [self.titleButton setTitle:@"哈哈哈" forState:UIControlStateNormal];
}

#pragma mark - Table view 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning 为什么写在这里:为了监听tableView每次显示数据的过程
    self.footer.hidden = self.statusFrames.count == 0;
    return self.statusFrames.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HMStatusCell *cell = [HMStatusCell cellWithTableView:tableView];

    cell.statusFrame = self.statusFrames[indexPath.row];

    return cell;
}

#pragma mark - tableView代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIViewController *newVc = [[UIViewController alloc] init];
    newVc.view.backgroundColor = [UIColor redColor];
    newVc.title = @"新控制器";
    [self.navigationController pushViewController:newVc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.statusFrames.count <= 0 || self.footer.isRefreshing) return;

    // 1.差距
    CGFloat delta = scrollView.contentSize.height - scrollView.contentOffset.y;
    // 刚好能完整看到footer的高度
    CGFloat sawFooterH = self.view.height - self.tabBarController.tabBar.height;

    // 2.如果能看见整个footer
    if (delta <= (sawFooterH - 0)) {
        // 进入上拉刷新状态
        [self.footer beginRefreshing];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 加载更多的微博数据
            [self loadMoreStatuses];
        });
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HMStatusFrame *frame = self.statusFrames[indexPath.row];
    return frame.cellHeight;
}
@end


text:
package org.instantlogic.designer.event;

import org.instantlogic.designer.DesignerApplicationGenerator;
import org.instantlogic.designer.EventDesign;

public class AddEntityEventGenerator extends EventDesign {

	public static AddEntityEventGenerator EVENT = new AddEntityEventGenerator();

	private AddEntityEventGenerator() {
		DesignerApplicationGenerator.APPLICATION.addToEvents(this);
		setName("AddEntity");
	}
}


text:
package io.blueocean.ath.util;

import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.common.FileSource;
import com.github.tomakehurst.wiremock.common.Gzip;
import com.github.tomakehurst.wiremock.common.SingleRootFileSource;
import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.extension.ResponseTransformer;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.HttpHeaders;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.Response;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.google.common.collect.Iterables;
import org.apache.log4j.Logger;

import java.io.File;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;

/**
 * @author cliffmeyers
 */
public class WireMockBase {
    private static Logger logger = Logger.getLogger(WireMockBase.class);

    protected static String getServerUrl(WireMockRule rule) {
        return String.format("http://localhost:%s/", rule.port());
    }

    protected static WireMockRule createWireMockServerRule(String resourceFolder, String baseUrl) {
        ReplaceUrlTransformer replaceUrlTransformer = new ReplaceUrlTransformer();

        final WireMockRule rule = new WireMockRule(
            wireMockConfig()
                .dynamicPort()
                .dynamicHttpsPort()
                .usingFilesUnderClasspath(resourceFolder)
                .extensions(
                    new GzipDecompressTransformer(),
                    replaceUrlTransformer
                )
        );

        String mappingsPath = String.format("src/test/resources/%s/mappings", resourceFolder);
        String filesPath = String.format("src/test/resources/%s/__files", resourceFolder);

        new File(mappingsPath).mkdirs();
        new File(filesPath).mkdirs();

        rule.enableRecordMappings(
            new SingleRootFileSource(mappingsPath),
            new SingleRootFileSource(filesPath)
        );

        rule.stubFor(
            WireMock.get(urlMatching(".*"))
                .atPriority(10)
                .willReturn(aResponse().proxiedFrom(baseUrl)));

        replaceUrlTransformer.configure(baseUrl, rule);

        return rule;
    }

    /**
     * Decompresses the request body if gzipped.
     * In most cases this should be added as the first ResponseTransformer in the "extensions" list.
     */
    static class GzipDecompressTransformer extends ResponseTransformer {

        @Override
        public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
            // if gzipped, ungzip they body and discard the Content-Encoding header
            if (response.getHeaders().getHeader("Content-Encoding").containsValue("gzip")) {
                Iterable<HttpHeader> headers = Iterables.filter(
                    response.getHeaders().all(),
                    (HttpHeader header) -> header != null && !header.keyEquals("Content-Encoding") && !header.containsValue("gzip")
                );
                return Response.Builder.like(response)
                    .but()
                    .body(Gzip.unGzip(response.getBody()))
                    .headers(new HttpHeaders(headers))
                    .build();
            }
            return response;
        }

        @Override
        public String getName() {
            return "gzip";
        }
    }

    static class ReplaceUrlTransformer extends ResponseTransformer {

        private String sourceUrl;
        private WireMockRule rule;

        public void configure(String sourceUrl, WireMockRule rule) {
            this.sourceUrl = sourceUrl.endsWith("/") ? sourceUrl : String.format("%s/", sourceUrl);
            this.rule = rule;
        }

        @Override
        public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
            if ("application/json"
                .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) {
                return Response.Builder.like(response)
                    .but()
                    .body(response.getBodyAsString().replace(sourceUrl, getServerUrl(rule)))
                    .build();
            }
            return response;
        }

        @Override
        public String getName() {
            return "replace-url";
        }
    }

    static class NoOpLoggingTransformer extends ResponseTransformer {

        @Override
        public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
            String url = request.getUrl();
            StringBuilder requestHeaders = new StringBuilder();
            StringBuilder responseHeaders = new StringBuilder();

            for (HttpHeader header : request.getHeaders().all()) {
                requestHeaders.append(String.format("\nrequest header %s %s", header.key(), header.values()));
            }

            for (HttpHeader header : response.getHeaders().all()) {
                responseHeaders.append(String.format("\nresponse header %s %s", header.key(), header.values()));
            }

            logger.info(String.format("----> begin serving %s response fromProxy=%s for url=%s", response.getStatus(), response.isFromProxy(), url));
            logger.info(requestHeaders.toString());
            logger.info(String.format("----> end request headers, begin response headers for url=%s", url));
            logger.info(responseHeaders.toString());
            logger.info("----> end response headers");
            logger.info(String.format("----> begin response body for url=%s", url));
            logger.info(response.getBodyAsString());
            logger.info("----> end response body");

            return response;
        }

        @Override
        public String getName() {
            return "no-op-logging";
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace P01_HospitalDatabase.Data.Models
{
    public class Diagnose
    {
        [Key]
        public int DiagnoseId { get; set; }

        [Column(TypeName = "nvarchar(50)")]
        public string Name { get; set; }

        [Column(TypeName = "nvarchar(250)")]
        public string Comments { get; set; }

        public int PatientId { get; set; }
        public virtual Patient Patient { get; set; }
    }
}


text:
RSpec.describe NipposController do
  describe 'GET new' do
    it 'returns OK and shows template' do
      get :new
      expect(response).to have_http_status(:success)
      expect(assigns(:nippo)).to be_present
      expect(assigns(:nippo).body).to eq current_user.template.body
      expect(assigns(:nippo).reported_for).to be_present
    end
  end

  describe 'POST create' do
    it 'creates new nippo', :vcr do
      expect do
        post :create, nippo: {
          reported_for: Time.zone.today,
          body: FFaker::Lorem.paragraph,
        }
      end.to change(Nippo, :count).by(1)
    end
  end

  describe 'GET show' do
    let(:nippo) { FG.create(:nippo) }

    it 'shows nippo' do
      get :show, id: nippo.id
      expect(assigns(:nippo)).to eq nippo
    end

    it 'creates reaction object and sets pv as 1' do
      get :show, id: nippo.id
      expect(Reaction.find_by(user: current_user, nippo: nippo).page_view).to eq 1
    end

    it 'increment existing reaction page view' do
      get :show, id: nippo.id
      expect { get :show, id: nippo.id }
        .to change { Reaction.find_by(user: current_user, nippo: nippo).page_view }.by(1)
    end
  end
end


text:
@implementation MSSCircleLabel

- (void)drawRect:(CGRect)rect
{
    if(_isSelected)
    {
        [MSS_SelectBackgroundColor setFill];
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path addArcWithCenter:CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2) radius:self.frame.size.height / 2 startAngle:0.0 endAngle:180.0 clockwise:YES];
        [path fill];
    }
    [super drawRect:rect];
}

- (void)setIsSelected:(BOOL)isSelected
{
    _isSelected = isSelected;
    [self setNeedsDisplay];
}

@end


text:
class AddAuthorsLockedToBoards < ActiveRecord::Migration[5.2]
  def up
    add_column :boards, :authors_locked, :boolean, default: true
    locked_boards = BoardAuthor.select(:board_id).distinct.pluck(:board_id)
    Board.where.not(id: locked_boards).update_all(authors_locked: false)

    rename_column :indexes, :open_to_anyone, :authors_locked
    change_column_default :indexes, :authors_locked, true
    Index.all.each { |index| index.update(authors_locked: !index.authors_locked) }
  end

  def down
    remove_column :boards, :authors_locked, :boolean
    Index.all.each { |index| index.update(authors_locked: !index.authors_locked) }
    change_column_default :indexes, :authors_locked, false
    rename_column :indexes, :authors_locked, :open_to_anyone
  end
end


text:
package fr.bmartel.protocol.wlan.frame.management.element.subelement;

import fr.bmartel.protocol.wlan.frame.management.element.IWlanSubElement;
import fr.bmartel.protocol.wlan.frame.management.element.subelement.inter.IHtCapabilityInformation;

/**
 * Ht informations sub element of HT capabilities element
 *
 *
 * @author Bertrand Martel
 *
 */
public class HtCapabilityInformation implements IWlanSubElement,IHtCapabilityInformation {

	/**
	 * guard interval defined for 20Mhz band in 400ns
	 */
	private boolean supportShortGi20Mhz = false;

	/**
	 * guard interval defined for 40Mhz band in 400ns
	 */
	private boolean supportShortGi40Mhz = false;

	/**
	 * Set to 0 if only 20 MHz operation is supported<br/>
	 * Set to 1 if both 20 MHz and 40 MHz operation is supported
	 */
	private boolean supportedChannelWidthSet = false;

	public HtCapabilityInformation(byte[] data) {
		supportShortGi20Mhz = ((data[0] & 0x40) != 0);
		supportShortGi40Mhz = ((data[0] & 0x20) != 0);
		supportedChannelWidthSet = ((data[0] & 0b01000000) != 0);
	}

	@Override
	public boolean isSupportShortGi20Mhz() {
		return supportShortGi20Mhz;
	}

	@Override
	public boolean isSupportShortGi40Mhz() {
		return supportShortGi40Mhz;
	}

	@Override
	public boolean isSupportedChannelWidthSet() {
		return supportedChannelWidthSet;
	}
}


text:
"""django-cms plugin for the ``document_library`` app."""
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _

from . import models

class DocumentLibraryPlugin(CMSPluginBase):
    model = models.DocumentPlugin
    name = _('Document Library Plugin')
    render_template = "document_library/document_library_plugin.html"

    def render(self, context, instance, placeholder):
        context.update({
            'document': instance.document,
            'categories': models.DocumentCategory.objects.all(),
        })
        return context

plugin_pool.register_plugin(DocumentLibraryPlugin)


text:
class OSGWidget : public QOpenGLWidget
{
  Q_OBJECT

public:
  OSGWidget( QWidget* parent = 0,
             Qt::WindowFlags f = 0 );

  virtual ~OSGWidget();

protected:

  virtual void paintEvent( QPaintEvent* paintEvent );
  virtual void paintGL();
  virtual void resizeGL( int width, int height );

  virtual void keyPressEvent( QKeyEvent* event );
  virtual void keyReleaseEvent( QKeyEvent* event );

  virtual void mouseMoveEvent( QMouseEvent* event );
  virtual void mousePressEvent( QMouseEvent* event );
  virtual void mouseReleaseEvent( QMouseEvent* event );
  virtual void wheelEvent( QWheelEvent* event );

  virtual bool event( QEvent* event );

private:

  virtual void onHome();
  virtual void onResize( int width, int height );

  osgGA::EventQueue* getEventQueue() const;

  osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> graphicsWindow_;
  osg::ref_ptr<osgViewer::CompositeViewer> viewer_;

  QPoint selectionStart_;
  QPoint selectionEnd_;

  bool selectionActive_;
  bool selectionFinished_;

  void processSelection();
};

#endif


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="customer.login.container">
            <block class="Amazon\Login\Block\Login" name="amazon_login" after="customer.new" template="Amazon_Login::login.phtml"/>
        </referenceContainer>
    </body>
</page>


text:
package io.druid.segment.data;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.google.common.base.Supplier;
import com.google.common.collect.Maps;
import io.druid.java.util.common.IAE;
import io.druid.java.util.common.io.smoosh.SmooshedFileMapper;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Map;

/**
 * Compression of metrics is done by using a combination of {@link io.druid.segment.data.CompressedObjectStrategy.CompressionStrategy}
 * and Encoding(such as {@link LongEncodingStrategy} for type Long). CompressionStrategy is unaware of the data type
 * and is based on byte operations. It must compress and decompress in block of bytes. Encoding refers to compression
 * method relies on data format, so a different set of Encodings exist for each data type.
 *

 * Storage Format :
 * Byte 1 : version (currently 0x02)
 * Byte 2 - 5 : number of values
 * Byte 6 - 9 : size per block (even if block format isn't used, this is needed for backward compatibility)
 * Byte 10 : compression strategy (contains a flag if there's an encoding byte, see below for how the flag is defined)
 * Byte 11(optional) : encoding type
 *

 * Encoding specific header (described below)
 *

 * Block related header (if block compression is used, described in GenericIndexed)
 *

 * Values
 */
public class CompressionFactory
{
  private CompressionFactory()
  {
    // No instantiation
  }

  public static final LongEncodingStrategy DEFAULT_LONG_ENCODING_STRATEGY = LongEncodingStrategy.LONGS;

  // encoding format for segments created prior to the introduction of encoding formats
  public static final LongEncodingFormat LEGACY_LONG_ENCODING_FORMAT = LongEncodingFormat.LONGS;

  /**
   * Delta Encoding Header v1:
   * Byte 1 : version
   * Byte 2 - 9 : base value
   * Byte 10 - 13 : number of bits per value
   */
  public static final byte DELTA_ENCODING_VERSION = 0x1;

  /**
   * Table Encoding Header v1 :
   * Byte 1 : version
   * Byte 2 - 5 : table size
   * Byte 6 - (6 + 8 * table size - 1) : table of encoding, where the ith 8-byte value is encoded as i
   */
  public static final byte TABLE_ENCODING_VERSION = 0x1;

  public static final int MAX_TABLE_SIZE = 256;

  /*
   * There is no header or version for Longs encoding for backward compatibility
   */

  /*
   * This is the flag mechanism for determine whether an encoding byte exist in the header. This is needed for
   * backward compatibility, since segment created prior to the introduction of encoding formats does not have the
   * encoding strategy byte. The flag is encoded in the compression strategy byte using the setEncodingFlag and
   * clearEncodingFlag function.
   */

  // 0xFE(-2) should be the smallest valid compression strategy id
  private static byte FLAG_BOUND = (byte) 0xFE;
  // 126 is the value here since -2 - 126 = -128, which is the lowest byte value
  private static int FLAG_VALUE = 126;

  public static boolean hasEncodingFlag(byte strategyId)
  {
    return strategyId < FLAG_BOUND;
  }

  public static byte setEncodingFlag(byte strategyId)
  {
    return hasEncodingFlag(strategyId) ? strategyId : (byte) (strategyId - FLAG_VALUE);
  }

  public static byte clearEncodingFlag(byte strategyId)
  {
    return hasEncodingFlag(strategyId) ? (byte) (strategyId + FLAG_VALUE) : strategyId;
  }

  /**
   * The compression of decompression of encodings are separated into different enums. EncodingStrategy refers to the
   * strategy used to encode the data, and EncodingFormat refers to the format the data is encoded in. Note there is not
   * necessarily an one-to-one mapping between to two. For instance, the AUTO LongEncodingStrategy scans the data once
   * and decide on which LongEncodingFormat to use based on data property, so it's possible for the EncodingStrategy to
   * write in any of the LongEncodingFormat. On the other hand, there are no LongEncodingStrategy that always write in
   * TABLE LongEncodingFormat since it only works for data with low cardinality.
   */
  public enum LongEncodingStrategy
  {
    /**
     * AUTO strategy scans all values once before encoding them. It stores the value cardinality and maximum offset
     * of the values to determine whether to use DELTA, TABLE, or LONGS format.
     */
    AUTO,

    /**
     * LONGS strategy always encode the values using LONGS format
     */
    LONGS;

    @JsonValue
    @Override
    public String toString()
    {
      return this.name().toLowerCase();
    }

    @JsonCreator
    public static LongEncodingStrategy fromString(String name)
    {
      return valueOf(name.toUpperCase());
    }
  }

  public enum LongEncodingFormat
  {
    /**
     * DELTA format encodes a series of longs by finding the smallest value first, and stores all values
     * as offset to the smallest value. The maximum value is also found to calculate how many bits are required
     * to store each offset using {@link VSizeLongSerde}.
     */
    DELTA((byte) 0x0) {
      @Override
      public LongEncodingReader getReader(ByteBuffer buffer, ByteOrder order)
      {
        return new DeltaLongEncodingReader(buffer);
      }
    },
    /**
     * TABLE format encodes a series of longs by mapping each unique value to an id, and string the id with the
     * minimum number of bits similar to how DELTA stores offset. TABLE format is only applicable to values with
     * less unique values than {@link CompressionFactory#MAX_TABLE_SIZE}.
     */
    TABLE((byte) 0x1) {
      @Override
      public LongEncodingReader getReader(ByteBuffer buffer, ByteOrder order)
      {
        return new TableLongEncodingReader(buffer);
      }
    },
    /**
     * LONGS format encodes longs as is, using 8 bytes for each value.
     */
    LONGS((byte) 0xFF) {
      @Override
      public LongEncodingReader getReader(ByteBuffer buffer, ByteOrder order)
      {
        return new LongsLongEncodingReader(buffer, order);
      }
    };

    final byte id;

    LongEncodingFormat(byte id)
    {
      this.id = id;
    }

    public byte getId()
    {
      return id;
    }

    static final Map<Byte, LongEncodingFormat> idMap = Maps.newHashMap();

    static {
      for (LongEncodingFormat format : LongEncodingFormat.values()) {
        idMap.put(format.getId(), format);
      }
    }

    public abstract LongEncodingReader getReader(ByteBuffer buffer, ByteOrder order);

    public static LongEncodingFormat forId(byte id)
    {
      return idMap.get(id);
    }
  }

  /**
   * This writer output encoded values to the given ByteBuffer or OutputStream. {@link #setBuffer(ByteBuffer)} or
   * {@link #setOutputStream(OutputStream)} must be called before any value is written, and {@link #flush()} must
   * be called before calling setBuffer or setOutputStream again to set another output.
   */
  public interface LongEncodingWriter
  {
    /**
     * Data will be written starting from current position of the buffer, and the position of the buffer will be
     * updated as content is written.
     */
    void setBuffer(ByteBuffer buffer);

    void setOutputStream(OutputStream output);

    void write(long value) throws IOException;

    /**
     * Flush the unwritten content to the current output.
     */
    void flush() throws IOException;

    /**
     * Output the header values of the associating encoding format to the given outputStream. The header also include
     * bytes for compression strategy and encoding format(optional) as described above in Compression Storage Format.
     */
    void putMeta(OutputStream metaOut, CompressedObjectStrategy.CompressionStrategy strategy) throws IOException;

    /**
     * Get the number of values that can be encoded into each block for the given block size in bytes
     */
    int getBlockSize(int bytesPerBlock);

    /**
     * Get the number of bytes required to encoding the given number of values
     */
    int getNumBytes(int values);
  }

  public interface LongEncodingReader
  {
    void setBuffer(ByteBuffer buffer);

    long read(int index);

    int getNumBytes(int values);

    LongEncodingReader duplicate();
  }

  public static Supplier<IndexedLongs> getLongSupplier(
      int totalSize,
      int sizePer,
      ByteBuffer fromBuffer,
      ByteOrder order,
      LongEncodingFormat encodingFormat,
      CompressedObjectStrategy.CompressionStrategy strategy,
      SmooshedFileMapper fileMapper
  )
  {
    if (strategy == CompressedObjectStrategy.CompressionStrategy.NONE) {
      return new EntireLayoutIndexedLongSupplier(totalSize, encodingFormat.getReader(fromBuffer, order));
    } else {
      return new BlockLayoutIndexedLongSupplier(
          totalSize,
          sizePer,
          fromBuffer,
          order,
          encodingFormat.getReader(fromBuffer, order),
          strategy,
          fileMapper
      );
    }
  }

  public static LongSupplierSerializer getLongSerializer(
      IOPeon ioPeon, String filenameBase, ByteOrder order,
      LongEncodingStrategy encodingStrategy,
      CompressedObjectStrategy.CompressionStrategy compressionStrategy
  )
  {
    if (encodingStrategy == LongEncodingStrategy.AUTO) {
      return new IntermediateLongSupplierSerializer(ioPeon, filenameBase, order, compressionStrategy);
    } else if (encodingStrategy == LongEncodingStrategy.LONGS){
      if (compressionStrategy == CompressedObjectStrategy.CompressionStrategy.NONE) {
        return new EntireLayoutLongSupplierSerializer(
            ioPeon, filenameBase, order, new LongsLongEncodingWriter(order)
        );
      } else{
        return new BlockLayoutLongSupplierSerializer(
            ioPeon, filenameBase, order, new LongsLongEncodingWriter(order), compressionStrategy
        );
      }
    } else {
      throw new IAE("unknown encoding strategy : %s", encodingStrategy.toString());
    }
  }

  // Float currently does not support any encoding types, and stores values as 4 byte float

  public static Supplier<IndexedFloats> getFloatSupplier(
      int totalSize,
      int sizePer,
      ByteBuffer fromBuffer,
      ByteOrder order,
      CompressedObjectStrategy.CompressionStrategy strategy,
      SmooshedFileMapper fileMapper
  )
  {
    if (strategy == CompressedObjectStrategy.CompressionStrategy.NONE) {
      return new EntireLayoutIndexedFloatSupplier(totalSize, fromBuffer, order);
    } else {
      return new BlockLayoutIndexedFloatSupplier(totalSize, sizePer, fromBuffer, order, strategy, fileMapper);
    }
  }

  public static FloatSupplierSerializer getFloatSerializer(
      IOPeon ioPeon, String filenameBase, ByteOrder order,
      CompressedObjectStrategy.CompressionStrategy compressionStrategy
  )
  {
    if (compressionStrategy == CompressedObjectStrategy.CompressionStrategy.NONE) {
      return new EntireLayoutFloatSupplierSerializer(
          ioPeon, filenameBase, order
      );
    } else{
      return new BlockLayoutFloatSupplierSerializer(
          ioPeon, filenameBase, order, compressionStrategy
      );
    }
  }

}


text:
  <meta charset="UTF-8">
  <title>JavaScript DOM Tutorials</title>
  <link href="style.css" rel="stylesheet" type="text/css" />

JavaScript DOM Tutorials

These interactive tutorials will teach you how to access and manipulate
  the DOM from JavaScript.  No libraries are used.
  Basic knowledge of JavaScript is assumed.

Tutorial 1: Accessing the DOM

Use <tt>getElementById</tt>, then walk the DOM to find any node.

Tutorial 2: Manipulating the DOM

Create and delete nodes.

Tutorial 3: DOM Events

Binding events to the DOM.

Tutorial 4: Asynchronous Server Requests

AJAX with the XMLHttpRequest object.

Questions? Use the Intro
    to JavaScript forum.

Google © 2012 - Neil Fraser (fraser@google.com)