text:
class License < ActiveRecord::Base
  has_many :datasets
  has_many :images
  has_many :videos
  has_many :maps
  has_many :articles
  has_many :sounds

  # TODO: (this also applies to node#rank) We need a way to add enums.
  # ...Namely, when we import things from partners, we *can* get new enumerable
  # values. So we'll need a system--probably a rake task--that actually adds
  # that data to the database AND to the associated class! ...A little scary,
  # and it needs thought, but having these as enums is REALLY helpful (in terms
  # of translations and storing integers in the DB).
  enum type: [:public_domain, :all_right_reserved, :cc, :by_sa, :by_nc,
    :by_nc_sa, :cc_zero, :no_known_restrictions, :na]

  # TODO: fix the attachment arguments:
  has_attached_file :icon,
    styles: { :medium => "300x300>", :thumb => "100x100>" },
    default_url: "/images/:style/missing.png"

  def abbr
    I18n.t("licenses.#{type}.abbr")
  end

  def name
    I18n.t("licenses.#{type}.name")
  end

  def description
    I18n.t("licenses.#{type}.description")
  end
end


text:
<?php

namespace Elcodi\Admin\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Class PasswordRecoverType
 */
class PasswordRecoverType extends AbstractType
{
    /**
     * Buildform function
     *
     * @param FormBuilderInterface $builder the formBuilder
     * @param array                $options the options for this form
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', 'email', [
                'required' => true,
            ])
            ->add('password', 'repeated', [
                'type'     => 'password',
                'required' => true,
            ]);
    }

    /**
     * Returns the prefix of the template block name for this type.
     *
     * The block prefix defaults to the underscored short class name with
     * the "Type" suffix removed (e.g. "UserProfileType" => "user_profile").
     *
     * @return string The prefix of the template block name
     */
    public function getBlockPrefix()
    {
        return 'elcodi_admin_user_form_type_password_recover';
    }

    /**
     * Return unique name for this form
     *
     * @deprecated Deprecated since Symfony 2.8, to be removed from Symfony 3.
     *
     * @return string
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PowerShellTools.Editors;

namespace HelpEditorOS
{
	/// <summary>
	/// Interaction logic for ParameterControl.xaml
	/// </summary>
	public partial class ParametersControl : UserControl
	{
		public ParametersControl()
		{
			this.InitializeComponent();
		}

        /// <summary>
        /// This routine is an event handler.
        /// I call the save Parameter Description routine everytime a
        /// LostFocus happened on an editable field in the Cmdlet description page.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void saveParameterDescription(object sender, RoutedEventArgs args)
        {
            saveParameterDescription1();
        }

        /// <summary>
        /// Save parameter data when the Globiing parameter is checked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GlobbingParam_Checked(object sender, RoutedEventArgs e)
        {
            saveParameterDescription1();
        }

        /// <summary>
        /// Called when parameters info gets lost focus
        /// </summary>
        public void saveParameterDescription1()
        {
            TreeViewItem Node = (TreeViewItem)MainWindow.NavControl.CmdletTreeView.SelectedItem;
            if (Node != null)
            {

                parameterDecription param = (parameterDecription)Node.DataContext;
                param.NewDescription = this.ParametersControl1.ParameterDescTextBox.Text;
                param.DefaultValue = this.ParametersControl1.DefaultValueTextBox.Text;
                if ((Boolean)this.ParametersControl1.GlobbingCheckBox.IsChecked)
                {
                    param.Globbing = true;
                }
                else
                {
                    param.Globbing = false;
                }
            }

        }

	}
}


text:
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import java.io.StringReader;
import javax.json.*;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.Headers ;

import edu.stanford.nlp.process.Tokenizer;
import edu.stanford.nlp.process.TokenizerFactory;
import edu.stanford.nlp.process.CoreLabelTokenFactory;
import edu.stanford.nlp.process.DocumentPreprocessor;
import edu.stanford.nlp.process.PTBTokenizer;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.ling.Sentence;
import edu.stanford.nlp.trees.*;
import edu.stanford.nlp.parser.lexparser.LexicalizedParser;

class NLPService {
  /*
    Pass model name as argument with complete path, http://nlp.stanford.edu/software/lex-parser.shtml
    PCFG Parser: edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz
    RNN  Parser: edu/stanford/nlp/models/lexparser/englishRNN.ser.gz
  */
  static LexicalizedParser lp = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishRNN.ser.gz");
  static TreebankLanguagePack tlp = lp.treebankLanguagePack();
  static GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();

  public static void main(String[] args) {
    try {
      HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
      server.createContext("/parse", new Handler());
      server.setExecutor(null);
      server.start();
    } catch(java.io.IOException SocketError) {
      System.out.println(SocketError);
      return;
    }
  }

  static class Handler implements HttpHandler {
    @Override
    public void handle(HttpExchange t) throws IOException {

      // Get post data from http request to parse sentence
      InputStream in    = t.getRequestBody();
      StringBuilder sb  = new StringBuilder();
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      // Extract headers from exchange and add content-type
      Headers headers = t.getResponseHeaders();
      headers.add("Content-Type", "application/json");
      t.sendResponseHeaders(200, 0);
      OutputStream os = t.getResponseBody();

      String inp_sentence;
      while ((inp_sentence = br.readLine()) != null) {
        StringReader r_inp_sentence = new StringReader(inp_sentence);

        for (List<HasWord> sentence : new DocumentPreprocessor(r_inp_sentence)) {
          Tree parse = lp.apply(sentence);
          GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
          Collection tdl = gs.typedDependenciesCCprocessed();
          String dep     = tdl.toString();

          JsonArrayBuilder tokens_ab = Json.createArrayBuilder();
          ListIterator<HasWord> litr = sentence.listIterator();
          int wordPos = 1;
          while(litr.hasNext()) {
            HasWord word = litr.next();

            JsonObject wordToken = Json.createObjectBuilder()
                .add("word", word.word())
                .add("pos", wordPos)
              .build();
            wordPos += 1;
            tokens_ab.add(wordToken);
            wordToken = null;
          }
          JsonObject sentence_ab = Json.createObjectBuilder()
              .add("tokens", tokens_ab)
              .add("dep", dep)
              .add("tree", parse.toString())
            .build();
          // Write processed sentence as soon as available to create a streaming service
          os.write((sentence_ab.toString()+"\n").getBytes());

          // Mark objects null for grabage collections
          parse = null;
          dep = null;
          gs  = null;
          tdl = null;
          sentence_ab = null;
          tokens_ab = null;
          sentence  = null;
          r_inp_sentence = null;

          System.gc();
        }
      }

      os.close();
    }
  }
  private NLPService() {} // static methods only
}


text:
<?php

use Johnnymn\Sim\Roles\Models\Permission;
use Illuminate\Database\Seeder;

class PermissionsTableSeeder extends Seeder
{
    /**
     * Creation of Permissions.
     *
     * @return void
     */
    public function run()
    {
        Permission::create([
            'name' => 'Create users',
            'slug' => 'create.users',
            'description' => '', // optional
        ]);
    }
}


text:
import React from 'react';

import { DataQueryRequest, serializeStateToUrlParam } from '@grafana/data';
import { getTemplateSrv } from '@grafana/runtime';

import { LokiQuery } from '../../../plugins/datasource/loki/types';

import { makeLogsQueryResponse } from './helper/query';
import { setupExplore, waitForExplore } from './helper/setup';

const fetch = jest.fn();
jest.mock('@grafana/runtime', () => ({
  ...jest.requireActual('@grafana/runtime'),
  getBackendSrv: () => ({ fetch }),
}));

jest.mock('app/core/core', () => ({
  contextSrv: {
    hasAccess: () => true,
  },
}));

jest.mock('react-virtualized-auto-sizer', () => {
  return {
    __esModule: true,
    default(props: any) {
      return <div>{props.children({ width: 1000 })}</div>;
    },
  };
});

describe('Explore: interpolation', () => {
  // support-escalations/issues/1459
  it('Time is interpolated when explore is opened with a URL', async () => {
    const urlParams = {
      left: serializeStateToUrlParam({
        datasource: 'loki',
        queries: [{ refId: 'A', expr: '{ job="a", from="${__from}", to="${__to}" }' }],
        range: { from: '1600000000000', to: '1700000000000' },
      }),
      right: serializeStateToUrlParam({
        datasource: 'loki',
        queries: [{ refId: 'b', expr: '{ job="b", from="${__from}", to="${__to}" }' }],
        range: { from: '1800000000000', to: '1900000000000' },
      }),
    };
    const { datasources } = setupExplore({ urlParams });
    const fakeFetch = jest.fn();

    (datasources.loki.query as jest.Mock).mockImplementation((request: DataQueryRequest<LokiQuery>) => {
      fakeFetch(getTemplateSrv().replace(request.targets[0]!.expr));
      return makeLogsQueryResponse();
    });

    await waitForExplore();

    expect(fakeFetch).toBeCalledTimes(2);
    expect(fakeFetch).toHaveBeenCalledWith('{ job="a", from="1600000000000", to="1700000000000" }');
    expect(fakeFetch).toHaveBeenCalledWith('{ job="b", from="1800000000000", to="1900000000000" }');
  });
});


text:
module LocomotiveCMS
  module Liquids
    module Filters
      module Math # :nodoc:
        def mod(input, modulus)
          input.to_i % modulus.to_i
        end
      end
    end
  end
end


text:
import { MdCard, MdCardActions, MdCardAvatar, MdCardContent, MdCardFooter, MdCardHeader, MdCardImage, MdCardLgImage, MdCardMdImage, MdCardSmImage, MdCardSubtitle, MdCardTitle, MdCardTitleGroup, MdCardXlImage } from './card';
import { MdCardModule } from './card-module';
export { MdCard as MatCard };
export { MdCardActions as MatCardActions };
export { MdCardAvatar as MatCardAvatar };
export { MdCardContent as MatCardContent };
export { MdCardFooter as MatCardFooter };
export { MdCardHeader as MatCardHeader };
export { MdCardImage as MatCardImage };
export { MdCardLgImage as MatCardLgImage };
export { MdCardMdImage as MatCardMatImage };
export { MdCardModule as MatCardModule };
export { MdCardSmImage as MatCardSmImage };
export { MdCardSubtitle as MatCardSubtitle };
export { MdCardTitle as MatCardTitle };
export { MdCardTitleGroup as MatCardTitleGroup };
export { MdCardXlImage as MatCardXlImage };


text:
from key import key

league_id = 4664

team_url = 'http://api.steampowered.com/IDOTA2Teams_570/GetTeamInfo/v1/?key={}&league_id={}'.format(
    key, league_id)

match_url = 'https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/v1/?key={}&league_id={}'.format(
    key, league_id)

detail_url = 'http://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/v1/?key={}&match_id={}'.format(
    key, '{}')

player_name_url = 'http://api.opendota.com/api/players/{}'

CONNECT_STRING = 'mysql+pymysql://dota:123456@localhost/dota'
IMMEDIATE = 'Immediate'
DELAY = 'delay'


text:
{% extends "templates/layout-question-post.html" %}

{% block body_classes %}version-7{% endblock %}

{% block page_title %}
  Which devices do you regularly use to access the internet?
{% endblock %}

{% block question_number %}3{% endblock %}
{% block previous_url %}postcode{% endblock %}
{% block next_url %}how-often{% endblock %}

{% block question_content %}

