text:
require "pathname"
require "socket"
require "timeout"

require_relative "parent_process/client"
require_relative "parent_process/server"

module Delayed
  module WorkQueue
    # ParentProcess is a WorkQueue implementation that spawns a separate worker
    # process for querying the queue. Each Worker child process sends requests to
    # the ParentProcess via IPC, and receives responses. This centralized queue
    # querying cuts down on db queries and lock contention, and allows the
    # possibility for other centralized logic such as notifications when all workers
    # are idle.
    #
    # The IPC implementation uses Unix stream sockets and Ruby's built-in Marshal
    # functionality. The ParentProcess creates a Unix socket on the filesystem in
    # the tmp directory, so that if a worker process dies and is restarted it can
    # reconnect to the socket.
    #
    # While Unix and IP sockets are API compatible, we take a lot of shortcuts
    # because we know it's just a local Unix socket. If we ever wanted to swap this
    # out for a TCP/IP socket and have the WorkQueue running on another host, we'd
    # want to be a lot more robust about partial reads/writes and timeouts.
    class ParentProcess
      class ProtocolError < RuntimeError
      end

      attr_reader :server_address

      DEFAULT_SOCKET_NAME = "inst-jobs.sock"
      private_constant :DEFAULT_SOCKET_NAME

      def initialize(config = Settings.parent_process)
        @config = config
        @server_address = generate_socket_path(config["server_address"])
      end

      def server(parent_pid: nil)
        # The unix_server_socket method takes care of cleaning up any existing
        # socket for us if the work queue process dies and is restarted.
        listen_socket = Socket.unix_server_socket(@server_address)
        Server.new(listen_socket, parent_pid: parent_pid, config: @config)
      end

      def client
        Client.new(Addrinfo.unix(@server_address), config: @config)
      end

      private

      def generate_socket_path(supplied_path)
        pathname = Pathname.new(supplied_path)

        if pathname.absolute? && pathname.directory?
          pathname.join(DEFAULT_SOCKET_NAME).to_s
        elsif pathname.absolute?
          supplied_path
        else
          generate_socket_path(Settings.expand_rails_path(supplied_path))
        end
      end
    end
  end
end


text:
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.LogicalTree;
using Xunit;

namespace Avalonia.Controls.UnitTests
{
    public class HeaderedItemsControlTests
    {
        [Fact]
        public void Control_Header_Should_Be_Logical_Child_Before_ApplyTemplate()
        {
            var target = new HeaderedItemsControl
            {
                Template = GetTemplate(),
            };

            var child = new Control();
            target.Header = child;

            Assert.Equal(child.Parent, target);
            Assert.Equal(child.GetLogicalParent(), target);
            Assert.Equal(new[] { child }, target.GetLogicalChildren());
        }

        [Fact]
        public void DataTemplate_Created_Control_Should_Be_Logical_Child_After_ApplyTemplate()
        {
            var target = new HeaderedItemsControl
            {
                Template = GetTemplate(),
            };

            target.Header = "Foo";
            target.ApplyTemplate();
            target.HeaderPresenter.UpdateChild();

            var child = target.HeaderPresenter.Child;

            Assert.NotNull(child);
            Assert.Equal(target, child.Parent);
            Assert.Equal(target, child.GetLogicalParent());
            Assert.Equal(new[] { child }, target.GetLogicalChildren());
        }

        [Fact]
        public void Clearing_Content_Should_Clear_Logical_Child()
        {
            var target = new HeaderedItemsControl();
            var child = new Control();

            target.Header = child;
            target.Header = null;

            Assert.Null(child.Parent);
            Assert.Null(child.GetLogicalParent());
            Assert.Empty(target.GetLogicalChildren());
        }

        private FuncControlTemplate GetTemplate()
        {
            return new FuncControlTemplate<HeaderedItemsControl>(parent =>
            {
                return new Border
                {
                    Child = new ContentPresenter
                    {
                        Name = "PART_HeaderPresenter",
                        [~ContentPresenter.ContentProperty] = parent[~HeaderedItemsControl.HeaderProperty],
                    }
                };
            });
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
App = function() {
    return {
        init : function() {
            Ext.QuickTips.init();
            this.initStores();
            this.createScheduler();
            this.createCalendar();
        },

        initStores : function(){
            var today = new Date().clearTime();
            this.eventStore = new Ext.ensible.sample.MemoryEventStore({
                fields : [
                /* These fields are shared by both components: */
                    'EventId',
                    'ResourceId',
                    'Title',
                    'Location',
                {
                    name: 'StartDate', type: 'date', dateFormat: 'Y-m-d g:i'
                },{
                    name: 'EndDate', type: 'date', dateFormat: 'Y-m-d g:i'
                },
                /* These are specific to calendar events only, but still must be defined
                 * in the store or they won't be saved into the records from the form
                 */
                'IsAllDay', 'Reminder', 'Notes', 'Url'
                ],
                data: {
                    evts: [{
                        EventId: 100,
                        ResourceId: '1',
                        Title: 'Some task',
                        StartDate: today.add(Date.HOUR, 8),
                        EndDate: today.add(Date.HOUR, 16),
                        Location: 'Some office',
                        Reminder: '15'
                    },{
                        EventId: 101,
                        ResourceId: '2',
                        Title: 'Some other task',
                        StartDate: today.add(Date.HOUR, 24),
                        EndDate: today.add(Date.HOUR, 100),
                        Location: 'Home office'
                    },{
                        EventId: 102,
                        ResourceId: '3',
                        Title: 'A basic task',
                        StartDate: today.add(Date.HOUR, 72),
                        EndDate: today.add(Date.HOUR, 120),
                        Location: 'Customer office'
                    },{
                        EventId: 103,
                        ResourceId: '1',
                        Title: 'Another task',
                        StartDate: today.add(Date.HOUR, 110),
                        EndDate: today.add(Date.HOUR, 160),
                        Location: 'Austin'
                    }]
                }
            });

            var profileBase = 'scheduler/images/profiles/';

            this.resourceStore = new Ext.data.JsonStore({
                sortInfo:{field: 'Id', direction: "ASC"},
                idProperty : 'Id',
                fields : [
                    'Id',
                    'Name',
                    'Type',
                    'ImgUrl',
                    'ColorId', // used by calendar
                    'Color'    // used by scheduler
                ],
                data: [{
                    Id: '1', Name: 'Dave', Type: 'Engineering', ImgUrl: profileBase+'dave.jpg', ColorId: 1, Color: '#FA7166'
                },{
                    Id: '2', Name: 'Arnold', Type: 'Sales', ImgUrl: profileBase+'arnold.jpg', ColorId: 11, Color: '#9D3283'
                },{
                    Id: '3', Name: 'Lisa', Type: 'Product Manager', ImgUrl: profileBase+'lisa.jpg', ColorId: 21, Color: '#1A5173'
                }]
            });
        },

        createScheduler : function() {
            // Customize the scheduler date/time formatting
            Sch.BasicViewPresets.weekAndDay.headerConfig.middle.dateFormat = 'l, M d';
            Sch.BasicViewPresets.weekAndDay.headerConfig.bottom.dateFormat = 'n/d';
            Sch.BasicViewPresets.hourAndDay.headerConfig.top.dateFormat = 'l, M d';
            Sch.BasicViewPresets.hourAndDay.headerConfig.middle.dateFormat = 'g:i A';

            this.scheduler = new DemoScheduler({
                width: 1000,
                height: 200,
                renderTo : 'sched',
                resourceStore: this.resourceStore,
                eventStore: this.eventStore,
                viewPreset: 'weekAndDay'
            });
        },

        createCalendar : function(){
            // Remap some default calendar fields to match the scheduler
            var Cal = Ext.ensible.cal;
            Cal.EventMappings.CalendarId.name = 'ResourceId';
            Cal.EventRecord.reconfigure();

            Cal.CalendarMappings.CalendarId.name = 'Id';
            Cal.CalendarMappings.Title.name = 'Name';
            Cal.CalendarRecord.reconfigure();

            // Override the default calendar field labels to match the scheduler
            Ext.ensible.cal.EventEditWindow.prototype.calendarLabelText = 'Staff';
            Ext.ensible.cal.EventEditForm.prototype.calendarLabelText = 'Staff';

            this.calendar = new Cal.CalendarPanel({
                eventStore: this.eventStore,
                calendarStore: this.resourceStore,
                renderTo: 'cal',
                width: 1000,
                height: 400,
                activeItem: 1,
                editModal: true,
                showMonthView: false,
                viewConfig: {
                    startDay: 1
                }
            });
        }
    }
}();

Ext.onReady(App.init, App);


text:
<template name="party">

This would be the page for party: {{partyName}}

  <button id="delete">Delete</button>

  << Back Home
</template>


text:
<% var tmpComments = $AX(context.task.commentList.comment); %>
<% for (var i = 0; i<tmpComments.length; i++) { %>
<% var comment = tmpComments[i]; %>

<%= comment.commentator %>(<%= comment.updateDate %>)

<%= comment.contents.formatSimpleHTML() %>

<% } %>


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

#include "components/autofill/content/renderer/password_autofill_agent.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/i18n/case_conversion.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/content/common/autofill_messages.h"
#include "components/autofill/content/renderer/form_autofill_util.h"
#include "components/autofill/content/renderer/password_form_conversion_utils.h"
#include "components/autofill/content/renderer/renderer_save_password_progress_logger.h"
#include "components/autofill/core/common/autofill_constants.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/autofill/core/common/password_form.h"
#include "components/autofill/core/common/password_form_fill_data.h"
#include "content/public/renderer/document_state.h"
#include "content/public/renderer/navigation_state.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "third_party/WebKit/public/platform/WebVector.h"
#include "third_party/WebKit/public/web/WebAutofillClient.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebFormElement.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebNode.h"
#include "third_party/WebKit/public/web/WebNodeList.h"
#include "third_party/WebKit/public/web/WebSecurityOrigin.h"
#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "ui/base/page_transition_types.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "url/gurl.h"

namespace autofill {
namespace {

// The size above which we stop triggering autocomplete.
static const size_t kMaximumTextSizeForAutocomplete = 1000;

// Experiment information
const char kFillOnAccountSelectFieldTrialName[] = "FillOnAccountSelect";
const char kFillOnAccountSelectFieldTrialEnabledWithHighlightGroup[] =
    "EnableWithHighlight";
const char kFillOnAccountSelectFieldTrialEnabledWithNoHighlightGroup[] =
    "EnableWithNoHighlight";

// Maps element names to the actual elements to simplify form filling.
typedef std::map<base::string16, blink::WebInputElement> FormInputElementMap;

// Use the shorter name when referencing SavePasswordProgressLogger::StringID
// values to spare line breaks. The code provides enough context for that
// already.
typedef SavePasswordProgressLogger Logger;

// Utility struct for form lookup and autofill. When we parse the DOM to look up
// a form, in addition to action and origin URL's we have to compare all
// necessary form elements. To avoid having to look these up again when we want
// to fill the form, the FindFormElements function stores the pointers
// in a FormElements* result, referenced to ensure they are safe to use.
struct FormElements {
  blink::WebFormElement form_element;
  FormInputElementMap input_elements;
};

typedef std::vector<FormElements*> FormElementsList;

bool FillDataContainsUsername(const PasswordFormFillData& fill_data) {
  return !fill_data.username_field.name.empty();
}

// Utility function to find the unique entry of the |form_element| for the
// specified input |field|. On successful find, adds it to |result| and returns
// |true|. Otherwise clears the references from each |HTMLInputElement| from
// |result| and returns |false|.
bool FindFormInputElement(blink::WebFormElement* form_element,
                          const FormFieldData& field,
                          FormElements* result) {
  blink::WebVector<blink::WebNode> temp_elements;
  form_element->getNamedElements(field.name, temp_elements);

  // Match the first input element, if any.
  // |getNamedElements| may return non-input elements where the names match,
  // so the results are filtered for input elements.
  // If more than one match is made, then we have ambiguity (due to misuse
  // of "name" attribute) so is it considered not found.
  bool found_input = false;
  for (size_t i = 0; i < temp_elements.size(); ++i) {
    if (temp_elements[i].to<blink::WebElement>().hasHTMLTagName("input")) {
      // Check for a non-unique match.
      if (found_input) {
        found_input = false;
        break;
      }

      // Only fill saved passwords into password fields and usernames into
      // text fields.
      blink::WebInputElement input_element =
          temp_elements[i].to<blink::WebInputElement>();
      if (input_element.isPasswordField() !=
          (field.form_control_type == "password"))
        continue;

      // This element matched, add it to our temporary result. It's possible
      // there are multiple matches, but for purposes of identifying the form
      // one suffices and if some function needs to deal with multiple
      // matching elements it can get at them through the FormElement*.
      // Note: This assignment adds a reference to the InputElement.
      result->input_elements[field.name] = input_element;
      found_input = true;
    }
  }

  // A required element was not found. This is not the right form.
  // Make sure no input elements from a partially matched form in this
  // iteration remain in the result set.
  // Note: clear will remove a reference from each InputElement.
  if (!found_input) {
    result->input_elements.clear();
    return false;
  }

  return true;
}

bool ShouldFillOnAccountSelect() {
  std::string group_name =
      base::FieldTrialList::FindFullName(kFillOnAccountSelectFieldTrialName);

  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableFillOnAccountSelect)) {
    return false;
  }

  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableFillOnAccountSelect) ||
      base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableFillOnAccountSelectNoHighlighting)) {
    return true;
  }

