text:
.class Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;
.super Landroid/os/AsyncTask;
.source "EthernetEnabler.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/android/settings/ethernet/EthernetEnabler;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "EthernetEnableTask"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/os/AsyncTask",
        "<",
        "Ljava/lang/String;",
        "Ljava/lang/Void;",
        "Ljava/lang/String;",
        ">;"
    }
.end annotation

# instance fields
.field final synthetic this$0:Lcom/samsung/android/settings/ethernet/EthernetEnabler;

# direct methods
.method private constructor <init>(Lcom/samsung/android/settings/ethernet/EthernetEnabler;)V
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;->this$0:Lcom/samsung/android/settings/ethernet/EthernetEnabler;

    invoke-direct {p0}, Landroid/os/AsyncTask;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/samsung/android/settings/ethernet/EthernetEnabler;Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;)V
    .locals 0

    invoke-direct {p0, p1}, Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;-><init>(Lcom/samsung/android/settings/ethernet/EthernetEnabler;)V

    return-void
.end method

# virtual methods
.method protected bridge synthetic doInBackground([Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1

    check-cast p1, [Ljava/lang/String;

    invoke-virtual {p0, p1}, Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;->doInBackground([Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method protected varargs doInBackground([Ljava/lang/String;)Ljava/lang/String;
    .locals 6

    const/4 v5, 0x1

    const/4 v4, 0x0

    aget-object v1, p1, v4

    aget-object v2, p1, v5

    const-string/jumbo v3, "enabling"

    invoke-virtual {v2, v3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_0

    :goto_0
    const-wide/16 v4, 0x3e8

    :try_start_0
    invoke-static {v4, v5}, Ljava/lang/Thread;->sleep(J)V
    :try_end_0
    .catch Ljava/lang/InterruptedException; {:try_start_0 .. :try_end_0} :catch_0

    :goto_1
    return-object v1

    :cond_0
    const-string/jumbo v3, "true"

    invoke-virtual {v1, v3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_1

    iget-object v3, p0, Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;->this$0:Lcom/samsung/android/settings/ethernet/EthernetEnabler;

    invoke-static {v3}, Lcom/samsung/android/settings/ethernet/EthernetEnabler;->-get1(Lcom/samsung/android/settings/ethernet/EthernetEnabler;)Landroid/net/EthernetManager;

    move-result-object v3

    invoke-virtual {v3, v4}, Landroid/net/EthernetManager;->setUserDisabled(Z)V

    goto :goto_0

    :cond_1
    iget-object v3, p0, Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;->this$0:Lcom/samsung/android/settings/ethernet/EthernetEnabler;

    invoke-static {v3}, Lcom/samsung/android/settings/ethernet/EthernetEnabler;->-get1(Lcom/samsung/android/settings/ethernet/EthernetEnabler;)Landroid/net/EthernetManager;

    move-result-object v3

    invoke-virtual {v3, v5}, Landroid/net/EthernetManager;->setUserDisabled(Z)V

    goto :goto_0

    :catch_0
    move-exception v0

    invoke-virtual {v0}, Ljava/lang/InterruptedException;->printStackTrace()V

    goto :goto_1
.end method

.method protected bridge synthetic onPostExecute(Ljava/lang/Object;)V
    .locals 0

    check-cast p1, Ljava/lang/String;

    invoke-virtual {p0, p1}, Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;->onPostExecute(Ljava/lang/String;)V

    return-void
.end method

.method protected onPostExecute(Ljava/lang/String;)V
    .locals 2

    const-string/jumbo v0, "true"

    invoke-virtual {p1, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;->this$0:Lcom/samsung/android/settings/ethernet/EthernetEnabler;

    const/4 v1, 0x1

    invoke-static {v0, v1}, Lcom/samsung/android/settings/ethernet/EthernetEnabler;->-wrap0(Lcom/samsung/android/settings/ethernet/EthernetEnabler;Z)V

    :goto_0
    return-void

    :cond_0
    iget-object v0, p0, Lcom/samsung/android/settings/ethernet/EthernetEnabler$EthernetEnableTask;->this$0:Lcom/samsung/android/settings/ethernet/EthernetEnabler;

    const/4 v1, 0x0

    invoke-static {v0, v1}, Lcom/samsung/android/settings/ethernet/EthernetEnabler;->-wrap0(Lcom/samsung/android/settings/ethernet/EthernetEnabler;Z)V

    goto :goto_0
.end method


text:
_websync is intended to be an **rsync task manager**, where rsync tasks can be added, scheduled and maintained in a sane manner._

## Table of content

- [Installation](#installation)
- [Screenshots](#screenshots)
- [Features](#features)
- [websync@docker](#websyncdocker)
- [Bugs & Requests/Enhancments](#bugs--requestsenhancments)
- [Roadmap](#roadmap)
- [Collaborate](#collaborate)
- [Contact](#contact)
- [FAQ](https://github.com/furier/websync/wiki/FAQ)
- [License](#license---mit)

## Installation

- [OS X](https://github.com/furier/websync/wiki/Installation---OS-X)
- [Ubuntu 12.04](https://github.com/furier/websync/wiki/Installation---Ubuntu-12.04)
- [Debian 6](https://github.com/furier/websync/wiki/Installation-Debian-6)
- Should work for any unix like system.

## Screenshots

### Tasks tab
![Tasks](doc/screenshots/tasks_tab.png)

### Hosts tab
![Hosts](doc/screenshots/hosts_tab.png)

## Features

- All
  - Every change is auto synchronized with the back end, no manual saving is required!
  - Data is stored in a simple json file on disk!

- Tasks
  - Create
  - Edit
  - Remove
  - Clone
  - Schedule
  - Multiple paths defined for one task.
  - Either source or destination can be a remote target, as long as a passwordless ssh RSA key (for the host running websync) has been added to authorized hosts on the remote target.
  - Realtime logs for each task in the browser.
  - Test and Run on demand.

- Hosts
  - Create
  - Edit
  - Remove
  - ssh-copy-id to remote targets

## websync@docker

websync can now be found @ docker, get it [here](https://registry.hub.docker.com/u/furier/websync/)!

All you have to do is

    sudo docker pull furier/websync
    sudo docker run -d -p 3000:3000 -v /path/to/share:/path/to/share -w /src furier/websync node server.js

and you are done!

## Bugs & Requests/Enhancments

Please file an issue report if you find a bug, or have any other request, suggestion etc!

## Roadmap

- **File Browser**, which can browse both localhost and remote targets.
- **Path autocompletion** for both localhost and remote targets when just typing the paths manually in the path list for each task.
- **Progressbars** to view total task progress, individual task progress and for each file!

## Collaborate

- Collaborators are very welcome, contact me!
- Pull requests are also welcome, fork me and send me a pull request!

## Contact

- Authors
  - Sander Struijk - furier84+github@gmail.com

## LICENSE - MIT

redpajama_set_name: RedPajamaGithub


text:
goog.provide('lf.pred.JoinPredicate');

goog.require('goog.asserts');
goog.require('goog.labs.structs.Multimap');
goog.require('lf.Row');
goog.require('lf.eval.Registry');
goog.require('lf.eval.Type');
goog.require('lf.pred.PredicateNode');
goog.require('lf.proc.Relation');
goog.require('lf.proc.RelationEntry');

/**
 * @constructor @struct
 * @extends {lf.pred.PredicateNode}
 *
 * @template T
 * @param {!lf.schema.Column} leftColumn
 * @param {!lf.schema.Column} rightColumn
 * @param {!lf.eval.Type} evaluatorType
 */
lf.pred.JoinPredicate = function(leftColumn, rightColumn, evaluatorType) {
  lf.pred.JoinPredicate.base(this, 'constructor');

  /** @type {!lf.schema.Column} */
  this.leftColumn = leftColumn;

  /** @type {!lf.schema.Column} */
  this.rightColumn = rightColumn;

  /** @type {!lf.eval.Type} */
  this.evaluatorType = evaluatorType;

  /** @private {Object} */
  this.nullPayload_ = null;

  var registry = /** @type {!lf.eval.Registry} */ (
      lf.eval.Registry.getInstance());

  /** @private {!function(!T, !T):boolean} */
  this.evaluatorFn_ = registry.getEvaluator(
      this.leftColumn.getType(), this.evaluatorType);
};
goog.inherits(lf.pred.JoinPredicate, lf.pred.PredicateNode);

/** @override */
lf.pred.JoinPredicate.prototype.copy = function() {
  var clone = new lf.pred.JoinPredicate(
      this.leftColumn, this.rightColumn, this.evaluatorType);
  clone.setId(this.getId());
  return clone;
};

/** @override */
lf.pred.JoinPredicate.prototype.getColumns = function(opt_results) {
  if (goog.isDefAndNotNull(opt_results)) {
    opt_results.push(this.leftColumn);
    opt_results.push(this.rightColumn);
    return opt_results;
  } else {
    return [this.leftColumn, this.rightColumn];
  }
};

/**
 * Creates a new predicate with the  left and right columns swapped and
 * operator changed (if necessary).
 * @return {!lf.Predicate}
 */
lf.pred.JoinPredicate.prototype.reverse = function() {
  var evaluatorType = this.evaluatorType;
  switch (this.evaluatorType) {
    case lf.eval.Type.GT:
      evaluatorType = lf.eval.Type.LT;
      break;
    case lf.eval.Type.LT:
      evaluatorType = lf.eval.Type.GT;
      break;
    case lf.eval.Type.GTE:
      evaluatorType = lf.eval.Type.LTE;
      break;
    case lf.eval.Type.LTE:
      evaluatorType = lf.eval.Type.GTE;
      break;
  }
  var newPredicate = new lf.pred.JoinPredicate(
      this.rightColumn, this.leftColumn, evaluatorType);
  return newPredicate;
};

/** @override */
lf.pred.JoinPredicate.prototype.eval = function(relation) {
  var entries = relation.entries.filter(function(entry) {
    var leftValue = entry.getField(this.leftColumn);
    var rightValue = entry.getField(this.rightColumn);
    return this.evaluatorFn_(leftValue, rightValue);
  }, this);

  return new lf.proc.Relation(entries, relation.getTables());
};

/** @override */
lf.pred.JoinPredicate.prototype.toString = function() {
  return 'join_pred(' +
      this.leftColumn.getNormalizedName() + ', ' +
      this.rightColumn.getNormalizedName() + ')';
};

/**
 * @param {!lf.proc.Relation} relation
 * @return {boolean} Whether the given relation can be used as the "left"
 *     parameter of this predicate.
 * @private
 */
lf.pred.JoinPredicate.prototype.appliesToLeft_ = function(relation) {
  return relation.getTables().indexOf(
      this.leftColumn.getTable().getEffectiveName()) != -1;
};

/**
 * @param {!lf.proc.Relation} relation
 * @return {boolean} Whether the given relation can be used as the "right"
 *     parameter of this predicate.
 * @private
 */
lf.pred.JoinPredicate.prototype.appliesToRight_ = function(relation) {
  return relation.getTables().indexOf(
      this.rightColumn.getTable().getEffectiveName()) != -1;
};

/**
 * Detects which input relation should be used as left/right.
 * @param {!lf.proc.Relation} relation1 The first relation to examine.
 * @param {!lf.proc.Relation} relation2 The second relation to examine.
 * @return {!Array<!lf.proc.Relation>} An array holding the two input relations
 *     in the order [left, right].
 * @private
 */
lf.pred.JoinPredicate.prototype.detectLeftRight_ = function(
    relation1, relation2) {
  var left = null;
  var right = null;

  if (this.appliesToLeft_(relation1)) {
    this.assertRelationsApply_(relation1, relation2);
    left = relation1;
    right = relation2;
  } else {
    this.assertRelationsApply_(relation2, relation1);
    left = relation2;
    right = relation1;
  }

  return [left, right];
};

/**
 * Asserts that the given relations are applicable to this join predicate.
 * Example of non-applicable relations:
 *   - join predicate: photoTable.albumId == albumTable.id
 *   leftRelation.getTables() does not include photoTable, or
 *   rightRelation.getTables() does not include albumTable.
 *
 * @param {!lf.proc.Relation} leftRelation The left relation to examine.
 * @param {!lf.proc.Relation} rightRelation The right relation to examine.
 * @private
 */
lf.pred.JoinPredicate.prototype.assertRelationsApply_ = function(
    leftRelation, rightRelation) {
  goog.asserts.assert(
      this.appliesToLeft_(leftRelation),
      'Mismatch between join predicate left operand and right relation.');
  goog.asserts.assert(
      this.appliesToRight_(rightRelation),
      'Mismatch between join predicate right operand and right relation.');
};

/**
 * Calculates the join between the input relations. The order of the input
 * relations does not matter, since the "left" and "right" relation will be
 * detected.
 * @param {!lf.proc.Relation} relation1 The first relation.
 * @param {!lf.proc.Relation} relation2 The second relation.
 * @param {boolean} isOuterJoin
 * @return {!lf.proc.Relation}
 */
lf.pred.JoinPredicate.prototype.evalRelations = function(relation1, relation2,
    isOuterJoin) {
  var leftRightRelations = [relation1, relation2];
  // For outer join, left and right are not interchangeable.
  if (!isOuterJoin) {
    leftRightRelations = this.detectLeftRight_(relation1, relation2);
  }
  var leftRelation = leftRightRelations[0];
  var rightRelation = leftRightRelations[1];

  return this.evaluatorType == lf.eval.Type.EQ ?
      this.evalRelationsHashJoin_(leftRelation, rightRelation, isOuterJoin) :
      this.evalRelationsNestedLoopJoin_(
          leftRelation, rightRelation, isOuterJoin);
};

/**
 * Creates a row with null columns with column names obtained from the table.
 * @param {!lf.schema.Table} table
 * @return {!Object}
 * @private
 */
lf.pred.JoinPredicate.prototype.createNullPayload_ = function(table) {
  var payload = {};
  table.getColumns().forEach(function(column) {
    payload[column.getName()] = null;
  });
  return payload;
};

/**
 * Creates a combined entry with an unmatched left entry from outer join
 * algorithm and a null entry.
 * @param {!lf.proc.RelationEntry} entry The left relation entry.
 * @param {!Array<string>} leftRelationTables
 * @return {!lf.proc.RelationEntry}
 * @private
 */
lf.pred.JoinPredicate.prototype.createCombinedEntryForUnmatched_ = function(
    entry, leftRelationTables) {
  if (goog.isNull(this.nullPayload_)) {
    this.nullPayload_ = this.createNullPayload_(
        this.rightColumn.getTable());
  }
  // The right relation is guaranteed to never be the result
  // of a previous join.
  var nullEntry = new lf.proc.RelationEntry(
      new lf.Row(lf.Row.DUMMY_ID, this.nullPayload_), false);
  var combinedEntry = lf.proc.RelationEntry.combineEntries(
      entry, leftRelationTables,
      nullEntry, [this.rightColumn.getTable().getEffectiveName()]);
  return combinedEntry;
};

/**
 * Calculates the join between the input relations using a Nested-Loop-Join
 * algorithm.
 * @param {!lf.proc.Relation} leftRelation The left relation.
 * @param {!lf.proc.Relation} rightRelation The relation relation.
 * @param {boolean} isOuterJoin
 * @return {!lf.proc.Relation}
 * @private
 */
lf.pred.JoinPredicate.prototype.evalRelationsNestedLoopJoin_ = function(
    leftRelation, rightRelation, isOuterJoin) {
  var combinedEntries = [];
  var leftRelationTables = leftRelation.getTables();
  var rightRelationTables = rightRelation.getTables();
  for (var i = 0; i < leftRelation.entries.length; i++) {
    var matchFound = false;
    for (var j = 0; j < rightRelation.entries.length; j++) {
      // Evaluating before combining the rows, since combining is fairly
      // expensive.
      var predicateResult = this.evaluatorFn_(
          leftRelation.entries[i].getField(this.leftColumn),
          rightRelation.entries[j].getField(this.rightColumn));

      if (predicateResult) {
        matchFound = true;
        var combinedEntry = lf.proc.RelationEntry.combineEntries(
            leftRelation.entries[i], leftRelationTables,
            rightRelation.entries[j], rightRelationTables);
        combinedEntries.push(combinedEntry);
      }
    }
    if (isOuterJoin && !matchFound) {
      combinedEntries.push(this.createCombinedEntryForUnmatched_(
          leftRelation.entries[i], leftRelationTables));
    }
  }
  var srcTables = leftRelation.getTables().concat(rightRelation.getTables());
  return new lf.proc.Relation(combinedEntries, srcTables);
};

/**
 * Calculates the join between the input relations using a Hash-Join
 * algorithm. Such a join implementation can only be used if the join conditions
 * is the "equals" operator.
 * @param {!lf.proc.Relation} leftRelation The left relation.
 * @param {!lf.proc.Relation} rightRelation The relation relation.
 * @param {boolean} isOuterJoin
 * @return {!lf.proc.Relation}
 * @private
 */
lf.pred.JoinPredicate.prototype.evalRelationsHashJoin_ = function(
    leftRelation, rightRelation, isOuterJoin) {
  // If it is an outerjoin, then swap to make sure that the right table is
  // used for the "build" phase of the hash-join algorithm. If it is inner
  // join, choose the smaller of the two relations to be used for the "build"
  // phase.
  var minRelation = leftRelation;
  var maxRelation = rightRelation;
  var minColumn = this.leftColumn;
  var maxColumn = this.rightColumn;
  if (isOuterJoin ||
      (leftRelation.entries.length > rightRelation.entries.length)) {
    minRelation = rightRelation;
    maxRelation = leftRelation;
    minColumn = this.rightColumn;
    maxColumn = this.leftColumn;
  }

  var map = new goog.labs.structs.Multimap();
  var combinedEntries = [];

  minRelation.entries.forEach(
      function(entry) {
        var key = String(entry.getField(minColumn));
        map.add(key, entry);
      });

  var minRelationTableNames = minRelation.getTables();
  var maxRelationTableNames = maxRelation.getTables();

  maxRelation.entries.forEach(
      function(entry) {
        var key = String(entry.getField(maxColumn));
        if (map.containsKey(key)) {
          var entries = /** @type {!Array<!lf.proc.RelationEntry>} */ (
              map.get(key));
          entries.forEach(
              function(innerEntry) {
                var combinedEntry = lf.proc.RelationEntry.combineEntries(
                    entry, maxRelationTableNames,
                    innerEntry, minRelationTableNames);
                combinedEntries.push(combinedEntry);
              });
        } else {
          if (isOuterJoin) {
            combinedEntries.push(this.createCombinedEntryForUnmatched_(
                entry, maxRelationTableNames));
          }
        }
      }.bind(this));

  var srcTables = leftRelation.getTables().concat(rightRelation.getTables());
  return new lf.proc.Relation(combinedEntries, srcTables);
};


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for C:\wamp\www\framework/vendor/symfony/routing/Symfony/Component/Routing/Exception/ResourceNotFoundException.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

C:\wamp\www\framework /

vendor /

symfony /

routing /

Symfony /

Component /

Routing /

Exception /

ResourceNotFoundException.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

100.00%

1 / 1

      CRAP

      ResourceNotFoundException

100.00%

1 / 1

      0

1
	<?php

2

3

11

12
	namespace Symfony\Component\Routing\Exception;

13

14
	/**

15
	 * The resource was not found.

16
	 *

17
	 * This exception should trigger an HTTP 404 response in your application code.

18
	 *

19
	 * @author Kris Wallsmith <kris@symfony.com>

20
	 *

21
	 * @api

22
	 */

23
	class ResourceNotFoundException extends \RuntimeException implements ExceptionInterface

24
	{

25
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.16 using PHP 5.4.12 and PHPUnit 3.7.32 at Fri Jan 9 11:26:01 CST 2015.


text:
sap.ui.define([
	"sap/m/Button",
	"sap/m/MessageToast",
	"sap/m/Text",
	"sap/ui/core/Popup",
	"sap/ui/layout/VerticalLayout",
	"sap/ui/unified/Menu",
	"sap/ui/unified/MenuItem",
	"sap/ui/unified/MenuTextFieldItem"
], function(Button, MessageToast, Text, Popup, VerticalLayout, Menu, MenuItem, MenuTextFieldItem) {
	"use strict";

	// -----------------
	// Utility functions
	// -----------------

	function handleMenuItemPress (oEvent) {
		var oItem = oEvent.getParameter("item"),
			sMsg;

		if (oItem.getSubmenu()) {
			return;
		}

		if (oItem.isA("sap.ui.unified.MenuTextFieldItem")) {
			sMsg = "'" + oItem.getValue() + "' entered";
		} else {
			sMsg = "'" + oItem.getText() + "' pressed";
		}

		MessageToast.show(sMsg);
	}

	function handleMenuButtonPress(oEvent) {
		var oSource = oEvent.getSource(),
			oMenu = getMenu();

		oMenu.open(window.bIsKeyboardPress, oSource, Popup.Dock.BeginTop, Popup.Dock.BeginBottom, oSource);
	}

	function getMenu() {
		if (!window.oMenu) {
			window.oMenu = new Menu({
				itemSelect: handleMenuItemPress,
				items: [
					new MenuItem({
						text: "View Settings"
					}),
					new MenuItem({
						text: "Create Settings",
						enabled: false
					}),
					new MenuItem({
						text: "Create Settings",
						icon: "sap-icon://create"
					}),
					new MenuItem({
						text: "Item with ariaLabelledBy",
						icon: "sap-icon://blank-tag",
						ariaLabelledBy: "labelling-text"
					}),
					new MenuItem({
						text: "Modify Settings",
						startsSection: true,
						icon: "sap-icon://edit",
						submenu: new Menu({
							itemSelect: handleMenuItemPress,
							items: [
								new MenuItem({
									text: "Edit"
								}),
								new MenuItem({
									text: "Delete"
								}),
								new MenuItem({
									text: "Edit Metadata",
									enabled: false
								})
							]
						})
					}),
					new MenuTextFieldItem({
						icon: "sap-icon://filter",
						label: "Filter",
						startsSection: true,
						select: handleMenuItemPress
					}),
					new MenuTextFieldItem({
						icon: "sap-icon://filter",
						label: "Another Filter",
						value: "FilterValue",
						enabled: false,
						select: handleMenuItemPress
					}),
					new MenuItem({
						text: "Clear filter"
					})
				]
			});
		}

		return window.oMenu;
	}

	// -------------------
	// Control preparation
	// -------------------

	var oTextForLabelling = new Text("labelling-text", {
		text: "This text will be used as a label for one menu item"
	});

	var oMenuButton = new Button({
		text: "Open settings menu",
		press: handleMenuButtonPress
	});

	oMenuButton.attachBrowserEvent("tap keyup", function (oEvent) {
		window.bIsKeyboardPress = (oEvent.type === "keyup");
	});

	// -------------
	// Page's layout
	// -------------

	var oLayout = new VerticalLayout({
		content: [
			oTextForLabelling,
			oMenuButton
		]
	});

	oLayout.placeAt("content");
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>ru.jeki</groupId>
    <artifactId>shedulenow</artifactId>
    <version>0.1-Alpha</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <!-- jsoup HTML parser library @ http://jsoup.org/ -->
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.zenjava</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>8.6.0</version>
                <configuration>
                    <mainClass>ru.jeki.schedulenow.ScheduleNow</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>create-jfxjar</id>
                        <phase>package</phase>
                        <goals>
                            <goal>build-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GalaSoft.MvvmLight;

namespace ReversiUniversal
{
    class PlayerNamesViewModel : ViewModelBase
    {
        private string blackName;
        private string whiteName;
        public string BlackName { get { return blackName; } set { Set(() => BlackName, ref blackName, value); } }
        public string WhiteName { get { return whiteName; } set { Set(() => WhiteName, ref whiteName, value); } }
    }
}


text:
'use strict';

angular.module('ngMask')
  .factory('SelectorService', [function(){
    function wrongPosition(type, mask, values, patterns){
      if(!values){ return 0; }

      var pos = undefined;

      for(var i=0; i<values.length; i++){
        var value   = values[i],
            pattern = patterns[mask[i]];

        if(pattern && !pattern.test(value)){
          pos = i;

          if(type === 'first'){
            break;
          }
        }
      }

      return (pos === undefined) ? values.length : pos;
    }

    function getFirstWrongPosition(mask, values, patterns){
      return wrongPosition('first', mask, values, patterns);
    }

    function getLastWrongPosition(mask, values, patterns){
      return wrongPosition('last', mask, values, patterns);
    }

    function setSelectionRange(input, selectionStart, selectionEnd){
      if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
      } else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
      }
    }

    function setCaretPosition(element, mask, values, patterns){
      // Set cursor on first wrong element
      var pos = getFirstWrongPosition(mask, values, patterns);
      setSelectionRange(element, pos, (pos+1));
    }

    return {
      setCaretPosition: setCaretPosition,
      setSelectionRange: setSelectionRange
    }
  }]);


text:
<?php

namespace Oro\Bundle\LocaleBundle\Form\Type;

use Oro\Bundle\FormBundle\Form\Type\CheckboxType;
use Oro\Bundle\FormBundle\Form\Type\OroRichTextType;
use Oro\Bundle\LocaleBundle\Form\DataTransformer\FallbackValueTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Manage value for given localization.
 */
class FallbackValueType extends AbstractType
{
    const NAME = 'oro_locale_fallback_value';

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return self::NAME;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired([
            'entry_type',
        ]);

        $resolver->setDefaults([
            'data_class' => null,
            'entry_options' => [],
            'fallback_type' => FallbackPropertyType::class,
            'fallback_type_localization' => null,
            'fallback_type_parent_localization' => null,
            'enabled_fallbacks' => [],
            'group_fallback_fields' => null,
            'exclude_parent_localization' => false,
            'use_tabs' => false,
        ]);

        $resolver->setNormalizer('group_fallback_fields', function (Options $options, $value) {
            if ($value !== null) {
                return $value;
            }

            return in_array($options['entry_type'], [TextareaType::class, OroRichTextType::class], true);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $valueOptions = array_merge($options['entry_options'], ['required' => false]);

        $builder
            ->add('value', $options['entry_type'], $valueOptions)
            ->add(
                'use_fallback',
                CheckboxType::class,
                [
                    'label' => $options['exclude_parent_localization']
                        ? 'oro.locale.fallback.use_fallback_to_default_value.label'
                        : 'oro.locale.fallback.use_fallback.label'
                ]
            )
            ->add(
                'fallback',
                $options['fallback_type'],
                [
                    'label' => 'oro.locale.fallback.form.label',
                    'tooltip' => 'oro.locale.fallback.form.tooltip',
                    'enabled_fallbacks' => $options['enabled_fallbacks'],
                    'localization' => $options['fallback_type_localization'],
                    'parent_localization' => $options['fallback_type_parent_localization'],
                    'required' => false,
                    'use_tabs' => $options['use_tabs'],
                ]
            );

        $builder->addViewTransformer(new FallbackValueTransformer());

        // disable validation is field uses fallback (because in this case value is null)
        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options, $valueOptions) {
            $data = $event->getData();
            if (is_array($data) && !empty($data['fallback'])) {
                $event->getForm()
                    ->remove('value')
                    ->add('value', $options['entry_type'], array_merge($valueOptions, ['validation_groups' => false]));
            }
        });
    }

    /**
     * {@inheritdoc}
     */
    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['group_fallback_fields'] = $options['group_fallback_fields'];
        $view->vars['exclude_parent_localization'] = $options['exclude_parent_localization'];

        if ($options['use_tabs']) {
            array_splice($view->vars['block_prefixes'], -1, 0, [$this->getBlockPrefix() . '_tabs']);
        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Ardisia furfuracella Standl.

### Remarks
null


text:
using System;
using n.Infrastructure;
using System.Collections.Generic;

namespace n.Infrastructure.Impl
{
	public class nTestView : nView
	{
		public const string TARGET = "TARGET";

		public nTestView(nModel model, Type target) {
			Model = model;
			Action = new nAction() {
				Params = new Dictionary<string, object>() {
					{ TARGET, target },
				}
			};
		}
	}
}


text:
@interface LLShareSocialRequestCommand : LLCommand

@property (nonatomic, strong) NSString *body;
@property (nonatomic, strong) NSURL *url;
@property (nonatomic, strong) UIImage *image;

@end


text:
Validates if the given input is even.

Valid values:

```js
validator.even().validate(null);
validator.even().validate('');
validator.even().validate('2');
validator.even().validate(-2);
validator.even().validate(-0);
validator.even().validate(0);
validator.even().validate(2);
```

Invalid values:

```js
validator.even().validate(undefined);
validator.even().validate('3');
validator.even().validate(-3);
validator.even().validate(-1);
validator.even().validate(1);
validator.even().validate(3);
```


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Auth controllers class
 *
 * @package     GROOT
 * @subpackage  Controllers
 * @category    Controllers
 * @author      Sistiandy Syahbana nugraha <sistiandy.web.id>
 */
class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('User_model');
        $this->load->library('form_validation');
        $this->load->helper('string');
        $this->load->helper('url');
    }

    function index() {
        redirect('admin/auth/login');
    }

    function login() {
        if ($this->session->userdata('logged')) {
            redirect('admin');
        }
        $this->form_validation->set_rules('username', 'Username', 'trim|required');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');
        if ($_POST AND $this->form_validation->run() == TRUE) {
            if ($this->input->post('location')) {
                $lokasi = $this->input->post('location');
            } else {
                $lokasi = NULL;
            }
            $this->process_login($lokasi);
        } else {
            $this->load->view('admin/login');
        }
    }

    // Login Prosessing
    function process_login($lokasi = '') {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');

        if ($this->form_validation->run() == TRUE) {
            $username = $this->input->post('username', TRUE);
            $password = $this->input->post('password', TRUE);
            $this->db->from('user');
            $this->db->where('user_name', $username);
            $this->db->where('user_password', sha1($password));
            $query = $this->db->get();

            if ($query->num_rows() > 0) {
                $this->session->set_userdata('logged', TRUE);
                $this->session->set_userdata('user_id', $query->row('user_id'));
                $this->session->set_userdata('user_name', $query->row('user_name'));
                $this->session->set_userdata('user_role', $query->row('role_id'));
                $this->session->set_userdata('user_email', $query->row('user_email'));
                $this->session->set_userdata('user_full_name', $query->row('user_full_name'));
                if ($lokasi != '') {
                    header("Location:" . htmlspecialchars($lokasi));
                } else {
                    redirect('admin');
                }
            } else {
                if ($lokasi != '') {
                    $this->session->set_flashdata('failed', 'Sorry, username and password do not match');
                    header("Location:" . site_url('admin/auth/login') . "?location=" . urlencode($lokasi));
                } else {
                    $this->session->set_flashdata('failed', 'Sorry, username and password do not match');
                    redirect('admin/auth/login');
                }
            }
        } else {
            $this->session->set_flashdata('failed', 'Sorry, username and password are not complete');
            redirect('admin/auth/login');
        }
    }

    // Logout Processing
    function logout() {
        $this->session->unset_userdata('logged');
        $this->session->unset_userdata('user_id');
        $this->session->unset_userdata('user_name');
        $this->session->unset_userdata('user_role');
        $this->session->unset_userdata('user_email');
        $this->session->unset_userdata('user_full_name');
        if ($this->input->post('location')) {
            $lokasi = $this->input->post('location');
        } else {
            $lokasi = NULL;
        }
        header("Location:" . $lokasi);
    }

}


text:
# Contribution Guide

Thank you for considering contributing to the project!

## Table of contents

* [Bug Reports](#bug-reports)
* [Coding Style](#coding-style)
    - [DocBlocks](#docblocks)

## Bug Reports

To encourage active collaboration, We strongly encourages pull requests, not just bug reports. "Bug reports" may also be sent in the form of a pull request containing a failing test.

However, if you file a bug report, your issue should contain a title and a clear description of the issue. You should also include as much relevant information as possible and a code sample that demonstrates the issue. The goal of a bug report is to make it easy for yourself - and others - to replicate the bug and develop a fix.

Remember, bug reports are created in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the bug report will automatically see any activity or that others will jump to fix it. Creating a bug report serves to help yourself and others start on the path of fixing the problem.

## Coding Style

This project follows the [PSR-2][psr2] coding standard and the [PSR-4][psr4] autoloading standard.

### DocBlocks

The `@param` tags should not be aligned and arguments should be separated by 2 spaces.

Here's an example block:

```php
/**
 * Register a binding with the container.
 *
 * @param  string|array  $abstract
 * @param  \Closure|string|null  $concrete
 * @param  bool  $shared
 * @return void
 */
public function bind($abstract, $concrete = null, $shared = false)
{
    // …
}
```

[psr2]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
[psr4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md


text:
package com.bearapp.material;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class CardContentFragment extends Fragment {

    public CardContentFragment() {
        // Required empty public constructor
    }

    public static CardContentFragment newInstance(Bundle bundle) {
        CardContentFragment fragment = new CardContentFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.recycler_view, container, false);
        ContentAdapter contentAdapter = new ContentAdapter(recyclerView.getContext());
        recyclerView.setAdapter(contentAdapter);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        return recyclerView;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public ImageView picture;
        public TextView name;
        public TextView description;

        public ViewHolder(LayoutInflater layoutInflater, ViewGroup parent) {
            super(layoutInflater.inflate(R.layout.item_card, parent, false));
            picture = (ImageView) itemView.findViewById(R.id.card_image);
            name = (TextView) itemView.findViewById(R.id.card_title);
            description = (TextView) itemView.findViewById(R.id.card_text);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Context context = view.getContext();
                    Intent intent = new Intent(context, DetailActivity.class);
                    intent.putExtra(DetailActivity.EXTRA_POSITION, getAdapterPosition());
                    context.startActivity(intent);
                }
            });
        }
    }

    public static class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {

        private static final int LENGTH = 18;
        private final String[] mPlaces;
        private final String[] mPlaceDesc;
        private final Drawable[] mPlacePictures;

        public ContentAdapter(Context context) {
            Resources resources = context.getResources();
            mPlaces = resources.getStringArray(R.array.places);
            mPlaceDesc = resources.getStringArray(R.array.place_desc);
            TypedArray a = resources.obtainTypedArray(R.array.places_picture);
            mPlacePictures = new Drawable[a.length()];
            for (int i = 0; i < mPlacePictures.length; i++) {
                mPlacePictures[i] = a.getDrawable(i);
            }
            a.recycle();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.picture.setImageDrawable(mPlacePictures[position % mPlacePictures.length]);
            holder.name.setText(mPlaces[position % mPlaces.length]);
            holder.description.setText(mPlaceDesc[position % mPlaceDesc.length]);
        }

        @Override
        public int getItemCount() {
            return LENGTH;
        }
    }

}


text:
#import "IntegrationManagerViewController.h"

#import "WidgetManager.h"

#import "GeneratedInterface-Swift.h"

NSString *const kIntegrationManagerMainScreen = nil;
NSString *const kIntegrationManagerAddIntegrationScreen = @"add_integ";

@interface IntegrationManagerViewController () <ServiceTermsModalCoordinatorBridgePresenterDelegate>
{
    MXSession *mxSession;
    NSString *roomId;
    NSString *screen;
    NSString *widgetId;
    NSString *scalarToken;

    MXHTTPOperation *operation;
}

@property (nonatomic, strong) ServiceTermsModalCoordinatorBridgePresenter *serviceTermsModalCoordinatorBridgePresenter;
@property (nonatomic) BOOL isViewAppearedOnce;

@end

@implementation IntegrationManagerViewController

- (instancetype)initForMXSession:(MXSession *)theMXSession inRoom:(NSString *)theRoomId screen:(NSString *)theScreen widgetId:(NSString *)theWidgetId
{
    self = [super init];
    if (self)
    {
        mxSession = theMXSession;
        roomId = theRoomId;
        screen = theScreen;
        widgetId = theWidgetId;
    }
    return self;
}

+ (NSString*)screenForWidget:(NSString*)widgetType
{
    return [NSString stringWithFormat:@"type_%@", widgetType];
}

- (void)destroy
{
    [super destroy];

    [operation cancel];
    operation = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (!self.isViewAppearedOnce)
    {
        self.isViewAppearedOnce = YES;
        [self loadData];
    }
}

- (void)loadData
{
    RiotSharedSettings *sharedSettings = [[RiotSharedSettings alloc] initWithSession:mxSession];
    if (!sharedSettings.hasIntegrationProvisioningEnabled)
    {
        [self showDisabledIntegrationManagerError];
        return;
    }

    if (!self.URL && !operation)
    {
        [self startActivityIndicator];

        // Make sure we have a scalar token
        MXWeakify(self);
        operation = [[WidgetManager sharedManager] getScalarTokenForMXSession:mxSession validate:YES  success:^(NSString *theScalarToken) {
            MXStrongifyAndReturnIfNil(self);

            self->operation = nil;
            self->scalarToken = theScalarToken;

            // Launch the webview on the right modular webapp page
            self.URL = [self interfaceUrl];

        } failure:^(NSError *error) {
            MXStrongifyAndReturnIfNil(self);

            MXLogDebug(@"[IntegraionManagerVS] Cannot open due to missing scalar token. Error: %@", error);

            self->operation = nil;
            [self stopActivityIndicator];

            if ([error.domain isEqualToString:WidgetManagerErrorDomain]
                && error.code == WidgetManagerErrorCodeTermsNotSigned)
            {
                [self presentTerms];
            }
            else
            {
                [self withdrawViewControllerAnimated:YES completion:^{
                    [[AppDelegate theDelegate] showErrorAsAlert:error];
                }];
            }
        }];
    }
}

#pragma mark - Private methods

/**
 Build the URL to use in the Modular interface webapp.
 */
- (NSString *)interfaceUrl
{
    NSMutableString *url;

    NSString *integrationsUiUrl = [[WidgetManager sharedManager] configForUser:mxSession.myUser.userId].uiUrl;

    if (scalarToken)
    {
        url = [NSMutableString stringWithFormat:@"%@?scalar_token=%@&room_id=%@",
               integrationsUiUrl,
               [MXTools encodeURIComponent:scalarToken],
               [MXTools encodeURIComponent:roomId]
               ];

        if (screen)
        {
            [url appendString:@"&screen="];
            [url appendString:[MXTools encodeURIComponent:screen]];
        }

        if (widgetId)
        {
            [url appendString:@"&integ_id="];
            [url appendString:[MXTools encodeURIComponent:widgetId]];
        }
    }

    return url;
}

#pragma mark - Modular postMessage API implementation

- (void)onPostMessageRequest:(NSString*)requestId data:(NSDictionary*)requestData
{
    NSString *roomIdInEvent, *userId, *action;

    MXJSONModelSetString(roomIdInEvent, requestData[@"room_id"]);
    MXJSONModelSetString(userId, requestData[@"user_id"]);
    MXJSONModelSetString(action, requestData[@"action"]);

    if ([action isEqualToString:@"close_scalar"])
    {
        [self withdrawViewControllerAnimated:YES completion:nil];
        return;
    }

    if (!roomIdInEvent)
    {
        // These APIs don't require roomId
        // Get and set user widgets (not associated with a specific room)
        // If roomId is specified, it must be validated, so room-based widgets agreed
        // handled further down.
        if ([@"set_widget" isEqualToString:action])
        {
            [self setWidget:requestId data:requestData];
            return;
        }
        else if ([@"get_widgets" isEqualToString:action])
        {
            [self getWidgets:requestId data:requestData];
            return;
        }
        else
        {
            [self sendError:[VectorL10n widgetIntegrationMissingRoomId] toRequest:requestId];
            return;
        }
    }

    if (![roomIdInEvent isEqualToString:roomId])
    {
        [self sendError:[VectorL10n widgetIntegrationRoomNotVisible:roomIdInEvent] toRequest:requestId];
        return;
    }

    // Get and set room-based widgets
    if ([@"set_widget" isEqualToString:action])
    {
        [self setWidget:requestId data:requestData];
        return;
    }
    else if ([@"get_widgets" isEqualToString:action])
    {
        [self getWidgets:requestId data:requestData];
        return;
    }

    // These APIs don't require userId
    if ([@"join_rules_state" isEqualToString:action])
    {
        [self getJoinRules:requestId data:requestData];
        return;
    }
    else if ([@"set_plumbing_state" isEqualToString:action])
    {
        [self setPlumbingState:requestId data:requestData];
        return;
    }
    else if ([@"get_membership_count" isEqualToString:action])
    {
        [self getMembershipCount:requestId data:requestData];
        return;
    }
    else if ([@"get_room_enc_state" isEqualToString:action])
    {
        [self getRoomEncState:requestId data:requestData];
        return;
    }
    else if ([@"can_send_event" isEqualToString:action])
    {
        [self canSendEvent:requestId data:requestData];
        return;
    }

    if (!userId)
    {
        [self sendError:[VectorL10n widgetIntegrationMissingUserId] toRequest:requestId];
        return;
    }

    if ([@"membership_state" isEqualToString:action])
    {
        [self getMembershipState:userId request:requestId data:requestData];
    }
    else if ([@"invite" isEqualToString:action])
    {
        [self inviteUser:userId request:requestId data:requestData];
    }
    else if ([@"bot_options" isEqualToString:action])
    {
        [self getBotOptions:userId request:requestId data:requestData];
    }
    else if ([@"set_bot_options" isEqualToString:action])
    {
        [self setBotOptions:userId request:requestId data:requestData];
    }
    else if ([@"set_bot_power" isEqualToString:action])
    {
        [self setBotPower:userId request:requestId data:requestData];
    }
    else
    {
        MXLogDebug(@"[IntegrationManagerViewControllerVC] Unhandled postMessage event with action %@: %@", action, requestData);
    }
}

#pragma mark - Private methods

- (void)roomCheckForRequest:(NSString*)requestId data:(NSDictionary*)requestData onComplete:(void (^)(MXRoom *room, MXRoomState *roomState))onComplete
{
    MXRoom *room = [mxSession roomWithRoomId:roomId];
    if (room)
    {
        [room state:^(MXRoomState *roomState) {
            onComplete(room, roomState);
        }];
    }
    else
    {
        [self sendError:[VectorL10n widgetIntegrationRoomNotRecognised] toRequest:requestId];
    }
}

- (void)inviteUser:(NSString*)userId request:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXLogDebug(@"[IntegrationManagerVC] Received request to invite %@ into room %@.", userId, roomId);

    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {

        MXRoomMember *member = [roomState.members memberWithUserId:userId];
        if (member && member.membership == MXMembershipJoin)
        {
            [self sendNSObjectResponse:@{
                                         @"success": @(YES)
                                         }
                               toRequest:requestId];
        }
        else
        {
            MXWeakify(self);
            [room inviteUser:userId success:^{
                MXStrongifyAndReturnIfNil(self);

                [self sendNSObjectResponse:@{
                                             @"success": @(YES)
                                             }
                                 toRequest:requestId];

            } failure:^(NSError *error) {
                MXStrongifyAndReturnIfNil(self);

                [self sendError:[VectorL10n widgetIntegrationNeedToBeAbleToInvite] toRequest:requestId];
            }];
        }
    }];
}

- (void)setWidget:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXLogDebug(@"[IntegrationManagerVC] Received request to set widget");

    NSString *widget_id, *widgetType, *widgetUrl;
    NSString *widgetName; // optional
    NSDictionary *widgetData ; // optional
    BOOL userWidget = NO;

    MXJSONModelSetString(widget_id, requestData[@"widget_id"]);
    MXJSONModelSetString(widgetType, requestData[@"type"]);
    MXJSONModelSetString(widgetUrl, requestData[@"url"]);
    MXJSONModelSetString(widgetName, requestData[@"name"]);
    MXJSONModelSetDictionary(widgetData, requestData[@"data"]);
    MXJSONModelSetBoolean(userWidget, requestData[@"userWidget"]);

    if (!widget_id)
    {
        [self sendError:[VectorL10n widgetIntegrationUnableToCreate] toRequest:requestId];
        return;
    }

    if (!widgetType)
    {
        [self sendError:[VectorL10n widgetIntegrationUnableToCreate] toRequest:requestId];
        return;
    }

    NSMutableDictionary *widgetEventContent = [NSMutableDictionary dictionary];
    if (widgetUrl)
    {
        widgetEventContent[@"type"] = widgetType;
        widgetEventContent[@"url"] = widgetUrl;

        if (widgetName)
        {
            widgetEventContent[@"name"] = widgetName;
        }
        if (widgetData)
        {
            widgetEventContent[@"data"] = widgetData;
        }
    }
    // else this is a deletion

    __weak __typeof__(self) weakSelf = self;

    if (userWidget)
    {
        // Update the user account data
        NSMutableDictionary *userWidgets = [NSMutableDictionary dictionaryWithDictionary:[mxSession.accountData accountDataForEventType:kMXAccountDataTypeUserWidgets]];

        // Delete existing widget with ID
        [userWidgets removeObjectForKey:widget_id];

        // Add new widget / update
        if (widgetUrl)
        {
            userWidgets[widget_id] = @{
                                      @"content": widgetEventContent,
                                      @"sender": mxSession.myUser.userId,
                                      @"state_key": widget_id,
                                      @"type": kWidgetMatrixEventTypeString,
                                      @"id": widget_id,
                                      };
        }

        [mxSession setAccountData:userWidgets forType:kMXAccountDataTypeUserWidgets success:^{

            typeof(self) self = weakSelf;
            if (self)
            {
                [self sendNSObjectResponse:@{
                                             @"success": @(YES)
                                             }
                                 toRequest:requestId];
            }
        } failure:^(NSError *error) {

            typeof(self) self = weakSelf;
            if (self)
            {
                [self sendError:[VectorL10n widgetIntegrationUnableToCreate] toRequest:requestId];
            }
        }];
    }
    else
    {
        // Room widget
        [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {

            // TODO: Move to kWidgetMatrixEventTypeString ("m.widget") type but when?
            [room sendStateEventOfType:kWidgetModularEventTypeString
                               content:widgetEventContent
                              stateKey:widget_id
                               success:^(NSString *eventId) {

                                   typeof(self) self = weakSelf;
                                   if (self)
                                   {
                                       [self sendNSObjectResponse:@{
                                                                    @"success": @(YES)
                                                                    }
                                                        toRequest:requestId];
                                   }
                               }
                               failure:^(NSError *error) {

                                   typeof(self) self = weakSelf;
                                   if (self)
                                   {
                                       [self sendError:[VectorL10n widgetIntegrationFailedToSendRequest] toRequest:requestId];
                                   }
                               }];
        }];
    }
}

- (void)getWidgets:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXWeakify(self);
    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        MXStrongifyAndReturnIfNil(self);

        NSMutableArray<NSDictionary*> *widgetStateEvents = [NSMutableArray array];

        NSArray<Widget*> *widgets = [[WidgetManager sharedManager] widgetsInRoom:room withRoomState:roomState];
        for (Widget *widget in widgets)
        {
            [widgetStateEvents addObject:widget.widgetEvent.JSONDictionary];
        }

        // Add user widgets (not linked to a specific room)
        for (Widget *widget in [[WidgetManager sharedManager] userWidgets:self->mxSession])
        {
            [widgetStateEvents addObject:widget.widgetEvent.JSONDictionary];
        }

        [self sendNSObjectResponse:widgetStateEvents toRequest:requestId];
    }];
}

- (void)getRoomEncState:(NSString*)requestId data:(NSDictionary*)requestData
{
    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        [self sendBoolResponse:room.summary.isEncrypted toRequest:requestId];
    }];
}

- (void)canSendEvent:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXWeakify(self);
    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        MXStrongifyAndReturnIfNil(self);

        NSString *eventType;
        BOOL isState = NO;

        if (room.summary.membership != MXMembershipJoin)
        {
            [self sendError:[VectorL10n widgetIntegrationMustBeInRoom] toRequest:requestId];
            return;
        }

        MXJSONModelSetString(eventType, requestData[@"event_type"]);
        MXJSONModelSetBoolean(isState, requestData[@"is_state"]);

        MXRoomPowerLevels *powerLevels = roomState.powerLevels;
        NSInteger userPowerLevel = [powerLevels powerLevelOfUserWithUserID:self->mxSession.myUser.userId];

        BOOL canSend = NO;

        if (isState)
        {
            canSend = (userPowerLevel >= [powerLevels minimumPowerLevelForSendingEventAsStateEvent:eventType]);
        }
        else
        {
            canSend = (userPowerLevel >= [powerLevels minimumPowerLevelForSendingEventAsMessage:eventType]);
        }

        if (canSend)
        {
            [self sendBoolResponse:YES toRequest:requestId];
        }
        else
        {
            [self sendError:[VectorL10n widgetIntegrationNoPermissionInRoom] toRequest:requestId];
        }

    }];
}

- (void)getMembershipState:(NSString*)userId request:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXLogDebug(@"[IntegrationManagerVC] membership_state of %@ in room %@ requested.", userId, roomId);

    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        MXRoomMember *member = [roomState.members memberWithUserId:userId];
        [self sendNSObjectResponse:member.originalEvent.content toRequest:requestId];
    }];
}

- (void)getJoinRules:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXLogDebug(@"[IntegrationManagerVC] join_rules of %@ requested.", roomId);

    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        MXEvent *event = [roomState stateEventsWithType:kMXEventTypeStringRoomJoinRules].lastObject;
        [self sendNSObjectResponse:event.JSONDictionary toRequest:requestId];
    }];
}

- (void)setPlumbingState:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXLogDebug(@"[IntegrationManagerVC] Received request to set plumbing state to status %@ in room %@.", requestData[@"status"], roomId);

    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        NSString *status;
        MXJSONModelSetString(status, requestData[@"status"]);

        if (status)
        {
            __weak __typeof__(self) weakSelf = self;

            [room sendStateEventOfType:kMXEventTypeStringRoomPlumbing
                               content:@{
                                         @"status": status
                                         }
                              stateKey:nil
                               success:^(NSString *eventId) {

                                   typeof(self) self = weakSelf;
                                   if (self)
                                   {
                                       [self sendNSObjectResponse:@{
                                                                    @"success": @(YES)
                                                                    }
                                                        toRequest:requestId];
                                   }
                               }
                               failure:^(NSError *error) {

                                   typeof(self) self = weakSelf;
                                   if (self)
                                   {
                                       [self sendError:[VectorL10n widgetIntegrationFailedToSendRequest] toRequest:requestId];
                                   }
                               }];
        }
        else
        {
            MXLogDebug(@"[IntegrationManagerVC] setPlumbingState. Error: Plumbing state status should be a string.");
        }

    }];
}

- (void)getBotOptions:(NSString*)userId request:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXLogDebug(@"[IntegrationManagerVC] Received request to get options for bot %@ in room %@", userId, roomId);

    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        NSString *stateKey = [NSString stringWithFormat:@"_%@", userId];

        NSArray<MXEvent*> *stateEvents = [roomState stateEventsWithType:kMXEventTypeStringRoomBotOptions];

        MXEvent *botOptionsEvent;

        for (MXEvent *stateEvent in stateEvents)
        {
            if ([stateEvent.stateKey isEqualToString:stateKey])
            {
                if (!botOptionsEvent || stateEvent.ageLocalTs > botOptionsEvent.ageLocalTs)
                {
                    botOptionsEvent = stateEvent;
                }
            }
        }

        [self sendNSObjectResponse:botOptionsEvent.JSONDictionary toRequest:requestId];

    }];
}

