text:
#include "main/glheader.h"
#include "main/mtypes.h"
#include "main/imports.h"
#include "main/shaderobj.h"
#include "program/prog_cache.h"
#include "program/program.h"

struct cache_item
{
   GLuint hash;
   unsigned keysize;
   void *key;
   struct gl_program *program;
   struct cache_item *next;
};

struct gl_program_cache
{
   struct cache_item **items;
   struct cache_item *last;
   GLuint size, n_items;
};

/**
 * Compute hash index from state key.
 */
static GLuint
hash_key(const void *key, GLuint key_size)
{
   const GLuint *ikey = (const GLuint *) key;
   GLuint hash = 0, i;

   assert(key_size >= 4);

   /* Make a slightly better attempt at a hash function:
    */
   for (i = 0; i < key_size / sizeof(*ikey); i++)
   {
      hash += ikey[i];
      hash += (hash << 10);
      hash ^= (hash >> 6);
   }

   return hash;
}

/**
 * Rebuild/expand the hash table to accomodate more entries
 */
static void
rehash(struct gl_program_cache *cache)
{
   struct cache_item **items;
   struct cache_item *c, *next;
   GLuint size, i;

   cache->last = NULL;

   size = cache->size * 3;
   items = malloc(size * sizeof(*items));
   memset(items, 0, size * sizeof(*items));

   for (i = 0; i < cache->size; i++)
      for (c = cache->items[i]; c; c = next) {
	 next = c->next;
	 c->next = items[c->hash % size];
	 items[c->hash % size] = c;
      }

   free(cache->items);
   cache->items = items;
   cache->size = size;
}

static void
clear_cache(struct gl_context *ctx, struct gl_program_cache *cache,
	    GLboolean shader)
{
   struct cache_item *c, *next;
   GLuint i;

   cache->last = NULL;

   for (i = 0; i < cache->size; i++) {
      for (c = cache->items[i]; c; c = next) {
	 next = c->next;
	 free(c->key);
	 if (shader) {
	    _mesa_reference_shader_program(ctx,
					   (struct gl_shader_program **)&c->program,
					   NULL);
	 } else {
	    _mesa_reference_program(ctx, &c->program, NULL);
	 }
	 free(c);
      }
      cache->items[i] = NULL;
   }

   cache->n_items = 0;
}

struct gl_program_cache *
_mesa_new_program_cache(void)
{
   struct gl_program_cache *cache = CALLOC_STRUCT(gl_program_cache);
   if (cache) {
      cache->size = 17;
      cache->items =
         calloc(1, cache->size * sizeof(struct cache_item));
      if (!cache->items) {
         free(cache);
         return NULL;
      }
   }
   return cache;
}

void
_mesa_delete_program_cache(struct gl_context *ctx, struct gl_program_cache *cache)
{
   clear_cache(ctx, cache, GL_FALSE);
   free(cache->items);
   free(cache);
}

void
_mesa_delete_shader_cache(struct gl_context *ctx,
			  struct gl_program_cache *cache)
{
   clear_cache(ctx, cache, GL_TRUE);
   free(cache->items);
   free(cache);
}

struct gl_program *
_mesa_search_program_cache(struct gl_program_cache *cache,
                           const void *key, GLuint keysize)
{
   if (cache->last &&
       cache->last->keysize == keysize &&
       memcmp(cache->last->key, key, keysize) == 0) {
      return cache->last->program;
   }
   else {
      const GLuint hash = hash_key(key, keysize);
      struct cache_item *c;

      for (c = cache->items[hash % cache->size]; c; c = c->next) {
         if (c->hash == hash &&
             c->keysize == keysize &&
             memcmp(c->key, key, keysize) == 0) {

            cache->last = c;
            return c->program;
         }
      }

      return NULL;
   }
}

void
_mesa_program_cache_insert(struct gl_context *ctx,
                           struct gl_program_cache *cache,
                           const void *key, GLuint keysize,
                           struct gl_program *program)
{
   const GLuint hash = hash_key(key, keysize);
   struct cache_item *c = CALLOC_STRUCT(cache_item);

   c->hash = hash;

   c->key = malloc(keysize);
   memcpy(c->key, key, keysize);
   c->keysize = keysize;

   c->program = program;  /* no refcount change */

   if (cache->n_items > cache->size * 1.5) {
      if (cache->size < 1000)
	 rehash(cache);
      else
	 clear_cache(ctx, cache, GL_FALSE);
   }

   cache->n_items++;
   c->next = cache->items[hash % cache->size];
   cache->items[hash % cache->size] = c;
}

void
_mesa_shader_cache_insert(struct gl_context *ctx,
			  struct gl_program_cache *cache,
			  const void *key, GLuint keysize,
			  struct gl_shader_program *program)
{
   const GLuint hash = hash_key(key, keysize);
   struct cache_item *c = CALLOC_STRUCT(cache_item);

   c->hash = hash;

   c->key = malloc(keysize);
   memcpy(c->key, key, keysize);
   c->keysize = keysize;

   c->program = (struct gl_program *)program;  /* no refcount change */

   if (cache->n_items > cache->size * 1.5) {
      if (cache->size < 1000)
	 rehash(cache);
      else
	 clear_cache(ctx, cache, GL_TRUE);
   }

   cache->n_items++;
   c->next = cache->items[hash % cache->size];
   cache->items[hash % cache->size] = c;
}


text:
/**
 * The possible ways search results are shown
 */
export enum ResultType {
  CATEGORIES = 'categories',
  TILES = 'tiles',
  LIST = 'list',
  MAP = 'map',
}

redpajama_set_name: RedPajamaGithub


text:
var searchwp_settings_handler = function(){
	(function($){

		var uniqid = function (prefix, more_entropy) {
			// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			// +    revised by: Kankrelune (http://www.webfaktory.info/)
			// %        note 1: Uses an internal counter (in php_js global) to avoid collision
			// *     example 1: uniqid();
			// *     returns 1: 'a30285b160c14'
			// *     example 2: uniqid('foo');
			// *     returns 2: 'fooa30285b1cd361'
			// *     example 3: uniqid('bar', true);
			// *     returns 3: 'bara20285b23dfd1.31879087'
			if (typeof prefix === 'undefined') {
				prefix = "";
			}

			var retId;
			var formatSeed = function (seed, reqWidth) {
				seed = parseInt(seed, 10).toString(16); // to hex str
				if (reqWidth < seed.length) { // so long we split
					return seed.slice(seed.length - reqWidth);
				}
				if (reqWidth > seed.length) { // so short we pad
					return new Array(1 + (reqWidth - seed.length)).join('0') + seed;
				}
				return seed;
			};

			// BEGIN REDUNDANT
			if (!this.php_js) {
				this.php_js = {};
			}
			// END REDUNDANT
			if (!this.php_js.uniqidSeed) { // init seed with big random int
				this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
			}
			this.php_js.uniqidSeed++;

			retId = prefix; // start with prefix, add current milliseconds hex string
			retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
			retId += formatSeed(this.php_js.uniqidSeed, 5); // add seed hex string
			if (more_entropy) {
				// for more entropy we add a float lower to 10
				retId += (Math.random() * 10).toFixed(8).toString();
			}

			return retId;
		};

		$(document).tooltip({
			items: ".swp-tooltip,.swp-tooltip-alt",
			content: function(){
				return $($(this).attr('href')).html();
			}
		});

		var excludeSelects = function() {

			function format_term (term) {
				var markup = "
" +
					"
" + $("
").text(term.text).html() + "

";

				return markup;
			}

			function format_term_selection (term) {
				return term.text;
			}

			$('select.swp-exclude-select').each(function(){
				var $el = $(this),
					options = {};

				if( $el.data('searchable') ) {
					options = {
						ajax: {
							url: ajaxurl,
							dataType: 'json',
							delay: 250,
							data: function (params) {
								return {
									q: params.term, // search term
									_ajax_nonce: $el.data('nonce'),
									tax: $el.data('tax'),
									engine: $el.data('engine'),
									action: 'searchwp_get_tax_terms'
								};
							},
							processResults: function (data, params) {
								return {
									results: data.items
								};
							},
							cache: true
						},
						escapeMarkup: function (markup) { return markup; },
						minimumInputLength: 1,
						language: {
							inputTooShort: function () {
								return $('#swp-search-placeholder').text();
							}
						},
						templateResult: format_term,
						templateSelection: format_term_selection
					}
				}

				$el.select2(options);
			});
		};

		excludeSelects();

		var customFieldSelects = function() {

			function format_key (term) {
				var markup = "
" +
					"
" + $("
").text(term.text).html() + "

";

				return markup;
			}

			function format_key_selection (term) {
				return term.text;
			}

			$('.swp-custom-field-select select').each(function(){
				var $el = $(this),
					options = {};

				if( $el.data('searchable') ) {
					options = {
						ajax: {
							url: ajaxurl,
							dataType: 'json',
							delay: 250,
							data: function (params) {
								return {
									q: params.term, // search term
									_ajax_nonce: $el.data('nonce'),
									action: 'searchwp_get_meta_keys'
								};
							},
							processResults: function (data, params) {
								return {
									results: data.items
								};
							},
							cache: true
						},
						escapeMarkup: function (markup) { return markup; },
						minimumInputLength: 1,
						language: {
							inputTooShort: function () {
								return $('#swp-search-placeholder').text();
							}
						},
						templateResult: format_key,
						templateSelection: format_key_selection
					}
				}

				$el.select2(options);
			});
		};

		customFieldSelects();

		var updateTabContentHeights = function( $parent ){
			// first check to make sure the tabs don't exceed the height
			var $parent_tab_content = $parent.find('.swp-tab-content');
			var $parent_tab_pane = $parent_tab_content.find('.swp-tab-pane');
			var $first_tab_pane = $parent_tab_pane.first();
			var $parent_nav = $parent.find('.swp-nav');
			if($parent_nav.height()>$first_tab_pane.height()){
				$first_tab_pane.height($parent_nav.height());
			}

			// make sure our tab content is at least the proper height
			// while doing that, hide each tab pane
			var tallest = 0;
			$parent_tab_pane.each(function(){
				if($(this).height()>tallest){
					tallest = $(this).height();
				}
			});
			$parent_tab_content.height(tallest+50);
		};

		var initTabs = function( $grandparent ){
			$grandparent .find('.swp-tabbable').each(function(){

				var $parent = $(this);

				// prevent clicking labels from toggling the checkbox
				$parent.find('.swp-tabs label').unbind('click').click(function(e){
					e.preventDefault();
				});

				updateTabContentHeights($parent);
				$parent.find('.swp-tab-content .swp-tab-pane').hide();

				// hook the clicks
				$parent.find('.swp-tabs > li').click(function(){
					$parent.find('.swp-tabs > li.swp-tab-active').removeClass('swp-tab-active');
					$parent.find('.swp-tab-content .swp-tab-pane').hide();
					$(this).addClass('swp-tab-active');
					$('#'+$(this).data('swp-engine')).show();
				});

				// make sure the first tab is active
				if(!$parent.find('.swp-tabs .swp-tab-active').length){
					$parent.find('.swp-tabs > li:eq(0)').trigger('click');
				}

			});
		};

		initTabs( $('.swp-default-engine') );
		$('.swp-supplemental-engine').each(function(){
			initTabs( $(this) );
		});

		var $body = $('body');

		// allow addition of custom fields
		$body.on('click','a.swp-add-custom-field', function(){
			_.templateSettings = {
				variable : 'swp',
				interpolate : /\{\{(.+?)\}\}/g
			};

			var template = _.template($('script#tmpl-swp-custom-fields').html());

			var swp = {
				arrayFlag: uniqid( 'swp', true).replace('.',''),
				postType: $(this).data('posttype'),
				engine: $(this).data('engine')
			};

			$(this).parents('tbody').find('tr:last').before(template(swp));

			// apply select2
			$(this).parents('tbody').find('.swp-custom-field:last .swp-custom-field-select select').select2({});

			updateTabContentHeights($(this).parents('.swp-tabbable'));

			return false;
		});

		$body.on('click','.swp-delete',function(){
			$(this).parents('tr').remove();
			return false;
		});

		$body.on('click','.swp-supplemental-engine-edit-trigger',function(){
			$(this).parents('.swp-supplemental-engine').addClass('swp-supplemental-engine-edit');
			updateTabContentHeights($(this).parents('.swp-supplemental-engine'));
			return false;
		});

		$body.on('click','.swp-del-supplemental-engine',function(){
			$(this).parents('.swp-supplemental-engine').remove();
			return false;
		});

		$body.on('click','.swp-add-supplemental-engine',function(e){
			e.preventDefault();
			_.templateSettings = {
				variable : 'swp',
				interpolate : /\{\{(.+?)\}\}/g
			};

			var engineSettingsTemplate = _.template($('script#tmpl-swp-engine').html());
			var supplementalTemplate = _.template($('script#tmpl-swp-supplemental-engine').html());

			var swp = {
				engine: uniqid( 'swpengine', true).replace('.',''),
				engineLabel: 'Supplemental'
			};

			swp.engineSettings = engineSettingsTemplate(swp);

			$(this).parents('.swp-supplemental-engines-wrapper').find('.swp-supplemental-engines').append(supplementalTemplate(swp));
			$(this).parents('.swp-supplemental-engines-wrapper').find('.swp-supplemental-engines .swp-supplemental-engine:last .swp-supplemental-engine-name > a').trigger('click');
			$(this).parents('.swp-supplemental-engines-wrapper').find('.swp-supplemental-engines .swp-supplemental-engine:last .swp-supplemental-engine-name > input').focus().select();
			initTabs( $('.swp-supplemental-engines .swp-supplemental-engine:last' ) );
			excludeSelects();
			customFieldSelects();
			return false;
		});

		// call out weights of -1 because they're usually unintended
		var maybe_weight_warning = function($el){
			if(parseFloat($el.val(),10)<0){
				$el.addClass('searchwp-weight-warning');
			}else{
				$el.removeClass('searchwp-weight-warning');
			}
		};
		$body.on('change keyup', '.swp-engine-weights input', function(){
			maybe_weight_warning($(this));
		});

	})(jQuery);
};