  return group_name ==
             kFillOnAccountSelectFieldTrialEnabledWithHighlightGroup ||
         group_name ==
             kFillOnAccountSelectFieldTrialEnabledWithNoHighlightGroup;
}

bool ShouldHighlightFields() {
  std::string group_name =
      base::FieldTrialList::FindFullName(kFillOnAccountSelectFieldTrialName);
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableFillOnAccountSelect) ||
      base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableFillOnAccountSelect)) {
    return true;
  }

  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableFillOnAccountSelectNoHighlighting)) {
    return false;
  }

  return group_name !=
         kFillOnAccountSelectFieldTrialEnabledWithNoHighlightGroup;
}

// Helper to search the given form element for the specified input elements in
// |data|, and add results to |result|.
bool FindFormInputElements(blink::WebFormElement* form_element,
                           const PasswordFormFillData& data,
                           FormElements* result) {
  return FindFormInputElement(form_element, data.password_field, result) &&
         (!FillDataContainsUsername(data) ||
          FindFormInputElement(form_element, data.username_field, result));
}

// Helper to locate form elements identified by |data|.
void FindFormElements(content::RenderFrame* render_frame,
                      const PasswordFormFillData& data,
                      FormElementsList* results) {
  DCHECK(results);

  blink::WebDocument doc = render_frame->GetWebFrame()->document();
  if (!doc.isHTMLDocument())
    return;

  if (data.origin != GetCanonicalOriginForDocument(doc))
    return;

  blink::WebVector<blink::WebFormElement> forms;
  doc.forms(forms);

  for (size_t i = 0; i < forms.size(); ++i) {
    blink::WebFormElement fe = forms[i];

    // Action URL must match.
    if (data.action != GetCanonicalActionForForm(fe))
      continue;

    scoped_ptr<FormElements> curr_elements(new FormElements);
    if (!FindFormInputElements(&fe, data, curr_elements.get()))
      continue;

    // We found the right element.
    // Note: this assignment adds a reference to |fe|.
    curr_elements->form_element = fe;
    results->push_back(curr_elements.release());
  }
}

bool IsElementEditable(const blink::WebInputElement& element) {
  return element.isEnabled() && !element.isReadOnly();
}

bool DoUsernamesMatch(const base::string16& username1,
                      const base::string16& username2,
                      bool exact_match) {
  if (exact_match)
    return username1 == username2;
  return base::StartsWith(username1, username2, base::CompareCase::SENSITIVE);
}

// Returns |true| if the given element is editable. Otherwise, returns |false|.
bool IsElementAutocompletable(const blink::WebInputElement& element) {
  return IsElementEditable(element);
}

// Returns true if the password specified in |form| is a default value.
bool PasswordValueIsDefault(const base::string16& password_element,
                            const base::string16& password_value,
                            blink::WebFormElement form_element) {
  blink::WebVector<blink::WebNode> temp_elements;
  form_element.getNamedElements(password_element, temp_elements);

  // We are loose in our definition here and will return true if any of the
  // appropriately named elements match the element to be saved. Currently
  // we ignore filling passwords where naming is ambigious anyway.
  for (size_t i = 0; i < temp_elements.size(); ++i) {
    if (temp_elements[i].to<blink::WebElement>().getAttribute("value") ==
        password_value)
      return true;
  }
  return false;
}

// Return true if either password_value or new_password_value is not empty and
// not default.
bool FormContainsNonDefaultPasswordValue(const PasswordForm& password_form,
                                         blink::WebFormElement form_element) {
  return (!password_form.password_value.empty() &&
          !PasswordValueIsDefault(password_form.password_element,
                                  password_form.password_value,
                                  form_element)) ||
      (!password_form.new_password_value.empty() &&
       !PasswordValueIsDefault(password_form.new_password_element,
                               password_form.new_password_value,
                               form_element));
}

// Log a message including the name, method and action of |form|.
void LogHTMLForm(SavePasswordProgressLogger* logger,
                 SavePasswordProgressLogger::StringID message_id,
                 const blink::WebFormElement& form) {
  logger->LogHTMLForm(message_id,
                      form.name().utf8(),
                      GURL(form.action().utf8()));
}

// Returns true if there are any suggestions to be derived from |fill_data|.
// Unless |show_all| is true, only considers suggestions with usernames having
// |current_username| as a prefix.
bool CanShowSuggestion(const PasswordFormFillData& fill_data,
                       const base::string16& current_username,
                       bool show_all) {
  base::string16 current_username_lower = base::i18n::ToLower(current_username);
  for (const auto& usernames : fill_data.other_possible_usernames) {
    for (size_t i = 0; i < usernames.second.size(); ++i) {
      if (show_all ||
          base::StartsWith(
              base::i18n::ToLower(base::string16(usernames.second[i])),
              current_username_lower, base::CompareCase::SENSITIVE)) {
        return true;
      }
    }
  }

  if (show_all ||
      base::StartsWith(base::i18n::ToLower(fill_data.username_field.value),
                       current_username_lower, base::CompareCase::SENSITIVE)) {
    return true;
  }

  for (const auto& login : fill_data.additional_logins) {
    if (show_all ||
        base::StartsWith(base::i18n::ToLower(login.first),
                         current_username_lower,
                         base::CompareCase::SENSITIVE)) {
      return true;
    }
  }

  return false;
}

// Returns true if there exists a credential suggestion whose username field is
// an exact match to the current username (not just a prefix).
bool HasExactMatchSuggestion(const PasswordFormFillData& fill_data,
                             const base::string16& current_username) {
  if (fill_data.username_field.value == current_username)
    return true;

  for (const auto& usernames : fill_data.other_possible_usernames) {
    for (const auto& username_string : usernames.second) {
      if (username_string == current_username)
        return true;
    }
  }

  for (const auto& login : fill_data.additional_logins) {
    if (login.first == current_username)
      return true;
  }

  return false;
}

// This function attempts to fill |username_element| and |password_element|
// with values from |fill_data|. The |password_element| will only have the
// suggestedValue set, and will be registered for copying that to the real
// value through |registration_callback|. If a match is found, return true and
// |nonscript_modified_values| will be modified with the autofilled credentials.
bool FillUserNameAndPassword(
    blink::WebInputElement* username_element,
    blink::WebInputElement* password_element,
    const PasswordFormFillData& fill_data,
    bool exact_username_match,
    bool set_selection,
    std::map<const blink::WebInputElement, blink::WebString>*
        nonscript_modified_values,
    base::Callback<void(blink::WebInputElement*)> registration_callback) {
  // Don't fill username if password can't be set.
  if (!IsElementAutocompletable(*password_element))
    return false;

  base::string16 current_username;
  if (!username_element->isNull()) {
    current_username = username_element->value();
  }

  // username and password will contain the match found if any.
  base::string16 username;
  base::string16 password;

  // Look for any suitable matches to current field text.
  if (DoUsernamesMatch(fill_data.username_field.value, current_username,
                       exact_username_match)) {
    username = fill_data.username_field.value;
    password = fill_data.password_field.value;
  } else {
    // Scan additional logins for a match.
    PasswordFormFillData::LoginCollection::const_iterator iter;
    for (iter = fill_data.additional_logins.begin();
         iter != fill_data.additional_logins.end();
         ++iter) {
      if (DoUsernamesMatch(
              iter->first, current_username, exact_username_match)) {
        username = iter->first;
        password = iter->second.password;
        break;
      }
    }

    // Check possible usernames.
    if (username.empty() && password.empty()) {
      for (PasswordFormFillData::UsernamesCollection::const_iterator iter =
               fill_data.other_possible_usernames.begin();
           iter != fill_data.other_possible_usernames.end();
           ++iter) {
        for (size_t i = 0; i < iter->second.size(); ++i) {
          if (DoUsernamesMatch(
                  iter->second[i], current_username, exact_username_match)) {
            username = iter->second[i];
            password = iter->first.password;
            break;
          }
        }
        if (!username.empty() && !password.empty())
          break;
      }
    }
  }
  if (password.empty())
    return false;

  // TODO(tkent): Check maxlength and pattern for both username and password
  // fields.

  // Input matches the username, fill in required values.
  if (!username_element->isNull() &&
      IsElementAutocompletable(*username_element)) {
    username_element->setValue(username, true);
    (*nonscript_modified_values)[*username_element] = username;
    username_element->setAutofilled(true);

    if (set_selection) {
      username_element->setSelectionRange(current_username.length(),
                                          username.length());
    }
  } else if (current_username != username) {
    // If the username can't be filled and it doesn't match a saved password
    // as is, don't autofill a password.
    return false;
  }

  // Wait to fill in the password until a user gesture occurs. This is to make
  // sure that we do not fill in the DOM with a password until we believe the
  // user is intentionally interacting with the page.
  password_element->setSuggestedValue(password);
  (*nonscript_modified_values)[*password_element] = password;
  registration_callback.Run(password_element);

  password_element->setAutofilled(true);
  return true;
}

