text:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace AppLib.WPF.Controls
{
    public partial class EditableSlider : UserControl
    {

        /// <summary>
        /// Minimum value property
        /// </summary>
        public static DependencyProperty MinimumProperty = DependencyProperty.Register("Minimum", typeof(double), typeof(EditableSlider), new PropertyMetadata(0.0d, Rerender));

        /// <summary>
        /// Maximum value property
        /// </summary>
        public static DependencyProperty MaximumProperty = DependencyProperty.Register("Maximum", typeof(double), typeof(EditableSlider), new PropertyMetadata(10.0d, Rerender));

        /// <summary>
        /// Value property
        /// </summary>
        public static DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(EditableSlider), new PropertyMetadata(3.0d, RerenderText));

        /// <summary>
        /// Default value property
        /// </summary>
        public static DependencyProperty DefaultValueProperty = DependencyProperty.Register("DefaultValue", typeof(double), typeof(EditableSlider), new PropertyMetadata(3.0d));

        private static void Rerender(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var slider = (EditableSlider)d;
            if (slider.Value < slider.Minimum) slider.Value = slider.Minimum;
            if (slider.Value > slider.Maximum) slider.Value = slider.Maximum;
            slider.UpdateView();
        }

        private static void RerenderText(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var slider = (EditableSlider)d;
            slider.UpdateView();
            slider.UpdateText();
        }

        /// <summary>
        /// Event Handler for value Changed event
        /// </summary>
        public event RoutedEventHandler ValueChanged;

        //private bool _editOnClickSetting;

        /// <summary>
        /// True if dragging via mouse, false otherwise
        /// </summary>
        private bool _isDragging;

        /// <summary>
        /// True if the textbox is enabled and being edited, false otherwise
        /// </summary>
        private bool _isInEditMode;

        /// <summary>
        /// True if the user started dragging, false otherwise
        /// </summary>
        //private bool _hasBeenDragging;

        private string _displayFormat = "0.00";

        private bool _usingCustomDisplayFormat;

        bool _isInitialized;

        private bool _isOverEditValueButton;

        /// <summary>
        /// Creates a new instance of EditableSlider
        /// </summary>
        public EditableSlider()
        {
            InitializeComponent();
            _isInitialized = true;
            this.SizeChanged += EditableSlider_SizeChanged;
        }

        void EditableSlider_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (!_isInitialized) return;
            UpdateView();
        }

        /// <summary>
        /// Minimal Editor value
        /// </summary>
        public double Minimum
        {
            get { return (double)GetValue(MinimumProperty); }
            set { SetValue(MinimumProperty, value); }
        }

        /// <summary>
        /// Maximal Editor value
        /// </summary>
        public double Maximum
        {
            get { return (double)GetValue(MaximumProperty); }
            set { SetValue(MaximumProperty, value); }
        }

        /// <summary>
        /// Current Editor value
        /// </summary>
        public double Value
        {
            get { return (double)GetValue(ValueProperty); }
            set
            {
                SetValue(ValueProperty, value);
                ValueChanged?.Invoke(this, new RoutedEventArgs());
            }
        }

        /// <summary>
        /// Same as Value = val, but does not fire the ValueChanged event
        /// </summary>
        public void SetValue(double val)
        {
            SetValue(ValueProperty, val);
            UpdateView();
            UpdateText();
        }

        /// <summary>
        /// Default Editor value
        /// </summary>
        public double DefaultValue
        {
            get { return (double)GetValue(DefaultValueProperty); }
            set { SetValue(DefaultValueProperty, value); }
        }

        /// <summary>
        /// Display format string
        /// </summary>
        public string DisplayFormat
        {
            get { return _displayFormat; }
            set
            {
                _usingCustomDisplayFormat = true;
                if (_displayFormat == value) return;
                _displayFormat = value;
                UpdateText();
            }
        }

        private void rectBase_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            rectBase.CaptureMouse();
            _isDragging = true;
            //_hasBeenDragging = false;
        }

        private void rectBase_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            rectBase.ReleaseMouseCapture();
            ReleaseMouseCapture();
            /*if (_editOnClickSetting)
            {
                _isDragging = false;
                if (!_hasBeenDragging) EnterEditMode();
            }
            else
            {*/
                if (_isDragging)
                {
                    double x = e.GetPosition(this.rectBase).X;
                    //if (x < 0) x = CorrectGetPosition(rectBase).X;
                    UpdatePercent(x);
                }
            //}
            _isDragging = false;
        }

        /*private Point CorrectGetPosition(Visual relativeTo)
        {
            return relativeTo.PointFromScreen(new Point(System.Windows.Forms.Control.MousePosition.X, System.Windows.Forms.Control.MousePosition.Y));
        }*/

        private void rectBase_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDragging)
            {
                double x = e.GetPosition(this.rectBase).X;
                //if (x < 0) x = CorrectGetPosition(rectBase).X;
                UpdatePercent(x);
                //_hasBeenDragging = true;
            }
        }

        private void UpdatePercent(double xPos)
        {
            if (xPos < 0) xPos = 0;
            if (xPos > rectBase.ActualWidth) xPos = rectBase.ActualWidth;
            rectPercent.Width = xPos;
            double valuePercent = xPos / rectBase.ActualWidth;
            Value = (Maximum - Minimum) * valuePercent + Minimum;
        }

        private void ChangeDisplayFormatIfNeeded(string newFormat)
        {
            if (_usingCustomDisplayFormat) return;
            if (_displayFormat == newFormat) return;
            _displayFormat = newFormat;
            UpdateText();
        }

        private void UpdateView()
        {
            double valuePercent = (Value - Minimum) / (Maximum - Minimum);
            rectPercent.Width = valuePercent < 0 ? 0 : rectBase.ActualWidth * valuePercent;

            double range = Math.Abs(Maximum - Minimum);
            if (range >= 40) ChangeDisplayFormatIfNeeded("0");
            else if (range >= 10) ChangeDisplayFormatIfNeeded("0.0");
            else if (range >= 0.5) ChangeDisplayFormatIfNeeded("0.00");
            else ChangeDisplayFormatIfNeeded("0.0000");
        }

        private void UpdateText()
        {
            textValue.Text = Value.ToString(_displayFormat);
            textValueEdit.Text = textValue.Text;
        }

        private void EnterEditMode()
        {
            _isInEditMode = true;
            textValueEdit.Visibility = Visibility.Visible;
            textValue.Visibility = Visibility.Collapsed;
            textValueEdit.Focus();
            textValueEdit.SelectAll();
        }

        private void ExitEditMode()
        {
            _isInEditMode = false;
            textValueEdit.Visibility = Visibility.Collapsed;
            textValue.Visibility = Visibility.Visible;
            double result;
            if (double.TryParse(textValueEdit.Text, out result))
            {
                if (result < Minimum) result = Minimum;
                if (result > Maximum) result = Maximum;
                Value = result;
            }
            else UpdateText();
        }

        private void textValueEdit_LostFocus(object sender, RoutedEventArgs e)
        {
            if (!_isOverEditValueButton) ExitEditMode();
        }

        private void textValueEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter) ExitEditMode();
        }

        private void btnEditValue_Click(object sender, RoutedEventArgs e)
        {
            if (_isInEditMode) ExitEditMode();
            else EnterEditMode();
        }

        private void btnEditValue_MouseEnter(object sender, MouseEventArgs e)
        {
            _isOverEditValueButton = true;
        }

        private void btnEditValue_MouseLeave(object sender, MouseEventArgs e)
        {
            _isOverEditValueButton = false;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            double value = Value;
            Value = value;
        }

        private void btnResetValue_Click(object sender, RoutedEventArgs e)
        {
            Value = DefaultValue;
        }

        private void rootGrid_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            bool value = Convert.ToBoolean(e.NewValue);
            if (!value) VisualStateManager.GoToState(this, "Disabled", false);
            else VisualStateManager.GoToState(this, "Enabled", false);
        }
    }
}