Select all that apply:

		<input type="checkbox" name="use_device_1" id="use_device_1">

		Desktop computer

	      <input type="checkbox" name="use_device_2" id="use_device_2">

		Laptop computer

	      <input type="checkbox" name="use_device_3" id="use_device_3">

		Tablet (eg. iPad)

	      <input type="checkbox" name="use_device_4" id="use_device_4">

		Smartphone (eg. iPhone, Samsung Galaxy)

	      <input type="checkbox" name="use_device_5" id="use_device_5">

		Other:

	      Please specify
	      <input class="form-control other-specify" type="text" id="other" name="use_device_freetext">

{% endblock %}


text:
<?php
class Controller_Top extends Controller {
    public function action_index() {
        echo "day la trang top";
    }
}


text:
<html>
<head>
	<title></title>
</head>

<body>
Python Stomp Client Daemon

Attaches to ActiveMQ Message Bus with it's server name as a queue name via the STOMP protocol.
The daemon loads message controllers dynamically, constructing a structure of messages and the appropriate message handler methods.
It then listens for asynchronous JSON messages placed into it's server queue.
Upon message reciept the message controller and method are identified, and a call to the method is invoked.
The message is passed as a parameter to the method.
* Firewall Requirements - Outbound connection to message server via port 61613

Controllers Implemented

BindZoneFileService
	"CreateBindZoneFile" - Create db.tld.domain zone file in /etc/bind.  Add zone file to /etc/bind/named.conf.local.
	"RemoveBindZoneFile" - Remove db.tld.domain zone file from /etc/bind.  Remove zone file from /etc/bind/named.conf.local.
	"EnableBindZoneFile" - Add zone file to /etc/bind/named.conf.local.
	"DisableBindZoneFile" - Remove zone file from /etc/bind/named.conf.local.
	* No reverse zone coverage currently available

DNSDomainService - Dependent on BindZoneFileService
	"AddBindZoneARecord" - Add A Record to /etc/bind/db.tld.domain zone file.
	"RemoveBindZoneARecord" - Remove A Record from /etc/bind/db.tld.domain zone file.
	"AddBindZoneAAAARecord" - Add AAAA Record to /etc/bind/db.tld.domain zone file.
	"RemoveBindZoneAAAARecord" - Remove AAAA Record from /etc/bind/db.tld.domain zone file.
	"AddBindZoneCNameRecord" - Add CName Record to /etc/bind/db.tld.domain zone file.
	"RemoveBindZoneCNameRecord" - Remove CName Record from /etc/bind/db.tld.domain zone file.
	"AddBindZoneMXRecord" - Add MX Record to /etc/bind/db.tld.domain zone file.
	"RemoveBindZoneMXRecord" - Remove MX Record from /etc/bind/db.tld.domain zone file.
	"AddBindZoneSPFRecord" - Add SPF Record to /etc/bind/db.tld.domain zone file.
	"RemoveBindZoneSPFRecord" - Remove SPF Record from /etc/bind/db.tld.domain zone file.
	"AddBindZoneSRVRecord" - Add SRV Record to /etc/bind/db.tld.domain zone file.
	"RemoveBindZoneSRVRecord" - Remove SRV Record from /etc/bind/db.tld.domain zone file.
	* No reverse zone coverage currently available

VirtualHostAccountService
	"CreateVirtualHostAccount" - Create domain host server user account. (subdomain.domain.tld)
	"RemoveVirtualHostAccount" - Remove domain host server user account.
	"EnableVirtualHostAcount" - Enable domain host server user account.
	"DisableVirtualHostAccount" - Disable domain host server user account.
	"SetVirtualHostAccountPasswd" - Set domain host user account password.
	"BackupVirtualHostAccount" - Backup domain host server user account.
	"RestoreVirtualHostAccount" - Restore domain host server user account.
	"AddSSHAuthorizedKey" - Add SSH key pair to host server user account.
	"RemoveSSHAuthorizedKey" - Remove SSH key pair from host server user account.
	"AddCRONJob" - Add CRON job to host server user crontab.
	"RemoveCRONJob" - Remove CRON job from host server user crontab.

ApacheVirtualHostService - Dependent on VirtualHostAccountService
	"CreateApacheVirtualHost" - Create Apache HTTP/HTTPS virtual host config file (subdomain-domain-tld.conf) in /etc/apache2/sites-available/. Create symlink from config file to /etc/apache2/sites-enabled/.
	"RemoveApacheVirtualHost" - Remove symlink from /etc/apache2/sites-enabled/. Remove Apache HTTP/HTTPS virtual host config file (subdomain-domain-tld.conf) from /etc/apache2/sites-available/.
	"EnableApacheVirtualHost" - Create symlink from config file to /etc/apache2/sites-enabled/.
	"DisableApacheVirtualHost" - Remove symlink from config file to /etc/apache2/sites-enabled/.
	"CreateApacheVirtualHostProxy" - Create proxy config file in /etc/apache2/site-proxies/subsomain.domain.tld.d/.
	"RemoveApacheVirtualHostProxy" - Remove proxy config file in /etc/apache2/site-proxies/subsomain.domain.tld.d/.
	"AddSSLCertificate" - Adds SSL certificate to site configuration.
	"RemoveSSLCertificate" - Removes SSL certificate from site configuration.
	"AddCORSAllow"
	"RemoveCORSAllow"
	* Apache virtual host config file points to ~/htdocs folder. (/etc/apache2/sites-available/subdomain.domain.tld.conf -> /home/subdomain.domain.tld/htdocs)
	* Apache virtual host config file includes /etc/apache2/site-proxies/subdomain.domain.tld.d/ subdir files.
	* Apache virtual host config file logs to /home/subdomain.domain.tld/log/. (access_log, error_log)

NginXVirtualHostService - Dependent on VirtualHostAccountService

TomcatVirtualHostService - Dependent on VirtualHostAccountService
	"CreateTomcatVirtualHost" - Create Apache Tomcat virtual host config file(s) in /etc/tomcat6/Catalina/subdomain.domain.tld/. (ROOT.xml, docs.xml, manager.xml, examples.xml)  Add Host entry to /etc/tomcat6/server.xml.
	"RemoveTomcatVirtualHost" - Remove Host entry from /etc/tomcat6/server.xml. Remove Apache Tomcat virtual host config file(s) from /etc/tomcat6/Catalina/subdomain.domain.tld/. (ROOT.xml, docs.xml, manager.xml, examples.xml)
	"EnableTomcatVirtualHost" - Add Host entry to /etc/tomcat6/server.xml.
	"DisableTomcatVirtualHost" - Remove Host entry from /etc/tomcat6/server.xml.
	* Host - appBase="/home/subdomain.domain.tld/webapps"
	* Host Valve org.apache.catalina.valves.AccessLogValve - dir="/home/subdomain.domain.tld/log" and prefix="subdomain.domain.tld-access_log"

PostfixDovecotVirtualHostService
	"CreatePostfixDovecotVirtualHost" - Create Dovecot virtual host dir /vmail/subdomain.domain.tld. Create /etc/postfix/virtual_domains entry.
	"RemovePostfixDovecotVirtualHost" - Remove /etc/postfix/virtual_domains entry. Remove Dovecot virtual host dir /vmail/subdomain.domain.tld.
	"EnablePostfixDovecotVirtualHost" - Create /etc/postfix/virtual_domains entry.
	"DisablePostfixDovecotVirtualHost" - Remove /etc/postfix/virtual_domains entry.
	"CreatePostfixDovecotVirtualHostRelay" - Create /etc/postfix/relay_domains_map entry.
	"RemovePostfixDovecotVirtualHostRelay" - Remove /etc/postfix/relay_domains_map entry
	* Postfix configured to utilize /etc/postfix/virtual_domains file.
	* Postfix configured to utilize /etc/postfix/relay_domains_map.

EximDovecotVirtualHostService

MailDomainService - Dependent on PostfixDovecotVirtualHostService
	"CreateVirtualMailbox" - Create mailbox /vmail/subdomain.domain.tld/user/Maildir.  Create /etc/dovecot/passwd entry.
	"RemoveVirtualMailbox" - Remove mailbox /vmail/subdomain.domain.tld/user/Maildir.  Remove /etc/dovecot/passwd entry.
	"EnableVirtualMailbox" - Enable access to Dovecot virtual mailbox.
	"DisableVirtualMailbox" - Disable access from Dovecot virtual mailbox.
	"SetVirtualMailboxPasswd" - Set Dovecot virtual mailbox password. /etc/dovecot/passwd
	"CreateVirtualMailAlias" - Create Postfix virtual domain mail alias. (Mailbox Server)
	"RemoveVirtualMailAlias" - Remove Postfix virtual domain mail alias. (Mailbox Server)
	"CreateRelayRecipient" - Create Postfix /etc/postfix/relay_recipients_map entry. (Non mailbox MX servers)
	"RemoveRelayRecipient" - Remove Postfix /etc/postfix/relay_recipient_map entry. (Non mailbox MX servers)
	* Dovecot configured to utilize /vmail/subdomain.domain.tld as mailbox location.
	* Dovecot configured to utilize email user as mailbox name
	* Needs to differentiate if/when using Exim

PostgresDatabaseService
	"CreatePostgresDatabase" - Create Postgres Database with GRANT options.
	"RemovePostgresDatabase" - Remove Postgres database.
	"EnablePostgresDatabase" - Enable Postgres database.
	"DisablePostgresDatabase" - Disable Postgres database.
	"SetPostgresDatabasePasswd" - Set the Postgres admin user password.
	"BackupPostgresDatabase" - Backup Postgres database
	"RestorePostgresDatabase" - Restore PostgresDatabase

MysqlDatabaseService
	"CreateMySQLDatabase" - Create MySQL database with GRANT option.
	"RemoveMySQLDatabase" - Remove MySQL database.
	"EnableMySQLDatabase" - Enable MySQL Database.
	"DisableMySQLDatabase" - Disable MySQL Database.
	"SetMySQLDatabasePasswd" Set the MySQL admin user password.
	"BackupMySQLDatabase" - Backup MySQL database.
	"RestoreMySQLDatabase" - RestoreMySQL database.

CouchdbService

RoundcubeWebmailService - Dependent on ApacheVirtualHostService
	"InstallRoundcubeWebmail"
	"UninstallRoundcubeWebmail"
	"EnableRoundcubeWebmail"
	"DisableRoundcubeWebmail"

WordpressService
	"InstallWordpress"
	"UninstallWordpress"
	"EnableWordpress"
	"DisableWordpress"

JoomlaService
	"InstallJoomla"
	"UninstallJoomla"
	"EnableJoomla"
	"DisableJoomla"

WebCalCardDavService

StompRegistration
	"Register" - Register STOMP queue with UserName for messaging.
	"Unregister" - Unregister STOMP queue.
	"SendPeerList" - Send a list of registered UserName and STOMP queue's that accept messages.
	"UserMessage" - Send a message to a STOMP queue from a Registered User.
	"MissingMethod" - Catch the missing method for future development.

</body>
</html>


text:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Services\ModelQueries;
use App\Services\Auditorias;

class Promotor extends Model {

	/**
	 * Consultas encapsuladas
	 *
	 * Actualiza los campos de Auditoria
	 */
	use ModelQueries, Auditorias;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'promotor';

	/**
	 * Los atributos agregados del formato JSON del Modelo
	 *
	 * @var array
	 */
	protected $with = ['grupo'];

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = ['nombres', 'apellidos', 'email', 'celular', 'foto', 'motorizado', 'grupo_id', 'dni', 'calificacion'];

	/**
	 * Los atributos excluidos del formato JSON del Modelo
	 *
	 * @var array
	 */
	protected $hidden = ['grupo_id', 'activo', 'created_at', 'updated_at',  'created_by', 'updated_by'];

	/**
	 *  Promotor pertenece a un Grupo
	 */
	public function grupo()
	{
		return $this->belongsTo('App\Grupo');
	}
}