text:
<?php

namespace WikiRenderer\Generator\Docbook;

class NoFormatBlock extends Preformated
{
    protected $dbTagName = 'para';
}


text:
import { Component, OnInit, OnDestroy, ChangeDetectionStrategy } from "@angular/core";
import { Store } from "@ngrx/store";
import { Observable, Subscription, pipe } from "rxjs";
import { map } from "rxjs/operators";
import { ActivatedRoute } from "@angular/router";

import { RouterExtensions, Config } from "../../modules/core/index";
import { Platform } from "../../modules/datas/models/index";
import { Country } from "../../modules/countries/models/country";

import { IAppState, getPlatformPageError, getSelectedPlatform, getPlatformPageMsg, getAllCountriesInApp } from "../../modules/ngrx/index";
import { PlatformAction } from "../../modules/datas/actions/index";
import { CountriesAction } from "../../modules/countries/actions/index";

@Component({
  selector: "bc-zone-import-page",
  template: `
    <bc-zone-import
      (upload)="handleUpload($event)"
      (removeAllZone)="removeAllZone($event)"
      (err)="handleErrorUpload($event)"
      (back)="return($event)"
      [error]="error$ | async"
      [msg]="msg$ | async"
      [platform]="platform$ | async"
      [countries]="countries$ | async">
    </bc-zone-import>
  `,
  styles: [``]
})
export class ZoneImportPageComponent implements OnInit, OnDestroy {
  platform$: Observable<Platform>;
  error$: Observable<string | null>;
  msg$: Observable<string | null>;
  countries$: Observable<Country[]>;

  actionsSubscription: Subscription;
  needHelp: boolean = false;
  private kmlFile: string;
  private docs_repo: string;

  constructor(private store: Store<IAppState>, public routerext: RouterExtensions, route: ActivatedRoute) {
    this.actionsSubscription = route.params.pipe(map(params => new PlatformAction.SelectPlatformAction(params.idPlatform))).subscribe(store);
  }

  ngOnInit() {
    this.error$ = this.store.select(getPlatformPageError);
    this.msg$ = this.store.select(getPlatformPageMsg);
    this.platform$ = this.store.select(getSelectedPlatform);
    this.countries$ = this.store.select(getAllCountriesInApp);
  }

  ngOnDestroy() {
    this.actionsSubscription.unsubscribe();
  }

  handleUpload(kmlFile: any): void {
    this.store.dispatch(new PlatformAction.ImportZoneAction(kmlFile));
  }

  removeAllZone(platform: Platform) {
    this.store.dispatch(new PlatformAction.RemoveAllZoneAction(platform));
  }

  return(code: string) {
    this.routerext.navigate(["/platform/" + code], {
      transition: {
        duration: 1000,
        name: "slideTop"
      }
    });
  }
}


text:
package com.odobo.vertx3.serviceproxy;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.vertx.core.json.JsonObject;

/**
 * User: plenderyou
 * Date: 19/10/15
 * Time: 09:06
 */
public class SamplePojo {

    private String string;
    private int intValue;

    @JsonDeserialize(using = JsonObjectDeserializer.class)
    @JsonSerialize(using = JsonObjectSerializer.class)
    private JsonObject jsonObject;

    public String getString() {
        return string;
    }

    public SamplePojo setString(final String string) {
        this.string = string;
        return this;
    }

    public int getIntValue() {
        return intValue;
    }

    public SamplePojo setIntValue(final int intValue) {
        this.intValue = intValue;
        return this;
    }

    public JsonObject getJsonObject() {
        return jsonObject;
    }

    public SamplePojo setJsonObject(final JsonObject jsonObject) {
        this.jsonObject = jsonObject;
        return this;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (!(o instanceof SamplePojo)) return false;

        final SamplePojo that = (SamplePojo) o;

        if (intValue != that.intValue) return false;
        if (string != null ? !string.equals(that.string) : that.string != null) return false;
        return !(jsonObject != null ? !jsonObject.equals(that.jsonObject) : that.jsonObject != null);

    }

    @Override
    public int hashCode() {
        int result = string != null ? string.hashCode() : 0;
        result = 31 * result + intValue;
        result = 31 * result + (jsonObject != null ? jsonObject.hashCode() : 0);
        return result;
    }
}


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

<title>Geometry (tangram 0.5.1-SNAPSHOT API)</title>
<meta name="date" content="2017-02-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.mapzen.tangram.geometry

Class Geometry

java.lang.Object

com.mapzen.tangram.geometry.Geometry

Direct Known Subclasses:

Point, Polygon, Polyline

public abstract class Geometry
extends java.lang.Object

Geometry is an abstract container of LngLat points and associated properties.

Field Summary

Fields

Modifier and Type
Field and Description

protected double[]
coordinates

protected java.lang.String[]
properties

protected int[]
rings

Constructor Summary

Constructors

Constructor and Description

Geometry()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

double[]
getCoordinateArray()

java.lang.String[]
getPropertyArray()

int[]
getRingArray()

protected java.lang.String[]
getStringMapAsArray(java.util.Map<java.lang.String,java.lang.String> properties)

Methods inherited from class java.lang.Object

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

Field Detail

coordinates

protected double[] coordinates

rings

protected int[] rings

properties

protected java.lang.String[] properties

Constructor Detail

Geometry

public Geometry()

Method Detail

getCoordinateArray

public double[] getCoordinateArray()

getRingArray

public int[] getRingArray()

getPropertyArray

public java.lang.String[] getPropertyArray()

getStringMapAsArray

protected java.lang.String[] getStringMapAsArray(java.util.Map<java.lang.String,java.lang.String> properties)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Withings.NET.Models
{
  public class Measuregrp
  {
    public int attrib { get; set; }
    public int category { get; set; }
    public string date { get; set; }
    public string grpid { get; set; }
    public IList<WithingsMeasure> measures { get; set; }
  }
}


text:
Please visit https://github.com/laravel/homestead/releases for details about each release.

Official documentation [is located here](http://laravel.com/docs/homestead).


text:
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path"
	"regexp"
	"time"

	consul_api "github.com/hashicorp/consul/api"
	"github.com/samuel/go-zookeeper/zk"
	client "go.etcd.io/etcd/client/v2"
	"go.etcd.io/etcd/pkg/transport"
)

var lastFoundClusterMembers = make(map[string][]PatroniClusterMember) // needed for cases where DCS is temporarily down
// don't want to immediately remove monitoring of DBs

func ParseHostAndPortFromJdbcConnStr(connStr string) (string, string, error) {
	r := regexp.MustCompile(`postgres://(.*)+:([0-9]+)/`)
	matches := r.FindStringSubmatch(connStr)
	if len(matches) != 3 {
		log.Errorf("Unexpected regex result groups:", matches)
		return "", "", fmt.Errorf("unexpected regex result groups: %v", matches)
	}
	return matches[1], matches[2], nil
}

