text:
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojsWatchdogPlugin = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (global){
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);

var _videoJs2 = _interopRequireDefault(_videoJs);

// Default options for the plugin.
var defaults = {
  timeout: 1000,
  errors: {
    1: {
      type: 'MEDIA_ERR_ABORTED',
      headline: 'The video download was cancelled'
    },
    2: {
      type: 'MEDIA_ERR_NETWORK',
      headline: 'The video connection was lost, please confirm you are ' + 'connected to the internet'
    },
    3: {
      type: 'MEDIA_ERR_DECODE',
      headline: 'The video is bad or in a format that cannot be played on your browser'
    },
    4: {
      type: 'MEDIA_ERR_SRC_NOT_SUPPORTED',
      headline: 'This video is either unavailable or not supported in this browser'
    },
    5: {
      type: 'MEDIA_ERR_ENCRYPTED',
      headline: 'The video you are trying to watch is encrypted and we do not know how ' + 'to decrypt it'
    },
    unknown: {
      type: 'MEDIA_ERR_UNKNOWN',
      headline: 'An unanticipated problem was encountered, check back soon and try again'
    }
  }
};

/**
 * Function to invoke when the player is ready.
 *
 * This is a great place for your plugin to initialize itself. When this
 * function is called, the player will have its DOM and child components
 * in place.
 *
 * @function onPlayerReady
 * @param    {Player} player
 * @param    {Object} [options={}]
 */
var onPlayerReady = function onPlayerReady(player, options) {
  var display = undefined;
  var watchdog = undefined;
  var errorTime = undefined;
  var request = undefined;
  var waitingForConnection = false;

  var resetWatchdog = function resetWatchdog() {
    player.clearInterval(watchdog);
    watchdog = player.setInterval(function () {
      if (!waitingForConnection) {
        return;
      }
      if (navigator.onLine && player.src()) {
        if (request) {
          request.abort();
        }
        request = new XMLHttpRequest();
        request.open('head', options.testUrl || player.src(), true);
        request.onreadystatechange = function receiveResponse() {
          if (this.readyState === 4 && this.status === 200) {
            waitingForConnection = false;
            display.close();
            player.src(player.src());
            player.currentTime(errorTime);
            player.play();
          }
        };
        request.send();
      }
    }, options.timeout);
  };

  player.on('error', function () {
    var error = player.error();

    if (player.src() && error.code === 2) {
      waitingForConnection = true;
      errorTime = player.cache_.currentTime;
    }
    var content = document.createElement('div');

    display = player.errorDisplay;
    content.innerHTML = '
\n
' + options.errors[error.code].headline + '
\n
';
    display.fillWith(content);
  });

  player.on('dispose', function () {
    player.clearInterval(watchdog);
  });

  resetWatchdog();
};

/**
 * Watchdog video.js plugin.
 *
 * In the plugin function, the value of `this` is a video.js `Player`
 * instance. You cannot rely on the player being in a "ready" state here,
 * depending on how the plugin is invoked. This may or may not be important
 * to you; if not, remove the wait for "ready"!
 *
 * @function watchdogPlugin
 * @param    {Object} [options={}]
 *           An object of options left to the plugin author to define.
 */
var watchdogPlugin = function watchdogPlugin(options) {
  var _this = this;

  this.ready(function () {
    onPlayerReady(_this, _videoJs2['default'].mergeOptions(defaults, options));
  });
};

// Register the plugin with video.js.
_videoJs2['default'].plugin('watchdogPlugin', watchdogPlugin);

// Include the version number.
watchdogPlugin.VERSION = '0.1.4';

exports['default'] = watchdogPlugin;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
});


text:
static int bufp;
static char buf[BUFFER];

int getch(){
  return bufp > 0 ? buf[--bufp] : getchar();
}

void ungetch(int ch){
  if(bufp < BUFFER)
    buf[bufp++] = ch;
  else
    printf("error: too many characters in buffer\n");
}

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

vector<Person*> filter(vector<Person*> data, const PersonPredicate* predicate) {
  vector<Person*> filtered;
  for (unsigned int i = 0; i < data.size(); i++) {
    if (predicate->apply(data[i])) {
      filtered.push_back(data[i]);
    }
  }
  return filtered;
}

vector<Person*> init(int size) {
  vector<Person*> people;
  for (int i = 0; i < size; i++) {
    if (i % 15 == 0) {
      people.push_back(new Professor());
    } else {
      people.push_back(new Student());
    }
  }
  return people;
}

void cleanup(vector<Person*> data) {
  for (unsigned int i = 0; i < data.size(); i++) {
    delete data[i];
  }
}

int main(int argc, char* argv[]) {

  vector<Person*> people = init(43000);

  PersonPredicate* predicate = new IsStudent();
  vector<Person*> students = filter(people, predicate);
  delete predicate;
  predicate = new IsProfessor();
  vector<Person*> professors = filter(people, predicate);

  cout << "    Num people: " << people.size() << endl;
  cout << "  Num students: " << students.size() << endl;
  cout << "Num professors: " << professors.size() << endl;

  return 0;
}


text:
package org.artifactory.request;

import org.artifactory.md.Properties;
import org.artifactory.mime.NamingUtils;
import org.artifactory.util.PathUtils;

import javax.annotation.Nonnull;

/**
 * Implementation based on a download http request.
 *
 * @author Yossi Shaul
 */
public class DownloadRequestContext extends BaseRequestContext {

    private boolean forceExpiryCheck;

    public DownloadRequestContext(@Nonnull ArtifactoryRequest artifactoryRequest) {
        super(artifactoryRequest);
    }

    public DownloadRequestContext(@Nonnull ArtifactoryRequest artifactoryRequest, boolean forceExpiryCheck) {
        super(artifactoryRequest);
        this.forceExpiryCheck = forceExpiryCheck;
    }

    @Override
    public boolean isFromAnotherArtifactory() {
        return request.isFromAnotherArtifactory();
    }

    @Override
    public String getResourcePath() {
        String path = request.getPath();
        return NamingUtils.isChecksum(path) ? PathUtils.stripExtension(path) : path;
    }

    @Override
    public Properties getProperties() {
        return request.getProperties();
    }

    @Override
    public boolean isForceExpiryCheck() {
        return forceExpiryCheck;
    }
}


text:
A small CodeIgniter Controller and Model to generate an (in theory... infinite-deep) multi-level menu.

