text:
package org.apache.solr.handler.admin;

import org.apache.commons.io.IOUtils;
import org.apache.solr.handler.RequestHandlerBase;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.core.SolrInfoMBean;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.response.BinaryResponseWriter;
import org.apache.solr.response.SolrQueryResponse;

import java.io.StringReader;
import java.net.URL;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;

/**
 * A request handler that provides info about all
 * registered SolrInfoMBeans.
 */
@SuppressWarnings("unchecked")
public class SolrInfoMBeanHandler extends RequestHandlerBase {

  /**
   * Take an array of any type and generate a Set containing the toString.
   * Set is guarantee to never be null (but may be empty)
   */
  private Set<String> arrayToSet(Object[] arr) {
    HashSet<String> r = new HashSet<>();
    if (null == arr) return r;
    for (Object o : arr) {
      if (null != o) r.add(o.toString());
    }
    return r;
  }

  @Override
  public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    NamedList<NamedList<NamedList<Object>>> cats = getMBeanInfo(req);
    if(req.getParams().getBool("diff", false)) {
      ContentStream body = null;
      try {
        body = req.getContentStreams().iterator().next();
      }
      catch(Exception ex) {
        throw new SolrException(ErrorCode.BAD_REQUEST, "missing content-stream for diff");
      }
      String content = IOUtils.toString(body.getReader());

      NamedList<NamedList<NamedList<Object>>> ref = fromXML(content);

      // Normalize the output
      SolrQueryResponse wrap = new SolrQueryResponse();
      wrap.add("solr-mbeans", cats);
      cats = (NamedList<NamedList<NamedList<Object>>>)
          BinaryResponseWriter.getParsedResponse(req, wrap).get("solr-mbeans");

      // Get rid of irrelevant things
      ref = normalize(ref);
      cats = normalize(cats);

      // Only the changes
      boolean showAll = req.getParams().getBool("all", false);
      rsp.add("solr-mbeans", getDiff(ref,cats, showAll));
    }
    else {
      rsp.add("solr-mbeans", cats);
    }
    rsp.setHttpCaching(false); // never cache, no matter what init config looks like
  }

  static NamedList<NamedList<NamedList<Object>>> fromXML(String content) {
    int idx = content.indexOf("<response>");
    if(idx<0) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "Body does not appear to be an XML response");
    }

    try {
      XMLResponseParser parser = new XMLResponseParser();
      return (NamedList<NamedList<NamedList<Object>>>)
          parser.processResponse(new StringReader(content.substring(idx))).get("solr-mbeans");
    }
    catch(Exception ex) {
      throw new SolrException(ErrorCode.BAD_REQUEST, "Unable to read original XML", ex);
    }
  }

  protected NamedList<NamedList<NamedList<Object>>> getMBeanInfo(SolrQueryRequest req) {

    NamedList<NamedList<NamedList<Object>>> cats = new NamedList<>();

    String[] requestedCats = req.getParams().getParams("cat");
    if (null == requestedCats || 0 == requestedCats.length) {
      for (SolrInfoMBean.Category cat : SolrInfoMBean.Category.values()) {
        cats.add(cat.name(), new SimpleOrderedMap<NamedList<Object>>());
      }
    } else {
      for (String catName : requestedCats) {
        cats.add(catName,new SimpleOrderedMap<NamedList<Object>>());
      }
    }

    Set<String> requestedKeys = arrayToSet(req.getParams().getParams("key"));

    Map<String, SolrInfoMBean> reg = req.getCore().getInfoRegistry();
    for (Map.Entry<String, SolrInfoMBean> entry : reg.entrySet()) {
      String key = entry.getKey();
      SolrInfoMBean m = entry.getValue();

      if ( ! ( requestedKeys.isEmpty() || requestedKeys.contains(key) ) ) continue;

      NamedList<NamedList<Object>> catInfo = cats.get(m.getCategory().name());
      if ( null == catInfo ) continue;

      NamedList<Object> mBeanInfo = new SimpleOrderedMap<>();
      mBeanInfo.add("class", m.getName());
      mBeanInfo.add("version", m.getVersion());
      mBeanInfo.add("description", m.getDescription());
      mBeanInfo.add("src", m.getSource());

      // Use an external form
      URL[] urls = m.getDocs();
      if(urls!=null) {
        List<String> docs = new ArrayList<>(urls.length);
        for(URL url : urls) {
          docs.add(url.toExternalForm());
        }
        mBeanInfo.add("docs", docs);
      }

      if (req.getParams().getFieldBool(key, "stats", false))
        mBeanInfo.add("stats", m.getStatistics());

      catInfo.add(key, mBeanInfo);
    }
    return cats;
  }

  protected NamedList<NamedList<NamedList<Object>>> getDiff(
      NamedList<NamedList<NamedList<Object>>> ref,
      NamedList<NamedList<NamedList<Object>>> now,
      boolean includeAll ) {

    NamedList<NamedList<NamedList<Object>>> changed = new NamedList<>();

    // Cycle through each category
    for(int i=0;i<ref.size();i++) {
      String category = ref.getName(i);
      NamedList<NamedList<Object>> ref_cat = ref.get(category);
      NamedList<NamedList<Object>> now_cat = now.get(category);
      if(now_cat != null) {
        String ref_txt = ref_cat+"";
        String now_txt = now_cat+"";
        if(!ref_txt.equals(now_txt)) {
          // Something in the category changed
          // Now iterate the real beans

          NamedList<NamedList<Object>> cat = new SimpleOrderedMap<>();
          for(int j=0;j<ref_cat.size();j++) {
            String name = ref_cat.getName(j);
            NamedList<Object> ref_bean = ref_cat.get(name);
            NamedList<Object> now_bean = now_cat.get(name);

            ref_txt = ref_bean+"";
            now_txt = now_bean+"";
            if(!ref_txt.equals(now_txt)) {
//              System.out.println( "----" );
//              System.out.println( category +" : " + name );
//              System.out.println( "REF: " + ref_txt );
//              System.out.println( "NOW: " + now_txt );

              // Calculate the differences
              NamedList diff = diffNamedList(ref_bean,now_bean);
              diff.add( "_changed_", true ); // flag the changed thing
              cat.add(name, diff);
            }
            else if(includeAll) {
              cat.add(name, ref_bean);
            }
          }
          if(cat.size()>0) {
            changed.add(category, cat);
          }
        }
        else if(includeAll) {
          changed.add(category, ref_cat);
        }
      }
    }
    return changed;
  }

  public NamedList diffNamedList(NamedList ref, NamedList now) {
    NamedList out = new SimpleOrderedMap();
    for(int i=0; i<ref.size(); i++) {
      String name = ref.getName(i);
      Object r = ref.getVal(i);
      Object n = now.remove(name);
      if(n == null) {
        if(r!=null) {
          out.add("REMOVE "+name, r);
        }
      }
      else {
        out.add(name, diffObject(r,n));
      }
    }

    for(int i=0; i<now.size(); i++) {
      String name = now.getName(i);
      Object v = now.getVal(i);
      if(v!=null) {
        out.add("ADD "+name, v);
      }
    }
    return out;
  }

  public Object diffObject(Object ref, Object now) {
    if(ref instanceof NamedList) {
      return diffNamedList((NamedList)ref, (NamedList)now);
    }
    if(ref.equals(now)) {
      return ref;
    }
    StringBuilder str = new StringBuilder();
    str.append("Was: ")
     .append(ref).append(", Now: ").append(now);

    if(ref instanceof Number) {
      NumberFormat nf = NumberFormat.getIntegerInstance(Locale.ROOT);
      if((ref instanceof Double) || (ref instanceof Float)) {
        nf = NumberFormat.getInstance(Locale.ROOT);
      }
      double dref = ((Number)ref).doubleValue();
      double dnow = ((Number)now).doubleValue();
      double diff = Double.NaN;
      if(Double.isNaN(dref)) {
        diff = dnow;
      }
      else if(Double.isNaN(dnow)) {
        diff = dref;
      }
      else {
        diff = dnow-dref;
      }
      str.append( ", Delta: ").append(nf.format(diff));
    }
    return str.toString();
  }

  /**
   * The 'avgRequestsPerSecond' field will make everything look like it changed
   */
  public NamedList normalize(NamedList input) {
    input.remove("avgRequestsPerSecond");
    for(int i=0; i<input.size(); i++) {
      Object v = input.getVal(i);
      if(v instanceof NamedList) {
        input.setVal(i, normalize((NamedList)v));
      }
    }
    return input;
  }

  @Override
  public String getDescription() {
    return "Get Info (and statistics) for registered SolrInfoMBeans";
  }

  @Override
  public String getSource() {
    return "$URL: https://svn.apache.org/repos/asf/lucene/dev/branches/lucene_solr_4_9/solr/core/src/java/org/apache/solr/handler/admin/SolrInfoMBeanHandler.java $";
  }
}


text:
// Copyright (c) 2006-2013 nudge:nudge (Johannes Hoffart & Daniel Bär). All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Cocoa/Cocoa.h>
#import "NNTag.h"
#import "NNTagStoreManager.h"

#import "NNQueryBundle.h"
#import "NNQueryFilter.h"
#import "NNSelectedTags.h"
#import "NSFileManager+Extensions.h"

@class NNFile;
@class NNTagStoreManager;
@class NNTagToFileWriter;

/** Posted when the receiver begins with the initial result-gathering phase of the query. */
extern NSString * const NNQueryDidStartGatheringNotification;

/** Posted when new results have been found */
extern NSString * const NNQueryGatheringProgressNotification;

/** Posted when the receiver's results have changed during the live-update phase of the query. */
extern NSString * const NNQueryDidUpdateNotification;

/** Posted when the receiver has finished with the initial result-gathering phase of the query. */
extern NSString * const NNQueryDidFinishGatheringNotification;

/** Posted when the query is reset - needed when results are emptied */
extern NSString * const NNQueryDidResetNotification;