text:
if [ $# -lt 3 ]; then
  echo "usage: $0 <db-name> <db-user> <db-pass> [db-host] [wp-version]"
  exit 1
fi

DB_NAME=$1
DB_USER=$2
DB_PASS=$3
DB_HOST=${4-localhost}
WP_VERSION=${5-latest}

MY_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

WP_CORE_DIR="$(dirname "$MY_DIR")"/wordpress/

create_folder() {
  rm -rf $WP_CORE_DIR
  mkdir -p $WP_CORE_DIR
}

install_wpcli() {
  cd $WP_CORE_DIR && curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
}

drop_database() {
  RESULT=`mysqlshow --user=$DB_USER --password=$DB_PASS $DB_NAME| grep -v Wildcard | grep -o $DB_NAME`

  if [ "$RESULT" == "$DB_NAME" ];
  then
    if [$DB_PASS == '']
    then
      mysqladmin -h $DB_HOST -u $DB_USER drop $DB_NAME
    else
      mysqladmin -h $DB_HOST -u $DB_USER -p $DB_PASS drop $DB_NAME
    fi
  fi
}

install_wp() {
  php $WP_CORE_DIR/wp-cli.phar core download --version=$WP_VERSION
  php $WP_CORE_DIR/wp-cli.phar core config --dbname="$DB_NAME" --dbuser="$DB_USER" --dbpass="$DB_PASS" --dbhost="$DB_HOST"
  php $WP_CORE_DIR/wp-cli.phar db create
  php $WP_CORE_DIR/wp-cli.phar core install --url='example.com' --title='Test Wordpress' --admin_user='admin' --admin_password='bestpasswordever' --admin_email='info@example.com'
}

install_acf() {
  read -e -p "ACF5-PRO Path: " ACF_DIR

  ln -s $ACF_DIR $WP_CORE_DIR/wp-content/plugins
  php $WP_CORE_DIR/wp-cli.phar plugin activate acf5-pro
}

create_symlink_to_acf_wpcli() {
  # ToDo: Make path variable
  # read -e -p "ACF WP-CLI Path: " ACF_WPCLI_DIR

  ACF_WPCLI_DIR="$(dirname "$MY_DIR")"

  ln -s $ACF_WPCLI_DIR $WP_CORE_DIR/wp-content/plugins
  php $WP_CORE_DIR/wp-cli.phar plugin activate advanced-custom-fields-wpcli
}

create_symlink_to_mu_plugins() {
  ln -s $ACF_WPCLI_DIR/features/bootstrap/mu-plugins $WP_CORE_DIR/wp-content
}

create_folder
install_wpcli
drop_database
install_wp
install_acf
create_symlink_to_acf_wpcli
create_symlink_to_mu_plugins

redpajama_set_name: RedPajamaGithub


text:
"""Provides a class for managing pending tasks tables."""

# Built-in modules.
import os
import time
import sqlite3
# Project specific modules.
import git
import utils as u
from logger import Logger
from cache import TaskCache
from task import Task, labels
from partials import Partials

class PendingTasks(object):
    """Manages the creation, modification and status of pending tasks."""

    def __init__(self, path="/opt/tm/logs/", project_name=None):
        """Tasks manager constructor"""
        self.log = Logger(path, project_name)
        if not self._check_if_exists():
            self.create_table("NotStarted", "WorkingOn", "Completed")
        # Use this queue to save the most recent new, modified, on process or
        # completed tasks. These tasks should be saved in tuples along with
        # their corresponding table. The length of this queue should not be
        # greater than 10 tasks.
        self.recent_tasks = TaskCache(10)
        # Lets the application know whether there are partial commits left to
        # push to remote repository.
        self.partials_exist = Partials(path)

    def __contains__(self, task):
        return self._is_task_duplicate(task)

# --> Public methods.

# Table methods.
    def create_table(self, *tables):
        """Creates tables with the same attribute structure.
        Args:
            tables: list of names for tables.
        Returns:
            No data is returned.
        """
        for table_name in tables:
            if table_name.isalnum():
                db_connection = sqlite3.connect("tasks.db")
                cursor = db_connection.cursor()
                cursor.execute(
                    "CREATE TABLE IF NOT EXISTS " + table_name +
                    """
                    (completed TEXT,
                    started TEXT,
                    created_at TEXT,
                    modified TEXT,
                    depends_from TEXT,
                    priority INTEGER,
                    description TEXT,
                    identifier TEXT)
                    """
                )
                db_connection.commit()
                db_connection.close()
                self.log.add_entry("Table creation: OK.",
                                   "'{}' table successfully"
                                   " created.".format(table_name),
                                   time.strftime("%Y-%m-%d %H:%M:%S"))
            else:
                print("{} is not alphanumeric.".format(table_name))
                self.log.add_entry("Table creation: ERROR.",
                                   "{} is not"
                                   " alphanumeric.".format(table_name),
                                   time.strftime("%Y-%m-%d %H:%M:%S"))

    def drop_table(self, *tables):
        """Deletes specified tables."""
        for table_name in tables:
            if table_name.isalnum():
                db_connection = sqlite3.connect("tasks.db")
                cursor = db_connection.cursor()
                cursor.execute(
                    "DROP TABLE " + table_name
                )
                db_connection.commit()
                db_connection.close()
                self.log.add_entry("Table deletition: OK.",
                                   "'{}' table successfully"
                                   " deleted.".format(table_name),
                                   time.strftime("%Y-%m-%d %H:%M:%S"))
            else:
                print("{} is not alphanumeric.".format(table_name))
                self.log.add_entry("Table deletition: ERROR.",
                                   "{} is not"
                                   " alphanumeric.".format(table_name),
                                   time.strftime("%Y-%m-%d %H:%M:%S"))

    def add_task_into(self, table, task, moving_task=False):
        """Adds a given task to a given table."""
        success = False
        db_connection = sqlite3.connect("tasks.db")
        cursor = db_connection.cursor()
        if (task not in self) or moving_task:
            cursor.execute(
                "INSERT INTO " + table +
                " VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                (str(task.info["completed"]), str(task.info["started"]),
                 str(task.info["created_at"]), str(task.info["modified"]),
                 str(task.info["depends_from"]), task.info["priority"],
                 task.info["description"], task.info["identifier"])
            )
            success = True
        db_connection.commit()
        db_connection.close()
        return success
# Task methods.

    def create_task(self, identifier, description, depends_from, priority):
        """Creates a new pending task.
        Args:
            identifier: short string that uniquely identifies the task.
            description: string that contains a verbose explanation of the new
            task.
            depends_from: list that contains the task ids that should be first
            compeleted before.
            priority: associated integer value.
        Returns:
            No data is returned.
        """
        task = Task({
            "completed": None,
            "started": None,
            "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "modified": None,
            "depends_from": depends_from,
            "priority": priority,
            "description": description,
            "identifier": identifier
        }, "NotStarted")
        status = self.add_task_into(
            "NotStarted", task
        )
        if status:
            self.recent_tasks.push(task)
            self.log.add_entry("Task creation: OK.",
                               "Task with id {} successfully"
                               " created.".format(task.info["identifier"]),
                               time.strftime("%Y-%m-%d %H:%M:%S"))
            return task
        else:
            print("There were problems when adding the created task"
                  " to the 'NotStarted' table.")
            self.log.add_entry("Task creation: ERROR.",
                               "Task with id {} not added to 'NotStarted'"
                               " table.".format(task.info["identifier"]),
                               time.strftime("%Y-%m-%d %H:%M:%S"))
            return None

    def start_task(self, identifier):
        """Sets a task as started, after checking dependencies.
        Args:
            identifier: string that uniquely identifies the task.
        Returns:
            - If the task was correctly added to the 'WorkingOn' table
            the recently started task is returned.
            - Instead, if the task depends from previous uncompleted tasks
            an informational message is returned.
        """
        task = self._get_task(identifier, "NotStarted")
        if task:
            started_task_info = dict(zip(labels, task[0]))
            depends_from = u.list_from_string(
                started_task_info["depends_from"])
            if not depends_from:
                started_task_info["started"] = time.strftime("%Y-%m-%d "
                                                             "%H:%M:%S")
                started_task = Task(started_task_info, "WorkingOn")
                status = self.add_task_into("WorkingOn", started_task, True)
                self.delete_task(identifier)
                print("Successfully labeled task as started.")
                git.branch(started_task.info["identifier"])
                self.log.add_entry("Created temp branch: OK", "Successfully"
                                   " created temp branch.",
                                   time.strftime("%Y-%m-%d %H:%M:%S"))
                if status:
                    if started_task in self.recent_tasks:
                        self.recent_tasks.update(started_task, "WorkingOn")
                        print("Task updated in cache.")
                        self.log.add_entry("Updated in Cache after start: OK.",
                                           "Task with id {} successfully"
                                           " updated in cache.".format(
                                               started_task.info["identifier"]
                                           ),
                                           time.strftime("%Y-%m-%d %H:%M:%S"))
                    else:
                        self.recent_tasks.push(started_task)
                        print("Task added to cache.")
                        self.log.add_entry("Add to Cache after start: OK.",
                                           "Task with id {} successfully"
                                           " added to cache.".format(
                                               started_task.info["identifier"]
                                           ),
                                           time.strftime("%Y-%m-%d %H:%M:%S"))
                    return started_task
                else:
                    print("There were problems when adding the started task"
                          " to the 'WorkingOn' table.")
                    self.log.add_entry("Label task as started: ERROR.",
                                       "Task with id {} could not be added to"
                                       " the 'WorkingOn' table".format(
                                           started_task.info["identifier"]),
                                       time.strftime("%Y-%m-%d %H:%M:%S"))
            else:
                incomplete_tasks = self._meets_dependencies(depends_from)
                msg = ("The current task ('{}') depends from ".format(
                    started_task_info["identifier"]))
                if len(incomplete_tasks) == 1:
                    msg += ("task '{}', which has to be completed before"
                            " starting this task.".format(incomplete_tasks[0]))
                else:
                    msg += ("tasks {}. Please complete them "
                            "first.".format(incomplete_tasks))
                    msg = u.replace_last_comma(msg)
                chars_to_remove = ["[", "]"]
                for char in chars_to_remove:
                    msg = msg.replace(char, "")
                return msg
        else:
            print("There is no task with that identifier waiting to be"
                  " started.")

    def update_task(self, identifier, **update_values):
        """Updates task information, no matter the table the task is in.
        Args:
            identifier: string that uniquely identifies the task.
            update_values: key-value arguments of task information to update.
        Returns:
            No data is returned.
        """
        table = self._get_table(identifier)
        if table:
            task = self._get_task(identifier, table)
            modified_task_info = dict(zip(labels, task[0]))
            for key, value in update_values.items():
                    modified_task_info[key] = value
            modified_task_info["modified"] = time.strftime("%Y-%m-%d %H:%M:%S")
            modified_task = Task(modified_task_info, table)
            db_connection = sqlite3.connect("tasks.db")
            cursor = db_connection.cursor()
            cursor.execute(
                "UPDATE " + table +
                """
                SET completed=?, started=?, created_at=?, modified=?,
                depends_from=?, priority=?, description=?, identifier=?
                WHERE identifier=?
                """,
                (modified_task.info["completed"],
                 modified_task.info["started"],
                 modified_task.info["created_at"],
                 modified_task.info["modified"],
                 str(modified_task.info["depends_from"]),
                 modified_task.info["priority"],
                 modified_task.info["description"],
                 modified_task.info["identifier"],
                 modified_task.info["identifier"])
            )
            db_connection.commit()
            db_connection.close()
            if modified_task in self.recent_tasks:
                self.recent_tasks.update(modified_task)
                print("Information updated.")
                self.log.add_entry("Updated in Cache: OK.",
                                   "Task with id {} successfully"
                                   " updated in cache.".format(
                                       modified_task.info["identifier"]),
                                   time.strftime("%Y-%m-%d %H:%M:%S"))
            else:
                self.recent_tasks.push(modified_task)
                print("Task added to cache.")
                self.log.add_entry("Add to Cache: OK.",
                                   "Task with id {} successfully"
                                   " added to cache.".format(
                                       modified_task.info["identifier"]),
                                   time.strftime("%Y-%m-%d %H:%M:%S"))
        else:
            print("The given identifier is not present in any table.")

    def delete_task(self, identifier):
        """Deletes a task in any table.
        Args:
            identifier: string that uniquely identifies the task.
        Returns:
            If the task with the given identifier exists in the cache
            it is returned after its deletition.
        """
        table = self._get_table(identifier)
        if identifier and table:
            try:
                db_connection = sqlite3.connect("tasks.db")
                cursor = db_connection.cursor()
                cursor.execute(
                    "DELETE FROM " + table + " WHERE identifier=?",
                    (identifier,)
                )
                db_connection.commit()
                db_connection.close()
                self.log.add_entry("Task deleted: OK.",
                                   "Task with id {} successfully"
                                   " deleted from '{}'.".format(
                                       identifier, table
                                   ),
                                   time.strftime("%Y-%m-%d %H:%M:%S"))
                return self.recent_tasks.pop((identifier, table))
            except sqlite3.OperationalError as detail:
                print("Table name contains non-alphanumeric characters.")
                self.log.add_entry("Task deleted: ERROR",
                                   "Table name contains non-alphanumeric"
                                   " characters. " + detail,
                                   time.strftime("%Y-%m-%d %H:%M:%S"))
        else:
            print("Cant delete the desired task. Please, verify if the given"
                  " 'identifier' is correctly spelled.")

    def completed_task(self, identifier, partials=False, branch="master"):
        """Labels a task as completed.
        Args:
            identifier: string that uniquely identifies the task.
            partials: indicates if local commits exist.
            branch: remote branch to push to.
        Returns:
            The recently labeled task is returned.
        """
        task = self._get_task(identifier, "WorkingOn")
        if task:
            completed_task_info = dict(zip(labels, task[0]))
            completed_task_info["completed"] = time.strftime(
                "%Y-%m-%d %H:%M:%S")
            completed_task = Task(completed_task_info, "Completed")
            status = self.add_task_into("Completed", completed_task, True)
            self.delete_task(identifier)
            git.make(
                completed_task.info["description"],
                "origin",
                completed_task.info["identifier"],
                partials
            )
            self.log.add_entry("Pushed to branch: OK", "Successfully pushed"
                               " changes to branch.",
                               time.strftime("%Y-%m-%d %H:%M:%S"))
            git.merge(completed_task.info["identifier"], branch)
            self.partials_exist = False
            self.log.add_entry("Merged with {}: OK".format(branch),
                               "Successfully merged feature branch with "
                               "{}.".format(branch),
                               time.strftime("%Y-%m-%d %H:%M:%S"))
            if status:
                if completed_task in self.recent_tasks:
                    self.recent_tasks.update(completed_task, "Completed")
                    print("Information updated.")
                    self.log.add_entry("Updated in Cache after complete: OK.",
                                       "Task with id {} successfully"
                                       " updated in cache.".format(
                                           completed_task.info["identifier"]),
                                       time.strftime("%Y-%m-%d %H:%M:%S"))
                else:
                    self.recent_tasks.push(completed_task)
                    print("Task added to cache.")
                    self.log.add_entry("Add to Cache after complete: OK.",
                                       "Task with id {} successfully"
                                       " added to cache.".format(
                                           completed_task.info["identifier"]),
                                       time.strftime("%Y-%m-%d %H:%M:%S"))
                return completed_task
            else:
                print("There were problems when adding the completed task"
                      " to the 'Completed' table.")
                self.log.add_entry("Label task as compelted: ERROR.",
                                   "Task with id {} could not be added to the"
                                   " 'Completed' table".format(
                                       completed_task.info["identifier"]),
                                   time.strftime("%Y-%m-%d %H:%M:%S"))
        else:
            print("There is no task with that identifier waiting to be"
                  " completed.")

    def partial(self, identifier, commit_message):
        """Creates a commit.
        Args:
            identifier: string that uniquely identifies the task.
            commit_message: partial changes commit message.
        Returns:
            No data is returned.
        """
        git.add_files(git._changed_files())
        git.status("")
        git.commit(identifier + " : " + commit_message)
        self.partials_exist = True
        self.log.add_entry("Partial added: OK",
                           "Added partial commit: {} : {}".format(
                                identifier, commit_message),
                           time.strftime("%Y-%m-%d %H:%M:%S"))

    def dump_db(self, name="dump.sql"):
        """Dumps the content of tasks.db into a file."""
        db_connection = sqlite3.connect('tasks.db')
        with open(name, 'w') as f:
            for line in db_connection.iterdump():
                f.write('%s\n' % line)
        db_connection.close()

    def generate_report(self, identifier):
        """Generates a report with the state of a given task.
        Args:
            identifier: string that uniquely identifies the task.
        Returns:
            No data is returned.
        """
        table = self._get_table(identifier)
        if identifier and table:
            task = self._get_task(identifier, table)
            if task:
                task_info = dict(zip(labels, task[0]))
                depends_from = u.list_from_string(task_info["depends_from"])
                incomplete_tasks = self._meets_dependencies(depends_from)
                msg = ("Task '{}' depends from ".format(
                    task_info["identifier"]))
                if len(incomplete_tasks) == 0:
                    msg += ("no other task(s).")
                elif len(incomplete_tasks) == 1:
                    msg += ("task '{}', which has to be completed before"
                            " starting this task.".format(incomplete_tasks[0]))
                else:
                    msg += ("tasks {}. Please complete them"
                            " first.".format(incomplete_tasks))
                    msg = u.replace_last_comma(msg)
                chars_to_remove = ["[", "]"]
                for char in chars_to_remove:
                    msg = msg.replace(char, "")
                print(
                    "Task #{0}:\n"
                    "- Description: {1}\n"
                    "- Priority: {2}\n"
                    "- Dependencies: {3}\n"
                    "- Created at: {4}\n"
                    "- Started at: {5}\n"
                    "- Completed at: {6}\n"
                    "- Modified at: {7}\n".format(
                        task_info["identifier"],
                        task_info["description"],
                        task_info["priority"],
                        msg,
                        task_info["created_at"],
                        task_info["started"],
                        task_info["completed"],
                        task_info["modified"]
                    )
                )