### Included features ###
* As less database calls as possible (we'll need only 1)
* As generic as possible (using a recursive function)
* As clean as possible
* The menu in this example is 5 levels 'deep' (friends, it can be as deep as the ocean...)
* following the HMVC specs.

Sourcecode contains only **25 relevant lines**

The result will be something like this

![Result MultiLevel Menu in CodeIgniter](http://www.driesen.eu/insiderclub/multilevelmenu/multilevel01.png)

### Requirement ###

* CodeIgniter 3.0.x (tested until 3.1.3) installed.
* HMVC installed
* Some basic PHP knowledge
* Some basic MySQL knowledge

#### Step 1: creating the table in MySQL. ####

Our table (named 'menus') will have only 4 fields...

* ***id (int)*** : Unique AI integer
* ***parent_id (int)*** : refers to the id...
* ***name (varchar)*** : the name of our menu
* ***sequence (int)*** : will determine the 'order' in which the menu-items will be shown (per level ...)

***Remark:***
By using the sequence field, we can make to menu-levels independent from the ID's in our table...

See the image below for details

![Rec Id in your database does not really mather](http://www.driesen.eu/insiderclub/multilevelmenu/multilevel02.png)

The SQL script to create, and fill your '***menus***' table is included in the SQL folder

#### Step 2: The Controller. ####

```
class Menus extends MY_Controller {

  function __construct() {
    parent::__construct();
    $this -> load -> model('menus/Mdl_menus');
  }

  function index() {
    $items = $this->Mdl_menus->get_items();
    $menu = $this->Mdl_menus->generateTree($items);
    $data = array(
     'menu' => $menu,
    );
    $this->load->view('menus/menu', $data, false);
  }

}
```

Pretty simple, no ?

#### Step 3: The Model. ####
Beside the constructor, our Model has 2 functions...

* **get_items()**  does 1 database call (yep, only ONE)
* **generateTree()**  is a recursive function which does the complete job. In other words, it generates ALL the menu levels, in a nice and clean way...

```
class Mdl_menus extends CI_Model {

  function __construct() {
    parent::__construct();

    $this->tableName = 'menus';
  }

  function get_items() {
    $this->db->select('*');
    $this->db->from($this->tableName);
    $this->db->order_by('parent_id');
    $this->db->order_by('sequence');
    $query = $this->db->get();
    return $query->result_array();
  }

  function generateTree($items = array(), $parent_id = 0){
    $tree = '<ul>';
    for($i=0, $ni=count($items); $i < $ni; $i++){
    	if($items[$i]['parent_id'] == $parent_id){
    		$tree .= '<li>';
    		$tree .= $items[$i]['name'];
    		$tree .= $this->generateTree($items, $items[$i]['id']);
    		$tree .= '</li>';
    	}
    }
    $tree .= '</ul>';
    return $tree;
  }

} // End of Model Class
```

#### Step 4 The view ####
Basic rule of HMVC ... NO Business Logic in your views...

Well, this is the content of our View ...
```
echo $menu;
```

** And we are DONE !!! **

Once the above files are copied to the right location, you can simply run this small demo by:

http\\\\ ***yourserver*** \\ ***yourappname*** \\ menus

Enjoy & Grtz,

Johnny


text:
<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}

/**
 * Param 'colorpicker' field
 *
 * @param $settings
 * @param $value
 *
 * @return string
 * @since 4.4
 */
function vc_colorpicker_form_field( $settings, $value ) {
	return sprintf( '
<input name="%s" class="wpb_vc_param_value wpb-textinput %s %s_field vc_color-control" type="text" value="%s"/>
', $settings['param_name'], $settings['param_name'], $settings['type'], $value );
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pyrenastrum fuscum Mont.

### Remarks
null


text:
package com.myjavaworld.gui;

import java.awt.Toolkit;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * An extension of javax.swing.text.PlainDocument.
 *
 * @author Sai Pullabhotla, psai [at] jMethods [dot] com
 * @version 1.0
 *
 */
public class MPlainDocument extends PlainDocument {

	private int maximumLength = 0;
	private int characterCase = 0;

	/**
	 * Created an instance of MPlainDocument.
	 *
	 */
	public MPlainDocument() {
		super();
		this.maximumLength = Integer.MAX_VALUE;
		this.characterCase = MTextComponent.MIXED_CASE;
	}

	/**
	 * Sets the maximum length of this document to the given
	 * maximumLength.
	 *
	 * @param maximumLength
	 *            Maximum number of characters to allow
	 *
	 */
	public void setMaximumLength(int maximumLength) {
		this.maximumLength = maximumLength;
	}

	/**
	 * Returns the maximum length allowed by this document.
	 *
	 * @return maximum length
	 *
	 */
	public int getMaximumLength() {
		return maximumLength;
	}

	/**
	 * Sets the character case of this doocument to the given case.
	 *
	 * @param characterCase
	 *            Character case to force on this document
	 *
	 */
	public void setCharacterCase(int characterCase) {
		this.characterCase = characterCase;
	}

	/**
	 * Returns the current character case in use by this document.
	 *
	 * @return character case
	 *
	 */
	public int getCharacterCase() {
		return characterCase;
	}

	@Override
	public void insertString(int offset, String str, AttributeSet a)
			throws BadLocationException {
		boolean beep = false;
		if (str.length() + getLength() > maximumLength) {
			str = str.substring(0, maximumLength - getLength());
			beep = true;
		}

		switch (characterCase) {
		case MTextComponent.UPPER_CASE:
			str = str.toUpperCase();
			break;

		case MTextComponent.LOWER_CASE:
			str = str.toLowerCase();
			break;
		}

		super.insertString(offset, str, a);
		if (beep) {
			Toolkit.getDefaultToolkit().beep();
		}
	}
}


text:
package com.intellij.refactoring.listeners;

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.psi.PsiElement;

/**
 * Refactorings invoke {@link #getListener(com.intellij.psi.PsiElement)} of registered
 * {@linkplain RefactoringElementListenerProvider} before particular element is subjected to refactoring.
 * @author dsl
 */
public interface RefactoringElementListenerProvider {
  ExtensionPointName<RefactoringElementListenerProvider> EP_NAME = ExtensionPointName.create("com.intellij.refactoring.elementListenerProvider");

  /**
   *
   * Should return a listener for particular element. Invoked in read action.
   */
  @javax.annotation.Nullable
  RefactoringElementListener getListener(PsiElement element);
}


text:
id: 682
title: Apple Executives – Past And Present
date: 2011-09-23T21:15:41+00:00
author: Junda Ong
layout: post
guid: http://blog.just2us.com/?p=682
permalink: /2011/09/apple-executives-%e2%80%93-past-and-present/
wp_plus_one_redirect:
  -
arkayne-cache-post:
  - |
    |

arkayne-time-post:
  - 1400154270
dsq_thread_id:
  - 423809360
categories:
  - whatever
---

  With Steve Jobs:

  Without:


text:
// ----------------------------------------------------------------------------
//
//     ***     AUTO GENERATED CODE    ***    Type: MMv1     ***
//
// ----------------------------------------------------------------------------
//
//     This file is automatically generated by Magic Modules and manual
//     changes will be clobbered when the file is regenerated.
//
//     Please read more about how to change this file in
//     .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------

package google

import (
	"bytes"
	"fmt"
	"log"
	"reflect"
	"regexp"
	"time"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func defaultBinaryAuthorizationPolicy(project string) map[string]interface{} {
	return map[string]interface{}{
		"name": fmt.Sprintf("projects/%s/policy", project),
		"admissionWhitelistPatterns": []interface{}{
			map[string]interface{}{
				"namePattern": "gcr.io/google_containers/*",
			},
		},
		"defaultAdmissionRule": map[string]interface{}{
			"evaluationMode":  "ALWAYS_ALLOW",
			"enforcementMode": "ENFORCED_BLOCK_AND_AUDIT_LOG",
		},
	}
}

func resourceBinaryAuthorizationPolicy() *schema.Resource {
	return &schema.Resource{
		Create: resourceBinaryAuthorizationPolicyCreate,
		Read:   resourceBinaryAuthorizationPolicyRead,
		Update: resourceBinaryAuthorizationPolicyUpdate,
		Delete: resourceBinaryAuthorizationPolicyDelete,

		Importer: &schema.ResourceImporter{
			State: resourceBinaryAuthorizationPolicyImport,
		},

		Timeouts: &schema.ResourceTimeout{
			Create: schema.DefaultTimeout(20 * time.Minute),
			Update: schema.DefaultTimeout(20 * time.Minute),
			Delete: schema.DefaultTimeout(20 * time.Minute),
		},

		Schema: map[string]*schema.Schema{
			"default_admission_rule": {
				Type:     schema.TypeList,
				Required: true,
				Description: `Default admission rule for a cluster without a per-cluster admission
rule.`,
				MaxItems: 1,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"enforcement_mode": {
							Type:         schema.TypeString,
							Required:     true,
							ValidateFunc: validateEnum([]string{"ENFORCED_BLOCK_AND_AUDIT_LOG", "DRYRUN_AUDIT_LOG_ONLY"}),
							Description:  `The action when a pod creation is denied by the admission rule. Possible values: ["ENFORCED_BLOCK_AND_AUDIT_LOG", "DRYRUN_AUDIT_LOG_ONLY"]`,
						},
						"evaluation_mode": {
							Type:         schema.TypeString,
							Required:     true,
							ValidateFunc: validateEnum([]string{"ALWAYS_ALLOW", "REQUIRE_ATTESTATION", "ALWAYS_DENY"}),
							Description:  `How this admission rule will be evaluated. Possible values: ["ALWAYS_ALLOW", "REQUIRE_ATTESTATION", "ALWAYS_DENY"]`,
						},
						"require_attestations_by": {
							Type:             schema.TypeSet,
							Optional:         true,
							DiffSuppressFunc: compareSelfLinkOrResourceName,
							Description: `The resource names of the attestors that must attest to a
container image. If the attestor is in a different project from the
policy, it should be specified in the format 'projects/*/attestors/*'.
Each attestor must exist before a policy can reference it. To add an
attestor to a policy the principal issuing the policy change
request must be able to read the attestor resource.

Note: this field must be non-empty when the evaluation_mode field
specifies REQUIRE_ATTESTATION, otherwise it must be empty.`,
							Elem: &schema.Schema{
								Type: schema.TypeString,
							},
							Set: selfLinkNameHash,
						},
					},
				},
			},
			"admission_whitelist_patterns": {
				Type:     schema.TypeList,
				Optional: true,
				Description: `A whitelist of image patterns to exclude from admission rules. If an
image's name matches a whitelist pattern, the image's admission
requests will always be permitted regardless of your admission rules.`,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"name_pattern": {
							Type:     schema.TypeString,
							Required: true,
							Description: `An image name pattern to whitelist, in the form
'registry/path/to/image'. This supports a trailing * as a
wildcard, but this is allowed only in text after the registry/
part.`,
						},
					},
				},
			},
			"cluster_admission_rules": {
				Type:     schema.TypeSet,
				Optional: true,
				Description: `Per-cluster admission rules. An admission rule specifies either that
all container images used in a pod creation request must be attested
to by one or more attestors, that all pod creations will be allowed,
or that all pod creations will be denied. There can be at most one
admission rule per cluster spec.

Identifier format: '{{location}}.{{clusterId}}'.
A location is either a compute zone (e.g. 'us-central1-a') or a region
(e.g. 'us-central1').`,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"cluster": {
							Type:     schema.TypeString,
							Required: true,
						},
						"enforcement_mode": {
							Type:         schema.TypeString,
							Required:     true,
							ValidateFunc: validateEnum([]string{"ENFORCED_BLOCK_AND_AUDIT_LOG", "DRYRUN_AUDIT_LOG_ONLY"}),
							Description:  `The action when a pod creation is denied by the admission rule. Possible values: ["ENFORCED_BLOCK_AND_AUDIT_LOG", "DRYRUN_AUDIT_LOG_ONLY"]`,
						},
						"evaluation_mode": {
							Type:         schema.TypeString,
							Required:     true,
							ValidateFunc: validateEnum([]string{"ALWAYS_ALLOW", "REQUIRE_ATTESTATION", "ALWAYS_DENY"}),
							Description:  `How this admission rule will be evaluated. Possible values: ["ALWAYS_ALLOW", "REQUIRE_ATTESTATION", "ALWAYS_DENY"]`,
						},
						"require_attestations_by": {
							Type:             schema.TypeSet,
							Optional:         true,
							DiffSuppressFunc: compareSelfLinkOrResourceName,
							Description: `The resource names of the attestors that must attest to a
container image. If the attestor is in a different project from the
policy, it should be specified in the format 'projects/*/attestors/*'.
Each attestor must exist before a policy can reference it. To add an
attestor to a policy the principal issuing the policy change
request must be able to read the attestor resource.

Note: this field must be non-empty when the evaluation_mode field
specifies REQUIRE_ATTESTATION, otherwise it must be empty.`,
							Elem: &schema.Schema{
								Type: schema.TypeString,
							},
							Set: selfLinkNameHash,
						},
					},
				},
				Set: func(v interface{}) int {
					// require_attestations_by is a set of strings that can have the format
					// projects/{project}/attestors/{attestor} or {attestor}. We diffsuppress
					// and hash that set on the name, but now we need to make sure that the
					// overall hash here respects that so changing the attestor format doesn't
					// change the hash code of cluster_admission_rules.
					raw := v.(map[string]interface{})

					// modifying raw actually modifies the values passed to the provider.
					// Use a copy to avoid that.
					copy := make((map[string]interface{}))
					for key, value := range raw {
						copy[key] = value
					}
					at := copy["require_attestations_by"].(*schema.Set)
					if at != nil {
						t := convertAndMapStringArr(at.List(), GetResourceNameFromSelfLink)
						copy["require_attestations_by"] = schema.NewSet(selfLinkNameHash, convertStringArrToInterface(t))
					}
					var buf bytes.Buffer
					schema.SerializeResourceForHash(&buf, copy, resourceBinaryAuthorizationPolicy().Schema["cluster_admission_rules"].Elem.(*schema.Resource))
					return hashcode(buf.String())
				},
			},
			"description": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: `A descriptive comment.`,
			},
			"global_policy_evaluation_mode": {
				Type:         schema.TypeString,
				Computed:     true,
				Optional:     true,
				ValidateFunc: validateEnum([]string{"ENABLE", "DISABLE", ""}),
				Description: `Controls the evaluation of a Google-maintained global admission policy
for common system-level images. Images not covered by the global
policy will be subject to the project admission policy. Possible values: ["ENABLE", "DISABLE"]`,
			},
			"project": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},
		},
		UseJSONNumber: true,
	}
}

func resourceBinaryAuthorizationPolicyCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	userAgent, err := generateUserAgentString(d, config.userAgent)
	if err != nil {
		return err
	}

	obj := make(map[string]interface{})
	descriptionProp, err := expandBinaryAuthorizationPolicyDescription(d.Get("description"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
		obj["description"] = descriptionProp
	}
	globalPolicyEvaluationModeProp, err := expandBinaryAuthorizationPolicyGlobalPolicyEvaluationMode(d.Get("global_policy_evaluation_mode"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("global_policy_evaluation_mode"); !isEmptyValue(reflect.ValueOf(globalPolicyEvaluationModeProp)) && (ok || !reflect.DeepEqual(v, globalPolicyEvaluationModeProp)) {
		obj["globalPolicyEvaluationMode"] = globalPolicyEvaluationModeProp
	}
	admissionWhitelistPatternsProp, err := expandBinaryAuthorizationPolicyAdmissionWhitelistPatterns(d.Get("admission_whitelist_patterns"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("admission_whitelist_patterns"); !isEmptyValue(reflect.ValueOf(admissionWhitelistPatternsProp)) && (ok || !reflect.DeepEqual(v, admissionWhitelistPatternsProp)) {
		obj["admissionWhitelistPatterns"] = admissionWhitelistPatternsProp
	}
	clusterAdmissionRulesProp, err := expandBinaryAuthorizationPolicyClusterAdmissionRules(d.Get("cluster_admission_rules"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("cluster_admission_rules"); !isEmptyValue(reflect.ValueOf(clusterAdmissionRulesProp)) && (ok || !reflect.DeepEqual(v, clusterAdmissionRulesProp)) {
		obj["clusterAdmissionRules"] = clusterAdmissionRulesProp
	}
	defaultAdmissionRuleProp, err := expandBinaryAuthorizationPolicyDefaultAdmissionRule(d.Get("default_admission_rule"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("default_admission_rule"); !isEmptyValue(reflect.ValueOf(defaultAdmissionRuleProp)) && (ok || !reflect.DeepEqual(v, defaultAdmissionRuleProp)) {
		obj["defaultAdmissionRule"] = defaultAdmissionRuleProp
	}

	url, err := replaceVars(d, config, "{{BinaryAuthorizationBasePath}}projects/{{project}}/policy")
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] Creating new Policy: %#v", obj)
	billingProject := ""

	project, err := getProject(d, config)
	if err != nil {
		return fmt.Errorf("Error fetching project for Policy: %s", err)
	}
	billingProject = project

	// err == nil indicates that the billing_project value was found
	if bp, err := getBillingProject(d, config); err == nil {
		billingProject = bp
	}

	res, err := sendRequestWithTimeout(config, "PUT", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate))
	if err != nil {
		return fmt.Errorf("Error creating Policy: %s", err)
	}

	// Store the ID now
	id, err := replaceVars(d, config, "projects/{{project}}")
	if err != nil {
		return fmt.Errorf("Error constructing id: %s", err)
	}
	d.SetId(id)

	log.Printf("[DEBUG] Finished creating Policy %q: %#v", d.Id(), res)

	return resourceBinaryAuthorizationPolicyRead(d, meta)
}

func resourceBinaryAuthorizationPolicyRead(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	userAgent, err := generateUserAgentString(d, config.userAgent)
	if err != nil {
		return err
	}

	url, err := replaceVars(d, config, "{{BinaryAuthorizationBasePath}}projects/{{project}}/policy")
	if err != nil {
		return err
	}

	billingProject := ""

	project, err := getProject(d, config)
	if err != nil {
		return fmt.Errorf("Error fetching project for Policy: %s", err)
	}
	billingProject = project

	// err == nil indicates that the billing_project value was found
	if bp, err := getBillingProject(d, config); err == nil {
		billingProject = bp
	}

	res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil)
	if err != nil {
		return handleNotFoundError(err, d, fmt.Sprintf("BinaryAuthorizationPolicy %q", d.Id()))
	}

	if err := d.Set("project", project); err != nil {
		return fmt.Errorf("Error reading Policy: %s", err)
	}

	if err := d.Set("description", flattenBinaryAuthorizationPolicyDescription(res["description"], d, config)); err != nil {
		return fmt.Errorf("Error reading Policy: %s", err)
	}
	if err := d.Set("global_policy_evaluation_mode", flattenBinaryAuthorizationPolicyGlobalPolicyEvaluationMode(res["globalPolicyEvaluationMode"], d, config)); err != nil {
		return fmt.Errorf("Error reading Policy: %s", err)
	}
	if err := d.Set("admission_whitelist_patterns", flattenBinaryAuthorizationPolicyAdmissionWhitelistPatterns(res["admissionWhitelistPatterns"], d, config)); err != nil {
		return fmt.Errorf("Error reading Policy: %s", err)
	}
	if err := d.Set("cluster_admission_rules", flattenBinaryAuthorizationPolicyClusterAdmissionRules(res["clusterAdmissionRules"], d, config)); err != nil {
		return fmt.Errorf("Error reading Policy: %s", err)
	}
	if err := d.Set("default_admission_rule", flattenBinaryAuthorizationPolicyDefaultAdmissionRule(res["defaultAdmissionRule"], d, config)); err != nil {
		return fmt.Errorf("Error reading Policy: %s", err)
	}

	return nil
}

func resourceBinaryAuthorizationPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	userAgent, err := generateUserAgentString(d, config.userAgent)
	if err != nil {
		return err
	}

	billingProject := ""

	project, err := getProject(d, config)
	if err != nil {
		return fmt.Errorf("Error fetching project for Policy: %s", err)
	}
	billingProject = project

	obj := make(map[string]interface{})
	descriptionProp, err := expandBinaryAuthorizationPolicyDescription(d.Get("description"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
		obj["description"] = descriptionProp
	}
	globalPolicyEvaluationModeProp, err := expandBinaryAuthorizationPolicyGlobalPolicyEvaluationMode(d.Get("global_policy_evaluation_mode"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("global_policy_evaluation_mode"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, globalPolicyEvaluationModeProp)) {
		obj["globalPolicyEvaluationMode"] = globalPolicyEvaluationModeProp
	}
	admissionWhitelistPatternsProp, err := expandBinaryAuthorizationPolicyAdmissionWhitelistPatterns(d.Get("admission_whitelist_patterns"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("admission_whitelist_patterns"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, admissionWhitelistPatternsProp)) {
		obj["admissionWhitelistPatterns"] = admissionWhitelistPatternsProp
	}
	clusterAdmissionRulesProp, err := expandBinaryAuthorizationPolicyClusterAdmissionRules(d.Get("cluster_admission_rules"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("cluster_admission_rules"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, clusterAdmissionRulesProp)) {
		obj["clusterAdmissionRules"] = clusterAdmissionRulesProp
	}
	defaultAdmissionRuleProp, err := expandBinaryAuthorizationPolicyDefaultAdmissionRule(d.Get("default_admission_rule"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("default_admission_rule"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, defaultAdmissionRuleProp)) {
		obj["defaultAdmissionRule"] = defaultAdmissionRuleProp
	}

	url, err := replaceVars(d, config, "{{BinaryAuthorizationBasePath}}projects/{{project}}/policy")
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] Updating Policy %q: %#v", d.Id(), obj)

	// err == nil indicates that the billing_project value was found
	if bp, err := getBillingProject(d, config); err == nil {
		billingProject = bp
	}

	res, err := sendRequestWithTimeout(config, "PUT", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate))

	if err != nil {
		return fmt.Errorf("Error updating Policy %q: %s", d.Id(), err)
	} else {
		log.Printf("[DEBUG] Finished updating Policy %q: %#v", d.Id(), res)
	}

	return resourceBinaryAuthorizationPolicyRead(d, meta)
}

func resourceBinaryAuthorizationPolicyDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	userAgent, err := generateUserAgentString(d, config.userAgent)
	if err != nil {
		return err
	}

	billingProject := ""

	project, err := getProject(d, config)
	if err != nil {
		return fmt.Errorf("Error fetching project for Policy: %s", err)
	}
	billingProject = project

	url, err := replaceVars(d, config, "{{BinaryAuthorizationBasePath}}projects/{{project}}/policy")
	if err != nil {
		return err
	}

	var obj map[string]interface{}
	obj = defaultBinaryAuthorizationPolicy(d.Get("project").(string))
	log.Printf("[DEBUG] Deleting Policy %q", d.Id())

	// err == nil indicates that the billing_project value was found
	if bp, err := getBillingProject(d, config); err == nil {
		billingProject = bp
	}

	res, err := sendRequestWithTimeout(config, "PUT", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutDelete))
	if err != nil {
		return handleNotFoundError(err, d, "Policy")
	}

	log.Printf("[DEBUG] Finished deleting Policy %q: %#v", d.Id(), res)
	return nil
}

func resourceBinaryAuthorizationPolicyImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
	config := meta.(*Config)
	if err := parseImportId([]string{
		"projects/(?P<project>[^/]+)",
		"(?P<project>[^/]+)",
	}, d, config); err != nil {
		return nil, err
	}

	// Replace import id for the resource id
	id, err := replaceVars(d, config, "projects/{{project}}")
	if err != nil {
		return nil, fmt.Errorf("Error constructing id: %s", err)
	}
	d.SetId(id)

	return []*schema.ResourceData{d}, nil
}

func flattenBinaryAuthorizationPolicyDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenBinaryAuthorizationPolicyGlobalPolicyEvaluationMode(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenBinaryAuthorizationPolicyAdmissionWhitelistPatterns(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return v
	}
	l := v.([]interface{})
	transformed := make([]interface{}, 0, len(l))
	for _, raw := range l {
		original := raw.(map[string]interface{})
		if len(original) < 1 {
			// Do not include empty json objects coming back from the api
			continue
		}
		transformed = append(transformed, map[string]interface{}{
			"name_pattern": flattenBinaryAuthorizationPolicyAdmissionWhitelistPatternsNamePattern(original["namePattern"], d, config),
		})
	}
	return transformed
}
func flattenBinaryAuthorizationPolicyAdmissionWhitelistPatternsNamePattern(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenBinaryAuthorizationPolicyClusterAdmissionRules(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return v
	}
	l := v.(map[string]interface{})
	transformed := make([]interface{}, 0, len(l))
	for k, raw := range l {
		original := raw.(map[string]interface{})
		transformed = append(transformed, map[string]interface{}{
			"cluster":                 k,
			"evaluation_mode":         flattenBinaryAuthorizationPolicyClusterAdmissionRulesEvaluationMode(original["evaluationMode"], d, config),
			"require_attestations_by": flattenBinaryAuthorizationPolicyClusterAdmissionRulesRequireAttestationsBy(original["requireAttestationsBy"], d, config),
			"enforcement_mode":        flattenBinaryAuthorizationPolicyClusterAdmissionRulesEnforcementMode(original["enforcementMode"], d, config),
		})
	}
	return transformed
}
func flattenBinaryAuthorizationPolicyClusterAdmissionRulesEvaluationMode(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenBinaryAuthorizationPolicyClusterAdmissionRulesRequireAttestationsBy(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return v
	}
	return schema.NewSet(selfLinkNameHash, v.([]interface{}))
}

func flattenBinaryAuthorizationPolicyClusterAdmissionRulesEnforcementMode(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenBinaryAuthorizationPolicyDefaultAdmissionRule(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return nil
	}
	original := v.(map[string]interface{})
	if len(original) == 0 {
		return nil
	}
	transformed := make(map[string]interface{})
	transformed["evaluation_mode"] =
		flattenBinaryAuthorizationPolicyDefaultAdmissionRuleEvaluationMode(original["evaluationMode"], d, config)
	transformed["require_attestations_by"] =
		flattenBinaryAuthorizationPolicyDefaultAdmissionRuleRequireAttestationsBy(original["requireAttestationsBy"], d, config)
	transformed["enforcement_mode"] =
		flattenBinaryAuthorizationPolicyDefaultAdmissionRuleEnforcementMode(original["enforcementMode"], d, config)
	return []interface{}{transformed}
}
func flattenBinaryAuthorizationPolicyDefaultAdmissionRuleEvaluationMode(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenBinaryAuthorizationPolicyDefaultAdmissionRuleRequireAttestationsBy(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return v
	}
	return schema.NewSet(selfLinkNameHash, v.([]interface{}))
}

func flattenBinaryAuthorizationPolicyDefaultAdmissionRuleEnforcementMode(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func expandBinaryAuthorizationPolicyDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandBinaryAuthorizationPolicyGlobalPolicyEvaluationMode(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandBinaryAuthorizationPolicyAdmissionWhitelistPatterns(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	l := v.([]interface{})
	req := make([]interface{}, 0, len(l))
	for _, raw := range l {
		if raw == nil {
			continue
		}
		original := raw.(map[string]interface{})
		transformed := make(map[string]interface{})

		transformedNamePattern, err := expandBinaryAuthorizationPolicyAdmissionWhitelistPatternsNamePattern(original["name_pattern"], d, config)
		if err != nil {
			return nil, err
		} else if val := reflect.ValueOf(transformedNamePattern); val.IsValid() && !isEmptyValue(val) {
			transformed["namePattern"] = transformedNamePattern
		}

		req = append(req, transformed)
	}
	return req, nil
}

func expandBinaryAuthorizationPolicyAdmissionWhitelistPatternsNamePattern(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandBinaryAuthorizationPolicyClusterAdmissionRules(v interface{}, d TerraformResourceData, config *Config) (map[string]interface{}, error) {
	if v == nil {
		return map[string]interface{}{}, nil
	}
	m := make(map[string]interface{})
	for _, raw := range v.(*schema.Set).List() {
		original := raw.(map[string]interface{})
		transformed := make(map[string]interface{})

		transformedEvaluationMode, err := expandBinaryAuthorizationPolicyClusterAdmissionRulesEvaluationMode(original["evaluation_mode"], d, config)
		if err != nil {
			return nil, err
		} else if val := reflect.ValueOf(transformedEvaluationMode); val.IsValid() && !isEmptyValue(val) {
			transformed["evaluationMode"] = transformedEvaluationMode
		}

		transformedRequireAttestationsBy, err := expandBinaryAuthorizationPolicyClusterAdmissionRulesRequireAttestationsBy(original["require_attestations_by"], d, config)
		if err != nil {
			return nil, err
		} else if val := reflect.ValueOf(transformedRequireAttestationsBy); val.IsValid() && !isEmptyValue(val) {
			transformed["requireAttestationsBy"] = transformedRequireAttestationsBy
		}

		transformedEnforcementMode, err := expandBinaryAuthorizationPolicyClusterAdmissionRulesEnforcementMode(original["enforcement_mode"], d, config)
		if err != nil {
			return nil, err
		} else if val := reflect.ValueOf(transformedEnforcementMode); val.IsValid() && !isEmptyValue(val) {
			transformed["enforcementMode"] = transformedEnforcementMode
		}

		transformedCluster, err := expandString(original["cluster"], d, config)
		if err != nil {
			return nil, err
		}
		m[transformedCluster] = transformed
	}
	return m, nil
}

func expandBinaryAuthorizationPolicyClusterAdmissionRulesEvaluationMode(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandBinaryAuthorizationPolicyClusterAdmissionRulesRequireAttestationsBy(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	r := regexp.MustCompile("projects/(.+)/attestors/(.+)")

	// It's possible that all entries in the list will specify a project, in
	// which case the user wouldn't necessarily have to specify a provider
	// project.
	var project string
	var err error
	for _, s := range v.(*schema.Set).List() {
		if !r.MatchString(s.(string)) {
			project, err = getProject(d, config)
			if err != nil {
				return []interface{}{}, err
			}
			break
		}
	}

	return convertAndMapStringArr(v.(*schema.Set).List(), func(s string) string {
		if r.MatchString(s) {
			return s
		}

		return fmt.Sprintf("projects/%s/attestors/%s", project, s)
	}), nil
}

func expandBinaryAuthorizationPolicyClusterAdmissionRulesEnforcementMode(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandBinaryAuthorizationPolicyDefaultAdmissionRule(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	l := v.([]interface{})
	if len(l) == 0 || l[0] == nil {
		return nil, nil
	}
	raw := l[0]
	original := raw.(map[string]interface{})
	transformed := make(map[string]interface{})

	transformedEvaluationMode, err := expandBinaryAuthorizationPolicyDefaultAdmissionRuleEvaluationMode(original["evaluation_mode"], d, config)
	if err != nil {
		return nil, err
	} else if val := reflect.ValueOf(transformedEvaluationMode); val.IsValid() && !isEmptyValue(val) {
		transformed["evaluationMode"] = transformedEvaluationMode
	}

	transformedRequireAttestationsBy, err := expandBinaryAuthorizationPolicyDefaultAdmissionRuleRequireAttestationsBy(original["require_attestations_by"], d, config)
	if err != nil {
		return nil, err
	} else if val := reflect.ValueOf(transformedRequireAttestationsBy); val.IsValid() && !isEmptyValue(val) {
		transformed["requireAttestationsBy"] = transformedRequireAttestationsBy
	}

	transformedEnforcementMode, err := expandBinaryAuthorizationPolicyDefaultAdmissionRuleEnforcementMode(original["enforcement_mode"], d, config)
	if err != nil {
		return nil, err
	} else if val := reflect.ValueOf(transformedEnforcementMode); val.IsValid() && !isEmptyValue(val) {
		transformed["enforcementMode"] = transformedEnforcementMode
	}

	return transformed, nil
}

func expandBinaryAuthorizationPolicyDefaultAdmissionRuleEvaluationMode(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandBinaryAuthorizationPolicyDefaultAdmissionRuleRequireAttestationsBy(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	r := regexp.MustCompile("projects/(.+)/attestors/(.+)")

	// It's possible that all entries in the list will specify a project, in
	// which case the user wouldn't necessarily have to specify a provider
	// project.
	var project string
	var err error
	for _, s := range v.(*schema.Set).List() {
		if !r.MatchString(s.(string)) {
			project, err = getProject(d, config)
			if err != nil {
				return []interface{}{}, err
			}
			break
		}
	}

	return convertAndMapStringArr(v.(*schema.Set).List(), func(s string) string {
		if r.MatchString(s) {
			return s
		}

		return fmt.Sprintf("projects/%s/attestors/%s", project, s)
	}), nil
}

func expandBinaryAuthorizationPolicyDefaultAdmissionRuleEnforcementMode(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package erp.mod.hrs.view;

import erp.gui.grid.SGridFilterPanelLoan;
import erp.mod.SModConsts;
import erp.mod.hrs.form.SDialogLayoutEmployee;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import sa.lib.SLibConsts;
import sa.lib.SLibTimeUtils;
import sa.lib.SLibUtils;
import sa.lib.db.SDbConsts;
import sa.lib.grid.SGridColumnView;
import sa.lib.grid.SGridConsts;
import sa.lib.grid.SGridFilterDatePeriod;
import sa.lib.grid.SGridFilterValue;
import sa.lib.grid.SGridPaneSettings;
import sa.lib.grid.SGridPaneView;
import sa.lib.grid.SGridUtils;
import sa.lib.gui.SGuiClient;
import sa.lib.gui.SGuiConsts;
import sa.lib.gui.SGuiDate;

/**
 *
 * @author Claudio Peña
 */
public class SViewEmployeeIdse extends SGridPaneView implements ActionListener{

    private SGridFilterDatePeriod moFilterDatePeriod;
    private JButton jbLayoutEmployeeHireIdse;
    private JButton jbLayoutEmployeeSbcIdse;
    private JButton jbLayoutEmployeeDismissIdse;
    private SDialogLayoutEmployee moDialogLayoutEmployee;
    private SGridFilterPanelLoan moFilterTypeIdse;

    public SViewEmployeeIdse(SGuiClient client, String title) {
        super(client, SGridConsts.GRID_PANE_VIEW, SModConsts.HRS_EMP_LOG_IDSE, SLibConsts.UNDEFINED, title);
        initComponentsCustom();
    }

    private void initComponentsCustom() {
        setRowButtonsEnabled(false);

        moFilterTypeIdse = new SGridFilterPanelLoan(miClient, this, SModConsts.HRSU_EMP_IDSE);
        moFilterTypeIdse.initFilter(null);
        getPanelCommandsCustom(SGuiConsts.PANEL_LEFT).add(moFilterTypeIdse);

        moFilterDatePeriod = new SGridFilterDatePeriod(miClient, this, SGuiConsts.DATE_PICKER_DATE_PERIOD);
        moFilterDatePeriod.initFilter(new SGuiDate(SGuiConsts.GUI_DATE_YEAR, miClient.getSession().getCurrentDate().getTime()));
        getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(moFilterDatePeriod);

        jbLayoutEmployeeHireIdse = SGridUtils.createButton(new ImageIcon(getClass().getResource("/erp/img/icon_std_save.gif")), "Layout alta empleados IDSE", this);
        getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbLayoutEmployeeHireIdse);
        jbLayoutEmployeeSbcIdse = SGridUtils.createButton(new ImageIcon(getClass().getResource("/erp/img/icon_std_save.gif")), "Layout modificación SBC de empleados IDSE", this);
        getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbLayoutEmployeeSbcIdse);
        jbLayoutEmployeeDismissIdse = SGridUtils.createButton(new ImageIcon(getClass().getResource("/erp/img/icon_std_save.gif")), "Layout baja empleados IDSE", this);
        getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbLayoutEmployeeDismissIdse);

    }

    private void actionLayoutEmployeeHireIdse() {
        if (jbLayoutEmployeeHireIdse.isEnabled()) {
            try {
                moDialogLayoutEmployee = new SDialogLayoutEmployee(miClient, "Layout empleados", SModConsts.HRSX_LAYOUT_IDSE_HIRE);
                moDialogLayoutEmployee.resetForm();
                moDialogLayoutEmployee.setVisible(true);
              }
            catch (Exception e) {
                SLibUtils.showException(this, e);
            }
        }
    }

    private void actionLayoutEmployeeSbcIdse() {
        if (jbLayoutEmployeeSbcIdse.isEnabled()) {
            try {
                moDialogLayoutEmployee = new SDialogLayoutEmployee(miClient, "Layout empleados", SModConsts.HRSX_LAYOUT_IDSE_SSC);
                moDialogLayoutEmployee.resetForm();
                moDialogLayoutEmployee.setVisible(true);
            }
            catch (Exception e) {
                SLibUtils.showException(this, e);
            }
        }
    }

    private void actionLayoutEmployeeDismissIdse(){
            if (jbLayoutEmployeeDismissIdse.isEnabled()) {
                try {
                    moDialogLayoutEmployee = new SDialogLayoutEmployee(miClient, "Layout empleados", SModConsts.HRSX_LAYOUT_IDSE_DISMISS);
                    moDialogLayoutEmployee.resetForm();
                    moDialogLayoutEmployee.setVisible(true);
                }
            catch (Exception e) {
                SLibUtils.showException(this, e);
            }
        }
    }

    @Override
    public void prepareSqlQuery() {
        String sql = "";
        Object filter = null;
        moPaneSettings = new SGridPaneSettings(1);

        String start = "";
        String end = "";
        SGuiDate guiDate = (SGuiDate) moFiltersMap.get(SGridConsts.FILTER_DATE_PERIOD).getValue();

        switch (guiDate.getGuiType()) {
            case SGuiConsts.GUI_DATE_DATE:
                start = "'" + SLibUtils.DbmsDateFormatDate.format(guiDate) + "' ";
                end = "'" + SLibUtils.DbmsDateFormatDate.format(guiDate) + "' ";
                break;
            case SGuiConsts.GUI_DATE_MONTH:
                start = "'" + SLibUtils.DbmsDateFormatDate.format(SLibTimeUtils.getBeginOfMonth(guiDate)) + "' ";
                end = "'" + SLibUtils.DbmsDateFormatDate.format(SLibTimeUtils.getEndOfMonth(guiDate)) + "' ";
                break;
            case SGuiConsts.GUI_DATE_YEAR:
                start = "'" + SLibUtils.DbmsDateFormatDate.format(SLibTimeUtils.getBeginOfYear(guiDate)) + "' ";
                end = "'" + SLibUtils.DbmsDateFormatDate.format(SLibTimeUtils.getEndOfYear(guiDate)) + "' ";
                break;
            default:
                // do nothing!
        }

        filter = ((SGridFilterValue) moFiltersMap.get(SModConsts.HRSU_EMP_IDSE)).getValue();
        if (filter == null) {
            sql += " INNER JOIN hrs_emp_log_hire AS hire ON hire.id_emp = emp.id_emp " +
                    "INNER JOIN cfg_param_co AS par " +
                    "INNER JOIN hrs_cfg AS cfg " +
                    "WHERE NOT hire.b_del  AND hire.b_hire = 1 AND id_log = 1 " +
                    "AND hire.dt_hire >= " + start + " AND hire.dt_hire <= " + end + " ORDER BY bp.id_bp; ";
        }
        else {
            if (((int[]) filter)[0] == 0) {
                sql += " INNER JOIN hrs_emp_log_hire AS hire ON hire.id_emp = emp.id_emp " +
                        "INNER JOIN cfg_param_co AS par " +
                        "INNER JOIN hrs_cfg AS cfg " +
                        "WHERE NOT hire.b_del  AND hire.b_hire = 1 AND id_log = 1 " +
                        "AND hire.dt_hire >= " + start + " AND hire.dt_hire <= " + end + " ORDER BY bp.id_bp; ";
            }
            else if (((int[]) filter)[0] == 1) {
                sql += " INNER JOIN hrs_emp_log_hire AS hire ON hire.id_emp = emp.id_emp " +
                        "INNER JOIN cfg_param_co AS par " +
                        "INNER JOIN hrs_cfg AS cfg " +
                        "WHERE NOT hire.b_del  AND hire.b_hire = 1 AND id_log = 1 " +
                        "AND hire.dt_hire >= " + start + " AND hire.dt_hire <= " + end + " ORDER BY bp.id_bp; ";
            }
            else if (((int[]) filter)[0] == 2) {
                 sql += " INNER JOIN hrs_emp_log_hire AS hire ON hire.id_emp = emp.id_emp " +
                        "INNER JOIN cfg_param_co AS par " +
                        "INNER JOIN hrs_cfg AS cfg " +
                        "WHERE NOT hire.b_del AND hire.b_hire = 0 " +
                        "AND hire.dt_dis_n >= " + start + " AND hire.dt_dis_n <= " + end + " ORDER BY bp.id_bp; ";
            }
            else if (((int[]) filter)[0] == 3) {
                 sql += " INNER JOIN HRS_EMP_LOG_HIRE AS hire ON hire.id_emp = emp.id_emp " +
                        "INNER JOIN HRS_EMP_LOG_SAL_SSC AS ssc ON ssc.id_emp = emp.id_emp " +
                        "INNER JOIN cfg_param_co AS par " +
                        "INNER JOIN hrs_cfg AS cfg " +
                        "WHERE ssc.dt >= " + start + " AND ssc.dt <= " + end + " AND NOT ssc.b_del AND ssc.id_log > 1 GROUP BY bp.id_bp ORDER BY bp.id_bp; ";
            }
        }

        msSql = "SELECT hire.id_emp AS " + SDbConsts.FIELD_ID + "1, hire.id_emp AS " + SDbConsts.FIELD_ID + "2, emp.num AS " + SDbConsts.FIELD_CODE  + ", bp.firstname AS Nombre, bp.alt_id AS CURP, emp.lastname1 AS ApellidoP, emp.lastname2 AS ApellidoM, " +
                "CONCAT(bp.firstname, ' ',  emp.lastname1, ' ', emp.lastname2) AS " + SDbConsts.FIELD_NAME + ", 08 as TypeMov, " +
                "emp.num AS ClaveTrab, emp.ssn AS SSN, emp.sal_ssc AS Salario, e.id_tp_emp AS TpTrabajador, " +
                "sal.id_tp_sal AS TpSalario, wrktp.id_tp_work_day AS Jornada, cfg.ss_subbra AS Guia, hire.dt_hire AS DateApplication, par.reg_ss AS Param " +
                "FROM erp.HRSU_EMP AS emp " +
                "INNER JOIN erp.BPSU_BP AS bp ON bp.id_bp = emp.id_emp " +
                "INNER JOIN erp.HRSU_TP_EMP AS e ON e.id_tp_emp = emp.fk_tp_emp " +
                "INNER JOIN erp.hrss_tp_sal AS sal ON sal.id_tp_sal = emp.fk_tp_sal " +
                "INNER JOIN erp.hrss_tp_work_day AS wrktp ON emp.fk_tp_work_day = wrktp.id_tp_work_day " +  sql ;
//                "INNER JOIN erp.hrss_tp_work_day AS wrktp ON emp.fk_tp_work_day = wrktp.id_tp_work_day " + // alta
//                "INNER JOIN hrs_emp_log_hire AS hire ON hire.id_emp = emp.id_emp " +
//                "INNER JOIN cfg_param_co AS par " +
//                "INNER JOIN hrs_cfg AS cfg " +
//                "WHERE NOT hire.b_del  AND hire.b_hire = 1 AND id_log = 1 " +
//                "AND hire.dt_hire >= " + start + " AND hire.dt_hire <= " + end + " ORDER BY bp.id_bp; " ;

    }

    @Override
    public ArrayList<SGridColumnView> createGridColumns() {
        ArrayList<SGridColumnView> gridColumnsViews = new ArrayList<>();

        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_ACC, "Param", "Registro patronal", 95));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_RAW, SDbConsts.FIELD_CODE , "Clave", 50));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT, "SSN", "NNS", 100));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_BPR_S,  SDbConsts.FIELD_NAME, "Empleado", 250));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_2D, "Salario", "SBC",50));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_1B, "TpTrabajador", "Tipo de trabajador", 50));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_1B, "TpSalario", "Tipo de salario", 50));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_1B, "Jornada", "Semana o jornada", 50));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DATE, "DateApplication", "Fecha inicio labores", 75));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_1B, "TypeMov", "Tipo movimiento", 50));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT, "Guia", "Guia", 150));
        gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT, "CURP", "Curp", 150));

        return gridColumnsViews;
    }

    @Override
    public void defineSuscriptions() {
        moSuscriptionsSet.add(mnGridType);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JButton) {
            JButton button = (JButton) e.getSource();

            if (button == jbLayoutEmployeeHireIdse) {
                actionLayoutEmployeeHireIdse();
            }
            else if (button == jbLayoutEmployeeSbcIdse) {
                actionLayoutEmployeeSbcIdse();
            }
            else if (button == jbLayoutEmployeeDismissIdse) {
                actionLayoutEmployeeDismissIdse();
            }
        }
    }
}