/** Posted when the receiver's grouping attributes have changed. */
//extern NSString * const NNQueryGroupingAttributesDidChange;

/**
NNQuery is mainly a wrapper around the NSMetadataQuery class, and shares a lot of its API.
 There are additional methods for manipulating the search, as NNQuery uses NNTag instances instead of
 directly setting the NSPredicate.
  */
@interface NNQuery : NSObject
{
	MDQueryRef				mdquery;
	MDQueryBatchingParams	batchingParams;

	NSArray					*valueListAttrs; // fetching the needed attributes in the query is a lot faster

	NNTagToFileWriter		*tagToFileWriter;
	NSString				*tagsSpotlightMetadataField;

	NSDictionary			*simpleGrouping;

	NNSelectedTags			*tags;

	NSMutableDictionary		*bundles;
	NSArray					*bundlingAttributes;

	NSArray					*sortDescriptors;

	NSMutableDictionary		*filterDict;
	NSMutableArray			*filters;

	NSDate					*startDate;
	NSDate					*endDate;

	NSMutableArray			*plainResults;
	NSMutableArray			*flatPlainResults;
	NSMutableArray			*filteredResults;
	NSMutableArray			*flatFilteredResults;

	NSWindow				*errorWindow;

	// query states
	BOOL					started;
	BOOL					stopped;
	BOOL					gathering;

	NSString				*metadataCacheFolder;
}

/**
 Executes a synchronous query for the query string
 that will return the results immediately.
 @param queryString Query string to execute
 @return TaggableObjects for query string
 */
- (NSArray*)executeSynchronousQueryForString:(NSString*)queryString;

/**
 Executes a synchronous query that will return the results
 immediately.

 @return TaggableObjects for selected tags
 */
- (NSArray*)executeSynchronousQuery;

/**
 Executes a synchronous query that will return the bundled
 results immediately.
 @param attr Bundling attribute, i.e. kMDItemContentTypeTree
 @return Bundles that contain taggableObjects for selected tags
 */
- (NSArray *)executeSynchronousQueryWithBundlingAttribute:(NSString *)attr;

/**
@return New query - use setTags: to set tags for searching
 */
- (id)init;

/**
Designated initializer - call this one if you want to set the selected tags
 right away.
 @param otherTags Tags to search for
 @return NNQuery ready to search for otherTags
 */
- (id)initWithTags:(NNSelectedTags*)otherTags;

/**
@return Tags the query is currently prepared to search for
 */
- (NNSelectedTags*)tags;

/**
@param otherTags Tags to search for
 */
- (void)setTags:(NNSelectedTags*)otherTags;

//wrapper methods
/**
Starts the query
 @return YES when succesful, NO otherwise
 */
- (BOOL)startQuery;

/**
Stops the query
 */
- (void)stopQuery;

/**
Temporarily stops the query from gathering results -
 use this if you e.g. want to display intermediate results.
 */
- (void)disableUpdates;

/**
Reenables result gathering - use this after disableUpdates.
 */
- (void)enableUpdates;

/**
@return YES if query is started, NO otherwise
 */
- (BOOL)isStarted;

/**
@return YES if the query is stopped, NO otherwise
 */
- (BOOL)isStopped;

/**
This returns YES if the query is started and updating was not
 disabled.
@return YES if query is gathering results, NO otherwise
 */
- (BOOL)isGathering;

/**
@return Number of results currently found
 */
- (NSUInteger)resultCount;

/**
@param idx Index of the result to return
 @return Result at position idx
 */
- (id)resultAtIndex:(NSUInteger)idx;

// query extension
/**
@return Results that may contain a hierarchical tree of bundles
 or a flat list of items. This depends on the current bundling
 attributes.
 */
- (NSArray *)results;

/**
@return Results as flat array
 */
- (NSArray *)flatResults;

/**
 @return Results as flat unfiltered array.
 */
- (NSMutableArray *)flatPlainResults;

/**
@return Bundling attributes as array
*/
- (NSArray *)bundlingAttributes;

/**
Sets new bundling attributes
@param attributes The new attributes to use
*/
- (void)setBundlingAttributes:(NSArray*)attributes;

/**
@return Sort descriptors
*/
- (NSArray *)sortDescriptors;

/**
@param someSortDescriptors The new sortDescriptors to use
*/
- (void)setSortDescriptors:(NSArray*)someSortDescriptors;

/**
@return Array of NNQueryFilters
 */
- (NSArray*)filters;

/**
@param someFilters Filters to use when executing the query
 */
- (void)setFilters:(NSMutableArray*)someFilters;

/**
Adds a filter to the query
 @param filter Filter to add
 */
- (void)addFilter:(NNQueryFilter*)filter;

/**
Adds multiple filters to the query
 @param someFilters Filters to add
 */
- (void)addFilters:(NSArray*)someFilters;

/**
Removes a filter from the query
 @param filter Filter to remove
 */
- (void)removeFilter:(NNQueryFilter*)filter;

/**
Removes all active query filters
 */
- (void)removeAllFilters;

/**
 @return startDate
 */
- (NSDate*)startDate;

/**
 If a startDate is set, tagged objects will only
 be retrieved if they have been tagged AFTER
 the given date

 @param date	Start date of tagged objects to return
 */
- (void)setStartDate:(NSDate*)date;

/**
 @return endDate
 */
- (NSDate*)endDate;

/**
 If a endDate is set, tagged objects will only
 be retrieved if they have been tagged BEFORE
 the given date

 @param date	End date of tagged objects to return
 */
- (void)setEndDate:(NSDate*)date;

/**
 TODO daniel

Applies new filter. may be set at any time even if the query is currently active.
 This has nothing to do with the filter methods above. filterResults: will filter gathered results,
 whereas the NNQueryFilters will constrain the query directly.
 @param flag If YES filter is applied
 @param filterValues Array of values to use for the filter, e.g. "DOCUMENTS" or "PDF"
 @param attribute DEPRECATED - currently supposed to be "kMDItemContentTypeTree"
 @param newAttributes DEPRECATED
 */
-   (void)filterResults:(BOOL)flag
			usingValues:(NSArray *)filterValues
   forBundlingAttribute:(NSString *)attribute
  newBundlingAttributes:(NSArray *)newAttributes;

/**
Returns YES if there are results for the given filter.
 @param filterValues Array of values to use for the filter, e.g. "DOCUMENTS" or "PDF"
 @param attribute Attribute to use, e.g. "kMDItemContentTypeTree"
 @return YES if there are results, NO otherwise
 */
- (BOOL)hasResultsUsingFilterWithValues:(NSArray *)filterValues
                   forBundlingAttribute:(NSArray *)attribute;

/**
@return YES if there's currently a filter
 */
- (BOOL)hasFilter;

@end

redpajama_set_name: RedPajamaGithub


text:
package de.danoeh.antennapod.core;

import de.danoeh.antennapod.core.storage.AutomaticDownloadAlgorithm;
import de.danoeh.antennapod.core.storage.EpisodeCleanupAlgorithm;

/**
 * Callbacks for the DBTasks class of the storage module.
 */
public interface DBTasksCallbacks {

    /**
     * Returns the client's implementation of the AutomaticDownloadAlgorithm interface.
     */
    AutomaticDownloadAlgorithm getAutomaticDownloadAlgorithm();

    /**
     * Returns the client's implementation of the EpisodeCacheCleanupAlgorithm interface.
     */
    EpisodeCleanupAlgorithm getEpisodeCacheCleanupAlgorithm();
}


text:
namespace Nalarium
{
    public static class PairSplitter
    {
        //- @Split -//
        public static Map Split(string[] pairArray)
        {
            if (pairArray == null)
            {
                return new Map();
            }
            var map = new Map();
            foreach (var item in pairArray)
            {
                var trimmed = item.Trim();
                if (trimmed.Contains("="))
                {
                    string first;
                    string second;
                    Split(trimmed, out first, out second);
                    //+
                    map.Add(first, second);
                }
                else
                {
                    map.Add(trimmed, null);
                }
            }
            //+
            return map;
        }

        public static void Split(string text, out string first, out string second)
        {
            if (string.IsNullOrEmpty(text))
            {
                first = string.Empty;
                second = string.Empty;
                return;
            }
            text = text.Trim();
            if (!text.Contains("="))
            {
                first = string.Empty;
                second = string.Empty;
                return;
            }
            var name = string.Empty;
            var value = string.Empty;
            var index = text.IndexOf('=');
            first = text.Substring(0, index);
            second = text.Substring(index + 1, text.Length - index - 1);
        }
    }
}


text:
void UnmappedMemoryDevice::Init(MemoryBus& memoryBus) {
    memoryBus.ConnectDevice(*this, MemoryMap::Unmapped.range, EnableSync::False);
}

uint8_t UnmappedMemoryDevice::Read(uint16_t address) const {
    ErrorHandler::Undefined("Read from unmapped range at address $%04x\n", address);
    return 0;
}

void UnmappedMemoryDevice::Write(uint16_t address, uint8_t value) {
    ErrorHandler::Undefined("Write to unmappped range of value $%02x at address $%04x\n", value,
                            address);
}


text:
from oslo_log import log as logging

from heat.common import exception
from heat.common.i18n import _
from heat.common.i18n import _LI
from heat.common.i18n import _LW
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support

LOG = logging.getLogger(__name__)

