text:
using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Runtime;
using IronRuby.Runtime;
using IronRuby.Builtins;
using System;
using System.Runtime.InteropServices;
using rho.common;

namespace rho.rubyext
{
    [RubyModule("Rho")]
    public static class Rho
    {
        [RubyModule("JSON")]
        public static class RhoJSON
        {
            #region Private Implementation Details

            private static RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
                new RhoLogger("RhoJSON");

            #endregion

            #region Private Instance & Singleton Methods

            [RubyMethodAttribute("parse", RubyMethodAttributes.PublicSingleton)]
            public static object parse(RubyModule/*!*/ self, [NotNull]string/*!*/ strData)
            {
                object res = null;
                try
                {
                    res = fastJSON.RJSONTokener.JsonDecode(strData);
                }
                catch (Exception ex)
                {
                    Exception rubyEx = self.Context.CurrentException;
                    if (rubyEx == null)
                    {
                        rubyEx = RubyExceptionData.InitializeException(new RuntimeError(ex.Message.ToString()), ex.Message);
                    }
                    LOG.ERROR("parse", ex);
                    throw rubyEx;
                }

                return res;
            }

            [RubyMethodAttribute("quote_value", RubyMethodAttributes.PublicSingleton)]
            public static object quote_value(RubyModule/*!*/ self, [NotNull]string/*!*/ strData)
            {
                object res = null;
                try
                {
                    String strRes = rho.json.JSONEntry.quoteValue(strData);
                    res = CRhoRuby.Instance.createString(strRes);
                }
                catch (Exception ex)
                {
                    Exception rubyEx = self.Context.CurrentException;
                    if (rubyEx == null)
                    {
                        rubyEx = RubyExceptionData.InitializeException(new RuntimeError(ex.Message.ToString()), ex.Message);
                    }
                    LOG.ERROR("quote_value", ex);
                    throw rubyEx;
                }

                return res;
            }

            #endregion
        }
    }
}


