text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;

namespace Azure.ResourceManager.PrivateDns
{
    /// <summary> A class to add extension methods to Azure.ResourceManager.PrivateDns. </summary>
    public static partial class PrivateDnsExtensions
    {
        private static SubscriptionResourceExtensionClient GetExtensionClient(SubscriptionResource subscriptionResource)
        {
            return subscriptionResource.GetCachedClient((client) =>
            {
                return new SubscriptionResourceExtensionClient(client, subscriptionResource.Id);
            }
            );
        }

        /// <summary>
        /// Lists the Private DNS zones in all resource groups in a subscription.
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Network/privateDnsZones
        /// Operation Id: PrivateZones_List
        /// </summary>
        /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param>
        /// <param name="top"> The maximum number of Private DNS zones to return. If not specified, returns up to 100 zones. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> An async collection of <see cref="PrivateZoneResource" /> that may take multiple service requests to iterate over. </returns>
        public static AsyncPageable<PrivateZoneResource> GetPrivateZonesAsync(this SubscriptionResource subscriptionResource, int? top = null, CancellationToken cancellationToken = default)
        {
            return GetExtensionClient(subscriptionResource).GetPrivateZonesAsync(top, cancellationToken);
        }

        /// <summary>
        /// Lists the Private DNS zones in all resource groups in a subscription.
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Network/privateDnsZones
        /// Operation Id: PrivateZones_List
        /// </summary>
        /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param>
        /// <param name="top"> The maximum number of Private DNS zones to return. If not specified, returns up to 100 zones. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> A collection of <see cref="PrivateZoneResource" /> that may take multiple service requests to iterate over. </returns>
        public static Pageable<PrivateZoneResource> GetPrivateZones(this SubscriptionResource subscriptionResource, int? top = null, CancellationToken cancellationToken = default)
        {
            return GetExtensionClient(subscriptionResource).GetPrivateZones(top, cancellationToken);
        }

        private static ResourceGroupResourceExtensionClient GetExtensionClient(ResourceGroupResource resourceGroupResource)
        {
            return resourceGroupResource.GetCachedClient((client) =>
            {
                return new ResourceGroupResourceExtensionClient(client, resourceGroupResource.Id);
            }
            );
        }

        /// <summary> Gets a collection of PrivateZoneResources in the ResourceGroupResource. </summary>
        /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param>
        /// <returns> An object representing collection of PrivateZoneResources and their operations over a PrivateZoneResource. </returns>
        public static PrivateZoneCollection GetPrivateZones(this ResourceGroupResource resourceGroupResource)
        {
            return GetExtensionClient(resourceGroupResource).GetPrivateZones();
        }

        /// <summary>
        /// Gets a Private DNS zone. Retrieves the zone properties, but not the virtual networks links or the record sets within the zone.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateDnsZones/{privateZoneName}
        /// Operation Id: PrivateZones_Get
        /// </summary>
        /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param>
        /// <param name="privateZoneName"> The name of the Private DNS zone (without a terminating dot). </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="privateZoneName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="privateZoneName"/> is null. </exception>
        [ForwardsClientCalls]
        public static async Task<Response<PrivateZoneResource>> GetPrivateZoneAsync(this ResourceGroupResource resourceGroupResource, string privateZoneName, CancellationToken cancellationToken = default)
        {
            return await resourceGroupResource.GetPrivateZones().GetAsync(privateZoneName, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Gets a Private DNS zone. Retrieves the zone properties, but not the virtual networks links or the record sets within the zone.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateDnsZones/{privateZoneName}
        /// Operation Id: PrivateZones_Get
        /// </summary>
        /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param>
        /// <param name="privateZoneName"> The name of the Private DNS zone (without a terminating dot). </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="privateZoneName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="privateZoneName"/> is null. </exception>
        [ForwardsClientCalls]
        public static Response<PrivateZoneResource> GetPrivateZone(this ResourceGroupResource resourceGroupResource, string privateZoneName, CancellationToken cancellationToken = default)
        {
            return resourceGroupResource.GetPrivateZones().Get(privateZoneName, cancellationToken);
        }

        #region PrivateZoneResource
        /// <summary>
        /// Gets an object representing a <see cref="PrivateZoneResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="PrivateZoneResource.CreateResourceIdentifier" /> to create a <see cref="PrivateZoneResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="PrivateZoneResource" /> object. </returns>
        public static PrivateZoneResource GetPrivateZoneResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient<PrivateZoneResource>(() =>
            {
                PrivateZoneResource.ValidateResourceId(id);
                return new PrivateZoneResource(client, id);
            }
            );
        }
        #endregion

        #region VirtualNetworkLinkResource
        /// <summary>
        /// Gets an object representing a <see cref="VirtualNetworkLinkResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="VirtualNetworkLinkResource.CreateResourceIdentifier" /> to create a <see cref="VirtualNetworkLinkResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="VirtualNetworkLinkResource" /> object. </returns>
        public static VirtualNetworkLinkResource GetVirtualNetworkLinkResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient(() =>
            {
                VirtualNetworkLinkResource.ValidateResourceId(id);
                return new VirtualNetworkLinkResource(client, id);
            }
            );
        }
        #endregion

        #region PrivateDnsARecordResource
        /// <summary>
        /// Gets an object representing a <see cref="PrivateDnsARecordResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="PrivateDnsARecordResource.CreateResourceIdentifier" /> to create a <see cref="PrivateDnsARecordResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="PrivateDnsARecordResource" /> object. </returns>
        public static PrivateDnsARecordResource GetPrivateDnsARecordResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient<PrivateDnsARecordResource>(() =>
            {
                PrivateDnsARecordResource.ValidateResourceId(id);
                return new PrivateDnsARecordResource(client, id);
            }
            );
        }
        #endregion

        #region PrivateDnsAaaaRecordResource
        /// <summary>
        /// Gets an object representing a <see cref="PrivateDnsAaaaRecordResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="PrivateDnsAaaaRecordResource.CreateResourceIdentifier" /> to create a <see cref="PrivateDnsAaaaRecordResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="PrivateDnsAaaaRecordResource" /> object. </returns>
        public static PrivateDnsAaaaRecordResource GetPrivateDnsAaaaRecordResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient<PrivateDnsAaaaRecordResource>(() =>
            {
                PrivateDnsAaaaRecordResource.ValidateResourceId(id);
                return new PrivateDnsAaaaRecordResource(client, id);
            }
            );
        }
        #endregion

        #region PrivateDnsCnameRecordResource
        /// <summary>
        /// Gets an object representing a <see cref="PrivateDnsCnameRecordResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="PrivateDnsCnameRecordResource.CreateResourceIdentifier" /> to create a <see cref="PrivateDnsCnameRecordResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="PrivateDnsCnameRecordResource" /> object. </returns>
        public static PrivateDnsCnameRecordResource GetPrivateDnsCnameRecordResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient<PrivateDnsCnameRecordResource>(() =>
            {
                PrivateDnsCnameRecordResource.ValidateResourceId(id);
                return new PrivateDnsCnameRecordResource(client, id);
            }
            );
        }
        #endregion

        #region PrivateDnsMXRecordResource
        /// <summary>
        /// Gets an object representing a <see cref="PrivateDnsMXRecordResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="PrivateDnsMXRecordResource.CreateResourceIdentifier" /> to create a <see cref="PrivateDnsMXRecordResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="PrivateDnsMXRecordResource" /> object. </returns>
        public static PrivateDnsMXRecordResource GetPrivateDnsMXRecordResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient<PrivateDnsMXRecordResource>(() =>
            {
                PrivateDnsMXRecordResource.ValidateResourceId(id);
                return new PrivateDnsMXRecordResource(client, id);
            }
            );
        }
        #endregion

        #region PrivateDnsPtrRecordResource
        /// <summary>
        /// Gets an object representing a <see cref="PrivateDnsPtrRecordResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="PrivateDnsPtrRecordResource.CreateResourceIdentifier" /> to create a <see cref="PrivateDnsPtrRecordResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="PrivateDnsPtrRecordResource" /> object. </returns>
        public static PrivateDnsPtrRecordResource GetPrivateDnsPtrRecordResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient<PrivateDnsPtrRecordResource>(() =>
            {
                PrivateDnsPtrRecordResource.ValidateResourceId(id);
                return new PrivateDnsPtrRecordResource(client, id);
            }
            );
        }
        #endregion

        #region PrivateDnsSoaRecordResource
        /// <summary>
        /// Gets an object representing a <see cref="PrivateDnsSoaRecordResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="PrivateDnsSoaRecordResource.CreateResourceIdentifier" /> to create a <see cref="PrivateDnsSoaRecordResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="PrivateDnsSoaRecordResource" /> object. </returns>
        public static PrivateDnsSoaRecordResource GetPrivateDnsSoaRecordResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient<PrivateDnsSoaRecordResource>(() =>
            {
                PrivateDnsSoaRecordResource.ValidateResourceId(id);
                return new PrivateDnsSoaRecordResource(client, id);
            }
            );
        }
        #endregion

        #region PrivateDnsSrvRecordResource
        /// <summary>
        /// Gets an object representing a <see cref="PrivateDnsSrvRecordResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="PrivateDnsSrvRecordResource.CreateResourceIdentifier" /> to create a <see cref="PrivateDnsSrvRecordResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="PrivateDnsSrvRecordResource" /> object. </returns>
        public static PrivateDnsSrvRecordResource GetPrivateDnsSrvRecordResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient<PrivateDnsSrvRecordResource>(() =>
            {
                PrivateDnsSrvRecordResource.ValidateResourceId(id);
                return new PrivateDnsSrvRecordResource(client, id);
            }
            );
        }
        #endregion

        #region PrivateDnsTxtRecordResource
        /// <summary>
        /// Gets an object representing a <see cref="PrivateDnsTxtRecordResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="PrivateDnsTxtRecordResource.CreateResourceIdentifier" /> to create a <see cref="PrivateDnsTxtRecordResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="PrivateDnsTxtRecordResource" /> object. </returns>
        public static PrivateDnsTxtRecordResource GetPrivateDnsTxtRecordResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient<PrivateDnsTxtRecordResource>(() =>
            {
                PrivateDnsTxtRecordResource.ValidateResourceId(id);
                return new PrivateDnsTxtRecordResource(client, id);
            }
            );
        }
        #endregion
    }
}


text:
package com.github.phenomics.ontolib.formats.hpo;