class OSDBInstance(resource.Resource):
    '''
    OpenStack cloud database instance resource.
    '''

    support_status = support.SupportStatus(version='2014.1')

    TROVE_STATUS = (
        ERROR, FAILED, ACTIVE,
    ) = (
        'ERROR', 'FAILED', 'ACTIVE',
    )

    TROVE_STATUS_REASON = {
        FAILED: _('The database instance was created, but heat failed to set '
                  'up the datastore. If a database instance is in the FAILED '
                  'state, it should be deleted and a new one should be '
                  'created.'),
        ERROR: _('The last operation for the database instance failed due to '
                 'an error.'),
    }

    BAD_STATUSES = (ERROR, FAILED)
    PROPERTIES = (
        NAME, FLAVOR, SIZE, DATABASES, USERS, AVAILABILITY_ZONE,
        RESTORE_POINT, DATASTORE_TYPE, DATASTORE_VERSION, NICS,
        REPLICA_OF, REPLICA_COUNT,
    ) = (
        'name', 'flavor', 'size', 'databases', 'users', 'availability_zone',
        'restore_point', 'datastore_type', 'datastore_version', 'networks',
        'replica_of', 'replica_count'
    )

    _DATABASE_KEYS = (
        DATABASE_CHARACTER_SET, DATABASE_COLLATE, DATABASE_NAME,
    ) = (
        'character_set', 'collate', 'name',
    )

    _USER_KEYS = (
        USER_NAME, USER_PASSWORD, USER_HOST, USER_DATABASES,
    ) = (
        'name', 'password', 'host', 'databases',
    )

    _NICS_KEYS = (
        NET, PORT, V4_FIXED_IP
    ) = (
        'network', 'port', 'fixed_ip'
    )

    ATTRIBUTES = (
        HOSTNAME, HREF,
    ) = (
        'hostname', 'href',
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('Name of the DB instance to create.'),
            constraints=[
                constraints.Length(max=255),
            ]
        ),
        FLAVOR: properties.Schema(
            properties.Schema.STRING,
            _('Reference to a flavor for creating DB instance.'),
            required=True,
            constraints=[
                constraints.CustomConstraint('trove.flavor')
            ]
        ),
        DATASTORE_TYPE: properties.Schema(
            properties.Schema.STRING,
            _("Name of registered datastore type."),
            constraints=[
                constraints.Length(max=255)
            ]
        ),
        DATASTORE_VERSION: properties.Schema(
            properties.Schema.STRING,
            _("Name of the registered datastore version. "
              "It must exist for provided datastore type. "
              "Defaults to using single active version. "
              "If several active versions exist for provided datastore type, "
              "explicit value for this parameter must be specified."),
            constraints=[constraints.Length(max=255)]
        ),
        SIZE: properties.Schema(
            properties.Schema.INTEGER,
            _('Database volume size in GB.'),
            required=True,
            constraints=[
                constraints.Range(1, 150),
            ]
        ),
        NICS: properties.Schema(
            properties.Schema.LIST,
            _("List of network interfaces to create on instance."),
            default=[],
            schema=properties.Schema(
                properties.Schema.MAP,
                schema={
                    NET: properties.Schema(
                        properties.Schema.STRING,
                        _('Name or UUID of the network to attach this NIC to. '
                          'Either %(port)s or %(net)s must be specified.') % {
                              'port': PORT, 'net': NET},
                        constraints=[
                            constraints.CustomConstraint('neutron.network')
                        ]
                    ),
                    PORT: properties.Schema(
                        properties.Schema.STRING,
                        _('Name or UUID of Neutron port to attach this '
                          'NIC to. '
                          'Either %(port)s or %(net)s must be specified.') % {
                              'port': PORT, 'net': NET},
                        constraints=[
                            constraints.CustomConstraint('neutron.port')
                        ],
                    ),
                    V4_FIXED_IP: properties.Schema(
                        properties.Schema.STRING,
                        _('Fixed IPv4 address for this NIC.'),
                        constraints=[
                            constraints.CustomConstraint('ip_addr')
                        ]
                    ),
                },
            ),
        ),
        DATABASES: properties.Schema(
            properties.Schema.LIST,
            _('List of databases to be created on DB instance creation.'),
            default=[],
            schema=properties.Schema(
                properties.Schema.MAP,
                schema={
                    DATABASE_CHARACTER_SET: properties.Schema(
                        properties.Schema.STRING,
                        _('Set of symbols and encodings.'),
                        default='utf8'
                    ),
                    DATABASE_COLLATE: properties.Schema(
                        properties.Schema.STRING,
                        _('Set of rules for comparing characters in a '
                          'character set.'),
                        default='utf8_general_ci'
                    ),
                    DATABASE_NAME: properties.Schema(
                        properties.Schema.STRING,
                        _('Specifies database names for creating '
                          'databases on instance creation.'),
                        required=True,
                        constraints=[
                            constraints.Length(max=64),
                            constraints.AllowedPattern(r'[a-zA-Z0-9_]+'
                                                       r'[a-zA-Z0-9_@?#\s]*'
                                                       r'[a-zA-Z0-9_]+'),
                        ]
                    ),
                },
            )
        ),
        USERS: properties.Schema(
            properties.Schema.LIST,
            _('List of users to be created on DB instance creation.'),
            default=[],
            schema=properties.Schema(
                properties.Schema.MAP,
                schema={
                    USER_NAME: properties.Schema(
                        properties.Schema.STRING,
                        _('User name to create a user on instance '
                          'creation.'),
                        required=True,
                        constraints=[
                            constraints.Length(max=16),
                            constraints.AllowedPattern(r'[a-zA-Z0-9_]+'
                                                       r'[a-zA-Z0-9_@?#\s]*'
                                                       r'[a-zA-Z0-9_]+'),
                        ]
                    ),
                    USER_PASSWORD: properties.Schema(
                        properties.Schema.STRING,
                        _('Password for those users on instance '
                          'creation.'),
                        required=True,
                        constraints=[
                            constraints.AllowedPattern(r'[a-zA-Z0-9_]+'
                                                       r'[a-zA-Z0-9_@?#\s]*'
                                                       r'[a-zA-Z0-9_]+'),
                        ]
                    ),
                    USER_HOST: properties.Schema(
                        properties.Schema.STRING,
                        _('The host from which a user is allowed to '
                          'connect to the database.'),
                        default='%'
                    ),
                    USER_DATABASES: properties.Schema(
                        properties.Schema.LIST,
                        _('Names of databases that those users can '
                          'access on instance creation.'),
                        schema=properties.Schema(
                            properties.Schema.STRING,
                        ),
                        required=True,
                        constraints=[
                            constraints.Length(min=1),
                        ]
                    ),
                },
            )
        ),
        AVAILABILITY_ZONE: properties.Schema(
            properties.Schema.STRING,
            _('Name of the availability zone for DB instance.')
        ),
        RESTORE_POINT: properties.Schema(
            properties.Schema.STRING,
            _('DB instance restore point.')
        ),
        REPLICA_OF: properties.Schema(
            properties.Schema.STRING,
            _('Identifier of the source instance to replicate.'),
            support_status=support.SupportStatus(version='5.0.0')
        ),
        REPLICA_COUNT: properties.Schema(
            properties.Schema.INTEGER,
            _('The number of replicas to be created.'),
            support_status=support.SupportStatus(version='5.0.0')
        ),
    }

    attributes_schema = {
        HOSTNAME: attributes.Schema(
            _("Hostname of the instance."),
            type=attributes.Schema.STRING
        ),
        HREF: attributes.Schema(
            _("Api endpoint reference of the instance."),
            type=attributes.Schema.STRING
        ),
    }

    default_client_name = 'trove'

    def __init__(self, name, json_snippet, stack):
        super(OSDBInstance, self).__init__(name, json_snippet, stack)
        self._href = None
        self._dbinstance = None

    @property
    def dbinstance(self):
        """Get the trove dbinstance."""
        if not self._dbinstance and self.resource_id:
            self._dbinstance = self.client().instances.get(self.resource_id)

        return self._dbinstance

    def _dbinstance_name(self):
        name = self.properties[self.NAME]
        if name:
            return name

        return self.physical_resource_name()

    def handle_create(self):
        '''
        Create cloud database instance.
        '''
        self.flavor = self.client_plugin().get_flavor_id(
            self.properties[self.FLAVOR])
        self.volume = {'size': self.properties[self.SIZE]}
        self.databases = self.properties[self.DATABASES]
        self.users = self.properties[self.USERS]
        restore_point = self.properties[self.RESTORE_POINT]
        if restore_point:
            restore_point = {"backupRef": restore_point}
        zone = self.properties[self.AVAILABILITY_ZONE]
        self.datastore_type = self.properties[self.DATASTORE_TYPE]
        self.datastore_version = self.properties[self.DATASTORE_VERSION]
        replica_of = self.properties[self.REPLICA_OF]
        replica_count = self.properties[self.REPLICA_COUNT]

        # convert user databases to format required for troveclient.
        # that is, list of database dictionaries
        for user in self.users:
            dbs = [{'name': db} for db in user.get(self.USER_DATABASES, [])]
            user[self.USER_DATABASES] = dbs

        # convert networks to format required by troveclient
        nics = []
        for nic in self.properties[self.NICS]:
            nic_dict = {}
            net = nic.get(self.NET)
            if net:
                if self.is_using_neutron():
                    net_id = (self.client_plugin(
                        'neutron').find_neutron_resource(
                        nic, self.NET, 'network'))
                else:
                    net_id = (self.client_plugin(
                        'nova').get_nova_network_id(net))
                nic_dict['net-id'] = net_id
            port = nic.get(self.PORT)
            if port:
                neutron = self.client_plugin('neutron')
                nic_dict['port-id'] = neutron.find_neutron_resource(
                    self.properties, self.PORT, 'port')
            ip = nic.get(self.V4_FIXED_IP)
            if ip:
                nic_dict['v4-fixed-ip'] = ip
            nics.append(nic_dict)

        # create db instance
        instance = self.client().instances.create(
            self._dbinstance_name(),
            self.flavor,
            volume=self.volume,
            databases=self.databases,
            users=self.users,
            restorePoint=restore_point,
            availability_zone=zone,
            datastore=self.datastore_type,
            datastore_version=self.datastore_version,
            nics=nics,
            replica_of=replica_of,
            replica_count=replica_count)
        self.resource_id_set(instance.id)

        return instance.id

    def _refresh_instance(self, instance_id):
        try:
            instance = self.client().instances.get(instance_id)
            return instance
        except Exception as exc:
            if self.client_plugin().is_over_limit(exc):
                LOG.warn(_LW("Stack %(name)s (%(id)s) received an "
                             "OverLimit response during instance.get():"
                             " %(exception)s"),
                         {'name': self.stack.name,
                          'id': self.stack.id,
                          'exception': exc})
                return None
            else:
                raise

    def check_create_complete(self, instance_id):
        '''
        Check if cloud DB instance creation is complete.
        '''
        instance = self._refresh_instance(instance_id)  # refresh attributes
        if instance is None:
            return False
        if instance.status in self.BAD_STATUSES:
            raise resource.ResourceInError(
                resource_status=instance.status,
                status_reason=self.TROVE_STATUS_REASON.get(instance.status,
                                                           _("Unknown")))

        if instance.status != self.ACTIVE:
            return False
        LOG.info(_LI("Database instance %(database)s created (flavor:%("
                     "flavor)s,volume:%(volume)s, datastore:%("
                     "datastore_type)s, datastore_version:%("
                     "datastore_version)s)"),
                 {'database': self._dbinstance_name(),
                  'flavor': self.flavor,
                  'volume': self.volume,
                  'datastore_type': self.datastore_type,
                  'datastore_version': self.datastore_version})
        return True

    def handle_check(self):
        instance = self.client().instances.get(self.resource_id)
        status = instance.status
        checks = [
            {'attr': 'status', 'expected': self.ACTIVE, 'current': status},
        ]
        self._verify_check_conditions(checks)

    def handle_delete(self):
        '''
        Delete a cloud database instance.
        '''
        if not self.resource_id:
            return

        try:
            instance = self.client().instances.get(self.resource_id)
        except Exception as ex:
            self.client_plugin().ignore_not_found(ex)
        else:
            instance.delete()
            return instance.id

    def check_delete_complete(self, instance_id):
        '''
        Check for completion of cloud DB instance deletion
        '''
        if not instance_id:
            return True

        try:
            # For some time trove instance may continue to live
            self._refresh_instance(instance_id)
        except Exception as ex:
            self.client_plugin().ignore_not_found(ex)
            return True

        return False

    def validate(self):
        '''
        Validate any of the provided params
        '''
        res = super(OSDBInstance, self).validate()
        if res:
            return res

        datastore_type = self.properties[self.DATASTORE_TYPE]
        datastore_version = self.properties[self.DATASTORE_VERSION]

        self.client_plugin().validate_datastore(
            datastore_type, datastore_version,
            self.DATASTORE_TYPE, self.DATASTORE_VERSION)

        # check validity of user and databases
        users = self.properties[self.USERS]
        if users:
            databases = self.properties[self.DATABASES]
            if not databases:
                msg = _('Databases property is required if users property '
                        'is provided for resource %s.') % self.name
                raise exception.StackValidationFailed(message=msg)

            db_names = set([db[self.DATABASE_NAME] for db in databases])
            for user in users:
                missing_db = [db_name for db_name in user[self.USER_DATABASES]
                              if db_name not in db_names]

                if missing_db:
                    msg = (_('Database %(dbs)s specified for user does '
                             'not exist in databases for resource %(name)s.')
                           % {'dbs': missing_db, 'name': self.name})
                    raise exception.StackValidationFailed(message=msg)

        # check validity of NICS
        is_neutron = self.is_using_neutron()
        nics = self.properties[self.NICS]
        for nic in nics:
            if not is_neutron and nic.get(self.PORT):
                msg = _("Can not use %s property on Nova-network.") % self.PORT
                raise exception.StackValidationFailed(message=msg)

            if bool(nic.get(self.NET)) == bool(nic.get(self.PORT)):
                msg = _("Either %(net)s or %(port)s must be provided.") % {
                    'net': self.NET, 'port': self.PORT}
                raise exception.StackValidationFailed(message=msg)

    def href(self):
        if not self._href and self.dbinstance:
            if not self.dbinstance.links:
                self._href = None
            else:
                for link in self.dbinstance.links:
                    if link['rel'] == 'self':
                        self._href = link[self.HREF]
                        break

        return self._href

    def _resolve_attribute(self, name):
        if name == self.HOSTNAME:
            return self.dbinstance.hostname
        elif name == self.HREF:
            return self.href()