text:
Thank you for signing up to our mailing list.

Your email address {{ $email }} has been added to our records, and the SIG
leader has been notified of your subscription.

UK Fluids Network


text:
#include "CookieJar.h"

#include "Autosaver.h"

#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QMetaEnum>
#include <QtCore/QSettings>
#include <QtCore/QUrl>

#include <QtWidgets/QCompleter>
#include <QtGui/QDesktopServices>
#include <QtWidgets/QHeaderView>
#include <QtGui/QKeyEvent>
#include <QtCore/QSortFilterProxyModel>
#include <QtNetwork/QNetworkCookie>

#include <QWebEngineSettings>

#include <QtCore/QDebug>
#include <QCoreApplication>

static const unsigned int JAR_VERSION = 23;

QT_BEGIN_NAMESPACE
QDataStream &operator<<(QDataStream &stream, const QList<QNetworkCookie> &list)
{
    stream << JAR_VERSION;
    stream << quint32(list.size());
    for (int i = 0; i < list.size(); ++i)
        stream << list.at(i).toRawForm();
    return stream;
}

QDataStream &operator>>(QDataStream &stream, QList<QNetworkCookie> &list)
{
    list.clear();

    quint32 version;
    stream >> version;

    if (version != JAR_VERSION)
        return stream;

    quint32 count;
    stream >> count;
    for(quint32 i = 0; i < count; ++i)
    {
        QByteArray value;
        stream >> value;
        QList<QNetworkCookie> newCookies = QNetworkCookie::parseCookies(value);
        if (newCookies.count() == 0 && value.length() != 0) {
            qWarning() << "CookieJar: Unable to parse saved cookie:" << value;
        }
        for (int j = 0; j < newCookies.count(); ++j)
            list.append(newCookies.at(j));
        if (stream.atEnd())
            break;
    }
    return stream;
}
QT_END_NAMESPACE

CookieJar::CookieJar(QObject *parent)
    : QNetworkCookieJar(parent)
    , m_loaded(false)
    , m_saveTimer(new AutoSaver(this))
    , m_acceptCookies(AcceptOnlyFromSitesNavigatedTo)
{
}

CookieJar::~CookieJar()
{
    if (m_keepCookies == KeepUntilExit)
        clear();
    m_saveTimer->saveIfNeccessary();
}

void CookieJar::clear()
{
    setAllCookies(QList<QNetworkCookie>());
    m_saveTimer->changeOccurred();
    emit cookiesChanged();
}

void CookieJar::load()
{
    if (m_loaded)
        return;
    // load cookies and exceptions
    qRegisterMetaTypeStreamOperators<QList<QNetworkCookie> >("QList<QNetworkCookie>");
    QSettings cookieSettings(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1String("/cookies.ini"), QSettings::IniFormat);
    setAllCookies(qvariant_cast<QList<QNetworkCookie> >(cookieSettings.value(QLatin1String("cookies"))));
    cookieSettings.beginGroup(QLatin1String("Exceptions"));
    m_exceptions_block = cookieSettings.value(QLatin1String("block")).toStringList();
    m_exceptions_allow = cookieSettings.value(QLatin1String("allow")).toStringList();
    m_exceptions_allowForSession = cookieSettings.value(QLatin1String("allowForSession")).toStringList();
    qSort(m_exceptions_block.begin(), m_exceptions_block.end());
    qSort(m_exceptions_allow.begin(), m_exceptions_allow.end());
    qSort(m_exceptions_allowForSession.begin(), m_exceptions_allowForSession.end());

    loadSettings();
}

void CookieJar::loadSettings()
{
    QSettings settings;
    settings.beginGroup(QLatin1String("cookies"));
    QByteArray value = settings.value(QLatin1String("acceptCookies"),
                        QLatin1String("AcceptOnlyFromSitesNavigatedTo")).toByteArray();
    QMetaEnum acceptPolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("AcceptPolicy"));
    m_acceptCookies = acceptPolicyEnum.keyToValue(value) == -1 ?
                        AcceptOnlyFromSitesNavigatedTo :
                        static_cast<AcceptPolicy>(acceptPolicyEnum.keyToValue(value));

    value = settings.value(QLatin1String("keepCookiesUntil"), QLatin1String("KeepUntilExpire")).toByteArray();
    QMetaEnum keepPolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("KeepPolicy"));
    m_keepCookies = keepPolicyEnum.keyToValue(value) == -1 ?
                        KeepUntilExpire :
                        static_cast<KeepPolicy>(keepPolicyEnum.keyToValue(value));

    if (m_keepCookies == KeepUntilExit)
        setAllCookies(QList<QNetworkCookie>());

    m_loaded = true;
    emit cookiesChanged();
}

void CookieJar::save()
{
    if (!m_loaded)
        return;
    purgeOldCookies();
    QString directory = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    if (directory.isEmpty())
        directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
    if (!QFile::exists(directory)) {
        QDir dir;
        dir.mkpath(directory);
    }
    QSettings cookieSettings(directory + QLatin1String("/cookies.ini"), QSettings::IniFormat);
    QList<QNetworkCookie> cookies = allCookies();
    for (int i = cookies.count() - 1; i >= 0; --i) {
        if (cookies.at(i).isSessionCookie())
            cookies.removeAt(i);
    }
    cookieSettings.setValue(QLatin1String("cookies"), QVariant::fromValue<QList<QNetworkCookie> >(cookies));
    cookieSettings.beginGroup(QLatin1String("Exceptions"));
    cookieSettings.setValue(QLatin1String("block"), m_exceptions_block);
    cookieSettings.setValue(QLatin1String("allow"), m_exceptions_allow);
    cookieSettings.setValue(QLatin1String("allowForSession"), m_exceptions_allowForSession);

    // save cookie settings
    QSettings settings;
    settings.beginGroup(QLatin1String("cookies"));
    QMetaEnum acceptPolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("AcceptPolicy"));
    settings.setValue(QLatin1String("acceptCookies"), QLatin1String(acceptPolicyEnum.valueToKey(m_acceptCookies)));

    QMetaEnum keepPolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("KeepPolicy"));
    settings.setValue(QLatin1String("keepCookiesUntil"), QLatin1String(keepPolicyEnum.valueToKey(m_keepCookies)));
}

void CookieJar::purgeOldCookies()
{
    QList<QNetworkCookie> cookies = allCookies();
    if (cookies.isEmpty())
        return;
    int oldCount = cookies.count();
    QDateTime now = QDateTime::currentDateTime();
    for (int i = cookies.count() - 1; i >= 0; --i) {
        if (!cookies.at(i).isSessionCookie() && cookies.at(i).expirationDate() < now)
            cookies.removeAt(i);
    }
    if (oldCount == cookies.count())
        return;
    setAllCookies(cookies);
    emit cookiesChanged();
}

QList<QNetworkCookie> CookieJar::cookiesForUrl(const QUrl &url) const
{
    CookieJar *that = const_cast<CookieJar*>(this);
    if (!m_loaded)
        that->load();

    /*QWebEngineSettings *globalSettings = QWebEngineSettings::globalSettings();
    if (globalSettings->testAttribute(QWebEngineSettings::PrivateBrowsing)) {
        QList<QNetworkCookie> noCookies;
        return noCookies;
    }*/

    return QNetworkCookieJar::cookiesForUrl(url);
}

bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
{
    if (!m_loaded)
        load();

    /*QWebEngineSettings *globalSettings = QWebEngineSettings::globalSettings();
    if (globalSettings->testAttribute(QWebEngineSettings::PrivateBrowsingEnabled))
        return false;
*/
    QString host = url.host();
    bool eBlock = qBinaryFind(m_exceptions_block.begin(), m_exceptions_block.end(), host) != m_exceptions_block.end();
    bool eAllow = qBinaryFind(m_exceptions_allow.begin(), m_exceptions_allow.end(), host) != m_exceptions_allow.end();
    bool eAllowSession = qBinaryFind(m_exceptions_allowForSession.begin(), m_exceptions_allowForSession.end(), host) != m_exceptions_allowForSession.end();

    bool addedCookies = false;
    // pass exceptions
    bool acceptInitially = (m_acceptCookies != AcceptNever);
    if ((acceptInitially && !eBlock)
        || (!acceptInitially && (eAllow || eAllowSession))) {
        // pass url domain == cookie domain
        QDateTime soon = QDateTime::currentDateTime();
        soon = soon.addDays(90);
        foreach(QNetworkCookie cookie, cookieList) {
            QList<QNetworkCookie> lst;
            if (m_keepCookies == KeepUntilTimeLimit
                && !cookie.isSessionCookie()
                && cookie.expirationDate() > soon) {
                    cookie.setExpirationDate(soon);
            }
            lst += cookie;
            if (QNetworkCookieJar::setCookiesFromUrl(lst, url)) {
                addedCookies = true;
            } else {
                // finally force it in if wanted
                if (m_acceptCookies == AcceptAlways) {
                    QList<QNetworkCookie> cookies = allCookies();
                    cookies += cookie;
                    setAllCookies(cookies);
                    addedCookies = true;
                }
#if 0
                else
                    qWarning() << "setCookiesFromUrl failed" << url << cookieList.value(0).toRawForm();
#endif
            }
        }
    }

    if (addedCookies) {
        m_saveTimer->changeOccurred();
        emit cookiesChanged();
    }
    return addedCookies;
}

CookieJar::AcceptPolicy CookieJar::acceptPolicy() const
{
    if (!m_loaded)
        (const_cast<CookieJar*>(this))->load();
    return m_acceptCookies;
}

void CookieJar::setAcceptPolicy(AcceptPolicy policy)
{
    if (!m_loaded)
        load();
    if (policy == m_acceptCookies)
        return;
    m_acceptCookies = policy;
    m_saveTimer->changeOccurred();
}

CookieJar::KeepPolicy CookieJar::keepPolicy() const
{
    if (!m_loaded)
        (const_cast<CookieJar*>(this))->load();
    return m_keepCookies;
}

void CookieJar::setKeepPolicy(KeepPolicy policy)
{
    if (!m_loaded)
        load();
    if (policy == m_keepCookies)
        return;
    m_keepCookies = policy;
    m_saveTimer->changeOccurred();
}

QStringList CookieJar::blockedCookies() const
{
    if (!m_loaded)
        (const_cast<CookieJar*>(this))->load();
    return m_exceptions_block;
}

QStringList CookieJar::allowedCookies() const
{
    if (!m_loaded)
        (const_cast<CookieJar*>(this))->load();
    return m_exceptions_allow;
}

QStringList CookieJar::allowForSessionCookies() const
{
    if (!m_loaded)
        (const_cast<CookieJar*>(this))->load();
    return m_exceptions_allowForSession;
}

void CookieJar::setBlockedCookies(const QStringList &list)
{
    if (!m_loaded)
        load();
    m_exceptions_block = list;
    qSort(m_exceptions_block.begin(), m_exceptions_block.end());
    m_saveTimer->changeOccurred();
}

void CookieJar::setAllowedCookies(const QStringList &list)
{
    if (!m_loaded)
        load();
    m_exceptions_allow = list;
    qSort(m_exceptions_allow.begin(), m_exceptions_allow.end());
    m_saveTimer->changeOccurred();
}

void CookieJar::setAllowForSessionCookies(const QStringList &list)
{
    if (!m_loaded)
        load();
    m_exceptions_allowForSession = list;
    qSort(m_exceptions_allowForSession.begin(), m_exceptions_allowForSession.end());
    m_saveTimer->changeOccurred();
}