# --> Private methods.

    # TODO: Extend it to add multiple conditions.
    def _get_task(self, identifier, table):
        """Get entries that meet a certain condition.
        Args:
            pending
        Returns:
            Resulting rows of the query.
        """
        try:
            db_connection = sqlite3.connect("tasks.db")
            cursor = db_connection.cursor()
            cursor.execute(
                "SELECT * FROM " + table + " WHERE identifier=?",
                (identifier,)
            )
            entries = cursor.fetchall()
            db_connection.close()
            return entries
        except sqlite3.OperationalError as detail:
            print("Table name contains non-alphanumeric characters or"
                  " is non-existent.")
            self.log.add_entry("Get task: ERROR",
                               "Table name contains non-alphanumeric"
                               " characters or is non-existent. " + detail,
                               time.strftime("%Y-%m-%d %H:%M:%S"))

    def _is_task_duplicate(self, task):
        """Checks if a given task is already in any of the tables.
        Args:
            task: data to look for.
        Returns:
            Boolean value depending on whether the given data is present in
            the database.
        """
        if task in self.recent_tasks:
            print("A task with that identifier already exists in the"
                  " cache.")
            return True
        db_connection = sqlite3.connect("tasks.db")
        cursor = db_connection.cursor()
        cursor.execute(
            "SELECT name FROM sqlite_master WHERE type='table';")
        for table in cursor.fetchall():
            # Get the table name from tuple.
            table_name = table[0]
            matches = self._get_task(task.info["identifier"], table_name)
            if len(matches) > 0:
                db_connection.close()
                return True
        db_connection.close()
        return False

    def _get_table(self, identifier):
        """Returns the table that holds a certain task."""
        db_connection = sqlite3.connect("tasks.db")
        cursor = db_connection.cursor()
        cursor.execute(
            "SELECT name FROM sqlite_master WHERE type='table';")
        for table in cursor.fetchall():
            # Get the table name from tuple.
            table_name = table[0]
            matches = self._get_task(identifier, table_name)
            if len(matches) > 0:
                return table[0]
        return None

    def _meets_dependencies(self, dependencies):
        """Returns all incomplete tasks."""
        incomplete_tasks = []
        db_connection = sqlite3.connect("tasks.db")
        cursor = db_connection.cursor()
        for dependency in dependencies:
            cursor.execute(
                "SELECT * FROM Completed WHERE identifier=?",
                (dependency,))
            if not cursor.fetchall():
                incomplete_tasks.append(str(dependency))
        return incomplete_tasks

    def _check_if_exists(self):
        """Tests if the three tables exist."""
        db_connection = sqlite3.connect("tasks.db")
        cursor = db_connection.cursor()
        cursor.execute(
            "SELECT name FROM sqlite_master WHERE type='table';")
        existing_tables = cursor.fetchall()
        existing_tables = [table[0] for table in existing_tables]
        return all([table in existing_tables for table in [
            "NotStarted", "WorkingOn", "Completed"]])


text:
class Command
  attr_accessor :target, :params

  def initialize(target: nil, params: nil)
    @target = target
    @params = params

    post_initialize
  end

  def post_initialize; end

  def execute
    return InvalidCommand.new.execute unless valid?
    issue_command
  end

  def valid?
    true
  end
end


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/plugin_vm/plugin_vm_util.h"

#include <string>
#include <utility>

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/no_destructor.h"
#include "base/observer_list.h"
#include "base/strings/pattern.h"
#include "base/strings/string_util.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/ash/plugin_vm/plugin_vm_drive_image_download_service.h"
#include "chrome/browser/ash/plugin_vm/plugin_vm_features.h"
#include "chrome/browser/ash/plugin_vm/plugin_vm_installer_factory.h"
#include "chrome/browser/ash/plugin_vm/plugin_vm_manager.h"
#include "chrome/browser/ash/plugin_vm/plugin_vm_manager_factory.h"
#include "chrome/browser/ash/plugin_vm/plugin_vm_pref_names.h"
#include "chrome/browser/ash/settings/cros_settings.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/ash/shelf/chrome_shelf_controller.h"
#include "chromeos/ash/components/dbus/dlcservice/dlcservice_client.h"
#include "components/exo/shell_surface_util.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "net/base/url_util.h"

namespace plugin_vm {

const char kPitaDlc[] = "pita";
const char kPluginVmShelfAppId[] = "lgjpclljbbmphhnalkeplcmnjpfmmaek";
const char kPluginVmName[] = "PvmDefault";
const char kChromeOSBaseDirectoryDisplayText[] = "Network \u203a ChromeOS";

namespace {

static std::string& MutableFakeLicenseKey() {
  static base::NoDestructor<std::string> license_key;
  return *license_key;
}

base::RepeatingClosureList& GetFakeLicenseKeyListeners() {
  static base::NoDestructor<base::RepeatingClosureList> instance;
  return *instance;
}

}  // namespace

bool IsPluginVmRunning(Profile* profile) {
  return plugin_vm::PluginVmManagerFactory::GetForProfile(profile)
                 ->vm_state() ==
             vm_tools::plugin_dispatcher::VmState::VM_STATE_RUNNING &&
         ChromeShelfController::instance()->IsOpen(
             ash::ShelfID(kPluginVmShelfAppId));
}

bool IsPluginVmAppWindow(const aura::Window* window) {
  const std::string* app_id = exo::GetShellApplicationId(window);
  if (!app_id)
    return false;
  return *app_id == "org.chromium.plugin_vm_ui";
}

std::string GetPluginVmUserIdForProfile(const Profile* profile) {
  DCHECK(profile);
  return profile->GetPrefs()->GetString(plugin_vm::prefs::kPluginVmUserId);
}

void SetFakePluginVmPolicy(Profile* profile,
                           const std::string& image_url,
                           const std::string& image_hash,
                           const std::string& license_key) {
  DictionaryPrefUpdate update(profile->GetPrefs(),
                              plugin_vm::prefs::kPluginVmImage);
  base::Value* dict = update.Get();
  dict->SetStringPath(prefs::kPluginVmImageUrlKeyName, image_url);
  dict->SetStringPath(prefs::kPluginVmImageHashKeyName, image_hash);
  plugin_vm::PluginVmInstallerFactory::GetForProfile(profile)
      ->SkipLicenseCheckForTesting();  // IN-TEST
  MutableFakeLicenseKey() = license_key;
  GetFakeLicenseKeyListeners().Notify();
}

std::string GetFakeLicenseKey() {
  return MutableFakeLicenseKey();
}

bool FakeLicenseKeyIsSet() {
  return !MutableFakeLicenseKey().empty();
}

void RemoveDriveDownloadDirectoryIfExists() {
  auto log_file_deletion_if_failed = [](bool success) {
    if (!success) {
      LOG(ERROR) << "PluginVM failed to delete download directory";
    }
  };

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
      base::BindOnce(&base::DeletePathRecursively,
                     base::FilePath(kPluginVmDriveDownloadDirectory)),
      base::BindOnce(std::move(log_file_deletion_if_failed)));
}