- (void)setBotOptions:(NSString*)userId request:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXLogDebug(@"[IntegrationManagerVC] Received request to set options for bot %@ in room %@", userId, roomId);

    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        NSDictionary *content;
        MXJSONModelSetDictionary(content, requestData[@"content"]);

        if (content)
        {
            __weak __typeof__(self) weakSelf = self;

            NSString *stateKey = [NSString stringWithFormat:@"_%@", userId];

            [room sendStateEventOfType:kMXEventTypeStringRoomBotOptions
                               content:content
                              stateKey:stateKey
                               success:^(NSString *eventId) {

                                   typeof(self) self = weakSelf;
                                   if (self)
                                   {
                                       [self sendNSObjectResponse:@{
                                                                    @"success": @(YES)
                                                                    }
                                                        toRequest:requestId];
                                   }
                               }
                               failure:^(NSError *error) {

                                   typeof(self) self = weakSelf;
                                   if (self)
                                   {
                                       [self sendError:[VectorL10n widgetIntegrationFailedToSendRequest] toRequest:requestId];
                                   }
                               }];
        }
        else
        {
            MXLogDebug(@"[IntegrationManagerVC] setBotOptions. Error: options should be a dict.");
        }
    }];
}

- (void)setBotPower:(NSString*)userId request:(NSString*)requestId data:(NSDictionary*)requestData
{
    MXLogDebug(@"[IntegrationManagerVC] Received request to set power level to %@ for bot %@ in room %@.", requestData[@"level"], userId, roomId);

    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        NSInteger level = -1;
        MXJSONModelSetInteger(level, requestData[@"level"]);

        if (level >= 0)
        {
            __weak __typeof__(self) weakSelf = self;

            [room setPowerLevelOfUserWithUserID:userId powerLevel:level success:^{

                typeof(self) self = weakSelf;
                if (self)
                {
                    [self sendNSObjectResponse:@{
                                                 @"success": @(YES)
                                                 }
                                     toRequest:requestId];
                }

            } failure:^(NSError *error) {

                typeof(self) self = weakSelf;
                if (self)
                {
                    [self sendError:[VectorL10n widgetIntegrationFailedToSendRequest] toRequest:requestId];
                }
            }];
        }
        else
        {
            MXLogDebug(@"[IntegrationManagerVC] setBotPower. Power level must be positive integer.");
            [self sendError:[VectorL10n widgetIntegrationPositivePowerLevel] toRequest:requestId];
        }
    }];
}