CookieModel::CookieModel(CookieJar *cookieJar, QObject *parent)
    : QAbstractTableModel(parent)
    , m_cookieJar(cookieJar)
{
    connect(m_cookieJar, SIGNAL(cookiesChanged()), this, SLOT(cookiesChanged()));
    m_cookieJar->load();
}

QVariant CookieModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::SizeHintRole) {
        QFont font;
        font.setPointSize(10);
        QFontMetrics fm(font);
        int height = fm.height() + fm.height()/3;
        int width = fm.width(headerData(section, orientation, Qt::DisplayRole).toString());
        return QSize(width, height);
    }

    if (orientation == Qt::Horizontal) {
        if (role != Qt::DisplayRole)
            return QVariant();

        switch (section) {
            case 0:
                return tr("Website");
            case 1:
                return tr("Name");
            case 2:
                return tr("Path");
            case 3:
                return tr("Secure");
            case 4:
                return tr("Expires");
            case 5:
                return tr("Contents");
            default:
                return QVariant();
        }
    }
    return QAbstractTableModel::headerData(section, orientation, role);
}

QVariant CookieModel::data(const QModelIndex &index, int role) const
{
    QList<QNetworkCookie> lst;
    if (m_cookieJar)
        lst = m_cookieJar->allCookies();
    if (index.row() < 0 || index.row() >= lst.size())
        return QVariant();

    switch (role) {
    case Qt::DisplayRole:
    case Qt::EditRole: {
        QNetworkCookie cookie = lst.at(index.row());
        switch (index.column()) {
            case 0:
                return cookie.domain();
            case 1:
                return cookie.name();
            case 2:
                return cookie.path();
            case 3:
                return cookie.isSecure();
            case 4:
                return cookie.expirationDate();
            case 5:
                return cookie.value();
        }
        }
    case Qt::FontRole:{
        QFont font;
        font.setPointSize(10);
        return font;
        }
    }

    return QVariant();
}

int CookieModel::columnCount(const QModelIndex &parent) const
{
    return (parent.isValid()) ? 0 : 6;
}

int CookieModel::rowCount(const QModelIndex &parent) const
{
    return (parent.isValid() || !m_cookieJar) ? 0 : m_cookieJar->allCookies().count();
}

bool CookieModel::removeRows(int row, int count, const QModelIndex &parent)
{
    if (parent.isValid() || !m_cookieJar)
        return false;
    int lastRow = row + count - 1;
    beginRemoveRows(parent, row, lastRow);
    QList<QNetworkCookie> lst = m_cookieJar->allCookies();
    for (int i = lastRow; i >= row; --i) {
        lst.removeAt(i);
    }
    m_cookieJar->setAllCookies(lst);
    endRemoveRows();
    return true;
}

void CookieModel::cookiesChanged()
{
    beginResetModel();
    endResetModel();
}

CookieExceptionsModel::CookieExceptionsModel(CookieJar *cookiejar, QObject *parent)
    : QAbstractTableModel(parent)
    , m_cookieJar(cookiejar)
{
    m_allowedCookies = m_cookieJar->allowedCookies();
    m_blockedCookies = m_cookieJar->blockedCookies();
    m_sessionCookies = m_cookieJar->allowForSessionCookies();
}

QVariant CookieExceptionsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::SizeHintRole) {
        QFont font;
        font.setPointSize(10);
        QFontMetrics fm(font);
        int height = fm.height() + fm.height()/3;
        int width = fm.width(headerData(section, orientation, Qt::DisplayRole).toString());
        return QSize(width, height);
    }

    if (orientation == Qt::Horizontal
        && role == Qt::DisplayRole) {
        switch (section) {
            case 0:
                return tr("Website");
            case 1:
                return tr("Status");
        }
    }
    return QAbstractTableModel::headerData(section, orientation, role);
}

QVariant CookieExceptionsModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < 0 || index.row() >= rowCount())
        return QVariant();

    switch (role) {
    case Qt::DisplayRole:
    case Qt::EditRole: {
        int row = index.row();
        if (row < m_allowedCookies.count()) {
            switch (index.column()) {
                case 0:
                    return m_allowedCookies.at(row);
                case 1:
                    return tr("Allow");
            }
        }
        row = row - m_allowedCookies.count();
        if (row < m_blockedCookies.count()) {
            switch (index.column()) {
                case 0:
                    return m_blockedCookies.at(row);
                case 1:
                    return tr("Block");
            }
        }
        row = row - m_blockedCookies.count();
        if (row < m_sessionCookies.count()) {
            switch (index.column()) {
                case 0:
                    return m_sessionCookies.at(row);
                case 1:
                    return tr("Allow For Session");
            }
        }
        }
    case Qt::FontRole:{
        QFont font;
        font.setPointSize(10);
        return font;
        }
    }
    return QVariant();
}

int CookieExceptionsModel::columnCount(const QModelIndex &parent) const
{
    return (parent.isValid()) ? 0 : 2;
}

int CookieExceptionsModel::rowCount(const QModelIndex &parent) const
{
    return (parent.isValid() || !m_cookieJar) ? 0 : m_allowedCookies.count() + m_blockedCookies.count() + m_sessionCookies.count();
}

bool CookieExceptionsModel::removeRows(int row, int count, const QModelIndex &parent)
{
    if (parent.isValid() || !m_cookieJar)
        return false;

    int lastRow = row + count - 1;
    beginRemoveRows(parent, row, lastRow);
    for (int i = lastRow; i >= row; --i) {
        if (i < m_allowedCookies.count()) {
            m_allowedCookies.removeAt(row);
            continue;
        }
        i = i - m_allowedCookies.count();
        if (i < m_blockedCookies.count()) {
            m_blockedCookies.removeAt(row);
            continue;
        }
        i = i - m_blockedCookies.count();
        if (i < m_sessionCookies.count()) {
            m_sessionCookies.removeAt(row);
            continue;
        }
    }
    m_cookieJar->setAllowedCookies(m_allowedCookies);
    m_cookieJar->setBlockedCookies(m_blockedCookies);
    m_cookieJar->setAllowForSessionCookies(m_sessionCookies);
    endRemoveRows();
    return true;
}


text:
command = testtex_command ("--gettexels -res 128 128 -d uint8 ../common/textures/grid.tx -o postage.tif")
outputs = [ "postage.tif" ]


text:
<?php

namespace FastBill\Model;

class InvoiceItem extends AbstractModel
{
    protected static $xmlProperties = array(
        'INVOICE_ITEM_ID' => 'invoiceItemId',
        'ARTICLE_NUMBER' => 'articleNumber',
        'DESCRIPTION' => 'description',
        'QUANTITY' => 'quantity',
        'UNIT_PRICE' => 'unitPrice',
        'UNIT' => 'unit',
        'VAT_PERCENT' => 'vatPercent',

        'VAT_VALUE' => 'vatValue',
        'COMPLETE_NET' => 'completeNet',
        'COMPLETE_GROSS' => 'completeGross',
        'SORT_ORDER' => 'sortOrder'
    );
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;

import com.yahoo.vdslib.distribution.ConfiguredNode;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
import org.junit.jupiter.api.Test;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.yahoo.vespa.clustercontroller.core.matchers.EventForNode.eventForNode;
import static com.yahoo.vespa.clustercontroller.core.matchers.NodeEventWithDescription.nodeEventWithDescription;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.AllOf.allOf;
import static org.hamcrest.core.IsCollectionContaining.hasItem;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class GroupAutoTakedownTest {

    private static ClusterFixture createFixtureForAllUpFlatCluster(int nodeCount, double minNodeRatioPerGroup) {
        ClusterFixture fixture = ClusterFixture.forFlatCluster(nodeCount);
        setSharedFixtureOptions(fixture, minNodeRatioPerGroup);
        return fixture;
    }

    private static ClusterFixture createFixtureForAllUpHierarchicCluster(
            DistributionBuilder.GroupBuilder root, double minNodeRatioPerGroup)
    {
        ClusterFixture fixture = ClusterFixture.forHierarchicCluster(root);
        setSharedFixtureOptions(fixture, minNodeRatioPerGroup);
        return fixture;
    }

    private static void setSharedFixtureOptions(ClusterFixture fixture, double minNodeRatioPerGroup) {
        fixture.setMinNodeRatioPerGroup(minNodeRatioPerGroup);
        fixture.disableTransientMaintenanceModeOnDown();
        fixture.disableAutoClusterTakedown();
        fixture.bringEntireClusterUp();
    }

    private String stateAfterStorageTransition(ClusterFixture fixture, final int index, final State state) {
        transitionStorageNodeToState(fixture, index, state);
        return fixture.generatedClusterState();
    }

    private String verboseStateAfterStorageTransition(ClusterFixture fixture, final int index, final State state) {
        transitionStorageNodeToState(fixture, index, state);
        return fixture.verboseGeneratedClusterState();
    }

    private void transitionStorageNodeToState(ClusterFixture fixture, int index, State state) {
        fixture.reportStorageNodeState(index, state);
    }

    private AnnotatedClusterState annotatedStateAfterStorageTransition(ClusterFixture fixture, final int index, final State state) {
        transitionStorageNodeToState(fixture, index, state);
        return fixture.annotatedGeneratedClusterState();
    }

    /**
     * Use a per-group availability requirement ratio of 99%. Ensure that taking down a single
     * node out of 5 in a flat hierarchy does not take down the cluster, i.e. the config should
     * not apply to a flat structure.
     */
    @Test
    void config_does_not_apply_to_flat_hierarchy_clusters() {
        ClusterFixture fixture = createFixtureForAllUpFlatCluster(5, 0.99);

        assertEquals("distributor:5 storage:5", fixture.generatedClusterState());

        assertEquals("distributor:5 storage:5 .1.s:d",
                stateAfterStorageTransition(fixture, 1, State.DOWN));
    }

    @Test
    void group_node_down_edge_implicitly_marks_down_rest_of_nodes_in_group() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);

        assertEquals("distributor:6 storage:6", fixture.generatedClusterState());