text:
// ***********************************************************************
// <copyright file="DecimalLengthAttribute.cs" company="ServiceStack, Inc.">
//     Copyright (c) ServiceStack, Inc. All Rights Reserved.
// </copyright>
// <summary>Fork for YetAnotherForum.NET, Licensed under the Apache License, Version 2.0</summary>
// ***********************************************************************
using System;

namespace ServiceStack.DataAnnotations;

/// <summary>
/// Decimal length attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class DecimalLengthAttribute : AttributeBase
{
    /// <summary>
    /// Gets or sets the precision.
    /// </summary>
    /// <value>The precision.</value>
    public int Precision { get; set; }
    /// <summary>
    /// Gets or sets the scale.
    /// </summary>
    /// <value>The scale.</value>
    public int Scale { get; set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="DecimalLengthAttribute"/> class.
    /// </summary>
    /// <param name="precision">The precision.</param>
    /// <param name="scale">The scale.</param>
    public DecimalLengthAttribute(int precision, int scale)
    {
        Precision = precision;
        Scale = scale;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="DecimalLengthAttribute"/> class.
    /// </summary>
    /// <param name="precision">The precision.</param>
    public DecimalLengthAttribute(int precision)
        : this(precision, 0)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="DecimalLengthAttribute"/> class.
    /// </summary>
    public DecimalLengthAttribute()
        : this(18, 0)
    {
    }

}


text:
(function ($) {// Preserve our jQuery

$(function() {
	// http://ivaynberg.github.io/select2/
	$("select").each(function() {
		var _	= $(this);
		var options	= {};
		if( !_.hasClass("searchable") ) {
			options.minimumResultsForSearch	= -1;
		}
		_.select2(options);
	});

	(function() {
		var hash = window.location.hash;
		hash && $('ul.nav a[href="'+hash+'"]').tab('show');
		$('.nav-tabs a').click(function (e) {
			$(this).tab('show');
			var scrollmem = $('body').scrollTop();
			window.location.hash = this.hash;
			$('html,body').scrollTop(scrollmem);
		});
	})();

	$('.modal').on('shown.bs.modal', function(e) {
//		document.activeElement.blur();
//		console.log(e);
//		console.log(e.relatedTarget);
		var target = $(e.relatedTarget);
		if( target.length && target.data("focus") ) {
			$(this).find(target.data("focus")).focus();
		} else {
			$(this).find(".modal-body :input:visible").first().focus();
		}
	});

	$("input.select2.autocomplete").shown(function() {
		var _	= $(this);
		if( _.data("autocomplete-auto") ) { return; }
		_.data("autocomplete-auto", 1);
		_.select2({
			minimumInputLength: 2,
			placeholder: "Entrez votre recherche en cliquant ici",
//			multiple: true,
//			maximumSelectionSize: _.data("maximumselectionsize") ? _.data("maximumselectionsize") : 1,
			query: function (query) {
				var queryStr	= _.data("query") ? "&"+_.data("query") : "";
				// Targetting the autocomplete itself
				requestAutocomplete(_.data('what'), query.term+queryStr, function(rows) {
					var data = {results: []};
					for( var k in rows ) {
						data.results.push({id: rows[k].id, text: rows[k].name });
					}
					query.callback(data);
				});
			}
		});
	});

	$("label").click(function() {
		$(this).next().focus();
	});

	$(".confirmable").click(function(e) {
//		debug("Click button");
		var _	= $(this);
//		console.log(_);
		if( _.data("confirm") ) {
			_.after('<input type="hidden" name="'+_.attr("name")+'_confirm" value="1"/>');
			return;
		}
		e.preventDefault();
		// Not mouse click
//		console.log(e.pageX);
//		console.log(_.data("confirm_timer"));
		if( !e.pageX || _.data("confirm_timer") ) { debug("Return"); return; }
//		console.log(e);
		// Delay the confirm to reject double click
//		debug("Confirm timer launch");
		_.data("confirm_timer", setTimeout(function() {
//			debug("Confirm ended");
			_.data("confirm_timer", 0);
			_.data("confirm", _.html());
			_.text("Confirmer ?");
			_.removeClass("btn-warning");
			_.addClass("btn-danger");
		}, 1000));
		_.addClass("btn-warning");
		// Cancel events
		_.one("mouseout.confirmable click.confirmable", function() {
			_.unbind(".confirmable");// Apply to each event, so we remove all others
//			debug("Cancel");
			if( _.data("confirm") ) {
//				debug("Cancel confirm");
				_.html(_.data("confirm"));
				_.data("confirm", 0);
				_.removeClass("btn-danger");
			} else {
//				debug("Abort timer");
				clearTimeout(_.data("confirm_timer"));
				_.data("confirm_timer", 0);
				_.removeClass("btn-warning");
			}
		});
	});
});

function refresh() {
//	console.log($('.uploadlayer'));
	$('.uploadlayer').each(function() {
//		console.log(".uploadlayer shown");
		var _	= $(this);
		if( _.data('uploadlayer') ) { return; }
		_.data('uploadlayer', 1);
		var l	= _.prev();
		var w	= l.outerWidth();
		var h	= l.outerHeight();
//		debug(l.css("display"));
		var pos	= l.position();
//		debug(l);
//		debug(l.position());
//		debug(parseInt(l.css('margin-top')));
//		debug(l.css('margin-left'));
		_.css({"opacity":0, "position":"absolute", "top":(pos.top+parseInt(l.css('margin-top')))+"px", "left":(pos.left+parseInt(l.css('margin-left')))+"px", "width":w+"px", "height":h+"px", "display":"block", "cursor":"pointer"});
//		_.css({"opacity":0, "margin-left": (-w-4)+"px", "width": w+"px", "height": h+"px", "display":l.css("display"), "cursor":"pointer"});
//		debug(_);
//		debug(_.position());
		_.hover(function() { l.addClass("active"); }, function() { l.removeClass("active"); });
		if( _.data('submit') ) {
			_.change(function() { $(_.data('submit')).click(); });
		}
	});
}

$.fn.confirmAction	= function(text) {
// 	if( !text ) { text = ""; }
	if( !$("#confirmModal").length ) {
//

\
		$("body").append('\

\

\

\

\
				<button type="button" class="close fa fa-times" data-dismiss="modal" aria-hidden="true"></button>\

\

\

\
				<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Annuler</button>\
				<button id="confirmBtn" type="button" class="btn btn-primary">Confirmer</button>\

\

\

\

');
		$("#confirmModal").modal({show: false});
		$("#confirmBtn").click(function() {
			$($(this).data("item")).trigger("click", [1]);
		});
	}
	$(this).click(function(e, force) {
		if( !force ) {
			e.preventDefault();
			$("#confirmBtn").data("item", $(this));
			if( typeof text == "function" ) {
				this.__text = text;
				text = this.__text();
			}
			$("#confirmModal").find(".confirm-title").html(text);
// 			$("#confirmModal").find(".confirm-text").html(text);
			$("#confirmModal").modal("show");
// 			if( onShown ) {
// 				this.__onShown	= onShown;
// 				this.__onShown();
// 			}
		}
	});
};

})(jQuery);

function makeSelect2(element) {
	var _		= $(element);
	var options	= {};
	var input	= _;
	if( _.is('input') ) {
		options.data	= [];
	}
	/*
	if( _.hasClass('allownewvalues') ) {
		if( _.is("select") ) {
			// Replace the select with an input
			input	= $("<input />");
			input.addClass(_.prop('class'));
			input.attr('name', $(this).attr('name'));
			var data	= [];
			var val		= '';
			_.find('option').each(function() {
				data.push({'id':$(this).attr('value'),'text':$(this).text()});
				if( $(this).prop('selected') ) {
					val	+= (val ? ',' : '').$(this).attr('value');
				}
			});
			options.data	= data;
			input.val(val);
			_.after(input);
			_.remove();
		}
		options.id		= function(object) {
			return object.text;
		};
		//Allow manually entered text in drop down.
		options.createSearchChoice	= function(term, data) {
			if( $(data).filter( function() {
				return this.text.localeCompare(term)===0;
			}).length===0) {
				return {id:term, text:term};
			}
		};
	}
	*/
//	var options	= {};
	if( !input.hasClass("searchable") ) {
		options.minimumResultsForSearch	= -1;
	}
	input.select2(options);
}


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

<title>ProtocolAnnotationsChecker</title>
<meta name="date" content="2017-02-09">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

seine.modelling.peersim

Class ProtocolAnnotationsChecker

java.lang.Object

seine.modelling.peersim.ProtocolAnnotationsChecker

public class ProtocolAnnotationsChecker
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

ProtocolAnnotationsChecker()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static void
check(java.lang.Object protocolInstance,
     int protocolId)

Perform some checks over the annotations in the protocol class.

static void
checkIndicators(java.util.HashSet<java.lang.String> indicators,
               java.lang.String protocolName)

static void
checkResources(java.util.HashSet<java.lang.String> resources,
              java.lang.String protocolName)

Methods inherited from class java.lang.Object

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

Constructor Detail

ProtocolAnnotationsChecker

public ProtocolAnnotationsChecker()

Method Detail

check

public static void check(java.lang.Object protocolInstance,
                         int protocolId)

Perform some checks over the annotations in the protocol class. In particular:
  (1) if '@Seine' was defined (otherwise, throw a warning)
  (2.1) if any '@Resource' were defined (otherwise, throw a warning)
  (2.2) if all '@Resource' apply to a public field (otherwise, throw an error)
  (3.1) if any annotations for deviations were defined (otherwise, throw a warning)
  (3.2) if all the annotations for deviations apply to public methods
                (otherwise, throw an error)

checkResources

public static void checkResources(java.util.HashSet<java.lang.String> resources,
                                  java.lang.String protocolName)

checkIndicators

public static void checkIndicators(java.util.HashSet<java.lang.String> indicators,
                                   java.lang.String protocolName)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace CentreonLegacy\Core\Widget;

use Pimple\Psr11\Container;
use Centreon\Test\Mock\CentreonDB;
use Centreon\Test\Mock\DependencyInjector\ServiceContainer;
use Centreon\Test\Mock\DependencyInjector\ConfigurationDBProvider;
use Centreon\Test\Mock\DependencyInjector\FilesystemProvider;
use Centreon\Test\Mock\DependencyInjector\FinderProvider;

class InformationTest extends \PHPUnit\Framework\TestCase
{
    private $container;
    private $db;
    private $utils;
    private $configuration;

    public function setUp(): void
    {
        $this->container = new ServiceContainer();

        $this->db = new CentreonDB();

        $this->utils = $this->getMockBuilder('CentreonLegacy\Core\Utils\Utils')
            ->disableOriginalConstructor()
            ->getMock();

        $this->configuration = array(
            'title' => 'My Widget',
            'author' => 'Centreon',
            'email' => 'contact@centreon.com',
            'website' => 'http://www.centreon.com',
            'description' => 'Widget for displaying host monitoring information',
            'version' => '1.0.0',
            'keywords' => 'centreon, widget, host, monitoring',
            'screenshot' => '',
            'thumbnail' => './widgets/host-monitoring/resources/centreon-logo.png',
            'url' => './widgets/host-monitoring/index.php',
            'directory' => 'my-widget',
            'preferences' => array(
                'preference' => array(
                    array(
                        '@attributes' => array(
                            'label' => 'Host Name',
                            'name' => 'host_name_search',
                            'defaultValue' => '',
                            'type' => 'compare',
                            'header' => 'Filters'
                        )

                    )
                )
            )
        );
    }

    public function tearDown(): void
    {
        $this->container->terminate();
        $this->container = null;
    }

    public function testGetConfiguration()
    {
        $expectedResult = $this->configuration;
        $expectedResult['autoRefresh'] = 0;

        $filesystem = $this->getMockBuilder('\Symfony\Component\Filesystem\Filesystem')
            ->disableOriginalConstructor()
            ->onlyMethods(array('exists'))
            ->getMock();
        $filesystem->expects($this->any())
            ->method('exists')
            ->willReturn(true);
        $this->container->registerProvider(new FilesystemProvider($filesystem));

        $this->utils->expects($this->any())
            ->method('buildPath')
            ->willReturn('MyWidget');
        $this->utils->expects($this->any())
            ->method('xmlIntoArray')
            ->willReturn($this->configuration);

        $information = new Information(new Container($this->container), $this->utils);
        $configuration = $information->getConfiguration('my-widget');

        $this->assertEquals($configuration, $expectedResult);
    }

    public function testGetTypes()
    {
        $expectedResult = array(
            'type1' => array(
                'id' => 1,
                'name' => 'type1'
            )
        );

        $query = 'SELECT ft_typename, field_type_id ' .
            'FROM widget_parameters_field_type ';
        $this->db->addResultSet(
            $query,
            array(
                array(
                    'ft_typename' => 'type1',
                    'field_type_id' => 1
                )
            )
        );

        $this->container->registerProvider(new ConfigurationDBProvider($this->db));

        $information = new Information(new Container($this->container), $this->utils);
        $types = $information->getTypes();

        $this->assertEquals($types, $expectedResult);
    }

    public function testGetParameterIdByName()
    {
        $query = 'SELECT parameter_id ' .
            'FROM widget_parameters ' .
            'WHERE parameter_code_name = :name ';
        $this->db->addResultSet(
            $query,
            array(
                array('parameter_id' => 1)
            )
        );

        $this->container->registerProvider(new ConfigurationDBProvider($this->db));

        $information = new Information(new Container($this->container), $this->utils);
        $id = $information->getParameterIdByName('MyWidget');

        $this->assertEquals($id, 1);
    }

    public function testGetParameters()
    {
        $expectedResult = array(
            'parameter1' => array(
                'parameter_id' => 1,
                'parameter_name' => 'parameter 1',
                'parameter_code_name' => 'parameter1',
                'default_value' => '',
                'parameter_order' => 1,
                'header_title' => 'title',
                'require_permission' => null,
                'widget_model_id' => 1,
                'field_type_id' => 1
            )
        );

        $query = 'SELECT * ' .
            'FROM widget_parameters ' .
            'WHERE widget_model_id = :id ';
        $this->db->addResultSet(
            $query,
            array(
                array(
                    'parameter_id' => 1,
                    'parameter_name' => 'parameter 1',
                    'parameter_code_name' => 'parameter1',
                    'default_value' => '',
                    'parameter_order' => 1,
                    'header_title' => 'title',
                    'require_permission' => null,
                    'widget_model_id' => 1,
                    'field_type_id' => 1
                )
            )
        );

        $this->container->registerProvider(new ConfigurationDBProvider($this->db));

        $information = new Information(new Container($this->container), $this->utils);
        $parameters = $information->getParameters(1);

        $this->assertEquals($parameters, $expectedResult);
    }

    public function testGetIdByName()
    {
        $query = 'SELECT widget_model_id ' .
            'FROM widget_models ' .
            'WHERE directory = :directory';
        $this->db->addResultSet(
            $query,
            array(
                array('widget_model_id' => 1)
            )
        );

        $this->container->registerProvider(new ConfigurationDBProvider($this->db));

        $information = new Information(new Container($this->container), $this->utils);
        $id = $information->getIdByName('MyWidget');

        $this->assertEquals($id, 1);
    }

    public function testGetAvailableList()
    {
        $configuration = $this->configuration;
        $configuration['autoRefresh'] = 0;
        $expectedResult = array(
            'my-widget' => $configuration
        );

        $finder = $this->getMockBuilder('\Symfony\Component\Finder\Finder')
            ->disableOriginalConstructor()
            ->onlyMethods(array('directories', 'depth', 'in'))
            ->getMock();
        $finder->expects($this->any())
            ->method('directories')
            ->willReturn($finder);
        $finder->expects($this->any())
            ->method('depth')
            ->willReturn($finder);
        $finder->expects($this->any())
            ->method('in')
            ->willReturn(
                array(
                    new \SplFileInfo('my-widget')
                )
            );
        $this->container->registerProvider(new FinderProvider($finder));

        $filesystem = $this->getMockBuilder('\Symfony\Component\Filesystem\Filesystem')
            ->disableOriginalConstructor()
            ->onlyMethods(array('exists'))
            ->getMock();
        $filesystem->expects($this->any())
            ->method('exists')
            ->willReturn(true);
        $this->container->registerProvider(new FilesystemProvider($filesystem));

        $this->utils->expects($this->any())
            ->method('buildPath')
            ->willReturn('MyWidget');
        $this->utils->expects($this->any())
            ->method('xmlIntoArray')
            ->willReturn($this->configuration);

        $information = new Information(new Container($this->container), $this->utils);
        $list = $information->getAvailableList();

        $this->assertEquals($list, $expectedResult);
    }

    public function testGetList()
    {
        $configuration = $this->configuration;
        $configuration['autoRefresh'] = 0;
        $configuration['source_available'] = true;
        $configuration['is_installed'] = true;
        $configuration['upgradeable'] = false;
        $configuration['installed_version'] = '1.0.0';
        $configuration['available_version'] = '1.0.0';
        $configuration['id'] = 1;
        unset($configuration['version']);

        $expectedResult = array(
            'my-widget' => $configuration
        );

        $this->db->addResultSet(
            'SELECT * FROM widget_models ',
            array(
                array(
                    'widget_model_id' => 1,
                    'title' => 'my title',
                    'description' => 'my description',
                    'url' => '',
                    'version' => '1.0.0',
                    'directory' => 'my-widget',
                    'author' => 'phpunit',
                    'email' => 'root@localhost',
                    'website' => 'centreon.com',
                    'keywords' => 'centreon',
                    'screenshot' => null,
                    'thumbnail' => '',
                    'autoRefresh' => 0
                )
            )
        );
        $this->container->registerProvider(new ConfigurationDBProvider($this->db));

        $this->utils->expects($this->any())
            ->method('buildPath')
            ->willReturn('MyWidget');

        $finder = $this->getMockBuilder('\Symfony\Component\Finder\Finder')
            ->disableOriginalConstructor()
            ->onlyMethods(array('directories', 'depth', 'in'))
            ->getMock();
        $finder->expects($this->any())
            ->method('directories')
            ->willReturn($finder);
        $finder->expects($this->any())
            ->method('depth')
            ->willReturn($finder);
        $finder->expects($this->any())
            ->method('in')
            ->willReturn(
                array(
                    new \SplFileInfo('my-widget')
                )
            );
        $this->container->registerProvider(new FinderProvider($finder));

        $filesystem = $this->getMockBuilder('\Symfony\Component\Filesystem\Filesystem')
            ->disableOriginalConstructor()
            ->onlyMethods(array('exists'))
            ->getMock();
        $filesystem->expects($this->any())
            ->method('exists')
            ->willReturn(true);
        $this->container->registerProvider(new FilesystemProvider($filesystem));

        $this->utils->expects($this->any())
            ->method('xmlIntoArray')
            ->willReturn($this->configuration);

        $information = new Information(new Container($this->container), $this->utils);
        $list = $information->getList();

        $this->assertEquals($list, $expectedResult);
    }
}


text:
@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIImageView *authorIcon;

@property NetworkManager *networkManager;

@end

@implementation ViewController

@synthesize webView, networkManager, authorIcon;

+ (NSString *)uuid
{
    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
    CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    return (__bridge NSString *)uuidStringRef;
}

- (void)viewDidLoad {
    // get the unique ID of the app on this device

    // if it doesn't exist, generate it with "+ (NSString *)uuid"
    // and store it in the preferences

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSString *indexPath = [HtmlGenerator createHtmlBookIndex];
    NSURL *url = [NSURL URLWithString:indexPath];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    //webView.scalesPageToFit = YES;
    //webView.autoresizesSubviews = YES;
    //webView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);

    // set size and alpha of author icon to zero
    authorIcon.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0, 0);
    authorIcon.alpha = 0;
    // register tap action on author icon
    UITapGestureRecognizer *authorIconTap =  [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(authorIconTapping:)];
    [authorIconTap setNumberOfTapsRequired:1];
    [authorIcon addGestureRecognizer:authorIconTap];

    // if we're in author mode, we always show the edit button
    // that way we can create a server manually
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"author-mode"]) {
        [self showAuthorIcon];
    }

    [webView loadRequest:req];

    //[webView loadHTMLString:@"
Hello!
" baseURL:nil];

    networkManager = [[NetworkManager alloc] initWithDelegate:self];
}