- (void)getMembershipCount:(NSString*)requestId data:(NSDictionary*)requestData
{
    [self roomCheckForRequest:requestId data:requestData onComplete:^(MXRoom *room, MXRoomState *roomState) {
        NSUInteger membershipCount = room.summary.membersCount.joined;
        [self sendIntegerResponse:membershipCount toRequest:requestId];
    }];
}

#pragma mark - Widget Permission

- (void)checkWidgetPermissionWithCompletion:(void (^)(BOOL granted))completion
{
    // The integration manager widget has its own terms
    completion(YES);
}

#pragma mark - Disabled Integrations

- (void)showDisabledIntegrationManagerError
{
    NSString *message = [VectorL10n widgetIntegrationManagerDisabled];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];

    [alert addAction:[UIAlertAction actionWithTitle:[VectorL10n ok]
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * action) {
                                                [self withdrawViewControllerAnimated:YES completion:nil];
                                            }]];

    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - Service terms

- (void)presentTerms
{
    WidgetManagerConfig *config =  [[WidgetManager sharedManager] configForUser:mxSession.myUser.userId];

    MXLogDebug(@"[IntegrationManagerVC] presentTerms for %@", config.baseUrl);

    ServiceTermsModalCoordinatorBridgePresenter *serviceTermsModalCoordinatorBridgePresenter = [[ServiceTermsModalCoordinatorBridgePresenter alloc] initWithSession:mxSession baseUrl:config.baseUrl
                                                                                serviceType:MXServiceTypeIntegrationManager
                                                                                accessToken:config.scalarToken];

    serviceTermsModalCoordinatorBridgePresenter.delegate = self;

    [serviceTermsModalCoordinatorBridgePresenter presentFrom:self animated:YES];
    self.serviceTermsModalCoordinatorBridgePresenter = serviceTermsModalCoordinatorBridgePresenter;
}