import java.util.Date;
import java.util.List;
import com.github.phenomics.ontolib.ontology.data.Dbxref;
import com.github.phenomics.ontolib.ontology.data.Term;
import com.github.phenomics.ontolib.ontology.data.TermId;
import com.github.phenomics.ontolib.ontology.data.TermSynonym;

/**
 * Representation of a term in the HPO.
 *
 * @author Manuel Holtgrewe
 * @author Sebastian Koehler
 */
public class HpoTerm implements Term {

  /** Serial UId for serialization. */
  private static final long serialVersionUID = 1L;

  /** The HPO term's Id. */
  private final TermId id;

  /** Alternative term Ids. */
  private final List<TermId> altTermIds;

  /** The human-readable name of the term. */
  private final String name;

  /** The term's definition. */
  private final String definition;

  /** The term's comment string. */
  private final String comment;

  /** The names of the subsets that the term is in, empty list if none. */
  private final List<String> subsets;

  /** The list of term synonyms. */
  private final List<TermSynonym> synonyms;

  /** Whether or not the term is obsolete. */
  private final boolean obsolete;

  /** The term's author name. */
  private final String createdBy;

  /** The term's creation date. */
  private final Date creationDate;

  /** The term's xref list. */
  private final List<Dbxref> xrefs;

  /**
   * Constructor.
   *
   * @param id The term's Id.
   * @param altTermIds Alternative term Ids.
   * @param name Human-readable term name.
   * @param definition Term definition.
   * @param comment Term comment.
   * @param subsets The names of the subsets that the term is in, empty if none.
   * @param synonyms The synonyms for the term.
   * @param obsolete Whether or not the term is obsolete.
   * @param createdBy Author of the term.
   * @param creationDate Date of creation of the term.
   * @param xrefs List of cross-references.
   */
  public HpoTerm(TermId id, List<TermId> altTermIds, String name, String definition, String comment,
      List<String> subsets, List<TermSynonym> synonyms, boolean obsolete, String createdBy,
      Date creationDate, List<Dbxref> xrefs) {
    this.id = id;
    this.altTermIds = altTermIds;
    this.name = name;
    this.definition = definition;
    this.comment = comment;
    this.subsets = subsets;
    this.synonyms = synonyms;
    this.obsolete = obsolete;
    this.createdBy = createdBy;
    this.creationDate = creationDate;
    this.xrefs = xrefs;
  }

  @Override
  public TermId getId() {
    return id;
  }

  @Override
  public List<TermId> getAltTermIds() {
    return altTermIds;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public String getDefinition() {
    return definition;
  }

  @Override
  public String getComment() {
    return comment;
  }

  @Override
  public List<String> getSubsets() {
    return subsets;
  }

  @Override
  public List<TermSynonym> getSynonyms() {
    return synonyms;
  }

  @Override
  public boolean isObsolete() {
    return obsolete;
  }

  @Override
  public String getCreatedBy() {
    return createdBy;
  }

  @Override
  public Date getCreationDate() {
    return creationDate;
  }

  @Override
  public List<Dbxref> getXrefs() {
    return xrefs;
  }

  @Override
  public String toString() {
    return "HPOTerm [id=" + id + ", altTermIds=" + altTermIds + ", name=" + name + ", definition="
        + definition + ", comment=" + comment + ", subsets=" + subsets + ", synonyms=" + synonyms
        + ", obsolete=" + obsolete + ", createdBy=" + createdBy + ", creationDate=" + creationDate
        + ", xrefs=" + xrefs + "]";
  }

}

redpajama_set_name: RedPajamaGithub


text:
package xfuzzy.xfj;

import java.io.*;

public class XfjFamiliarMemFunc {

 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
 //			MIEMBROS PRIVADOS			//
 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

 private String eol = System.getProperty("line.separator", "\n");
 private File dir;
 private String pkgname;

 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
 //			METODOS CONSTANTES			//
 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

 public static final String create(File dir, String pkgname) {
  XfjFamiliarMemFunc creator = new XfjFamiliarMemFunc(dir,pkgname);
  creator.createFile();
  return creator.getMessage();
 }

 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
 //			   CONSTRUCTOR				//
 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

 public XfjFamiliarMemFunc(File dir, String pkgname) {
  this.dir = dir;
  this.pkgname = pkgname;
 }

 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
 //			METODOS PUBLICOS			//
 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

 //-------------------------------------------------------------//
 // Obtiene el nombre del fichero creado			//
 //-------------------------------------------------------------//

 private String getMessage() {
  File file = new File(dir,"FamiliarMembershipFunction.java");
  return file.getAbsolutePath();
 }

 //-------------------------------------------------------------//
 // Genera el fichero "FamiliarMembershipFunction.java"		//
 //-------------------------------------------------------------//

 public void createFile() {
  File file = new File(dir,"FamiliarMembershipFunction.java");

  String heading[] = getHeading();
  String source[] = getSource();

  String code = "";
  for(int i=0; i<heading.length; i++) code += heading[i]+eol;
  code += getPackage()+eol+eol;
  for(int i=0; i<source.length; i++) code += source[i]+eol;

  byte[] buf = code.getBytes();
  try {
   OutputStream stream = new FileOutputStream(file);
   stream.write(buf);
   stream.close();
  }
  catch (IOException e) {}
 }

 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
 //			METODOS PRIVADOS			//
 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

 //-------------------------------------------------------------//
 // Genera el codigo de cabecera				//
 //-------------------------------------------------------------//

 private String[] getHeading() {
  String source[] = {
   "//++++++++++++++++++++++++++++++++++++++++++++++++++++++//",
   "//                                                      //",
   "// Class:  FamiliarMembershipFunction                   //",
   "//                                                      //",
   "// Author: Automatically generated by Xfuzzy            //",
   "//                                                      //",
   "// Description: Membership function of an input         //",
   "//              variable described as part of a family  //",
   "//                                                      //",
   "//++++++++++++++++++++++++++++++++++++++++++++++++++++++//",
   "" };

  return source;
 }

 //-------------------------------------------------------------//
 // Genera el codigo del paquete				//
 //-------------------------------------------------------------//

 private String getPackage() {
  if(pkgname != null && pkgname.length()>0) return "package "+this.pkgname+";";
  return "";
 }

 //-------------------------------------------------------------//
 // Genera el codigo de la clase "FamiliarMembershipFunction"	//
 //-------------------------------------------------------------//

 private String[] getSource() {
  String source[] = {
"public class FamiliarMembershipFunction extends InputMembershipFunction {",
" double min;",
" double max;",
" double step;",
" MembershipFunctionFamily family;",
" int index;",
"",
" public FamiliarMembershipFunction(MembershipFunctionFamily fam, int i) {",
"  this.min = fam.min;",
"  this.max = fam.max;",
"  this.step = fam.step;",
"  this.family = fam;",
"  this.index = i;",
" }",
"",
" public double center() {",
"  return family.center(index);",
" }",
"",
" public double basis() {",
"  return family.center(index);",
" }",
"",
" public double param(int i) {",
"  return family.param(i);",
" }",
"",
" public double isEqual(double x) {",
"  return family.isEqual(index,x);",
" }",
"",
" public double isSmallerOrEqual(double x) {",
"  return family.isSmallerOrEqual(index,x);",
" }",
"",
" public double isGreaterOrEqual(double x) {",
"  return family.isGreaterOrEqual(index,x);",
" }",
"}" };

  return source;
 }
}


text:
import pytest

from api.base.settings.defaults import API_BASE
from api_tests.providers.mixins import ProviderSubmissionListViewTestBaseMixin

from osf_tests.factories import (
    RegistrationFactory,
    RegistrationProviderFactory,
)

class TestSubmissionList(ProviderSubmissionListViewTestBaseMixin):
    provider_class = RegistrationProviderFactory
    submission_class = RegistrationFactory

    @pytest.fixture()
    def url(self, submission_provider):
        return '/{}providers/registrations/{}/submissions/'.format(API_BASE, submission_provider._id)


text:
const express = require('express');
const Note = require(__dirname + '/../models/note');
const jsonParser = require('body-parser').json();
const handleDBError = require(__dirname + '/../lib/handle_db_error');
const jwtAuth = require(__dirname + '/../lib/jwt_auth');

const notesRouter = module.exports = exports = express.Router();

notesRouter.post('/create', jwtAuth, jsonParser, (req, res) => {
  var incNote = req.body;
  if (!req.user.id || !incNote.content || !incNote.relatedCollection || !incNote.relatedId) {
    return res.status(400).json( { msg: 'Missing required information' } );
  }
  var newestNote = new Note();
  try {
    newestNote.ownedBy = req.user.id;
    newestNote.title = incNote.title;
    newestNote.content = incNote.content;
    newestNote.relatedCollection = incNote.relatedCollection;
    newestNote.relatedId = incNote.relatedId;
  } catch (e) {
    console.log('error in setting note properties : ', e);
    return res.status(500).json( { msg: 'Error in creating the new note.' } );
  }

  newestNote.save((err, data) => {
    if (err) handleDBError(err, res);

    res.status(200).json(data);
  });
});

notesRouter.get('/getLatest', jwtAuth, jsonParser, (req, res) => {

  Note.findOne({ ownedBy: req.user.id }, (err, data) => {
    if (err) {
      console.log('error: ', err);
      return handleDBError(err, res);
    }

    res.status(200).json(data);
  });
});

notesRouter.get('/getAll', jwtAuth, jsonParser, (req, res) => {
  Note.find({ ownedBy: req.user.id }, (err, data) => {
    if (err) return handleDBError(err, res);

    res.status(200).json(data);
  });
});

notesRouter.put('/change/:id', jwtAuth, jsonParser, (req, res) => {
  var noteData = req.body;
  Note.update({ _id: req.params.id, ownedBy: req.user.id }, noteData, (err) => {
    if (err) return handleDBError(err, res);

    res.status(200).json({ msg: 'Successfully updated note' });
  });
});

notesRouter.delete('/delete/:id', jwtAuth, jsonParser, (req, res) => {
  Note.remove({ _id: req.params.id, ownedBy: req.user.id }, (err) => {
    if (err) return handleDBError(err, res);

    res.status(200).json({ msg: 'Successfully deleted note' });
  });
});


text:
package org.elasticsearch.painless.node;

import org.elasticsearch.painless.Definition;
import org.elasticsearch.painless.Location;
import org.elasticsearch.painless.Variables;
import org.objectweb.asm.Label;
import org.elasticsearch.painless.MethodWriter;

/**
 * Represents a while loop.
 */
public final class SWhile extends AStatement {

    final int maxLoopCounter;
    AExpression condition;
    final SBlock block;

    public SWhile(Location location, int maxLoopCounter, AExpression condition, SBlock block) {
        super(location);

        this.maxLoopCounter = maxLoopCounter;
        this.condition = condition;
        this.block = block;
    }