// Attempts to fill |username_element| and |password_element| with the
// |fill_data|. Will use the data corresponding to the preferred username,
// unless the |username_element| already has a value set. In that case,
// attempts to fill the password matching the already filled username, if
// such a password exists. The |password_element| will have the
// |suggestedValue| set, and |suggestedValue| will be registered for copying to
// the real value through |registration_callback|. Returns true if the password
// is filled.
bool FillFormOnPasswordReceived(
    const PasswordFormFillData& fill_data,
    blink::WebInputElement username_element,
    blink::WebInputElement password_element,
    std::map<const blink::WebInputElement, blink::WebString>*
        nonscript_modified_values,
    base::Callback<void(blink::WebInputElement*)> registration_callback) {
  // Do not fill if the password field is in a chain of iframes not having
  // identical origin.
  blink::WebFrame* cur_frame = password_element.document().frame();
  blink::WebString bottom_frame_origin =
          cur_frame->securityOrigin().toString();

  DCHECK(cur_frame);

  while (cur_frame->parent()) {
    cur_frame = cur_frame->parent();
    if (!bottom_frame_origin.equals(cur_frame->securityOrigin().toString()))
      return false;
  }

  // If we can't modify the password, don't try to set the username
  if (!IsElementAutocompletable(password_element))
    return false;

  bool form_contains_username_field = FillDataContainsUsername(fill_data);
  // If the form contains an autocompletable username field, try to set the
  // username to the preferred name, but only if:
  //   (a) The fill-on-account-select flag is not set, and
  //   (b) The username element isn't prefilled
  //
  // If (a) is false, then just mark the username element as autofilled if the
  // user is not in the "no highlighting" group and return so the fill step is
  // skipped.
  //
  // If there is no autocompletable username field, and (a) is false, then the
  // username element cannot be autofilled, but the user should still be able to
  // select to fill the password element, so the password element must be marked
  // as autofilled and the fill step should also be skipped if the user is not
  // in the "no highlighting" group.
  //
  // In all other cases, do nothing.
  bool form_has_fillable_username = form_contains_username_field &&
                                    IsElementAutocompletable(username_element);

  if (ShouldFillOnAccountSelect()) {
    if (!ShouldHighlightFields()) {
      return false;
    }

    if (form_has_fillable_username) {
      username_element.setAutofilled(true);
    } else if (username_element.isNull() ||
               HasExactMatchSuggestion(fill_data, username_element.value())) {
      password_element.setAutofilled(true);
    }
    return false;
  }

  if (form_has_fillable_username && username_element.value().isEmpty()) {
    // TODO(tkent): Check maxlength and pattern.
    username_element.setValue(fill_data.username_field.value, true);
  }

  // Fill if we have an exact match for the username. Note that this sets
  // username to autofilled.
  return FillUserNameAndPassword(&username_element,
                                 &password_element,
                                 fill_data,
                                 true /* exact_username_match */,
                                 false /* set_selection */,
                                 nonscript_modified_values,
                                 registration_callback);
}

// Takes a |map| with pointers as keys and linked_ptr as values, and returns
// true if |key| is not NULL and  |map| contains a non-NULL entry for |key|.
// Makes sure not to create an entry as a side effect of using the operator [].
template <class Key, class Value>
bool ContainsNonNullEntryForNonNullKey(
    const std::map<Key*, linked_ptr<Value>>& map,
    Key* key) {
  if (!key)
    return false;
  auto it = map.find(key);
  return it != map.end() && it->second.get();
}

// Helper function to check if there exist any form on |frame| where its action
// equals |action|. Return true if so.
bool IsFormVisible(
    blink::WebFrame* frame,
    GURL& action) {
  blink::WebVector<blink::WebFormElement> forms;
  frame->document().forms(forms);

  for (size_t i = 0; i < forms.size(); ++i) {
    const blink::WebFormElement& form = forms[i];
    if (!IsWebNodeVisible(form))
      continue;

    if (action == GetCanonicalActionForForm(form))
      return true; // Form still exists
  }

  return false;
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// PasswordAutofillAgent, public:

PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame)
    : content::RenderFrameObserver(render_frame),
      legacy_(render_frame->GetRenderView(), this),
      logging_state_active_(false),
      was_username_autofilled_(false),
      was_password_autofilled_(false),
      username_selection_start_(0),
      did_stop_loading_(false),
      weak_ptr_factory_(this) {
  Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id()));
}

PasswordAutofillAgent::~PasswordAutofillAgent() {
}

PasswordAutofillAgent::PasswordValueGatekeeper::PasswordValueGatekeeper()
    : was_user_gesture_seen_(false) {
}

PasswordAutofillAgent::PasswordValueGatekeeper::~PasswordValueGatekeeper() {
}

void PasswordAutofillAgent::PasswordValueGatekeeper::RegisterElement(
    blink::WebInputElement* element) {
  if (was_user_gesture_seen_)
    ShowValue(element);
  else
    elements_.push_back(*element);
}

void PasswordAutofillAgent::PasswordValueGatekeeper::OnUserGesture() {
  was_user_gesture_seen_ = true;

  for (std::vector<blink::WebInputElement>::iterator it = elements_.begin();
       it != elements_.end();
       ++it) {
    ShowValue(&(*it));
  }

  elements_.clear();
}

void PasswordAutofillAgent::PasswordValueGatekeeper::Reset() {
  was_user_gesture_seen_ = false;
  elements_.clear();
}

void PasswordAutofillAgent::PasswordValueGatekeeper::ShowValue(
    blink::WebInputElement* element) {
  if (!element->isNull() && !element->suggestedValue().isEmpty())
    element->setValue(element->suggestedValue(), true);
}

bool PasswordAutofillAgent::TextFieldDidEndEditing(
    const blink::WebInputElement& element) {
  LoginToPasswordInfoMap::const_iterator iter =
      login_to_password_info_.find(element);
  if (iter == login_to_password_info_.end())
    return false;

  const PasswordInfo& password_info = iter->second;
  // Don't let autofill overwrite an explicit change made by the user.
  if (password_info.password_was_edited_last)
    return false;

  const PasswordFormFillData& fill_data = password_info.fill_data;

  // If wait_for_username is false, we should have filled when the text changed.
  if (!fill_data.wait_for_username)
    return false;

  blink::WebInputElement password = password_info.password_field;
  if (!IsElementEditable(password))
    return false;

  blink::WebInputElement username = element;  // We need a non-const.

  // Do not set selection when ending an editing session, otherwise it can
  // mess with focus.
  FillUserNameAndPassword(
      &username, &password, fill_data, true, false,
      &nonscript_modified_values_,
      base::Bind(&PasswordValueGatekeeper::RegisterElement,
                 base::Unretained(&gatekeeper_)));
  return true;
}

bool PasswordAutofillAgent::TextDidChangeInTextField(
    const blink::WebInputElement& element) {
  // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
  blink::WebInputElement mutable_element = element;  // We need a non-const.

  LoginToPasswordInfoMap::iterator iter = login_to_password_info_.find(element);
  if (iter == login_to_password_info_.end())
    return false;

  mutable_element.setAutofilled(false);
  iter->second.password_was_edited_last = false;

  // If wait_for_username is true we will fill when the username loses focus.
  if (iter->second.fill_data.wait_for_username)
    return false;

  if (!element.isText() || !IsElementAutocompletable(element) ||
      !IsElementAutocompletable(iter->second.password_field)) {
    return false;
  }

  if (element.nameForAutofill().isEmpty())
    return false;  // If the field has no name, then we won't have values.

  // Don't attempt to autofill with values that are too large.
  if (element.value().length() > kMaximumTextSizeForAutocomplete)
    return false;

  // Show the popup with the list of available usernames.
  ShowSuggestionPopup(iter->second.fill_data, element, false, false);
  return true;
}

void PasswordAutofillAgent::UpdateStateForTextChange(
    const blink::WebInputElement& element) {
  // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
  blink::WebInputElement mutable_element = element;  // We need a non-const.

  if (element.isTextField())
    nonscript_modified_values_[element] = element.value();

  LoginToPasswordInfoMap::iterator password_info_iter =
      login_to_password_info_.find(element);
  if (password_info_iter != login_to_password_info_.end()) {
    password_info_iter->second.username_was_edited = true;
  }

  DCHECK_EQ(element.document().frame(), render_frame()->GetWebFrame());

  if (element.isPasswordField()) {
    // Some login forms have event handlers that put a hash of the password into
    // a hidden field and then clear the password (http://crbug.com/28910,
    // http://crbug.com/391693). This method gets called before any of those
    // handlers run, so save away a copy of the password in case it gets lost.
    // To honor the user having explicitly cleared the password, even an empty
    // password will be saved here.
    ProvisionallySavePassword(element.form(), RESTRICTION_NONE);

    PasswordToLoginMap::iterator iter = password_to_username_.find(element);
    if (iter != password_to_username_.end()) {
      login_to_password_info_[iter->second].password_was_edited_last = true;
      // Note that the suggested value of |mutable_element| was reset when its
      // value changed.
      mutable_element.setAutofilled(false);
    }
  }
}

bool PasswordAutofillAgent::FillSuggestion(
    const blink::WebNode& node,
    const blink::WebString& username,
    const blink::WebString& password) {
  // The element in context of the suggestion popup.
  blink::WebInputElement filled_element;
  PasswordInfo* password_info;

  if (!FindLoginInfo(node, &filled_element, &password_info) ||
      !IsElementAutocompletable(filled_element) ||
      !IsElementAutocompletable(password_info->password_field)) {
    return false;
  }

  password_info->password_was_edited_last = false;
  // Note that in cases where filled_element is the password element, the value
  // gets overwritten with the correct one below.
  filled_element.setValue(username, true);
  filled_element.setAutofilled(true);

  password_info->password_field.setValue(password, true);
  password_info->password_field.setAutofilled(true);

  filled_element.setSelectionRange(filled_element.value().length(),
                                   filled_element.value().length());

  return true;
}