- (void)serviceTermsModalCoordinatorBridgePresenterDelegateDidAccept:(ServiceTermsModalCoordinatorBridgePresenter * _Nonnull)coordinatorBridgePresenter
{
    [coordinatorBridgePresenter dismissWithAnimated:YES completion:^{
        [self loadData];
    }];
    self.serviceTermsModalCoordinatorBridgePresenter = nil;
}

- (void)serviceTermsModalCoordinatorBridgePresenterDelegateDidDecline:(ServiceTermsModalCoordinatorBridgePresenter * _Nonnull)coordinatorBridgePresenter session:(MXSession * _Nonnull)session
{
    [coordinatorBridgePresenter dismissWithAnimated:YES completion:^{
        [self withdrawViewControllerAnimated:YES completion:nil];
    }];
    self.serviceTermsModalCoordinatorBridgePresenter = nil;
}

- (void)serviceTermsModalCoordinatorBridgePresenterDelegateDidClose:(ServiceTermsModalCoordinatorBridgePresenter * _Nonnull)coordinatorBridgePresenter
{
    self.serviceTermsModalCoordinatorBridgePresenter = nil;
}

@end


text:
package gorm

import (
	"database/sql"
	"fmt"
	"os"
	"reflect"
	"regexp"
	"runtime"
	"strings"
)