        // Same group as node 4
        assertEquals("distributor:6 storage:4",
                stateAfterStorageTransition(fixture, 5, State.DOWN));
        // Same group as node 1
        assertEquals("distributor:6 storage:4 .0.s:d .1.s:d",
                stateAfterStorageTransition(fixture, 0, State.DOWN));
    }

    @Test
    void restored_group_node_availability_takes_group_back_up_automatically() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);

        // Group #2 -> down
        assertEquals("distributor:6 storage:4",
                stateAfterStorageTransition(fixture, 5, State.DOWN));

        // Group #2 -> back up again
        assertEquals("distributor:6 storage:6",
                stateAfterStorageTransition(fixture, 5, State.UP));
    }

    @Test
    void no_op_for_downed_nodes_in_already_downed_group() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);

        assertEquals("distributor:6 storage:4",
                stateAfterStorageTransition(fixture, 5, State.DOWN));

        // 4, 5 in same group; this should not cause a new state since it's already implicitly down
        fixture.reportStorageNodeState(4, State.DOWN);
        assertEquals("distributor:6 storage:4", fixture.generatedClusterState());
    }

    @Test
    void verbose_node_state_description_updated_for_implicitly_downed_nodes() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.75);

        // Nodes 6 and 7 are taken down implicitly and should have a message reflecting this.
        // Node 8 is taken down by the fixture and gets a fixture-assigned message that
        // we should _not_ lose/overwrite.
        assertEquals("distributor:9 storage:9 .6.s:d " +
                ".6.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
                ".7.s:d " +
                ".7.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
                ".8.s:d .8.m:mockdesc",
                verboseStateAfterStorageTransition(fixture, 8, State.DOWN));
    }

    @Test
    void legacy_cluster_wide_availabilty_ratio_is_computed_after_group_takedowns() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
        fixture.setMinNodesUp(5, 5, 0.51, 0.51);

        // Taking down a node in a group forces the entire group down, which leaves us with
        // only 4 content nodes (vs. minimum of 5 as specified above). The entire cluster
        // should be marked as down in this case.
        assertEquals("cluster:d distributor:6 storage:4",
                stateAfterStorageTransition(fixture, 5, State.DOWN));
    }

    @Test
    void maintenance_wanted_state_not_overwritten() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);

        fixture.proposeStorageNodeWantedState(5, State.MAINTENANCE);
        // Maintenance not counted as down, so group still up
        assertEquals("distributor:9 storage:9 .5.s:m", fixture.generatedClusterState());

        // Group goes down, but maintenance node should still be in maintenance
        assertEquals("distributor:9 storage:9 .3.s:d .4.s:d .5.s:m",
                stateAfterStorageTransition(fixture, 4, State.DOWN));
    }

    @Test
    void transient_maintenance_mode_on_down_edge_does_not_take_down_group() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
        fixture.enableTransientMaintenanceModeOnDown(1000);

        // Our timers are mocked, so taking down node 4 will deterministically transition to
        // a transient maintenance mode. Group should not be taken down here.
        assertEquals("distributor:9 storage:9 .4.s:m",
                stateAfterStorageTransition(fixture, 4, State.DOWN));

        // However, once grace period expires the group should be taken down.
        fixture.timer.advanceTime(1001);
        NodeListener changeListener = mock(NodeListener.class);
        fixture.nodeStateChangeHandler.watchTimers(
                fixture.cluster, fixture.annotatedGeneratedClusterState().getClusterState(), changeListener);

        assertEquals("distributor:9 storage:9 .3.s:d .4.s:d .5.s:d", fixture.generatedClusterState());
    }

    private static Node contentNode(int index) {
        return new Node(NodeType.STORAGE, index);
    }

    @Test
    void taking_down_node_adds_node_specific_event() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);

        final List<Event> events = EventDiffCalculator.computeEventDiff(EventDiffCalculator.params()
                .cluster(fixture.cluster)
                .fromState(ClusterStateBundle.ofBaselineOnly(fixture.annotatedGeneratedClusterState()))
                .toState(ClusterStateBundle.ofBaselineOnly(annotatedStateAfterStorageTransition(fixture, 5, State.DOWN))));

        assertThat(events, hasItem(allOf(
                nodeEventWithDescription("Group node availability is below configured threshold"),
                eventForNode(contentNode(4)))));
    }

    @Test
    void bringing_node_back_up_adds_node_specific_event() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);

        assertEquals("distributor:6 storage:4",
                stateAfterStorageTransition(fixture, 5, State.DOWN));

        final List<Event> events = EventDiffCalculator.computeEventDiff(EventDiffCalculator.params()
                .cluster(fixture.cluster)
                .fromState(ClusterStateBundle.ofBaselineOnly(fixture.annotatedGeneratedClusterState()))
                .toState(ClusterStateBundle.ofBaselineOnly(annotatedStateAfterStorageTransition(fixture, 5, State.UP))));

        assertThat(events, hasItem(allOf(
                nodeEventWithDescription("Group node availability has been restored"),
                eventForNode(contentNode(4)))));
    }

    @Test
    void wanted_state_retired_implicitly_down_node_is_transitioned_to_retired_mode_immediately() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);

        assertEquals("distributor:9 storage:6",
                stateAfterStorageTransition(fixture, 6, State.DOWN));
        // Node 7 is implicitly down. Mark wanted state as retired. It should now be Retired
        // but not Down.
        fixture.proposeStorageNodeWantedState(7, State.RETIRED);

        assertEquals("distributor:9 storage:8 .6.s:d .7.s:r", fixture.generatedClusterState());
    }

    @Test
    void downed_config_retired_node_transitions_back_to_retired_on_up_edge() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.49);

        assertEquals("distributor:6 storage:6 .4.s:d",
                stateAfterStorageTransition(fixture, 4, State.DOWN));
        assertEquals("distributor:6 storage:4",
                stateAfterStorageTransition(fixture, 5, State.DOWN));

        // Node 5 gets config-retired under our feet.
        Set<ConfiguredNode> nodes = new HashSet<>(fixture.cluster.clusterInfo().getConfiguredNodes().values());
        nodes.remove(new ConfiguredNode(5, false));
        nodes.add(new ConfiguredNode(5, true));
        // TODO this should ideally also set the retired flag in the distribution
        // config, but only the ConfiguredNodes are actually looked at currently.
        fixture.cluster.setNodes(nodes, new NodeListener() {
        });

        assertEquals("distributor:6 storage:6 .4.s:d .5.s:r",
                stateAfterStorageTransition(fixture, 5, State.UP));
    }

    @Test
    void init_progress_is_preserved_across_group_down_up_edge() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);

        final NodeState newState = new NodeState(NodeType.STORAGE, State.INITIALIZING);
        newState.setInitProgress(0.5f);

        fixture.reportStorageNodeState(4, newState);

        assertEquals("distributor:6 storage:6 .4.s:i .4.i:0.5", fixture.generatedClusterState());

        assertEquals("distributor:6 storage:4",
                stateAfterStorageTransition(fixture, 5, State.DOWN));
        assertEquals("distributor:6 storage:6 .4.s:i .4.i:0.5",
                stateAfterStorageTransition(fixture, 5, State.UP));
    }

    @Test
    void down_wanted_state_is_preserved_across_group_down_up_edge() {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.60);

        fixture.proposeStorageNodeWantedState(5, State.DOWN, "borkbork");

        assertEquals("distributor:9 storage:9 .5.s:d .5.m:borkbork", fixture.verboseGeneratedClusterState());

        assertEquals("distributor:9 storage:9 " +
                ".3.s:d .3.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
                ".4.s:d .4.m:mockdesc .5.s:d .5.m:borkbork",
                verboseStateAfterStorageTransition(fixture, 4, State.DOWN));
        assertEquals("distributor:9 storage:9 .5.s:d .5.m:borkbork",
                verboseStateAfterStorageTransition(fixture, 4, State.UP));
    }

    @Test
    void previously_cleared_start_timestamps_are_not_reintroduced_on_up_edge() throws Exception {
        ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
                DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);

        final NodeState newState = new NodeState(NodeType.STORAGE, State.UP);
        newState.setStartTimestamp(123456);

        fixture.reportStorageNodeState(4, newState);

        assertEquals("distributor:6 storage:6 .4.t:123456", fixture.generatedClusterState());

        DatabaseHandler handler = mock(DatabaseHandler.class);
        DatabaseHandler.DatabaseContext context = mock(DatabaseHandler.DatabaseContext.class);
        when(context.getCluster()).thenReturn(fixture.cluster);

        Set<ConfiguredNode> nodes = new HashSet<>(fixture.cluster.clusterInfo().getConfiguredNodes().values());
        fixture.nodeStateChangeHandler.handleAllDistributorsInSync(
                fixture.annotatedGeneratedClusterState().getClusterState(), nodes, handler, context);

        // Timestamp should now be cleared from state
        assertEquals("distributor:6 storage:6", fixture.generatedClusterState());

        // Trigger a group down+up edge. Timestamp should _not_ be reintroduced since it was previously cleared.
        assertEquals("distributor:6 storage:4",
                stateAfterStorageTransition(fixture, 5, State.DOWN));
        assertEquals("distributor:6 storage:6",
                stateAfterStorageTransition(fixture, 5, State.UP));
    }

}


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\PeerAssessment\Display\Component\UserAttemptStatusViewer;

use Chamilo\Libraries\Format\Table\Extension\DataClassTable\DataClassTableDataProvider;
use Chamilo\Libraries\Storage\ResultSet\ArrayResultSet;

/**
 *
 * @package repository.lib.complex_display.peer_asessment.component.user_attempt_status_viewer
 */
/**
 * This class represents a data provider for a results candidate table
 */
class UserAttemptStatusViewerTableDataProvider extends DataClassTableDataProvider
{

    public function retrieve_data($condition, $offset, $count, $order_property = null)
    {
        try
        {
            $array_result = $this->get_component()->get_attempts($this->get_component()->get_publication_id());
            return new ArrayResultSet($array_result);
        }
        catch (\ErrorException $e)
        {
            return false;
        }
    }

    public function count_data($condition)
    {
        try
        {
            $array_result = $this->get_component()->get_attempts($this->get_component()->get_publication_id());
            return count($array_result);
        }
        catch (\ErrorException $e)
        {
            return false;
        }
    }
}


text:
@extends('admin.layouts.default') {{-- Web site Title --}}
@section('title') {{{ Lang::get("admin/language.languages") }}} ::
@parent @stop {{-- Content --}} @section('content')

    {{{ Lang::get("admin/language.languages") }}}

       {{
        Lang::get("admin/modal.new") }}

      {{ Lang::get("admin/modal.title") }}
      {{ Lang::get("admin/language.code") }}
      {{ Lang::get("admin/language.icon") }}
      {{ Lang::get("admin/admin.action") }}

@stop {{-- Scripts --}} @section('scripts')