    @Override
    void analyze(Variables variables) {
        variables.incrementScope();

        condition.expected = Definition.BOOLEAN_TYPE;
        condition.analyze(variables);
        condition = condition.cast(variables);

        boolean continuous = false;

        if (condition.constant != null) {
            continuous = (boolean)condition.constant;

            if (!continuous) {
                throw createError(new IllegalArgumentException("Extraneous while loop."));
            }

            if (block == null) {
                throw createError(new IllegalArgumentException("While loop has no escape."));
            }
        }

        if (block != null) {
            block.beginLoop = true;
            block.inLoop = true;

            block.analyze(variables);

            if (block.loopEscape && !block.anyContinue) {
                throw createError(new IllegalArgumentException("Extraneous while loop."));
            }

            if (continuous && !block.anyBreak) {
                methodEscape = true;
                allEscape = true;
            }

            block.statementCount = Math.max(1, block.statementCount);
        }

        statementCount = 1;

        if (maxLoopCounter > 0) {
            loopCounterSlot = variables.getVariable(location, "#loop").slot;
        }

        variables.decrementScope();
    }

    @Override
    void write(MethodWriter writer) {
        writer.writeStatementOffset(location);

        Label begin = new Label();
        Label end = new Label();

        writer.mark(begin);

        condition.fals = end;
        condition.write(writer);

        if (block != null) {
            writer.writeLoopCounter(loopCounterSlot, Math.max(1, block.statementCount), location);

            block.continu = begin;
            block.brake = end;
            block.write(writer);
        } else {
            writer.writeLoopCounter(loopCounterSlot, 1, location);
        }

        if (block == null || !block.allEscape) {
            writer.goTo(begin);
        }

        writer.mark(end);
    }
}


text:
ENV['RACK_ENV'] = 'test'

require File.expand_path '../../app', __FILE__


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

/**
* Class m150403_104500_add_pay_and_delivery_table*/
class m150403_104500_add_pay_and_delivery_table extends Migration
{
    /**
     * migration table name
     */
    public $tableName = '{{%pay_and_delivery}}';

    /**
    * commands will be executed in transaction
    */
    public function safeUp()
    {
        $this->createTable(
            $this->tableName,
            [
                'id' => Schema::TYPE_INTEGER. ' UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
                'type_id' => Schema::TYPE_SMALLINT. '(1) NOT NULL DEFAULT 1',
                'name' => Schema::TYPE_STRING. ' NOT NULL COMMENT "Тип доставки и оплаты"',
                'price' => Schema::TYPE_STRING. ' NOT NULL COMMENT "Стоимость"',
                'for_kiev' => Schema::TYPE_SMALLINT. '(1) UNSIGNED NOT NULL DEFAULT 1 COMMENT "Для Киева"',
                'for_regions' => Schema::TYPE_SMALLINT. '(1) UNSIGNED NOT NULL DEFAULT 1 COMMENT "Для регионов"',
                'visible' => Schema::TYPE_INTEGER. ' UNSIGNED NOT NULL DEFAULT 1 COMMENT "Отображать"',
                'position' => Schema::TYPE_INTEGER. ' UNSIGNED NOT NULL DEFAULT 0 COMMENT "Позиция"',
                'created' => Schema::TYPE_DATETIME. ' NOT NULL COMMENT "Создано"',
                'modified' => Schema::TYPE_DATETIME. ' NOT NULL COMMENT "Обновлено"',
            ],
            'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'
        );
    }

    /**
    * commands will be executed in transaction
    */
    public function safeDown()
    {
        $this->dropTable($this->tableName);
    }
}


text:
package server

import (
	"net"
	"net/http"

	"sigs.k8s.io/aws-iam-authenticator/pkg/config"
)

// Server for the authentication webhook.
type Server struct {
	// Config is the whole configuration of aws-iam-authenticator used for valid keys and certs, kubeconfig, and so on
	config.Config
	httpServer http.Server
	listener   net.Listener
}


text:
#include <memory>
#include <string>

#include "PythonBindings.h"
#include "PythonScriptEngine.h"

namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace python {

std::unique_ptr<py::scoped_interpreter> PythonScriptEngine::guard_;
std::unique_ptr<py::gil_scoped_release> PythonScriptEngine::gil_release_;
std::mutex PythonScriptEngine::init_mutex_;
bool PythonScriptEngine::initialized_;

PythonScriptEngine::PythonScriptEngine() {
  {
    std::lock_guard<std::mutex> lock(init_mutex_);

    if (!initialized_) {
      throw std::runtime_error("Python is not yet initialized");
    }
  }

  {
    py::gil_scoped_acquire gil{};
    py::module::import("minifi_native");
    bindings_.reset(new py::dict());
    (*bindings_) = py::globals().attr("copy")();
  }
}

void PythonScriptEngine::eval(const std::string &script) {
  py::gil_scoped_acquire gil{};

  if (script[0] == '\n') {
    py::eval<py::eval_statements>(py::module::import("textwrap").attr("dedent")(script), *bindings_, *bindings_);
  } else {
     py::eval<py::eval_statements>(script, *bindings_, *bindings_);
  }
}

void PythonScriptEngine::evalFile(const std::string &file_name) {
  py::gil_scoped_acquire gil{};
  py::eval_file(file_name, *bindings_, *bindings_);
}

void PythonScriptEngine::initialize() {
  std::lock_guard<std::mutex> lock(init_mutex_);

  if (initialized_) {
    return;
  }

  initialized_ = true;
  guard_.reset(new py::scoped_interpreter());
  gil_release_.reset(new py::gil_scoped_release());
}

} /* namespace python */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */


text:
package net.sourceforge.plantuml.svek;

import net.sourceforge.plantuml.awt.geom.XDimension2D;
import net.sourceforge.plantuml.graphic.AbstractTextBlock;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.graphic.SymbolContext;
import net.sourceforge.plantuml.ugraphic.UEllipse;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UPath;
import net.sourceforge.plantuml.ugraphic.UTranslate;
import net.sourceforge.plantuml.ugraphic.color.HColors;

public class Boundary extends AbstractTextBlock {

	private final double margin = 4;

	private final double radius = 12;
	private final double left = 17;

	private final SymbolContext symbolContext;

	public Boundary(SymbolContext symbolContext) {
		this.symbolContext = symbolContext;
	}

	public void drawU(UGraphic ug) {
		double x = 0;
		double y = 0;
		x += margin;
		y += margin;
		ug = symbolContext.apply(ug);
		final UEllipse circle = new UEllipse(radius * 2, radius * 2);
		circle.setDeltaShadow(symbolContext.getDeltaShadow());

		final UPath path1 = new UPath();
		path1.moveTo(0, 0);
		path1.lineTo(0, radius * 2);
		path1.setDeltaShadow(symbolContext.getDeltaShadow());

		final UPath path = new UPath();
		path.moveTo(0, 0);
		path.lineTo(0, radius * 2);
		path.moveTo(0, radius);
		path.lineTo(left, radius);
		path.setDeltaShadow(symbolContext.getDeltaShadow());
		ug.apply(new UTranslate(x, y)).apply(HColors.none().bg()).draw(path);

		// final ULine line1 = ULine.dy(radius * 2);
		// line1.setDeltaShadow(deltaShadow);
		// ug.apply(new UTranslate(x, y)).draw(line1);
		// final ULine line2 = new ULine(left, 0);
		// line2.setDeltaShadow(deltaShadow);
		// ug.apply(new UTranslate(x, y + radius)).draw(line2);

		ug.apply(new UTranslate(x + left, y)).draw(circle);

	}

	public XDimension2D calculateDimension(StringBounder stringBounder) {
		return new XDimension2D(radius * 2 + left + 2 * margin, radius * 2 + 2 * margin);
	}

}


text:
import Ember from 'ember';
import Application from '../../app';
import config from '../../config/environment';

import registerAsyncHelpers from './ember-cli-g-maps/register-async-helpers';

export default function startApp(attrs) {
  let attributes = Ember.merge({}, config.APP);
  attributes = Ember.merge(attributes, attrs); // use defaults, but you can override;

  return Ember.run(() => {
    let application = Application.create(attributes);
    registerAsyncHelpers();
    application.setupForTesting();
    application.injectTestHelpers();
    return application;
  });
}


text:
require 'rails_helper'

describe Georgia::Widget, type: :model do

  specify { expect(build(:georgia_widget)).to be_valid }

  it { expect(subject).to have_many(:ui_associations) }
  it { expect(subject).to have_many(:ui_sections) }
  it { expect(subject).to have_many(:revisions) }

  it_behaves_like 'a contentable model'

  describe 'scopes' do

    before :all do
      @footer_widget = create(:georgia_widget)
      @sidebar_widget = create(:georgia_widget)
      @submenu_widget = create(:georgia_widget)
      create(:georgia_ui_association, widget: @footer_widget, ui_section: create(:georgia_ui_section, name: 'Footer'))
      create(:georgia_ui_association, widget: @sidebar_widget, ui_section: create(:georgia_ui_section, name: 'Sidebar'))
      create(:georgia_ui_association, widget: @submenu_widget, ui_section: create(:georgia_ui_section, name: 'Submenu'))
    end

    after :all do
      Georgia::Widget.destroy_all
    end

    describe '.footer' do
      let(:widgets) { Georgia::Widget.footer }

      it 'scopes footer widgets' do
        expect(widgets).to include @footer_widget
        expect(widgets).not_to include @sidebar_widget
        expect(widgets).not_to include @submenu_widget
      end
    end

    describe '.sidebar' do
      let(:widgets) { Georgia::Widget.sidebar }

      it 'scopes sidebar widgets' do
        expect(widgets).not_to include @footer_widget
        expect(widgets).to include @sidebar_widget
        expect(widgets).not_to include @submenu_widget
      end
    end

    describe '.submenu' do
      let(:widgets) { Georgia::Widget.submenu }

      it 'scopes submenu widgets' do
        expect(widgets).not_to include @footer_widget
        expect(widgets).not_to include @sidebar_widget
        expect(widgets).to include @submenu_widget
      end
    end