bool PasswordAutofillAgent::PreviewSuggestion(
    const blink::WebNode& node,
    const blink::WebString& username,
    const blink::WebString& password) {
  blink::WebInputElement username_element;
  PasswordInfo* password_info;

  if (!FindLoginInfo(node, &username_element, &password_info) ||
      !IsElementAutocompletable(username_element) ||
      !IsElementAutocompletable(password_info->password_field)) {
    return false;
  }

  was_username_autofilled_ = username_element.isAutofilled();
  username_selection_start_ = username_element.selectionStart();
  username_element.setSuggestedValue(username);
  username_element.setAutofilled(true);
  username_element.setSelectionRange(
      username_selection_start_,
      username_element.suggestedValue().length());

  was_password_autofilled_ = password_info->password_field.isAutofilled();
  password_info->password_field.setSuggestedValue(password);
  password_info->password_field.setAutofilled(true);

  return true;
}

bool PasswordAutofillAgent::DidClearAutofillSelection(
    const blink::WebNode& node) {
  blink::WebInputElement username_element;
  PasswordInfo* password_info;
  if (!FindLoginInfo(node, &username_element, &password_info))
    return false;

  ClearPreview(&username_element, &password_info->password_field);
  return true;
}

bool PasswordAutofillAgent::FindPasswordInfoForElement(
    const blink::WebInputElement& element,
    const blink::WebInputElement** username_element,
    PasswordInfo** password_info) {
  DCHECK(username_element && password_info);
  if (!element.isPasswordField()) {
    *username_element = &element;
  } else {
    PasswordToLoginMap::const_iterator password_iter =
        password_to_username_.find(element);
    if (password_iter == password_to_username_.end())
      return false;
    *username_element = &password_iter->second;
  }

  LoginToPasswordInfoMap::iterator iter =
      login_to_password_info_.find(**username_element);

  if (iter == login_to_password_info_.end())
    return false;

  *password_info = &iter->second;
  return true;
}

bool PasswordAutofillAgent::ShowSuggestions(
    const blink::WebInputElement& element,
    bool show_all,
    bool generation_popup_showing) {
  const blink::WebInputElement* username_element;
  PasswordInfo* password_info;
  if (!FindPasswordInfoForElement(element, &username_element, &password_info))
    return false;

  // If autocomplete='off' is set on the form elements, no suggestion dialog
  // should be shown. However, return |true| to indicate that this is a known
  // password form and that the request to show suggestions has been handled (as
  // a no-op).
  if (!IsElementAutocompletable(element) ||
      !IsElementAutocompletable(password_info->password_field))
    return true;

  bool username_is_available =
      !username_element->isNull() && IsElementEditable(*username_element);
  // If the element is a password field, a popup should only be shown if there
  // is no username or the corresponding username element is not editable since
  // it is only in that case that the username element does not have a
  // suggestions popup.
  if (element.isPasswordField() && username_is_available &&
      (!password_info->fill_data.is_possible_change_password_form ||
       password_info->username_was_edited))
    return true;

  UMA_HISTOGRAM_BOOLEAN(
      "PasswordManager.AutocompletePopupSuppressedByGeneration",
      generation_popup_showing);

  if (generation_popup_showing)
    return false;

  // Chrome should never show more than one account for a password element since
  // this implies that the username element cannot be modified. Thus even if
  // |show_all| is true, check if the element in question is a password element
  // for the call to ShowSuggestionPopup.
  return ShowSuggestionPopup(
      password_info->fill_data,
      username_element->isNull() ? element : *username_element,
      show_all && !element.isPasswordField(), element.isPasswordField());
}

bool PasswordAutofillAgent::OriginCanAccessPasswordManager(
    const blink::WebSecurityOrigin& origin) {
  return origin.canAccessPasswordManager();
}

void PasswordAutofillAgent::OnDynamicFormsSeen() {
  SendPasswordForms(false /* only_visible */);
}

void PasswordAutofillAgent::AJAXSucceeded() {
  OnSamePageNavigationCompleted();
}

void PasswordAutofillAgent::OnSamePageNavigationCompleted() {
  if (!ProvisionallySavedPasswordIsValid())
    return;
  blink::WebFrame* frame = render_frame()->GetWebFrame();

  // Prompt to save only if the form is now gone, either invisible or
  // removed from the DOM.
  if (IsFormVisible(frame, provisionally_saved_form_->action))
    return;

  Send(new AutofillHostMsg_InPageNavigation(routing_id(),
                                            *provisionally_saved_form_));
  provisionally_saved_form_.reset();
}

void PasswordAutofillAgent::FirstUserGestureObserved() {
  gatekeeper_.OnUserGesture();
}

void PasswordAutofillAgent::SendPasswordForms(bool only_visible) {
  scoped_ptr<RendererSavePasswordProgressLogger> logger;
  if (logging_state_active_) {
    logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
    logger->LogMessage(Logger::STRING_SEND_PASSWORD_FORMS_METHOD);
    logger->LogBoolean(Logger::STRING_ONLY_VISIBLE, only_visible);
  }

  blink::WebFrame* frame = render_frame()->GetWebFrame();
  // Make sure that this security origin is allowed to use password manager.
  blink::WebSecurityOrigin origin = frame->document().securityOrigin();
  if (logger) {
    logger->LogURL(Logger::STRING_SECURITY_ORIGIN,
                   GURL(origin.toString().utf8()));
  }
  if (!OriginCanAccessPasswordManager(origin)) {
    if (logger) {
      logger->LogMessage(Logger::STRING_SECURITY_ORIGIN_FAILURE);
    }
    return;
  }

  // Checks whether the webpage is a redirect page or an empty page.
  if (IsWebpageEmpty(frame)) {
    if (logger) {
      logger->LogMessage(Logger::STRING_WEBPAGE_EMPTY);
    }
    return;
  }

  blink::WebVector<blink::WebFormElement> forms;
  frame->document().forms(forms);
  if (logger)
    logger->LogNumber(Logger::STRING_NUMBER_OF_ALL_FORMS, forms.size());

  std::vector<PasswordForm> password_forms;
  for (size_t i = 0; i < forms.size(); ++i) {
    const blink::WebFormElement& form = forms[i];
    if (only_visible) {
      bool is_form_visible = IsWebNodeVisible(form);
      if (logger) {
        LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE, form);
        logger->LogBoolean(Logger::STRING_FORM_IS_VISIBLE, is_form_visible);
      }

      // If requested, ignore non-rendered forms, e.g., those styled with
      // display:none.
      if (!is_form_visible)
        continue;
    }

    scoped_ptr<PasswordForm> password_form(
        CreatePasswordForm(form, nullptr, &form_predictions_));
    if (password_form.get()) {
      if (logger) {
        logger->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD,
                                *password_form);
      }
      password_forms.push_back(*password_form);
    }
  }

  if (password_forms.empty() && !only_visible) {
    // We need to send the PasswordFormsRendered message regardless of whether
    // there are any forms visible, as this is also the code path that triggers
    // showing the infobar.
    return;
  }

  if (only_visible) {
    Send(new AutofillHostMsg_PasswordFormsRendered(routing_id(),
                                                   password_forms,
                                                   did_stop_loading_));
  } else {
    Send(new AutofillHostMsg_PasswordFormsParsed(routing_id(), password_forms));
  }
}

bool PasswordAutofillAgent::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PasswordAutofillAgent, message)
    IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordForm, OnFillPasswordForm)
    IPC_MESSAGE_HANDLER(AutofillMsg_SetLoggingState, OnSetLoggingState)
    IPC_MESSAGE_HANDLER(AutofillMsg_AutofillUsernameAndPasswordDataReceived,
                        OnAutofillUsernameAndPasswordDataReceived)
    IPC_MESSAGE_HANDLER(AutofillMsg_FindFocusedPasswordForm,
                        OnFindFocusedPasswordForm)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void PasswordAutofillAgent::DidFinishDocumentLoad() {
  // The |frame| contents have been parsed, but not yet rendered.  Let the
  // PasswordManager know that forms are loaded, even though we can't yet tell
  // whether they're visible.
  SendPasswordForms(false);
}

void PasswordAutofillAgent::DidFinishLoad() {
  // The |frame| contents have been rendered.  Let the PasswordManager know
  // which of the loaded frames are actually visible to the user.  This also
  // triggers the "Save password?" infobar if the user just submitted a password
  // form.
  SendPasswordForms(true);
}

void PasswordAutofillAgent::FrameWillClose() {
  FrameClosing();
}

void PasswordAutofillAgent::DidCommitProvisionalLoad(
    bool is_new_navigation, bool is_same_page_navigation) {
  blink::WebFrame* frame = render_frame()->GetWebFrame();
  // TODO(dvadym): check if we need to check if it is main frame navigation
  // http://crbug.com/443155
  if (frame->parent())
    return; // Not a top-level navigation.

  if (is_same_page_navigation) {
    OnSamePageNavigationCompleted();
  }
}

void PasswordAutofillAgent::DidStartLoading() {
  did_stop_loading_ = false;
}

void PasswordAutofillAgent::DidStopLoading() {
  did_stop_loading_ = true;
}

void PasswordAutofillAgent::FrameDetached() {
  // If a sub frame has been destroyed while the user was entering information
  // into a password form, try to save the data. See https://crbug.com/450806
  // for examples of sites that perform login using this technique.
  if (render_frame()->GetWebFrame()->parent() &&
      ProvisionallySavedPasswordIsValid()) {
    Send(new AutofillHostMsg_InPageNavigation(routing_id(),
                                              *provisionally_saved_form_));
  }
  FrameClosing();
}

void PasswordAutofillAgent::WillSendSubmitEvent(
    const blink::WebFormElement& form) {
  // Forms submitted via XHR are not seen by WillSubmitForm if the default
  // onsubmit handler is overridden. Such submission first gets detected in
  // DidStartProvisionalLoad, which no longer knows about the particular form,
  // and uses the candidate stored in |provisionally_saved_form_|.
  //
  // User-typed password will get stored to |provisionally_saved_form_| in
  // TextDidChangeInTextField. Autofilled or JavaScript-copied passwords need to
  // be saved here.
  //
  // Only non-empty passwords are saved here. Empty passwords were likely
  // cleared by some scripts (http://crbug.com/28910, http://crbug.com/391693).
  // Had the user cleared the password, |provisionally_saved_form_| would
  // already have been updated in TextDidChangeInTextField.
  ProvisionallySavePassword(form, RESTRICTION_NON_EMPTY_PASSWORD);
}