@stop


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

    <!-- General -->

    <!-- Navigation drawer state for usability assistance-->
    <string name="open">درج التصفح مفتوح</string>
    <string name="close">درج التصفح مغلق</string>

    <!-- Network error notification and prompts -->
    <string name="offline_mode_toast">تطبيقMurmur  يعمل في وضع عدم الاتصال بالشبكة</string>
    <string name="notification_connection_error_title">خطأ في الاتصال</string>
    <string name="notification_connection_error_message">تشغيل البلوتوث/الواي فاي أو الانتقال إلى وضع عدم الاتصال بالشبكة</string>
    <string name="notification_no_bluetooth_title">خطأ في الاتصال: البلوتوث لا يعمل</string>
  <!-- no longer in use, uses single error for both WIFI and BT-->
    <string name="notification_no_bluetooth_message">برجاء تشغيل البلوتوث أو الانتقال إلى وضع عدم الاتصال بالشبكة</string>
  <!-- no longer in use, uses single error for both WIFI and BT-->
    <string name="notification_no_wifi_title">خطأ في الاتصال: الواي فاي لا يعمل</string>
  <!-- no longer in use, uses single error for both WIFI and BT-->
    <string name="notification_no_wifi_message">برجاء تشغيل البلوتوث/الواي فاي أو الانتقال إلى وضع عدم الاتصال بالشبكة</string>
  <!-- no longer in use, uses single error for both WIFI and BT-->

    <string name="error_notification_action_onwifi">تشغيل</string>
    <string name="error_notification_action_turnon_bt">تشغيل</string>
    <string name="error_notification_action_off_service">الانتقال إلى وضع عدم الاتصال بالشبكة</string>

    <!-- New messages notification-->
    <string name="unread_notification_title">لا توجد رسائل غير مقروءة</string>
    <string name="unread_notification_content">تبادلات جديدة</string>

    <!-- New messages snackbar -->
    <string name="new_messages_notification_desc">رسائل جديدة</string>
    <string name="new_message_notification_desc">رسالة جديدة</string>
    <string name="new_messages_notification_btn">عرض الجديد</string>
    <string name="exchanges">تبادلات جديدة</string>
    <string name="exchange">تبادل جديد</string>

    <!-- Drawer menu actions (also used as page titles)-->
    <string name="drawer_menu_feed">التلقيم</string>
    <string name="drawer_menu_starred">مميز بنجمة</string>
    <string name="drawer_menu_offline_mode">وضع عدم الاتصال بالشبكة</string>
    <string name="drawer_menu_contact">جهات الاتصال</string>
    <string name="drawer_menu_profile">الملف الشخصي</string>
    <string name="drawer_menu_settings">الإعدادات</string>
    <string name="drawer_menu_help">المساعدة والتعقيبات</string>
    <string name="drawer_menu_info">حول التطبيق</string>
    <string name="drawer_menu_reset">إعادة ضبط التطبيق</string>
    <string name="drawer_menu_export">تصدير التلقيم</string>
    <string name="drawer_menu_share_app">مشاركة Murmur</string>
    <string name="drawer_menu_advanced">متقدم</string>

    <!-- share app picker title-->
    <string name="share_using">.مشاركة باستخدام</string>

    <!-- export process toasts-->
    <string name="export">جارِ التصدير ...</string>
    <string name="export_message">برجاء الانتظار</string>
    <string name="export_successful">تم إخراج التلقيم إلى مجلد التحميلات</string>
    <string name="export_failed">عفوا، تعذر تصدير التلقيم، يرجى المحاولة مرة أخرى</string>

    <!-- Share message (from feed/stared)-->
    <string name="share_prefix">تم الإرسال بواسطة Murmur</string>

    <!-- Actionbar/Toolbar-->

    <string name="empty_string"/>
    <string name="select_all">اختيار الكل</string>
    <string name="deselect_all">إلغاء اختيار الكل</string>

    <!-- actionbar sort options-->
    <string name="sort_opt_newest">الأحدث</string>
    <string name="sort_opt_oldest">الأقدم</string>
    <string name="sort_opt_mostendorsed">الأكثر تأييدًا</string>
    <string name="sort_opt_leastendorsed">الأقل تأييدًا</string>
    <string name="sort_opt_mostconnected">الأكثر اتصالاً</string>
    <string name="sort_opt_leastconnected">الأقل اتصالاً</string>

    <!-- menu item titles (not shown but required) -->
    <string name="send">إرسال</string>
    <string name="search_title">بحث</string>
    <string name="retweet">إعادة المشاركة</string>
    <string name="share">مشاركة</string>
    <string name="delete">حذف</string>

    <!-- menu item titles (shown when in advance delete mode-->
    <string name="delete_from_sender">نفس الاسم المستعار</string>
  <!--Delete messages with same sender-->
    <string name="delete_by_connection">نفس الدرجة أو أقل</string>
  <!--Delete messages with same or lower connection-->
    <string name="delete_by_exchange">نفس التبادل</string>
  <!--Delete messages from same exchange-->
    <string name="delete_tree">إدراج الردود</string>
  <!--Delete message and replies-->

    <!-- Feed/Starred-->

    <!-- delete dialog conformation-->
    <string name="delete_dialog_title">حذف المحتوى</string>
    <string name="delete_dialog_message1">هل أنت متأكد من رغبتك في حذف</string>
  <!-- pre-number-->
    <string name="delete_dialog_message2">عنصر (عناصر)؟</string>
  <!-- post-number-->

    <!-- item time units -->
    <string name="days_short">يوم</string>
    <string name="just_now">آخر ساعة</string>
    <string name="today">اليوم</string>
    <string name="h_ago">منذ ساعة واحدة</string>
    <string name="d_ago">منذ يوم واحد</string>

    <!-- self destruct pre-text-->
    <string name="self_destruct_in">تدمير ذاتي في</string>
  <!-- time -->

    <!-- reset application dialog -->
    <string name="reset_dialog_title">إعادة ضبط التطبيق</string>
    <string name="reset_app_message">هل أنت متأكد من رغبتك في إعادة ضبط تطبيق Murmur؟\nسوف يتم حذف جميع الرسائل وجهات الاتصال؟</string>
    <string name="confirm_reset_dialog_title">تأكيد إعادة الضبط</string>
    <string name="confirm_reset_app_message">انقر على\"نعم\" لإعادة ضبط Murmur</string>

    <!-- Post/Reply post -->
    <!-- actionbar titles-->
    <string name="new_post">مشاركة جديدة</string>
    <string name="reply">رد</string>

    <string name="post_hint">اكتب رسالتك</string>

    <!-- Self-destruct dialog -->
    <string name="timebound_dialog_title">تدمير ذاتي</string>
    <string name="hours_short">ساعات</string>

    <!-- Share location error -->
    <string name="no_gps_error">تعذر تحديد الموقع، يرجى تفعيل تحديد المواقع (GPS)</string>

    <!-- Profile -->
    <string name="pseudonym_title">الاسم المستعار</string>
    <string name="qr_title">رمز الاستجابة السريعة</string>

    <!-- Contacts-->

    <!-- Menu item title (not shown but required) -->
    <string name="add">إضافة</string>

    <!-- Add Contact dialog -->
    <string name="add_friend_dialog_title">إضافة جهة اتصال</string>
    <string name="add_friend_dialog_body">حدد الطريقة</string>
    <string name="add_friend_qrcode">رمز الاستجابة السريعة</string>
    <string name="add_friend_phonebook">دليل الهاتف</string>

    <!-- edit contact dialog -->
    <string name="conf_friend_dialog_title">تعديل جهة الاتصال</string>
    <string name="conf_friend_dialog_name_title">الاسم المستعار</string>
    <string name="conf_friend_dialog_number_title">الهاتف</string>

    <!-- Delete contact conformation dialog-->
    <string name="delete_dialog_friend1">هل أنت متأكد من رغبتك في حذف</string>
  <!--pre-number-->
    <string name="delete_dialog_friend2">عناصر</string>
  <!--post-number-->

    <!-- QR code scanner prompt message-->
    <string name="qr_scanner_message">المسح الضوئي لرمز الاستجابة السريعة في Murmur</string>
    <!-- valid QR code prefix to identify app related QR-->

    <!-- add contact result toasts -->
    <string name="contact_add_conf">تمت إضافة جهة الاتصال</string>
    <string name="contact_exist">موجود بالفعل في جهات الاتصال</string>
    <string name="contact_add_fail">جهة الاتصال المختارة ليس لديها رقم هاتف</string>
    <string name="qr_badqr_error">ليس رمز استجابة سريعة في Murmur</string>

    <!-- Settings-->
    <!-- profile preset block-->
    <string name="select_profile_title">اختيار ملف شخصي</string>
    <string name="profile_flexible">مزايا أكثر/ أمن أقل</string>
    <string name="profile_strict">أمن أكثر/ مزايا أقل</string>
    <string name="profile_custom">مخصص</string>
    <string name="profile_custom_annotation">موصى به للمستخدمين المتقدمين فقط</string>

    <!-- anonymity settings block-->
    <string name="settings_anonymity_title">إخفاء الهوية</string>

    <string name="settings_timestamp">طوابع زمنية</string>
    <string name="settings_location_tagging">تحديد الموقع</string>
    <string name="settings_pseudonym">أسماء مستعارة</string>

    <!-- privacy settings block-->
    <string name="settings_privacy_title">الخصوصية</string>

    <string name="settings_trust">درجات الاتصال</string>
    <string name="settings_self_dest">مدة التدمير الذاتي</string>
    <string name="settings_self_dest_annotation">مدة رسالة التدمير الذاتي الافتراضية بالساعات</string>
    <string name="settings_restricted">رسائل محظورة (جهات الاتصال)</string>
    <string name="settings_restricted_annotation">الحد الأدنى لجهات الاتصال المشتركة لإرسال رسالة</string>

    <!-- feed related settings block-->
    <string name="settings_feed_title">تلقيم</string>

    <string name="settings_autodelete">الحذف التلقائي للرسائل</string>
    <string name="settings_autodelete_trust_annotation">بدرجة اتصال أقل من</string>
  <!-- describe meaning of changing connection score threshold-->
    <string name="settings_autodelete_age_annotation">أقدم من (بالأيام)</string>
  <!-- describe meaning of changing age threshold-->

    <!-- contact related settings block-->
    <string name="settings_contacts_title">جهات الاتصال</string>

    <string name="settings_add_via_phonebook">إضافة جهات اتصال بواسطة سجل الهاتف</string>
    <string name="settings_add_via_qr">إضافة جهات اتصال بواسطة رمز الاستجابة السريعة</string>

    <!-- exchange related settings block-->
    <string name="settings_exchange_title">تبادلات</string>

    <string name="settings_max_messages_p_exchange">الحد الأقصى للرسائل في التبادل الواحد</string>
    <string name="settings_timeout_p_exchange">زمن الانتظار بين التبادلات</string>

    <!-- network related settings block (not currently in use)-->
    <string name="settings_network_title">الشبكة</string>

    <string name="settings_mac_title">عنوان البلوتوث</string>

    <string name="settings_bt_device_settings">الذهاب إلى شاشة الحالة</string>

    <!-- About -->

    <string name="aboutTitle">حول تطبيق Murmur</string>
    <string name="aboutBody">Murmur هو تطبيق لإرسال الرسائل مجاني، ومفتوح\nالمصدر ويخفي\nالهوية، ولا يتطلب الاتصال بالإنترنت.\nو لا يتم إرسال الرسائل في الوقت الحقيقي كما هو الحال في تطبيقات الرسائل الأخرى\nالتي تعتمد على الإنترنت ولها خادم مركزي، ولكن بدلاً من ذلك فإنها تنتقل مباشرة\nمن جهاز إلى آخر (تشكل شبكة ند إلى ند) دون تدخل المستخدم باستخدام تقنية البلوتوث\nوواي فاي مباشرة. وكلما زاد عدد الأجهزة كلما انتشرت الرسالة بشكل أسرع! وإذا لم تكن\nهناك أجهزة قريبة، يتم وضع الرسالة في قائمة الانتظار في التلقيم ليتم إرسالها في\nوقت لاحق. ويمكنك التحكم في عدم الكشف عن هويتك وتحديدالمعلومات التي تشاركها مع\nالآخرين عن نفسك. وأخيرًا،  تساعدك درجات الاتصال\nعلى تصفية الرسائل غير المرغوب فيها فضلاً عن أن الرسائل المحظورة تجعل جمهورك\nمقتصر على أصدقائك.</string>

    <!-- Share app-->
    <!-- notification attached to the url message -->
    <string name="share_app_promo1">اكتشف تطبيق Murmur! على Google Play</string>
    <string name="share_app_promo2">أو إذا لم يكن لديك إمكانية الدخول هنا</string>

    <!-- On-boarding -->
    <string name="skip_welcome">التالى</string>
    <string name="skip_welcome2">حفظ</string>

    <string name="onboarding1_title">تواصل بحرية</string>
    <string name="onboarding1_message">يتم نقل الرسائل بين الأجهزة عبر البلوتوث والواي فاي. وكلما زاد عدد الأجهزة، تحركت الرسائل بشكل أسرع! وإذا لم يكن هناك أجهزة قريبة، يتم وضع الرسائل في قائمة الانتظار ليتم إرسالها في وقت لاحق</string>

    <string name="onboarding2_title">تحكم في إخفاء هويتك.</string>
    <string name="onboarding2_message">قم باختيار إعدادات الأمان لتحديد مستوى إخفاء هويتك. وكلما زادت الإعدادات المتاحة، زادت المعلومات التي تشاركها عن نفسك</string>

    <string name="onboarding3_title">حافظ على خصوصيتك</string>
    <string name="onboarding3_message">قم بتصفية الرسائل غير المرغوب فيها باستخدام درجات الاتصال وقلل عدد جمهورك بواسطة الرسائل المحظورة</string>

    <string name="onboarding4_title">شئ آخر واحد فقط</string>
    <string name="onboarding4_message">يرجى تشغيل البلوتوث، والذهاب إلى شاشة الحالة، ونسخ ولصق عنوان البلوتوث الخاص بك أدناه:</string>
    <string name="onboarding4_message_small_why">\n\n\n \n  \n  لماذا نطلب منك ذلك؟</string>
    <string name="onboarding4_message_small">يستخدم تطبيق Murmur البلوتوث للاتصال. وللأسف، فإن تطبيقات أندرويد 6.x لا يمكنها الوصول التلقائي لعنوان البلوتوث الخاص بك، ولذلك نحن في حاجة لمساعدتك. ولا تقلق - سيكون عليك إدخال هذا مرة واحدة فقط. وإذا أخطأت في إدخال العنوان يمكنك تصحيح ذلك لاحقًا في الإعدادات</string>
    <string name="onboarding4_message_error">عنوان بلوتوث غير صحيح</string>

    <!--Replies feed-->
    <string name="comments">ردود</string>

    <!-- Help & Feedback-->
    <!-- feedback-->
    <string name="send_feedback">أرسل تعقيبًا</string>
    <string name="feedback_intro">السيد ممثل الدعم في Murmur،</string>

    <string name="more_help">
    <u> المزيد >> </u>
  </string>

</resources>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MvcApplication13.CustomFilters;

namespace MvcApplication13
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
           // filters.Add(new ElmahHandledErrorLoggerFilter());
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            //routes.IgnoreRoute("elmah.axd");
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            //GlobalFilters.Filters.Add(new HandleErrorAttribute());
        }
    }
}