def resource_mapping():
    return {
        'OS::Trove::Instance': OSDBInstance,
    }


text:
@class RFLPhotoBrowser;
@protocol RFLPhotoBrowserDelegate <NSObject>
@optional
- (void)photoBrowser:(RFLPhotoBrowser *)photoBrowser didShowPhotoAtIndex:(NSUInteger)index;
- (void)photoBrowser:(RFLPhotoBrowser *)photoBrowser willDismissWithGesture:(BOOL)gesture;
- (void)photoBrowser:(RFLPhotoBrowser *)photoBrowser didDismissAtPageIndex:(NSUInteger)index;
- (void)photoBrowser:(RFLPhotoBrowser *)photoBrowser didDismissActionSheetWithButtonIndex:(NSUInteger)buttonIndex photoIndex:(NSUInteger)photoIndex;
- (RFLCaptionView *)photoBrowser:(RFLPhotoBrowser *)photoBrowser captionViewForPhotoAtIndex:(NSUInteger)index;
//custom
- (void)photoBrowser:(RFLPhotoBrowser *)photoBrowser didSelectPhotoAtIndex:(NSUInteger)index;
- (void)photoBrowser:(RFLPhotoBrowser *)photoBrowser didDeSelectPhotoAtIndex:(NSUInteger)index;
@end

// IDMPhotoBrowser
@interface RFLPhotoBrowser : UIViewController <UIScrollViewDelegate, UIActionSheetDelegate>

// Properties
@property (nonatomic, strong) id <RFLPhotoBrowserDelegate> delegate;

// Toolbar customization
@property (nonatomic) BOOL displayToolbar;
@property (nonatomic) BOOL displayCounterLabel;
@property (nonatomic) BOOL displayArrowButton;
@property (nonatomic) BOOL displayActionButton;
@property (nonatomic, strong) NSArray *actionButtonTitles;
@property (nonatomic, weak) UIImage *leftArrowImage, *leftArrowSelectedImage;
@property (nonatomic, weak) UIImage *rightArrowImage, *rightArrowSelectedImage;

// View customization
@property (nonatomic) BOOL displayDoneButton;
@property (nonatomic) BOOL useWhiteBackgroundColor;
@property (nonatomic, weak) UIImage *selectButtonImage;
@property (nonatomic, weak) UIImage *selectedButtonImage;
@property (nonatomic, weak) UIColor *trackTintColor, *progressTintColor;

@property (nonatomic, weak) UIImage *scaleImage;

@property (nonatomic) BOOL arrowButtonsChangePhotosAnimated;

@property (nonatomic) BOOL forceHideStatusBar;
@property (nonatomic) BOOL usePopAnimation;
@property (nonatomic) BOOL disableVerticalSwipe;

// defines zooming of the background (default 1.0)
@property (nonatomic) float backgroundScaleFactor;

// animation time (default .28)
@property (nonatomic) float animationDuration;

// custom radius
@property (nonatomic) float resizableImageRadius;

// Init
- (id)initWithPhotos:(NSArray *)photosArray;

// Init (animated)
- (id)initWithPhotos:(NSArray *)photosArray animatedFromView:(UIView*)view;

// With Index
- (id)initWithPhotos:(NSArray *)photosArray animatedFromView:(UIView*)view index:(NSInteger)index;

// With All Index
- (id)initWithPhotos:(NSArray *)photosArray animatedFromView:(UIView*)view index:(NSInteger)index indexes:(NSDictionary *)indexes;

// Init with NSURL objects
- (id)initWithPhotoURLs:(NSArray *)photoURLsArray;

// Init with NSURL objects (animated)
- (id)initWithPhotoURLs:(NSArray *)photoURLsArray animatedFromView:(UIView*)view;

// Reloads the photo browser and refetches data
- (void)reloadData;

// Set page that photo browser starts on
- (void)setInitialPageIndex:(NSUInteger)index;

// Get IDMPhoto at index
- (RFLPhoto *)photoAtIndex:(NSUInteger)index;