func ConsulGetClusterMembers(database MonitoredDatabase) ([]PatroniClusterMember, error) {
	var ret []PatroniClusterMember

	if len(database.HostConfig.DcsEndpoints) == 0 {
		return ret, errors.New("Missing Consul connect info, make sure host config has a 'dcs_endpoints' key")
	}

	config := consul_api.Config{}
	config.Address = database.HostConfig.DcsEndpoints[0]
	if config.Address[0] == '/' { // Consul doesn't have leading slashes
		config.Address = config.Address[1 : len(config.Address)-1]
	}
	client, err := consul_api.NewClient(&config)
	if err != nil {
		log.Error("Could not connect to Consul", err)
		return ret, err
	}

	kv := client.KV()

	membersPath := path.Join(database.HostConfig.Namespace, database.HostConfig.Scope, "members")
	members, _, err := kv.List(membersPath, nil)
	if err != nil {
		log.Error("Could not read Patroni members from Consul:", err)
		return ret, err
	}
	for _, member := range members {
		name := path.Base(member.Key)
		log.Debugf("Found a cluster member from Consul: %+v", name)
		nodeData, err := jsonTextToStringMap(string(member.Value))
		if err != nil {
			log.Errorf("Could not parse Consul node data for node \"%s\": %s", name, err)
			continue
		}
		role := nodeData["role"]
		connUrl := nodeData["conn_url"]

		ret = append(ret, PatroniClusterMember{Scope: database.HostConfig.Scope, ConnUrl: connUrl, Role: role, Name: name})
	}

	return ret, nil
}

func EtcdGetClusterMembers(database MonitoredDatabase) ([]PatroniClusterMember, error) {
	var ret = make([]PatroniClusterMember, 0)
	var cfg client.Config
	var CAFile = database.HostConfig.CAFile
	var CertFile = database.HostConfig.CertFile
	var KeyFile = database.HostConfig.KeyFile

	if len(database.HostConfig.DcsEndpoints) == 0 {
		return ret, errors.New("Missing ETCD connect info, make sure host config has a 'dcs_endpoints' key")
	}

	if database.HostConfig.CAFile != "" || database.HostConfig.KeyFile != "" || database.HostConfig.CertFile != "" {
		if database.HostConfig.CAFile != "" {
			if _, err := os.Stat(database.HostConfig.CAFile); os.IsNotExist(err) {
				log.Warningf("Configured CAFile for Patroni cluster '%s' not found, ignoring the file: %s", database.DBUniqueName, database.HostConfig.CAFile)
				CAFile = ""
			}
		}
		if database.HostConfig.CertFile != "" {
			if _, err := os.Stat(database.HostConfig.CertFile); os.IsNotExist(err) {
				log.Warningf("Configured CertFile for Patroni cluster '%s' not found, ignoring the file: %s", database.DBUniqueName, database.HostConfig.CertFile)
				CertFile = ""
			}
		}
		if database.HostConfig.KeyFile != "" {
			if _, err := os.Stat(database.HostConfig.KeyFile); os.IsNotExist(err) {
				log.Warningf("Configured KeyFile for Patroni cluster '%s' not found, ignoring the file: %s", database.DBUniqueName, database.HostConfig.KeyFile)
				KeyFile = ""
			}
		}
		tls := transport.TLSInfo{
			TrustedCAFile: CAFile,
			CertFile:      CertFile,
			KeyFile:       KeyFile,
		}
		//log.Debugf("Setting ETCD TLS config for %s: %+v", database.DBUniqueName, tls)
		dialTimeout := 10 * time.Second
		etcdTransport, _ := transport.NewTransport(tls, dialTimeout)
		cfg = client.Config{
			Endpoints:               database.HostConfig.DcsEndpoints,
			Transport:               etcdTransport,
			HeaderTimeoutPerRequest: time.Second,
			Username:                database.HostConfig.Username,
			Password:                database.HostConfig.Password,
		}
	} else {
		cfg = client.Config{
			Endpoints:               database.HostConfig.DcsEndpoints,
			Transport:               client.DefaultTransport,
			HeaderTimeoutPerRequest: time.Second,
			Username:                database.HostConfig.Username,
			Password:                database.HostConfig.Password,
		}
	}

	c, err := client.New(cfg)
	if err != nil {
		log.Errorf("[%s ]Could not connect to ETCD: %v", database.DBUniqueName, err)
		return ret, err
	}
	kapi := client.NewKeysAPI(c)

	if database.DBType == DBTYPE_PATRONI_NAMESPACE_DISCOVERY { // all scopes, all DBs (regex filtering applies if defined)
		if len(database.DBName) > 0 {
			log.Errorf("Skipping Patroni entry %s - cannot specify a DB name when monitoring all scopes (regex patterns are supported though)", database.DBUniqueName)
			return ret, errors.New(fmt.Sprintf("Skipping Patroni entry %s - cannot specify a DB name when monitoring all scopes (regex patterns are supported though)", database.DBUniqueName))
		}
		if database.HostConfig.Namespace == "" {
			log.Errorf("Skipping Patroni entry %s - search 'namespace' not specified", database.DBUniqueName)
			return ret, errors.New(fmt.Sprintf("Skipping Patroni entry %s - search 'namespace' not specified", database.DBUniqueName))
		}
		log.Errorf("Scanning ETCD namespace %s for clusters to track...", database.HostConfig.Namespace)
		resp, err := kapi.Get(context.Background(), database.HostConfig.Namespace, &client.GetOptions{Recursive: true})
		if err != nil {
			log.Error("Could not read Patroni scopes from ETCD:", err)
			return ret, err
		}

		for _, node := range resp.Node.Nodes {
			log.Errorf("[%s] Patroni namespace discovery - found a scope from etcd: %+v", database.DBUniqueName, node.Key)
			scope := path.Base(node.Key) // Key="/service/batman"
			scopeMembers, err := extractEtcdScopeMembers(database, scope, kapi, true)
			if err != nil {
				continue
			}
			for _, sm := range scopeMembers {
				ret = append(ret, sm)
			}
		}
	} else {
		ret, err = extractEtcdScopeMembers(database, database.HostConfig.Scope, kapi, false)
		if err != nil {
			return ret, err
		}
	}
	lastFoundClusterMembers[database.DBUniqueName] = ret
	return ret, nil
}

func extractEtcdScopeMembers(database MonitoredDatabase, scope string, kapi client.KeysAPI, addScopeToName bool) ([]PatroniClusterMember, error) {
	var ret = make([]PatroniClusterMember, 0)
	var name string
	membersPath := path.Join(database.HostConfig.Namespace, scope, "members")

	resp, err := kapi.Get(context.Background(), membersPath, &client.GetOptions{Recursive: true})
	if err != nil {
		log.Errorf("Could not read Patroni members from ETCD for %s scope %s: %v", database.DBUniqueName, scope, err)
		return nil, err
	}
	log.Debugf("ETCD response for %s scope %s: %+v", database.DBUniqueName, scope, resp)

	for _, node := range resp.Node.Nodes {
		log.Debugf("Found a cluster member from etcd [%s:%s]: %+v", database.DBUniqueName, scope, node.Value)
		nodeData, err := jsonTextToStringMap(node.Value)
		if err != nil {
			log.Errorf("Could not parse ETCD node data for node \"%s\": %s", node, err)
			continue
		}
		role := nodeData["role"]
		connUrl := nodeData["conn_url"]
		if addScopeToName {
			name = scope + "_" + path.Base(node.Key)
		} else {
			name = path.Base(node.Key)
		}

		ret = append(ret, PatroniClusterMember{Scope: scope, ConnUrl: connUrl, Role: role, Name: name})
	}
	return ret, nil
}

func ZookeeperGetClusterMembers(database MonitoredDatabase) ([]PatroniClusterMember, error) {
	var ret []PatroniClusterMember

	if len(database.HostConfig.DcsEndpoints) == 0 {
		return ret, errors.New("Missing Zookeeper connect info, make sure host config has a 'dcs_endpoints' key")
	}

	c, _, err := zk.Connect(database.HostConfig.DcsEndpoints, time.Second, zk.WithLogInfo(false))
	if err != nil {
		log.Error("Could not connect to Zookeeper", err)
		return ret, err
	}
	defer c.Close()

	members, _, err := c.Children(path.Join(database.HostConfig.Namespace, database.HostConfig.Scope, "members"))
	if err != nil {
		log.Error("Could not read Patroni members from Zookeeper:", err)
		return ret, err
	}

	for _, member := range members {
		log.Debugf("Found a cluster member from Zookeeper: %+v", member)
		keyData, _, err := c.Get(path.Join(database.HostConfig.Namespace, database.HostConfig.Scope, "members", member))
		if err != nil {
			log.Errorf("Could not read member (%s) info from Zookeeper:", member, err)
			continue
		}
		nodeData, err := jsonTextToStringMap(string(keyData))
		if err != nil {
			log.Errorf("Could not parse Zookeeper node data for node \"%s\": %s", member, err)
			continue
		}
		role := nodeData["role"]
		connUrl := nodeData["conn_url"]
		name := path.Base(member)

		ret = append(ret, PatroniClusterMember{Scope: database.HostConfig.Scope, ConnUrl: connUrl, Role: role, Name: name})
	}

	return ret, nil
}