void PasswordAutofillAgent::WillSubmitForm(const blink::WebFormElement& form) {
  scoped_ptr<RendererSavePasswordProgressLogger> logger;
  if (logging_state_active_) {
    logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
    logger->LogMessage(Logger::STRING_WILL_SUBMIT_FORM_METHOD);
    LogHTMLForm(logger.get(), Logger::STRING_HTML_FORM_FOR_SUBMIT, form);
  }

  scoped_ptr<PasswordForm> submitted_form =
      CreatePasswordForm(form, &nonscript_modified_values_, &form_predictions_);

  // If there is a provisionally saved password, copy over the previous
  // password value so we get the user's typed password, not the value that
  // may have been transformed for submit.
  // TODO(gcasto): Do we need to have this action equality check? Is it trying
  // to prevent accidentally copying over passwords from a different form?
  if (submitted_form) {
    if (logger) {
      logger->LogPasswordForm(Logger::STRING_CREATED_PASSWORD_FORM,
                              *submitted_form);
    }
    if (provisionally_saved_form_ &&
        submitted_form->action == provisionally_saved_form_->action) {
      if (logger)
        logger->LogMessage(Logger::STRING_SUBMITTED_PASSWORD_REPLACED);
      submitted_form->password_value =
          provisionally_saved_form_->password_value;
      submitted_form->new_password_value =
          provisionally_saved_form_->new_password_value;
      submitted_form->username_value =
          provisionally_saved_form_->username_value;
    }

    // Some observers depend on sending this information now instead of when
    // the frame starts loading. If there are redirects that cause a new
    // RenderView to be instantiated (such as redirects to the WebStore)
    // we will never get to finish the load.
    Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
                                                   *submitted_form));
    provisionally_saved_form_.reset();
  } else if (logger) {
    logger->LogMessage(Logger::STRING_FORM_IS_NOT_PASSWORD);
  }
}

void PasswordAutofillAgent::LegacyDidStartProvisionalLoad(
    blink::WebLocalFrame* navigated_frame) {
  scoped_ptr<RendererSavePasswordProgressLogger> logger;
  if (logging_state_active_) {
    logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
    logger->LogMessage(Logger::STRING_DID_START_PROVISIONAL_LOAD_METHOD);
  }

  if (navigated_frame->parent()) {
    if (logger)
      logger->LogMessage(Logger::STRING_FRAME_NOT_MAIN_FRAME);
    return;
  }

  // Bug fix for crbug.com/368690. isProcessingUserGesture() is false when
  // the user is performing actions outside the page (e.g. typed url,
  // history navigation). We don't want to trigger saving in these cases.
  content::DocumentState* document_state =
      content::DocumentState::FromDataSource(
          navigated_frame->provisionalDataSource());
  content::NavigationState* navigation_state =
      document_state->navigation_state();
  ui::PageTransition type = navigation_state->GetTransitionType();
  if (ui::PageTransitionIsWebTriggerable(type) &&
      ui::PageTransitionIsNewNavigation(type) &&
      !blink::WebUserGestureIndicator::isProcessingUserGesture()) {
    // If onsubmit has been called, try and save that form.
    if (provisionally_saved_form_) {
      if (logger) {
        logger->LogPasswordForm(
            Logger::STRING_PROVISIONALLY_SAVED_FORM_FOR_FRAME,
            *provisionally_saved_form_);
      }
      Send(new AutofillHostMsg_PasswordFormSubmitted(
          routing_id(), *provisionally_saved_form_));
      provisionally_saved_form_.reset();
    } else {
      // Loop through the forms on the page looking for one that has been
      // filled out. If one exists, try and save the credentials.
      blink::WebVector<blink::WebFormElement> forms;
      render_frame()->GetWebFrame()->document().forms(forms);

      bool password_forms_found = false;
      for (size_t i = 0; i < forms.size(); ++i) {
        blink::WebFormElement form_element = forms[i];
        if (logger) {
          LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE,
                      form_element);
        }
        scoped_ptr<PasswordForm> password_form(CreatePasswordForm(
            form_element, &nonscript_modified_values_, &form_predictions_));
        if (password_form.get() && !password_form->username_value.empty() &&
            FormContainsNonDefaultPasswordValue(*password_form, form_element)) {
          password_forms_found = true;
          if (logger) {
            logger->LogPasswordForm(Logger::STRING_PASSWORD_FORM_FOUND_ON_PAGE,
                                    *password_form);
          }
          Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
                                                         *password_form));
        }
      }
      if (!password_forms_found && logger)
        logger->LogMessage(Logger::STRING_PASSWORD_FORM_NOT_FOUND_ON_PAGE);
    }
  }

  // This is a new navigation, so require a new user gesture before filling in
  // passwords.
  gatekeeper_.Reset();
}

void PasswordAutofillAgent::OnFillPasswordForm(
    int key,
    const PasswordFormFillData& form_data) {

  FormElementsList forms;
  // We own the FormElements* in forms.
  FindFormElements(render_frame(), form_data, &forms);
  FormElementsList::iterator iter;
  for (iter = forms.begin(); iter != forms.end(); ++iter) {
    scoped_ptr<FormElements> form_elements(*iter);

    // Attach autocomplete listener to enable selecting alternate logins.
    blink::WebInputElement username_element, password_element;

    // Check whether the password form has a username input field.
    bool form_contains_username_field = FillDataContainsUsername(form_data);
    if (form_contains_username_field) {
      username_element =
          form_elements->input_elements[form_data.username_field.name];
    }

    // No password field, bail out.
    if (form_data.password_field.name.empty())
      break;

    // We might have already filled this form if there are two <form> elements
    // with identical markup.
    if (login_to_password_info_.find(username_element) !=
        login_to_password_info_.end())
      continue;

    // Get pointer to password element. (We currently only support single
    // password forms).
    password_element =
        form_elements->input_elements[form_data.password_field.name];

    // If wait_for_username is true, we don't want to initially fill the form
    // until the user types in a valid username.
    if (!form_data.wait_for_username) {
      FillFormOnPasswordReceived(
          form_data,
          username_element,
          password_element,
          &nonscript_modified_values_,
          base::Bind(&PasswordValueGatekeeper::RegisterElement,
                     base::Unretained(&gatekeeper_)));
    }

    PasswordInfo password_info;
    password_info.fill_data = form_data;
    password_info.password_field = password_element;
    login_to_password_info_[username_element] = password_info;
    password_to_username_[password_element] = username_element;
    login_to_password_info_key_[username_element] = key;
  }
}

void PasswordAutofillAgent::OnSetLoggingState(bool active) {
  logging_state_active_ = active;
}

void PasswordAutofillAgent::OnAutofillUsernameAndPasswordDataReceived(
    const FormsPredictionsMap& predictions) {
  form_predictions_ = predictions;
}

void PasswordAutofillAgent::OnFindFocusedPasswordForm() {
  scoped_ptr<PasswordForm> password_form;

  blink::WebElement element = render_frame()->GetFocusedElement();
  if (!element.isNull() && element.hasHTMLTagName("input")) {
    blink::WebInputElement input = element.to<blink::WebInputElement>();
    if (input.isPasswordField() && !input.form().isNull()) {
      password_form = CreatePasswordForm(
          input.form(), &nonscript_modified_values_, &form_predictions_);
    }
  }

  if (!password_form.get())
    password_form.reset(new PasswordForm());

  Send(new AutofillHostMsg_FocusedPasswordFormFound(
      routing_id(), *password_form));
}

////////////////////////////////////////////////////////////////////////////////
// PasswordAutofillAgent, private:

PasswordAutofillAgent::PasswordInfo::PasswordInfo()
    : password_was_edited_last(false),
      username_was_edited(false) {
}

bool PasswordAutofillAgent::ShowSuggestionPopup(
    const PasswordFormFillData& fill_data,
    const blink::WebInputElement& user_input,
    bool show_all,
    bool show_on_password_field) {
  DCHECK(!user_input.isNull());
  blink::WebFrame* frame = user_input.document().frame();
  if (!frame)
    return false;

  blink::WebView* webview = frame->view();
  if (!webview)
    return false;

  FormData form;
  FormFieldData field;
  FindFormAndFieldForFormControlElement(user_input, &form, &field);

  blink::WebInputElement selected_element = user_input;
  if (show_on_password_field && !selected_element.isPasswordField()) {
    LoginToPasswordInfoMap::const_iterator iter =
        login_to_password_info_.find(user_input);
    DCHECK(iter != login_to_password_info_.end());
    selected_element = iter->second.password_field;
  }
  gfx::Rect bounding_box(selected_element.boundsInViewportSpace());

  blink::WebInputElement username;
  if (!show_on_password_field || !user_input.isPasswordField()) {
    username = user_input;
  }
  LoginToPasswordInfoKeyMap::const_iterator key_it =
      login_to_password_info_key_.find(username);
  DCHECK(key_it != login_to_password_info_key_.end());

  float scale =
      render_frame()->GetRenderView()->GetWebView()->pageScaleFactor();
  gfx::RectF bounding_box_scaled(bounding_box.x() * scale,
                                 bounding_box.y() * scale,
                                 bounding_box.width() * scale,
                                 bounding_box.height() * scale);
  int options = 0;
  if (show_all)
    options |= SHOW_ALL;
  if (show_on_password_field)
    options |= IS_PASSWORD_FIELD;
  base::string16 username_string(
      username.isNull() ? base::string16()
                        : static_cast<base::string16>(user_input.value()));
  Send(new AutofillHostMsg_ShowPasswordSuggestions(
      routing_id(), key_it->second, field.text_direction, username_string,
      options, bounding_box_scaled));
  return CanShowSuggestion(fill_data, username_string, show_all);
}

void PasswordAutofillAgent::FrameClosing() {
  for (auto const& iter : login_to_password_info_) {
    login_to_password_info_key_.erase(iter.first);
    password_to_username_.erase(iter.second.password_field);
  }
  login_to_password_info_.clear();
  provisionally_saved_form_.reset();
  nonscript_modified_values_.clear();
}

bool PasswordAutofillAgent::FindLoginInfo(const blink::WebNode& node,
                                          blink::WebInputElement* found_input,
                                          PasswordInfo** found_password) {
  if (!node.isElementNode())
    return false;

  blink::WebElement element = node.toConst<blink::WebElement>();
  if (!element.hasHTMLTagName("input"))
    return false;

  *found_input = element.to<blink::WebInputElement>();
  const blink::WebInputElement* username_element;  // ignored
  return FindPasswordInfoForElement(*found_input, &username_element,
                                    found_password);
}

void PasswordAutofillAgent::ClearPreview(
    blink::WebInputElement* username,
    blink::WebInputElement* password) {
  if (!username->suggestedValue().isEmpty()) {
    username->setSuggestedValue(blink::WebString());
    username->setAutofilled(was_username_autofilled_);
    username->setSelectionRange(username_selection_start_,
                                username->value().length());
  }
  if (!password->suggestedValue().isEmpty()) {
      password->setSuggestedValue(blink::WebString());
      password->setAutofilled(was_password_autofilled_);
  }
}