text:
//
//  SDLChoiceSet.h
//  SmartDeviceLink
//
//  Created by Joel Fischer on 5/21/18.
//  Copyright © 2018 smartdevicelink. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol SDLChoiceSetDelegate;
@class SDLChoiceCell;
@class SDLTTSChunk;
@class SDLVRHelpItem;

NS_ASSUME_NONNULL_BEGIN

/**
 Notifies the subscriber that the choice set should be cancelled.
 */
typedef void (^SDLChoiceSetCanceledHandler)(void);

/// The layout to use when a choice set is displayed
typedef NS_ENUM(NSUInteger, SDLChoiceSetLayout) {
    /// Menu items will be displayed in a list
    SDLChoiceSetLayoutList,

    /// Menu items will be displayed as a tiled list
    SDLChoiceSetLayoutTiles,
};

/**
 The choice set to be displayed to the user. Contains a list of selectable options.
 */
@interface SDLChoiceSet: NSObject

/**
 Set this to change the default timeout for all choice sets. If a timeout is not set on an individual choice set object (or if it is set to 0.0), then it will use this timeout instead. See `timeout` for more details. If this is not set by you, it will default to 10 seconds. The minimum is 5 seconds, the maximum is 100 seconds. If this is set below the minimum, it will be capped at 5 seconds. If this is set above the maximum, it will be capped at 100 seconds.
 */
@property (class, assign, nonatomic) NSTimeInterval defaultTimeout;

/**
 Set this to change the default layout for all choice sets. If a layout is not set on an individual choice set object, then it will use this layout instead. See `layout` for more details. If this is not set by you, it will default to `SDLChoiceSetLayoutList`.
 */
@property (class, assign, nonatomic) SDLChoiceSetLayout defaultLayout;

/**
 Maps to PerformInteraction.initialText. The title of the choice set, and/or the initial text on a keyboard prompt.
 */
@property (copy, nonatomic) NSString *title;

/**
 Maps to PerformInteraction.initialPrompt. The initial prompt spoken to the user at the start of an interaction.
 */
@property (copy, nonatomic, nullable) NSArray<SDLTTSChunk *> *initialPrompt;

/**
 Maps to PerformInteraction.interactionLayout. Whether the presented choices are arranged as a set of tiles or a list.
 */
@property (assign, nonatomic) SDLChoiceSetLayout layout;

/**
 Maps to PerformInteraction.timeout. Timeout in seconds. Defaults to 0, which will use `defaultTimeout`. If this is set below the minimum, it will be capped at 5 seconds. Minimum 5 seconds, maximum 100 seconds. If this is set above the maximum, it will be capped at 100 seconds. Defaults to 0.

 @note This applies only to a manual selection (not a voice selection, which has its timeout handled by the system).
 */
@property (assign, nonatomic) NSTimeInterval timeout;

/**
 Maps to PerformInteraction.timeoutPrompt. This text is spoken when a VR interaction times out. If this set is presented in a manual (non-voice) only interaction, this will be ignored.
 */
@property (copy, nonatomic, nullable) NSArray<SDLTTSChunk *> *timeoutPrompt;

/**
 Maps to PerformInteraction.helpPrompt. This is the spoken string when a user speaks "help" when the interaction is occurring.
 */
@property (copy, nonatomic, nullable) NSArray<SDLTTSChunk *> *helpPrompt;

/**
 Maps to PerformInteraction.vrHelp. This is a list of help text presented to the user when they are in a voice recognition interaction from your choice set of options. If this set is presented in a touch only interaction, this will be ignored.

 @note that while SDLVRHelpItem's position will be automatically set based on position in the array, the image will need to uploaded by you before use using SDLFileManager.
 */
@property (copy, nonatomic, nullable) NSArray<SDLVRHelpItem *> *helpList;

/**
 The delegate of this choice set, called when the user interacts with it.
 */
@property (weak, nonatomic) id<SDLChoiceSetDelegate> delegate;

/**
 The choices to be displayed to the user within this choice set. These choices could match those already preloaded via `SDLScreenManager preloadChoices:withCompletionHandler:`.

 This is limited to 100 items. If you attempt to set more than 100 items, the set will not have any items (this array will be empty).
 */
@property (copy, nonatomic) NSArray<SDLChoiceCell *> *choices;

/// Initialize with a title, delegate, and choices. It will use the default timeout and layout, all other properties (such as prompts) will be `nil`.
///
/// WARNING: If you display multiple cells with the same `text` with the only uniquing property between cells being different `vrCommands` or a feature that is not displayed on the head unit (e.g. if the head unit doesn't display `secondaryArtwork` and that's the only uniquing property between two cells) then the cells may appear to be the same to the user in `Manual` mode. This only applies to RPC connections >= 7.1.0.
///
/// WARNING: On < 7.1.0 connections, the `text` cell will be automatically modified among cells that have the same `text` when they are preloaded, so they will always appear differently on-screen when they are displayed. `cell.uniqueText` will be created by appending ` (2)`, ` (3)`, etc.
- (instancetype)init;

/**
 Initialize with a title, delegate, and choices. It will use the default timeout and layout, all other properties (such as prompts) will be `nil`.

 WARNING: If you display multiple cells with the same `text` with the only uniquing property between cells being different `vrCommands` or a feature that is not displayed on the head unit (e.g. if the head unit doesn't display `secondaryArtwork` and that's the only uniquing property between two cells) then the cells may appear to be the same to the user in `Manual` mode. This only applies to RPC connections >= 7.1.0.

 WARNING: On < 7.1.0 connections, the `text` cell will be automatically modified among cells that have the same `text` when they are preloaded, so they will always appear differently on-screen when they are displayed. `cell.uniqueText` will be created by appending ` (2)`, ` (3)`, etc.

 @param title The choice set's title
 @param delegate The choice set delegate called after the user has interacted with your choice set
 @param choices The choices to be displayed to the user for interaction
 @return The choice set
 */
- (instancetype)initWithTitle:(NSString *)title delegate:(id<SDLChoiceSetDelegate>)delegate choices:(NSArray<SDLChoiceCell *> *)choices;

/**
 Initializer with all possible properties.

 WARNING: If you display multiple cells with the same `text` with the only uniquing property between cells being different `vrCommands` or a feature that is not displayed on the head unit (e.g. if the head unit doesn't display `secondaryArtwork` and that's the only uniquing property between two cells) then the cells may appear to be the same to the user in `Manual` mode. This only applies to RPC connections >= 7.1.0.

 WARNING: On < 7.1.0 connections, the `text` cell will be automatically modified among cells that have the same `text` when they are preloaded, so they will always appear differently on-screen when they are displayed. `cell.uniqueText` will be created by appending ` (2)`, ` (3)`, etc.

 @param title The choice set's title
 @param delegate The choice set delegate called after the user has interacted with your choice set
 @param layout The layout of choice options (Manual/touch only)
 @param timeout The timeout of a touch interaction in seconds (Manual/touch only)
 @param initialPrompt A voice prompt spoken to the user when this set is displayed
 @param timeoutPrompt A voice prompt spoken to the user when the set times out (Voice only)
 @param helpPrompt A voice prompt spoken to the user when the user asks for "help"
 @param helpList A table list of text and images shown to the user during a voice recognition session for this choice set (Voice only)
 @param choices The list of choices presented to the user either as a manual/touch interaction or via the user's voice
 @return The choice set
 */
- (instancetype)initWithTitle:(NSString *)title delegate:(id<SDLChoiceSetDelegate>)delegate layout:(SDLChoiceSetLayout)layout timeout:(NSTimeInterval)timeout initialPromptString:(nullable NSString *)initialPrompt timeoutPromptString:(nullable NSString *)timeoutPrompt helpPromptString:(nullable NSString *)helpPrompt vrHelpList:(nullable NSArray<SDLVRHelpItem *> *)helpList choices:(NSArray<SDLChoiceCell *> *)choices;

/**
 Initializer with all possible properties.

 WARNING: If you display multiple cells with the same `text` with the only uniquing property between cells being different `vrCommands` or a feature that is not displayed on the head unit (e.g. if the head unit doesn't display `secondaryArtwork` and that's the only uniquing property between two cells) then the cells may appear to be the same to the user in `Manual` mode. This only applies to RPC connections >= 7.1.0.

 WARNING: On < 7.1.0 connections, the `text` cell will be automatically modified among cells that have the same `text` when they are preloaded, so they will always appear differently on-screen when they are displayed. `cell.uniqueText` will be created by appending ` (2)`, ` (3)`, etc.

 @param title The choice set's title
 @param delegate The choice set delegate called after the user has interacted with your choice set
 @param layout The layout of choice options (Manual/touch only)
 @param timeout The timeout of a touch interaction in seconds (Manual/touch only)
 @param initialPrompt A voice prompt spoken to the user when this set is displayed
 @param timeoutPrompt A voice prompt spoken to the user when the set times out (Voice only)
 @param helpPrompt A voice prompt spoken to the user when the user asks for "help"
 @param helpList A table list of text and images shown to the user during a voice recognition session for this choice set (Voice only)
 @param choices The list of choices presented to the user either as a manual/touch interaction or via the user's voice
 @return The choice set
 */
- (instancetype)initWithTitle:(NSString *)title delegate:(id<SDLChoiceSetDelegate>)delegate layout:(SDLChoiceSetLayout)layout timeout:(NSTimeInterval)timeout initialPrompt:(nullable NSArray<SDLTTSChunk *> *)initialPrompt timeoutPrompt:(nullable NSArray<SDLTTSChunk *> *)timeoutPrompt helpPrompt:(nullable NSArray<SDLTTSChunk *> *)helpPrompt vrHelpList:(nullable NSArray<SDLVRHelpItem *> *)helpList choices:(NSArray<SDLChoiceCell *> *)choices;

/**
 Cancels the choice set. If the choice set has not yet been sent to Core, it will not be sent. If the choice set is already presented on Core, the choice set will be immediately dismissed. Canceling an already presented choice set will only work if connected to Core versions 6.0+. On older versions of Core, the choice set will not be dismissed.
 */
- (void)cancel;

@end

NS_ASSUME_NONNULL_END


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/sliceGrey"
    android:background="@android:color/darker_gray">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/type"
        android:paddingRight="10dp"
        android:text="Medium text" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/descriprion"
        android:paddingRight="10dp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/time" />

</LinearLayout>