func ResolveDatabasesFromPatroni(ce MonitoredDatabase) ([]MonitoredDatabase, error) {
	md := make([]MonitoredDatabase, 0)
	cm := make([]PatroniClusterMember, 0)
	var err error
	var ok bool
	var dbUnique string

	if ce.DBType == DBTYPE_PATRONI_NAMESPACE_DISCOVERY && ce.HostConfig.DcsType != DCS_TYPE_ETCD {
		log.Warningf("Skipping Patroni monitoring entry \"%s\" as currently only ETCD namespace scanning is supported...", ce.DBUniqueName)
		return md, nil
	}
	log.Debugf("Resolving Patroni nodes for \"%s\" from HostConfig: %+v", ce.DBUniqueName, ce.HostConfig)
	if ce.HostConfig.DcsType == DCS_TYPE_ETCD {
		cm, err = EtcdGetClusterMembers(ce)
	} else if ce.HostConfig.DcsType == DCS_TYPE_ZOOKEEPER {
		cm, err = ZookeeperGetClusterMembers(ce)
	} else if ce.HostConfig.DcsType == DCS_TYPE_CONSUL {
		cm, err = ConsulGetClusterMembers(ce)
	} else {
		log.Error("unknown DCS", ce.HostConfig.DcsType)
		return md, errors.New("unknown DCS")
	}
	if err != nil {
		log.Warningf("Failed to get info from DCS for %s, using previous member info if any", ce.DBUniqueName)
		cm, ok = lastFoundClusterMembers[ce.DBUniqueName]
		if ok { // mask error from main loop not to remove monitored DBs due to "jitter"
			err = nil
		}
	} else {
		lastFoundClusterMembers[ce.DBUniqueName] = cm
	}
	if len(cm) == 0 {
		log.Warningf("No Patroni cluster members found for cluster [%s:%s]", ce.DBUniqueName, ce.HostConfig.Scope)
		return md, nil
	}
	log.Infof("Found %d Patroni members for entry %s", len(cm), ce.DBUniqueName)

	for _, m := range cm {
		log.Infof("Processing Patroni cluster member [%s:%s]", ce.DBUniqueName, m.Name)
		if ce.OnlyIfMaster && m.Role != "master" {
			log.Infof("Skipping over Patroni cluster member [%s:%s] as not a master", ce.DBUniqueName, m.Name)
			continue
		}
		host, port, err := ParseHostAndPortFromJdbcConnStr(m.ConnUrl)
		if err != nil {
			log.Errorf("Could not parse Patroni conn str \"%s\" [%s:%s]: %v", m.ConnUrl, ce.DBUniqueName, m.Scope, err)
			continue
		}
		if ce.OnlyIfMaster {
			dbUnique = ce.DBUniqueName
			if ce.DBType == DBTYPE_PATRONI_NAMESPACE_DISCOVERY {
				dbUnique = ce.DBUniqueName + "_" + m.Scope
			}
		} else {
			dbUnique = ce.DBUniqueName + "_" + m.Name
		}
		if ce.DBName != "" {
			md = append(md, MonitoredDatabase{
				DBUniqueName:      dbUnique,
				DBUniqueNameOrig:  ce.DBUniqueName,
				DBName:            ce.DBName,
				Host:              host,
				Port:              port,
				User:              ce.User,
				Password:          ce.Password,
				PasswordType:      ce.PasswordType,
				SslMode:           ce.SslMode,
				SslRootCAPath:     ce.SslRootCAPath,
				SslClientCertPath: ce.SslClientCertPath,
				SslClientKeyPath:  ce.SslClientKeyPath,
				StmtTimeout:       ce.StmtTimeout,
				Metrics:           ce.Metrics,
				PresetMetrics:     ce.PresetMetrics,
				IsSuperuser:       ce.IsSuperuser,
				CustomTags:        ce.CustomTags,
				HostConfig:        ce.HostConfig,
				DBType:            "postgres"})
			continue
		} else {
			c, err := GetPostgresDBConnection("", host, port, "template1", ce.User, ce.Password,
				ce.SslMode, ce.SslRootCAPath, ce.SslClientCertPath, ce.SslClientKeyPath)
			if err != nil {
				log.Errorf("Could not contact Patroni member [%s:%s]: %v", ce.DBUniqueName, m.Scope, err)
				continue
			}
			defer c.Close()
			sql := `select datname::text as datname,
					quote_ident(datname)::text as datname_escaped
					from pg_database
					where not datistemplate
					and datallowconn
					and has_database_privilege (datname, 'CONNECT')
					and case when length(trim($1)) > 0 then datname ~ $2 else true end
					and case when length(trim($3)) > 0 then not datname ~ $4 else true end`

			data, err := DBExecRead(c, ce.DBUniqueName, sql, ce.DBNameIncludePattern, ce.DBNameIncludePattern, ce.DBNameExcludePattern, ce.DBNameExcludePattern)
			if err != nil {
				log.Errorf("Could not get DB name listing from Patroni member [%s:%s]: %v", ce.DBUniqueName, m.Scope, err)
				continue
			}

			for _, d := range data {
				md = append(md, MonitoredDatabase{
					DBUniqueName:      dbUnique + "_" + d["datname_escaped"].(string),
					DBUniqueNameOrig:  dbUnique,
					DBName:            d["datname"].(string),
					Host:              host,
					Port:              port,
					User:              ce.User,
					Password:          ce.Password,
					PasswordType:      ce.PasswordType,
					SslMode:           ce.SslMode,
					SslRootCAPath:     ce.SslRootCAPath,
					SslClientCertPath: ce.SslClientCertPath,
					SslClientKeyPath:  ce.SslClientKeyPath,
					StmtTimeout:       ce.StmtTimeout,
					Metrics:           ce.Metrics,
					PresetMetrics:     ce.PresetMetrics,
					IsSuperuser:       ce.IsSuperuser,
					CustomTags:        ce.CustomTags,
					HostConfig:        ce.HostConfig,
					DBType:            "postgres"})
			}
		}

	}

	return md, err
}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.impl.analysis;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.java.stubs.index.JavaModuleNameIndex;
import com.intellij.psi.impl.light.LightJavaModule;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.util.CachedValueProvider.Result;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.graph.DFSTBuilder;
import com.intellij.util.graph.Graph;
import com.intellij.util.graph.GraphGenerator;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.java.JavaSourceRootType;