@end


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DirectGraphResultFinder.Test
{
    using Model;

    [TestClass]
    public class TestGrouping
    {
        private const int min_site_name_length = 8;
        private const int max_site_name_length = 9;

        private const int min_number_of_regions = 3;
        private const int max_number_of_regions = 5;

        private const int min_number_of_sites_in_region = 5;
        private const int max_number_of_sites_in_region = 6;

        private const int min_number_of_mesh_items = 2;
        private const int max_number_of_mesh_items = 4;

        private const int min_number_of_mesh_connections = 2;
        private const int max_number_of_mesh_connections = 5;

        private static Dictionary<string, bool> usedSiteNames { get; set; }

        private static Random randomActionHolder { get; set; }

        private static int test_seed {get;set;}

        private static Random getRandomHandle()
        {
            if (randomActionHolder == null)
            {
                if (test_seed == 0)
                {
                    randomActionHolder = new Random();
                }
                else
                {
                    randomActionHolder = new Random(test_seed);
                }
            }
            return randomActionHolder;
        }

        [TestMethod]
        public void TestRandomSiteNames()
        {
            var getRandom = getRandomHandle();
            var numberOfSites = getRandom.Next(0,32);
            var siteNames = getSiteNames(numberOfSites);
            Assert.AreEqual(numberOfSites, siteNames.Length);
        }

        [TestMethod]
        public void TestLinkTextMapping()
        {
            test_seed = 100;
            var generatedRegion = getRandomRegion();
            var linksForRegion = generatedRegion.links;
            var givenText = ProcessData.exportInformation(linksForRegion);
            var regionDataForText = ProcessData.parseGivenInput(givenText);
            var generatedMd5 = getMd5SumForLinks(linksForRegion);
            var methodMd5 = getMd5SumForLinks(regionDataForText);
            Assert.AreEqual(methodMd5, generatedMd5);
        }

        [TestMethod]
        public void TestRegionGrouping()
        {
            test_seed = 100;
            var generatedRegions = getRandomRegionData();
            var regionsResolved = ProcessData.findRegions(pullLinkDataFromRegionData(generatedRegions),null);
            var resultOfComparingRegionData = areRegionsEqual(generatedRegions, regionsResolved);
            Assert.AreEqual(true, resultOfComparingRegionData);
        }

        private static bool areRegionsEqual(DataPointRegion[] regionDataA,DataPointRegion[] regionDataB )
        {
            var sitesAreEqual = true;
            var md5SumsForRegionDataA = new List<string>();
            foreach (var region in regionDataA)
            {
                md5SumsForRegionDataA.Add(getMd5SumForRegion(region));
            }
            var md5SumsForRegionDataB = new List<string>();
            foreach (var region in regionDataB)
            {
                md5SumsForRegionDataB.Add(getMd5SumForRegion(region));
            }
            sitesAreEqual = (md5SumsForRegionDataA.Count == md5SumsForRegionDataB.Count);
            if (sitesAreEqual)
            {
                md5SumsForRegionDataA.Sort();
                md5SumsForRegionDataB.Sort();
                for (int currentRegionSearch = 0; currentRegionSearch < md5SumsForRegionDataA.Count; currentRegionSearch++)
                {
                    if (!md5SumsForRegionDataA[currentRegionSearch].Equals(md5SumsForRegionDataB[currentRegionSearch]))
                    {
                        sitesAreEqual = false;
                        break;
                    }
                }
            }
            return sitesAreEqual;
        }

        private static string getMd5SumForRegion(DataPointRegion regionToGetMd5SumFor)
        {
            return getMd5SumForLinks(regionToGetMd5SumFor.links);
        }
        private static string getMd5SumForLinks(LinkedData[] givenLinks)
        {
            var siteNamesForRegion = new List<string>();
            foreach (var link in givenLinks)
            {
                siteNamesForRegion.Add(link.pointA.name);
                siteNamesForRegion.Add(link.pointB.name);
            }
            siteNamesForRegion.Sort();

            var textBuilder = new StringBuilder();
            foreach (var site in siteNamesForRegion)
            {
                textBuilder.Append(site);
                textBuilder.Append(LinkedData.link_line_separator);
            }
            return calculateMD5Hash(textBuilder.ToString());
        }

        private static LinkedData[] pullLinkDataFromRegionData(DataPointRegion[] regionData)
        {
            var linkDataFromRegions = new List<LinkedData>();
            foreach (var region in regionData)
            {
                linkDataFromRegions.AddRange(region.links);
            }
            for (int linkPossition = 0; linkPossition < linkDataFromRegions.Count; linkPossition++)
            {
                linkDataFromRegions[linkPossition].edge_id = linkPossition;
            }
            return linkDataFromRegions.ToArray();
        }

        private static DataPointRegion[] getRandomRegionData()
        {
            var getRandomInformation = getRandomHandle();
            var numberOfRegions = getRandomInformation.Next(min_number_of_regions, max_number_of_regions);
            var regionsToReturn = new DataPointRegion[numberOfRegions];
            int currentFilterCount = 1;
            for (int regionPossition = 0; regionPossition < numberOfRegions; regionPossition++)
            {
                regionsToReturn[regionPossition] = getRandomRegion(currentFilterCount);
                currentFilterCount += regionsToReturn[regionPossition].links.Length;
            }
            return regionsToReturn;
        }

        private static DataPointRegion getRandomRegion()
        {
            return getRandomRegion(1);
        }

        private static DataPointRegion getRandomRegion(int baseToUseForUniqueEdgeIds)
        {
            var getRandomInformation = getRandomHandle();
            var totalSitesInRegion = getRandomInformation.Next(min_number_of_sites_in_region, max_number_of_sites_in_region);
            var itemsInMesh = getRandomInformation.Next(min_number_of_mesh_items, max_number_of_mesh_items);
            itemsInMesh = itemsInMesh > totalSitesInRegion ? totalSitesInRegion : itemsInMesh;
            itemsInMesh = itemsInMesh == 1 ? 2 : itemsInMesh;
            var itemsSetupAsSpur = totalSitesInRegion - itemsInMesh;
            var disconnectedSiteListForRegion = getSiteNames(totalSitesInRegion).ToList();
            var linkInfo = new List<LinkedData>();
            if (itemsInMesh > 0)
            {
                linkInfo.AddRange(getRandomMeshConnections(itemsInMesh, ref disconnectedSiteListForRegion));
            }
            if (itemsSetupAsSpur > 0)
            {
                linkInfo.AddRange(getRandomMostlySpurConnections(ref linkInfo, ref disconnectedSiteListForRegion));
            }
            linkInfo.AddRange(getLinksToEnsureSiteCanReachAllSites(ref linkInfo));
            linkInfo = simplifyLinks(ref linkInfo);
            for (int linkPossition = 0; linkPossition < linkInfo.Count; linkPossition++)
            {
                var numberForLink = baseToUseForUniqueEdgeIds + linkPossition;
                linkInfo[linkPossition].edge_id = numberForLink;
            }
            return new DataPointRegion(baseToUseForUniqueEdgeIds.ToString(),linkInfo.ToArray());
        }

        private static List<LinkedData> simplifyLinks(ref List<LinkedData> existingLinks)
        {
            var linksWithOutDuplicates = new List<LinkedData>();
            var linkedSites = new Dictionary<string, List<string>>();
            var sitesForLocation = findWhatSitesConnectTo(ref existingLinks);
            var sitesToLink = sitesForLocation.Keys.ToArray();
            foreach (var site in sitesToLink)
            {
                var connectedSites = sitesForLocation.Keys.ToArray();
                for (int connectedSite = (connectedSites.Length - 1); connectedSite >= 0; connectedSite--)
                {
                    if (!site.Equals(connectedSites[connectedSite]))
                    {
                        var sitesForLink = new List<string> { site, connectedSites[connectedSite] };
                        sitesForLink.Sort();
                        if (linkedSites.ContainsKey(sitesForLink[0]))
                        {
                            if (!linkedSites[sitesForLink[0]].Contains(sitesForLink[1]))
                            {
                                linkedSites[sitesForLink[0]].Add(sitesForLink[1]);
                                linksWithOutDuplicates.Add(new LinkedData(new DataPoint(sitesForLink[0]), new DataPoint(sitesForLink[1])));
                            }
                        }
                        else
                        {
                            linkedSites.Add(sitesForLink[0], new List<string> { sitesForLink[1] });
                            linksWithOutDuplicates.Add(new LinkedData(new DataPoint(sitesForLink[0]), new DataPoint(sitesForLink[1])));
                        }
                    }
                }
            }
            return linksWithOutDuplicates;
        }

        private static LinkedData[] getRandomMeshConnections(int numberOfSitesToMesh,ref List<string> disconnectedSites)
        {
            var linksToReturn = new List<LinkedData>();
            var getRandomInformation = getRandomHandle();
            var sitesToMesh = new List<string>();
            if (numberOfSitesToMesh < 2) throw new Exception("At least 2 sites must be allowed in order to mesh!");
            for (int sitesToHandle = (numberOfSitesToMesh-1); sitesToHandle >=0; sitesToHandle--)
            {
                var siteToMesh = disconnectedSites[sitesToHandle];
                sitesToMesh.Add(siteToMesh);
                disconnectedSites.Remove(siteToMesh);
            }
            foreach (var siteToMesh in sitesToMesh)
            {
                var numberOfMeshLinks = getRandomInformation.Next(min_number_of_mesh_connections, max_number_of_mesh_connections);
                for (int currentMeshLink = 0; currentMeshLink < numberOfMeshLinks; currentMeshLink++)
                {
                    var secondMeshPoints = siteToMesh;
                    while (secondMeshPoints.Equals(siteToMesh))
                    {
                        var possitionToLinkWith = (getRandomInformation.Next(0, sitesToMesh.Count));
                        secondMeshPoints = sitesToMesh[possitionToLinkWith];
                    }
                    linksToReturn.Add(new LinkedData(new DataPoint(siteToMesh), new DataPoint(secondMeshPoints)));
                }
            }
            linksToReturn.AddRange(getConnectionsNeededForMesh(ref linksToReturn, sitesToMesh));
            return linksToReturn.ToArray();
        }

        private static LinkedData[] getConnectionsNeededForMesh(ref List<LinkedData> existingLinks, List<string> allSites)
        {
            var linksToMakeFullMesh = new List<LinkedData>();
            var sitesConnected = findWhatSitesConnectTo(ref existingLinks);
            foreach (var siteConnection in sitesConnected)
            {
                foreach (var sitesToConfirmMeshed in allSites)
                {
                    if(!siteConnection.Value.Contains(sitesToConfirmMeshed))
                    {
                        linksToMakeFullMesh.Add(new LinkedData(new DataPoint(siteConnection.Key), new DataPoint(sitesToConfirmMeshed)));
                    }
                }
            }
            return linksToMakeFullMesh.ToArray();
        }

        private static LinkedData[] getLinksToEnsureSiteCanReachAllSites(ref List<LinkedData> existingLinks)
        {
            return getLinksToEnsureSiteCanReachAllSites(existingLinks[0].pointA.name,ref existingLinks);
        }
        private static LinkedData[] getLinksToEnsureSiteCanReachAllSites(string siteToConfirmCanReachAllSites,ref List<LinkedData> existingLinks)
        {
            var missingLinksForSite = new List<LinkedData>();
            var sitesFromLinks = findWhatSitesConnectTo(ref existingLinks);
            var allSites = sitesFromLinks.Keys.ToArray();
            var currentConnections = sitesFromLinks[siteToConfirmCanReachAllSites];
            foreach (var site in allSites)
            {
                if (!currentConnections.Contains(site))
                {
                    missingLinksForSite.Add(new LinkedData(new DataPoint(siteToConfirmCanReachAllSites), new DataPoint(site)));
                }
            }
            return missingLinksForSite.ToArray();
        }

        private static Dictionary<string, List<string>> findWhatSitesConnectTo(ref List<LinkedData> givenDataPoints)
        {
            var siteWIthWhatItsConnectedTo = new Dictionary<string, List<string>>();
            foreach (var link in givenDataPoints)
            {
                if (siteWIthWhatItsConnectedTo.ContainsKey(link.pointA.name))
                {
                    siteWIthWhatItsConnectedTo[link.pointA.name].Add(link.pointB.name);
                }
                else
                {
                    siteWIthWhatItsConnectedTo.Add(link.pointA.name, new List<string> { link.pointB.name });
                }
                if (siteWIthWhatItsConnectedTo.ContainsKey(link.pointB.name))
                {
                    siteWIthWhatItsConnectedTo[link.pointB.name].Add(link.pointA.name);
                }
                else
                {
                    siteWIthWhatItsConnectedTo.Add(link.pointB.name, new List<string> { link.pointA.name });
                }
            }
            return siteWIthWhatItsConnectedTo;
        }

        private static LinkedData[] getRandomMostlySpurConnections(ref List<LinkedData> existingLinks,ref List<string> disconnectedSites)
        {
            var linksToReturn = new LinkedData[disconnectedSites.Count];
            var getRandomInformation = getRandomHandle();
            for (int currentSpurPos = (disconnectedSites.Count - 1); currentSpurPos >= 0; currentSpurPos--)
            {
                var firstConnectionPoint = new DataPoint();
                var secondConnectionPoint = new DataPoint(disconnectedSites[currentSpurPos]);
                disconnectedSites.RemoveAt(currentSpurPos);
                var connectToExistingPointA = (getRandomInformation.Next(0, 1) > 0);
                if (existingLinks.Count == 0)
                {
                    var existingLinkToUse = existingLinks[getRandomInformation.Next(0, (existingLinks.Count - 1))];
                    firstConnectionPoint.name = connectToExistingPointA  ? existingLinkToUse.pointA.name:existingLinkToUse.pointB.name;
                    firstConnectionPoint.name = currentSpurPos == 0 ? linksToReturn[linksToReturn.Length - 1].pointB.name : disconnectedSites[0];
                }
                else
                {
                    var existingLinkToUse = existingLinks[getRandomInformation.Next(0, (existingLinks.Count - 1))];
                    firstConnectionPoint.name = connectToExistingPointA  ? existingLinkToUse.pointA.name:existingLinkToUse.pointB.name;
                }
                linksToReturn[currentSpurPos] = new LinkedData(firstConnectionPoint, secondConnectionPoint);

            }
            return linksToReturn;
        }

        private static string[] getSiteNames(int numberOfSites)
        {
            var siteNames = new string[numberOfSites];
            for (int sitePosition = 0; sitePosition < numberOfSites; sitePosition++)
            {
                siteNames[sitePosition] = getRandomSiteName();
            }
            return siteNames;
        }

        private static string getRandomSiteName()
        {
            if (usedSiteNames == null)
            {
                usedSiteNames = new Dictionary<string, bool>();
            }
            var getRandomInformation = getRandomHandle();
            var siteNameString = String.Empty;
            while (String.IsNullOrEmpty(siteNameString) || usedSiteNames.ContainsKey(siteNameString))
            {
                var siteNameLength = getRandomInformation.Next(min_site_name_length, max_site_name_length);
                var siteNmae = new char[siteNameLength];
                for (int siteLetterPos = 0; siteLetterPos < siteNameLength; siteLetterPos++)
                {
                    siteNmae[siteLetterPos] = (char)('a' + getRandomInformation.Next(0, 26));
                }
                siteNameString = new string(siteNmae);
            }
            usedSiteNames.Add(siteNameString, true);
            return siteNameString;
        }

        private static string calculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            var md5 = System.Security.Cryptography.MD5.Create();
            var inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            var hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            var sb = new StringBuilder();
            for (int charInHash = 0; charInHash < hash.Length; charInHash++)
            {
                sb.Append(hash[charInHash].ToString("X2"));
            }
            return sb.ToString();
        }

    }
}