text:
body {
    background-color: #050b38;
    color: rgba(0, 0, 0, 0.87);
    font-family: sans-serif;
    margin: 0;
}

header {
    padding: 0.5em 1em;
}

section,
h1 {
    max-width: 1170px;
    margin-left: auto;
    margin-right: auto;
}

a {
    list-style: none;
    writing-mode: vertical-lr;
    position: relative;
    z-index: 2;
    display: inline-block;
    margin-bottom:20px;
    margin-top:20px;
    text-align: center;
    transform: rotate(180deg);
    font-size: 14px;
    color: white;
    text-transform: uppercase;
    font-weight: 400;
    letter-spacing: 20px;
}

h1 {
    display: block;
    font-size: 34px;
    line-height: 34px;
    color: rgba(255, 255, 255, 0.87);
}

.dark-blue-background {
    background-color: #191818;
}

.poiret-font{
    font-family: 'Poiret One', cursive;
}

.create {
    position: absolute;
    right: 10px;
}

.tabs {
    display: block;
    border-right: 1px solid #807979;
    border-top: 1px solid #807979;
    border-bottom: 1px solid #807979;
    margin: 0;
    padding-left: 0;
    list-style: none;
    text-align: center;
}

.tabs > li {
  position: relative;
  display: block;
  width:31px;
  float: left;
}

.tabs > li > a {
  position: relative;
  display: block;
  padding: 15px;
  color: white;
  line-height: 31px;
  border: 1px solid transparent;
  border-radius: 4px 4px 4px 4px;
  text-align: center;
  cursor:pointer;
}

.tabs > li > a:hover,
.tabs > li > a:focus {
  text-decoration: none;
  background-color: #717171;
  text-align: center;
  cursor:pointer;
}

.tabs > li > a:hover {
  border-color: #292929 #292929 #292929;
}
.tabs > li.active > a,
.tabs > li.active > a:hover,
.tabs > li.active > a:focus {
  color: black;
  background-color: #a3a3a9;
  border: 1px solid #ddd;
  cursor:pointer;
  text-align: center;

}

.box::-webkit-scrollbar {
    width: 1em;
}

.box::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px black;
}

.box::-webkit-scrollbar-thumb {
  background-color: #807979;
  outline: 1px solid #807979;
}

.separator-container {
  text-align: center;
  position: relative;
}
.separator-container .separator {
  color: white;
  margin: 0 auto 1em;
}
.separator-container .separator.line-separator:before, .separator-container .separator.line-separator:after {
  display: block;
  width: 40%;
  content: " ";
  margin-top: 14px;
  border: 1px solid white;
}
.separator-container .separator.line-separator:before {
  float: left;
}
.separator-container .separator.line-separator:after {
  float: right;
}

.no-border{
    border: 0px;
}

.margin {
    margin: 50px;
}

.margin-small {
    margin: 10px;
}

.info {
    color: white;
    position: absolute;
    right: 10px;
    margin: 10px;
}

.left {
    position: absolute;
    left: 10px;
}

.grey-background {
    color: white;
    background-color: #292929;
}

.pacifico {
    font-family: 'Pacifico', cursive;
    color: #C0C0C0;
}

.incomplete-item {
    display: inline-block;
    padding-left: 10px;
    padding-right: 10px;
    right: 10px;
    font-size: 20px;
    font-family: 'Poiret One', cursive;
}

.complete-item {
    display: inline-block;
    text-decoration: line-through;
    font-style: italic;
    padding-left: 10px;
    font-size: 20px;
    font-family: 'Poiret One', cursive;
}

.item-element {
    position: relative;
    display: block;
    padding: 10px 15px;
    margin-bottom: -1px;
    border: 1px solid black;
    margin:10px;
}

input:focus {
    outline:none;
}

.create-element {
    position: relative;
    display: block;
    padding: 10px 15px;
    margin-bottom: -1px;
    margin-top: 50px;
    border: 2px solid black;
}

.comment-element {
    position: relative;
    display: block;
    padding: 10px;
    margin-bottom: -1px;
    margin-top: 10px;
    border: 1px solid black;
}

.right-box {
    position: absolute;
    right: 5px;
    display: inline-block;
}

.button-header {
    display: inline-block;
    color: white;
    padding: 15px;
    margin: 10px;
    text-align: center;
    font-size: 12px;
    color: white;
    text-transform: uppercase;
    font-weight: 200;
    letter-spacing: 5px;
    cursor:pointer;
}

.create-text {
    color: white;
    padding: 15px;
    text-align: center;
    font-size: 12px;
    color: white;
    text-transform: uppercase;
    font-weight: 200;
    letter-spacing: 5px;
    width: 50%;
    top: 20%;
    margin: 0 auto;
    margin-top: 50px;
}

.button-header:hover {
  border-bottom: 1px solid #ddd;
}

.footer {
    position: absolute;
    bottom: 0px;
    z-index: 10;
    text-align: center;
    color: white;
    padding: 15px;
    margin: 10px;
    text-align: center;
    font-size: 12px;
    color: white;
    text-transform: uppercase;
    font-weight: 200;
    letter-spacing: 5px;
    right: 50%;
    width: 300px;
    margin-left: -150px;
}

.box {
    position: absolute;
    left: 50%;
    top: 550px;
    height: 500px;
    margin-top: -250px;
    overflow-y: auto;
    width: 800px;
    margin-left: -400px;
    border: 1px solid black;
}

.create-box {
    position: absolute;
    left: 50%;
    margin-top: 0px;
    overflow-y: auto;
    width: 900px;
    margin-left: -450px;
}


text:
<?php

namespace WindowsAzure\MediaServices\Models;

use WindowsAzure\Common\Internal\Validate;

/**
 * Represents Encoding ComplexType object used in media services.
 *
 * @category  Microsoft
 *
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 *
 * @version   Release: 0.4.3_2016-05
 *
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ChannelEncoding
{
    /**
     * Encoding AdMarkerSource.
     *
     * @var string
     */
    private $_adMarkerSource;

    /**
     * Encoding IgnoreCea708ClosedCaptions.
     *
     * @var bool
     */
    private $_ignoreCea708ClosedCaptions = false;

    /**
     * Encoding VideoStreams.
     *
     * @var mixing
     */
    private $_videoStreams;

    /**
     * Encoding AudioStreams.
     *
     * @var array
     */
    private $_audioStreams;

    /**
     * Encoding SystemPreset.
     *
     * @var string
     */
    private $_systemPreset;

    /**
     * Create Encoding from array.
     *
     * @param array $options Array containing values for object properties
     *
     * @return Encoding
     */
    public static function createFromOptions($options)
    {
        $operation = new self();
        $operation->fromArray($options);

        return $operation;
    }

    /**
     * Create Encoding.
     */
    public function __construct()
    {
        $this->_videoStreams = array();
        $this->_audioStreams = array();
    }

    /**
     * Fill Encoding from array.
     *
     * @param array $options Array containing values for object properties
     */
    public function fromArray($options)
    {
        if (isset($options['AdMarkerSource'])) {
            Validate::isString($options['AdMarkerSource'], 'options[AdMarkerSource]');
            $this->_adMarkerSource = $options['AdMarkerSource'];
        }

	    if (isset($options['IgnoreCea708ClosedCaptions'])) {
            Validate::isString($options['IgnoreCea708ClosedCaptions'], 'options[IgnoreCea708ClosedCaptions]');
            $this->_ignoreCea708ClosedCaptions = (bool) $options['IgnoreCea708ClosedCaptions'];
        }

        if (!empty($options['VideoStreams'])) {
            Validate::isArray($options['VideoStreams'], 'options[VideoStreams]');
            foreach ($options['VideoStreams'] as $videoStream) {
                $this->_videoStreams[] = VideoStream::createFromOptions($videoStream);
            }
        }

        if (!empty($options['AudioStreams'])) {
            Validate::isArray($options['AudioStreams'], 'options[AudioStreams]');
            foreach ($options['AudioStreams'] as $audioStream) {
                $this->_audioStreams[] = AudioStream::createFromOptions($audioStream);
            }
        }

        if (isset($options['SystemPreset'])) {
            Validate::isString($options['SystemPreset'], 'options[SystemPreset]');
            $this->_systemPreset = $options['SystemPreset'];
        }
    }

    /**
     * Get the Encoding AdMarkerSource.
     *
     * @return string
     */
    public function getAdMarkerSource()
    {
        return $this->_adMarkerSource;
    }

    /**
     * Set the Encoding AdMarkerSource.
     *
     * @param string $value Encoding AdMarkerSource.
     */
    public function setAdMarkerSource($value)
    {
        $this->_adMarkerSource = $value;
    }

    /**
     * Get the Encoding IgnoreCea708ClosedCaptions.
     *
     * @return string
     */
    public function getIgnoreCea708ClosedCaptions()
    {
        return $this->_ignoreCea708ClosedCaptions;
    }

    /**
     * Set the Encoding IgnoreCea708ClosedCaptions.
     *
     * @param string $value Encoding IgnoreCea708ClosedCaptions.
     */
    public function setIgnoreCea708ClosedCaptions($value)
    {
        $this->_ignoreCea708ClosedCaptions = $value;
    }

    /**
     * Get the Encoding VideoStream.
     *
     * @return mixing
     */
    public function getVideoStreams()
    {
        return $this->_videoStreams;
    }

    /**
     * Set the Encoding VideoStreams.
     *
     * @param mixing $value Encoding VideoStreams.
     */
    public function setVideoStreams($value)
    {
        $this->_videoStreams = $value;
    }

    /**
     * Get the Encoding AudioStreams.
     *
     * @return mixing
     */
    public function getAudioStreams()
    {
        return $this->_audioStreams;
    }

    /**
     * Set the Encoding AudioStreams.
     *
     * @param mixing $value Encoding AudioStreams.
     */
    public function setAudioStreams($value)
    {
        $this->_audioStreams = $value;
    }

    /**
     * Get the Encoding SystemPreset.
     *
     * @return string
     */
    public function getSystemPreset()
    {
        return $this->_systemPreset;
    }

    /**
     * Set the Encoding SystemPreset.
     *
     * @param string $value Encoding SystemPreset.
     */
    public function setSystemPreset($value)
    {
        $this->_systemPreset = $value;
    }
}


text:
package org.elasticsearch.versioning;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.test.ESIntegTestCase;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;

/**
 *
 */
public class ConcurrentDocumentOperationIT extends ESIntegTestCase {
    public void testConcurrentOperationOnSameDoc() throws Exception {
        logger.info("--> create an index with 1 shard and max replicas based on nodes");
        assertAcked(prepareCreate("test")
                .setSettings(settingsBuilder().put(indexSettings()).put("index.number_of_shards", 1)));

        logger.info("execute concurrent updates on the same doc");
        int numberOfUpdates = 100;
        final AtomicReference<Throwable> failure = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(numberOfUpdates);
        for (int i = 0; i < numberOfUpdates; i++) {
            client().prepareIndex("test", "type1", "1").setSource("field1", i).execute(new ActionListener<IndexResponse>() {
                @Override
                public void onResponse(IndexResponse response) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable e) {
                    e.printStackTrace();
                    failure.set(e);
                    latch.countDown();
                }
            });
        }

        latch.await();

        assertThat(failure.get(), nullValue());

        client().admin().indices().prepareRefresh().execute().actionGet();

        logger.info("done indexing, check all have the same field value");
        Map masterSource = client().prepareGet("test", "type1", "1").execute().actionGet().getSourceAsMap();
        for (int i = 0; i < (cluster().size() * 5); i++) {
            assertThat(client().prepareGet("test", "type1", "1").execute().actionGet().getSourceAsMap(), equalTo(masterSource));
        }
    }
}