text:
int getFile(serverData *config, char *path, char *contentType, char *header)
{
	if (strstr(path, "stats/") != NULL)
	{
		sprintf(header, "HTTP/1.1 200 OK\n\nNumber of request accepted: %d", config->requests);
		return -99;
	}
	int fd=0;
	struct stat buf;
	char * filepath = NULL;
	extern int errno;

	filepath = safemalloc(sizeof(char) * (strlen(path) + strlen(config->droot)));

	strcpy(filepath, config->droot);

	if (filepath[ strlen(filepath) - 1 ] == '/')
		filepath[ strlen(filepath) -1 ] = '\0';
	strcat(filepath,path);

	if(stat(filepath, &buf) < 0)
	{
		if (errno == ENOENT)
			strcpy(header, "HTTP/1.1 404 Not Found\n");
	}

	fd = open(filepath, O_RDONLY);

	if (fd < 0)
	{
		if(errno == EACCES)
			strcpy(header, "HTTP/1.1 500 Internal Server Error\n");
		return -1;
	}

	sprintf(header, "HTTP/1.1 200 OK\nDate: %sContent-Type: %s\nContent-Length: %d\n\n", ctime(&(buf.st_mtime)), contentType, (int) buf.st_size);

	free(filepath);

	return fd;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Fields
 */
$GLOBALS['TL_LANG']['tl_translation_fields']['fid'] = array('Feld ID', 'Diese Feld ID stellt die Verknüpfung zu einem Übersetzungsfeld her.');
$GLOBALS['TL_LANG']['tl_translation_fields']['language'] = array('Sprache', 'Dieses Feld stellt die Verknüpfung zu einer Sprache her.');
$GLOBALS['TL_LANG']['tl_translation_fields']['content'] = array('Inhalt', 'Dieses Feld zeigt den Inhalt der Übersetzung.');

/**
 * Legends
 */
$GLOBALS['TL_LANG']['tl_translation_fields']['translation_legend'] = 'Übersetzung';

/**
 * Buttons
 */
$GLOBALS['TL_LANG']['tl_translation_fields']['new'] = array('Neue Übersetzung anlegen', 'Neue Übersetzung anlegen');
$GLOBALS['TL_LANG']['tl_translation_fields']['edit'] = array('Übersetzung bearbeiten', 'Übersetzung ID %s bearbeiten');
$GLOBALS['TL_LANG']['tl_translation_fields']['delete'] = array('Übersetzung löschen', 'Übersetzung ID %s löschen');
$GLOBALS['TL_LANG']['tl_translation_fields']['show'] = array('Übersetzung anzeigen', 'Übersetzung ID %s anzeigen');


text:
package main

import (
	"fmt"
	"log"
	"strings"
	"time"

	tg "github.com/go-telegram-bot-api/telegram-bot-api"
)

func channelPost(msg *tg.Message) {
	if msg.Chat.ID == int64(chID) {
		ifNews := false
		ifBot := false
		ifUserName := false

		if msg.Text == "" {
			if msg.Caption == "" {
				return
			}
			ifNews = strings.Contains(msg.Caption, "#news")
			ifBot = strings.Contains(msg.Caption, "#bot")
			ifUserName = strings.Contains(msg.Caption, fmt.Sprint("@", bot.Self.UserName))
		} else {
			ifNews = strings.Contains(msg.Text, "#news")
			ifBot = strings.Contains(msg.Text, "#bot")
			ifUserName = strings.Contains(msg.Text, fmt.Sprint("@", bot.Self.UserName))
		}

		if ifNews && (ifBot || ifUserName) {
			users, err := getUsers()
			if err != nil {
				log.Println(err.Error())
				return
			}

			for _, user := range users {
				forw := tg.NewForward(int64(user.ID), int64(chID), msg.MessageID)
				if _, err := bot.Send(forw); err != nil {
					log.Println(err.Error())
				}
				time.Sleep(50 * time.Millisecond)
			}
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace HelloSignNet.Core
{
    public class HelloSignClient
    {
        private readonly HttpClient _httpClient;
        private JsonSerializer _serializer;

        public HelloSignClient(HelloSignConfig config)
        {
            Config = config;
            _httpClient = FrameworkHelper.CreateBasicAuthHttpClient(Config.ApiKey, "");
            _httpClient.Timeout = new TimeSpan(0, 0, 0, 0, config.ApiTimeoutMiliseconds);
        }

        public HelloSignClient(string apiKey)
            : this(new HelloSignConfig(apiKey))
        {
            // elided
        }

        public HelloSignClient(HttpClient httpClient, HelloSignConfig config = null)
        {
            _httpClient = httpClient;
            Config = config ?? new HelloSignConfig("UNKNOWN-HELLOSIGN-API-KEY");
        }

        public HelloSignConfig Config { get; set; }

        private JsonSerializer Serializer
        {
            get
            {
                return _serializer ??
                       (_serializer =
                           new JsonSerializer {ContractResolver = new FrameworkHelper.UnderscoreMappingResolver()});
            }
        }

        public IFileStorage FileStorage { get; set; }

        public Task<HSSignatureRequestResponse> GetSignatureRequest(string signatureRequestId)
        {
            return _httpClient.GetAsync(Config.GetSignatureRequestUri + "/" + signatureRequestId)
                .ContinueWith(t =>
                {
                    using (var sr = new StreamReader(t.Result.Content.ReadAsStreamAsync().Result))
                    using (var jtr = new JsonTextReader(sr))
                    {
                        var response = Serializer.Deserialize<HSSignatureRequestResponse>(jtr);
                        return response;
                    }
                });
        }

        public Task<HSSignatureRequestResponse> SendSignatureRequest(HSSendSignatureRequestData request)
        {
            if (!request.IsValid)
                throw new ArgumentException("Invalid Signature Request Data");

            var formData = CreateFormData(request);

            return _httpClient.PostAsync(Config.SendSignatureRequestUri, formData).ContinueWith(t =>
            {
                using (var sr = new StreamReader(t.Result.Content.ReadAsStreamAsync().Result))
                using (var jtr = new JsonTextReader(sr))
                {
                    var response = Serializer.Deserialize<HSSignatureRequestResponse>(jtr);
                    return response;
                }
            });
        }

        public Task<HSSignatureRequestResponse> RemindSignatureRequest(HSRemindSignatureRequestData request)
        {
            var formData = CreateFormData(request);

            return
                _httpClient.PostAsync(Config.RemindSignatureRequestUri + "/" + request.SignatureRequestId, formData)
                    .ContinueWith(t =>
                    {
                        using (var sr = new StreamReader(t.Result.Content.ReadAsStreamAsync().Result))
                        using (var jtr = new JsonTextReader(sr))
                        {
                            var response = Serializer.Deserialize<HSSignatureRequestResponse>(jtr);
                            return response;
                        }
                    });
        }

        public Task<string> DownloadSignatureRequestDocuments(HSDownloadSignatureRequestData request, string outputDir)
        {
            if (FileStorage == null)
                throw new IOException("Undefined FileStore");

            string getUrl = Config.GetSignatureRequestFilesUri + "/" + request.SignatureRequestId;

            if (!string.IsNullOrEmpty(request.FileType))
                getUrl = getUrl + "?file_type=" + request.FileType;

            return _httpClient.GetAsync(getUrl, HttpCompletionOption.ResponseHeadersRead).ContinueWith(t =>
            {
                HttpResponseMessage response = t.Result;
                ContentDispositionHeaderValue contentDisposition = response.Content.Headers.ContentDisposition;

                // Not found
                if (contentDisposition == null)
                    return null;

                var filename = contentDisposition.FileName.Trim('"');

                var download = response.Content.ReadAsStreamAsync()
                    .ContinueWith(a => FileStorage.SaveFileAsync(a.Result, outputDir, filename));
                download.Wait();

                return filename;
            });
        }

        public Task<Stream> DownloadSignatureRequestDocuments(HSDownloadSignatureRequestData request)
        {
            string getUrl = Config.GetSignatureRequestFilesUri + "/" + request.SignatureRequestId;
            if (!string.IsNullOrEmpty(request.FileType))
                getUrl = getUrl + "?file_type=" + request.FileType;

            return _httpClient.GetAsync(getUrl, HttpCompletionOption.ResponseHeadersRead).ContinueWith(t =>
            {
                HttpResponseMessage response = t.Result;

                // No documents found from the input request data
                if (response.Content.Headers.ContentDisposition == null)
                    return null;

                return response.Content.ReadAsStreamAsync().Result;
            });
        }

        public Task<bool> CancelSignatureRequest(string signatureRequestId)
        {
            return
                _httpClient.PostAsync(Config.CancelSignatureRequestUri + "/" + signatureRequestId, null).ContinueWith(t =>
                {
                    var response = t.Result;
                    return response.IsSuccessStatusCode;
                });
        }

        private MultipartFormDataContent CreateFormData(HSRemindSignatureRequestData request)
        {
            var formData = new MultipartFormDataContent();
            if (!string.IsNullOrEmpty(request.EmailAddress))
                formData.AddStringContent("email_address", request.EmailAddress);
            return formData;
        }

        private MultipartFormDataContent CreateFormData(HSSendSignatureRequestData request)
        {
            var formData = new MultipartFormDataContent();

            if (!string.IsNullOrEmpty(request.Title))
                formData.AddStringContent("title", request.Title);
            if (!string.IsNullOrEmpty(request.Subject))
                formData.AddStringContent("subject", request.Subject);
            if (!string.IsNullOrEmpty(request.Message))
                formData.AddStringContent("message", request.Message);
            if (!string.IsNullOrEmpty(request.SigningRedirectUrl))
                formData.AddStringContent("signing_redirect_url", request.SigningRedirectUrl);

            for (var i = 0; i < request.Signers.Count; i++)
            {
                formData.AddStringContent(string.Format("signers[{0}][name]", i), request.Signers[i].Name);
                formData.AddStringContent(string.Format("signers[{0}][email_address]", i),
                    request.Signers[i].EmailAddress);
                if (!string.IsNullOrEmpty(request.Signers[i].Order))
                    formData.AddStringContent(string.Format("signers[{0}][order]", i), request.Signers[i].Order);
                if (!string.IsNullOrEmpty(request.Signers[i].Pin))
                    formData.AddStringContent(string.Format("signers[{0}][pin]", i), request.Signers[i].Pin);
            }

            for (var i = 0; request.CcEmailAddresses != null && i < request.CcEmailAddresses.Count; i++)
            {
                formData.AddStringContent(string.Format("cc_email_addresses[{0}]", i), request.CcEmailAddresses[i]);
            }

            for (var i = 0; request.Files != null && i < request.Files.Count; i++)
            {
                formData.AddFileStreamContent(i, request.Files[i].FullName, request.Files[i].Name);
            }

            for (var i = 0; request.FileUrls != null && i < request.FileUrls.Count; i++)
            {
                formData.AddStringContent(string.Format("file_url[{0}]", i), request.FileUrls[i]);
            }

            if (request.UseTextTags == 1)
                formData.AddStringContent("use_text_tags", "1");

            if (request.HideTextTags == 1)
                formData.AddStringContent("hide_text_tags", "1");

            formData.AddStringContent("test_mode", "1");

            return formData;
        }

        #region Accounts API

        public Task<HSAccountResponse> GetAccount()
        {
            return _httpClient.GetAsync(Config.GetAcountUri)
                .ContinueWith(t =>
                {
                    using (var sr = new StreamReader(t.Result.Content.ReadAsStreamAsync().Result))
                    using (var jtr = new JsonTextReader(sr))
                    {
                        var response = Serializer.Deserialize<HSAccountResponse>(jtr);
                        return response;
                    }
                });
        }

        public Task<HSAccountResponse> UpdateAccount(string callbackUrl)
        {
            var formData = new MultipartFormDataContent();

            if (!string.IsNullOrEmpty(callbackUrl))
                formData.AddStringContent("callback_url", callbackUrl);

            return _httpClient.PostAsync(Config.UpdateAccountUri, formData)
                .ContinueWith(t =>
                {
                    using (var sr = new StreamReader(t.Result.Content.ReadAsStreamAsync().Result))
                    using (var tr = new JsonTextReader(sr))
                    {
                        var resp = Serializer.Deserialize<HSAccountResponse>(tr);
                        return resp;
                    }
                });
        }

        public Task<HSAccountResponse> VerifyAccount(string emailAddress)
        {
            var formData = new MultipartFormDataContent();
            if (!string.IsNullOrEmpty(emailAddress))
                formData.AddStringContent("email_address", emailAddress);

            return _httpClient.PostAsync(Config.VerifyAccountUri, formData)
                .ContinueWith(t =>
                {
                    using (var sr = new StreamReader(t.Result.Content.ReadAsStreamAsync().Result))
                    using (var tr = new JsonTextReader(sr))
                    {
                        var resp = Serializer.Deserialize<HSAccountResponse>(tr);
                        return resp;
                    }
                });
        }

        public Task<HSAccountResponse> CreateAccount(string emailAddress, string password)
        {
            var formData = new MultipartFormDataContent();
            if (!string.IsNullOrEmpty(emailAddress) && !string.IsNullOrEmpty(password))
            {
                formData.AddStringContent("email_address", emailAddress);
                formData.AddStringContent("password", password);
            }
            else
                throw new ArgumentNullException("emailAddress", "Both email address and password is required");

            return _httpClient.PostAsync(Config.CreateAccountUri, formData)
                .ContinueWith(t =>
                {
                    using (var sr = new StreamReader(t.Result.Content.ReadAsStreamAsync().Result))
                    using (var tr = new JsonTextReader(sr))
                    {
                        var resp = Serializer.Deserialize<HSAccountResponse>(tr);
                        return resp;
                    }
                });
        }

        #endregion
    }
}


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for SharesLevel.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="SharesLevel">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="low"/>
 *     <enumeration value="normal"/>
 *     <enumeration value="high"/>
 *     <enumeration value="custom"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "SharesLevel")
@XmlEnum
public enum SharesLevel {

    @XmlEnumValue("low")
    LOW("low"),
    @XmlEnumValue("normal")
    NORMAL("normal"),
    @XmlEnumValue("high")
    HIGH("high"),
    @XmlEnumValue("custom")
    CUSTOM("custom");
    private final String value;

    SharesLevel(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static SharesLevel fromValue(String v) {
        for (SharesLevel c: SharesLevel.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
const char blow_ini[] = "/blow.ini";
char iniPath[255];
char *iniKey = NULL;
int iniUsed = 0;
char g_myPrivKey[300], g_myPubKey[300];
int keyx_query_created = 0;

#define ZeroMemory(dest,count) memset((void *)dest, 0, count)
#define IsNULLorEmpty(psz) (psz==NULL || *psz=='\0')
#define isNoChar(c) ((c) == 'n' || (c) == 'N' || (c) == '0')
#define FiSH_div_ceil(n, d) ((n / d) + (!!(n % d)))
#define DH1080_INIT "DH1080_INIT "
#define DH1080_FINISH "DH1080_FINISH "
#define CBC_SUFFIX " CBC"

char *isPlainPrefix(const char *msg);
char *strfcpy(char *dest, char *buffer, int destSize); // removes leading and trailing blanks from string
void DH1080_received(SERVER_REC * server, char *msg, char *nick, char *address,
        char *target);


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License in the project root for license information.

'use strict';
var utils = require('../test/util/utils'),
  path = require('path'),
  fs = require('fs'),
  os = require('os'),
  exec = require('child_process').exec,
  execSync = require('child_process').execSync,
  oad = require('oad');

  // This map is used to store the mapping between files resolved and stored location
var resolvedMapForNewSpecs = {};
let outputFolder = path.join(os.tmpdir(), "resolved");
// Used to enable running script outside TravisCI for debugging
let isRunningInTraviCI = process.env.MODE === 'BreakingChange' && process.env.PR_ONLY === 'true';

/**
 * Compares old and new specifications for breaking change detection.
 *
 * @param {string} oldSpec Path to the old swagger specification file.
 *
 * @param {string} newSpec Path to the new swagger specification file.
 */
function runOad(oldSpec, newSpec) {
  if (oldSpec === null || oldSpec === undefined || typeof oldSpec.valueOf() !== 'string' || !oldSpec.trim().length) {
    return Promise.reject(new Error('oldSpec is a required parameter of type "string" and it cannot be an empty string.'));
  }

  if (newSpec === null || newSpec === undefined || typeof newSpec.valueOf() !== 'string' || !newSpec.trim().length) {
    return Promise.reject(new Error('newSpec is a required parameter of type "string" and it cannot be an empty string.'));
  }

  console.log(`>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>`);
  console.log(`Old Spec: "${oldSpec}"`);
  console.log(`New Spec: "${newSpec}"`);
  console.log(`>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>`);

  return oad.compare(oldSpec, newSpec, { consoleLogLevel: 'warn', json: true }).then((result) => {
    console.log(result);
    if (result !== undefined && typeof result.valueOf() === 'string' && result.indexOf(`"type": "Error"`) > -1) {
      console.log(`There are potential breaking changes in this PR. Please review before moving forward. Thanks!`);
      process.exitCode = 1;
    }
    return Promise.resolve();
  }).catch(err => {
    console.log(err);
  });
}

/**
 * Processes the given swagger and stores the resolved swagger on to disk
 *
 * @param {string} swaggerPath Path to the swagger specification file.
 */
function processViaAutoRest(swaggerPath) {
  if (swaggerPath === null || swaggerPath === undefined || typeof swaggerPath.valueOf() !== 'string' || !swaggerPath.trim().length) {
    return Promise.reject(new Error('swaggerPath is a required parameter of type "string" and it cannot be an empty string.'));
  }

  console.log(`Processing via AutoRest...`);

  let outputFileNameWithExt = path.basename(swaggerPath);
  let outputFileNameWithoutExt = path.basename(swaggerPath, '.json');
  let autoRestCmd = `autorest --input-file=${swaggerPath} --output-artifact=swagger-document.json --output-file=${outputFileNameWithoutExt} --output-folder=${outputFolder}`;

  console.log(`Executing : ${autoRestCmd}`);

  try {
    let result = execSync(`${autoRestCmd}`, { encoding: 'utf8', maxBuffer: 1024 * 1024 * 64 });
    resolvedMapForNewSpecs[outputFileNameWithExt] = path.join(outputFolder, outputFileNameWithExt);
  } catch (err) {
    // Do not update map in case of errors
  }

  return Promise.resolve();
}

//main function
async function runScript() {
  // See whether script is in Travis CI context
  console.log(`isRunningInTraviCI: ${isRunningInTraviCI}`);

  // Create directory to store the processed & resolved swaggers
  if (!fs.existsSync(outputFolder)) {
    fs.mkdirSync(outputFolder);
  }

  let swaggersToProcess = utils.getFilesChangedInPR();

  // For debugging in your repo, please uncomment following section and update swaggersToProcess array for the desired swaggers
  // if (!isRunningInTraviCI) {
  //   swaggersToProcess = [ '/Users/vishrut/git-repos/azure-rest-api-specs/specification/storage/resource-manager/Microsoft.Storage/2017-06-01/storage.json',
  //                         '/Users/vishrut/git-repos/azure-rest-api-specs/specification/network/resource-manager/Microsoft.Network/2017-06-01/applicationGateway.json' ];
  // }
  console.log(swaggersToProcess);

  for (const swagger of swaggersToProcess) {
    await processViaAutoRest(swagger);
  }

  if (isRunningInTraviCI) {
    utils.checkoutTargetBranch();
  }

  console.log(`Resolved map for the new specification is:`);
  console.dir(resolvedMapForNewSpecs);

  for (const swagger of swaggersToProcess) {
    // If file does not exists in the previous commits then we ignore it as it's new file
    if (!fs.existsSync(swagger)) {
      console.log(`File: "${swagger}" looks to be newly added in this PR.`);
      continue;
    }

    let outputFileNameWithExt = path.basename(swagger);
    console.log(outputFileNameWithExt);
    if (resolvedMapForNewSpecs[outputFileNameWithExt]) {
      await runOad(swagger, resolvedMapForNewSpecs[outputFileNameWithExt]);
    }
  }
}

// magic starts here
runScript().then(success => {
  console.log(`Thanks for using breaking change tool to review.`);
  console.log(`If you encounter any issue(s), please open issue(s) at https://github.com/Azure/openapi-diff/issues .`);
}).catch(err => {
  console.log(err);
  process.exitCode = 1;
})


text:
@media (max-width: 640px) {

 /* passer tous les éléments de largeur fixe en largeur automatique */
 body, element1, element2 {
   width: auto;
   margin: 0;
   padding: 0;
 }

 /* fixer une largeur maximale  de 100 % aux éléments potentiellement problématiques */
 img, table, td, blockquote, code, pre, textarea, input, iframe, object, embed, video {
   max-width: 100%;
 }
/* conserver le ratio des images et empêcher les débordements de boîtes dûs aux border ou padding */
 img {
   height: auto; width: auto;
   -webkit-box-sizing: border-box;
   -moz-box-sizing: border-box;
   box-sizing: border-box;
 }

 /* gestion des mots longs */
 textarea, table, td, th, code, pre, samp {
   word-wrap: break-word; /* passage à la ligne forcé */
   -webkit-hyphens: auto; /* césure propre */
   -moz-hyphens: auto;
   hyphens: auto;
 }
 code, pre, samp {
   white-space: pre-wrap; /* passage à la ligne spécifique pour les éléments à châsse fixe */
 }

 /* Passer à une seule colonne (à appliquer aux éléments multi-colonnes) */
 element1, element2 {
   float: none;
   width: auto;
 }

 /* masquer les éléments superflus */
 .hide_mobile {
   display: none !important;
 }

 /* Un message personnalisé */
 body:before {
   content: "Version mobile du site";
   display: block;
   color: #777;
   text-align: center;
   font-style: italic;
 }
}


text:
<?php

namespace AbdullahKasim\LaravelShipping\Shipping\Http\Controllers\Obj;

class Meta
{
    public $status;
}


text:
namespace media {
class GpuVideoAcceleratorFactories;
}  // namespace media

namespace content {

// RTCVideoEncoder uses a media::VideoEncodeAccelerator to implement a
// webrtc::VideoEncoder class for WebRTC.  Internally, VEA methods are
// trampolined to a private RTCVideoEncoder::Impl instance.  The Impl class runs
// on the worker thread queried from the |gpu_factories_|, which is presently
// the media thread.  RTCVideoEncoder is sychronized by webrtc::VideoSender.
// webrtc::VideoEncoder methods do not run concurrently. RtcVideoEncoder needs
// to synchronize RegisterEncodeCompleteCallback and encode complete callback.
class CONTENT_EXPORT RTCVideoEncoder
    : NON_EXPORTED_BASE(public webrtc::VideoEncoder) {
 public:
  RTCVideoEncoder(webrtc::VideoCodecType type,
                  media::GpuVideoAcceleratorFactories* gpu_factories);
  ~RTCVideoEncoder() override;

  // webrtc::VideoEncoder implementation.  Tasks are posted to |impl_| using the
  // appropriate VEA methods.
  int32_t InitEncode(const webrtc::VideoCodec* codec_settings,
                     int32_t number_of_cores,
                     size_t max_payload_size) override;
  int32_t Encode(
      const webrtc::VideoFrame& input_image,
      const webrtc::CodecSpecificInfo* codec_specific_info,
      const std::vector<webrtc::FrameType>* frame_types) override;
  int32_t RegisterEncodeCompleteCallback(
      webrtc::EncodedImageCallback* callback) override;
  int32_t Release() override;
  int32_t SetChannelParameters(uint32_t packet_loss, int64_t rtt) override;
  int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override;

 private:
  class Impl;
  friend class RTCVideoEncoder::Impl;

  void RecordInitEncodeUMA(int32_t init_retval,
                           media::VideoCodecProfile profile);

  // The video codec type, as reported to WebRTC.
  const webrtc::VideoCodecType video_codec_type_;

  // Factory for creating VEAs, shared memory buffers, etc.
  media::GpuVideoAcceleratorFactories* gpu_factories_;

  // Task runner that the video accelerator runs on.
  const scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner_;

  // The RTCVideoEncoder::Impl that does all the work.
  scoped_refptr<Impl> impl_;

  DISALLOW_COPY_AND_ASSIGN(RTCVideoEncoder);
};

}  // namespace content

#endif  // CONTENT_RENDERER_MEDIA_RTC_VIDEO_ENCODER_H_


text:
import logging
import time

from luigi_gcloud.gcore import _GCloudTask
from luigi_gcloud.storage import GCSFileSystem

logger = logging.getLogger('luigi-gcloud')

default_pig_udf = None
default_spark_udf = None

class _DataProcJob:
    def __init__(self, dataproc_api, project_id, job):
        self.dataproc_api = dataproc_api
        self.project_id = project_id
        self.job = dataproc_api.projects().jobs().submit(
                projectId=self.project_id,
                body=job).execute()
        self.job_id = self.job['reference']['jobId']
        logger.info('DataProc job %s is %s', self.job_id, str(self.job['status']['state']))

    def wait_for_done(self):
        while True:
            self.job = self.dataproc_api.projects().jobs().get(
                    projectId=self.project_id,
                    jobId=self.job_id).execute()
            if 'ERROR' == self.job['status']['state']:
                print(str(self.job))
                logger.error('DataProc job %s has errors', self.job_id)
                logger.error(self.job['status']['details'])
                logger.debug(str(self.job))
                return False
            if 'CANCELLED' == self.job['status']['state']:
                print(str(self.job))
                logger.warning('DataProc job %s is cancelled', self.job_id)
                logger.warning(self.job['status']['details'])
                logger.debug(str(self.job))
                return False
            if 'DONE' == self.job['status']['state']:
                return True
            logger.debug('DataProc job %s is %s', self.job_id, str(self.job['status']['state']))
            time.sleep(5)

    def raise_error(self, message=None):
        if 'ERROR' == self.job['status']['state']:
            if message is None:
                message = "Google DataProc job has error"
            raise Exception(message + ": " + str(self.job['status']['details']))

    def get(self):
        return self.job

class DataProcPigTask(_GCloudTask):
    service_name = "dataproc"

    def query_file(self):
        return None

    def query_uri(self):
        return self.client.project_staging() + self.resolved_name() + ".pig"

    def lib_uris(self):
        return []

    def _jar_file_uris(self):
        global default_pig_udf
        artifacts = []
        uris = self.lib_uris()
        artifacts.extend(uris)
        if default_pig_udf is not None:
            if not default_pig_udf.get('append') and len(uris) == 0:
                artifacts.extend(default_pig_udf.get('uris'))
            elif default_pig_udf.get('append'):
                artifacts.extend(default_pig_udf.get('uris'))
        return artifacts

    def run(self):
        self.start_job()
        http = self.client.http_authorized()
        dataproc_api = self.client.dataproc_api(http)
        name = self.job_name()

        if self.query_file() is not None:
            fs = GCSFileSystem()
            fs.put(self.query_file(),
                   self.query_uri())

        job = {
            "job": {
                "reference": {
                    "projectId": self.client.project_id(),
                    "jobId": name,
                },
                "placement": {
                    "clusterName": self.get_service_value("clusterName", "cluster-1")
                },
                "pigJob": {
                    "continueOnFailure": False,
                    "queryFileUri": self.query_uri(),
                    "jarFileUris": self._jar_file_uris(),
                }
            }
        }
        variables = self.variables()
        if variables is not None:
            job["job"]["pigJob"]["scriptVariables"] = variables

        print(job)
        submitted = _DataProcJob(dataproc_api, self.client.project_id(), job)
        if not submitted.wait_for_done():
            submitted.raise_error("DataProcTask has errors")

class DataProcSparkTask(_GCloudTask):
    service_name = "dataproc"

    def job_file(self):
        return None

    def job_uri(self):
        return self.client.project_staging() + self.resolved_name() + ".jar"

    def lib_uris(self):
        return []

    def main(self):
        raise NotImplementedError

    def args(self):
        return []

    def _jar_file_uris(self):
        global default_spark_udf
        artifacts = [self.job_uri()]
        uris = self.lib_uris()
        artifacts.extend(uris)
        if default_spark_udf is not None:
            if not default_spark_udf.get('append') and len(uris) == 0:
                artifacts.extend(default_spark_udf.get('uris'))
            elif default_spark_udf.get('append'):
                artifacts.extend(default_spark_udf.get('uris'))
        return artifacts

    def run(self):
        self.start_job()
        http = self.client.http_authorized()
        dataproc_api = self.client.dataproc_api(http)
        name = self.job_name()

        if self.job_file() is not None:
            logger.warning("Copying job artifact to storage. Consider uploading outside of job.")
            fs = GCSFileSystem()
            fs.put(self.get_service_value("basePath", ".") + self.job_file(),
                   self.job_uri())

        job = {
            "job": {
                "reference": {
                    "projectId": self.client.project_id(),
                    "jobId": name,
                },
                "placement": {
                    "clusterName": self.get_service_value("clusterName", "cluster-1")
                },
                "sparkJob": {
                    "mainClass": self.main(),
                    "jarFileUris": self._jar_file_uris(),
                }
            }
        }
        args = self.args()
        if args is not None:
            job["job"]["sparkJob"]["args"] = args

        print(job)
        submitted = _DataProcJob(dataproc_api, self.client.project_id(), job)
        if not submitted.wait_for_done():
            submitted.raise_error("DataProcTask has errors")

def set_default_pig_udf(uris, append=False):
    global default_pig_udf
    default_pig_udf = {
        'append': append,
        'uris': uris
    }

def set_default_spark_udf(uris, append=False):
    global default_spark_udf
    default_spark_udf = {
        'append': append,
        'uris': uris
    }


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.file.v1beta1.model;

/**
 * A Filestore snapshot.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Filestore API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Snapshot extends com.google.api.client.json.GenericJson {

  /**
   * Output only. The time when the snapshot was created.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String createTime;

  /**
   * A description of the snapshot with 2048 characters or less. Requests with longer descriptions
   * will be rejected.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String description;

  /**
   * Output only. The amount of bytes needed to allocate a full copy of the snapshot content
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long filesystemUsedBytes;

  /**
   * Resource labels to represent user provided metadata.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.String> labels;

  /**
   * Output only. The resource name of the snapshot, in the format `projects/{project_id}/locations/
   * {location_id}/instances/{instance_id}/snapshots/{snapshot_id}`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * Output only. The snapshot state.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String state;

  /**
   * Output only. The time when the snapshot was created.
   * @return value or {@code null} for none
   */
  public String getCreateTime() {
    return createTime;
  }

  /**
   * Output only. The time when the snapshot was created.
   * @param createTime createTime or {@code null} for none
   */
  public Snapshot setCreateTime(String createTime) {
    this.createTime = createTime;
    return this;
  }

  /**
   * A description of the snapshot with 2048 characters or less. Requests with longer descriptions
   * will be rejected.
   * @return value or {@code null} for none
   */
  public java.lang.String getDescription() {
    return description;
  }

  /**
   * A description of the snapshot with 2048 characters or less. Requests with longer descriptions
   * will be rejected.
   * @param description description or {@code null} for none
   */
  public Snapshot setDescription(java.lang.String description) {
    this.description = description;
    return this;
  }

  /**
   * Output only. The amount of bytes needed to allocate a full copy of the snapshot content
   * @return value or {@code null} for none
   */
  public java.lang.Long getFilesystemUsedBytes() {
    return filesystemUsedBytes;
  }

  /**
   * Output only. The amount of bytes needed to allocate a full copy of the snapshot content
   * @param filesystemUsedBytes filesystemUsedBytes or {@code null} for none
   */
  public Snapshot setFilesystemUsedBytes(java.lang.Long filesystemUsedBytes) {
    this.filesystemUsedBytes = filesystemUsedBytes;
    return this;
  }

  /**
   * Resource labels to represent user provided metadata.
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.String> getLabels() {
    return labels;
  }

  /**
   * Resource labels to represent user provided metadata.
   * @param labels labels or {@code null} for none
   */
  public Snapshot setLabels(java.util.Map<String, java.lang.String> labels) {
    this.labels = labels;
    return this;
  }

  /**
   * Output only. The resource name of the snapshot, in the format `projects/{project_id}/locations/
   * {location_id}/instances/{instance_id}/snapshots/{snapshot_id}`.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * Output only. The resource name of the snapshot, in the format `projects/{project_id}/locations/
   * {location_id}/instances/{instance_id}/snapshots/{snapshot_id}`.
   * @param name name or {@code null} for none
   */
  public Snapshot setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * Output only. The snapshot state.
   * @return value or {@code null} for none
   */
  public java.lang.String getState() {
    return state;
  }

  /**
   * Output only. The snapshot state.
   * @param state state or {@code null} for none
   */
  public Snapshot setState(java.lang.String state) {
    this.state = state;
    return this;
  }

  @Override
  public Snapshot set(String fieldName, Object value) {
    return (Snapshot) super.set(fieldName, value);
  }

  @Override
  public Snapshot clone() {
    return (Snapshot) super.clone();
  }

}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Persona */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'ID_PERSONA')->textInput() ?>

    <?= $form->field($model, 'NOMBRE')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
/*
Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
*/

#include <vector>

class Solution {
public:
    int singleNumber(std::vector<int>& nums) {
        int result = 0;
        for (int n : nums) {
            result ^= n;
        }
        return result;
    }
};


text:
namespace MassTransit.SystemView.Core
{
    using StructureMap;
    using StructureMapIntegration;

    public class SystemViewRegistry :
        MassTransitRegistryBase
    {
        public SystemViewRegistry(IConfiguration configuration, IContainer container)
        {
            RegisterControlBus(configuration.SystemViewControlUri, x => { });

            RegisterServiceBus(configuration.SystemViewDataUri, x =>
                {
                    x.SetConcurrentConsumerLimit(1);
                    x.UseControlBus(container.GetInstance<IControlBus>());

                    ConfigureSubscriptionClient(configuration.SubscriptionServiceUri, x);
                });
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="bower_components/magnify/dist/css/magnify.css">
  <link rel="stylesheet" href="app.css">

jquery.reel

images-loaded

reel+images-loaded, angular-reel

raphaeljs example

three.js

WebGL

Angular seed app: v


text:
package com.jonnyware.timetracker;

import com.jonnyware.timetracker.analyzer.DateConverter;
import com.jonnyware.timetracker.analyzer.DayMonthDateConverter;
import com.jonnyware.timetracker.line.TimeEntry;
import com.jonnyware.timetracker.line.TimeEntryLineParser;
import com.jonnyware.timetracker.line.YearLineParser;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Period;

import java.io.InputStream;
import java.util.*;

public class TimeEntryParser {
    private final Scanner scanner;
    private final DateTime now;
    private Integer year;
    Map<LocalDate, String> parsed = new TreeMap<LocalDate, String>();

    public TimeEntryParser(InputStream input, DateTime now) {
        this.scanner = new Scanner(input);
        this.now = now;
        parse();
    }

    public TimeEntryParser(String input, DateTime now) {
        this.scanner = new Scanner(input);
        this.now = now;
        parse();
    }

    private void parse() {
        LinkedList<TimeEntry> entries = new LinkedList<TimeEntry>();
        while (scanner.hasNextLine()) {
            String line = LineMassager.massage(scanner.nextLine());
            if (line.isEmpty()) {
                continue;
            }

            if (year == null) {
                year = new YearLineParser(line).getYear();
            } else {
                TimeEntry entry = new TimeEntryLineParser(line).getTimeEntry();
                entries.add(entry);
            }
        }

        DateConverter dateConverter = new DayMonthDateConverter(year);
        for (TimeEntry entry : entries) {
            LocalDate date = dateConverter.toDate(entry);
            parsed.put(date, entry.getText());
        }
    }

    public Integer getYear() {
        return year;
    }

    public Collection<NeutralDay> neutralDays() {
        Collection<NeutralDay> result = new LinkedList<NeutralDay>();

        for (Map.Entry<LocalDate, String> entry : parsed.entrySet()) {
            LocalDate date = entry.getKey();
            String value = entry.getValue();

            if (value.startsWith("=(")) {
                int right = value.indexOf(')');
                if (right > 0) {
                    String period = value.substring(2, right);
                    Period hours = Formatter.parse(period);
                    result.add(new NeutralDay(date, value.substring(right + 1), hours));
                }
            } else if (value.startsWith("=")) {
                result.add(new NeutralDay(date, value.substring(1)));
            }
        }
        return result;
    }

    public Collection<Vacation> listVacations() {
        Collection<Vacation> result = new LinkedList<Vacation>();

        for (Map.Entry<LocalDate, String> entry : parsed.entrySet()) {
            LocalDate date = entry.getKey();
            String value = entry.getValue();
            if (value.startsWith("+")) {
                result.add(new Vacation(date, value.substring(1)));
            }
        }

        return result;
    }

    public Collection<NormalDay> listTimeEntries() {
        Collection<NormalDay> result = new LinkedList<NormalDay>();

        for (Map.Entry<LocalDate, String> entry : parsed.entrySet()) {
            LocalDate date = entry.getKey();
            String value = entry.getValue();

            if (Character.isDigit(value.codePointAt(0))) {
                NormalDay interval = new IntervalParser(date, value, now).getIntervals();
                result.add(interval);
            }
        }

        return Collections.unmodifiableCollection(result);
    }
}


text:
using Graphs
using Gaston

# array of tuples of the type (x, y, z)
points = [(1, 1, 0),
          (2, 2, 0),
          (2.5, 2, 0.5),
          (3.14, 2, -0.5),
          (4, 4, 0)]

xs = map((p)-> p[1], points)
ys = map((p)-> p[2], points)
zs = map((p)-> p[3], points)

function euclidian_distance(p1, p2)
  x = (p1[1] - p2[1]) ^ 2
  y = (p1[2] - p2[2]) ^ 2
  sqrt(x + y)
end

# gets (x, y) from (x, y, z)
function twoD(p)
  (p[1], p[2])
end

# function that is used on a sorted in ascending order array. It will add the value after the first element (looking from backward) that is lower than it. Never changes the size of the array. (If a new element is added, the highest from the old ones will be removed)
function add_priority_queue(arr, x)
  i = length(arr)

  if x[3] > arr[i][3]
      return arr
  end

  while i > 0 && x[3] < arr[i][3]
    i -= 1
  end

  for j = 1:length(arr) - i - 1
    arr[length(arr) - j + 1] = arr[length(arr) - j]
  end

  arr[i + 1] = x
  arr
end

# given a number of points (x, y, z) will return n*floor(sqrt(n)) edges of the type (index, index, weight). The direction of the edge is from the point represented with the first index to the point represented with the second.
function edges(points)
  degree = int(sqrt(length(points)))
  pairs = (Int64, Int64, Float64)[]
  for i = 1:length(points)
    queue = fill((0, 0, Inf), degree)

    for j = 1:length(points)
      if i != j
        queue = add_priority_queue(queue, (i, j, euclidian_distance(points[i], points[j])))
      end
    end

    for i in queue
      push!(pairs, i)
    end
  end
  pairs
end

# as the edges() function may return a graph with some vertexes that aren't pointed by any edge, this function ensures that every vertex is reachable. It will do so by adding the inverted edges of edges that start from this vertex.
function ensure_graph_correctness(edges, points)
  # local copy of points
  lpoints = copy(points)
  for edge in edges
    lpoints[edge[2]] = (0, 0, Inf)
  end

  for i = 1:length(lpoints)
    if lpoints[i] != (0, 0, Inf)
      for edge in edges
        if edge[1] == i
          push!(edges, (edge[2], edge[1], edge[3]))
        end
      end
    end
  end
  edges
end

# BFStates stands for BellmanFordStates
function path(BFStates, from, to)
  curr_path = Int64[]
  push!(curr_path, to)
  pos = BFStates.parents[to]
  while pos != from
    push!(curr_path, pos)
    pos = BFStates.parents[pos]
  end
  push!(curr_path, from)
  (reverse(curr_path), BFStates.dists[to])
end

println(points)
wedges = edges(points)
println(wedges)
wedges = ensure_graph_correctness(wedges, points)
println(wedges)

graph = simple_inclist(length(points))

wedges_len = length(wedges)
weights = zeros(wedges_len)
for i = 1:wedges_len
  wedge = wedges[i]
  add_edge!(graph, wedge[1], wedge[2])
  weights[i] = wedge[3]
end

res = bellman_ford_shortest_paths(graph, weights, [1])
println(res)
println()
println(path(res, 1, 5))

figure()
axes = Gaston.AxesConf()
curve = Gaston.CurveConf()
curve.plotstyle = "points"
Gaston.addconf(axes)
for edge in wedges
  p1, p2 = edge
  x1, y1, z1 = points[p1]
  x2, y2, z2 = points[p2]
  # really lame api forces me to add 4 identical points instead of just one
  Gaston.addcoords([x1, x1], [y1, y1], [z1 z1; z1 z1], curve)
  Gaston.addcoords([x2, x2], [y2, y2], [z2 z2; z2 z2], curve)
end
Gaston.llplot()
sleep(3600)


text:
package com.github.ttwd80.tigerpayroll.model.entity;

import static com.mysema.query.types.PathMetadataFactory.*;

import com.mysema.query.types.path.*;

import com.mysema.query.types.PathMetadata;
import javax.annotation.Generated;
import com.mysema.query.types.Path;
import com.mysema.query.types.path.PathInits;

/**
 * QAllowance is a Querydsl query type for Allowance
 */
@Generated("com.mysema.query.codegen.EntitySerializer")
public class QAllowance extends EntityPathBase<Allowance> {

    private static final long serialVersionUID = -285534577L;

    private static final PathInits INITS = PathInits.DIRECT2;

    public static final QAllowance allowance = new QAllowance("allowance");

    public final NumberPath<java.math.BigDecimal> amount = createNumber("amount", java.math.BigDecimal.class);

    public final DateTimePath<java.time.ZonedDateTime> createdDate = createDateTime("createdDate", java.time.ZonedDateTime.class);

    public final ComparablePath<Character> id = createComparable("id", Character.class);

    public final DateTimePath<java.time.ZonedDateTime> lastModifiedDate = createDateTime("lastModifiedDate", java.time.ZonedDateTime.class);

    public final StringPath name = createString("name");

    public final NumberPath<Integer> position = createNumber("position", Integer.class);

    public final SetPath<UserAllowance, QUserAllowance> userAllowances = this.<UserAllowance, QUserAllowance>createSet("userAllowances", UserAllowance.class, QUserAllowance.class, PathInits.DIRECT2);

    public final QUser userByCreatedBy;

    public final QUser userByLastModifiedBy;

    public QAllowance(String variable) {
        this(Allowance.class, forVariable(variable), INITS);
    }

    public QAllowance(Path<? extends Allowance> path) {
        this(path.getType(), path.getMetadata(), path.getMetadata().isRoot() ? INITS : PathInits.DEFAULT);
    }

    public QAllowance(PathMetadata<?> metadata) {
        this(metadata, metadata.isRoot() ? INITS : PathInits.DEFAULT);
    }

    public QAllowance(PathMetadata<?> metadata, PathInits inits) {
        this(Allowance.class, metadata, inits);
    }

    public QAllowance(Class<? extends Allowance> type, PathMetadata<?> metadata, PathInits inits) {
        super(type, metadata, inits);
        this.userByCreatedBy = inits.isInitialized("userByCreatedBy") ? new QUser(forProperty("userByCreatedBy"), inits.get("userByCreatedBy")) : null;
        this.userByLastModifiedBy = inits.isInitialized("userByLastModifiedBy") ? new QUser(forProperty("userByLastModifiedBy"), inits.get("userByLastModifiedBy")) : null;
    }

}


text:
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SendCoinsDialog),
    model(0)
{
    ui->setupUi(this);
    GUIUtil::SetBitBayFonts(this);

#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
    ui->addButton->setIcon(QIcon());
    ui->clearButton->setIcon(QIcon());
    ui->sendButton->setIcon(QIcon());
#endif

    addEntry();

    connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
    connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));

    // Coin Control
    connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
    connect(ui->pushButtonTxPreview, SIGNAL(clicked()), this, SLOT(txPreviewButtonClicked()));

    // Coin Control: clipboard actions
    QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
    QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
    QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
    QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
    QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
    QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
    QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this);
    QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
    connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
    connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
    connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee()));
    connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee()));
    connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes()));
    connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority()));
    connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput()));
    connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange()));
    ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
    ui->labelCoinControlAmount->addAction(clipboardAmountAction);
    ui->labelCoinControlFee->addAction(clipboardFeeAction);
    ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
    ui->labelCoinControlBytes->addAction(clipboardBytesAction);
    ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
    ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
    ui->labelCoinControlChange->addAction(clipboardChangeAction);

    fNewRecipientAllowed = true;

    QString white1 = R"(
        QWidget {
            padding-left: 3px;
            padding-right:3px;
        }
    )";
    QString white2 = R"(
        QWidget {
            color: rgb(102,102,102);
            padding-left: 3px;
            padding-right:3px;
        }
    )";

    ui->labelLiquidityText  ->setStyleSheet(white2);
    ui->labelReservesText   ->setStyleSheet(white2);
    ui->labelLiquidity      ->setStyleSheet(white1);
    ui->labelReserves       ->setStyleSheet(white1);

    ui->comboBoxTxType->clear();
    ui->comboBoxTxType->addItem(tr("Transfer spendable funds (liquidity)"), PEG_MAKETX_SEND_LIQUIDITY);
    ui->comboBoxTxType->addItem(tr("Transfer reserve and freeze it for 1 month"), PEG_MAKETX_SEND_RESERVE);
    ui->comboBoxTxType->addItem(tr("Freeze reserve for 1 month (such funds have 20 BAY staking reward)"), PEG_MAKETX_FREEZE_RESERVE);
    ui->comboBoxTxType->addItem(tr("Freeze liquidity for 4 month (such funds have 40 BAY staking reward)"), PEG_MAKETX_FREEZE_LIQUIDITY);