absl::optional<std::string> GetIdFromDriveUrl(const GURL& url) {
  const std::string& spec = url.spec();

  const std::string kOpenUrlBase = "https://drive.google.com/open?";
  if (base::StartsWith(spec, kOpenUrlBase,
                       base::CompareCase::INSENSITIVE_ASCII)) {
    // e.g. https://drive.google.com/open?id=[ID]
    std::string id;
    if (!net::GetValueForKeyInQuery(url, "id", &id))
      return absl::nullopt;
    return id;
  }

  // These will match some invalid URLs, which is fine.
  const std::string kViewUrlPatternWithDomain =
      "https://drive.google.com/a/*/file/d/*/view*";
  const std::string kViewUrlPatternWithoutDomain =
      "https://drive.google.com/file/d/*/view*";
  if (base::MatchPattern(spec, kViewUrlPatternWithDomain) ||
      base::MatchPattern(spec, kViewUrlPatternWithoutDomain)) {
    // e.g. https://drive.google.com/a/example.org/file/d/[ID]/view?usp=sharing
    // or https://drive.google.com/file/d/[ID]/view?usp=sharing
    size_t id_end = spec.find("/view");
    size_t id_start = spec.rfind('/', id_end - 1) + 1;
    return spec.substr(id_start, id_end - id_start);
  }

  return absl::nullopt;
}

PluginVmPolicySubscription::PluginVmPolicySubscription(
    Profile* profile,
    base::RepeatingCallback<void(bool)> callback)
    : profile_(profile), callback_(callback) {
  DCHECK(ash::CrosSettings::IsInitialized());
  ash::CrosSettings* cros_settings = ash::CrosSettings::Get();
  // Subscriptions are automatically removed when this object is destroyed.
  pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>();
  pref_change_registrar_->Init(profile->GetPrefs());
  pref_change_registrar_->Add(
      plugin_vm::prefs::kPluginVmAllowed,
      base::BindRepeating(&PluginVmPolicySubscription::OnPolicyChanged,
                          base::Unretained(this)));
  pref_change_registrar_->Add(
      plugin_vm::prefs::kPluginVmUserId,
      base::BindRepeating(&PluginVmPolicySubscription::OnPolicyChanged,
                          base::Unretained(this)));
  device_allowed_subscription_ = cros_settings->AddSettingsObserver(
      ash::kPluginVmAllowed,
      base::BindRepeating(&PluginVmPolicySubscription::OnPolicyChanged,
                          base::Unretained(this)));
  fake_license_subscription_ = GetFakeLicenseKeyListeners().Add(
      base::BindRepeating(&PluginVmPolicySubscription::OnPolicyChanged,
                          base::Unretained(this)));

  is_allowed_ = PluginVmFeatures::Get()->IsAllowed(profile);
}

void PluginVmPolicySubscription::OnPolicyChanged() {
  bool allowed = PluginVmFeatures::Get()->IsAllowed(profile_);
  if (allowed != is_allowed_) {
    is_allowed_ = allowed;
    callback_.Run(allowed);
  }
}

PluginVmPolicySubscription::~PluginVmPolicySubscription() = default;

}  // namespace plugin_vm


text:
using System;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BiBilet.Domain.Entities.Application;
using BiBilet.Domain.Repositories.Application;

namespace BiBilet.Data.EntityFramework.Repositories.Application
{
    /// <summary>
    /// Entity framework implementation of <see cref="ITicketRepository" />
    /// </summary>
    public class TicketRepository : Repository<Ticket>, ITicketRepository
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="context"></param>
        public TicketRepository(BiBiletContext context)
            : base(context)
        {
        }

        /// <summary>
        /// Returns a single ticket
        /// </summary>
        /// <param name="id"></param>
        /// <returns>A single <see cref="Ticket" /></returns>
        public Ticket GetTicket(Guid id)
        {
            return Set.FirstOrDefault(t => t.TicketId == id);
        }

        /// <summary>
        /// Asynchronously returns a single ticket
        /// </summary>
        /// <param name="id"></param>
        /// <returns>A single <see cref="Ticket" /></returns>
        public Task<Ticket> GetTicketAsync(Guid id)
        {
            return Set
                .Include(t => t.UserTickets)
                .FirstOrDefaultAsync(t => t.TicketId == id);
        }

        /// <summary>
        /// Asynchronously returns a single ticket
        /// with cancellation support
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>A single <see cref="Ticket" /></returns>
        public Task<Ticket> GetTicketAsync(Guid id, CancellationToken cancellationToken)
        {
            return Set
                .Include(t => t.UserTickets)
                .FirstOrDefaultAsync(t => t.TicketId == id, cancellationToken);
        }
    }
}


text:
function client (appKey, appSecret){
  var OAuth = require('oauth'),
      Q = require('q');

  this.oauth = new OAuth.OAuth(
    'http://beta.snowshoestamp.com/oauth/request_token',
    'http://beta.snowshoestamp.com/oauth/access_token',
    appKey,
    appSecret,
    '1.0',
    null,
    'HMAC-SHA1'
  ),

  this.post = function(points, callback){
    var deferred = Q.defer();
    this._postWithOAuth(points, function(error, data, oauthResponse){
      if (error) {
        deferred.reject(error);
        if (callback) { return deferred.promise.nodeify(callback(error, null, oauthResponse)) };
      }
      var data = JSON.parse(data);
      deferred.resolve(data);
      if (callback) { return deferred.promise.nodeify(callback(null, data, oauthResponse)) };
    })
    return deferred.promise;
  }

  this._postWithOAuth = function(points, callback){
    this.oauth.post(
      'http://beta.snowshoestamp.com/api/v2/stamp',
      '',
      '',
      points,
      callback
    )
  }
}

exports.client = client;


text:
class TagCollection {
  /**
   * @param {Tag[]}
   */
  constructor (tags) {
    this.tags = tags || []

    this.dict = {}

    this.tags.forEach(tag => {
      this.dict[tag.name] = tag
    })
  }

  /**
   * Gets the tag by its name.
   * @param {string} name The tag name
   */
  getByName (name) {
    return this.dict[name]
  }

  /**
   * Gets the tags by their names.
   * @param {string[]} names The tag names
   */
  getByNames (names) {
    return new TagCollection(names.map(name => this.getByName(name)).filter(x => x != null))
  }

  /**
   * Maps the tags by the function.
   * @return {Array}
   */
  map (func) {
    return this.tags.map(func)
  }

  forEach (func) {
    this.tags.forEach(func)
  }

  sort () {
    this.tags.sort((x, y) => y.projects.length - x.projects.length)
  }
}

module.exports = TagCollection


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.nbstudio.core.cls;

import org.netbeans.api.editor.mimelookup.MimeRegistration;
import org.netbeans.spi.editor.fold.FoldManager;
import org.netbeans.spi.editor.fold.FoldManagerFactory;

@MimeRegistration(mimeType = "text/isc-cls", service = FoldManagerFactory.class)
public class clsFoldManagerFactory implements FoldManagerFactory{

    @Override
    public FoldManager createFoldManager() {
        return new clsFoldManager();
    }

}


text:
package org.apache.ignite.spi.communication.tcp;

import java.net.BindException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.internal.managers.communication.GridIoMessageFactory;
import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor;
import org.apache.ignite.internal.util.lang.GridAbsPredicate;
import org.apache.ignite.internal.util.nio.GridNioRecoveryDescriptor;
import org.apache.ignite.internal.util.nio.GridNioServer;
import org.apache.ignite.internal.util.nio.GridNioSession;
import org.apache.ignite.internal.util.typedef.CI1;
import org.apache.ignite.internal.util.typedef.CO;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteInClosure;
import org.apache.ignite.lang.IgniteRunnable;
import org.apache.ignite.plugin.extensions.communication.Message;
import org.apache.ignite.spi.IgniteSpiAdapter;
import org.apache.ignite.spi.IgniteSpiException;
import org.apache.ignite.spi.communication.CommunicationListener;
import org.apache.ignite.spi.communication.CommunicationSpi;
import org.apache.ignite.spi.communication.GridTestMessage;
import org.apache.ignite.testframework.GridSpiTestContext;
import org.apache.ignite.testframework.GridTestNode;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.GridTestKernalContext;
import org.apache.ignite.testframework.junits.IgniteTestResources;
import org.apache.ignite.testframework.junits.spi.GridSpiAbstractTest;
import org.apache.ignite.testframework.junits.spi.GridSpiTest;
import org.eclipse.jetty.util.ConcurrentHashSet;

/**
 *
 */