  end

end


text:
'''
Work on pip config file
'''

import os.path
import sys
import platform
import shutil
import pipes
import glob
from mando import command, main

IS_WINDOWS = platform.system() == 'Windows'

def platform_choice(posix, windows):
    return windows if IS_WINDOWS else posix

def config_file(posix, windows):
    return os.path.expanduser(platform_choice(posix, windows))

def pip_config():
    return config_file('~/.pip/pip.conf', windows='~/pip/pip.ini')

PIP_CONF_TEMPLATE = '''\
[global]
# Base URL of Python Package Index

index-url = https://pypi.python.org/simple/

# Extra URLs of package indexes to use in addition to --index-url.

extra-index-url =

# Ignore package index (only looking at --find-links URLs instead).

no-index = false

# If a url or path to an html file, then parse for links to archives.
# If a local path or file:// url that's a directory, then look for archives
# in the directory listing.

find-links =
'''

@command
def create():
    '''
    Create a pip config file with defaults
    '''
    pip_config_file = pip_config()
    pip_config_dir = os.path.dirname(pip_config_file)
    try:
        os.makedirs(pip_config_dir)
    except OSError:
        pass
    with open(pip_config_file, 'w') as pip_conf:
        pip_conf.write(PIP_CONF_TEMPLATE)

@command('ed')
def edit():
    '''
    Edit user's pip config file with the default text editor
    '''
    default_editor = platform_choice('/usr/bin/vi', windows='notepad.exe')
    editor = os.environ.get('EDITOR') or default_editor
    os.system(
        '{} {}'.format(
            editor,
            pipes.quote(pip_config())))

def file_version(filename, version):
    return '{}.{}'.format(filename, version)

def copy(cmd, source, destination):
    print('(command "{}") {} -> {}'.format(cmd, source, destination))
    shutil.copy2(source, destination)

@command('cp')
def copy_cmd(version):
    '''
    Make a copy of the config with VERSION suffix.

    pip.conf -> pip.conf[version]
    '''
    pip_conf = pip_config()
    copy('copy', pip_conf, file_version(pip_conf, version))

@command
def use(version):
    '''
    Copy the saved config with suffix VERSION over the config file

    pip.conf[version] -> pip.conf
    :param version:
    '''
    pip_conf = pip_config()
    copy('use', file_version(pip_conf, version), pip_conf)

@command('ls')
def list_cmd():
    '''List known config <VERSION>s'''
    pip_conf = pip_config()
    configs = glob.glob('{}.*'.format(pip_conf))
    versions = [config[len(pip_conf) + 1:] for config in configs]
    print('Saved versions:')
    print('  ' + '\n  '.join(sorted(versions)))

@command('cat')
def print_cmd(version=None):
    '''
    Print config to stdout

    :param version: version to dump, defaults to current config
    '''
    if version:
        filename = file_version(pip_config(), version)
    else:
        filename = pip_config()
    with open(filename) as config:
        sys.stdout.write(config.read())

@command('rm')
def delete(version):
    '''ReMove saved config <VERSION>

    :param version: remove pip.conf saved as <VERSION>
    '''
    os.remove(file_version(pip_config(), version))

if __name__ == '__main__':
    main()


text:
// -----------------------------------------------------------------------
// <copyright file="ContactsController.cs" company="Nodine Legal, LLC">
// Licensed to Nodine Legal, LLC under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Nodine Legal, LLC 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.
// </copyright>
// -----------------------------------------------------------------------

namespace OpenLawOffice.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using AutoMapper;
    using System.Data;

    [HandleError(View = "Errors/Index", Order = 10)]
    public class ContactsController : BaseController
    {
        [Authorize(Roles = "Login, User")]
        public ActionResult Index()
        {
            List<ViewModels.Contacts.ContactViewModel> viewModelList = null;
            string contactFilter;

            viewModelList = new List<ViewModels.Contacts.ContactViewModel>();

            using (IDbConnection conn = Data.Database.Instance.GetConnection())
            {
                if (!string.IsNullOrEmpty(contactFilter = Request["contactFilter"]))
                {
                    Data.Contacts.Contact.List(contactFilter, conn, false).ForEach(x =>
                    {
                        viewModelList.Add(Mapper.Map<ViewModels.Contacts.ContactViewModel>(x));
                    });
                }
                else
                {
                    Data.Contacts.Contact.List(conn, false).ForEach(x =>
                    {
                        viewModelList.Add(Mapper.Map<ViewModels.Contacts.ContactViewModel>(x));
                    });
                }
            }

            return View(viewModelList);
        }

        [Authorize(Roles = "Login, User")]
        public ActionResult ListDisplayNameOnly()
        {
            string term;
            List<Common.Models.Contacts.Contact> list;

            term = Request["term"];

            using (IDbConnection conn = Data.Database.Instance.GetConnection())
            {
                list = Data.Contacts.Contact.List(term.Trim(), conn, false);
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "Login, User")]
        public ActionResult Details(int id)
        {
            Common.Models.Contacts.Contact contact = null;
            ViewModels.Contacts.ContactViewModel viewModel;

            using (IDbConnection conn = Data.Database.Instance.GetConnection())
            {
                contact = OpenLawOffice.Data.Contacts.Contact.Get(id, conn, false);
                if (contact.BillingRate != null && contact.BillingRate.Id.HasValue)
                    contact.BillingRate = Data.Billing.BillingRate.Get(contact.BillingRate.Id.Value, conn, false);
                else
                    contact.BillingRate = null;

                if (contact == null)
                    return View("InvalidRequest");

                viewModel = Mapper.Map<ViewModels.Contacts.ContactViewModel>(contact);
                if (contact.BillingRate != null)
                    viewModel.BillingRate = Mapper.Map<ViewModels.Billing.BillingRateViewModel>(contact.BillingRate);

                PopulateCoreDetails(viewModel, conn);
            }

            return View(viewModel);
        }

        [Authorize(Roles = "Login, User")]
        public ActionResult Create()
        {
            List<ViewModels.Billing.BillingRateViewModel> billingRateList;

            billingRateList = new List<ViewModels.Billing.BillingRateViewModel>();

            using (IDbConnection conn = Data.Database.Instance.GetConnection())
            {
                Data.Billing.BillingRate.List(conn, false).ForEach(x =>
                {
                    ViewModels.Billing.BillingRateViewModel vm = Mapper.Map<ViewModels.Billing.BillingRateViewModel>(x);
                    vm.Title += " (" + vm.PricePerUnit.ToString("C") + ")";
                    billingRateList.Add(vm);
                });
            }

            ViewBag.BillingRateList = billingRateList;

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Login, User")]
        public ActionResult Create(ViewModels.Contacts.ContactViewModel viewModel)
        {
            string errorListString = "";
            List<ViewModels.Billing.BillingRateViewModel> billingRateList;
            Common.Models.Account.Users currentUser = null;
            Common.Models.Contacts.Contact model;
            List<Common.Models.Contacts.Contact> possibleDuplicateList;

            using (Data.Transaction trans = Data.Transaction.Create(true))
            {
                try
                {
                    currentUser = Data.Account.Users.Get(trans, User.Identity.Name);

                    model = Mapper.Map<Common.Models.Contacts.Contact>(viewModel);

                    if (Request["OverrideConflict"] != "True")
                    {
                        possibleDuplicateList = Data.Contacts.Contact.ListPossibleDuplicates(trans, model);

                        if (possibleDuplicateList.Count > 0)
                        {
                            billingRateList = new List<ViewModels.Billing.BillingRateViewModel>();

                            possibleDuplicateList.ForEach(x =>
                            {
                                errorListString += "
" + x.DisplayName + " [edit]
";
                            });

                            Data.Billing.BillingRate.List(trans).ForEach(x =>
                            {
                                ViewModels.Billing.BillingRateViewModel vm = Mapper.Map<ViewModels.Billing.BillingRateViewModel>(x);
                                vm.Title += " (" + vm.PricePerUnit.ToString("C") + ")";
                                billingRateList.Add(vm);
                            });

                            ViewBag.ErrorMessage = "Contact possibly conflicts with the following existing contacts:
" + errorListString + "
Click Save again to create the contact anyway.";
                            ViewBag.OverrideConflict = "True";
                            ViewBag.BillingRateList = billingRateList;
                            return View(viewModel);
                        }
                    }

                    model = Data.Contacts.Contact.Create(trans, model, currentUser);

                    trans.Commit();
                    return RedirectToAction("Details", new { Id = model.Id.Value });
                }
                catch
                {
                    trans.Rollback();
                }
            }
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "Login, User")]
        public ActionResult Edit(int id)
        {
            Common.Models.Contacts.Contact model = null;
            ViewModels.Contacts.ContactViewModel viewModel;
            List<ViewModels.Billing.BillingRateViewModel> billingRateList;

            billingRateList = new List<ViewModels.Billing.BillingRateViewModel>();

            using (IDbConnection conn = Data.Database.Instance.GetConnection())
            {
                model = Data.Contacts.Contact.Get(id, conn, false);

                viewModel = Mapper.Map<ViewModels.Contacts.ContactViewModel>(model);

                if (model.BillingRate != null && model.BillingRate.Id.HasValue)
                {
                    model.BillingRate = Data.Billing.BillingRate.Get(model.BillingRate.Id.Value, conn, false);
                    viewModel.BillingRate = Mapper.Map<ViewModels.Billing.BillingRateViewModel>(model.BillingRate);
                }

                Data.Billing.BillingRate.List(conn, false).ForEach(x =>
                {
                    ViewModels.Billing.BillingRateViewModel vm = Mapper.Map<ViewModels.Billing.BillingRateViewModel>(x);
                    vm.Title += " (" + vm.PricePerUnit.ToString("C") + ")";
                    billingRateList.Add(vm);
                });
            }

            ViewBag.BillingRateList = billingRateList;

            return View(viewModel);
        }

        [HttpPost]
        [Authorize(Roles = "Login, User")]
        public ActionResult Edit(int id, ViewModels.Contacts.ContactViewModel viewModel)
        {
            Common.Models.Account.Users currentUser = null;
            Common.Models.Contacts.Contact model, oldModel;

            using (Data.Transaction trans = Data.Transaction.Create(true))
            {
                try
                {
                    // When modifying a user, if they have a billing rate then if they are being modified from an employee to not an employee (terminated)
                    // we need to make sure and retain that billing rate - needs to also retain the rate for future edits - basically, once there is a billing rate
                    // there will always be a billing rate

                    currentUser = Data.Account.Users.Get(trans, User.Identity.Name);

                    model = Mapper.Map<Common.Models.Contacts.Contact>(viewModel);

                    oldModel = Data.Contacts.Contact.Get(trans, id);
                    if (oldModel.BillingRate != null && oldModel.BillingRate.Id.HasValue)
                        model.BillingRate = oldModel.BillingRate;

                    model = Data.Contacts.Contact.Edit(trans, model, currentUser);

                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                }
            }

            return RedirectToAction("Index");
        }