//    ui->comboBoxTxType->insertSeparator(4);
//    ui->comboBoxTxType->addItem(tr("Transfer coins to cold wallet"), PEG_MAKETX_SEND_TOCOLD);
//    ui->comboBoxTxType->addItem(tr("Return coins from cold wallet"), PEG_MAKETX_SEND_FROMCOLD);

    connect(ui->comboBoxTxType, SIGNAL(activated(int)), this, SLOT(clear()));
}

void SendCoinsDialog::setModel(WalletModel *model)
{
    this->model = model;

    if(model && model->getOptionsModel())
    {
        for(int i = 0; i < ui->entries->count(); ++i)
        {
            SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
            if(entry)
            {
                entry->setModel(model);
            }
        }

        vector<CFrozenCoinInfo> frozenCoins;
        int64_t nFrozen = model->getFrozen(NULL, &frozenCoins);
        setBalance(model->getBalance(),
                   model->getReserve(), model->getLiquidity(), nFrozen, frozenCoins,
                   model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
        connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64, std::vector<CFrozenCoinInfo>, qint64, qint64, qint64)),
                this, SLOT(setBalance(qint64, qint64, qint64, qint64, std::vector<CFrozenCoinInfo>, qint64, qint64, qint64)));
        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));

        // Coin Control
        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));
        connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));
        connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels()));
        ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures());
        coinControlUpdateLabels();
    }
}