@GridSpiTest(spi = TcpCommunicationSpi.class, group = "Communication SPI")
public class IgniteTcpCommunicationRecoveryAckClosureSelfTest<T extends CommunicationSpi>
    extends GridSpiAbstractTest<T> {
    /** */
    private static final Collection<IgniteTestResources> spiRsrcs = new ArrayList<>();

    /** */
    protected static final List<TcpCommunicationSpi> spis = new ArrayList<>();

    /** */
    protected static final List<ClusterNode> nodes = new ArrayList<>();

    /** */
    private static final int SPI_CNT = 2;

    /** */
    private static GridTimeoutProcessor timeoutProcessor;

    /**
     *
     */
    static {
        GridIoMessageFactory.registerCustom(GridTestMessage.DIRECT_TYPE, new CO<Message>() {
            @Override public Message apply() {
                return new GridTestMessage();
            }
        });
    }

    /**
     * Disable SPI auto-start.
     */
    public IgniteTcpCommunicationRecoveryAckClosureSelfTest() {
        super(false);
    }

    /** */
    private class TestListener implements CommunicationListener<Message> {
        /** */
        private ConcurrentHashSet<Long> msgIds = new ConcurrentHashSet<>();

        /** */
        private AtomicInteger rcvCnt = new AtomicInteger();

        /** {@inheritDoc} */
        @Override public void onMessage(UUID nodeId, Message msg, IgniteRunnable msgC) {
            assertTrue("Unexpected message: " + msg, msg instanceof GridTestMessage);

            GridTestMessage msg0 = (GridTestMessage)msg;

            assertTrue("Duplicated message received: " + msg0, msgIds.add(msg0.getMsgId()));

            rcvCnt.incrementAndGet();

            msgC.run();
        }

        /** {@inheritDoc} */
        @Override public void onDisconnected(UUID nodeId) {
            // No-op.
        }
    }

    /**
     * @throws Exception If failed.
     */
    public void testAckOnIdle() throws Exception {
        checkAck(10, 2000, 9);
    }

    /**
     * @throws Exception If failed.
     */
    public void testAckOnCount() throws Exception {
        checkAck(10, 60_000, 10);
    }

    /**
     * @param ackCnt Recovery acknowledgement count.
     * @param idleTimeout Idle connection timeout.
     * @param msgPerIter Messages per iteration.
     * @throws Exception If failed.
     */
    @SuppressWarnings("unchecked")
    private void checkAck(int ackCnt, int idleTimeout, int msgPerIter) throws Exception {
        createSpis(ackCnt, idleTimeout, TcpCommunicationSpi.DFLT_MSG_QUEUE_LIMIT);

        try {
            TcpCommunicationSpi spi0 = spis.get(0);
            TcpCommunicationSpi spi1 = spis.get(1);

            ClusterNode node0 = nodes.get(0);
            ClusterNode node1 = nodes.get(1);

            int msgId = 0;

            int expMsgs = 0;

            long totAcked = 0;

            for (int i = 0; i < 5; i++) {
                info("Iteration: " + i);

                final AtomicInteger ackMsgs = new AtomicInteger(0);

                IgniteInClosure<IgniteException> ackC = new CI1<IgniteException>() {
                    @Override public void apply(IgniteException o) {
                        assert o == null;

                        ackMsgs.incrementAndGet();
                    }
                };

                for (int j = 0; j < msgPerIter; j++) {
                    spi0.sendMessage(node1, new GridTestMessage(node0.id(), ++msgId, 0), ackC);

                    spi1.sendMessage(node0, new GridTestMessage(node1.id(), ++msgId, 0), ackC);

                    if (j == 0) {
                        final TestListener lsnr0 = (TestListener)spi0.getListener();
                        final TestListener lsnr1 = (TestListener)spi1.getListener();

                        GridTestUtils.waitForCondition(new GridAbsPredicate() {
                            @Override public boolean apply() {
                                return lsnr0.rcvCnt.get() >= 1 && lsnr1.rcvCnt.get() >= 1;
                            }
                        }, 1000);
                    }
                }

                expMsgs += msgPerIter;

                final long totAcked0 = totAcked;

                for (TcpCommunicationSpi spi : spis) {
                    GridNioServer srv = U.field(spi, "nioSrvr");

                    Collection<? extends GridNioSession> sessions = GridTestUtils.getFieldValue(srv, "sessions");

                    assertFalse(sessions.isEmpty());

                    boolean found = false;

                    for (GridNioSession ses : sessions) {
                        final GridNioRecoveryDescriptor recoveryDesc = ses.outRecoveryDescriptor();

                        if (recoveryDesc != null) {
                            found = true;

                            GridTestUtils.waitForCondition(new GridAbsPredicate() {
                                @Override public boolean apply() {
                                    long acked = GridTestUtils.getFieldValue(recoveryDesc, "acked");

                                    return acked > totAcked0;
                                }
                            }, 5000);

                            GridTestUtils.waitForCondition(new GridAbsPredicate() {
                                @Override public boolean apply() {
                                    return recoveryDesc.messagesRequests().isEmpty();
                                }
                            }, 10_000);

                            assertEquals("Unexpected messages: " + recoveryDesc.messagesRequests(), 0,
                                recoveryDesc.messagesRequests().size());

                            break;
                        }
                    }

                    assertTrue(found);
                }

                final int expMsgs0 = expMsgs;

                for (TcpCommunicationSpi spi : spis) {
                    final TestListener lsnr = (TestListener)spi.getListener();

                    GridTestUtils.waitForCondition(new GridAbsPredicate() {
                        @Override public boolean apply() {
                            return lsnr.rcvCnt.get() >= expMsgs0;
                        }
                    }, 5000);

                    assertEquals(expMsgs, lsnr.rcvCnt.get());
                }

                assertEquals(msgPerIter * 2, ackMsgs.get());

                totAcked += msgPerIter;
            }
        }
        finally {
            stopSpis();
        }
    }

    /**
     * @throws Exception If failed.
     */
    public void testQueueOverflow() throws Exception {
        for (int i = 0; i < 3; i++) {
            try {
                startSpis(5, 60_000, 10);

                checkOverflow();

                break;
            }
            catch (IgniteCheckedException e) {
                if (e.hasCause(BindException.class)) {
                    if (i < 2) {
                        info("Got exception caused by BindException, will retry after delay: " + e);

                        stopSpis();

                        U.sleep(10_000);
                    }
                    else
                        throw e;
                }
                else
                    throw e;
            }
            finally {
                stopSpis();
            }
        }
    }

    /**
     * @throws Exception If failed.
     */
    @SuppressWarnings("unchecked")
    private void checkOverflow() throws Exception {
        TcpCommunicationSpi spi0 = spis.get(0);
        TcpCommunicationSpi spi1 = spis.get(1);

        ClusterNode node0 = nodes.get(0);
        ClusterNode node1 = nodes.get(1);

        // Await time to close the session by queue overflow.
        final int awaitTime = 5_000;

        // Check that session will not be closed by idle timeout because expected close by queue overflow.
        assertTrue(spi0.getIdleConnectionTimeout() > awaitTime);

        final GridNioServer srv1 = U.field(spi1, "nioSrvr");

        // For prevent session close by write timeout.
        srv1.writeTimeout(60_000);

        final AtomicInteger ackMsgs = new AtomicInteger(0);

        IgniteInClosure<IgniteException> ackC = new CI1<IgniteException>() {
            @Override public void apply(IgniteException o) {
                assert o == null;

                ackMsgs.incrementAndGet();
            }
        };

        int msgId = 0;

        // Send message to establish connection.
        spi0.sendMessage(node1, new GridTestMessage(node0.id(), ++msgId, 0), ackC);

        int sentMsgs = 1;

        // Prevent node1 from send
        GridTestUtils.setFieldValue(srv1, "skipWrite", true);

        final GridNioSession ses0 = communicationSession(spi0);

        int queueLimit = ses0.outRecoveryDescriptor().queueLimit();

        for (int i = sentMsgs; i < queueLimit; i++) {
            try {
                spi0.sendMessage(node1, new GridTestMessage(node0.id(), ++msgId, 0), ackC);

                sentMsgs++;
            }
            catch (IgniteSpiException e) {
                log.info("Send error [err=" + e + ", sentMsgs=" + sentMsgs + ']');

                break;
            }
        }

        // Wait when session is closed because of queue overflow.
        GridTestUtils.waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                return ses0.closeTime() != 0;
            }
        }, awaitTime);

        assertTrue("Failed to wait for session close", ses0.closeTime() != 0);

        GridTestUtils.setFieldValue(srv1, "skipWrite", false);

        // It to gain all acks since acks have batch nature.
        int cnt = 100 - sentMsgs % spi0.getAckSendThreshold();

        for (int i = 0; i < cnt; i++)
            spi0.sendMessage(node1, new GridTestMessage(node0.id(), ++msgId, 0), ackC);

        final int expMsgs = sentMsgs + cnt;

        final TestListener lsnr = (TestListener)spi1.getListener();

        GridTestUtils.waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                return lsnr.rcvCnt.get() >= expMsgs;
            }
        }, 5000);

        assertEquals(expMsgs, lsnr.rcvCnt.get());

        GridTestUtils.waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                return expMsgs == ackMsgs.get();
            }
        }, 5000);

        assertEquals(expMsgs, ackMsgs.get());
    }

    /**
     * @param spi SPI.
     * @return Session.
     * @throws Exception If failed.
     */
    @SuppressWarnings("unchecked")
    private GridNioSession communicationSession(TcpCommunicationSpi spi) throws Exception {
        final GridNioServer srv = U.field(spi, "nioSrvr");

        GridTestUtils.waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                Collection<? extends GridNioSession> sessions = GridTestUtils.getFieldValue(srv, "sessions");

                return !sessions.isEmpty();
            }
        }, 5000);

        Collection<? extends GridNioSession> sessions = GridTestUtils.getFieldValue(srv, "sessions");

        assertEquals(1, sessions.size());

        return sessions.iterator().next();
    }

    /**
     * @param ackCnt Recovery acknowledgement count.
     * @param idleTimeout Idle connection timeout.
     * @param queueLimit Message queue limit.
     * @return SPI instance.
     */
    protected TcpCommunicationSpi getSpi(int ackCnt, int idleTimeout, int queueLimit) {
        TcpCommunicationSpi spi = new TcpCommunicationSpi();

        spi.setLocalPort(GridTestUtils.getNextCommPort(getClass()));
        spi.setIdleConnectionTimeout(idleTimeout);
        spi.setTcpNoDelay(true);
        spi.setAckSendThreshold(ackCnt);
        spi.setMessageQueueLimit(queueLimit);
        spi.setSharedMemoryPort(-1);
        spi.setConnectionsPerNode(1);

        return spi;
    }

    /**
     * @param ackCnt Recovery acknowledgement count.
     * @param idleTimeout Idle connection timeout.
     * @param queueLimit Message queue limit.
     * @throws Exception If failed.
     */
    private void startSpis(int ackCnt, int idleTimeout, int queueLimit) throws Exception {
        spis.clear();
        nodes.clear();
        spiRsrcs.clear();

        Map<ClusterNode, GridSpiTestContext> ctxs = new HashMap<>();

        timeoutProcessor = new GridTimeoutProcessor(new GridTestKernalContext(log));

        timeoutProcessor.start();

        timeoutProcessor.onKernalStart(true);

        for (int i = 0; i < SPI_CNT; i++) {
            TcpCommunicationSpi spi = getSpi(ackCnt, idleTimeout, queueLimit);

            GridTestUtils.setFieldValue(spi, IgniteSpiAdapter.class, "igniteInstanceName", "grid-" + i);

            IgniteTestResources rsrcs = new IgniteTestResources();

            GridTestNode node = new GridTestNode(rsrcs.getNodeId());

            GridSpiTestContext ctx = initSpiContext();

            ctx.setLocalNode(node);

            ctx.timeoutProcessor(timeoutProcessor);

            spiRsrcs.add(rsrcs);

            rsrcs.inject(spi);

            spi.setListener(new TestListener());

            node.setAttributes(spi.getNodeAttributes());

            node.order(i);

            nodes.add(node);

            spi.spiStart(getTestIgniteInstanceName() + (i + 1));

            spis.add(spi);

            spi.onContextInitialized(ctx);

            ctxs.put(node, ctx);
        }

        // For each context set remote nodes.
        for (Map.Entry<ClusterNode, GridSpiTestContext> e : ctxs.entrySet()) {
            for (ClusterNode n : nodes) {
                if (!n.equals(e.getKey()))
                    e.getValue().remoteNodes().add(n);
            }
        }
    }

    /**
     * @param ackCnt Recovery acknowledgement count.
     * @param idleTimeout Idle connection timeout.
     * @param queueLimit Message queue limit.
     * @throws Exception If failed.
     */
    private void createSpis(int ackCnt, int idleTimeout, int queueLimit) throws Exception {
        for (int i = 0; i < 3; i++) {
            try {
                startSpis(ackCnt, idleTimeout, queueLimit);

                break;
            }
            catch (IgniteCheckedException e) {
                if (e.hasCause(BindException.class)) {
                    if (i < 2) {
                        info("Failed to start SPIs because of BindException, will retry after delay.");

                        stopSpis();

                        U.sleep(10_000);
                    }
                    else
                        throw e;
                }
                else
                    throw e;
            }
        }
    }

    /**
     * @throws Exception If failed.
     */
    private void stopSpis() throws Exception {
        if (timeoutProcessor != null) {
            timeoutProcessor.onKernalStop(true);

            timeoutProcessor.stop(true);

            timeoutProcessor = null;
        }

        for (CommunicationSpi<Message> spi : spis) {
            spi.onContextDestroyed();

            spi.setListener(null);

            spi.spiStop();
        }

        for (IgniteTestResources rsrcs : spiRsrcs)
            rsrcs.stopThreads();

        spis.clear();
        nodes.clear();
        spiRsrcs.clear();
    }
}