        [Authorize(Roles = "Login, User")]
        public ActionResult Conflicts(int id)
        {
            List<Common.Models.Matters.Matter> matterList = null;
            Common.Models.Contacts.Contact contact;
            List<Tuple<Common.Models.Matters.Matter, Common.Models.Matters.MatterContact, Common.Models.Contacts.Contact>> matterRelationshipList;
            ViewModels.Contacts.ConflictViewModel viewModel = new ViewModels.Contacts.ConflictViewModel();

            using (IDbConnection conn = Data.Database.Instance.GetConnection())
            {
                contact = Data.Contacts.Contact.Get(id, conn, false);

                viewModel.Contact = Mapper.Map<ViewModels.Contacts.ContactViewModel>(contact);

                viewModel.Matters = new List<ViewModels.Contacts.ConflictViewModel.MatterRelationship>();

                matterList = Data.Contacts.Contact.ListMattersForContact(id, conn, false);

                foreach (var x in matterList)
                {
                    ViewModels.Contacts.ConflictViewModel.MatterRelationship mr = new ViewModels.Contacts.ConflictViewModel.MatterRelationship();

                    mr.Matter = Mapper.Map<ViewModels.Matters.MatterViewModel>(x);

                    mr.MatterContacts = new List<ViewModels.Matters.MatterContactViewModel>();

                    matterRelationshipList = Data.Contacts.Contact.ListMatterRelationshipsForContact(id, x.Id.Value, conn, false);

                    matterRelationshipList.ForEach(y =>
                    {
                        ViewModels.Matters.MatterContactViewModel mc = Mapper.Map<ViewModels.Matters.MatterContactViewModel>(y.Item2);
                        mc.Contact = Mapper.Map<ViewModels.Contacts.ContactViewModel>(y.Item3);
                        mc.Matter = mr.Matter;
                        mr.MatterContacts.Add(mc);
                    });

                    viewModel.Matters.Add(mr);
                };
            }

            return View(viewModel);
        }

        [Authorize(Roles = "Login, User")]
        public ActionResult Matters(int? id)
        {
            List<ViewModels.Matters.MatterViewModel> list;
            int contactId;

            if (id.HasValue)
                contactId = id.Value;
            else
                contactId = int.Parse(Request["ContactId"]);

            list = new List<ViewModels.Matters.MatterViewModel>();
            using (IDbConnection conn = Data.Database.Instance.GetConnection())
            {
                ViewBag.Contact = Mapper.Map<ViewModels.Contacts.ContactViewModel>(Data.Contacts.Contact.Get(contactId));
                Data.Matters.Matter.ListAllMattersForContact(contactId, conn, false).ForEach(x =>
                {
                    list.Add(Mapper.Map<ViewModels.Matters.MatterViewModel>(x));
                });
            }

            return View(list);
        }

        [Authorize(Roles = "Login, User")]
        public ActionResult Tasks(int? id)
        {
            ViewModels.Tasks.TaskViewModel viewModel;
            List<ViewModels.Tasks.TaskViewModel> list;
            int contactId;

            if (id.HasValue)
                contactId = id.Value;
            else
                contactId = int.Parse(Request["ContactId"]);

            list = new List<ViewModels.Tasks.TaskViewModel>();

            using (IDbConnection conn = Data.Database.Instance.GetConnection())
            {
                ViewBag.Contact = Mapper.Map<ViewModels.Contacts.ContactViewModel>(Data.Contacts.Contact.Get(contactId));
                Data.Tasks.Task.ListAllTasksForContact(contactId, conn, false).ForEach(x =>
                {
                    viewModel = Mapper.Map<ViewModels.Tasks.TaskViewModel>(x);

                    if (viewModel.IsGroupingTask)
                    {
                        if (Data.Tasks.Task.GetTaskForWhichIAmTheSequentialPredecessor(x.Id.Value, conn, false) != null)
                            viewModel.Type = "Sequential Group";
                        else
                            viewModel.Type = "Group";
                    }
                    else
                    {
                        if (x.SequentialPredecessor != null)
                            viewModel.Type = "Sequential";
                        else
                            viewModel.Type = "Standard";
                    }
                    list.Add(viewModel);
                });
            }

            return View(list);
        }
    }
}


text:
This plugin implements BLE support for Android and iOS. Enable your Cordova and PhoneGap mobile applications to communicate with all sorts of BLE devices.

Available functionality:

* Scan for BLE devices
* Establish connections
* List services, characteristics and descriptors
* Read and write the values of characteristics and descriptors
* Request notification of changes to the values of characteristics
* Poll RSSI (signal strength) of a device

### Use Evothings Studio for fast and easy BLE mobile app development

This plugin is used in Evothings Studio, and is compatible with Apache Cordova and PhoneGap.