void PasswordAutofillAgent::ProvisionallySavePassword(
    const blink::WebFormElement& form,
    ProvisionallySaveRestriction restriction) {
  scoped_ptr<PasswordForm> password_form(CreatePasswordForm(
      form, &nonscript_modified_values_, &form_predictions_));
  if (!password_form || (restriction == RESTRICTION_NON_EMPTY_PASSWORD &&
                         password_form->password_value.empty() &&
                         password_form->new_password_value.empty())) {
    return;
  }
  provisionally_saved_form_ = password_form.Pass();
}

bool PasswordAutofillAgent::ProvisionallySavedPasswordIsValid() {
   return provisionally_saved_form_ &&
       !provisionally_saved_form_->username_value.empty() &&
       !(provisionally_saved_form_->password_value.empty() &&
         provisionally_saved_form_->new_password_value.empty());
}

// LegacyPasswordAutofillAgent -------------------------------------------------

PasswordAutofillAgent::LegacyPasswordAutofillAgent::LegacyPasswordAutofillAgent(
    content::RenderView* render_view,
    PasswordAutofillAgent* agent)
    : content::RenderViewObserver(render_view), agent_(agent) {
}

PasswordAutofillAgent::LegacyPasswordAutofillAgent::
    ~LegacyPasswordAutofillAgent() {
}

void PasswordAutofillAgent::LegacyPasswordAutofillAgent::OnDestruct() {
  // No op. Do not delete |this|.
}

void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStartLoading() {
  agent_->DidStartLoading();
}

void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStopLoading() {
  agent_->DidStopLoading();
}

void PasswordAutofillAgent::LegacyPasswordAutofillAgent::
    DidStartProvisionalLoad(blink::WebLocalFrame* navigated_frame) {
  agent_->LegacyDidStartProvisionalLoad(navigated_frame);
}

}  // namespace autofill


text:
/**
 * @stable
 */
export class RouterOutletMap {
    constructor() {
        /** @internal */
        this._outlets = {};
    }
    registerOutlet(name, outlet) { this._outlets[name] = outlet; }
}
//# sourceMappingURL=router_outlet_map.js.map


text:
Basket = {
    'selector':{
        'productItemContainer':'._product-list',
        'productItem':'._product-item',
        'count':'._basket-count',
        'checkbox':'._product-checkbox',
        'counterValue':'._counter-value',
        'orderForm':'._order-form',
        'orderItem':'._order-item',
        'orderItemJs':'_order-item',
        'orderClass':'OrderItem'
    },
    'items':[],
    'init':function(){
        Basket.calculate();
    },
    'minus':function(element,min){
        var element = $(element);
        var counterElement = element.next('span').find(Basket.selector.counterValue);
        var counterValue = parseInt(counterElement.val());
        if((counterValue-1) <= min)
            counterValue = min;
        else
            counterValue-=1;
        counterElement.val(counterValue);
        Basket.calculate();
    },
    'plus':function(element){
        var element = $(element);
        var counterElement = element.prev('span').find(Basket.selector.counterValue);
        var counterValue = parseInt(counterElement.val());
        counterValue++;
        counterElement.val(counterValue);
        Basket.calculate();
    },
    'select':function()
    {
        Basket.calculate();
    },
    'calculate':function(){
        var total = {
            'count':0,
            'price':0
        };
        $(Basket.selector.orderForm+' '+Basket.selector.orderItem).remove();

        var i = 0;
        $(Basket.selector.productItemContainer+' ' +Basket.selector.productItem).each(function(){
            var element = this;

            var productId = $(element).data("product-id");
            var checkbox = $(Basket.selector.checkbox,element);

            if(checkbox.prop('checked'))
            {
                var countElement = $(Basket.selector.counterValue,element);
                var count = countElement.val();
                total.count += parseInt(count);

                $("<input>",{
                    'type':'hidden',
                    'value':productId,
                    'name':Basket.selector.orderClass+'['+i+'][productId]',
                    'class':Basket.selector.orderItemJs
                }).appendTo(Basket.selector.orderForm);

                $("<input>",{
                    'type':'hidden',
                    'value':count,
                    'name':Basket.selector.orderClass+'['+i+'][quantity]',
                    'class':Basket.selector.orderItemJs
                }).appendTo(Basket.selector.orderForm);

                i++;
            }
        });
        $(Basket.selector.count).text(total.count);
    }
};

$(function(){
    $("._sparesOrder").click(function () {
        var elem = $(this);
        $("#sparesorder-productid").val(elem.data("id"));
    });
});


text:
<?php

namespace Application\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * @ORM\Entity
 */
class CollectionElementTranslation
{
    use ORMBehaviors\Translatable\Translation;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $info;

    /**
     * Set name
     *
     * @param string $name
     *
     * @return CollectionElement
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set info
     *
     * @param string $info
     *
     * @return CollectionElement
     */
    public function setInfo($info)
    {
        $this->info = $info;

        return $this;
    }

    /**
     * Get info
     *
     * @return string
     */
    public function getInfo()
    {
        return $this->info;
    }
}


text:
import logging
import unittest

"""Dominator (https://codility.com/demo/take-sample-test/dominator/)

Analysis:
    - Find leader in O(N) and count_of_leader (https://codility.com/media/train/6-Leader.pdf)
    - Validate if it's more than half, return index
"""

__author__ = 'au9ustine'
logging.basicConfig(format='%(message)s', level=logging.DEBUG)

def solution(A):
    candidate_val = -1
    count_of_candidate = 0
    candidate_idx = -1
    for i, val in enumerate(A):
        if count_of_candidate == 0:
            candidate_idx = i
            candidate_val = val
            count_of_candidate += 1
        else:
            if val != candidate_val:
                count_of_candidate -= 1
            else:
                count_of_candidate += 1
    count_of_leader = len([val for val in A if val == candidate_val])
    if count_of_leader <= len(A) // 2:
        return -1
    return candidate_idx

class SolutionTest(unittest.TestCase):

    def setUp(self):
        self.data = [
            ([3, 4, 3, 2, 3, -1, 3, 3], 6)
        ]

    def test_solution(self):
        for input_data, expected in self.data:
            actual = solution(input_data)
            self.assertEquals(expected, actual)

if __name__ == "__main__":
    unittest.main(failfast=True)


text:
import httplib

from cors import constants

class ResponseState(object):
    """Indicates how the response should behave."""

    END = 1  # The response should end. Do not pass go. Do not collect $200.
    CONTINUE = 2  # The response should continue to the downstream handlers.

class HttpResponse(object):
    """Stores the CORS-specific response details.

    This class contains any response headers that should be set on the response
    as well as a state property, which indicates whether the request should
    continue or end. If the response ends, the status property indicates the
    recommended HTTP status code for the response.
    """
    def __init__(self):
        self.headers = {}
        self.state = ResponseState.CONTINUE
        # '200 OK'
        self.status = '%s %s' % (httplib.OK, httplib.responses[httplib.OK])
        self.error = None

    def end(self, error=None):
        if error:
            self.status = error.status
            self.error = error
        self.state = ResponseState.END

def create(request, response, error=None):
    """Creates a new HttpResponse instance.

    Args:
      request (CorsRequest) - The request details.
      response (CorsResponse) - The response details.
      error (CorsException) - The error (if any). Defaults to None.
    """
    http_response = HttpResponse()

    # Set any generic response headers (such as Vary).
    for key, value in response.headers.items():
        http_response.headers[key] = value

    if error:
        # If there is an error, return immediately, do not set any
        # CORS-specific headers.
        http_response.end(error)
        return http_response

    # The Access-Control-Allow-Origin and Access-Control-Allow-Credentials are
    # set on both CORS and preflight responses.
    if response.allow_origin:
        http_response.headers[constants.ACCESS_CONTROL_ALLOW_ORIGIN] = \
            response.allow_origin
    if response.allow_credentials:
        http_response.headers[constants.ACCESS_CONTROL_ALLOW_CREDENTIALS] = \
            'true'

    if request.is_preflight:
        # Set the preflight-only headers.
        if len(response.allow_methods):
            http_response.headers[constants.ACCESS_CONTROL_ALLOW_METHODS] = \
                ','.join(response.allow_methods)
        if response.allow_headers and len(response.allow_headers):
            http_response.headers[constants.ACCESS_CONTROL_ALLOW_HEADERS] = \
                ','.join(response.allow_headers)
        if response.max_age:
            http_response.headers[constants.ACCESS_CONTROL_MAX_AGE] = \
                str(response.max_age)
        # '200 OK'
        http_response.status = '%s %s' % (
            httplib.OK,
            httplib.responses[httplib.OK]
        )
        http_response.end()
    else:
        # Set the CORS-only headers.
        if len(response.expose_headers):
            http_response.headers[constants.ACCESS_CONTROL_EXPOSE_HEADERS] = \
                ','.join(response.expose_headers)
    return http_response


text:
<?php
if (! defined('BASEPATH')) exit('No direct script access allowed');
class Dashboard extends CI_Controller
{
	function __construct()
	{
		parent::__construct();

		if (! $this->session->userdata('isLoggedIn'))
		{
			redirect('/login/show_login');
		}

		$this->_init();
	}
	private function _init()
	{
		$this->output->set_template($this->config->item('default_theme_name') . '/templates/default');
		$this->output->set_title('Dashboard | TrocDeal - Business changing between products');
		$this->load->css('assets/themes/' . $this->config->item('default_theme_name') . '/css/theme-default.css');
		$this->load->audio('assets/themes/' . $this->config->item('default_theme_name') . '/audio/alert.mp3');
		$this->load->audio('assets/themes/' . $this->config->item('default_theme_name') . '/audio/fail.mp3');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/jquery/jquery.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/jquery/jquery-ui.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/bootstrap/bootstrap.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/icheck/icheck.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/mcustomscrollbar/jquery.mCustomScrollbar.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/scrolltotop/scrolltopcontrol.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/morris/raphael-min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/morris/morris.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/rickshaw/d3.v3.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/rickshaw/rickshaw.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/jvectormap/jquery-jvectormap-world-mill-en.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/bootstrap/bootstrap-datepicker.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/owl/owl.carousel.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/moment.min.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins/daterangepicker/daterangepicker.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/settings.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/plugins.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/actions.js');
		$this->load->js('assets/themes/' . $this->config->item('default_theme_name') . '/js/demo_dashboard.js');
	}
	public function index()
	{
		$this->breadcrumbs->push('Dashboard', '/dashboard/index');
		$this->breadcrumbs->unshift('Home', '/');
		$this->load->section('breadcrumbs', 'layout/' . $this->config->item('default_theme_name') . '/sections/breadcrumbs/breadcrumbs');
		$this->load->view('layout/' . $this->config->item('default_theme_name') . '/sections/dashboard/dashboard');
	}
}