text:
<fxlayout help_file="FogIno.pdf">
  <page name="Fog Ino">
    <control>radius</control>
    <control>curve</control>
    <control>power</control>
    <control>threshold_min</control>
    <control>threshold_max</control>
    <control>alpha_rendering</control>
  </page>
</fxlayout>


text:
"""
    Talon.One API

    Use the Talon.One API to integrate with your application and to manage applications and campaigns:  - Use the operations in the [Integration API section](#integration-api) are used to integrate with our platform - Use the operation in the [Management API section](#management-api) to manage applications and campaigns.  ## Determining the base URL of the endpoints  The API is available at the same hostname as your Campaign Manager deployment. For example, if you are reading this page at `https://mycompany.talon.one/docs/api/`, the URL for the [updateCustomerSession](https://docs.talon.one/integration-api/#operation/updateCustomerSessionV2) endpoint is `https://mycompany.talon.one/v2/customer_sessions/{Id}`   # noqa: E501

    The version of the OpenAPI document: 1.0.0
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from talon_one.configuration import Configuration

class AudienceIntegrationID(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'integration_id': 'str'
    }

    attribute_map = {
        'integration_id': 'integrationId'
    }

    def __init__(self, integration_id=None, local_vars_configuration=None):  # noqa: E501
        """AudienceIntegrationID - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._integration_id = None
        self.discriminator = None

        if integration_id is not None:
            self.integration_id = integration_id

    @property
    def integration_id(self):
        """Gets the integration_id of this AudienceIntegrationID.  # noqa: E501

        The ID of this audience in the third-party integration.  # noqa: E501

        :return: The integration_id of this AudienceIntegrationID.  # noqa: E501
        :rtype: str
        """
        return self._integration_id

    @integration_id.setter
    def integration_id(self, integration_id):
        """Sets the integration_id of this AudienceIntegrationID.

        The ID of this audience in the third-party integration.  # noqa: E501

        :param integration_id: The integration_id of this AudienceIntegrationID.  # noqa: E501
        :type: str
        """
        if (self.local_vars_configuration.client_side_validation and
                integration_id is not None and len(integration_id) > 1000):
            raise ValueError("Invalid value for `integration_id`, length must be less than or equal to `1000`")  # noqa: E501
        if (self.local_vars_configuration.client_side_validation and
                integration_id is not None and len(integration_id) < 1):
            raise ValueError("Invalid value for `integration_id`, length must be greater than or equal to `1`")  # noqa: E501

        self._integration_id = integration_id

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, AudienceIntegrationID):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, AudienceIntegrationID):
            return True

        return self.to_dict() != other.to_dict()


text:
using namespace std;

namespace EGF {

namespace UI {

using namespace GeometryDefines;

using namespace FreeType;

Component::Component() throw(runtime_error):
    box_(PointI(0, 0), PointI(0, 0)),
    mouseDownX_(-100),
    mouseDownY_(-100),
    isHovered_(false),
    isPressed_(false)
{

    SingletonPointer<ResourceManager> resourceManager = ResourceManager::getInstance();

    boost::shared_ptr<Font> fontResource = resourceManager->getResource<Font>(DEFAULT_FONT);

    font_ = *fontResource;

}

Component::~Component() {}

void Component::setRect(int x, int y, unsigned int width, unsigned int height) {

    box_.min_corner().x(x);
    box_.min_corner().y(y);

    box_.max_corner().x(x + width);
    box_.max_corner().y(y + height);

}

int Component::getX() const {

    return box_.min_corner().x();

}

int Component::getY() const {

    return box_.min_corner().y();

}

unsigned int Component::getWidth() const {

    return box_.max_corner().x() - box_.min_corner().x();

}

unsigned int Component::getHeight() const {

    return box_.max_corner().y() - box_.min_corner().y();

}

const BoxI& Component::getBoxI() const {

    return box_;

}

void Component::setText(const char* text) {

    if(text == 0) {

        text_ = "";

    } else {

        text_ = text;

    }

}

void Component::setText(const string& text) {

    text_ = text;

}

const string& Component::getText() const {

    return text_;

}

void Component::setName(const char* name) {

    if(name == 0) {

        name_ = "";

    } else {

        name_ = name;

    }

}

void Component::setName(const string& name) {

    setName(name.c_str());

}

const string& Component::getName() const {

    return name_;

}

void Component::setFont(const Font& font) {

    font_ = font;

}

Font& Component::getFont() {

    return font_;

}

const Font& Component::getFont() const {

    return font_;

}

bool Component::isContains(int x, int y) {

	// TODO: Найти стандартные бустовские функции вместо этого.

	if( ( x >= box_.min_corner().x() )
			&& ( x <= box_.max_corner().x() ) ) {

		if( ( y >= box_.min_corner().y() )
				&& ( y <= box_.max_corner().y() ) ) {

			return true;

		}

	}

    return false;

}

// Все событийные методы преобразовывают аргументы в
// Event структуры и вызывают обработчики.

void Component::mouseDown(int x, int y, MouseButton btn) {

    if(btn == EGF::BUTTON_LEFT) { // сохраним координаты, на случай, если это был клик.

        mouseDownX_ = x;
        mouseDownY_ = y;

    }

    isPressed_ = true;

    try {

        MouseEvent event;

        event.x            =  x;
        event.y            =  y;
        event.mouseButton  =  btn;

        mouseDownEvent_(this, event);

    } catch(const boost::bad_function_call&) {}

}

void Component::mouseUp(int x, int y, MouseButton btn) {

    isPressed_ = false;

    try {

        MouseEvent event;

        event.x            =  x;
        event.y            =  y;
        event.mouseButton  =  btn;

        mouseUpEvent_(this, event);

    } catch(const boost::bad_function_call&) {}

    if(btn != EGF::BUTTON_LEFT) {
        return;
    }

    if((mouseDownX_ == x)
        || (mouseDownY_ == y)) { // если был клик.

            click(x, y);

    }

}

void Component::click(int x, int y) {

    try {

        MouseEvent event;

        event.x            =  x;
        event.y            =  y;
        event.mouseButton  =  MouseButton::BUTTON_LEFT;

        clickEvent_(this, event);

    } catch(const boost::bad_function_call&) {}

}

void Component::mouseMotion(int x, int y) {

    if(isContains(x, y)) {

        if(!isHovered_) {

            isHovered_ = true;

            mouseHover();

        }

    } else {

        if(isHovered_) {

            isHovered_ = false;

            mouseLeave();

        }

    }

    try {

        MouseEvent event;

        event.x             =   x;
        event.y             =   y;
        event.mouseButton   =   MouseButton::BUTTON_NONE;

        mouseMotionEvent_(this, event);

    } catch(const boost::bad_function_call&) {}

}

void Component::mouseHover() {

    try {

        Event event;

        hoverEvent_(this, event);

    } catch(const boost::bad_function_call&) {}

}

void Component::mouseLeave() {

    try {

        Event event;

        leaveEvent_(this, event);

    } catch (const boost::bad_function_call&) {}

}

void Component::draw() {

    try {

        Event event;

        drawEvent_(this, event);

    } catch(const boost::bad_function_call&) {}

}

void Component::keyDown(int key) {

    try {

        KeyEvent event;

        event.key = key;

        keyDownEvent_(this, event);

    } catch(const boost::bad_function_call&) {}

}

void Component::keyUp(int key) {

    try {

        KeyEvent event;

        event.key = key;

        keyUpEvent_(this, event);

    } catch(const boost::bad_function_call&) {}

}

void Component::setMouseMotionEvent(const Component::MouseMotionEvent& eventHandler) {

    mouseMotionEvent_ = eventHandler;

}

void Component::setHoveredEvent(const Component::MouseHoverEvent& eventHandler) {

    hoverEvent_ = eventHandler;

}

void Component::setLeavedEvent(const Component::MouseLeaveEvent& eventHandler) {

    leaveEvent_ = eventHandler;

}

void Component::setClickedEvent(const Component::MouseClickEvent& eventHandler) {

    clickEvent_ = eventHandler;

}

void Component::setMouseDownEvent(const Component::MouseDownEvent& eventHandler) {

    mouseDownEvent_ = eventHandler;

}

void Component::setMouseUpEvent(const Component::MouseUpEvent& eventHandler) {

    mouseUpEvent_ = eventHandler;

}

void Component::setDrawEvent(const Component::DrawEvent& eventHandler) {

    drawEvent_ = eventHandler;

}

void Component::setKeyDownEvent(const Component::KeyDownEvent& eventHandler) {

    keyDownEvent_ = eventHandler;

}

void Component::setKeyUpEvent(const Component::KeyUpEvent& eventHandler) {

    keyUpEvent_ = eventHandler;

}

}

}


text:
#ifndef DOMAINS_CONCRETE_CONCRETEMEMORY_HH
#define DOMAINS_CONCRETE_CONCRETEMEMORY_HH

#include <stdio.h>
#include <stddef.h>
#include <inttypes.h>

#include <map>

#include <domains/concrete/ConcreteValue.hh>
#include <domains/concrete/ConcreteAddress.hh>

#include <kernel/Memory.hh>
#include <kernel/RegisterMap.hh>

#include <utils/Object.hh>
#include <utils/tools.hh>
#include <utils/unordered11.hh>