text:
/*
 * Do not modify this file. This file is generated from the directconnect-2012-10-25.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.DirectConnect.Model
{
    /// <summary>
    /// A virtual interface (VLAN) transmits the traffic between the AWS Direct Connect location
    /// and the customer.
    /// </summary>
    public partial class CreatePublicVirtualInterfaceResponse : AmazonWebServiceResponse
    {
        private string _amazonAddress;
        private int? _asn;
        private string _authKey;
        private string _connectionId;
        private string _customerAddress;
        private string _customerRouterConfig;
        private string _location;
        private string _ownerAccount;
        private List<RouteFilterPrefix> _routeFilterPrefixes = new List<RouteFilterPrefix>();
        private string _virtualGatewayId;
        private string _virtualInterfaceId;
        private string _virtualInterfaceName;
        private VirtualInterfaceState _virtualInterfaceState;
        private string _virtualInterfaceType;
        private int? _vlan;

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

        // Check to see if AmazonAddress property is set
        internal bool IsSetAmazonAddress()
        {
            return this._amazonAddress != null;
        }

        /// <summary>
        /// Gets and sets the property Asn.
        /// </summary>
        public int Asn
        {
            get { return this._asn.GetValueOrDefault(); }
            set { this._asn = value; }
        }

        // Check to see if Asn property is set
        internal bool IsSetAsn()
        {
            return this._asn.HasValue;
        }

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

        // Check to see if AuthKey property is set
        internal bool IsSetAuthKey()
        {
            return this._authKey != null;
        }

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

        // Check to see if ConnectionId property is set
        internal bool IsSetConnectionId()
        {
            return this._connectionId != null;
        }

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

        // Check to see if CustomerAddress property is set
        internal bool IsSetCustomerAddress()
        {
            return this._customerAddress != null;
        }

        /// <summary>
        /// Gets and sets the property CustomerRouterConfig.
        /// <para>
        /// Information for generating the customer router configuration.
        /// </para>
        /// </summary>
        public string CustomerRouterConfig
        {
            get { return this._customerRouterConfig; }
            set { this._customerRouterConfig = value; }
        }

        // Check to see if CustomerRouterConfig property is set
        internal bool IsSetCustomerRouterConfig()
        {
            return this._customerRouterConfig != null;
        }

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

        // Check to see if Location property is set
        internal bool IsSetLocation()
        {
            return this._location != null;
        }

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

        // Check to see if OwnerAccount property is set
        internal bool IsSetOwnerAccount()
        {
            return this._ownerAccount != null;
        }

        /// <summary>
        /// Gets and sets the property RouteFilterPrefixes.
        /// </summary>
        public List<RouteFilterPrefix> RouteFilterPrefixes
        {
            get { return this._routeFilterPrefixes; }
            set { this._routeFilterPrefixes = value; }
        }

        // Check to see if RouteFilterPrefixes property is set
        internal bool IsSetRouteFilterPrefixes()
        {
            return this._routeFilterPrefixes != null && this._routeFilterPrefixes.Count > 0;
        }

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

        // Check to see if VirtualGatewayId property is set
        internal bool IsSetVirtualGatewayId()
        {
            return this._virtualGatewayId != null;
        }

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

        // Check to see if VirtualInterfaceId property is set
        internal bool IsSetVirtualInterfaceId()
        {
            return this._virtualInterfaceId != null;
        }

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

        // Check to see if VirtualInterfaceName property is set
        internal bool IsSetVirtualInterfaceName()
        {
            return this._virtualInterfaceName != null;
        }

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

        // Check to see if VirtualInterfaceState property is set
        internal bool IsSetVirtualInterfaceState()
        {
            return this._virtualInterfaceState != null;
        }

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

        // Check to see if VirtualInterfaceType property is set
        internal bool IsSetVirtualInterfaceType()
        {
            return this._virtualInterfaceType != null;
        }

        /// <summary>
        /// Gets and sets the property Vlan.
        /// </summary>
        public int Vlan
        {
            get { return this._vlan.GetValueOrDefault(); }
            set { this._vlan = value; }
        }

        // Check to see if Vlan property is set
        internal bool IsSetVlan()
        {
            return this._vlan.HasValue;
        }

    }
}


text:
/*
 *  Written for the Pkcs11Interop project by:
 *  Jaroslav IMRICH <jimrich@jimrich.sk>
 */

using System;
using System.Collections.Generic;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI.MechanismParams;
using Net.Pkcs11Interop.LowLevelAPI41.MechanismParams;

// Note: Code in this file is maintained manually.

namespace Net.Pkcs11Interop.HighLevelAPI41.MechanismParams
{
    /// <summary>
    /// Parameters for OTP mechanisms in a generic fashion
    /// </summary>
    public class CkOtpParams : ICkOtpParams
    {
        /// <summary>
        /// Flag indicating whether instance has been disposed
        /// </summary>
        private bool _disposed = false;

        /// <summary>
        /// Low level mechanism parameters
        /// </summary>
        private CK_OTP_PARAMS _lowLevelStruct = new CK_OTP_PARAMS();

        /// <summary>
        /// Initializes a new instance of the CkOtpParams class.
        /// </summary>
        /// <param name='parameters'>List of OTP parameters</param>
        public CkOtpParams(List<ICkOtpParam> parameters)
        {
            _lowLevelStruct.Params = IntPtr.Zero;
            _lowLevelStruct.Count = 0;

            if ((parameters != null) && (parameters.Count > 0))
            {
                // Allocate memory for parameters
                int ckOtpParamSize = UnmanagedMemory.SizeOf(typeof(CK_OTP_PARAM));
                _lowLevelStruct.Params = UnmanagedMemory.Allocate(ckOtpParamSize * parameters.Count);
                _lowLevelStruct.Count = ConvertUtils.UInt32FromInt32(parameters.Count);

                // Copy paramaters to allocated memory
                for (int i = 0; i < parameters.Count; i++)
                {
                    IntPtr tempPointer = new IntPtr(_lowLevelStruct.Params.ToInt64() + (i * ckOtpParamSize));
                    UnmanagedMemory.Write(tempPointer, parameters[i].ToMarshalableStructure());
                }
            }
        }