- (void)authorIconTapping:(UIGestureRecognizer *)recognizer {
    // NSLog(@"author icon tapped");
    [self presentViewController:networkManager.serversView animated:YES completion:nil];
    [self hideAuthorIcon];
    //[self.navigationController pushViewController:serversView animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark NetworkManagerDelegate implementations

- (void)bookUpdateStarted {
    [webView loadHTMLString:@"
Updating...
" baseURL:nil];
}

- (void)bookUpdateEnded:(NSString *)bookHtmlIndex {
    NSLog(@"Loading book: %@", bookHtmlIndex);
    NSURL *url = [NSURL URLWithString:bookHtmlIndex];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    [webView loadRequest:req];
}

- (void)showAuthorIcon {
    if (authorIcon.alpha > 0) {
        return;
    }

    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         authorIcon.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1, 1);
                         authorIcon.alpha = 1;
                     }
                     completion:^(BOOL finished) {
                     }
     ];
}

- (void)hideAuthorIcon {
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"author-mode"]) return;

    if (authorIcon.alpha < 1) {
        return;
    }

    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState| UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         authorIcon.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0, 0);
                         authorIcon.alpha = 0;
                     }
                     completion:^(BOOL finished) {
                     }
     ];
}

// Back button in ServersTableView
- (void)backTapped {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
package com.blogspot.oraclestack.utilities;

import java.util.HashSet;
import java.util.Set;
import oracle.core.ojdl.logging.ODLLevel;
import oracle.core.ojdl.logging.ODLLogger;
import oracle.iam.platform.OIMClient;
import oracle.iam.platformservice.api.PlatformUtilsService;
import oracle.iam.platformservice.exception.InvalidCacheCategoryException;
import oracle.iam.platformservice.exception.PlatformServiceException;
import oracle.iam.platformservice.vo.JarElement;
import com.blogspot.oraclestack.constants.JarElementType;;

/**
 * This class contain methods that have the same functionality as the out of the box
 * scripts given in $MW_HOME/Oracle_IDM1/server/bin/" directory.
 * @author rayedchan
 */
public class PlatformServiceUtilities
{
    // Logger
    public static ODLLogger logger = ODLLogger.getODLLogger(PlatformServiceUtilities.class.getName());

    private PlatformUtilsService platformUtilsServiceOps = null;

    /**
     * Constructor
     * Precondition: A system administrator is logged in with the OIM client
     * @param oimClient
     */
    public PlatformServiceUtilities(OIMClient oimClient)
    {
        this.platformUtilsServiceOps = oimClient.getService(PlatformUtilsService.class);
    }

    /**
    * Purges the entire OIM cache. Same functionality as the "PurgeCache.sh" script
    * which is located in "$MW_HOME/Oracle_IDM1/server/bin/" directory.
    * @throws InvalidCacheCategoryException
    */
    public void purgeCache() throws InvalidCacheCategoryException
    {
        platformUtilsServiceOps.purgeCache("ALL");
        logger.log(ODLLevel.NOTIFICATION, "Successfully purged the cache.");
    }

    /**
     * Uploads a single jar file to database. A record will be added to OIM.OIMHOME_JARS
     * table to indicate the jar is successfully uploaded. Same functionality as the "UploadJars.sh" script
     * which is located in "$MW_HOME/Oracle_IDM1/server/bin/" directory.
     * @param jarType   The type of jar to be uploaded.
     * @param jarPath   The absolute path to the jar file that is being uploaded.
     */
    public void uploadJar(JarElementType jarType, String jarPath) throws PlatformServiceException
    {
        // Build a jar element containing path and type data
        JarElement jarElement = new JarElement();
        jarElement.setType(jarType.name());
        jarElement.setPath(jarPath);

        // Build a set object to put jar element
        Set<JarElement> jarElements = new HashSet<JarElement>();
        jarElements.add(jarElement);

        // Service to upload jar to OIM Schema
        platformUtilsServiceOps.uploadJars(jarElements);
        logger.log(ODLLevel.NOTIFICATION, "Successfully uploaded jar: Type = {0}, Path = {1}", new Object[]{jarType.name(), jarPath});
    }

    /**
     * Removes a jar from the database. The corresponding jar record will be removed
     * from OIM.OIMHOME_JARS table. Same functionality as the "DeleteJars.sh" script
     * which is located in "$MW_HOME/Oracle_IDM1/server/bin/" directory.
     * @param jarType   The type of jar to be removed.
     * @param jarName   The name of the jar in the backend. Use the value in OIM.OIMHOME_JARS.OJ_NAME column.
     * @throws PlatformServiceException
     */
    public void deleteJar(JarElementType jarType, String jarName) throws PlatformServiceException
    {
        // Build a jar element containing path and type data
        JarElement jarElement = new JarElement();
        jarElement.setType(jarType.name());
        jarElement.setName(jarName);

        // Build a set object to put jar element
        Set<JarElement> jarElements = new HashSet<JarElement>();
        jarElements.add(jarElement);

        // Service to remove jar from OIM Schema
        platformUtilsServiceOps.deleteJars(jarElements);
        logger.log(ODLLevel.NOTIFICATION, "Successfully deleted jar: Type = {0}, Name = {1}", new Object[]{jarType.name(),jarName});
    }

     /**
     * Updates a single jar file to database. UPDATE_ON and UPDATED_BY columns in the OIMHOME_JARS table will be updated with current date
     * to indicate the jar is successfully updated. Same functionality as the "UpdateJars.sh" script
     * which is located in "$MW_HOME/Oracle_IDM1/server/bin/" directory.
     * @param jarType   The type of jar to be updated.
     * @param jarPath   The absolute path to the jar file that is being updated. The jar name must exist in the database.
     */
    public void updateJar(JarElementType jarType, String jarPath) throws PlatformServiceException
    {
        // Build a jar element containing path and type data
        JarElement jarElement = new JarElement();
        jarElement.setType(jarType.name());
        jarElement.setPath(jarPath);

        // Build a set object to put jar element
        Set<JarElement> jarElements = new HashSet<JarElement>();
        jarElements.add(jarElement);

        // Service to update jar to OIM Schema
        platformUtilsServiceOps.updateJars(jarElements);
        logger.log(ODLLevel.NOTIFICATION, "Successfully updated jar: Type = {0}, Path = {1}", new Object[]{jarType.name(), jarPath});
    }

    /**
     * Download a jar from the database. Same functionality as the "DownloadJars.sh" script
     * which is located in "$MW_HOME/Oracle_IDM1/server/bin/" directory.
     * @param jarType   The type of jar to be downloaded.
     * @param jarName   The name of the jar in the backend to be downloaded. Use the value in OIM.OIMHOME_JARS.OJ_NAME column.
     * @throws PlatformServiceException
     */
    public void downloadJar(JarElementType jarType, String jarName, String destinationPath) throws PlatformServiceException
    {
        // Build a jar element containing path and type data
        JarElement jarElement = new JarElement();
        jarElement.setType(jarType.name());
        jarElement.setName(jarName);
        jarElement.setPath(destinationPath);

        // Build a set object to put jar element
        Set<JarElement> jarElements = new HashSet<JarElement>();
        jarElements.add(jarElement);

        // Service to download jar from OIM Schema
        platformUtilsServiceOps.downloadJars(jarElements);
        logger.log(ODLLevel.NOTIFICATION, "Successfully downloaded jar: Type = {0}, Name = {1}", new Object[]{jarType.name(),jarName});
    }
}


text:
'use strict';

angular.module('dandelionApp')
  .controller('EditAddressesController', function($scope, Auth, $http, $state, Address, $stateParams, $timeout, _) {

  	Address.get({ id: $stateParams.id }).$promise
  		.then((address) => {
  			$scope.address = {
  				name: address.name,
  				phone: address.phone,
  				city: address.city,
  				district: address.district,
  				ward: address.ward,
  				street: address.street,
  				default: address.default,
  			};

        $scope.master = angular.copy($scope.address.default);
      });

    $scope.editAddress = function() {
      // console.log('Edit');
      $scope.submitted = true;

      if ($scope.form.$valid) {
        // console.log('valid');

        var name = $scope.address.name;
        var phone = $scope.address.phone;
        var city = {
          id: $scope.address.city.ID,
          title: $scope.address.city.Title
        };
        var district = {
          id: $scope.address.district.ID,
          title: $scope.address.district.Title
        };
        var ward = {
          id: $scope.address.ward.ID,
          title: $scope.address.ward.Title
        };
        var street = $scope.address.street;
        var isDefault = $scope.address.default;

        Address.update({
          id: $stateParams.id
        },{
          uid: Auth.getCurrentUser()._id,
          name: name,
          phone: phone,
          city: city,
          district: district,
          ward: ward,
          street: street,
          default: isDefault
        })
          .$promise.then((res) => {
            $state.go('account.addresses');
          });
      }
    };

    $http.get('/api/addresses/city')
      .then((res) => {
        $scope.cities = res.data.LtsItem;
        // console.log('Cities');
        // console.log($scope.cities);

        $scope.address.city = _.find($scope.cities, function(city){
          return city.ID == $scope.address.city.id;
        });

        // console.log('City');
        // console.log($scope.address.city);
      });

    $scope.$watch('address.city', function(newVal) {
      if(typeof newVal !== 'undefined'){
        if(typeof newVal.ID !== 'undefined') {
          // console.log('City newVal');
          // console.log(newVal);
          $http.get('/api/addresses/city/'+newVal.ID+'/district')
            .then((res) => {
              $scope.districts = res.data;
              // console.log('Districts');
              // console.log($scope.districts);

              $scope.address.district = _.find($scope.districts, function(district){
                return district.ID == $scope.address.district.id;
              });

              // console.log('District');
              // console.log($scope.address.district);
            });
        }
      }
    });

    $scope.$watch('address.district', function(newVal) {
      if(typeof newVal !== 'undefined') {
        if(typeof newVal.ID !== 'undefined') {
          // console.log('District newVal');
          // console.log(newVal);
          $http.get('/api/addresses/district/'+newVal.ID+'/ward')
            .then((res) => {
              $scope.wards = res.data;
              // console.log('Wards');
              // console.log($scope.wards);

              $scope.address.ward = _.find($scope.wards, function(ward){
                return ward.ID == $scope.address.ward.id;
              });
              // console.log('Ward');
              // console.log($scope.address.ward);
            });
        }
      }
    });
  });


text:
package common.string;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import org.trianacode.gui.panels.ParameterPanel;
import org.trianacode.gui.panels.TFileChooser;
import org.trianacode.gui.windows.ErrorDialog;

/**
 * $POPUP_DESCRIPTION
 *
 * @author $AUTHOR
 * @version $Revision: 2921 $
 */

public class StringGenPanel extends ParameterPanel implements ActionListener, FocusListener, ItemListener {

    private JTextArea textarea = new JTextArea(10, 30);

    private JMenuItem open = new JMenuItem("Open...");
    private JMenuItem clear = new JMenuItem("Clear");
    private JCheckBoxMenuItem wordwrap = new JCheckBoxMenuItem("Word Wrap", false);

    /**
     * This method is called before the panel is displayed. It should initialise the panel layout.
     */
    public void init() {
        setLayout(new BorderLayout());

        JMenu filemenu = new JMenu("File");
        filemenu.add(open);
        filemenu.add(clear);
        open.addActionListener(this);
        clear.addActionListener(this);

        JMenu viewmenu = new JMenu("View");
        viewmenu.add(wordwrap);
        wordwrap.addItemListener(this);

        JMenuBar menu = new JMenuBar();
        menu.add(filemenu);
        menu.add(viewmenu);

        setMenuBar(menu);

        textarea.setLineWrap(false);
        textarea.setWrapStyleWord(true);
        textarea.addFocusListener(this);
        textarea.setText(getParameter("str").toString());

        JLabel label = new JLabel("Enter String:");
        label.setBorder(new EmptyBorder(0, 0, 3, 0));

        JScrollPane scroll = new JScrollPane(textarea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        JPanel textpanel = new JPanel(new BorderLayout());
        textpanel.add(label, BorderLayout.NORTH);
        textpanel.add(scroll, BorderLayout.CENTER);

        add(textpanel, BorderLayout.CENTER);
    }

    /**
     * This method is called when cancel is clicked on the parameter window. It should synchronize the GUI components
     * with the task parameter values
     */
    public void reset() {
        textarea.setText(getParameter("str").toString());
    }

    /**
     * This method is called when a parameter in the task is updated. It should update the GUI in response to the
     * parameter update
     */
    public void parameterUpdate(String paramname, Object value) {
        if (paramname.equals("str")) {
            textarea.setText(value.toString());
        }
    }

    /**
     * This method is called when the panel is being disposed off. It should clean-up subwindows, open files etc.
     */
    public void dispose() {
        textarea.removeFocusListener(this);
    }

    /**
     * Opens a text file into the string gen
     */
    private void open() {
        TFileChooser chooser = new TFileChooser("Common.String.StringGen");
        chooser.setDialogTitle("Open...");
        chooser.setFileSelectionMode(TFileChooser.FILES_ONLY);

        int result = chooser.showOpenDialog(this);

        if (result == TFileChooser.APPROVE_OPTION) {
            String str = "";
            String line;
            boolean init = true;

            try {
                BufferedReader reader = new BufferedReader(new FileReader(chooser.getSelectedFile()));

                while ((line = reader.readLine()) != null) {
                    if (!init) {
                        str += "\n";
                    } else {
                        init = false;
                    }

                    str += line;
                }
            } catch (IOException except) {
                ErrorDialog.show("Error Reading File: " + chooser.getSelectedFile(), except);
            }

            textarea.setText(str);
            textarea.setCaretPosition(0);
        }
    }

    /**
     * Invoked when an action occurs.
     */
    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == open) {
            open();
        } else if (event.getSource() == clear) {
            textarea.setText("");
        }
    }

    public void itemStateChanged(ItemEvent event) {
        if (event.getSource() == wordwrap) {
            textarea.setLineWrap(wordwrap.isSelected());
        }
    }

    public void focusGained(FocusEvent event) {
    }

    public void focusLost(FocusEvent event) {
        setParameter("str", textarea.getText());
    }

}