func fileWithLineNum() string {
	for i := 1; i < 15; i++ {
		_, file, line, ok := runtime.Caller(i)
		if ok && (!regexp.MustCompile(`jinzhu/gorm/.*.go`).MatchString(file) || regexp.MustCompile(`jinzhu/gorm/.*test.go`).MatchString(file)) {
			return fmt.Sprintf("%v:%v", strings.TrimPrefix(file, os.Getenv("GOPATH")+"src/"), line)
		}
	}
	return ""
}

func setFieldValue(field reflect.Value, value interface{}) (result bool) {
	result = false
	if field.IsValid() && field.CanAddr() {
		result = true
		if scanner, ok := field.Addr().Interface().(sql.Scanner); ok {
			scanner.Scan(value)
		} else if reflect.TypeOf(value).ConvertibleTo(field.Type()) {
			field.Set(reflect.ValueOf(value).Convert(field.Type()))
		} else {
			result = false
		}
	}
	return
}

func isBlank(value reflect.Value) bool {
	return reflect.DeepEqual(value.Interface(), reflect.Zero(value.Type()).Interface())
}

func toSearchableMap(attrs ...interface{}) (result interface{}) {
	if len(attrs) > 1 {
		if str, ok := attrs[0].(string); ok {
			result = map[string]interface{}{str: attrs[1]}
		}
	} else if len(attrs) == 1 {
		if attr, ok := attrs[0].(map[string]interface{}); ok {
			result = attr
		}

		if attr, ok := attrs[0].(interface{}); ok {
			result = attr
		}
	}
	return
}