import java.util.*;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JavaModuleGraphUtil {
  private JavaModuleGraphUtil() { }

  @Nullable
  public static PsiJavaModule findDescriptorByElement(@Nullable PsiElement element) {
    if (element != null) {
      PsiFileSystemItem fsItem = element instanceof PsiFileSystemItem ? (PsiFileSystemItem)element : element.getContainingFile();
      if (fsItem != null) {
        return findDescriptorByFile(fsItem.getVirtualFile(), fsItem.getProject());
      }
    }

    return null;
  }

  @Nullable
  public static PsiJavaModule findDescriptorByFile(@Nullable VirtualFile file, @NotNull Project project) {
    if (file == null) return null;

    ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(project);
    if (index.isInLibrary(file)) {
      VirtualFile root = index.getClassRootForFile(file);
      if (root != null) {
        VirtualFile descriptorFile = JavaModuleNameIndex.descriptorFile(root);
        if (descriptorFile != null) {
          PsiFile psiFile = PsiManager.getInstance(project).findFile(descriptorFile);
          if (psiFile instanceof PsiJavaFile) {
            return ((PsiJavaFile)psiFile).getModuleDeclaration();
          }
        }
        else if (root.getFileSystem() instanceof JarFileSystem && "jar".equalsIgnoreCase(root.getExtension())) {
          return LightJavaModule.getModule(PsiManager.getInstance(project), root);
        }
      }
    }
    else {
      return findDescriptorByModule(index.getModuleForFile(file), index.isInTestSourceContent(file));
    }

    return null;
  }

  @Nullable
  public static PsiJavaModule findDescriptorByModule(@Nullable Module module, boolean inTests) {
    if (module != null) {
      JavaSourceRootType rootType = inTests ? JavaSourceRootType.TEST_SOURCE : JavaSourceRootType.SOURCE;
      List<VirtualFile> files = ModuleRootManager.getInstance(module).getSourceRoots(rootType).stream()
        .map(root -> root.findChild(PsiJavaModule.MODULE_INFO_FILE))
        .filter(Objects::nonNull)
        .collect(Collectors.toList());
      if (files.size() == 1) {
        PsiFile psiFile = PsiManager.getInstance(module.getProject()).findFile(files.get(0));
        if (psiFile instanceof PsiJavaFile) {
          return ((PsiJavaFile)psiFile).getModuleDeclaration();
        }
      }
    }

    return null;
  }

  @Nullable
  public static Collection<PsiJavaModule> findCycle(@NotNull PsiJavaModule module) {
    Project project = module.getProject();
    List<Set<PsiJavaModule>> cycles = CachedValuesManager.getManager(project).getCachedValue(project, () ->
      Result.create(findCycles(project), cacheDependency()));
    return ContainerUtil.find(cycles, set -> set.contains(module));
  }

  public static boolean exports(@NotNull PsiJavaModule source, @NotNull String packageName, @Nullable PsiJavaModule target) {
    Map<String, Set<String>> exports = CachedValuesManager.getCachedValue(source, () ->
      Result.create(exportsMap(source), source.getContainingFile()));
    Set<String> targets = exports.get(packageName);
    return targets != null && (targets.isEmpty() || target != null && targets.contains(target.getName()));
  }

  public static boolean reads(@NotNull PsiJavaModule source, @NotNull PsiJavaModule destination) {
    return getRequiresGraph(source).reads(source, destination);
  }

  @Nullable
  public static Trinity<String, PsiJavaModule, PsiJavaModule> findConflict(@NotNull PsiJavaModule module) {
    return getRequiresGraph(module).findConflict(module);
  }

  @Nullable
  public static PsiJavaModule findOrigin(@NotNull PsiJavaModule module, @NotNull String packageName) {
    return getRequiresGraph(module).findOrigin(module, packageName);
  }

  @SuppressWarnings("deprecation")
  private static Object cacheDependency() {
    return PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT;
  }

  /*
   * Looks for cycles between Java modules in the project sources.
   * Library/JDK modules are excluded - in assumption there can't be any lib -> src dependencies.
   * Module references are resolved "globally" (i.e., without taking project dependencies into account).
   */
  private static List<Set<PsiJavaModule>> findCycles(Project project) {
    Set<PsiJavaModule> projectModules = ContainerUtil.newHashSet();
    for (Module module : ModuleManager.getInstance(project).getModules()) {
      List<PsiJavaModule> descriptors = Stream.of(ModuleRootManager.getInstance(module).getSourceRoots(true))
        .map(root -> findDescriptorByFile(root, project))
        .filter(Objects::nonNull)
        .collect(Collectors.toList());
      if (descriptors.size() > 1) return Collections.emptyList();  // aborts the process when there are incorrect modules in the project
      if (descriptors.size() == 1) projectModules.add(descriptors.get(0));
    }

    if (!projectModules.isEmpty()) {
      MultiMap<PsiJavaModule, PsiJavaModule> relations = MultiMap.create();
      for (PsiJavaModule module : projectModules) {
        for (PsiRequiresStatement statement : module.getRequires()) {
          PsiJavaModuleReference ref = statement.getModuleReference();
          if (ref != null) {
            ResolveResult[] results = ref.multiResolve(true);
            if (results.length == 1) {
              PsiJavaModule dependency = (PsiJavaModule)results[0].getElement();
              if (dependency != null && projectModules.contains(dependency)) {
                relations.putValue(module, dependency);
              }
            }
          }
        }
      }

      if (!relations.isEmpty()) {
        Graph<PsiJavaModule> graph = new ChameleonGraph<>(relations, false);
        DFSTBuilder<PsiJavaModule> builder = new DFSTBuilder<>(graph);
        Collection<Collection<PsiJavaModule>> components = builder.getComponents();
        if (!components.isEmpty()) {
          return ContainerUtil.map(components, ContainerUtil::newLinkedHashSet);
        }
      }
    }

    return Collections.emptyList();
  }

  private static Map<String, Set<String>> exportsMap(@NotNull PsiJavaModule source) {
    Map<String, Set<String>> map = ContainerUtil.newHashMap();
    for (PsiPackageAccessibilityStatement statement : source.getExports()) {
      String pkg = statement.getPackageName();
      List<String> targets = statement.getModuleNames();
      map.put(pkg, targets.isEmpty() ? Collections.emptySet() : ContainerUtil.newTroveSet(targets));
    }
    return map;
  }

  private static RequiresGraph getRequiresGraph(PsiJavaModule module) {
    Project project = module.getProject();
    return CachedValuesManager.getManager(project).getCachedValue(project, () ->
      Result.create(buildRequiresGraph(project), cacheDependency()));
  }

  /*
   * Collects all module dependencies in the project.
   * The resulting graph is used for tracing readability and checking package conflicts.
   */
  private static RequiresGraph buildRequiresGraph(Project project) {
    MultiMap<PsiJavaModule, PsiJavaModule> relations = MultiMap.create();
    Set<String> transitiveEdges = ContainerUtil.newTroveSet();

    JavaModuleNameIndex index = JavaModuleNameIndex.getInstance();
    GlobalSearchScope scope = ProjectScope.getAllScope(project);
    for (String key : index.getAllKeys(project)) {
      for (PsiJavaModule module : index.get(key, project, scope)) {
        visit(module, relations, transitiveEdges);
      }
    }

    Graph<PsiJavaModule> graph = GraphGenerator.generate(new ChameleonGraph<>(relations, true));
    return new RequiresGraph(graph, transitiveEdges);
  }

  private static void visit(PsiJavaModule module, MultiMap<PsiJavaModule, PsiJavaModule> relations, Set<? super String> transitiveEdges) {
    if (!(module instanceof LightJavaModule) && !relations.containsKey(module)) {
      relations.putValues(module, Collections.emptyList());
      boolean explicitJavaBase = false;
      for (PsiRequiresStatement statement : module.getRequires()) {
        PsiJavaModuleReference ref = statement.getModuleReference();
        if (ref != null) {
          if (PsiJavaModule.JAVA_BASE.equals(ref.getCanonicalText())) explicitJavaBase = true;
          for (ResolveResult result : ref.multiResolve(false)) {
            PsiJavaModule dependency = (PsiJavaModule)result.getElement();
            assert dependency != null : result;
            relations.putValue(module, dependency);
            if (statement.hasModifierProperty(PsiModifier.TRANSITIVE)) transitiveEdges.add(RequiresGraph.key(dependency, module));
            visit(dependency, relations, transitiveEdges);
          }
        }
      }
      if (!explicitJavaBase) {
        PsiJavaModule javaBase = JavaPsiFacade.getInstance(module.getProject()).findModule(PsiJavaModule.JAVA_BASE, module.getResolveScope());
        if (javaBase != null) relations.putValue(module, javaBase);
      }
    }
  }

  private static class RequiresGraph {
    private final Graph<PsiJavaModule> myGraph;
    private final Set<String> myTransitiveEdges;

    private RequiresGraph(Graph<PsiJavaModule> graph, Set<String> transitiveEdges) {
      myGraph = graph;
      myTransitiveEdges = transitiveEdges;
    }

    public boolean reads(PsiJavaModule source, PsiJavaModule destination) {
      Collection<PsiJavaModule> nodes = myGraph.getNodes();
      if (nodes.contains(destination) && nodes.contains(source)) {
        Iterator<PsiJavaModule> directReaders = myGraph.getOut(destination);
        while (directReaders.hasNext()) {
          PsiJavaModule next = directReaders.next();
          if (source.equals(next) || myTransitiveEdges.contains(key(destination, next)) && reads(source, next)) {
            return true;
          }
        }
      }
      return false;
    }

    public Trinity<String, PsiJavaModule, PsiJavaModule> findConflict(PsiJavaModule source) {
      Map<String, PsiJavaModule> exports = ContainerUtil.newHashMap();
      return processExports(source, (pkg, m) -> {
        PsiJavaModule existing = exports.put(pkg, m);
        return existing != null ? new Trinity<>(pkg, existing, m) : null;
      });
    }

    public PsiJavaModule findOrigin(PsiJavaModule module, String packageName) {
      return processExports(module, (pkg, m) -> packageName.equals(pkg) ? m : null);
    }

    private <T> T processExports(PsiJavaModule start, BiFunction<? super String, ? super PsiJavaModule, ? extends T> processor) {
      return myGraph.getNodes().contains(start) ? processExports(start.getName(), start, 0, ContainerUtil.newHashSet(), processor) : null;
    }

    private <T> T processExports(String name,
                                 PsiJavaModule module,
                                 int layer,
                                 Set<? super PsiJavaModule> visited,
                                 BiFunction<? super String, ? super PsiJavaModule, ? extends T> processor) {
      if (visited.add(module)) {
        if (layer == 1) {
          for (PsiPackageAccessibilityStatement statement : module.getExports()) {
            List<String> exportTargets = statement.getModuleNames();
            if (exportTargets.isEmpty() || exportTargets.contains(name)) {
              T result = processor.apply(statement.getPackageName(), module);
              if (result != null) return result;
            }
          }
        }
        if (layer < 2) {
          Iterator<PsiJavaModule> iterator = myGraph.getIn(module);
          while (iterator.hasNext()) {
            PsiJavaModule dependency = iterator.next();
            if (layer == 0 || myTransitiveEdges.contains(key(dependency, module))) {
              T result = processExports(name, dependency, 1, visited, processor);
              if (result != null) return result;
            }
          }
        }
      }

      return null;
    }

    public static String key(PsiJavaModule module, PsiJavaModule exporter) {
      return module.getName() + '/' + exporter.getName();
    }
  }

  private static class ChameleonGraph<N> implements Graph<N> {
    private final Set<N> myNodes;
    private final MultiMap<N, N> myEdges;
    private final boolean myInbound;

    private ChameleonGraph(MultiMap<N, N> edges, boolean inbound) {
      myNodes = new THashSet<>();
      edges.entrySet().forEach(e -> {
        myNodes.add(e.getKey());
        myNodes.addAll(e.getValue());
      });
      myEdges = edges;
      myInbound = inbound;
    }

    @NotNull
    @Override
    public Collection<N> getNodes() {
      return myNodes;
    }

    @NotNull
    @Override
    public Iterator<N> getIn(N n) {
      return myInbound ? myEdges.get(n).iterator() : Collections.emptyIterator();
    }

    @NotNull
    @Override
    public Iterator<N> getOut(N n) {
      return myInbound ? Collections.emptyIterator() : myEdges.get(n).iterator();
    }
  }
}


text:
  <form action="{{ route('replies.store') }}" method="POST" accept-charset="UTF-8">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="hidden" name="topic_id" value="{{ $topic->id }}">

      <textarea class="form-control" rows="3" placeholder="分享你的想法" name="content"></textarea>

    <button type="submit" class="btn btn-primary btn-sm">回复</button>
  </form>


text:
package com.intellij.unscramble;

import com.intellij.Patches;
import com.intellij.openapi.application.ApplicationActivationListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.util.Alarm;

import java.util.regex.Pattern;

/**
 * @author Konstantin Bulenkov
 */
public class UnscrambleListener extends ApplicationActivationListener.Adapter {
  private static final int MAX_STACKTRACE_SIZE = 100 * 1024;
  private String stacktrace = null;

  @Override
  public void applicationActivated(final IdeFrame ideFrame) {
    final Runnable processClipboard = new Runnable() {
      @Override
      public void run() {
        final String clipboard = AnalyzeStacktraceUtil.getTextInClipboard();
        if (clipboard != null && clipboard.length() < MAX_STACKTRACE_SIZE && !clipboard.equals(stacktrace)) {
          stacktrace = clipboard;
          final Project project = ideFrame.getProject();
          if (project != null && isStacktrace(stacktrace)) {
            final UnscrambleDialog dialog = new UnscrambleDialog(project);
            dialog.createNormalizeTextAction().actionPerformed(null);
            dialog.doOKAction();
          }
        }
      }
    };

    if (Patches.SLOW_GETTING_CLIPBOARD_CONTENTS) {
      //IDEA's clipboard is synchronized with the system clipboard on frame activation so we need to postpone clipboard processing
      new Alarm().addRequest(processClipboard, 300);
    }
    else {
      processClipboard.run();
    }
  }

  @Override
  public void applicationDeactivated(IdeFrame ideFrame) {
    if (SystemInfo.isMac) return;

    stacktrace = AnalyzeStacktraceUtil.getTextInClipboard();
  }

  private static final Pattern STACKTRACE_LINE =
    Pattern.compile("[\t]*at [[_a-zA-Z0-9]+\\.]+[_a-zA-Z$0-9]+\\.[a-zA-Z0-9_]+\\([A-Za-z0-9_]+\\.java:[\\d]+\\)+[ [~]*\\[[a-zA-Z0-9\\.\\:/]\\]]*");

  public static boolean isStacktrace(String stacktrace) {
    stacktrace = UnscrambleDialog.normalizeText(stacktrace);
    int linesCount = 0;
    for (String line : stacktrace.split("\n")) {
      line = line.trim();
      if (line.length() == 0) continue;
      if (line.endsWith("\r")) {
        line = line.substring(0, line.length() - 1);
      }
      if (STACKTRACE_LINE.matcher(line).matches()) {
        linesCount++;
      }
      else {
        linesCount = 0;
      }
      if (linesCount > 2) return true;
    }
    return false;
  }
}