text:
class Absence < Event
  validates :start_date, :end_date, :event_type, presence: true

  scope :week, (-> { where('start_date <= ? AND end_date >= ?', Date.current + 6.days, Date.current) })

  # Contants
  #
  TYPES = %i[workshop vacation sick other].freeze
end

# == Schema Information
#
# Table name: events
#
#  id          :integer          not null, primary key
#  name        :string
#  location    :string
#  start_date  :datetime
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#  event_type  :string
#  end_date    :date
#  user_id     :integer
#  type        :string
#  description :text
#


text:
<?php

class CM_FormField_LocationTest extends CMTest_TestCase {

    public function testSetValueByEnvironment() {
        $location = CMTest_TH::createLocation();
        $locationCity = $location->get(CM_Model_Location::LEVEL_CITY);

        $environment = new CM_Frontend_Environment();
        $environment->setLocation(null);
        $field = new CM_FormField_Location();
        $field->setValueByEnvironment($environment);
        $this->assertNull($field->getValue());

        $environment->setLocation($location->get(CM_Model_Location::LEVEL_COUNTRY));
        $field = new CM_FormField_Location(['levelMin' => CM_Model_Location::LEVEL_CITY]);
        $field->setValueByEnvironment($environment);
        $this->assertNull($field->getValue());

        $environment->setLocation($location);
        $field = new CM_FormField_Location(['levelMin' => CM_Model_Location::LEVEL_CITY, 'levelMax' => CM_Model_Location::LEVEL_CITY]);
        $field->setValueByEnvironment($environment);
        $value = $field->getValue();
        /** @var CM_Model_Location $locationValue */
        $locationValue = $value[0];
        $this->assertSame($locationCity->getId(), $locationValue->getId());
        $this->assertSame($locationCity->getLevel(), $locationValue->getLevel());

        $environment->setLocation($locationCity);
        $field = new CM_FormField_Location(['levelMin' => CM_Model_Location::LEVEL_CITY, 'levelMax' => CM_Model_Location::LEVEL_CITY]);
        $field->setValueByEnvironment($environment);
        $value = $field->getValue();
        /** @var CM_Model_Location $locationValue */
        $locationValue = $value[0];
        $this->assertSame($locationCity->getId(), $locationValue->getId());
        $this->assertSame($locationCity->getLevel(), $locationValue->getLevel());
    }
}


text:
<?php

namespace PhpBench\Expression\Func;

use PhpBench\Expression\Ast\BooleanNode;
use PhpBench\Expression\Ast\FloatNode;
use PhpBench\Expression\Ast\ListNode;
use PhpBench\Math\Statistics;

final class VarianceFunction
{
    public function __invoke(ListNode $values, ?BooleanNode $sample = null): FloatNode
    {
        return new FloatNode(Statistics::variance($values->nonNullPhpValues(), $sample ? $sample->value() : false));
    }
}


text:
package dk.bitmovers.timeregistration.model;

// Generated Jun 1, 2015 5:56:38 AM by Hibernate Tools 4.3.1

import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * User generated by hbm2java
 */
@Entity
@Table(name = "user", catalog = "timereg")
public class User implements java.io.Serializable {

	private Integer id;
	private Date created;
	private String login;
	private String name;
	private String locale;
	private String language;
	private String isLoginEnabled;
	private byte enabled;
	private Set<RegistrationSubmitted> registrationSubmitteds = new HashSet<RegistrationSubmitted>(
			0);
	private Set<Client> clients = new HashSet<Client>(0);
	private Set<ProviderAccount> providerAccounts = new HashSet<ProviderAccount>(
			0);
	private Set<WorkClockEvent> workClockEvents = new HashSet<WorkClockEvent>(0);
	private Set<Provider> providers = new HashSet<Provider>(0);
	private Set<RegistrationEvent> registrationEvents = new HashSet<RegistrationEvent>(
			0);
	private Set<RegistrationItem> registrationItems = new HashSet<RegistrationItem>(
			0);
	private Set<UserRoleLink> userRoleLinks = new HashSet<UserRoleLink>(0);
	private Set<UserPassword> userPasswords = new HashSet<UserPassword>(0);
	private Set<ClientProject> clientProjects = new HashSet<ClientProject>(0);

	public User() {
	}

	public User(Date created, String login, String isLoginEnabled, byte enabled, String locale,String language) {
		this.created = created;
		this.login = login;
		this.isLoginEnabled = isLoginEnabled;
		this.enabled = enabled;
		this.locale = locale;
		this.language = language;
	}

	public User(Date created, String login, String name, String isLoginEnabled,
			byte enabled, String locale,String language, Set<RegistrationSubmitted> registrationSubmitteds,
			Set<Client> clients, Set<ProviderAccount> providerAccounts,
			Set<WorkClockEvent> workClockEvents, Set<Provider> providers,
			Set<RegistrationEvent> registrationEvents,
			Set<RegistrationItem> registrationItems,
			Set<UserRoleLink> userRoleLinks, Set<UserPassword> userPasswords,
			Set<ClientProject> clientProjects) {
		this.created = created;
		this.login = login;
		this.name = name;
		this.isLoginEnabled = isLoginEnabled;
		this.enabled = enabled;
		this.registrationSubmitteds = registrationSubmitteds;
		this.clients = clients;
		this.providerAccounts = providerAccounts;
		this.workClockEvents = workClockEvents;
		this.providers = providers;
		this.registrationEvents = registrationEvents;
		this.registrationItems = registrationItems;
		this.userRoleLinks = userRoleLinks;
		this.userPasswords = userPasswords;
		this.clientProjects = clientProjects;
		this.locale = locale;
		this.language = language;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "created", nullable = false, length = 19)
	public Date getCreated() {
		return this.created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}