SendCoinsDialog::~SendCoinsDialog()
{
    delete ui;
}

void SendCoinsDialog::on_sendButton_clicked()
{
    if(!model || !model->getOptionsModel())
        return;

    QList<SendCoinsRecipient> recipients;
    bool valid = true;

    for(int i = 0; i < ui->entries->count(); ++i)
    {
        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
        if(entry)
        {
            if(entry->validate())
            {
                recipients.append(entry->getValue());
            }
            else
            {
                valid = false;
            }
        }
    }

    if(!valid || recipients.isEmpty())
    {
        return;
    }

    // Format confirmation message
    QStringList formatted;
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount), Qt::escape(rcp.label), rcp.address));
    }

    fNewRecipientAllowed = false;

    QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
                          tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
          QMessageBox::Yes|QMessageBox::Cancel,
          QMessageBox::Cancel);

    if(retval != QMessageBox::Yes)
    {
        fNewRecipientAllowed = true;
        return;
    }

    WalletModel::UnlockContext ctx(model->requestUnlock());
    if(!ctx.isValid())
    {
        // Unlock wallet was cancelled
        fNewRecipientAllowed = true;
        return;
    }

    PegTxType nTxType = static_cast<PegTxType>(ui->comboBoxTxType->currentData().toInt());
    WalletModel::SendCoinsReturn sendstatus;
    CCoinControl *coinControl = nullptr;
    string sFailCause;

    if (model->getOptionsModel() && model->getOptionsModel()->getCoinControlFeatures()) {
        coinControl = CoinControlDialog::coinControl;
    }

    sendstatus = model->sendCoins(recipients, nTxType, coinControl, sFailCause);

    if (!sFailCause.empty()) {
        sFailCause = "\n"+sFailCause;
    }
    QString errdetails = QString::fromStdString(sFailCause);

    switch(sendstatus.status)
    {
    case WalletModel::InvalidAddress:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The recipient address is not valid, please recheck.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::InvalidAmount:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The amount to pay must be larger than 0.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::InvalidTxType:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The selected transaction type is not supported yet.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::AmountExceedsBalance:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The amount exceeds your balance.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::AmountWithFeeExceedsBalance:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The total exceeds your balance when the %1 transaction fee is included.").
            arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), sendstatus.fee))+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::DuplicateAddress:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("Duplicate address found, can only send to each address once per send operation.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::TransactionCreationFailed:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("Error: Transaction creation failed!")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::TransactionCommitFailed:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("Error: The transaction was rejected. "
               "This might happen if some of the coins in your "
               "wallet were already spent, such as if you used "
               "a copy of wallet.dat and coins were spent in "
               "the copy but not marked as spent here.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::Aborted: // User aborted, nothing to do
        break;
    case WalletModel::OK:
        accept();
        CoinControlDialog::coinControl->UnSelectAll();
        coinControlUpdateLabels();
        break;
    }
    fNewRecipientAllowed = true;
}