/** \brief ConcreteMemory module which manage memory and also registers. */
class ConcreteMemory : public Memory<ConcreteAddress, ConcreteValue>,
		       public RegisterMap<ConcreteValue>
{
public:
  /** \brief Data structure used to encode the concrete memory. */
  typedef std::unordered_map<address_t,
				  uint8_t,
				  std::hash<address_t> > MemoryMap;
  typedef MemoryMap::const_iterator const_memcell_iterator;
  typedef ConcreteValue Value;
  typedef ConcreteAddress Address;

  /***************************************************************************/
  /* Constructors                                                            */
  /***************************************************************************/

  /** \brief Default constructor : the memory is empty. */
  ConcreteMemory();

  /** \brief Copy constructor. */
  explicit ConcreteMemory(const ConcreteMemory &mem);

  ConcreteMemory(const ConcreteMemory *base);

  /** \brief Destructor. */
  virtual ~ConcreteMemory();

  /***************************************************************************/
  /* Memory Access                                                           */
  /***************************************************************************/

  /** \brief Retrieve the content of the memory cell at a given
   *   address and according to a specified endianness. The 'size'
   *   parameter is a number of bytes. Note that if the memory cell
   *   has not yet been set, the function will raise an exception
   *   UndefinedValue. */
  virtual ConcreteValue get(const ConcreteAddress &,
			    const int size,
			    const Architecture::endianness_t) const
    throw (UndefinedValueException);

  /** \brief Put the value into the memory cell at a given address. */
  virtual void put(const ConcreteAddress &,
		   const ConcreteValue &,
		   const Architecture::endianness_t);

  /** \brief Retrieve the content of a register. Note that if the
   *   register has not yet been set, the function will raise an
   *   exception 'UndefinedValue'. */
  virtual ConcreteValue get(const RegisterDesc *) const
    throw (UndefinedValueException);

  /** \brief Put the value v into the register */

  using RegisterMap<ConcreteValue>::put;

  /** \brief Tells if the register has been written or not. */
  bool is_defined(const RegisterDesc *) const;

  /** \brief Tells if the memory cell has been written or not. */
  bool is_defined(const ConcreteAddress &) const;

  /***************************************************************************/
  /* Utils                                                                   */
  /***************************************************************************/
  virtual bool equals (const ConcreteMemory &mem) const;
  virtual std::size_t hashcode () const;
  void output_text(std::ostream &) const;
  void get_address_range (address_t &min, address_t &max) const;

  virtual const_memcell_iterator begin () const;
  virtual const_memcell_iterator end () const;
  virtual ConcreteMemory *clone () const;

private:
  /** \brief The actual storage into memory. */
  const ConcreteMemory *base;
  MemoryMap memory;
  address_t minaddr;
  address_t maxaddr;
};

#endif /* DOMAINS_CONCRETE_CONCRETEMEMORY_HH */


text:
package sql.generic.ddl.procedures;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import sql.SQLHelper;

public class ProcedureBody {

  public static Connection getDefaultConnection() {
    Connection conn = null;
    try {
      conn = DriverManager.getConnection("jdbc:default:connection");
      // Log.getLogWriter().info("Connection in - getDefaultConnection " +
      // conn.getMetaData().getDriverName());
    } catch (SQLException se) {
      SQLHelper.handleSQLException(se);
    }
    return conn;
  }

  // let the calling procedure handling the exception instead for this procedure
  // call
  public static void selectCustomers(int tid, ResultSet[] rs)
      throws SQLException {
    // Log.getLogWriter().info("I am inside the selectCustomers" );
    Connection conn = getDefaultConnection();
    PreparedStatement ps2 = conn
        .prepareStatement("select count(*) from trade.customers where tid= ?");
    ps2.setInt(1, tid);
    ResultSet rsCount = ps2.executeQuery();
    if (rsCount.next())
      System.out.println("total rown in db " + rsCount.getInt(1));

    PreparedStatement ps1 = conn
        .prepareStatement("select * from trade.customers where tid= ?");
    ps1.setInt(1, tid);
    rs[0] = ps1.executeQuery();
    if (rs[0] != null)
      System.out.println("resultset in the method " + rs[0]);
    System.out.println("getting metdata" + rs[0].getMetaData());
    conn.close();
  }

  public static void addInterest(int tid) throws SQLException {
    Connection conn = getDefaultConnection();
    // PreparedStatement ps1 =
    // conn.prepareStatement("update trade.networth set cash=cash*1.01 where cash>=10000 and cash < 1000000 and tid= ?"
    // );
    PreparedStatement ps1 = conn
        .prepareStatement("update trade.networth set cash=trade.multiply(cash) where cash>=10000 and cash < 1000000 and tid= ?");
    PreparedStatement ps2 = conn
        .prepareStatement("update trade.networth set cash=cash*1.02 where cash<10000 and cash >=1000 and tid= ?");
    PreparedStatement ps3 = conn
        .prepareStatement("update trade.networth set cash=cash*1.03 where cash<1000 and tid= ?");
    if (tid % 11 == 1) {
      ps1.setInt(1, tid);
      ps2.setInt(1, tid);
      ps3.setInt(1, tid);

      ps1.execute();
      // int num = ps2.executeUpdate();
      ps3.execute();

      // System.out.println("ps2 warning is " + ps2.getWarnings() +
      // " ps2 updated " + num + " of rows.");

    }
    else {
      ps1.setInt(1, tid);
      ps2.setInt(1, tid);
      ps3.setInt(1, tid);

      ps1.execute();
      int num = ps2.executeUpdate();
      ps3.execute();

      System.out.println("ps2 warning is " + ps2.getWarnings()
          + " ps2 updated " + num + " of rows.");
    }
    conn.close();
  }

  // one input param, one output param, one inout param, and two resultSets
  // need to retry during HA tests
  public static void testInOutParam(int tid, BigDecimal[] maxCash, int[] inOut,
      ResultSet[] rs, ResultSet[] rs2) throws SQLException {
    boolean[] success = new boolean[1];
    testInOutParam(tid, maxCash, inOut, rs, rs2, success);
    while (!success[0])
      testInOutParam(tid, maxCash, inOut, rs, rs2, success);
  }

  // one input param, one output param, one inout param, and two resultSets
  // retrying during HA tests
  private static void testInOutParam(int tid, BigDecimal[] maxCash,
      int[] inOut, ResultSet[] rs, ResultSet[] rs2, boolean[] success)
      throws SQLException {
    Connection conn = getDefaultConnection();
    success[0] = true;
    try {
      PreparedStatement ps1 = conn
          .prepareStatement("select * from trade.networth where tid= ? order by cash desc");
      ps1.setInt(1, tid);
      rs[0] = ps1.executeQuery();

      PreparedStatement ps2 = conn
          .prepareStatement("select * from trade.portfolio where tid= ?");
      ps2.setInt(1, tid);
      rs2[0] = ps2.executeQuery();

      PreparedStatement ps3 = conn
          .prepareStatement("select max(cash + securities-(loanlimit-availloan)) "
              + " as net from trade.networth where tid = ?");
      ps3.setInt(1, tid);
      ResultSet rs3 = ps3.executeQuery();

      if (rs3.next()) {
        maxCash[0] = rs3.getBigDecimal("NET");
      }

      inOut[0]++;
      System.out.println("inOut is " + inOut[0]);
    } catch (SQLException se) {
      if (se.getSQLState().equals("X0Z01")) {
        System.out
            .println("remote node is down during the query, need to retry");
        success[0] = false;
      }
      else
        throw se;
    }

    // conn.close();
  }
}


text:
    (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
     (__GNUC__ >= 4))  // GCC supports "pragma once" correctly since 3.4
#pragma once
#endif

#include "yaml-cpp/dll.h"
#include "yaml-cpp/node/node.h"
#include "yaml-cpp/node/detail/iterator_fwd.h"
#include "yaml-cpp/node/detail/iterator.h"
#include <list>
#include <utility>
#include <vector>

// Assert in place so gcc + libc++ combination properly builds
static_assert(std::is_constructible<YAML::Node, const YAML::Node&>::value, "Node must be copy constructable");

namespace YAML {
namespace detail {
struct iterator_value : public Node, std::pair<Node, Node> {
  iterator_value() = default;
  explicit iterator_value(const Node& rhs)
      : Node(rhs),
        std::pair<Node, Node>(Node(Node::ZombieNode), Node(Node::ZombieNode)) {}
  explicit iterator_value(const Node& key, const Node& value)
      : Node(Node::ZombieNode), std::pair<Node, Node>(key, value) {}
};
}
}

#endif  // VALUE_ITERATOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66


text:
package org.apache.giraph.block_app.library.coarsening;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Iterator;

import org.apache.giraph.block_app.framework.api.BlockWorkerReceiveApi;
import org.apache.giraph.block_app.framework.api.BlockWorkerSendApi;
import org.apache.giraph.block_app.framework.block.Block;
import org.apache.giraph.block_app.framework.block.SequenceBlock;
import org.apache.giraph.block_app.framework.piece.Piece;
import org.apache.giraph.block_app.framework.piece.delegate.FilteringPiece;
import org.apache.giraph.block_app.framework.piece.interfaces.VertexReceiver;
import org.apache.giraph.block_app.framework.piece.interfaces.VertexSender;
import org.apache.giraph.block_app.library.VertexSuppliers;
import org.apache.giraph.combiner.MessageCombiner;
import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration;
import org.apache.giraph.edge.Edge;
import org.apache.giraph.edge.EdgeFactory;
import org.apache.giraph.factories.MessageValueFactory;
import org.apache.giraph.function.Function;
import org.apache.giraph.function.ObjectTransfer;
import org.apache.giraph.function.vertex.ConsumerWithVertex;
import org.apache.giraph.function.vertex.SupplierFromVertex;
import org.apache.giraph.types.ops.NumericTypeOps;
import org.apache.giraph.types.ops.PrimitiveIdTypeOps;
import org.apache.giraph.types.ops.TypeOps;
import org.apache.giraph.types.ops.TypeOpsUtils;
import org.apache.giraph.types.ops.collections.Basic2ObjectMap;
import org.apache.giraph.types.ops.collections.WritableWriter;
import org.apache.giraph.utils.ReflectionUtils;
import org.apache.giraph.writable.tuple.PairWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;

/**
 * Utilities class that creates a new coarsened graph, while keeping the
 * original graph, allowing us to execute things on either representation
 * of the graph.
 */
public class CoarseningUtils {

  private CoarseningUtils() { }

  //CHECKSTYLE: stop ParameterNumberCheck