	@Column(name = "login", nullable = false, length = 80)
	public String getLogin() {
		return this.login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	@Column(name = "name", length = 140)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(name = "is_login_enabled", nullable = false, length = 2)
	public String getIsLoginEnabled() {
		return this.isLoginEnabled;
	}

	public void setIsLoginEnabled(String isLoginEnabled) {
		this.isLoginEnabled = isLoginEnabled;
	}

	@Column(name = "enabled", nullable = false)
	public byte getEnabled() {
		return this.enabled;
	}

	public void setEnabled(byte enabled) {
		this.enabled = enabled;
	}

	@Column(name = "locale", nullable = true, length = 3)
	public String getLocale() {
		return this.locale;
	}

	public void setLocale(String login) {
		this.locale = login;
	}

	@Column(name = "language", nullable = true, length = 3)
	public String getLanguage() {
		return this.language;
	}

	public void setLanguage(String login) {
		this.language = login;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<RegistrationSubmitted> getRegistrationSubmitteds() {
		return this.registrationSubmitteds;
	}

	public void setRegistrationSubmitteds(
			Set<RegistrationSubmitted> registrationSubmitteds) {
		this.registrationSubmitteds = registrationSubmitteds;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<Client> getClients() {
		return this.clients;
	}

	public void setClients(Set<Client> clients) {
		this.clients = clients;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<ProviderAccount> getProviderAccounts() {
		return this.providerAccounts;
	}

	public void setProviderAccounts(Set<ProviderAccount> providerAccounts) {
		this.providerAccounts = providerAccounts;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<WorkClockEvent> getWorkClockEvents() {
		return this.workClockEvents;
	}

	public void setWorkClockEvents(Set<WorkClockEvent> workClockEvents) {
		this.workClockEvents = workClockEvents;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<Provider> getProviders() {
		return this.providers;
	}

	public void setProviders(Set<Provider> providers) {
		this.providers = providers;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<RegistrationEvent> getRegistrationEvents() {
		return this.registrationEvents;
	}

	public void setRegistrationEvents(Set<RegistrationEvent> registrationEvents) {
		this.registrationEvents = registrationEvents;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<RegistrationItem> getRegistrationItems() {
		return this.registrationItems;
	}

	public void setRegistrationItems(Set<RegistrationItem> registrationItems) {
		this.registrationItems = registrationItems;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<UserRoleLink> getUserRoleLinks() {
		return this.userRoleLinks;
	}

	public void setUserRoleLinks(Set<UserRoleLink> userRoleLinks) {
		this.userRoleLinks = userRoleLinks;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<UserPassword> getUserPasswords() {
		return this.userPasswords;
	}

	public void setUserPasswords(Set<UserPassword> userPasswords) {
		this.userPasswords = userPasswords;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
	public Set<ClientProject> getClientProjects() {
		return this.clientProjects;
	}

	public void setClientProjects(Set<ClientProject> clientProjects) {
		this.clientProjects = clientProjects;
	}

}


text:
#pragma once

#include "types.h"
#include <memory>
#include <functional>
#include "mega/command.h"

namespace mega
{

struct UnifiedSync;

/**
 * @brief The HeartBeatBackupInfo class
 * This class holds the information that will be heartbeated
 */

class HeartBeatBackupInfo
{
public:
    HeartBeatBackupInfo();
    HeartBeatBackupInfo(HeartBeatBackupInfo&&) = default;
    HeartBeatBackupInfo& operator=(HeartBeatBackupInfo&&) = default;
    virtual ~HeartBeatBackupInfo() = default;

    MEGA_DISABLE_COPY(HeartBeatBackupInfo)

    virtual int status() const;

    virtual double progress(m_off_t inflightProgress) const;
    virtual void invalidateProgress();

    virtual m_time_t lastAction() const;

    virtual handle lastItemUpdated() const;

    virtual m_time_t lastBeat() const;
    virtual void setLastBeat(const m_time_t &lastBeat);
    virtual void setLastAction(const m_time_t &lastAction);
    virtual void setStatus(const int &status);
    virtual void setProgress(const double &progress);
    virtual void setLastSyncedItem(const handle &lastItemUpdated);

    virtual void updateStatus(UnifiedSync& us) {}

    bool mModified = false;
    bool mSending = false;

protected:
    int mStatus = 0;
    double mProgress = 0;
    bool mProgressInvalid = true;

    friend class BackupMonitor;
    int32_t mPendingUps = 0;
    int32_t mPendingDowns = 0;

    handle mLastItemUpdated = UNDEF; // handle of node most recently updated

    m_time_t mLastAction = -1;   //timestamps of the last action
    m_time_t mLastBeat = -1;     //timestamps of the last beat

    void updateLastActionTime();
};

/**
 * @brief Backup info controlled by transfers
 * progress is advanced with transfer progress
 * by holding the count of total and transferred bytes
 *
 */
class HeartBeatTransferProgressedInfo : public HeartBeatBackupInfo
{
public:
    double progress(m_off_t inflightProgress) const override;

    void adjustTransferCounts(int32_t upcount, int32_t downcount, long long totalBytes, long long transferBytes);

private:
    friend class BackupMonitor;
    long long mTotalBytes = 0;
    long long mTransferredBytes = 0;
};

#ifdef ENABLE_SYNC
class HeartBeatSyncInfo : public HeartBeatTransferProgressedInfo
{
public:
    enum Status
    {
        UPTODATE = 1, // Up to date: local and remote paths are in sync
        SYNCING = 2, // The sync engine is working, transfers are in progress
        PENDING = 3, // The sync engine is working, e.g: scanning local folders
        INACTIVE = 4, // Sync is not active. A state != ACTIVE should have been sent through '''sp'''
        UNKNOWN = 5, // Unknown status
    };

    HeartBeatSyncInfo();
    MEGA_DISABLE_COPY(HeartBeatSyncInfo)

    virtual void updateStatus(UnifiedSync& us) override;
};
#endif

/**
 * @brief Information for registration/update of a backup
 */
class BackupInfo
{
public:
    BackupInfo(BackupType type, string backupName, LocalPath localFolder, handle megaHandle, int state, int substate, string extra);

    BackupType type() const;

    string backupName() const;

    LocalPath localFolder() const;

    handle megaHandle() const;

    int state() const;

    int subState() const;

    string extra() const;

protected:
    BackupType mType;
    string mBackupName;
    LocalPath mLocalFolder;
    handle mMegaHandle;
    int mState;
    int mSubState;
    string mExtra;
};

#ifdef ENABLE_SYNC
class BackupInfoSync : public BackupInfo
{
public:
    enum State
    {
        ACTIVE = 1,             // Working fine (enabled)
        FAILED = 2,             // Failed (permanently disabled)
        TEMPORARY_DISABLED = 3, // Temporarily disabled due to a transient situation (e.g: account blocked). Will be resumed when the condition passes
        DISABLED = 4,           // Disabled by the user
        PAUSE_UP = 5,           // Active but upload transfers paused in the SDK
        PAUSE_DOWN = 6,         // Active but download transfers paused in the SDK
        PAUSE_FULL = 7,         // Active but transfers paused in the SDK
    };

    BackupInfoSync(UnifiedSync&);

    static BackupType getSyncType(const SyncConfig& config);
    static int getSyncState (UnifiedSync&);
    static int getSyncState(SyncError error, syncstate_t state, MegaClient *client);
    static int getSyncState(const SyncConfig& config, MegaClient *client);
    static int getSyncSubstatus (UnifiedSync&);
    string getSyncExtraData(UnifiedSync&);

    bool operator==(const BackupInfoSync& o) const;
    bool operator!=(const BackupInfoSync& o) const;

private:
    static int calculatePauseActiveState(MegaClient *client);
};
#endif

class BackupMonitor
{
public:
    explicit BackupMonitor(MegaClient * client);

    void beat(); // produce heartbeats!

    void onSyncConfigChanged();
    void updateOrRegisterSync(UnifiedSync&);

private:
    void digestPutResult(handle backupId, UnifiedSync* syncPtr);

    static constexpr int MAX_HEARBEAT_SECS_DELAY = 60*30; // max time to wait before a heartbeat for unchanged backup

    mega::MegaClient *mClient = nullptr;

    void updateBackupInfo(handle backupId, const BackupInfo &info);

#ifdef ENABLE_SYNC
    void beatBackupInfo(UnifiedSync& us);
#endif
};
}


text:
package org.mozilla.javascript.tests;

import org.junit.Test;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextAction;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

/**
 * Unit tests for Bug 374918 -
 * String primitive prototype wrongly resolved when used with many top scopes
 */
public class PrimitiveTypeScopeResolutionTest
{
    /**
     */
    @Test
    public void functionCall() {
        String str2 = "function f() {\n"
            + "String.prototype.foo = function() { return 'from 2' }; \n"
            + "var s2 = 's2';\n"
            + "var s2Foo = s2.foo();\n"
            + "if (s2Foo != 'from 2') throw 's2 got: ' + s2Foo;\n" // fails
            + "}";

        String str1 = "String.prototype.foo = function() { return 'from 1'};"
            + "scope2.f()";
    	testWithTwoScopes(str1, str2);
    }

    /**
     */
    @Test
    public void propertyAccess() {
        String str2 = "function f() { String.prototype.foo = 'from 2'; \n"
            + "var s2 = 's2';\n"
            + "var s2Foo = s2.foo;\n"
            + "if (s2Foo != 'from 2') throw 's2 got: ' + s2Foo;\n" // fails
            + "}";

        String str1 = "String.prototype.foo = 'from 1'; scope2.f()";
    	testWithTwoScopes(str1, str2);
    }

    /**
     */
    @Test
    public void elementAccess() {
        String str2 = "function f() { String.prototype.foo = 'from 2'; \n"
            + "var s2 = 's2';\n"
            + "var s2Foo = s2['foo'];\n"
            + "if (s2Foo != 'from 2') throw 's2 got: ' + s2Foo;\n" // fails
            + "}";

        String str1 = "String.prototype.foo = 'from 1'; scope2.f()";
    	testWithTwoScopes(str1, str2);
    }

    private void testWithTwoScopes(final String scriptScope1,
                                   final String scriptScope2)
    {
    	final ContextAction action = new ContextAction()
    	{
    		public Object run(final Context cx)
    		{
    	        final Scriptable scope1 = cx.initStandardObjects(
    	            new MySimpleScriptableObject("scope1"));
    	        final Scriptable scope2 = cx.initStandardObjects(
    	            new MySimpleScriptableObject("scope2"));
    	        cx.evaluateString(scope2, scriptScope2, "source2", 1, null);

    	        scope1.put("scope2", scope1, scope2);

    	        return cx.evaluateString(scope1, scriptScope1, "source1", 1,
    	                                 null);
    		}
    	};
    	Utils.runWithAllOptimizationLevels(action);
    }

	/**
	 * Simple utility allowing to better see the concerned scope while debugging
	 */
	static class MySimpleScriptableObject extends ScriptableObject
	{
        private static final long serialVersionUID = 1L;
        private String label_;
		MySimpleScriptableObject(String label)
		{
			label_ = label;
		}
		@Override
		public String getClassName()
		{
			return "MySimpleScriptableObject";
		}

		@Override
		public String toString()
		{
			return label_;
		}
	}

    public static class MyObject extends ScriptableObject {
        private static final long serialVersionUID = 1L;

    @Override
      public String getClassName()
      {
          return "MyObject";
      }

      public Object readPropFoo(final Scriptable s) {
          return ScriptableObject.getProperty(s, "foo");
      }
  }

  /**
   * Test that FunctionObject use the right top scope to convert a primitive
   * to an object
   */
  @Test
  public void functionObjectPrimitiveToObject() throws Exception {
      final String scriptScope2 = "function f() {\n"
          + "String.prototype.foo = 'from 2'; \n"
          + "var s2 = 's2';\n"
          + "var s2Foo = s2.foo;\n"
          + "var s2FooReadByFunction = myObject.readPropFoo(s2);\n"
          + "if (s2Foo != s2FooReadByFunction)\n"
          + "throw 's2 got: ' + s2FooReadByFunction;\n"
          + "}";

      // define object with custom method
      final MyObject myObject = new MyObject();
      final String[] functionNames = { "readPropFoo" };
      myObject.defineFunctionProperties(functionNames, MyObject.class,
          ScriptableObject.EMPTY);

      final String scriptScope1 = "String.prototype.foo = 'from 1'; scope2.f()";

      final ContextAction action = new ContextAction()
      {
          public Object run(final Context cx)
          {
              final Scriptable scope1 = cx.initStandardObjects(
                  new MySimpleScriptableObject("scope1"));
              final Scriptable scope2 = cx.initStandardObjects(
                  new MySimpleScriptableObject("scope2"));

              scope2.put("myObject", scope2, myObject);
              cx.evaluateString(scope2, scriptScope2, "source2", 1, null);

              scope1.put("scope2", scope1, scope2);

              return cx.evaluateString(scope1, scriptScope1, "source1", 1, null);
          }
      };
      Utils.runWithAllOptimizationLevels(action);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace SharedDemo.iOS
{
    [Register("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        UIWindow window;

        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            window = new UIWindow(UIScreen.MainScreen.Bounds);
            UINavigationController controller = new UINavigationController(new MainViewController());

            window.RootViewController = controller;

            window.MakeKeyAndVisible();

            return true;
        }
    }
}


text:
[![AngularJS Express](http://i.imgur.com/nTj9QgN.png)](https://github.com/angular-express/angular-express)

## Angular exception handler decorator

This component provides you with the boilerplate to decorate the default AngularJS exception handler.

## Installation

To install the component:

```bash
$ ngx install angular-exception-handler-decorator
```

No clue what the `ngx` command line tool is? Learn more about [AngularJS Express](https://github.com/angular-express/angular-express).

## How to use

After installing the component, edit the `exception-handler.decorator.js` file in the `_build` directory of the component and add your custom logic.

## License

MIT.


text:
.PHONY: all install clean

# This project requires ocamlfind (default - false).
#
USE_OCAMLFIND = true
BYTE_ENABLED = true

if $(not $(OCAMLFIND_EXISTS))
    eprintln(This project requires ocamlfind, but is was not found.)
    eprintln(You need to install ocamlfind and run "omake --configure".)
    exit 1

#
# Various options
#

OCAMLFLAGS    += -dtypes -g

FILES[] = find_ear_rails parse_ruby_methods

.SUBDIRS: diamondback-ruby-0.20090726

PROGRAM = find_ear_rails
GETOPT_DIR=$(shell ocamlfind query getopt)
OCAMLGRAPH_DIR=$(shell ocamlfind query ocamlgraph)

OCAMLINCLUDES += diamondback-ruby-0.20090726/src/cfg diamondback-ruby-0.20090726/src/dyn diamondback-ruby-0.20090726/src/parser diamondback-ruby-0.20090726/src/typing diamondback-ruby-0.20090726/src/ $(GETOPT_DIR) $(OCAMLGRAPH_DIR)

OCAML_LIBS += diamondback-ruby-0.20090726/libdruby

OCAML_OTHER_LIBS += nums unix str getopt graph
# OCAML_CLIBS +=
# OCAML_OTHER_LIBS +=
# OCAML_LIB_FLAGS +=
#

.DEFAULT: $(OCamlProgram $(PROGRAM), $(FILES))

ALL_FILES = $`(ls R, .) #`
ALL_TARGETS = $`(filter-targets $(ALL_FILES))) #`
TARGETS = $`(filter-proper-targets $(ALL_TARGETS)) #`
ANNOTS = $`(filter-exists $(replacesuffixes .ml, .annot, \
	                      $(filter %.ml, $(ALL_TARGETS)))) #`
clean:
	rm -f $(TARGETS)
	rm -f $(ANNOTS)