        #region IMechanismParams

        /// <summary>
        /// Returns managed object that can be marshaled to an unmanaged block of memory
        /// </summary>
        /// <returns>A managed object holding the data to be marshaled. This object must be an instance of a formatted class.</returns>
        public object ToMarshalableStructure()
        {
            if (this._disposed)
                throw new ObjectDisposedException(this.GetType().FullName);

            return _lowLevelStruct;
        }

        #endregion

        #region IDisposable

        /// <summary>
        /// Disposes object
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Disposes object
        /// </summary>
        /// <param name="disposing">Flag indicating whether managed resources should be disposed</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    // Dispose managed objects
                }

                // Dispose unmanaged objects
                UnmanagedMemory.Free(ref _lowLevelStruct.Params);
                _lowLevelStruct.Count = 0;

                _disposed = true;
            }
        }

        /// <summary>
        /// Class destructor that disposes object if caller forgot to do so
        /// </summary>
        ~CkOtpParams()
        {
            Dispose(false);
        }

        #endregion
    }
}


text:
// Copyright 2010 Aqua Bird Consulting (http://www.aquabirdconsulting.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://github.com/khalidabuhakmeh/FluentSitemap
namespace FluentSitemap.Core
{
    public static class It
    {
        public static T Is<T>()
        {
            return default(T);
        }
    }
}


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

namespace Artemis.Engine
{
    /// <summary>
    /// An exception that occurs when something goes wrong whilst registering a multiform.
    /// </summary>
    public class MultiformRegistrationException : Exception
    {
    	public MultiformRegistrationException() : base() { }
    	public MultiformRegistrationException(string msg) : base(msg) { }
    	public MultiformRegistrationException(string msg, Exception inner) : base(msg, inner) { }
    	public MultiformRegistrationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
    }
}


text:
/**
 *
 */
package fr.upem.lgtools.parser.arcstandard;

import fr.upem.lgtools.parser.Configuration;
import fr.upem.lgtools.parser.Container;
import fr.upem.lgtools.parser.DepTree;
import fr.upem.lgtools.text.Unit;

/**
 * @author Mathieu
 *
 */
public class LeftArcTransitionWithImplicitComplete extends LeftArcTransition {
	boolean withImplicit = false;

	public LeftArcTransitionWithImplicitComplete(String type, String label) {
		super(type, label);
	}

	Unit getTargetUnitForCompletion(Configuration<DepTree> configuration){
		Container stack = configuration.getFirstStack();
		Unit u0 = stack.pop();
		Unit u = stack.peekFirst();
		stack.push(u0);
		return ParserUtils.getLexicalUnitFromComponent(u, configuration.getAnalyses(), configuration.getSentence());

	}

	void completeUnit(Unit u,Configuration<DepTree> configuration){
		Container stack = configuration.getSecondStack();
		Unit u0 = stack.pop();
		Unit u1 = stack.pop();
		//System.err.println("LA:");
		//System.err.println(configuration);
		//System.err.println(u+" "+u0+" "+u1);
		if(u == u0){
			stack.push(u1);
			return;
		}
		else{
			if(u == u1){
			   stack.push(u0);
			   return;
			}
		}
		throw new IllegalStateException("Cannot complete top-1 or top-2 element in lexical stack during implicit complete!");
	}

	@Override
	public Configuration<DepTree> perform(Configuration<DepTree> configuration) {
		Unit u = getTargetUnitForCompletion(configuration);
		withImplicit = false;
		configuration = super.perform(configuration);

		if(ParserUtils.unitIsSyntacticallyCompleted(u, configuration.getAnalyses(),configuration.getSentence())){
			completeUnit(u,configuration);
			withImplicit = true;
		}
		return configuration;
	}

	@Override
	public String toString(){
		String res = super.toString();
		return withImplicit?res+"-CMP":res;
	}

}


text:
module.exports = {
    Context : require('./Context')
};


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Update_experiment extends CI_Migration {

	public function up()
	{
		$fields = array(
			'date_start' => array('type' => 'DATE', 'null' => TRUE),
			'date_end' => array('type' => 'DATE', 'null' => TRUE),
			'target_nr_participants' => array('type' => 'INT', 'constraint' => 11),
		);

		$this->dbforge->add_column('experiment', $fields);
	}

	public function down()
	{
		$this->dbforge->drop_column('experiment', 'date_start');
		$this->dbforge->drop_column('experiment', 'date_end');
		$this->dbforge->drop_column('experiment', 'target_nr_participants');
	}
}


text:
recipesApp.controller('SingleRecipeController', function SingleRecipeController($scope, $routeParams, requester, $location) {
    'use strict';

    $scope.like = function() {
        if ($scope.likeText == 'Dislike') {
            $scope.likeText = 'Like';
            $scope.recipe.RecipeLikes--;
        }
        else {
            $scope.likeText = 'Dislike';
            $scope.recipe.RecipeLikes++;
        }

        requester.actions.like($scope.recipe.Id);
    };

    function refresh(){
        requester.recipe.byId($routeParams.id).then(function(data){
            $scope.recipe = data;
            if ($scope.recipe.Liked == true) {
                $scope.likeText = 'Dislike';
            }
            else {
                $scope.likeText = 'Like';
            }
        });
    }

    refresh();

    $scope.addComment = function(commentText) {
        requester.actions.comment($scope.recipe.Id, commentText).then(function() {
            $scope.commentText = '';
            refresh();
        })
    }
});


text:
package com.google.cloud.teleport.v2.utils;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.cloud.teleport.v2.options.DataplexBigQueryToGcsOptions;
import com.google.cloud.teleport.v2.utils.WriteDisposition.WriteDispositionException;
import com.google.cloud.teleport.v2.values.BigQueryTable;
import com.google.cloud.teleport.v2.values.BigQueryTablePartition;
import com.google.common.base.Splitter;
import com.google.re2j.Pattern;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.joda.time.Instant;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Filter to exclude unwanted tables and partitions. */
public class DataplexBigQueryToGcsFilter implements BigQueryMetadataLoader.Filter {
  private static final Logger LOG = LoggerFactory.getLogger(DataplexBigQueryToGcsFilter.class);
  private static final Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();

  private final Instant maxLastModifiedTime;
  private final Set<String> includeTables;
  private final Pattern includePartitions;
  private final String writeDisposition;
  private final String fileSuffix;
  private final List<String> existingTargetFiles;
  private final BigQueryToGcsDirectoryNaming directoryNaming;

  public DataplexBigQueryToGcsFilter(
      DataplexBigQueryToGcsOptions options, List<String> existingTargetFiles) {
    String dateTime = options.getExportDataModifiedBeforeDateTime();
    if (dateTime != null && !dateTime.isEmpty()) {
      if (dateTime.startsWith("-P") || dateTime.startsWith("-p")) {
        this.maxLastModifiedTime = Instant.now().plus(Duration.parse(dateTime).toMillis());
      } else {
        this.maxLastModifiedTime =
            Instant.parse(dateTime, ISODateTimeFormat.dateOptionalTimeParser());
      }
    } else {
      this.maxLastModifiedTime = null;
    }

    String tableRefs = options.getTables();
    if (tableRefs != null && !tableRefs.isEmpty()) {
      List<String> tableRefList = SPLITTER.splitToList(tableRefs);
      checkArgument(
          !tableRefList.isEmpty(),
          "Got an non-empty tables param '%s', but couldn't parse it into a valid table list,"
              + " please check its format.",
          tableRefs);
      this.includeTables = new HashSet<>(tableRefList);
    } else {
      this.includeTables = null;
    }

    String partitionRegExp = options.getPartitionIdRegExp();
    if (partitionRegExp != null && !partitionRegExp.isEmpty()) {
      this.includePartitions = Pattern.compile(partitionRegExp);
    } else {
      this.includePartitions = null;
    }

    this.writeDisposition = options.getWriteDisposition().getWriteDispositionOption();
    this.fileSuffix = options.getFileFormat().getFileSuffix();
    this.existingTargetFiles = existingTargetFiles;
    this.directoryNaming = new BigQueryToGcsDirectoryNaming(options.getEnforceSamePartitionKey());
  }

  private boolean shouldSkipTableName(BigQueryTable.Builder table) {
    if (includeTables != null && !includeTables.contains(table.getTableName())) {
      return true;
    }
    return false;
  }

  private boolean shouldSkipFile(String table, String partition, String path) {
    String identifier = partition == null ? table : table + "$" + partition;
    switch (writeDisposition) {
      case "FAIL":
        throw new WriteDispositionException(
            String.format(
                "Target File %s exists for %s. Failing according to writeDisposition = %s.",
                path, identifier, writeDisposition));
      case "SKIP":
        LOG.info(
            "Target File {} exists for {}. Skipping according to writeDisposition = {}.",
            path,
            identifier,
            writeDisposition);
        return true;
      case "OVERWRITE":
        LOG.info(
            "Target File {} exists for {}. Overwriting according to writeDisposition = {}.",
            path,
            identifier,
            writeDisposition);
        return false;
      default:
        throw new UnsupportedOperationException(
            writeDisposition + " writeDisposition not implemented");
    }
  }

  @Override
  public boolean shouldSkipUnpartitionedTable(BigQueryTable.Builder table) {
    if (shouldSkipTableName(table)) {
      return true;
    }
    // Check the last modified time only for NOT partitioned table.
    // If a table is partitioned, we check the last modified time on partition level only.
    if (maxLastModifiedTime != null
        // BigQuery timestamps are in microseconds so / 1000.
        && maxLastModifiedTime.isBefore(table.getLastModificationTime() / 1000)) {
      return true;
    }
    // Check if the target file already exists.
    String expectedTargetPath = tableTargetFileName(table);
    if (existingTargetFiles.contains(expectedTargetPath)) {
      return shouldSkipFile(table.getTableName(), null, expectedTargetPath);
    }
    return false;
  }