// Coin Control: preview transaction
void SendCoinsDialog::txPreviewButtonClicked()
{
    if(!model || !model->getOptionsModel())
        return;

    QList<SendCoinsRecipient> recipients;
    bool valid = true;

    for(int i = 0; i < ui->entries->count(); ++i)
    {
        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
        if(entry)
        {
            if(entry->validate())
            {
                recipients.append(entry->getValue());
            }
            else
            {
                valid = false;
            }
        }
    }

    if(!valid || recipients.isEmpty())
    {
        return;
    }

    PegTxType nTxType = static_cast<PegTxType>(ui->comboBoxTxType->currentData().toInt());
    WalletModel::SendCoinsReturn sendstatus;
    CCoinControl *coinControl = nullptr;
    string sFailCause;

    if (model->getOptionsModel() && model->getOptionsModel()->getCoinControlFeatures()) {
        coinControl = CoinControlDialog::coinControl;
    }

    CWalletTx wtx;
    sendstatus = model->sendCoinsTest(wtx, recipients, nTxType, coinControl, sFailCause);

    if (!sFailCause.empty()) {
        sFailCause = "\n"+sFailCause;
    }
    QString errdetails = QString::fromStdString(sFailCause);

    switch(sendstatus.status)
    {
    case WalletModel::InvalidAddress:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The recipient address is not valid, please recheck.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::InvalidAmount:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The amount to pay must be larger than 0.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::InvalidTxType:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The selected transaction type is not supported yet.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::AmountExceedsBalance:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The amount exceeds your balance.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::AmountWithFeeExceedsBalance:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The total exceeds your balance when the %1 transaction fee is included.").
            arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), sendstatus.fee))+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::DuplicateAddress:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("Duplicate address found, can only send to each address once per send operation.")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::TransactionCreationFailed:
        QMessageBox::warning(this, tr("Send Coins"),
            tr("Error: Transaction creation failed!")+errdetails,
            QMessageBox::Ok, QMessageBox::Ok);
        break;
    case WalletModel::TransactionCommitFailed:
        break;
    case WalletModel::Aborted:
        break;
    case WalletModel::OK:
        QDialog dlg(this);
        auto vbox = new QVBoxLayout;
        vbox->setMargin(12);
        auto txdetails = new TxDetailsWidget;
        txdetails->layout()->setMargin(0);
        vbox->addWidget(txdetails);
        auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok);
        connect(buttonBox, SIGNAL(accepted()), &dlg, SLOT(accept()));
        vbox->addWidget(buttonBox);
        dlg.setLayout(vbox);

        int nPegInterval = Params().PegInterval(nBestHeight);
        int nCycle = nBestHeight / nPegInterval;

        txdetails->openTx(wtx, nullptr, 0,
                          nCycle,
                          model->getPegSupplyIndex(),
                          model->getPegSupplyNIndex(),
                          model->getPegSupplyNNIndex(),
                          wtx.nTime);
        dlg.resize(1400,800);
        dlg.exec();
        break;
    }
}