  /**
   * Create block that creates coarsened graph from given set of vertices
   * (original vertices, that return true for originalNodesChecker).
   *
   * Old graph is not deleted, if needed, you can trivially do that by calling
   * Pieces.removeVertices(originalNodesChecker) after this block.
   *
   *
   * @param idTypeOps Type ops for vertex ids
   * @param edgeTypeOps Type ops for edge values
   * @param coarsenedVertexIdSupplier Supplier called on original nodes,
   *                                  that should return it's coarsened vertex
   *                                  id
   * @param vertexInfoClass Part of the vertex value that is needed to create
   *                        coarsened vertices
   * @param vertexInfoSupplier Supplier providing part of the vertex value that
   *                           is needed to create coarsened vertices
   * @param vertexInfoCombiner Combiner that aggregates individual vertex info
   *                           values into coarsened value
   * @param coarsenedVertexValueInitializer Function that initializes coarsened
   *                                        vertex value, from an aggregated
   *                                        vertex info of original vertex
   *                                        values that are coarsened into this
   *                                        vertex
   * @param edgeCoarseningCombiner Combiner that aggregates individual edge
   *                               values into coarsened edge value
   * @param originalNodesChecker Vertices with id that this gives true for will
   *                             be coarsened
   * @param clusterNodesChecker Should return true only for coarsened ids
   *                            (ones returned by coarsenedVertexIdSupplier)
   * @return Block that does coarsening
   */
  public static
  <I extends WritableComparable, V extends Writable, E extends Writable,
  VI extends Writable>
  Block createCustomCoarseningBlock(
      PrimitiveIdTypeOps<I> idTypeOps,
      TypeOps<E> edgeTypeOps,
      SupplierFromVertex<I, V, E, I> coarsenedVertexIdSupplier,
      Class<VI> vertexInfoClass,
      SupplierFromVertex<I, V, E, VI> vertexInfoSupplier,
      MessageCombiner<? super I, VI> vertexInfoCombiner,
      ConsumerWithVertex<I, V, E, VI> coarsenedVertexValueInitializer,
      MessageCombiner<? super I, E> edgeCoarseningCombiner,
      Function<I, Boolean> originalNodesChecker,
      Function<I, Boolean> clusterNodesChecker) {

  //CHECKSTYLE: resume ParameterNumberCheck

    ObjectTransfer<Iterable<PairWritable<I, E>>> edgesHolder =
        new ObjectTransfer<>();

    MessageValueFactory<PairWritable<I, E>> pairMessageFactory =
        () -> new PairWritable<I, E>(
            idTypeOps.create(), edgeTypeOps.create());
    Piece<I, V, E, PairWritable<I, E>, Object> calcWeightsOnEdgesPiece =
        new Piece<I, V, E, PairWritable<I, E>, Object>() {
      @Override
      public VertexSender<I, V, E> getVertexSender(
          BlockWorkerSendApi<I, V, E, PairWritable<I, E>> workerApi,
          Object executionStage) {
        PairWritable<I, E> message = pairMessageFactory.newInstance();
        return (vertex) -> {
          idTypeOps.set(
              message.getLeft(), coarsenedVertexIdSupplier.get(vertex));
          for (Edge<I, E> edge : vertex.getEdges()) {
            edgeTypeOps.set(message.getRight(), edge.getValue());
            workerApi.sendMessage(edge.getTargetVertexId(), message);
          }
        };
      }

      @Override
      public VertexReceiver<I, V, E, PairWritable<I, E>> getVertexReceiver(
          BlockWorkerReceiveApi<I> workerApi, Object executionStage) {
        return (vertex, messages) -> {
          edgesHolder.apply(messages);
        };
      }

      @Override
      protected MessageValueFactory<PairWritable<I, E>> getMessageFactory(
          ImmutableClassesGiraphConfiguration conf) {
        return pairMessageFactory;
      }

      @Override
      public String toString() {
        return "CoarseningCalcWeightsOnEdges";
      }
    };

    WritableWriter<E> edgeValueWriter = new WritableWriter<E>() {
      @Override
      public void write(DataOutput out, E value) throws IOException {
        value.write(out);
      }

      @Override
      public E readFields(DataInput in) throws IOException {
        E edge = edgeTypeOps.create();
        edge.readFields(in);
        return edge;
      }
    };

    Piece<I, V, E, PairWritable<VI, Basic2ObjectMap<I, E>>, Object>
    createNewVerticesPiece =
        new Piece<I, V, E, PairWritable<VI, Basic2ObjectMap<I, E>>, Object>() {
      @Override
      public VertexSender<I, V, E> getVertexSender(
          BlockWorkerSendApi<I, V, E, PairWritable<VI, Basic2ObjectMap<I, E>>>
            workerApi,
          Object executionStage) {
        return (vertex) -> {
          Basic2ObjectMap<I, E> map =
              idTypeOps.create2ObjectOpenHashMap(edgeValueWriter);
          for (PairWritable<I, E> message : edgesHolder.get()) {

            E value = map.get(message.getLeft());
            if (value == null) {
              value = edgeCoarseningCombiner.createInitialMessage();
              map.put(message.getLeft(), value);
            }

            edgeCoarseningCombiner.combine(
                message.getLeft(), value, message.getRight());
          }

          workerApi.sendMessage(
              coarsenedVertexIdSupplier.get(vertex),
              new PairWritable<>(vertexInfoSupplier.get(vertex), map));
        };
      }

      @Override
      public
      VertexReceiver<I, V, E, PairWritable<VI, Basic2ObjectMap<I, E>>>
      getVertexReceiver(
          BlockWorkerReceiveApi<I> workerApi, Object executionStage) {
        return (vertex, messages) -> {
          VI vertexInfo = vertexInfoCombiner.createInitialMessage();
          Basic2ObjectMap<I, E> map = idTypeOps.create2ObjectOpenHashMap(null);
          for (PairWritable<VI, Basic2ObjectMap<I, E>> message : messages) {
            vertexInfoCombiner.combine(
                vertex.getId(), vertexInfo, message.getLeft());

            for (Iterator<I> iter = message.getRight().fastKeyIterator();
                iter.hasNext();) {
              I key = iter.next();
              E value = map.get(key);
              if (value == null) {
                value = edgeCoarseningCombiner.createInitialMessage();
                map.put(key, value);
              }
              edgeCoarseningCombiner.combine(
                  vertex.getId(), value, message.getRight().get(key));
            }
          }

          for (Iterator<I> iter = map.fastKeyIterator(); iter.hasNext();) {
            I key = iter.next();
            Edge<I, E> edge = EdgeFactory.create(
                idTypeOps.createCopy(key), map.get(key));
            vertex.addEdge(edge);
          }

          coarsenedVertexValueInitializer.apply(vertex, vertexInfo);
        };
      }

      @Override
      protected MessageValueFactory<PairWritable<VI, Basic2ObjectMap<I, E>>>
      getMessageFactory(
          ImmutableClassesGiraphConfiguration conf) {
        return () -> new PairWritable<>(
            ReflectionUtils.newInstance(vertexInfoClass),
            idTypeOps.create2ObjectOpenHashMap(edgeValueWriter));
      }

      @Override
      public String toString() {
        return "CoarseningCreateNewVertices";
      }
    };

    return new SequenceBlock(
        new FilteringPiece<>(
            (vertex) -> originalNodesChecker.apply(vertex.getId()),
            calcWeightsOnEdgesPiece),
        new FilteringPiece<>(
            (vertex) -> originalNodesChecker.apply(vertex.getId()),
            (vertex) -> clusterNodesChecker.apply(vertex.getId()),
            createNewVerticesPiece));
  }

  /**
   * Create block that creates coarsened graph from given set of vertices
   * (original vertices, that return true for originalNodesChecker), when
   * vertex and edge values are primitives (or TypeOps exist for them).
   * Coarsening vertex values and edge values are computed as sum of their
   * individual values.
   *
   * Old graph is not deleted, if needed, you can trivially do that by calling
   * Pieces.removeVertices(originalNodesChecker) after this block.
   *
   * @param idTypeOps Vertex id TypeOps
   * @param valueTypeOps Vertex value TypeOps
   * @param edgeTypeOps Edge value TypeOps
   * @param coarsenedVertexIdSupplier Supplier called on original nodes,
   *                                  that should return it's coarsened vertex
   *                                  id
   * @param originalNodesChecker Vertices with id that this gives true for will
   *                             be coarsened
   * @param clusterNodesChecker Should return true only for coarsened ids
   *                            (ones returned by coarsenedVertexIdSupplier)
   * @return Block that does coarsening
   */
  public static
  <I extends WritableComparable, V extends Writable, E extends Writable>
  Block createCoarseningBlock(
      PrimitiveIdTypeOps<I> idTypeOps,
      NumericTypeOps<V> valueTypeOps,
      NumericTypeOps<E> edgeTypeOps,
      SupplierFromVertex<I, V, E, I> coarsenedVertexIdSupplier,
      Function<I, Boolean> originalNodesChecker,
      Function<I, Boolean> clusterNodesChecker) {
    return CoarseningUtils.<I, V, E, V>createCustomCoarseningBlock(
        idTypeOps,
        edgeTypeOps,
        coarsenedVertexIdSupplier,
        valueTypeOps.getTypeClass(),
        VertexSuppliers.vertexValueSupplier(),
        new MessageCombiner<I, V>() {
          @Override
          public void combine(
              I vertexIndex, V originalMessage, V messageToCombine) {
            valueTypeOps.plusInto(originalMessage, messageToCombine);
          }

          @Override
          public V createInitialMessage() {
            return valueTypeOps.createZero();
          }
        },
        (vertex, value) -> valueTypeOps.set(vertex.getValue(), value),
        new MessageCombiner<I, E>() {
          @Override
          public void combine(
              I vertexIndex, E originalMessage, E messageToCombine) {
            edgeTypeOps.plusInto(originalMessage, messageToCombine);
          }

          @Override
          public E createInitialMessage() {
            return edgeTypeOps.createZero();
          }
        },
        originalNodesChecker,
        clusterNodesChecker);
  }

  /**
   * Uses configuration to figure out vertex id, value and edge value types,
   * and calls above createCoarseningBlock with it, look at it's
   * documentation for more details.
   */
  public static
  <I extends WritableComparable, V extends Writable, E extends Writable>
  Block createCoarseningBlock(
      ImmutableClassesGiraphConfiguration<I, V, E> conf,
      SupplierFromVertex<I, V, E, I> coarsenedVertexIdSupplier,
      Function<I, Boolean> originalNodesChecker,
      Function<I, Boolean> clusterNodesChecker) {
    return createCoarseningBlock(
        TypeOpsUtils.getPrimitiveIdTypeOps(conf.getVertexIdClass()),
        (NumericTypeOps<V>)
          TypeOpsUtils.getTypeOps(conf.getVertexValueClass()),
        (NumericTypeOps<E>) TypeOpsUtils.getTypeOps(conf.getEdgeValueClass()),
        coarsenedVertexIdSupplier, originalNodesChecker, clusterNodesChecker);
  }
}


text:
Topcoat Button Bar
==============

Default skin for topcoat button bar.
Uses topcoat-button-bar-base for reset and topcoat-theme for variables.

[![Build Status](https://travis-ci.org/topcoat/button-bar.png?branch=master)](https://travis-ci.org/topcoat/button-bar)

[![NPM](https://nodei.co/npm/topcoat-button-bar.png)](https://nodei.co/npm/topcoat-button-bar/)