  @Override
  public boolean shouldSkipPartitionedTable(
      BigQueryTable.Builder table, List<BigQueryTablePartition> partitions) {
    if (shouldSkipTableName(table)) {
      return true;
    }
    if (partitions.isEmpty()) {
      LOG.info(
          "Skipping table {}: "
              + "table is partitioned, but no eligible partitions found => nothing to export.",
          table.getTableName());
      return true;
    }
    return false;
  }

  @Override
  public boolean shouldSkipPartition(
      BigQueryTable.Builder table, BigQueryTablePartition partition) {
    if (maxLastModifiedTime != null
        // BigQuery timestamps are in microseconds so / 1000.
        && maxLastModifiedTime.isBefore(partition.getLastModificationTime() / 1000)) {
      return true;
    }
    if (includePartitions != null && !includePartitions.matches(partition.getPartitionName())) {
      LOG.info(
          "Skipping partition {} not matching regexp: {}",
          partition.getPartitionName(),
          includePartitions.pattern());
      return true;
    }
    // Check if target file already exists.
    String expectedTargetPath = partitionTargetFileName(table, partition);
    if (existingTargetFiles.contains(expectedTargetPath)) {
      return shouldSkipFile(table.getTableName(), partition.getPartitionName(), expectedTargetPath);
    }
    return false;
  }

  public String tableTargetFileName(BigQueryTable.Builder table) {
    String dirName = directoryNaming.getTableDirectory(table.getTableName());
    String fileName =
        new BigQueryToGcsFileNaming(fileSuffix, table.getTableName())
            .getFilename(null, null, 0, 0, null);
    return dirName + "/" + fileName;
  }

  public String partitionTargetFileName(
      BigQueryTable.Builder table, BigQueryTablePartition partition) {
    String dirName =
        directoryNaming.getPartitionDirectory(
            table.getTableName(), partition.getPartitionName(), table.getPartitioningColumn());
    String fileName =
        new BigQueryToGcsFileNaming(fileSuffix, table.getTableName(), partition.getPartitionName())
            .getFilename(null, null, 0, 0, null);
    return dirName + "/" + fileName;
  }
}


text:
<?php

$addressData = include __DIR__ . '/address_data.php';

$billingAddress = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
    'Magento\Sales\Model\Order\Address',
    ['data' => $addressData]
);
$billingAddress->setAddressType('billing');

$shippingAddress = clone $billingAddress;
$shippingAddress->setId(null)->setAddressType('shipping');

$payment = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Sales\Model\Order\Payment');
$payment->setMethod('payflowpro')->setCcExpMonth('5')->setCcLast4('0005')->setCcType('AE')->setCcExpYear('2016');

$order = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Sales\Model\Order');
$order->setIncrementId(
    '100000001'
)->setSubtotal(
    100
)->setBaseSubtotal(
    100
)->setCustomerEmail(
    'admin@example.com'
)->setCustomerIsGuest(
    true
)->setBillingAddress(
    $billingAddress
)->setShippingAddress(
    $shippingAddress
)->setStoreId(
    \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
        'Magento\Store\Model\StoreManagerInterface'
    )->getStore()->getId()
)->setPayment(
    $payment
);

$order->save();


text:
<?php
	Ini_Set( 'display_errors', true );
	include '../../init.php';

	$plex_url = composeUrl($GLOBALS["config"]["networkDetails"]["wanDomain"], $GLOBALS["config"]["services"]["plex"]["subdomain"]);
	$plexSessionXML = simplexml_load_file($plex_url.'status/sessions?X-Plex-Token=' . $GLOBALS["config"]["apiKeys"]["plexAuthToken"]);

	$plexSessionID = $_GET['id'];

	$duration = $plexSessionXML->Video[$plexSessionID]['duration'];
	$viewOffset = $plexSessionXML->Video[$plexSessionID]['viewOffset'];
	$progress = sprintf('%.0f',($viewOffset / $duration) * 100);

	return $progress;
?>


text:
* Access control list (ACL) security is always on

### Encrypted Communications

* Transport layer security (TLS) over TCP command channel
* UDP data channel traffic secured via AES keys exchanged over TCL command channel

### Strong Identity Validation

* X.509 certificates
* Self-signed certificates

### Publisher Initiated Security Considerations

How does publisher initiated connection, to cross security zones in desired direction, affect identity validation and TLS?

### Access Control Lists

* Allow/deny for specific points (data point explicit)
* Allow/deny for group with specific points (group explicit)
* Allow/deny for filter expression (filter implicit)
* Allow/deny for group with filter expression (group implicit)

#### Expression based Access Control

* Expressions can be used to define filters and groups
* How do filters work against extensible metadata, missing columns?

#### Access Control Precedence

* (1) Data Point Explicit
* (2) Group Explicit
* (3) Filter Implicit
* (4) Group Implicit


text:
package com.nokia.springboot.training.d03.s02.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.nokia.springboot.training.d03.s02")
//@EnableJdbcHttpSession
public class AppConfig {
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Couchbase.Linq.Metadata;

namespace Couchbase.Linq.Extensions
{
    // UseXXX extensions

    public static partial class QueryExtensions
    {
        #region UseKeys

        /// <summary>
        ///     Filters documents based on a list of keys
        /// </summary>
        /// <typeparam name="T">Type of the items being filtered</typeparam>
        /// <param name="items">Items being filtered</param>
        /// <param name="keys">Keys to be selected</param>
        /// <returns>Modified IQueryable</returns>
        public static IQueryable<T> UseKeys<T>(
            this IQueryable<T> items,
            IEnumerable<string> keys)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }
            if (keys == null)
            {
                throw new ArgumentNullException(nameof(keys));
            }

            if (items is EnumerableQuery<T>)
            {
                // If outer is an IEnumerable converted to IQueryable via AsQueryable
                // Then we need to just call the IEnumerable implementation

                if (!typeof(IDocumentMetadataProvider).IsAssignableFrom(typeof(T)))
                {
                    throw new NotSupportedException("Items Sequence Must Implement IDocumentMetadataProvider To Function With EnumerableQuery<T>");
                }

                var methodCall =
                    Expression.Call(
                        EnumerableExtensionMethods.UseKeys.MakeGenericMethod(typeof(T)),
                        Expression.Constant(items, typeof(IEnumerable<T>)),
                        Expression.Constant(keys, typeof(IEnumerable<string>)));

                return items.Provider.CreateQuery<T>(
                    Expression.Call(
                        typeof(Queryable).GetMethods().First(p => p.Name == "AsQueryable" && p.GetGenericArguments().Length == 1)
                            .MakeGenericMethod(typeof(T)),
                        methodCall));
            }
            else
            {
                return items.Provider.CreateQuery<T>(
                    Expression.Call(
                        QueryExtensionMethods.UseKeys.MakeGenericMethod(typeof(T)),
                        items.Expression,
                        GetSourceExpression(keys)));
            }
        }

        #endregion

        #region UseIndex

        /// <summary>
        /// Provides an index hint to the query engine.
        /// </summary>
        /// <typeparam name="T">Type of items being queried.</typeparam>
        /// <param name="source">Items being queried.</param>
        /// <param name="indexName">Name of the index to use.</param>
        /// <returns>Modified IQueryable</returns>
        public static IQueryable<T> UseIndex<T>(this IQueryable<T> source, string indexName) =>
            source.UseIndex(indexName, N1QlIndexType.Gsi);

        /// <summary>
        /// Provides an index hint to the query engine.
        /// </summary>
        /// <typeparam name="T">Type of items being queried.</typeparam>
        /// <param name="source">Items being queried.</param>
        /// <param name="indexName">Name of the index to use.</param>
        /// <param name="indexType">Type of the index to use.</param>
        /// <returns>Modified IQueryable</returns>
        public static IQueryable<T> UseIndex<T>(this IQueryable<T> source, string indexName, N1QlIndexType indexType)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (indexType < N1QlIndexType.Gsi || indexType > N1QlIndexType.View)
            {
                throw new ArgumentOutOfRangeException(nameof(indexType));
            }

            return source.Provider.CreateQuery<T>(
                Expression.Call(
                    QueryExtensionMethods.UseIndexWithType.MakeGenericMethod(typeof(T)),
                    source.Expression,
                    Expression.Constant(indexName),
                    Expression.Constant(indexType)));
        }

        #endregion

        #region Use Hash

        /// <summary>
        /// Provides an hash join hint to the query engine.
        /// </summary>
        /// <typeparam name="T">Type of items being queried.</typeparam>
        /// <param name="source">Items being queried.</param>
        /// <param name="type">Type of hash hint to provide.</param>
        /// <returns>Modified IQueryable</returns>
        /// <remarks>Only valid when using Couchbase Server 5.5 Enterprise Edition (or later).  Not supported by Community Edition.</remarks>
        public static IQueryable<T> UseHash<T>(this IQueryable<T> source, HashHintType type)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (type < HashHintType.Build || type > HashHintType.Probe)
            {
                throw new ArgumentOutOfRangeException(nameof(type));
            }

            return source.Provider.CreateQuery<T>(
                Expression.Call(
                    QueryExtensionMethods.UseHash.MakeGenericMethod(typeof(T)),
                    source.Expression,
                    Expression.Constant(type)));
        }

        #endregion
    }
}


text:
[`djes`](https://github.com/theonion/djes) + [`drf`](https://github.com/tomchristie/django-rest-framework) = one legit api

## WTF is `djesrf`?

`djesrf` is an open source, reusable Django application the combines [`djes`](https://github.com/theonion/djes) and
[`drf`](https://github.com/tomchristie/django-rest-framework) to provide Django RESTful APIs driven by Elasticsearch!

## Contribute to `djesrf`!

* Read and clone the source at [https://github.com/theonion/djesrf](https://github.com/theonion/djesrf)
* Open an issue at [https://github.com/theonion/djesrf/issues](https://github.com/theonion/djesrf/issues)

## Licensing

`djesrf` is MIT licensed, so you can freely use this software in open and proprietary projects!