void SendCoinsDialog::clear()
{
    // Remove entries until only one left
    while(ui->entries->count())
    {
        delete ui->entries->takeAt(0)->widget();
    }
    addEntry();

    updateRemoveEnabled();

    CoinControlDialog::coinControl->UnSelectAll();
    coinControlUpdateLabels();

    if (sender() != ui->comboBoxTxType)
        ui->comboBoxTxType->setCurrentIndex(0);

    ui->sendButton->setDefault(true);

    PegTxType nTxType = static_cast<PegTxType>(ui->comboBoxTxType->currentData().toInt());
    ui->addButton->setEnabled(nTxType == PEG_MAKETX_SEND_RESERVE ||
                              nTxType == PEG_MAKETX_SEND_LIQUIDITY);
}

void SendCoinsDialog::reject()
{
    clear();
}

void SendCoinsDialog::accept()
{
    clear();
}

SendCoinsEntry *SendCoinsDialog::addEntry()
{
    SendCoinsEntry *entry = new SendCoinsEntry(this);
    entry->setModel(model);
    PegTxType txType = static_cast<PegTxType>(ui->comboBoxTxType->currentData().toInt());
    entry->setTxType(txType);
    ui->entries->addWidget(entry);
    connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
    connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));

    updateRemoveEnabled();

    // Focus the field, so that entry can start immediately
    entry->clear();
    entry->setFocus();
    ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
    QCoreApplication::instance()->processEvents();
    QScrollBar* bar = ui->scrollArea->verticalScrollBar();
    if(bar)
        bar->setSliderPosition(bar->maximum());
    return entry;
}

void SendCoinsDialog::updateRemoveEnabled()
{
    // Remove buttons are enabled as soon as there is more than one send-entry
    bool enabled = (ui->entries->count() > 1);
    for(int i = 0; i < ui->entries->count(); ++i)
    {
        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
        if(entry)
        {
            entry->setRemoveEnabled(enabled);
        }
    }
    setupTabChain(0);
    coinControlUpdateLabels();
}

void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
    delete entry;
    updateRemoveEnabled();
}

QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
    for(int i = 0; i < ui->entries->count(); ++i)
    {
        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
        if(entry)
        {
            prev = entry->setupTabChain(prev);
        }
    }
    QWidget::setTabOrder(prev, ui->addButton);
    QWidget::setTabOrder(ui->addButton, ui->sendButton);
    return ui->sendButton;
}

void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
    if(!fNewRecipientAllowed)
        return;

    SendCoinsEntry *entry = 0;
    // Replace the first entry if it is still unused
    if(ui->entries->count() == 1)
    {
        SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
        if(first->isClear())
        {
            entry = first;
        }
    }
    if(!entry)
    {
        entry = addEntry();
    }

    entry->setValue(rv);
}

bool SendCoinsDialog::handleURI(const QString &uri)
{
    SendCoinsRecipient rv;
    // URI has to be valid
    if (GUIUtil::parseBitcoinURI(uri, &rv))
    {
        CBitcoinAddress address(rv.address.toStdString());
        if (!address.IsValid())
            return false;
        pasteEntry(rv);
        return true;
    }

    return false;
}

void SendCoinsDialog::setBalance(qint64 balance,
                                 qint64 reserves, qint64 liquidity, qint64 frozen,
                                 vector<CFrozenCoinInfo> frozenCoins,
                                 qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
    Q_UNUSED(stake);
    Q_UNUSED(frozen);
    Q_UNUSED(balance);
    Q_UNUSED(frozenCoins);
    Q_UNUSED(unconfirmedBalance);
    Q_UNUSED(immatureBalance);

    if(model && model->getOptionsModel())
    {
        //ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance));
        ui->labelReserves->setText(BitcoinUnits::formatWithUnitForLabel(model->getOptionsModel()->getDisplayUnit(), reserves));
        ui->labelLiquidity->setText(BitcoinUnits::formatWithUnitForLabel(model->getOptionsModel()->getDisplayUnit(), liquidity));
    }
}

void SendCoinsDialog::updateDisplayUnit()
{
    vector<CFrozenCoinInfo> frozenCoins;
    int64_t nFrozen = model->getFrozen(NULL, &frozenCoins);
    setBalance(model->getBalance(), model->getReserve(), model->getLiquidity(), nFrozen, frozenCoins, 0, 0, 0);
}

// Coin Control: copy label "Quantity" to clipboard
void SendCoinsDialog::coinControlClipboardQuantity()
{
    QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text());
}

// Coin Control: copy label "Amount" to clipboard
void SendCoinsDialog::coinControlClipboardAmount()
{
    QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}

// Coin Control: copy label "Fee" to clipboard
void SendCoinsDialog::coinControlClipboardFee()
{
    QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")));
}

// Coin Control: copy label "After fee" to clipboard
void SendCoinsDialog::coinControlClipboardAfterFee()
{
    QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")));
}

// Coin Control: copy label "Bytes" to clipboard
void SendCoinsDialog::coinControlClipboardBytes()
{
    QApplication::clipboard()->setText(ui->labelCoinControlBytes->text());
}

// Coin Control: copy label "Priority" to clipboard
void SendCoinsDialog::coinControlClipboardPriority()
{
    QApplication::clipboard()->setText(ui->labelCoinControlPriority->text());
}

// Coin Control: copy label "Low output" to clipboard
void SendCoinsDialog::coinControlClipboardLowOutput()
{
    QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text());
}

// Coin Control: copy label "Change" to clipboard
void SendCoinsDialog::coinControlClipboardChange()
{
    QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")));
}

// Coin Control: settings menu - coin control enabled/disabled by user
void SendCoinsDialog::coinControlFeatureChanged(bool checked)
{
    ui->frameCoinControl->setVisible(checked);

    if (!checked && model) // coin control features disabled
        CoinControlDialog::coinControl->SetNull();
}

// Coin Control: button inputs -> show actual coin control dialog
void SendCoinsDialog::coinControlButtonClicked()
{
    PegTxType txType = static_cast<PegTxType>(ui->comboBoxTxType->currentData().toInt());

    CoinControlDialog dlg;
    dlg.setTxType(txType);
    dlg.setModel(model);
    dlg.exec();
    coinControlUpdateLabels();
}

// Coin Control: update labels
void SendCoinsDialog::coinControlUpdateLabels()
{
    if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
        return;

    // set pay amounts
    CoinControlDialog::payAmounts.clear();
    for(int i = 0; i < ui->entries->count(); ++i)
    {
        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
        if(entry)
            CoinControlDialog::payAmounts.append(entry->getValue().amount);
    }

    if (CoinControlDialog::coinControl->HasSelected())
    {
        PegTxType txType = static_cast<PegTxType>(ui->comboBoxTxType->currentData().toInt());

        // actual coin control calculation
        CoinControlDialog::updateLabels(model, this, txType);

        // show coin control stats
        ui->labelCoinControlAutomaticallySelected->hide();
        ui->widgetCoinControl->show();
    }
    else
    {
        // hide coin control stats
        ui->labelCoinControlAutomaticallySelected->show();
        ui->widgetCoinControl->hide();
        ui->labelCoinControlInsuffFunds->hide();
    }
}


text:
class ApplicationController < Flame::Controller
	def index; end

	def foo
		'Hello from foo!'
	end

	def bar; end

	def hello(name); end

	def baz(first, second, third = nil, fourth = nil); end

	def view
		render :view
	end
end

module TestRefinedActions
	extend Flame::Controller::Actions

	post def injected; end

	put 'module/update',
		def update; end
end

class ApplicationRefinedActionsController < Flame::Controller
	include with_actions TestRefinedActions, exclude: %i[injected]

	def foo; end

	get def bar; end

	post def baz; end

	put def qux; end

	delete '/refined_quux/:id',
		def quux(id); end

	def quuz; end
	patch '/refined_quuz', :quuz
end

class ApplicationRefinedPathController < Flame::Controller
	PATH = '/that_path_is_refined'

	def index; end

	def show(id); end
end

## Test controller with REST methods for Application
class ApplicationRESTController < Flame::Controller
	def index; end

	def create; end

	def show(id); end

	def update(id); end

	def delete(id); end
end

module ApplicationNamespace
	module Nested
		class IndexController < Flame::Controller
			def index; end
		end
	end

	class Application < Flame::Application
	end
end