[Evothings Studio](http://evothings.com) is a development and prototyping tool for making Cordova/PhoneGap apps. With Evothings Studio the edit/run turn-around cycle is just a second or two, which is much faster compared to the traditional method of rebuilding the Cordova project for each update.

[![Evothings Studio Workflow](http://evomedia.evothings.com/2013/11/illustration_ble_plugin.jpg)](http://evothings.com)

See [Evothings Examples](http://evothings.com/doc/examples/examples.html) for comprehensive examples of mobile apps that communicate over Bluetooth Low Energy, and which you can use for your own projects to get quickly up and running.

### Documentation

Reference documentation is available in the [ble.js](https://github.com/evothings/cordova-ble/blob/master/ble.js) source file.

To build the documentation using [jsdoc](https://github.com/jsdoc3/jsdoc), run this command:

    jsdoc -l -c conf.json ble.js

The file [introduction.md](introduction.md) contains a general introduction to BLE programming.

### Getting started tutorial

Read the [BLE app development tutorial](http://evothings.com/ble-app-development-explained/) to get started with your BLE mobile application.

[![BLE Mobile App Development Video](http://evomedia.evothings.com/2013/11/youtube_ble_example_start.png)](http://www.youtube.com/watch?v=A7uxNS_0QOI)

### Download Evothings Studio

[Download Evothings Studio now](http://evothings.com/download/) - it is fun and easy to get started. And it is all open source!


text:
namespace MonsterClicker
{
    using System;
    using System.Windows.Forms;

    public static class StartUp
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}


text:
#ifndef __OPENSPACE_CORE___LONGPROPERTY___H__
#define __OPENSPACE_CORE___LONGPROPERTY___H__

 /**
 * \file longproperty.h
 *
 * \addtogroup openspace
 * @{
 * \addtogroup properties
 * @{

 * \class LongProperty
 * This class is a concrete implementation of openspace::properties::TemplateProperty with
 * the type long.

 * @} @}
 */

#include <openspace/properties/numericalproperty.h>
#include <limits>

namespace openspace::properties {

class LongProperty : public NumericalProperty<long> {
public:
    LongProperty(Property::PropertyInfo info, long value = long(0),
        long minValue = std::numeric_limits<long>::lowest(),
        long maxValue = std::numeric_limits<long>::max(),
        long stepValue = long(1));

    std::string_view className() const override;
    int typeLua() const override;

    using TemplateProperty<long>::operator=;

protected:
    long fromLuaConversion(lua_State* state, bool& success) const override;
};

} // namespace openspace::properties

#endif // __OPENSPACE_CORE___LONGPROPERTY___H__


text:
CKEDITOR.plugins.setLang( 'indent', 'gl', {
	indent: 'Aumentar Sangría',
	outdent: 'Disminuir Sangría'
});


text:
package io.fastjson.bnsf.holders.basic;

import io.fastjson.bnsf.WireValueType;
import io.fastjson.bnsf.holders.WireValueHolder;

/**
 * Created by Richard on 9/25/14.
 */
public class UintHolder  extends Number implements WireValueHolder {
    private char value;

    public char getValue() {
        return value;
    }

    public void setValue(char value) {
        this.value = value;
    }

    @Override
    public WireValueType type() {
        return WireValueType.UINT;
    }

    @Override
    public int intValue() {
        return value;
    }

    @Override
    public long longValue() {
        return value;
    }

    @Override
    public float floatValue() {
        return value;
    }

    @Override
    public double doubleValue() {
        return value;
    }

}


text:
PHP Intro: gestione di form

  <?php if($errors) { ?>

Il form contiene degli errori. Correggi e riprova.

        <?php foreach($errors as $e) { ?>

<?=$e?>

        <?php } ?>

  <?php } ?>

  <form method='post'>

      Nome
      <input type="text" class="form-control" id="fname" name='fname' placeholder="Nome" value="<?=htmlspecialchars($form['fname'])?>">

      Cognome
      <input type="text" class="form-control" id="lname" name='lname' placeholder="Cognome" value="<?=$form['lname']?>">

      Email
      <input type="text" class="form-control" id="email" name='email' placeholder="email@example.com" value="<?=$form['email']?>">

      Username
      <input type="text" class="form-control" id="username" name='username' placeholder="" value="<?=$form['username']?>">

Solo lettere, numeri e trattini alti.

      Password
      <input type="password" class="form-control" id="password" name="password" placeholder="Password">

      Digita nuovamente la password
      <input type="password" class="form-control" id="password2" name="password2" placeholder="Password">

      Privacy

      <input type="checkbox" id="privacy" name="privacy" value="1" <?=$form['privacy']?>>
      Acconsento al trattamento dei dati

    <button type="submit" class="btn btn-primary">Invia</button>
  </form>

Funzioni utili in questa fase

    echo($x): stampa immediatamente una stringa

    print_r($x): stampa ricorsivamente una variabile (solo per debug)

    die($x): stampa $x (opzionale) e termina immediatamente l'esecuzione dello script

    isset($x): true se la variabile è definita, false altrimenti

    strlen($x): ritorna la lunghezza della stringa (in byte)

    filter_var($x,FILTER_VALIDATE_EMAIL)($x): ritorna true se la variabile è un indirizzo di email valido

    preg_match(...): controlla se la stringa corrisponde all'espressione regolare

    include($fileName): include sul posto il file $fileName


text:
package org.nutz.lang.util;

import java.util.Date;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author hxy
 */
public class CronSequenceGeneratorTests {

    public CronSequenceGeneratorTests() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @SuppressWarnings("deprecation")
    @Test
    public void testAt50Seconds() {
        assertEquals(new Date(2012, 6, 2, 1, 0),
                new CronSequenceGenerator("*/15 * 1-4 * * *").next(new Date(2012, 6, 1, 9, 53, 50)));
    }

    @SuppressWarnings("deprecation")
    @Test
    public void testAt0Seconds() {
        assertEquals(new Date(2012, 6, 2, 1, 0),
                new CronSequenceGenerator("*/15 * 1-4 * * *").next(new Date(2012, 6, 1, 9, 53)));
    }

    @SuppressWarnings("deprecation")
    @Test
    public void testAt0Minutes() {
        assertEquals(new Date(2012, 6, 2, 1, 0),
                new CronSequenceGenerator("0 */2 1-4 * * *").next(new Date(2012, 6, 1, 9, 0)));
    }

    @SuppressWarnings("deprecation")
    @Test(expected = IllegalArgumentException.class)
    public void testWith0Increment() {
        new CronSequenceGenerator("*/0 * * * * *").next(new Date(2012, 6, 1, 9, 0));
    }

    @SuppressWarnings("deprecation")
    @Test(expected = IllegalArgumentException.class)
    public void testWithNegativeIncrement() {
        new CronSequenceGenerator("*/-1 * * * * *").next(new Date(2012, 6, 1, 9, 0));
    }
}


text:
{% extends "html/core/hints/base.html" %}

{% block hint_content %}

{{ user }}, {% trans %}there are no Services yet{% endtrans %}.

{% endblock %}


text:
//
//  RealNumericIndexer.java
//  xal
//
//  Created by Thomas Pelaia on 6/23/06.
//  Copyright 2006 Oak Ridge National Lab. All rights reserved.
//

package xal.tools;

import java.util.*;

/** Order objects by their specified numeric index and assign a corresponding integer index based on sequential order and provide mapping between the two indices. */
public class RealNumericIndexer<T> implements Iterable<T> {
	/** records of data */
	protected final List<NumericRecord<T>> _records;

	/** Constructor */
	public RealNumericIndexer() {
		_records = new ArrayList<NumericRecord<T>>();
	}

	/**
	 * Get the size
	 * @return the number of items indexed
	 */
	public int size() {
		return _records.size();
	}

	/**
	 * Get an indexer for the indexed items.
	 * @return an iterator over the indexed items
	 */
	public Iterator<T> iterator() {
		return new Iterator<T> () {
			int index = 0;

			public boolean hasNext() {
				return index < _records.size();
			}

			public T next() {
				return _records.get( index++ ).getValue();
			}

			public void remove() {
				throw new UnsupportedOperationException( "RealNumericIndexer does not support the remove() operation in its iterator." );
			}
		};
	}

	/**
	 * Generate a list of the values.
	 * @return a list of the values ordered according to the index
	 */
	public List<T> toList() {
		final List<T> list = new ArrayList<T>();
		final Iterator<T> iterator = iterator();
		while( iterator.hasNext() ) {
			list.add( iterator.next() );
		}
		return list;
	}

	/**
	 * Get the element at the specified index
	 * @return the value at the specified index
	 */
	public T get( final int index ) {
		return _records.get( index ).getValue();
	}

	/**
	 * Get the location corresponding to the specified index.
	 * @param index the index of the record to fetch
	 * @return the location corresponding to the specified index
	 */
	public double getLocation( final int index ) {
		return _records.get( index ).getLocation();
	}

	/**
	 * Get the index which is the greatest integer less than or equal to the index of the specified location.
	 * However, if there are several indices for the specified location, pick the least one.
	 * @param location the location for which to identify the array index
	 * @return the index which is the greatest integer less than or equal to the index of the specified location
	 */
	public int getLowerIndex( final double location ) {
		int lowerIndex = (int)Math.floor( findIndex( location ) );
		// now search for the smallest index corresponding to the specified location
		for ( int index = lowerIndex - 1 ; index >= 0 ; index-- ) {
			if ( getLocation( index ) < location )   break;
			lowerIndex = index;
		}

		return lowerIndex;
	}

	/**
	 * Get the index which is the least integer greater than or equal to the index of the specified location but the greatest of equals.
	 * However, if there are several indices for the specified location, pick the greatest one.
	 * @param location the location for which to identify the array index
	 * @return the index which is the least integer greater than or equal to the index of the specified location
	 */
	public int getUpperIndex( final double location ) {
		return getUpperIndex( location, 0 );
	}

	/**
	 * Get the index which is the least integer greater than or equal to the index of the specified location but the greatest of equals.
	 * However, if there are several indices for the specified location, pick the greatest one.
	 * @param location the location for which to identify the array index
	 * @param startIndex the initial index from which to start the upward search
	 * @return the index which is the least integer greater than or equal to the index of the specified location
	 */
	private int getUpperIndex( final double location, final int startIndex ) {
		final int count = size();
		int upperIndex = (int)Math.ceil( findIndex( location, startIndex, count - 1 ) );
		// now search for the largest index corresponding to the specified location
		for ( int index = upperIndex ; index < count ; index++ ) {
			if ( getLocation( index ) > location )   break;
			upperIndex = index;
		}

		return upperIndex;
	}

	/**
	 * Get the smallest range of indices whose location range contains the specified range inclusive.
	 * @param startLocation the starting location
	 * @param endLocation the ending location
	 * @return the indices corresponding to the location range or a range of -1s if none exists
	 */
	public int[] getIndicesWithinLocationRange( final double startLocation, final double endLocation ) {
		final int count = size();
		if ( count == 0 ) {
			return null;
		}
		else if ( startLocation == endLocation ) {
			final int index = (int)findIndex( startLocation );
			return getLocation( index ) == startLocation ? new int[] { index, index } : null;
		}
		else {
			int lowerIndex = getLowerIndex( startLocation );
			if ( getLocation( lowerIndex ) < startLocation )  ++lowerIndex;
			if ( lowerIndex >= count )  return null;
			int upperIndex = getUpperIndex( endLocation, lowerIndex );
			if ( getLocation( upperIndex ) > endLocation )  --upperIndex;
			if ( upperIndex >= lowerIndex ) {
				return new int[] { lowerIndex, upperIndex };
			}
			else {
				return null;
			}
		}
	}

	/**
	 * Get the index which is closest to the index of the specified location and round down if two are equally close.
	 * @param location the location for which to identify the array index
	 * @return the closest index
	 */
	public int getClosestIndex( final double location ) {
		return (int)Math.round( findIndex( location ) );
	}

	/**
	 * Get the index of the specified location.
	 * @param location the location for which to identify the array index
	 * @return the array index for the specified location
	 */
	public double findIndex( final double location ) {
		return findIndex( location, 0, size() - 1 );
	}

	/**
	 * Get the index of the specified location.
	 * @param location the location for which to identify the array index
	 * @return the array index for the specified location
	 */
	private double findIndex( final double location, final int startIndex, final int endIndex ) {
		if ( startIndex == endIndex )  return startIndex;
		if ( size() == 0 )  return Double.NaN;

		int nmin = startIndex;
		int nmax = endIndex;
		double xmin = getLocation( nmin );
		double xmax = getLocation( nmax );

		if (xmin >= location) return nmin;
		if (xmax <= location) return nmax;

		int iterations = 0;
		while ( nmax - nmin > 1 ) {
			iterations += 1;
			int index = (int)Math.round(estimateIndex( location, nmin, nmax, xmin, xmax ));
			if (index <= nmin) index = nmin+1; // this is needed to guarantee progress
			else if (index >= nmax) index = nmax-1;

			final double middle = getLocation( index );
			if ( location > middle ) {
				xmin = middle;
				nmin = index;
			} else if (location < middle) {
				xmax = middle;
				nmax = index;
			} else {
				nmin = nmax = index;
				break;
			}

		}
		return location >= xmin ? nmax : nmin;
	}

	/**
	 * Estimate the index of the element at the specified location
	 * @param x the location for which to estimate the index
	 * @return the estimated index
	 */
	static private double estimateIndex( final double x, final int nmin, final int nmax, final double xmin, final double xmax ) {
		return ( nmin * ( xmax - x ) + nmax * ( x - xmin ) ) / ( xmax - xmin );
	}

	/**
	 * Get the minimum location.
	 * @return the minimum location
	 */
	private double getMinLocation() {
		return size() > 0 ? _records.get( 0 ).getLocation() : Double.NaN;
	}

	/**
	 * Get the maximum location.
	 * @return the maximum location
	 */
	private double getMaxLocation() {
		final int count = size();
		return count > 0 ? _records.get( count - 1 ).getLocation() : Double.NaN;
	}

	/**
	 * Add the specified value at the specified location.
	 * @param value the value to add
	 * @param location the location of the value
	 */
	public void add( final double location, final T value ) {
		final NumericRecord<T> newRecord = new NumericRecord<T>( value, location );
		final int NUM_RECORDS = _records.size();
		if ( NUM_RECORDS > 0 ) {
			final int index = getUpperIndex( location );
			if ( location < getMinLocation() ) {
				_records.add( 0, newRecord );
			}
			else if ( location >= getMaxLocation() ) {
				_records.add( newRecord );
			}
			else if ( index >= 0 && index < NUM_RECORDS ) {
				_records.add( index, newRecord );
			}
			else {
				throw new RuntimeException( "RealNumericIndexer exception while adding a new record at location: " + location + " with index: " + index );
			}
		}
		else {
			_records.add( newRecord );
		}
	}

	/**
	 * Remove the specified item by index.
	 * @param index the index of the item to remove
	 */
	public T remove( final int index ) {
		final NumericRecord<T> record = _records.remove( index );
		return record != null ? record.getValue() : null;
	}
}

/** numeric record */
final class NumericRecord<T> implements Comparable<NumericRecord<T>> {
	protected T _value;
	protected double _location;

	/** constructor */
	public NumericRecord( final T value, final double location ) {
		_value = value;
		_location = location;
	}

	/** get the value */
	final public T getValue() {
		return _value;
	}

	/** get the location */
	final public double getLocation() {
		return _location;
	}

	/** compare this record to another */
	final public int compareTo( final NumericRecord<T> record ) {
		return _location < record._location ? -1 : _location > record._location ? 1 : 0;
	}

	/** string representation */
	@Override
    final public String toString() {
		return "location:  " + _location + ", value:  " + _value;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.devocative</groupId>
		<artifactId>ares-parent</artifactId>
		<version>1.0-SNAPSHOT</version>
	</parent>
	<artifactId>ares-web</artifactId>
	<packaging>jar</packaging>

	<name>Ares Web</name>

	<dependencies>

		<dependency>
			<groupId>org.devocative</groupId>
			<artifactId>ares-common</artifactId>
			<version>1.0-SNAPSHOT</version>
		</dependency>

		<dependency>
			<groupId>org.devocative</groupId>
			<artifactId>demeter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
		</dependency>

	</dependencies>

	<build>
		<resources>

			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**</include>
				</includes>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</resource>

		</resources>
	</build>
</project>


text:
namespace file_manager {
namespace util {
namespace {

// Helper class that sets up a temporary file system.
class TempFileSystem {
 public:
  TempFileSystem(Profile* profile, const GURL& appURL)
      : name_(base::UnguessableToken::Create().ToString()),
        appURL_(appURL),
        origin_(url::Origin::Create(appURL)),
        file_system_context_(
            GetFileSystemContextForSourceURL(profile, appURL)) {}

  ~TempFileSystem() {
    storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(name_);
  }

  // Finishes setting up the temporary file system. Must be called before use.
  bool SetUp() {
    if (!temp_dir_.CreateUniqueTempDir()) {
      return false;
    }
    if (!storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem(
            name_, storage::kFileSystemTypeLocal,
            storage::FileSystemMountOption(), temp_dir_.GetPath())) {
      return false;
    }

    // Grant the test extension the ability to access the just created
    // file system.
    file_system_context_->external_backend()->GrantFileAccessToOrigin(
        origin_, base::FilePath(name_));
    return true;
  }

  bool TearDown() {
    return storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(
        name_);
  }

  // For the given FileSystemURL creates a file.
  base::File::Error CreateFile(const storage::FileSystemURL& url) {
    return storage::AsyncFileTestHelper::CreateFile(file_system_context_, url);
  }

  // For the given FileSystemURL creates a directory.
  base::File::Error CreateDirectory(const storage::FileSystemURL& url) {
    return storage::AsyncFileTestHelper::CreateDirectory(file_system_context_,
                                                         url);
  }

  // Creates an external file system URL for the given path.
  storage::FileSystemURL CreateFileSystemURL(const std::string& path) {
    return file_system_context_->CreateCrackedFileSystemURL(
        blink::StorageKey(origin_), storage::kFileSystemTypeExternal,
        base::FilePath().Append(name_).Append(
            base::FilePath::FromUTF8Unsafe(path)));
  }

 private:
  const std::string name_;
  const GURL appURL_;
  const url::Origin origin_;
  storage::FileSystemContext* const file_system_context_;
  base::ScopedTempDir temp_dir_;
};

// Parameter for the unit test to allow us to test both System Files App case
// and Extension Files app.
enum FilesAppMode {
  EXTENSION_FILES_APP,
  SYSTEM_FILES_APP,
};

class FileManagerFileAPIUtilTest
    : public ::testing::TestWithParam<FilesAppMode> {
 public:
  FileManagerFileAPIUtilTest() {
    if (GetParam() == SYSTEM_FILES_APP) {
      feature_list_.InitAndEnableFeature(chromeos::features::kFilesSWA);
    }
  }

  // Carries information on how to create a FileSystemURL for a given file name.
  // For !valid orders we create a test URL. Otherwise, we use temp file system.
  struct FileSystemURLOrder {
    std::string file_name;
    bool valid;
  };

  void SetUp() override {
    testing::Test::SetUp();
    profile_manager_ = std::make_unique<TestingProfileManager>(
        TestingBrowserProcess::GetGlobal());
    ASSERT_TRUE(profile_manager_->SetUp());
    profile_ = profile_manager_->CreateTestingProfile("testing_profile");
  }

  void TearDown() override {
    profile_manager_->DeleteAllTestingProfiles();
    profile_ = nullptr;
    profile_manager_.reset();
  }

  TestingProfile* GetProfile() { return profile_; }

 protected:
  // Checks if the conversion of FileDefinition to EntryDefinition works
  // correctly for the given |appURLStr| and a set of |orders|. If the
  // order indicates that the file should not be created, we expect the
  // conversion to return base::File::FILE_ERROR_NOT_FOUND error. Otherwise,
  // we expect base::File::FILE_OK status.
  void CheckConvertFileDefinitionListToEntryDefinitionList(
      const std::string& appURLStr,
      const std::vector<FileSystemURLOrder>& orders) {
    GURL appURL(appURLStr);
    ASSERT_TRUE(appURL.is_valid());
    auto temp_file_system = std::make_unique<TempFileSystem>(profile_, appURL);
    ASSERT_TRUE(temp_file_system->SetUp());

    std::vector<base::File::Error> errors;
    std::vector<FileDefinition> file_definitions;
    for (const FileSystemURLOrder& order : orders) {
      storage::FileSystemURL fs_url;
      if (order.valid) {
        fs_url = temp_file_system->CreateFileSystemURL(order.file_name);
        errors.push_back(base::File::FILE_OK);
      } else {
        fs_url = storage::FileSystemURL::CreateForTest(
            blink::StorageKey(url::Origin::Create(appURL)),
            storage::kFileSystemTypeExternal, base::FilePath(order.file_name));
        errors.push_back(base::File::FILE_ERROR_NOT_FOUND);
      }
      file_definitions.push_back({.virtual_path = fs_url.virtual_path()});
    }

    base::RunLoop run_loop;
    EntryDefinitionListCallback callback = base::BindOnce(
        [](std::unique_ptr<TempFileSystem> temp_file_system,
           std::vector<base::File::Error> errors,
           base::OnceClosure quit_closure,
           std::unique_ptr<EntryDefinitionList> entries) {
          ASSERT_EQ(errors.size(), entries->size());
          for (size_t i = 0; i < errors.size(); ++i) {
            const EntryDefinition& entry_def = (*entries)[i];
            EXPECT_EQ(errors[i], entry_def.error)
                << "for " << entry_def.full_path << " at " << i;
          }

          EXPECT_TRUE(temp_file_system->TearDown());
          std::move(quit_closure).Run();
        },
        std::move(temp_file_system), std::move(errors), run_loop.QuitClosure());
    ConvertFileDefinitionListToEntryDefinitionList(
        GetFileSystemContextForSourceURL(profile_, appURL),
        url::Origin::Create(appURL), file_definitions, std::move(callback));
    run_loop.Run();
  }

  void TestGenerateUnusedFilename(std::vector<std::string> existing_files,
                                  std::string target_filename,
                                  base::FileErrorOr<std::string> expected);

  const std::string file_system_id_ = "test-filesystem";

 private:
  base::test::ScopedFeatureList feature_list_;
  content::BrowserTaskEnvironment task_environment_;
  std::unique_ptr<TestingProfileManager> profile_manager_;
  TestingProfile* profile_;
};

// Passes the |result| to the |output| pointer.
void PassFileChooserFileInfoList(FileChooserFileInfoList* output,
                                 FileChooserFileInfoList result) {
  for (const auto& file : result)
    output->push_back(file->Clone());
}

TEST_P(FileManagerFileAPIUtilTest,
       ConvertSelectedFileInfoListToFileChooserFileInfoList) {
  Profile* const profile = GetProfile();
  const std::string extension_id = "abc";
  auto fake_provider =
      ash::file_system_provider::FakeExtensionProvider::Create(extension_id);
  const auto kProviderId = fake_provider->GetId();
  auto* service = ash::file_system_provider::Service::Get(profile);
  service->RegisterProvider(std::move(fake_provider));
  service->MountFileSystem(
      kProviderId, ash::file_system_provider::MountOptions(file_system_id_,
                                                           "Test FileSystem"));

  // Obtain the file system context.
  content::StoragePartition* const partition =
      profile->GetStoragePartitionForUrl(GURL("http://example.com"));
  ASSERT_TRUE(partition);
  storage::FileSystemContext* const context = partition->GetFileSystemContext();
  ASSERT_TRUE(context);

  // Prepare the test input.
  SelectedFileInfoList selected_info_list;

  // Native file.
  {
    ui::SelectedFileInfo info;
    info.file_path = base::FilePath(FILE_PATH_LITERAL("/native/File 1.txt"));
    info.local_path = base::FilePath(FILE_PATH_LITERAL("/native/File 1.txt"));
    info.display_name = "display_name";
    selected_info_list.push_back(info);
  }

  const std::string path = FILE_PATH_LITERAL(base::StrCat(
      {"/provided/", extension_id, ":", file_system_id_, ":/hello.txt"}));
  // Non-native file with cache.
  {
    ui::SelectedFileInfo info;
    info.file_path = base::FilePath(path);
    info.local_path = base::FilePath(FILE_PATH_LITERAL("/native/cache/xxx"));
    info.display_name = "display_name";
    selected_info_list.push_back(info);
  }

  // Non-native file without.
  {
    ui::SelectedFileInfo info;
    info.file_path = base::FilePath(path);
    selected_info_list.push_back(info);
  }

  // Run the test target.
  FileChooserFileInfoList result;
  ConvertSelectedFileInfoListToFileChooserFileInfoList(
      context, GURL("http://example.com"), selected_info_list,
      base::BindOnce(&PassFileChooserFileInfoList, &result));
  content::RunAllTasksUntilIdle();

  // Check the result.
  ASSERT_EQ(3u, result.size());

  EXPECT_TRUE(result[0]->is_native_file());
  EXPECT_EQ(FILE_PATH_LITERAL("/native/File 1.txt"),
            result[0]->get_native_file()->file_path.value());
  EXPECT_EQ(u"display_name", result[0]->get_native_file()->display_name);

  EXPECT_TRUE(result[1]->is_native_file());
  EXPECT_EQ(FILE_PATH_LITERAL("/native/cache/xxx"),
            result[1]->get_native_file()->file_path.value());
  EXPECT_EQ(u"display_name", result[1]->get_native_file()->display_name);

  EXPECT_TRUE(result[2]->is_file_system());
  EXPECT_TRUE(result[2]->get_file_system()->url.is_valid());
  const storage::FileSystemURL url =
      context->CrackURLInFirstPartyContext(result[2]->get_file_system()->url);
  EXPECT_EQ(GURL("http://example.com"), url.origin().GetURL());
  EXPECT_EQ(storage::kFileSystemTypeIsolated, url.mount_type());
  EXPECT_EQ(storage::kFileSystemTypeProvided, url.type());
  EXPECT_EQ(55u, result[2]->get_file_system()->length);
}

TEST_P(FileManagerFileAPIUtilTest,
       ConvertFileDefinitionListToEntryDefinitionListExtension) {
  std::vector<FileSystemURLOrder> orders = {
      {.file_name = "x.txt", .valid = true},
      {.file_name = "no-such-file.txt", .valid = false},
      {.file_name = "z.txt", .valid = true},
  };
  CheckConvertFileDefinitionListToEntryDefinitionList("chrome-extension://abc",
                                                      orders);
  CheckConvertFileDefinitionListToEntryDefinitionList("chrome-extension://abc/",
                                                      orders);
  CheckConvertFileDefinitionListToEntryDefinitionList(
      "chrome-extension://abc/efg", orders);
}

TEST_P(FileManagerFileAPIUtilTest,
       ConvertFileDefinitionListToEntryDefinitionListApp) {
  std::vector<FileSystemURLOrder> orders = {
      {.file_name = "a.txt", .valid = false},
      {.file_name = "b.txt", .valid = false},
      {.file_name = "i-am-a-file.txt", .valid = true},
  };
  CheckConvertFileDefinitionListToEntryDefinitionList("chrome://file-manager",
                                                      orders);
  CheckConvertFileDefinitionListToEntryDefinitionList("chrome://file-manager/",
                                                      orders);
  CheckConvertFileDefinitionListToEntryDefinitionList(
      "chrome://file-manager/abc", orders);
}

TEST_P(FileManagerFileAPIUtilTest,
       ConvertFileDefinitionListToEntryDefinitionNullContext) {
  Profile* const profile = GetProfile();
  const GURL appURL("chrome-extension://abc/");
  auto temp_file_system = std::make_unique<TempFileSystem>(profile, appURL);
  ASSERT_TRUE(temp_file_system->SetUp());
  storage::FileSystemURL x_file_url =
      temp_file_system->CreateFileSystemURL(".");
  FileDefinition x_fd = {.virtual_path = x_file_url.virtual_path()};

  // Check a simple case where the context is already null before we have
  // a chance to call the conversion function.
  base::RunLoop run_loop;
  EntryDefinitionListCallback callback = base::BindOnce(
      [](std::unique_ptr<TempFileSystem> temp_file_system,
         base::OnceClosure quit_closure,
         std::unique_ptr<EntryDefinitionList> entries) {
        ASSERT_EQ(1, entries->size());
        EXPECT_EQ(base::File::FILE_ERROR_INVALID_OPERATION,
                  entries->at(0).error);
        EXPECT_TRUE(temp_file_system->TearDown());
        std::move(quit_closure).Run();
      },
      std::move(temp_file_system), run_loop.QuitClosure());

  ConvertFileDefinitionListToEntryDefinitionList(
      nullptr, url::Origin::Create(appURL), {x_fd}, std::move(callback));
  run_loop.Run();
}

TEST_P(FileManagerFileAPIUtilTest,
       ConvertFileDefinitionListToEntryDefinitionContextReset) {
  Profile* const profile = GetProfile();
  const GURL appURL("chrome-extension://abc/");
  auto temp_file_system = std::make_unique<TempFileSystem>(profile, appURL);
  ASSERT_TRUE(temp_file_system->SetUp());
  storage::FileSystemURL x_file_url =
      temp_file_system->CreateFileSystemURL(".");
  FileDefinition x_fd = {.virtual_path = x_file_url.virtual_path()};
  scoped_refptr<storage::FileSystemContext> file_system_context =
      GetFileSystemContextForSourceURL(profile, appURL);

  base::RunLoop run_loop;
  EntryDefinitionListCallback callback = base::BindOnce(
      [](std::unique_ptr<TempFileSystem> temp_file_system,
         base::OnceClosure quit_closure,
         std::unique_ptr<EntryDefinitionList> entries) {
        ASSERT_EQ(1, entries->size());
        EXPECT_EQ(base::File::FILE_OK, entries->at(0).error);
        EXPECT_TRUE(temp_file_system->TearDown());
        std::move(quit_closure).Run();
      },
      std::move(temp_file_system), run_loop.QuitClosure());

  // Check the case where the context is not null, but is reset to null as
  // soon as function call is completed. Conversion takes place on a
  // different thread, after the function call returns. However, since
  // it holds to a copy of a scoped pointer we expect it to succeed.
  ConvertFileDefinitionListToEntryDefinitionList(file_system_context,
                                                 url::Origin::Create(appURL),
                                                 {x_fd}, std::move(callback));
  file_system_context.reset();

  run_loop.Run();
}

TEST_P(FileManagerFileAPIUtilTest, IsFileManagerURL) {
  EXPECT_TRUE(IsFileManagerURL(GetFileManagerURL()));
  EXPECT_TRUE(IsFileManagerURL(GetFileManagerURL().Resolve("/some/path")));
  EXPECT_TRUE(IsFileManagerURL(
      GetFileManagerURL().Resolve("/some/path").Resolve("#anchor")));
  EXPECT_TRUE(IsFileManagerURL(GetFileManagerURL()
                                   .Resolve("/some/path")
                                   .Resolve("#anchor")
                                   .Resolve("?a=b")));
  EXPECT_FALSE(IsFileManagerURL(GURL("chrome://not-file-manager")));
  EXPECT_FALSE(IsFileManagerURL(GURL("chrome://not-file-manager/")));
  EXPECT_FALSE(IsFileManagerURL(
      GURL("chrome-extension://iamnotafilemanagerextensionid")));
  EXPECT_FALSE(IsFileManagerURL(
      GURL("chrome-extension://iamnotafilemanagerextensionid/")));
}

void FileManagerFileAPIUtilTest::TestGenerateUnusedFilename(
    std::vector<std::string> existing_files,
    std::string target_filename,
    base::FileErrorOr<std::string> expected) {
  const GURL appURL("chrome-extension://abc/");
  auto temp_file_system =
      std::make_unique<TempFileSystem>(GetProfile(), appURL);
  ASSERT_TRUE(temp_file_system->SetUp());
  storage::FileSystemURL root_url = temp_file_system->CreateFileSystemURL("");
  scoped_refptr<storage::FileSystemContext> file_system_context =
      GetFileSystemContextForSourceURL(GetProfile(), appURL);

  for (const std::string& file : existing_files) {
    if (file.back() == '/') {
      temp_file_system->CreateDirectory(
          temp_file_system->CreateFileSystemURL(file));
    } else {
      temp_file_system->CreateFile(temp_file_system->CreateFileSystemURL(file));
    }
  }

  base::RunLoop run_loop;
  GenerateUnusedFilename(
      root_url, base::FilePath(target_filename), file_system_context,
      base::BindLambdaForTesting(
          [&](base::FileErrorOr<storage::FileSystemURL> result) {
            if (expected.is_error()) {
              EXPECT_TRUE(result.is_error())
                  << "Unexpected result " << result->ToGURL();
              EXPECT_EQ(expected.error(), result.error());
            } else {
              EXPECT_FALSE(result.is_error())
                  << "Unexpected error " << result.error();
              EXPECT_EQ(temp_file_system->CreateFileSystemURL(expected.value())
                            .ToGURL(),
                        result->ToGURL());
            }
            run_loop.Quit();
          }));
  run_loop.Run();
}

TEST_P(FileManagerFileAPIUtilTest, GenerateUnusedFilenameBasic) {
  TestGenerateUnusedFilename({}, "foo.bar", {"foo.bar"});
  TestGenerateUnusedFilename({"foo.bar"}, "foo.bar", {"foo (1).bar"});
  TestGenerateUnusedFilename({"foo.bar/"}, "foo.bar", {"foo (1).bar"});
  TestGenerateUnusedFilename({"foo (1).bar"}, "foo.bar", {"foo.bar"});
  TestGenerateUnusedFilename({"foo.bar", "foo (1).bar"}, "foo.bar",
                             {"foo (2).bar"});
  TestGenerateUnusedFilename({"foo.bar", "foo (1).bar/"}, "foo.bar",
                             {"foo (2).bar"});
  TestGenerateUnusedFilename({"foo.bar", "foo (2).bar"}, "foo.bar",
                             {"foo (1).bar"});
  TestGenerateUnusedFilename({"foo.bar/", "foo (1).bar"}, "foo (1).bar",
                             {"foo (2).bar"});
  TestGenerateUnusedFilename({"foo (3).bar"}, "foo (3).bar", {"foo (1).bar"});
  TestGenerateUnusedFilename({"foo (2).bar"}, "foo (1).bar", {"foo (1).bar"});
  TestGenerateUnusedFilename({"foo (2) (1).bar"}, "foo (2) (1).bar",
                             {"foo (2) (2).bar"});
  TestGenerateUnusedFilename({"foo (2) (2).bar"}, "foo (2) (2).bar",
                             {"foo (2) (1).bar"});
  TestGenerateUnusedFilename({}, " foo.bar", {" foo.bar"});
  TestGenerateUnusedFilename({" foo.bar"}, " foo.bar", {" foo (1).bar"});
  TestGenerateUnusedFilename({"foo.bar"}, " foo.bar", {" foo.bar"});
}

TEST_P(FileManagerFileAPIUtilTest, GenerateUnusedFilenameUnicode) {
  TestGenerateUnusedFilename({}, "é è ê ô œ.txt€", {"é è ê ô œ.txt€"});
  TestGenerateUnusedFilename({"é è ê ô œ.txt€"}, "é è ê ô œ.txt€",
                             {"é è ê ô œ (1).txt€"});
}

TEST_P(FileManagerFileAPIUtilTest, GenerateUnusedFilenameNoExtension) {
  TestGenerateUnusedFilename({}, "no-ext", {"no-ext"});
  TestGenerateUnusedFilename({"no-ext"}, "no-ext", {"no-ext (1)"});
  TestGenerateUnusedFilename({"no-ext/"}, "no-ext", {"no-ext (1)"});
  TestGenerateUnusedFilename({"no-ext (1)"}, "no-ext (1)", {"no-ext (2)"});

  TestGenerateUnusedFilename({}, "a", {"a"});
  TestGenerateUnusedFilename({"a"}, "a", {"a (1)"});
  TestGenerateUnusedFilename({"a/"}, "a", {"a (1)"});
}

TEST_P(FileManagerFileAPIUtilTest, GenerateUnusedFilenameDoubleExtension) {
  TestGenerateUnusedFilename({}, "double.ext.10.13.txt",
                             {"double.ext.10.13.txt"});
  TestGenerateUnusedFilename({"double.ext.10.13.txt"}, "double.ext.10.13.txt",
                             {"double.ext.10.13 (1).txt"});
  TestGenerateUnusedFilename({"double.ext.10.13.txt/"}, "double.ext.10.13.txt",
                             {"double.ext.10.13 (1).txt"});

  TestGenerateUnusedFilename({}, "archive.tar.gz", {"archive.tar.gz"});
  TestGenerateUnusedFilename({"archive.tar.gz"}, "archive.tar.gz",
                             {"archive (1).tar.gz"});
}

TEST_P(FileManagerFileAPIUtilTest, GenerateUnusedFilenameInvalidFilename) {
  TestGenerateUnusedFilename({}, "", base::File::FILE_ERROR_INVALID_OPERATION);
  TestGenerateUnusedFilename({}, "path/with/slashes",
                             base::File::FILE_ERROR_INVALID_OPERATION);
}

INSTANTIATE_TEST_SUITE_P(FilesAppMode,
                         FileManagerFileAPIUtilTest,
                         ::testing::Values(EXTENSION_FILES_APP,
                                           SYSTEM_FILES_APP));

}  // namespace
}  // namespace util
}  // namespace file_manager