text:
<?php
spl_autoload_register(function($class) {
    // does the class use the namespace prefix?
    $namespace = 'Resonantcore\\Lib\\';
    $base_dir = __DIR__.'/src/';

    $len = strlen($namespace);
    if (strncmp($namespace, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});


text:
package com.github.dynamo.magazines.tasks;

import com.github.dynamo.magazines.model.MagazineIssue;
import com.github.dynamo.model.backlog.core.FindDownloadableTask;

public class FindMagazineIssueTask extends FindDownloadableTask<MagazineIssue> {

	public FindMagazineIssueTask(MagazineIssue issue) {
		super(issue);
	}

	@Override
	public String toString() {
		return String.format("Searching for Magazine issue : %s", downloadable.toString());
	}

}


text:
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/0.11.4/angular-material.css">
	<base href="/">
</head>
<body ng-app="newEmpTraining">
	<div ng-view></div>
	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-resource.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/0.11.4/angular-material.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-animate.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-aria.min.js"></script>
	<script type="text/javascript" src="./assets/js/app.js"></script>
	<script type="text/javascript" src="./assets/js/route.js"></script>
	<script type="text/javascript" src="./assets/js/services.js"></script>
	<script type="text/javascript" src="./assets/js/controller.js"></script>

</body>
</html>


text:
"""
Base settings for Sigma Pi, Gamma Iota chapter website.
"""

import os

BASE_DIR = os.getcwd()

EC_EMAIL = "gr-sigmapi@wpi.edu"
ACTIVES_EMAIL = "sigmapiactives@wpi.edu"
ALUMNI_EMAIL = "sigmapialumni@wpi.edu"

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = "America/New_York"

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en-us"

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = "/content/"

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = "/static/"

STATICFILES_FINDERS = (
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "sass_processor.finders.CssFinder",
)

STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"

LOGIN_URL = "/login/"
LOGIN_REDIRECT_URL = "/secure/"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "apps.PubSite.processors.menu_items",
            ],
        },
    }
]

MIDDLEWARE = (
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
)

X_FRAME_OPTIONS = "SAMEORIGIN"

DOWNLOADVIEW_RULES = [
    {
        "destination_dir": "lightpd-optimized-by-middleware",
    },
]

ROOT_URLCONF = "common.urls"

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = "common.wsgi.application"

PREREQ_APPS = (
    "django",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.admin",
    "sass_processor",
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)
PROJECT_APPS = (
    "common",
    "apps.PubSite",
    "apps.UserInfo",
    "apps.Archive",
    "apps.PartyList",
    "apps.PartyListV2",
    "apps.Secure",
    "apps.Links",
    "apps.Standards",
    "apps.Scholarship",
    "apps.Slack",
)
INSTALLED_APPS = PREREQ_APPS + PROJECT_APPS

SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer"

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
    "handlers": {
        "mail_admins": {
            "level": "ERROR",
            "filters": ["require_debug_false"],
            "class": "django.utils.log.AdminEmailHandler",
        }
    },
    "loggers": {
        "django.request": {
            "handlers": ["mail_admins"],
            "level": "ERROR",
            "propagate": True,
        },
    },
}

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"

SASS_PROCESSOR_AUTO_INCLUDE = False
SASS_PRECISION = 8

PUBLIC_PAGES = [
    {"title": "Home", "view": "pub-index"},
    {"title": "About", "view": "pub-about"},
    {"title": "Service & Activities", "view": "pub-service"},
    # {"title": "Campaign", "view": "pub-campaign"},
    {"title": "Rush Sigma Pi", "view": "pub-rush"},
    {"title": "Brothers", "view": "userinfo-users"},
    {
        "title": "Donate",
        "target": "_blank",
        "url": ("https://paypal.me/sigmapigammaiota?locale.x=en_US"),
    },  # reasons why I hate python, this single string looks like three
    # This is hard-coded into login.scss
    {"title": "Log In", "view": "pub-login"},
]


text:
'use strict';

var core = require('ses-core');
var dirs = require('../../../config/directories');
var path = require('path');

var asideCtx = require('../contexts/aside');

module.exports = function (app, express) {
  app.get('/feature/see', function (req, res, next) {
    var context = {
      title :  'see-eat-sleep',
      aside :  asideCtx,
      see: { },
      eat: { clazz: 'ses-hidden' },
      sleep: { clazz: 'ses-hidden' }
    };

    core.renderView(path.join(dirs.templates, 'index.hbs'), context, function (err, html) {
      if (err) return next(err);
      res.send(html);
    });
  });
};


text:
"""
    The actual implementation of the SQLAlchemy data layer.

    :copyright: (c) 2013 by Andrew Mleczko and Tomasz Jezierski (Tefnet)
    :license: BSD, see LICENSE for more details.
"""

__version__ = '0.1-dev'

import simplejson as json
import flask.ext.sqlalchemy as flask_sqlalchemy

from flask import abort
from copy import copy

from eve.io.base import ConnectionException
from eve.io.base import DataLayer
from eve.utils import config, debug_error_message, str_to_date
from .parser import parse, parse_dictionary, ParseError, sqla_op, parse_sorting
from .structures import SQLAResultCollection
from .utils import dict_update, validate_filters, sqla_object_to_dict, extract_sort_arg

db = flask_sqlalchemy.SQLAlchemy()

try:
    string_type = basestring
except NameError:
    # Python 3
    string_type = str

class SQL(DataLayer):
    """
    SQLAlchemy data access layer for Eve REST API.
    """
    driver = db
    serializers = {'datetime': str_to_date}

    def init_app(self, app):
        try:
            # FIXME: dumb double initialisation of the
            # driver because Eve sets it to None in __init__
            self.driver = db
            self.driver.app = app
            self.driver.init_app(app)
        except Exception as e:
            raise ConnectionException(e)

        self.register_schema(app)

    @classmethod
    def lookup_model(cls, model_name):
        """
        Lookup SQLAlchemy model class by its name

        :param model_name: Name of SQLAlchemy model.
        """
        return cls.driver.Model._decl_class_registry[model_name]

#    @classmethod
    def register_schema(self, app, model_name=None):
        """Register eve schema for SQLAlchemy model(s)
        :param app: Flask application instance.
        :param model_name: Name of SQLAlchemy model
            (register all models if not provided)
        """
        if model_name:
            models = {model_name.capitalize(): self.driver.
                      Model._decl_class_registry[model_name.capitalize()]}
        else:
            models = self.driver.Model._decl_class_registry

        for model_name, model_cls in models.items():
            if model_name.startswith('_'):
                continue
            if getattr(model_cls, '_eve_schema', None):
                eve_schema = model_cls._eve_schema
                dict_update(app.config['DOMAIN'], eve_schema)

        for k, v in app.config['DOMAIN'].items():
            # If a resource has a relation, copy the properties of the relation
            if 'datasource' in v and 'source' in v['datasource']:
                source = v['datasource']['source']
                source = app.config['DOMAIN'].get(source.lower())
                if source:
                    v['schema'] = source['schema']
                    v['item_lookup_field'] = source['item_lookup_field']
                    v['item_url'] = source['item_url']

    def find(self, resource, req, sub_resource_lookup):
        """Retrieves a set of documents matching a given request. Queries can
        be expressed in two different formats: the mongo query syntax, and the
        python syntax. The first kind of query would look like: ::

            ?where={"name": "john doe}

        while the second would look like: ::

            ?where=name=="john doe"

        The resultset if paginated.

        :param resource: resource name.
        :param req: a :class:`ParsedRequest`instance.
        :param sub_resource_lookup: sub-resource lookup from the endpoint url.
        """
        args = {'sort': extract_sort_arg(req),
                'resource': resource}

        client_projection = self._client_projection(req)
        client_embedded = self._client_embedded(req)
        model, args['spec'], fields, args['sort'] = \
            self._datasource_ex(resource, [], client_projection,
                                args['sort'], client_embedded)
        if req.where:
            try:
                args['spec'] = self.combine_queries(args['spec'],
                                                    parse(req.where, model))
            except ParseError:
                try:
                    spec = json.loads(req.where)
                    args['spec'] = \
                        self.combine_queries(args['spec'],
                                             parse_dictionary(spec, model))
                except (AttributeError, TypeError):
                    # if parse failed and json loads fails - raise 400
                    abort(400)

        bad_filter = validate_filters(args['spec'], resource)
        if bad_filter:
            abort(400, bad_filter)

        if sub_resource_lookup:
            args['spec'] = \
                self.combine_queries(args['spec'],
                                     parse_dictionary(sub_resource_lookup,
                                                      model))

        if req.if_modified_since:
            updated_filter = sqla_op.gt(getattr(model, config.LAST_UPDATED),
                                        req.if_modified_since)
            args['spec'].append(updated_filter)

        query = self.driver.session.query(model)

        if args['sort']:
            ql = []
            for sort_item in args['sort']:
                ql.append(parse_sorting(model, query, *sort_item))
            args['sort'] = ql

        if req.max_results:
            args['max_results'] = req.max_results
        if req.page > 1:
            args['page'] = req.page
        return SQLAResultCollection(query, fields, **args)

    def find_one(self, resource, req, **lookup):
        client_projection = self._client_projection(req)
        client_embedded = self._client_embedded(req)
        model, filter_, fields, _ = \
            self._datasource_ex(resource, [], client_projection, None,
                                client_embedded)

        if isinstance(lookup.get(config.ID_FIELD), dict) \
                or isinstance(lookup.get(config.ID_FIELD), list):
            # very dummy way to get the related object
            # that commes from embeddable parameter
            return lookup
        else:
            filter_ = self.combine_queries(filter_,
                                           parse_dictionary(lookup, model))
            query = self.driver.session.query(model)
            document = query.filter(*filter_).first()

        return sqla_object_to_dict(document, fields) if document else None

    def find_one_raw(self, resource, _id):
        raise NotImplementedError

    def find_list_of_ids(self, resource, ids, client_projection=None):
        raise NotImplementedError

    def insert(self, resource, doc_or_docs):
        rv = []
        model, filter_, fields_, _ = self._datasource_ex(resource)
        for document in doc_or_docs:
            model_instance = model(**document)
            self.driver.session.add(model_instance)
            self.driver.session.commit()
            id_field = getattr(model_instance, self.driver.app.config['ID_FIELD'])
            document['_id'] = id_field
            rv.append(id_field)
        return rv

    def replace(self, resource, id_, document, original):
        model, filter_, fields_, _ = self._datasource_ex(resource, [])
        id_field = self.driver.app.config['ID_FIELD']
        filter_ = self.combine_queries(filter_,
                                       parse_dictionary({id_field: id_}, model))
        query = self.driver.session.query(model)

        # Find and delete the old object
        old_model_instance = query.filter(*filter_).first()
        if old_model_instance is None:
            abort(500, description=debug_error_message('Object not existent'))
        self.driver.session.delete(old_model_instance)
        self.driver.session.commit()

        # create and insert the new one
        model_instance = model(**document)
        model_instance._id = id_
        self.driver.session.add(model_instance)
        self.driver.session.commit()

    def update(self, resource, id_, updates, original):
        model, filter_, _, _ = self._datasource_ex(resource, [])
        id_field = self.driver.app.config['ID_FIELD']
        filter_ = self.combine_queries(filter_,
                                       parse_dictionary({id_field: id_}, model))
        query = self.driver.session.query(model)
        model_instance = query.filter(*filter_).first()
        if model_instance is None:
            abort(500, description=debug_error_message('Object not existent'))
        for k, v in updates.items():
            setattr(model_instance, k, v)
        self.driver.session.commit()

    def remove(self, resource, lookup):
        model, filter_, _, _ = self._datasource_ex(resource, [])
        filter_ = self.combine_queries(filter_,
                                       parse_dictionary(lookup, model))
        query = self.driver.session.query(model)
        if len(filter_):
            query = query.filter(*filter_)
        for item in query:
            self.driver.session.delete(item)

        self.driver.session.commit()

    @staticmethod
    def _source(resource):
        return config.SOURCES[resource]['source']

    def _model(self, resource):
        return self.lookup_model(self._source(resource))

    def _parse_filter(self, model, filter):
        """
        Convert from Mongo/JSON style filters to SQLAlchemy expressions.
        """
        if filter is None or len(filter) == 0:
            filter = []
        elif isinstance(filter, string_type):
            filter = parse(filter, model)
        elif isinstance(filter, dict):
            filter = parse_dictionary(filter, model)
        elif not isinstance(filter, list):
            filter = []
        return filter

    def datasource(self, resource):
        """
        Overridden from super to return the actual model class of the database
        table instead of the name of it. We also parse the filter coming from
        the schema definition into a SQL compatible filter
        """
        model = self._model(resource)

        filter_ = config.SOURCES[resource]['filter']
        filter_ = self._parse_filter(model, filter_)
        projection_ = copy(config.SOURCES[resource]['projection'])
        sort_ = copy(config.SOURCES[resource]['default_sort'])
        return model, filter_, projection_, sort_

    # NOTE(Gonéri): preserve the _datasource method for compatibiliy with
    # pre 0.6 Eve release (See: commit 87742343fd0362354b9f75c749651f92d6e4a9c8
    # from the Eve repository)
    def _datasource(self, resource):
        return self.datasource(resource)

    def _datasource_ex(self, resource, query=None, client_projection=None,
                       client_sort=None, client_embedded=None):
        model, filter_, fields_, sort_ = \
            super(SQL, self)._datasource_ex(resource, query, client_projection,
                                            client_sort)
        filter_ = self._parse_filter(model, filter_)
        if client_embedded:
            fields_.update(client_embedded)
        fields = [field for field in fields_.keys() if fields_[field]]
        return model, filter_, fields, sort_

    def combine_queries(self, query_a, query_b):
        # TODO: dumb concatenation of query lists.
        #       We really need to check for duplicate queries
        query_a.extend(query_b)
        return query_a

    def is_empty(self, resource):
        model, filter_, _, _ = self.datasource(resource)
        query = self.driver.session.query(model)
        if len(filter_):
            return query.filter_by(*filter_).count() == 0
        else:
            return query.count() == 0

    def _client_embedded(self, req):
        """ Returns a properly parsed client embeddable if available.

        :param req: a :class:`ParsedRequest` instance.

        .. versionadded:: 0.4
        """
        client_embedded = {}
        if req and req.embedded:
            try:
                client_embedded = json.loads(req.embedded)
            except:
                abort(400, description=debug_error_message(
                    'Unable to parse `embedded` clause'
                ))
        return client_embedded

    def _client_projection(self, req):
        """ Returns a properly parsed client projection if available.

        :param req: a :class:`ParsedRequest` instance.

        .. versionadded:: 0.4
        """
        client_projection = {}
        if req and req.projection:
            try:
                client_projection = json.loads(req.projection)
            except:
                abort(400, description=debug_error_message(
                    'Unable to parse `projection` clause'
                ))
        return client_projection