module ApplicationControllers
	class Controller < Flame::Controller
	end

	module Site
		class Controller < ApplicationControllers::Controller
		end

		class IndexController < Site::Controller
			def index; end

			def about; end
		end

		class PagesController < Site::Controller
			def show(id); end
		end

		module Cabinet
			class Controller < Site::Controller
			end

			class IndexController < Cabinet::Controller
				def index; end
			end

			class SignInController < Cabinet::Controller
				def index; end

				def sign_in_post; end
				post '/', :sign_in_post
			end

			module Common
				class Controller < Cabinet::Controller
				end
			end

			module Admin
				class IndexController < Cabinet::Controller
					def index; end
				end

				class UsersController < Cabinet::Common::Controller
					def index; end

					def show(id); end

					def update(id); end

					def delete(id); end
				end
			end
		end
	end

	module API
		class Controller < ApplicationControllers::Controller
		end

		class IndexController < API::Controller
			def index; end

			def about; end
		end

		class FooController < API::Controller
			def show(id); end
		end

		module Restricted
			class Controller < API::Controller
			end

			class IndexController < Restricted::Controller
				def index; end
			end

			class UsersController < Restricted::Controller
				def index; end

				def show(id); end

				def update(id); end

				def delete(id); end
			end
		end
	end

	class Application < Flame::Application
	end
end

def initialize_path_hash(
	controller:, prefix:, action:, http_method: :GET, **options
)
	route = Flame::Router::Route.new(controller, action)
	ctrl_path = options.fetch :ctrl_path, controller.path
	action_path = Flame::Path.new(
		options.fetch(:action_path, action == :index ? '/' : action)
	).adapt(controller, action)
	path_routes, endpoint =
		Flame::Path.new(prefix, ctrl_path, action_path).to_routes_with_endpoint
	endpoint[http_method] = route
	path_routes
end

using GorillaPatch::DeepMerge

def initialize_path_hashes(
	controller, *actions, prefix: nil, **actions_with_options
)
	actions.to_h { |action| [action, {}] }
		.merge(actions_with_options)
		.each_with_object({}) do |(action, options), result|
			result.deep_merge! initialize_path_hash(
				controller: controller, prefix: prefix, action: action, **options
			)
		end
end

def initialize_rest_route(action)
	Flame::Router::Route.new(ApplicationRESTController, action)
end

def initialize_rest_routes
	{
		GET: initialize_rest_route(:index),
		POST: initialize_rest_route(:create),
		':id' => {
			GET: initialize_rest_route(:show),
			PUT: initialize_rest_route(:update),
			DELETE: initialize_rest_route(:delete)
		}
	}
end

def rest_routes(prefix = nil)
	routes, endpoint = Flame::Path.new(prefix).to_routes_with_endpoint

	endpoint.merge! initialize_rest_routes

	routes
end