func convertInterfaceToMap(values interface{}) map[string]interface{} {
	attrs := map[string]interface{}{}

	switch value := values.(type) {
	case map[string]interface{}:
		for k, v := range value {
			attrs[ToSnake(k)] = v
		}
	case []interface{}:
		for _, v := range value {
			for key, value := range convertInterfaceToMap(v) {
				attrs[key] = value
			}
		}
	case interface{}:
		reflectValue := reflect.ValueOf(values)

		switch reflectValue.Kind() {
		case reflect.Map:
			for _, key := range reflectValue.MapKeys() {
				attrs[ToSnake(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
			}
		default:
			scope := Scope{Value: values}
			for _, field := range scope.Fields() {
				if !field.IsBlank {
					attrs[field.DBName] = field.Value
				}
			}
		}
	}
	return attrs
}


text:
<?php

namespace Silvestra\Bundle\Text\NodeBundle\Model;

use Silvestra\Component\Text\Model\TextInterface;
use Tadcka\Component\Tree\Model\NodeInterface;

class TextNode implements TextNodeInterface
{

    /**
     * @var TextInterface
     */
    protected $text;

    /**
     * @var NodeInterface
     */
    protected $node;

    /**
     * {@inheritdoc}
     */
    public function setText(TextInterface $text)
    {
        $this->text = $text;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getText()
    {
        return $this->text;
    }

    /**
     * {@inheritdoc}
     */
    public function setNode(NodeInterface $node)
    {
        $this->node = $node;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getNode()
    {
        return $this->node;
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由工具生成。
//     运行时版本:4.0.30319.42000
//
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------

namespace ConsoleDBApp.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.3.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=revenger\\sqlexpress;Initial Catalog=sac;Persist Security Info=True;Us" +
            "er ID=sa")]
        public string sacConnectionString {
            get {
                return ((string)(this["sacConnectionString"]));
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=revenger\\sqlexpress;Initial Catalog=qichacha;Persist Security Info=Tr" +
            "ue;User ID=sa")]
        public string qichachaConnectionString {
            get {
                return ((string)(this["qichachaConnectionString"]));
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=REVENGER\\SQLEXPRESS;Initial Catalog=chuci_license;Persist Security In" +
            "fo=True;User ID=sa")]
        public string chuci_licenseConnectionString {
            get {
                return ((string)(this["chuci_licenseConnectionString"]));
            }
        }
    }
}


text:
package jenkins.security;

import com.gargoylesoftware.htmlunit.Page;
import hudson.model.UnprotectedRootAction;
import hudson.security.ACL;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.util.HttpResponses;
import jenkins.model.Jenkins;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.HttpResponse;

public class Security380Test {

    @Rule
    public JenkinsRule j = new JenkinsRule();

    @Issue("SECURITY-380")
    @Test
    public void testGetItemsWithoutAnonRead() throws Exception {
        FullControlOnceLoggedInAuthorizationStrategy strategy = new FullControlOnceLoggedInAuthorizationStrategy();
        strategy.setAllowAnonymousRead(false);
        Jenkins.get().setAuthorizationStrategy(strategy);

        Jenkins.get().setSecurityRealm(j.createDummySecurityRealm());

        j.createFreeStyleProject();
        ACL.impersonate2(Jenkins.ANONYMOUS2, new Runnable() {
            @Override
            public void run() {
                Assert.assertEquals("no items", 0, Jenkins.get().getItems().size());
            }
        });
    }

    @Issue("SECURITY-380")
    @Test
    public void testGetItems() throws Exception {
        FullControlOnceLoggedInAuthorizationStrategy strategy = new FullControlOnceLoggedInAuthorizationStrategy();
        strategy.setAllowAnonymousRead(true);
        Jenkins.get().setAuthorizationStrategy(strategy);

        Jenkins.get().setSecurityRealm(j.createDummySecurityRealm());

        j.createFreeStyleProject();
        ACL.impersonate2(Jenkins.ANONYMOUS2, new Runnable() {
            @Override
            public void run() {
                Assert.assertEquals("one item", 1, Jenkins.get().getItems().size());
            }
        });
    }

    @Issue("SECURITY-380")
    @Test
    public void testWithUnprotectedRootAction() throws Exception {
        FullControlOnceLoggedInAuthorizationStrategy strategy = new FullControlOnceLoggedInAuthorizationStrategy();
        strategy.setAllowAnonymousRead(false);
        Jenkins.get().setAuthorizationStrategy(strategy);

        Jenkins.get().setSecurityRealm(j.createDummySecurityRealm());
        j.createFreeStyleProject();

        JenkinsRule.WebClient wc = j.createWebClient();
        Page page = wc.goTo("listJobs", "text/plain");
        // return "0\r\n"
        Assert.assertEquals("expect 0 items", "0", page.getWebResponse().getContentAsString().trim());
    }

    @TestExtension
    public static class JobListingUnprotectedRootAction implements UnprotectedRootAction {

        @Override
        public String getIconFileName() {
            return null;
        }

        @Override
        public String getDisplayName() {
            return null;
        }

        @Override
        public String getUrlName() {
            return "listJobs";
        }

        public HttpResponse doIndex() throws Exception {
            return HttpResponses.plainText(Integer.toString(Jenkins.get().getItems().size()));
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CreditCardPage</title>
<meta name="date" content="2018-11-08">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.mercadopago.android.px.testcheckout.pages

Class CreditCardPage

java.lang.Object

com.mercadopago.android.testlib.pages.PageObject<CheckoutValidator>

com.mercadopago.android.px.testcheckout.pages.CreditCardPage

public class CreditCardPage
extends PageObject<CheckoutValidator>

Field Summary

Fields inherited from class com.mercadopago.android.testlib.pages.PageObject

validator

Constructor Summary

Constructors

Constructor and Description

CreditCardPage()

CreditCardPage(CheckoutValidator validator)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

ReviewPaymentMethodsPage
clickPaymentMethodNotSupportedSnackbar()

NamePage
enterCreditCardNumber(java.lang.String cardNumber)

CreditCardPage
enterExcludedCreditCardNumber(java.lang.String cardNumber)

PaymentMethodPage
pressBack()

NoCheckoutPage
pressBackWithExclusion()

CreditCardPage
validate(CheckoutValidator validator)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CreditCardPage

public CreditCardPage()

CreditCardPage

public CreditCardPage(CheckoutValidator validator)

Method Detail

validate

public CreditCardPage validate(CheckoutValidator validator)

Specified by:

validate in class PageObject<CheckoutValidator>

enterCreditCardNumber

public NamePage enterCreditCardNumber(java.lang.String cardNumber)

pressBackWithExclusion

public NoCheckoutPage pressBackWithExclusion()

pressBack

public PaymentMethodPage pressBack()

enterExcludedCreditCardNumber

public CreditCardPage enterExcludedCreditCardNumber(java.lang.String cardNumber)

clickPaymentMethodNotSupportedSnackbar

public ReviewPaymentMethodsPage clickPaymentMethodNotSupportedSnackbar()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
var _       = require('lodash');
var capture = require('../capture');

exports.assert = function(/*[error,] response, fn*/) {
  var response;
  if (this.__shimmed.assert.length < 3) {
    response = arguments[0];
  } else {
    response = arguments[1];
  }

  capture.add({
    request: extractRequest(this),
    response: extractResponse(this, response)
  });
  return this.__shimmed.assert.apply(this, arguments);
};

// These headers are set on every request
// But not very useful in the documentation
var requestHeaderBlacklist = [
  'host',
  'accept-encoding',
  'user-agent'
];

function extractRequest(superTest) {
  var fields = {
    headers: requestHeaders(superTest.req),
    method: superTest.req.method,
    path: superTest.req.path
  };
  if (superTest._data) {
    fields.data = superTest._data;
  }
  return fields;
}

function extractResponse(superTest, response) {
  return {
    status: response.status,
    headers: responseHeaders(superTest, response),
    body: superTest.res.body || superTest.res.text
  };
}

function requestHeaders(superTest) {
  return _.omit(superTest._headers, function(value, key) {
    var excluded = requestHeaderBlacklist.indexOf(key) !== -1;
    return excluded || (!value);
  });
}

function responseHeaders(superTest, response) {
  // only show response headers that were asserted on
  var names = Object.keys(superTest._fields).map(function(s) { return s.toLowerCase() });
  return _.pick(response.headers, function(value, key) {
    return names.indexOf(key.toLowerCase()) !== -1;
  });
}


text:
/* globals describe, beforeEach, module, it, inject, expect */
describe('myApp.version module', function() {
    'use strict';
    beforeEach(module('myApp.version'));

    describe('version service', function() {
        it('should return current version', inject(function(version) {
            expect(version).toEqual('0.1');
        }));
    });
});


text:
"""
L{HostKeys}
"""

import base64
import binascii
from Crypto.Hash import SHA, HMAC
import UserDict

from paramiko.common import *
from paramiko.dsskey import DSSKey
from paramiko.rsakey import RSAKey

class InvalidHostKey(Exception):

    def __init__(self, line, exc):
        self.line = line
        self.exc = exc
        self.args = (line, exc)

class HostKeyEntry:
    """
    Representation of a line in an OpenSSH-style "known hosts" file.
    """

    def __init__(self, hostnames=None, key=None):
        self.valid = (hostnames is not None) and (key is not None)
        self.hostnames = hostnames
        self.key = key

    def from_line(cls, line):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the openssh known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        @param line: a line from an OpenSSH known_hosts file
        @type line: str
        """
        fields = line.split(' ')
        if len(fields) < 3:
            # Bad number of fields
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(',')

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            if keytype == 'ssh-rsa':
                key = RSAKey(data=base64.decodestring(key))
            elif keytype == 'ssh-dss':
                key = DSSKey(data=base64.decodestring(key))
            else:
                return None
        except binascii.Error, e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
    from_line = classmethod(from_line)

    def to_line(self):
        """
        Returns a string in OpenSSH known_hosts file format, or None if
        the object is not in a valid state.  A trailing newline is
        included.
        """
        if self.valid:
            return '%s %s %s\n' % (','.join(self.hostnames), self.key.get_name(),
                   self.key.get_base64())
        return None

    def __repr__(self):
        return '<HostKeyEntry %r: %r>' % (self.hostnames, self.key)

class HostKeys (UserDict.DictMixin):
    """
    Representation of an openssh-style "known hosts" file.  Host keys can be
    read from one or more files, and then individual hosts can be looked up to
    verify server keys during SSH negotiation.

    A HostKeys object can be treated like a dict; any dict lookup is equivalent
    to calling L{lookup}.

    @since: 1.5.3
    """

    def __init__(self, filename=None):
        """
        Create a new HostKeys object, optionally loading keys from an openssh
        style host-key file.

        @param filename: filename to load host keys from, or C{None}
        @type filename: str
        """
        # emulate a dict of { hostname: { keytype: PKey } }
        self._entries = []
        if filename is not None:
            self.load(filename)

    def add(self, hostname, keytype, key):
        """
        Add a host key entry to the table.  Any existing entry for a
        C{(hostname, keytype)} pair will be replaced.

        @param hostname: the hostname (or IP) to add
        @type hostname: str
        @param keytype: key type (C{"ssh-rsa"} or C{"ssh-dss"})
        @type keytype: str
        @param key: the key to add
        @type key: L{PKey}
        """
        for e in self._entries:
            if (hostname in e.hostnames) and (e.key.get_name() == keytype):
                e.key = key
                return
        self._entries.append(HostKeyEntry([hostname], key))

    def load(self, filename):
        """
        Read a file of known SSH host keys, in the format used by openssh.
        This type of file unfortunately doesn't exist on Windows, but on
        posix, it will usually be stored in
        C{os.path.expanduser("~/.ssh/known_hosts")}.

        If this method is called multiple times, the host keys are merged,
        not cleared.  So multiple calls to C{load} will just call L{add},
        replacing any existing entries and adding new ones.

        @param filename: name of the file to read host keys from
        @type filename: str

        @raise IOError: if there was an error reading the file
        """
        f = open(filename, 'r')
        for line in f:
            line = line.strip()
            if (len(line) == 0) or (line[0] == '#'):
                continue
            e = HostKeyEntry.from_line(line)
            if e is not None:
                self._entries.append(e)
        f.close()

    def save(self, filename):
        """
        Save host keys into a file, in the format used by openssh.  The order of
        keys in the file will be preserved when possible (if these keys were
        loaded from a file originally).  The single exception is that combined
        lines will be split into individual key lines, which is arguably a bug.

        @param filename: name of the file to write
        @type filename: str

        @raise IOError: if there was an error writing the file

        @since: 1.6.1
        """
        f = open(filename, 'w')
        for e in self._entries:
            line = e.to_line()
            if line:
                f.write(line)
        f.close()

    def lookup(self, hostname):
        """
        Find a hostkey entry for a given hostname or IP.  If no entry is found,
        C{None} is returned.  Otherwise a dictionary of keytype to key is
        returned.  The keytype will be either C{"ssh-rsa"} or C{"ssh-dss"}.

        @param hostname: the hostname (or IP) to lookup
        @type hostname: str
        @return: keys associated with this host (or C{None})
        @rtype: dict(str, L{PKey})
        """
        class SubDict (UserDict.DictMixin):
            def __init__(self, hostname, entries, hostkeys):
                self._hostname = hostname
                self._entries = entries
                self._hostkeys = hostkeys

            def __getitem__(self, key):
                for e in self._entries:
                    if e.key.get_name() == key:
                        return e.key
                raise KeyError(key)

            def __setitem__(self, key, val):
                for e in self._entries:
                    if e.key is None:
                        continue
                    if e.key.get_name() == key:
                        # replace
                        e.key = val
                        break
                else:
                    # add a new one
                    e = HostKeyEntry([hostname], val)
                    self._entries.append(e)
                    self._hostkeys._entries.append(e)

            def keys(self):
                return [e.key.get_name() for e in self._entries if e.key is not None]

        entries = []
        for e in self._entries:
            for h in e.hostnames:
                if (h.startswith('|1|') and (self.hash_host(hostname, h) == h)) or (h == hostname):
                    entries.append(e)
        if len(entries) == 0:
            return None
        return SubDict(hostname, entries, self)

    def check(self, hostname, key):
        """
        Return True if the given key is associated with the given hostname
        in this dictionary.

        @param hostname: hostname (or IP) of the SSH server
        @type hostname: str
        @param key: the key to check
        @type key: L{PKey}
        @return: C{True} if the key is associated with the hostname; C{False}
            if not
        @rtype: bool
        """
        k = self.lookup(hostname)
        if k is None:
            return False
        host_key = k.get(key.get_name(), None)
        if host_key is None:
            return False
        return str(host_key) == str(key)

    def clear(self):
        """
        Remove all host keys from the dictionary.
        """
        self._entries = []

    def __getitem__(self, key):
        ret = self.lookup(key)
        if ret is None:
            raise KeyError(key)
        return ret

    def __setitem__(self, hostname, entry):
        # don't use this please.
        if len(entry) == 0:
            self._entries.append(HostKeyEntry([hostname], None))
            return
        for key_type in entry.keys():
            found = False
            for e in self._entries:
                if (hostname in e.hostnames) and (e.key.get_name() == key_type):
                    # replace
                    e.key = entry[key_type]
                    found = True
            if not found:
                self._entries.append(HostKeyEntry([hostname], entry[key_type]))

    def keys(self):
        # python 2.4 sets would be nice here.
        ret = []
        for e in self._entries:
            for h in e.hostnames:
                if h not in ret:
                    ret.append(h)
        return ret

    def values(self):
        ret = []
        for k in self.keys():
            ret.append(self.lookup(k))
        return ret

    def hash_host(hostname, salt=None):
        """
        Return a "hashed" form of the hostname, as used by openssh when storing
        hashed hostnames in the known_hosts file.

        @param hostname: the hostname to hash
        @type hostname: str
        @param salt: optional salt to use when hashing (must be 20 bytes long)
        @type salt: str
        @return: the hashed hostname
        @rtype: str
        """
        if salt is None:
            salt = rng.read(SHA.digest_size)
        else:
            if salt.startswith('|1|'):
                salt = salt.split('|')[2]
            salt = base64.decodestring(salt)
        assert len(salt) == SHA.digest_size
        hmac = HMAC.HMAC(salt, hostname, SHA).digest()
        hostkey = '|1|%s|%s' % (base64.encodestring(salt), base64.encodestring(hmac))
        return hostkey.replace('\n', '')
    hash_host = staticmethod(hash_host)


text:
package org.camunda.bpm.integrationtest.functional.ejb.remote.bean;

import javax.ejb.EJB;
import javax.inject.Named;
import javax.naming.InitialContext;

import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.integrationtest.util.TestContainer;

/**
 * A CDI bean delegating to the remote business
 * interface of a SLSB from a different application.
 *
 * @author Daniel Meyer
 *
 */
@Named
public class RemoteSLSBClientDelegateBean implements JavaDelegate {

  @Override
  public void execute(DelegateExecution execution) throws Exception {
    BusinessInterface businessInterface = (BusinessInterface) new InitialContext().lookup("java:global/" +
        TestContainer.getAppName() +
        "service/" +
        "RemoteSLSBean!org.camunda.bpm.integrationtest.functional.ejb.remote.bean.BusinessInterface");

    execution.setVariable("result", businessInterface.doBusiness());
  }

}


text:
import {Request, Response} from 'express';
import {customers} from './data';

export function getAll(req: Request, res: Response): void {
    res.send(customers);
}


text:
package org.sana.android.provider;

import android.net.Uri;

import org.sana.core.VHT;

/**
 * Created by Marting on 21/11/2016.
 */

public class VHTs {
    public static final String TAG = VHTs.class.getSimpleName();

    public static final String AUTHORITY = "org.sana.provider";

    public static final Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY);

    /**
     * The MIME type of CONTENT_URI providing a directory of vhts.
     */
    public static final String CONTENT_TYPE =
            "vnd.android.cursor.dir/org.sana.vht";

    /** The content type of {@link #CONTENT_URI} for a single instance. */
    public static final String CONTENT_ITEM_TYPE =
            "vnd.android.cursor.item/org.sana.vht";

    /**
     * The content:// style URI for this content provider.
     */
    public static final Uri CONTENT_URI = Uri.parse("content://"
            + AUTHORITY + "/core/vht");
    /**
     * sort order according to the first name
     */
    public static final String FIRST_NAME_SORT_ORDER = Contract.FIRST_NAME + " ASC";

    public interface Contract extends BaseContract<VHT>{
        public static final String PHONE_NUMBER = "phone_number";
        public static final String FIRST_NAME = "first_name";
        public static final String LAST_NAME = "last_name";
        public static final String LOCATION = "location";
    }
}


text:
/**
 * Get the window associated with the element
 * @argument {Element} element
 * @returns {Window}
 */
export default function getWindow(element) {
  const ownerDocument = element.ownerDocument;
  return ownerDocument ? ownerDocument.defaultView : window;
}


text:
package com.github.tycrelic.sqldisadvantage.command;

import com.github.tycrelic.sqldisadvantage.parser.ClientEnvironment;

public class ColumnCommand extends SqlClientCommand {
	private String columnName;
  private String variableName;

	/*public void execute(ClientEnvironment env) {

	}*/

	/**
	 * @return the columnName
	 */
	public String getColumnName() {
		return columnName;
	}

	/**
	 * @param columnName the columnName to set
	 */
	public void setColumnName(String columnName) {
		this.columnName = columnName.toUpperCase();
	}

	/**
	 * @return the variableName
	 */
	public String getVariableName() {
		return variableName;
	}

	/**
	 * @param variableName the variableName to set
	 */
	public void setVariableName(String variableName) {
		this.variableName = variableName.toUpperCase();
	}

}


text:
PKG_NAME = zsh
PKG_VERS = 5.0.5
PKG_EXT = tar.bz2
PKG_DIST_NAME = $(PKG_NAME)-$(PKG_VERS).$(PKG_EXT)
PKG_DIST_SITE = http://www.zsh.org/pub/
PKG_DIR = $(PKG_NAME)-$(PKG_VERS)

DEPENDS = cross/ncursesw

HOMEPAGE = http://www.zsh.org/
COMMENT  = Zsh is a shell designed for interactive use, although it is also a powerful scripting language.
LICENSE  = Custom

GNU_CONFIGURE = 1

INSTALL_TARGET = myInstall

include ../../mk/spksrc.cross-cc.mk

.PHONY: myInstall
myInstall:
	$(RUN) $(MAKE) install DESTDIR=$(INSTALL_DIR)