text:
from google import pubsub_v1

async def sample_list_subscriptions():
    # Create a client
    client = pubsub_v1.SubscriberAsyncClient()

    # Initialize request argument(s)
    request = pubsub_v1.ListSubscriptionsRequest(
        project="project_value",
    )

    # Make the request
    page_result = client.list_subscriptions(request=request)

    # Handle the response
    async for response in page_result:
        print(response)

# [END pubsub_v1_generated_Subscriber_ListSubscriptions_async]


text:
/*
 * Do not modify this file. This file is generated from the codepipeline-2015-07-09.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.CodePipeline.Model
{
    /// <summary>
    /// Container for the parameters to the PutActionRevision operation.
    /// Provides information to AWS CodePipeline about new revisions to a source.
    /// </summary>
    public partial class PutActionRevisionRequest : AmazonCodePipelineRequest
    {
        private string _actionName;
        private ActionRevision _actionRevision;
        private string _pipelineName;
        private string _stageName;

        /// <summary>
        /// Gets and sets the property ActionName.
        /// <para>
        /// The name of the action that will process the revision.
        /// </para>
        /// </summary>
        public string ActionName
        {
            get { return this._actionName; }
            set { this._actionName = value; }
        }

        // Check to see if ActionName property is set
        internal bool IsSetActionName()
        {
            return this._actionName != null;
        }

        /// <summary>
        /// Gets and sets the property ActionRevision.
        /// </summary>
        public ActionRevision ActionRevision
        {
            get { return this._actionRevision; }
            set { this._actionRevision = value; }
        }

        // Check to see if ActionRevision property is set
        internal bool IsSetActionRevision()
        {
            return this._actionRevision != null;
        }

        /// <summary>
        /// Gets and sets the property PipelineName.
        /// <para>
        /// The name of the pipeline that will start processing the revision to the source.
        /// </para>
        /// </summary>
        public string PipelineName
        {
            get { return this._pipelineName; }
            set { this._pipelineName = value; }
        }

        // Check to see if PipelineName property is set
        internal bool IsSetPipelineName()
        {
            return this._pipelineName != null;
        }

        /// <summary>
        /// Gets and sets the property StageName.
        /// <para>
        /// The name of the stage that contains the action that will act upon the revision.
        /// </para>
        /// </summary>
        public string StageName
        {
            get { return this._stageName; }
            set { this._stageName = value; }
        }

        // Check to see if StageName property is set
        internal bool IsSetStageName()
        {
            return this._stageName != null;
        }

    }
}


text:
<?php

namespace Metrique\Meta\Contracts;

interface MetaTagsInterface
{
    /**
     * Return the tags in an array, in html format.
     * @return array
     */
    public function toArray();

    /**
     * Add a new meta tag or set of meta tags.
     *
     * $meta->tags()->add([
     *     ['charset'=>'utf-8'],
     *     ['name'=>'viewport', 'content'=>'width=device-width, initial-scale=1']
     * ]);
     *
     * @param array $attributes
     * @param boolean $overwriteMatchingKeys
     * @return $this.
     */
    public function add($attributes, $overwrite = true);

    /**
     * Remove a meta tag or set of meta tags by key/value pairs.
     * The value is treated as a wild card when it is set to null.
     *
     * $meta->tags()->remove([
     *     ['charset'=>null],
     *     ['name'=>'viewport', 'content'=>null]
     * ]);
     *
     * @param  array $matchingKeys
     * @param boolean $removeContents
     * @return $this
     */
    public function remove($attributes, $removeContents = false);

    /**
     * Clears all tags
     * @return $this
     */
    public function clear();

    /**
     * Sets the template to be used to generate the meta tags
     * @param  string $template
     * @return $this
     */
    public function template($template);
}


text:
function mosaic = fast_row_sweep(frames,objective,direction)
start_time = tic;

classToUse = 'single';

sizeFrame = size(frames{1});
total_frames = size(frames,1);

    roi = int32([0 0 sizeFrame(2) sizeFrame(1)]);

if objective == 2
    nth_frame = 10;
    delta_x = 2238;
    delta_y = 5;
end

if strcmp(direction,'left')
    delta_x = delta_x * -1;
    delta_y = delta_y * -1;
end

tform = [1 0; 0 1; delta_x delta_y];
sizePano = [sizeFrame(1), sizeFrame(2) + delta_x * ceil(total_frames/nth_frame)];
origPano = [0 0];

if strcmp(direction,'left')
    origPano(2) = sizePano(2) - sizeFrame(2);
end

%%
% Create a GeometricTransformer System object.
hgeotrans = vision.GeometricTransformer( ...
    'OutputImagePositionSource', 'Property', 'ROIInputPort', true, ...
    'OutputImagePosition', [-origPano sizePano]);

%%
% Create a AlphaBlender System object to overlay the consecutive video
% frames to produce the panorama.
halphablender = vision.AlphaBlender( ...
    'Operation', 'Binary mask', 'MaskSource', 'Input port');

%%
% Create VideoPlayer System object to draw the panorama.
hVideo1 = vision.VideoPlayer('Name', 'fast_Mosaic');
hVideo1.Position(1) = hVideo1.Position(1) - 350;
hVideo1.Position(2) = hVideo1.Position(2) - 100;
hVideo1.Position([3 4]) = [2200 1600];

is_Initialized = 0;
iter = 1;
current_frame = 1;