describe Flame::Application do
	subject(:app) { app_class.new(another_app) }

	let(:app_class) { Class.new(described_class) }

	let(:another_app) { nil }

	let(:env_path) { '/foo' }

	let(:env) do
		{
			Rack::RACK_INPUT => StringIO.new,
			Rack::REQUEST_METHOD => 'GET',
			Rack::PATH_INFO => env_path
		}
	end

	describe '.config' do
		subject { app_class.config }

		it { is_expected.to be_a Flame::Config }
	end

	describe '.router' do
		subject { app_class.router }

		it { is_expected.to be_a Flame::Router }
	end

	describe '.cached_tilts' do
		subject(:cached_tilts) { app_class.cached_tilts }

		it { is_expected.to be_a Hash }

		describe 'filling' do
			let(:call_result) { app_class.call(env) }

			let(:env_path) { '/view' }

			let(:view_names) do
				%w[view layout].map do |filename|
					File.join(__dir__, 'views', "#{filename}.html.erb")
				end
			end

			around do |example|
				original_rack_env = ENV.fetch('RACK_ENV', nil)
				ENV['RACK_ENV'] = 'production'

				example.run

				ENV['RACK_ENV'] = original_rack_env
			end

			before do
				app_class.class_exec do
					mount :application, '/'
				end

				call_result
			end

			describe 'status' do
				subject { call_result.first }

				it { is_expected.to eq 200 }
			end

			describe 'size' do
				subject { cached_tilts.size }

				it { is_expected.to eq 2 }
			end

			describe 'keys' do
				subject { cached_tilts.keys }

				it { is_expected.to eq view_names }
			end

			describe 'values' do
				subject { cached_tilts.values }

				it { is_expected.to all a_kind_of(Tilt::Template) }
			end
		end
	end

	describe '.require_dirs' do
		let(:expected_files) do
			%w[
				config/config

				lib/some_lib/lib/some_lib

				models/_some_model_module
				models/some_model

				helpers/some_helper

				mailers/_base
				mailers/some_mailer

				services/_base
				services/_common/_base
				services/regular/_base
				services/_common/create
				services/_common/find
				services/another/find
				services/another_service
				services/regular/all
				services/regular/create
				services/something_service

				controllers/_base_controller
				controllers/site/_controller
				controllers/site/index_controller
			]
		end

		let(:required_files) { [] }

		before do
			allow(app_class).to receive(:require) do |file|
				required_files.push(
					file.sub("#{__dir__}/require_dirs/", '').delete_suffix('.rb')
				)
			end

			app_class.require_dirs(
				%w[config lib models helpers mailers services controllers]
					.map! { |dir| File.join 'require_dirs', dir },
				ignore: [%r{lib/\w+/spec}]
			)
		end

		it do
			# puts required_files
			expect(required_files).to eq expected_files
		end
	end

	describe '.inherited' do
		describe 'default config' do
			subject { app_class.config }

			it { is_expected.to be_a Flame::Config }

			describe 'values' do
				subject { super()[key] }

				{
					root_dir: __dir__,
					public_dir: File.join(__dir__, 'public'),
					views_dir: File.join(__dir__, 'views'),
					config_dir: File.join(__dir__, 'config'),
					tmp_dir: File.join(__dir__, 'tmp'),
					environment: 'development'
				}.each do |key, value|
					describe key.to_s do
						let(:key) { key }

						it { is_expected.to eq value }
					end
				end

				describe 'environment from ENV' do
					around do |example|
						original_rack_env = ENV.fetch('RACK_ENV', nil)
						ENV['RACK_ENV'] = 'production'

						example.run

						ENV['RACK_ENV'] = original_rack_env
					end

					let(:key) { :environment }

					it { is_expected.to eq 'production' }
				end
			end
		end
	end

	describe '.call' do
		subject(:result) { app_class.call(env) }

		it { is_expected.to be_a Array }

		it 'caches created instance' do
			first_app, second_app = Array.new(2) do
				result
				app.instance_variable_get(:@app)
			end

			expect(first_app).to equal second_app
		end
	end

	describe '.path_to' do
		subject(:result) { app_class.path_to(*args) }

		before do
			app_class.class_exec do
				mount :application, '/'
			end
		end

		context 'with controller and action' do
			let(:args) { [ApplicationController, :foo] }

			it { is_expected.to eq '/foo' }
		end

		context 'with controller and default index action' do
			let(:args) { [ApplicationController] }

			it { is_expected.to eq '/' }
		end

		context 'with controller and action with arguments' do
			let(:args) { [ApplicationController, :hello, { name: 'world' }] }

			it { is_expected.to eq '/hello/world' }
		end

		context 'with nonexistent action' do
			let(:args) { [ApplicationController, :not_exist] }

			it do
				expect { result }.to raise_error(
					Flame::Errors::RouteNotFoundError,
					/'ApplicationController' [\w\s]+ 'not_exist'/
				)
			end
		end

		context 'with nested params' do
			let(:args) do
				[
					ApplicationController, :foo, {
						name: 'world',
						nested: { some: 'here', another: %w[there maybe] }
					}
				]
			end

			let(:expected_result) do
				<<~PATH.delete("\n")
					/foo?
					name=world&
					nested[some]=here&
					nested[another][]=there&
					nested[another][]=maybe
				PATH
			end

			it { is_expected.to eq expected_result }
		end
	end

	describe '#initialize' do
		describe '@app parameter' do
			subject { app.instance_variable_get(:@app) }

			let(:another_app) { app_class.new }

			it { is_expected.to be another_app }
		end
	end

	describe '#call' do
		subject(:call_result) { app.call(env) }

		context 'with mounted controller' do
			before do
				app_class.class_exec do
					mount :application, '/'
				end
			end

			it { is_expected.to be_a Array }

			describe 'status' do
				subject { super().first }

				it { is_expected.to eq 200 }
			end

			describe 'body' do
				subject { super().last }

				it { is_expected.to eq ['Hello from foo!'] }
			end
		end

		context 'when initialized with another app' do
			subject(:foo) { another_app.foo }

			let(:another_app_class) do
				Class.new(described_class) do
					attr_reader :foo

					def call(env)
						@foo = env[:bar]
					end
				end
			end

			let(:another_app) { another_app_class.new }

			let(:env) { super().merge(bar: 'baz') }

			before { call_result }

			it { is_expected.to eq 'baz' }

			context 'without call method' do
				let(:another_app_class) { Object }

				it { expect { call_result }.not_to raise_error }
			end
		end
	end

	describe '.mount' do
		subject(:routes) { app_class.router.routes }

		context 'when controller without refinings' do
			before do
				app_class.class_exec do
					mount :application
				end
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController, :index, :foo, :bar, :hello, :baz, :view
				)
			end
		end

		context 'when controller with `_controller` in name' do
			before do
				app_class.class_exec do
					mount :application_controller
				end
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController, :index, :foo, :bar, :hello, :baz, :view
				)
			end
		end

		context 'when controller with another path' do
			before do
				app_class.class_exec do
					mount :application, '/another'
				end
			end

			let(:expected_paths) do
				{
					index: { ctrl_path: '/another' },
					foo: { ctrl_path: '/another' },
					bar: { ctrl_path: '/another' },
					hello: { ctrl_path: '/another' },
					baz: { ctrl_path: '/another' },
					view: { ctrl_path: '/another' }
				}
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController, **expected_paths
				)
			end
		end

		context 'when controller with refining HTTP-methods' do
			before do
				app_class.class_exec do
					mount :application do
						post :baz
					end
				end
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController,
					:index, :foo, :bar, :hello, :view, baz: { http_method: :POST }
				)
			end
		end

		context 'when controller with overwritten action path' do
			before do
				app_class.class_exec do
					mount :application do
						get '/bat/:first/:second/:?third/:?fourth', :baz
					end
				end
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController,
					:index, :foo, :bar, :hello, :view, baz: { action_path: '/bat' }
				)
			end
		end

		context 'when controller with overwritten arguments order' do
			before do
				app_class.class_exec do
					mount :application do
						get '/baz/:second/:first/:?third/:?fourth', :baz
					end
				end
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController,
					:index, :foo, :bar, :hello, :view,
					baz: { action_path: '/baz/:second/:first/:?third/:?fourth' }
				)
			end
		end

		context 'when controller with all of available overwrites' do
			before do
				app_class.class_exec do
					mount :application do
						post '/bat/:second/:first/:?third/:?fourth', :baz
					end
				end
			end

			let(:expected_simple_paths) do
				%i[index foo bar hello view]
			end

			let(:expected_paths_with_options) do
				{
					baz: {
						action_path: '/bat/:second/:first/:?third/:?fourth',
						http_method: :POST
					}
				}
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController,
					*expected_simple_paths,
					**expected_paths_with_options
				)
			end
		end

		context 'when controller without arguments in path' do
			before do
				app_class.class_exec do
					mount :application do
						post '/bat', :baz
					end
				end
			end

			let(:expected_simple_paths) do
				%i[index foo bar hello view]
			end

			let(:expected_paths_with_options) do
				{
					baz: {
						action_path: '/bat/:first/:second/:?third/:?fourth',
						http_method: :POST
					}
				}
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController,
					*expected_simple_paths,
					**expected_paths_with_options
				)
			end
		end

		context 'when controller with missed required arguments' do
			before do
				app_class.class_exec do
					mount :application do
						post '/bat/:second', :baz
					end
				end
			end

			let(:expected_simple_paths) do
				%i[index foo bar hello view]
			end

			let(:expected_paths_with_options) do
				{
					baz: {
						action_path: '/bat/:second/:first/:?third/:?fourth',
						http_method: :POST
					}
				}
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController,
					*expected_simple_paths,
					**expected_paths_with_options
				)
			end
		end

		context 'when controller with missing optional arguments' do
			before do
				app_class.class_exec do
					mount :application do
						post '/bat/:second/:first', :baz
					end
				end
			end

			let(:expected_simple_paths) do
				%i[index foo bar hello view]
			end

			let(:expected_paths_with_options) do
				{
					baz: {
						action_path: '/bat/:second/:first/:?third/:?fourth',
						http_method: :POST
					}
				}
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController,
					*expected_simple_paths,
					**expected_paths_with_options
				)
			end
		end

		context 'when action does not exist' do
			subject(:mounting) do
				app_class.class_exec do
					mount :application do
						post :wat
					end
				end
			end

			it do
				expect { mounting }.to raise_error(
					NameError, /`wat' [\w\s]+ `ApplicationController'/
				)
			end
		end

		context 'with wrong HTTP-method' do
			subject(:mounting) do
				app_class.class_exec do
					mount :application do
						wrong :baz
					end
				end
			end

			it do
				expect { mounting }.to raise_error(
					NoMethodError, /`wrong'/
				)
			end
		end

		context 'with extra required path arguments' do
			subject(:mounting) do
				app_class.class_exec do
					mount :application do
						get '/baz/:first/:second/:third', :baz
					end
				end
			end

			it do
				expect { mounting }.to raise_error(
					Flame::Errors::RouteExtraArgumentsError,
					"Action 'ApplicationController#baz' has no " \
						'required arguments [:third]'
				)
			end
		end

		context 'with extra optional path arguments' do
			subject(:mounting) do
				app_class.class_exec do
					mount :application do
						get '/baz/:first/:second/:?third/:?fourth/:?fifth', :baz
					end
				end
			end

			it do
				expect { mounting }.to raise_error(
					Flame::Errors::RouteExtraArgumentsError,
					"Action 'ApplicationController#baz' has no " \
						'optional arguments [:fifth]'
				)
			end
		end

		context 'with wrong order of optional arguments' do
			subject(:mounting) do
				app_class.class_exec do
					mount :application do
						get '/baz/:first/:second/:?fourth/:?third', :baz
					end
				end
			end

			it do
				expect { mounting }.to raise_error(
					Flame::Errors::RouteArgumentsOrderError, <<~MESSAGE.chomp
						Path '/baz/:first/:second/:?fourth/:?third' should have ':?third' argument before ':?fourth'
					MESSAGE
				)
			end
		end

		describe 'mounting defaults REST actions' do
			before do
				app_class.class_exec do
					mount :application_REST, '/'
				end
			end

			it { is_expected.to eq rest_routes }
		end

		describe 'overwriting existing routes' do
			before do
				app_class.class_exec do
					mount :application do
						get :baz
						post :baz
					end
				end
			end

			let(:expected_simple_paths) do
				%i[index foo bar hello view]
			end

			let(:expected_paths_with_options) do
				{
					baz: { http_method: :POST }
				}
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationController,
					*expected_simple_paths,
					**expected_paths_with_options
				)
			end
		end

		context 'with nested controllers' do
			before do
				app_class.class_exec do
					mount :application do
						get :foo

						mount :application_REST, '/rest'
					end
				end
			end

			let(:expected_routes) do
				rest_routes('/application/rest').deep_merge!(
					initialize_path_hashes(
						ApplicationController, :index, :foo, :bar, :hello, :view, :baz
					)
				)
			end

			it { expect(routes).to eq expected_routes }

			describe 'reverse routes' do
				subject(:reverse_routes) { app_class.router.reverse_routes }

				let(:expected_routes) do
					{
						'ApplicationController' => {
							index: '/application/',
							foo: '/application/foo',
							bar: '/application/bar',
							hello: '/application/hello/:name',
							view: '/application/view',
							baz: '/application/baz/:first/:second/:?third/:?fourth'
						},
						'ApplicationRESTController' => {
							index: '/application/rest/',
							create: '/application/rest/',
							show: '/application/rest/:id',
							update: '/application/rest/:id',
							delete: '/application/rest/:id'
						}
					}
				end

				it { expect(reverse_routes).to eq expected_routes }
			end
		end

		describe(
			'mounting neighboring controllers with root-with-argument action'
		) do
			before do
				app_class.class_exec do
					mount :application do
						get '/', :baz

						mount :application_REST, '/rest'
					end
				end
			end

			describe 'routes' do
				let(:expected_routes) do
					rest_routes('/application/rest').deep_merge!(
						initialize_path_hashes(
							ApplicationController, :index, :foo, :bar, :hello, :view,
							baz: { action_path: '/:first/:second/:?third/:?fourth' }
						)
					)
				end

				it { is_expected.to eq expected_routes }
			end

			describe 'reverse routes' do
				subject { app_class.router.reverse_routes }

				let(:expected_reverse_routes) do
					{
						'ApplicationController' => {
							index: '/application/',
							foo: '/application/foo',
							bar: '/application/bar',
							hello: '/application/hello/:name',
							view: '/application/view',
							baz: '/application/:first/:second/:?third/:?fourth'
						},
						'ApplicationRESTController' => {
							index: '/application/rest/',
							create: '/application/rest/',
							show: '/application/rest/:id',
							update: '/application/rest/:id',
							delete: '/application/rest/:id'
						}
					}
				end

				it { is_expected.to eq expected_reverse_routes }
			end
		end

		context 'when controller from the same namespace as application' do
			subject(:mounting) do
				app_class.class_exec do
					mount :nested
				end
			end

			let(:app_class) { Class.new(ApplicationNamespace::Application) }

			it { expect { mounting }.not_to raise_error }
		end

		context 'when controller is anonymous' do
			subject(:mounting) do
				controller = self.controller

				app_class.class_exec do
					mount controller, '/'
				end
			end

			let(:controller) { Class.new(Flame::Controller) }

			it { expect { mounting }.not_to raise_error }
		end

		context 'when controller with refined HTTP-methods inside' do
			before do
				app_class.class_exec do
					mount :application_refined_actions
				end
			end

			let(:expected_routes) do
				{
					foo: { http_method: :GET },
					bar: { http_method: :GET },
					baz: { http_method: :POST },
					qux: { http_method: :PUT },
					quux: {
						http_method: :DELETE,
						action_path: '/refined_quux/:id'
					},
					quuz: {
						http_method: :PATCH,
						action_path: '/refined_quuz'
					},
					update: {
						http_method: :PUT,
						action_path: '/module/update'
					}
				}
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationRefinedActionsController, **expected_routes
				)
			end
		end

		context 'when controller with refined path inside' do
			before do
				app_class.class_exec do
					mount ApplicationRefinedPathController
				end
			end

			let(:expected_routes) do
				{
					index: {
						ctrl_path: '/that_path_is_refined',
						http_method: :GET
					},
					show: {
						ctrl_path: '/that_path_is_refined',
						http_method: :GET,
						action_path: '/:id'
					}
				}
			end

			it do
				expect(routes).to eq initialize_path_hashes(
					ApplicationRefinedPathController, **expected_routes
				)
			end
		end

		describe 'auto-mount nested controllers' do
			before do
				app_class.class_exec do
					mount :site

					mount :api, nested: false do
						mount :foo
					end
				end
			end

			let(:app_class) { Class.new(ApplicationControllers::Application) }

			let(:expected_result) do
				initialize_path_hashes(
					ApplicationControllers::Site::IndexController, :index, :about
				).deep_merge! initialize_path_hashes(
					ApplicationControllers::Site::PagesController,
					prefix: :site,
					show: { action_path: '/:id' }
				).deep_merge! initialize_path_hashes(
					ApplicationControllers::Site::Cabinet::IndexController, :index,
					prefix: :site
				).deep_merge! initialize_path_hashes(
					ApplicationControllers::Site::Cabinet::SignInController, :index,
					prefix: 'site/cabinet',
					sign_in_post: { http_method: :POST, action_path: '/' }
				).deep_merge! initialize_path_hashes(
					ApplicationControllers::Site::Cabinet::Admin::IndexController, :index,
					prefix: 'site/cabinet'
				).deep_merge! initialize_path_hashes(
					ApplicationControllers::Site::Cabinet::Admin::UsersController,
					:index,
					prefix: 'site/cabinet/admin',
					show: { action_path: '/:id' },
					update: { http_method: :PUT, action_path: '/:id' },
					delete: {
						http_method: :DELETE, action_path: '/:id'
					}
				).deep_merge! initialize_path_hashes(
					ApplicationControllers::API::IndexController, :index, :about
				).deep_merge! initialize_path_hashes(
					ApplicationControllers::API::FooController,
					prefix: :api,
					show: { action_path: '/:id' }
				)
			end

			it { is_expected.to eq expected_result }

			context 'with nonexistent controller name' do
				subject(:mounting) do
					app_class.class_exec do
						mount :nonexistent
					end
				end

				it do
					expect { mounting }.to raise_error(
						Flame::Errors::ControllerNotFoundError,
						"Controller 'nonexistent' not found for 'ApplicationControllers'"
					)
				end
			end
		end
	end
end