text:
get '/' do
  # Send to login page if they aren't logged in
  redirect '/login' unless session[:id]
  # Send to user profile/show page if they are logged in
  redirect "/users/#{session[:id]}"
end


text:
module Adauth
    module Rails
        # Included into Models in Rails
        #
        # Requires you to set 2 Constants
        #
        # AdauthMappings
        #
        # A hash which controls how Adauth maps its values to rails e.g.
        #
        # AdauthMappings = {
        #   :name => :login
        # }
        #
        # This will store Adauths 'login' value in the 'name' field.
        #
        # AdauthSearchField
        #
        # This is an array which contains 2 values and is used to find the objects record e.g.
        #
        # AdauthSearchField = [:login, :name]
        #
        # This will cause RailsModel.where(:name => AdauthObject.login).first_or_initialize
        #
        # The Order is [adauth_field, rails_field]
        module ModelBridge
            # Registers the class methods when ModelBridge is included
            def self.included(base)
                base.extend ClassMethods
            end

            # Uses AdauthMappings to update the values on the model using the ones from Adauth
            def update_from_adauth(adauth_model)
                self.class::AdauthMappings.each do |k, v|
                    setter = "#{k.to_s}=".to_sym
                    value = v.is_a?(Array) ? v.join(", ") : v

                    # ensure the attribute exists in the collected data and only assign if it does
                    if adauth_model.respond_to?(value)
                      self.send(setter, adauth_model.send(value))
                    end
                end
                self.save
                self
            end

            # Class Methods for ModelBridge
            module ClassMethods
                # Creates a new RailsModel from the adauth_model
                def create_from_adauth(adauth_model)
                    rails_model = self.new
                    rails_model.update_from_adauth(adauth_model)
                end

                # Used to create the RailsModel if it doesn't exist and update it if it does
                def return_and_create_from_adauth(adauth_model)
                    adauth_field = self::AdauthSearchField.first
                    adauth_search_value = adauth_model.send(adauth_field)
                    rails_search_field = self::AdauthSearchField.second
                    # Model#where({}).first_or_initialize is also compatible with Mongoid (3.1.0+)
                    rails_model = self.send(:where, { rails_search_field => adauth_search_value }).first_or_initialize
                    rails_model.update_from_adauth(adauth_model)
                    rails_model
                end
            end
        end
    end
end


text:
/* @flow */
export default {
  id: 'import-syntax',
  title: 'Import Syntax',
  description: `\`\`\`
import Dialog, { DialogHeader, DialogTitle } from 'mineral-ui/Dialog';
\`\`\``
};


text:
'use strict'

const check = require('check-types')
const BfjStream = require('./stream')
const util = require('util')

util.inherits(DataStream, BfjStream)

module.exports = DataStream

function DataStream (read, options) {
  if (check.not.instanceStrict(this, DataStream)) {
    return new DataStream(read, options)
  }

  return BfjStream.call(this, read, Object.assign({ objectMode: true }, options))
}