while current_frame < total_frames - 45
    reg_start = tic;

    current_frame = (iter * nth_frame) + 1;
    if current_frame > total_frames
        break;
    end
    iter = iter + 1;

    rgb = frames{current_frame};

    if is_Initialized
        xtform = xtform * [tform, [0 0 1]'];
    else
        xtform = eye(3, classToUse);
        mosaic = zeros([sizePano,3], classToUse);
        is_Initialized = 1;
    end

    % Warp the current image onto the mosaic image
    rgb = single(rgb)./255;     % FAILED: required single/double
    transformedImage = step(hgeotrans, rgb, xtform, roi);
    mosaic = step(halphablender, mosaic, transformedImage, ...
        transformedImage(:,:,1)>0);

    register(iter) = toc(reg_start)

    step(hVideo1, mosaic);
end

total_time = toc(start_time)

end


text:
package org.kaazing.gateway.transport.wsr;

public class RtmpStreamRecordedMessage extends RtmpUserControlMessage {

	private int streamId;

	@Override
	public UserControlKind getUserControlKind() {
		return UserControlKind.STREAM_RECORDED;
	}

	public void setStreamId(int streamId) {
		this.streamId = streamId;
	}

	public int getStreamId() {
		return streamId;
	}

}


text:
package net.krotscheck.kangaroo.authz.common.database.entity;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.base.Strings;
import io.swagger.annotations.ApiModelProperty;
import net.krotscheck.kangaroo.common.hibernate.id.AbstractEntityReferenceDeserializer;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.ContainedIn;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.hibernate.search.annotations.Store;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapKeyColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * This represents a registered client, as well as it's connection metadata,
 * for
 * a specific application. Multiple different clients may exist per
 * application.
 *
 * @author Michael Krotscheck
 */
@Entity
@Table(name = "clients")
@Indexed(index = "clients")
@Analyzer(definition = "entity_analyzer")
public final class Client extends AbstractAuthzEntity {

    /**
     * The Application to whom this client belongs.
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "application", nullable = false, updatable = false)
    @JsonIdentityReference(alwaysAsId = true)
    @JsonIdentityInfo(
            generator = ObjectIdGenerators.PropertyGenerator.class,
            property = "id")
    @JsonDeserialize(using = Application.Deserializer.class)
    @IndexedEmbedded(includePaths = {"id", "owner.id"})
    @ApiModelProperty(
            required = true,
            dataType = "string",
            example = "3f631a2d6a04f5cc55f9e192f45649b7"
    )
    private Application application;

    /**
     * List of the application's authenticators.
     */
    @OneToMany(
            fetch = FetchType.LAZY,
            mappedBy = "client",
            cascade = {CascadeType.REMOVE},
            orphanRemoval = true
    )
    @JsonIgnore
    @OnDelete(action = OnDeleteAction.CASCADE)
    private List<Authenticator> authenticators = new ArrayList<>();

    /**
     * OAuth tokens issued to this client.
     */
    @OneToMany(
            fetch = FetchType.LAZY,
            mappedBy = "client",
            cascade = {CascadeType.REMOVE, CascadeType.MERGE},
            orphanRemoval = true
    )
    @JsonIgnore
    @OnDelete(action = OnDeleteAction.CASCADE)
    @ContainedIn
    private List<OAuthToken> tokens = new ArrayList<>();

    /**
     * Human recognizable name for this client.
     */
    @Basic(optional = false)
    @Column(name = "name", nullable = false)
    @Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
    @Size(min = 3, max = 255, message = "Client name must be between 3 "
            + "and 255 characters.")
    @ApiModelProperty(required = true)
    private String name;

    /**
     * Human recognizable name for this client.
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "type", nullable = false)
    @NotNull
    private ClientType type;

    /**
     * A client secret, indicating a password which must be provided to the
     * client.
     */
    @Basic
    @Column(name = "clientSecret", updatable = true, nullable = true)
    private String clientSecret;

    /**
     * A collection of referral URL's, used for CORS matching.
     */
    @OneToMany(
            fetch = FetchType.LAZY,
            mappedBy = "client",
            cascade = {CascadeType.ALL},
            orphanRemoval = true
    )
    @JsonIgnore
    @OnDelete(action = OnDeleteAction.CASCADE)
    @IndexedEmbedded(includePaths = {"id", "uri"})
    private List<ClientReferrer> referrers = new ArrayList<>();

    /**
     * A list of redirect URL's, used for redirection-based flows.
     */
    @OneToMany(
            fetch = FetchType.LAZY,
            mappedBy = "client",
            cascade = {CascadeType.REMOVE},
            orphanRemoval = true
    )
    @JsonIgnore
    @OnDelete(action = OnDeleteAction.CASCADE)
    @IndexedEmbedded(includePaths = {"id", "uri"})
    private List<ClientRedirect> redirects = new ArrayList<>();

    /**
     * The configuration settings for this application.
     */
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "client_configs",
                     joinColumns = @JoinColumn(name = "client"))
    @MapKeyColumn(name = "configKey")
    @Column(name = "configValue")
    private Map<String, String> configuration = new TreeMap<>();

    /**
     * Get the application this client belongs to.
     *
     * @return The application.
     */
    public Application getApplication() {
        return application;
    }

    /**
     * Set the application which this client belongs to.
     *
     * @param application The new application.
     */
    public void setApplication(final Application application) {
        this.application = application;
    }

    /**
     * Get the name for this client.
     *
     * @return The client's human-readable name.
     */
    public String getName() {
        return name;
    }

    /**
     * Set the client's name.
     *
     * @param name The name to use, should be human-readable.
     */
    public void setName(final String name) {
        this.name = name;
    }

    /**
     * Retrieve the client secret.
     *
     * @return The client secret.
     */
    public String getClientSecret() {
        return clientSecret;
    }

    /**
     * Set the client secret.
     *
     * @param clientSecret A new client secret.
     */
    public void setClientSecret(final String clientSecret) {
        this.clientSecret = clientSecret;
    }

    /**
     * Get the list of valid referrers.
     *
     * @return This client's list of valid referrers.
     */
    public List<ClientReferrer> getReferrers() {
        return referrers;
    }

    /**
     * Update the set of valid referrers.
     *
     * @param referrers A new set of referrers.
     */
    public void setReferrers(final List<ClientReferrer> referrers) {
        this.referrers = new ArrayList<>(referrers);
    }

    /**
     * Get the valid redirect URI's.
     *
     * @return The valid redirect url's.
     */
    public List<ClientRedirect> getRedirects() {
        return redirects;
    }

    /**
     * Set the list of redirects.
     *
     * @param redirects The redirects.
     */
    public void setRedirects(final List<ClientRedirect> redirects) {
        this.redirects = new ArrayList<>(redirects);
    }

    /**
     * The list of authenticators active in this client.
     *
     * @return The list of authenticators.
     */
    public List<Authenticator> getAuthenticators() {
        return authenticators;
    }

    /**
     * Set the authenticators.
     *
     * @param authenticators New list of authenticators.
     */
    public void setAuthenticators(final List<Authenticator> authenticators) {
        this.authenticators = new ArrayList<>(authenticators);
    }

    /**
     * Get all the tokens issued under this client.
     *
     * @return A list of all tokens (lazy loaded)
     */
    public List<OAuthToken> getTokens() {
        return tokens;
    }

    /**
     * Set the list of tokens for this client.
     *
     * @param tokens A new list of tokens.
     */
    public void setTokens(final List<OAuthToken> tokens) {
        this.tokens = new ArrayList<>(tokens);
    }

    /**
     * Get the client type.
     *
     * @return The client type.
     */
    public ClientType getType() {
        return type;
    }

    /**
     * Set the client type.
     *
     * @param type The client type!
     */
    public void setType(final ClientType type) {
        this.type = type;
    }

    /**
     * Retrieve configuration for this client.
     *
     * @return A set of configuration elements, such as token expiry.
     */
    public Map<String, String> getConfiguration() {
        return configuration;
    }

    /**
     * Set the configuration for this client.
     *
     * @param configuration The new configuration.
     */
    public void setConfiguration(final Map<String, String> configuration) {
        this.configuration = new HashMap<>(configuration);
    }

    /**
     * Extract the authorization code expiration time (in seconds) for this
     * client. This value is derived from the default configuration values, or
     * from a default, if such exists.
     *
     * @return The expiration horizon of an access token, in seconds.
     */
    @JsonIgnore
    public Integer getAuthorizationCodeExpiresIn() {
        try {
            Map<String, String> config = getConfiguration();
            String value =
                    config.get(ClientConfig.AUTHORIZATION_CODE_EXPIRES_NAME);
            return Integer.parseInt(value);
        } catch (Exception e) {
            return ClientConfig.AUTHORIZATION_CODE_EXPIRES_DEFAULT;
        }
    }

    /**
     * Extract the access token expiration time (in seconds) for this client.
     * This value is derived from the default configuration values, or from a
     * default, if such exists.
     *
     * @return The expiration horizon of an access token, in seconds.
     */
    @JsonIgnore
    public Integer getAccessTokenExpireIn() {
        try {
            Map<String, String> config = getConfiguration();
            String value = config.get(ClientConfig.ACCESS_TOKEN_EXPIRES_NAME);
            return Integer.parseInt(value);
        } catch (Exception e) {
            return ClientConfig.ACCESS_TOKEN_EXPIRES_DEFAULT;
        }
    }

    /**
     * Extract the refresh token expiration time (in seconds) for this client.
     * This value is derived from the default configuration values, or from a
     * default, if such exists.
     *
     * @return The expiration horizon of an access token, in seconds.
     */
    @JsonIgnore
    public Integer getRefreshTokenExpireIn() {
        try {
            Map<String, String> config = getConfiguration();
            String value = config.get(ClientConfig.REFRESH_TOKEN_EXPIRES_NAME);
            return Integer.parseInt(value);
        } catch (Exception e) {
            return ClientConfig.REFRESH_TOKEN_EXPIRES_DEFAULT;
        }
    }

    /**
     * The owner of this entity.
     *
     * @return This entity's owner, if it exists.
     */
    @Override
    @Transient
    @JsonIgnore
    public User getOwner() {
        if (application != null) {
            return application.getOwner();
        }
        return null;
    }

    /**
     * Whether this client is private.
     *
     * @return true, if this is a private client, otherwise false.
     */
    @Transient
    @JsonIgnore
    public Boolean isPrivate() {
        return !Strings.isNullOrEmpty(clientSecret);
    }

    /**
     * Whether this client is public.
     *
     * @return true, if this is a public client, otherwise false.
     */
    @Transient
    @JsonIgnore
    public Boolean isPublic() {
        return !isPrivate();
    }

    /**
     * Deserialize a reference to an User.
     *
     * @author Michael Krotschecks
     */
    public static final class Deserializer
            extends AbstractEntityReferenceDeserializer<Client> {

        /**
         * Constructor.
         */
        public Deserializer() {
            super(Client.class);
        }
    }
}


text:
function [feat] = load_feature(dataset_name, feature, imgset, c, batch_id)
%
% Copyright Aditya Khosla http://mit.edu/khosla
%
% Please cite this paper if you use this code in your publication:
%   A. Khosla, J. Xiao, A. Torralba, A. Oliva
%   Memorability of Image Regions
%   Advances in Neural Information Processing Systems (NIPS) 2012
%

if(~exist('dataset_name', 'var') || isempty(dataset_name))
    dataset_name = '';
end
cache_folder = [c.cache '/' dataset_name '/'];
p = c.feature_config.(feature);

if(isfield(p, 'dictionary_size'))
    feature_file = sprintf(p.([imgset '_file']), cache_folder, p.dictionary_size);
else
    feature_file = sprintf(p.([imgset '_file']), cache_folder);
end

tmp = load(feature_file);
if(isempty(tmp.feat))
    batch_files = tmp.batch_files;
    if(~exist('batch_id', 'var') || isempty(batch_id))
        batch_id = 1:length(batch_files);
    end

    feat = cell(length(batch_id), 1);
    for i=1:length(batch_id)
      vprintf(c.verbosity, 1, 'Loading batch %d of %d\r', i, length(batch_id));
      tmp = load(batch_files{batch_id(i)});
      feat{i} = tmp.poolfeat;
    end
		vprintf(c.verbosity, 1, '\n');
    feat = cell2mat(feat);
else
    feat = tmp.feat;
end