text:
package org.axonframework.integrationtests.polymorphic;

import org.axonframework.modelling.command.TargetAggregateIdentifier;

/**
 * The common command for both first level children. Command handler for it is placed on abstract parent.
 *
 * @author Milan Savic
 */
public class CommonCommand {

    @TargetAggregateIdentifier
    private final String id;

    public CommonCommand(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package brooklyn.location.cloud;

import java.util.Map;

import brooklyn.config.ConfigKey;
import brooklyn.entity.Entity;
import brooklyn.entity.basic.ConfigKeys;
import brooklyn.entity.basic.EntityInternal;
import brooklyn.util.config.ConfigBag;
import brooklyn.util.text.Strings;
import brooklyn.util.text.TemplateProcessor;

import com.google.common.collect.ImmutableMap;
import com.google.common.reflect.TypeToken;

public class CustomMachineNamer extends CloudMachineNamer {

    public static final ConfigKey<String> MACHINE_NAME_TEMPLATE = ConfigKeys.newStringConfigKey("custom.machine.namer.machine",
            "Freemarker template format for custom machine name", "${entity.displayName}");
    @SuppressWarnings("serial")
    public static final ConfigKey<Map<String, ?>> EXTRA_SUBSTITUTIONS = ConfigKeys.newConfigKey(new TypeToken<Map<String, ?>>() {},
            "custom.machine.namer.substitutions", "Additional substitutions to be used in the template", ImmutableMap.<String, Object>of());

    public CustomMachineNamer(ConfigBag setup) {
        super(setup);
    }

    @Override
    public String generateNewMachineUniqueName() {
        Object context = setup.peek(CloudLocationConfig.CALLER_CONTEXT);
        Entity entity = null;
        if (context instanceof Entity) {
            entity = (Entity) context;
        }

        String template = this.setup.get(MACHINE_NAME_TEMPLATE);

        String processed;
        if (entity == null) {
            processed = TemplateProcessor.processTemplateContents(template, this.setup.get(EXTRA_SUBSTITUTIONS));
        } else {
            processed = TemplateProcessor.processTemplateContents(template, (EntityInternal)entity, this.setup.get(EXTRA_SUBSTITUTIONS));
        }

        processed = Strings.removeFromStart(processed, "#ftl\n");

        return sanitize(processed);
    }

    @Override
    public String generateNewMachineUniqueNameFromGroupId(String groupId) {
        return generateNewMachineUniqueName();
    }
}


text:
module NewRelic
  module Plugin
#
# Primary newrelic_plugin agent.
#
# Author:: Lee Atchison <lee@newrelic.com>
# Copyright:: Copyright (c) 2012 New Relic, Inc.
#
    module Agent
      class Base
        class << self
          attr_reader :label,:instance_label_proc,:guid,:version
          attr_accessor :config_options_list

          #
          # Define the GUID for this agent.
          #
          def agent_guid str
            raise "Did not set GUID" if str.nil? or str==""
            @guid=str
          end

          #
          # Define version for this agent
          #
          def agent_version str
            @version = str
          end

          #
          #
          # Human Readable labels for plugin.
          #   label - Name of the plugin
          #   block return - Name of a particular instance of a plugin component.
          #
          #
          def agent_human_labels label,&block
            @label=label
            @instance_label_proc=block
          end

          #
          #
          # Support for single instance, non-configurable agents.
          #
          #
          def no_config_required
            @no_config_required=true
          end
          def config_required?
            !@no_config_required
          end

          #
          #
          # Specify name of configuration values used in plugin implementation.
          #
          #
          def agent_config_options *args
            @config_options_list||=[]
            args.each do |config|
              attr_accessor config
              @config_options_list << config
            end
          end
        end

        #
        # Instance Info
        #
        attr_reader :name,:agent_info
        def guid
          return @guid if @guid
          @guid=self.class.guid
          #
          # Verify GUID is set correctly...
          #
          if @guid=="guid" or @guid=="_TYPE_YOUR_GUID_HERE_"
            #this feels tightly coupled to the config class, testing this is difficult, thinking about refactoring (NH)
            @guid = NewRelic::Plugin::Config.config.newrelic['guids'][agent_info[:ident].to_s] if NewRelic::Plugin::Config.config.newrelic['guids']
            puts "NOTE: GUID updated for #{instance_label} at run-time to '#{@guid}'"
          end
          raise "Did not set GUID" if @guid.nil? or @guid=="" or @guid=="guid" or @guid=="_TYPE_YOUR_GUID_HERE_"
          @guid
        end
        def version
          self.class.version
        end
        def label
          self.class.label
        end
        #
        # Instantiate a newrelic_plugin instance
        def initialize name,agent_info,options={}
          @name=name
          @agent_info=agent_info
          @ident=agent_info[:ident]
          @options=options
          if self.class.config_options_list
            self.class.config_options_list.each do |config|
              self.send("#{config}=",options[config])
            end
          end
          @last_time=nil

          #
          # Run agent-specific metric setup, if necessary
          setup_metrics if respond_to? :setup_metrics
        end
        def instance_label
          if !respond_to? :instance_label_proc_method
            mod=Module.new
            mod.send :define_method,:instance_label_proc_method,self.class.instance_label_proc
            self.extend mod
          end
          self.instance_label_proc_method
        end

        #
        #
        # Setup & Report Metrics
        #
        #
        def report_metric metric_name,units,value,opts={}
          return if value.nil?
          @data_collector.add_data metric_name,units,value.to_f,opts
        end

        #
        #
        # Execute a poll cycle
        #
        #
        def run poll_interval
          #
          # Start of cycle work, if any
          cycle_start if respond_to? :cycle_start

          #
          # Collect Data
          @data_collector=DataCollector.new self,poll_interval
          poll_cycle
          cnt=@data_collector.process
          @data_collector=nil

          #
          # End of cycle work, if any
          cycle_end if respond_to? :cycle_end
          cnt
        end
      end
    end
  end
end


text:
@class NSString;

@interface IDEWorkspaceToolbarItemProvider : NSObject <IDEToolbarItemProvider>
{
}

+ (void)_toolbarItemViewFrameChanged:(id)arg1;
+ (void)_startObservingFrameChangesIfNeededForToolbarItem:(id)arg1;
+ (id)_createSplitViewDividerToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)_createSpaceToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)_createToggleInspectorToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)_createComparisonModeToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)_createLibraryToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)_createActivityViewToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)_createActiveSchemeToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)_createStopToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)_createRunPauseContinueToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)_createToggleNavigatorToolbarItemWithIdentifier:(id)arg1 window:(id)arg2;
+ (id)itemForItemIdentifier:(id)arg1 forToolbarInWindow:(id)arg2;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
var app = angular.module('minmax', []);

app.controller('MinMaxCtrl', function($scope){
   $scope.formModel = {};

   $scope.onSubmit = function() {
       console.log("Hey I'm submitted");
       console.log($scope.formData);
   }
});


text:
<?php

/*
|--------------------------------------------------------------------------
| Route
|--------------------------------------------------------------------------
|
| Route Facebook URL to our controller action.
|
*/
if(! empty(Config::get('gponster/laravel-oauth-server::routes'))) {

	Route::get(Config::get('gponster/laravel-oauth-server::routes.access_token'),
		'\Gponster\OAuth\Provider\OAuthController@getAccessToken');

	Route::get(Config::get('gponster/laravel-oauth-server::routes.request_token'),
		'\Gponster\OAuth\Provider\OAuthController@getRequestToken');

	Route::get(Config::get('gponster/laravel-oauth-server::routes.authorize'),
		'\Gponster\OAuth\Provider\OAuthController@getAuthorize');

	Route::post(Config::get('gponster/laravel-oauth-server::routes.authorize'),
		'\Gponster\OAuth\Provider\OAuthController@postAuthorize');

	$xAuthEndpoint = Config::get('gponster/laravel-oauth-server::routes.x_auth');
	if(! empty($xAuthEndpoint)) {
		Route::post($xAuthEndpoint, '\Gponster\OAuth\Provider\OAuthController@postAuth');
	}
}


text:
  <?php if($this->config->site->allowOpenPhotoLogin == 1) { ?>

Sign in with your email and password

    <form class="login" method="post">
      <fieldset class="control-group">
        What's your email address?
        <input type="text" name="email" placeholder="user@example.com" id="login-email">
      </fieldset>

      <fieldset class="control-group">
        Enter your password below
        <input type="password" name="password" placeholder="Your password">
      </fieldset>

      <button class="btn btn-brand">Login</button> or enter your email and click to reset
      <input type="hidden" name="r" value="<?php $this->utility->safe($r); ?>">
    </form>

  <?php } ?>
  <?php if($this->plugin->isActive('FacebookConnect')) { ?>

    You can also sign in using...

Facebook Connect

  <?php } ?>


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
LaunchType options are: JAVA_PROCESS, SERVLET_CONTAINER
gameId must be are UUID
ports must be unique on each machine to avoid classes
contextPath must be unique on each port
gracefulStopTimeInMillis is only required for web applications
-->

<!-- Lauch java process using script -jar <jarFile> -->
<script-launched-application friendlyName="my-script-launched-application">

    <options>
        <deploymentFile value="script-sample"/>
        <scriptFile value="bin/start"/>
        <extraClassPath value=""/>
        <bundleId value="80ea7234-0f00-4c54-9443-9ca8422895d3"/>
        <description value=""/>
        <version value="1.5"/>
        <printClassPath value="false"/>
        <numInstances value="1"/>
        <healthCheckInterval value="1"/>
        <healthCheckInitialDelay value="1"/>
        <!--Possible values: DAYS ,HOURS, MICROSECONDS ,MILLISECONDS ,MINUTES ,NANOSECONDS ,SECONDS -->
        <healthCheckIntervalUnit value="MINUTES"/>
        <healthCheckInitialDelayUnit value="MINUTES"/>
        <deployedPostContainerStart value="false"/>
        <enableJolokia value="true"/>
        <jolokiaOptions value=""/>
    </options>
</script-launched-application>


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Project</title>

    <link rel="manifest" href="manifest.json">

    <meta name="mobile-web-app-capable" content="yes">
    <meta name="application-name" content="Web Starter Kit">
    <link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Web Starter Kit">
    <link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png">

    <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#3372DF">

    <meta name="theme-color" content="#3372DF">

    <link rel="stylesheet" href="styles/main.css">

Submit Timesheet


text:
package com.devicehive.dao;

import com.devicehive.configuration.Constants;
import com.devicehive.model.OAuthClient;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Stateless
public class OAuthClientDAO {

    @PersistenceContext(unitName = Constants.PERSISTENCE_UNIT)
    private EntityManager em;

    public OAuthClient insert(OAuthClient client) {
        em.persist(client);
        return client;
    }

    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public OAuthClient get(Long id) {
        return em.find(OAuthClient.class, id);
    }

    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public OAuthClient get(String oauthId) {
        TypedQuery<OAuthClient> query = em.createNamedQuery("OAuthClient.getByOAuthId", OAuthClient.class);
        query.setParameter("oauthId", oauthId);
        CacheHelper.cacheable(query);
        List<OAuthClient> result = query.getResultList();
        return result.isEmpty() ? null : result.get(0);
    }

    public OAuthClient get(String id, String secret) {
        TypedQuery<OAuthClient> query = em.createNamedQuery("OAuthClient.getByOAuthIdAndSecret", OAuthClient.class);
        query.setParameter("oauthId", id);
        query.setParameter("secret", secret);
        List<OAuthClient> result = query.getResultList();
        return result.isEmpty() ? null : result.get(0);
    }

    public boolean delete(Long id) {
        Query query = em.createNamedQuery("OAuthClient.deleteById");
        query.setParameter("id", id);
        return query.executeUpdate() != 0;
    }

    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public List<OAuthClient> list(String name,
                                  String namePattern,
                                  String domain,
                                  String oauthId,
                                  String sortField,
                                  Boolean sortOrderAsc,
                                  Integer take,
                                  Integer skip) {
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<OAuthClient> criteria = criteriaBuilder.createQuery(OAuthClient.class);
        Root<OAuthClient> from = criteria.from(OAuthClient.class);

        List<Predicate> predicates = new ArrayList<>();
        if (namePattern != null) {
            predicates.add(criteriaBuilder.like(from.<String>get("name"), namePattern));
        } else {
            if (name != null) {
                predicates.add(criteriaBuilder.equal(from.get("name"), name));
            }
        }

        if (domain != null) {
            predicates.add(criteriaBuilder.equal(from.get("domain"), domain));
        }
        if (oauthId != null) {
            predicates.add(criteriaBuilder.equal(from.get("oauthId"), oauthId));
        }
        criteria.where(predicates.toArray(new Predicate[predicates.size()]));

        if (sortField != null) {
            if (sortOrderAsc) {
                criteria.orderBy(criteriaBuilder.asc(from.get(sortField)));
            } else {
                criteria.orderBy(criteriaBuilder.desc(from.get(sortField)));
            }
        }

        TypedQuery<OAuthClient> resultQuery = em.createQuery(criteria);
        if (skip != null) {
            resultQuery.setFirstResult(skip);
        }
        if (take == null) {
            take = Constants.DEFAULT_TAKE;
            resultQuery.setMaxResults(take);
        }

        return resultQuery.getResultList();

    }

    public OAuthClient getByName(String name) {
        TypedQuery<OAuthClient> query = em.createNamedQuery("OAuthClient.getByName", OAuthClient.class);
        query.setParameter("name", name);
        List<OAuthClient> result = query.getResultList();
        return result.isEmpty() ? null : result.get(0);
    }
}


text:
require 'rubygems'
require 'net/ping'
require 'socket'
require 'timeout'

module MCollective
    module Agent
        class Nettest<RPC::Agent

            metadata    :name        => "Ping",
                        :description => "Agent to do network tests from a mcollective host",
                        :author      => "Dean Smith",
                        :license     => "BSD",
                        :version     => "1.0",
                        :url         => "http://github.com/deasmi",
                        :timeout     => 60

            action "ping" do
                          validate :fqdn,String

                          fqdn = request[:fqdn]

                          icmp = Net::Ping::ICMP.new(fqdn)

                          if icmp.ping? then
                                  reply[:rtt] = (icmp.duration*1000).to_s
                          else
                                  reply[:rtt]="Host did not respond"
                          end
            end

            action "connect" do

                        validate :fqdn,String
			validate :port,String

                        fqdn = request[:fqdn]
                        port = request[:port]

			begin
				Timeout::timeout(2) do

		                        begin
        		                        t=TCPSocket.new(fqdn,port)
                		        rescue
			                	reply[:connect]="Connection Refused"
	                	        else
        	                	        reply[:connect] = "Connected"
	                	                t.close
		                        end
				end
			rescue Timeout::Error
	                	reply[:connect]="Connection timeout"
			end
            end
        end
    end
end


text:
{% load staticfiles %}

{% block stylesheet %}
    <link rel="stylesheet" type="text/css" href="{% static "css/bootstrap.css" %}" media="screen"/>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
    <style>
        .map-style {
            width: 80%;
            height: 400px;
            display: inline-block;
        }
        .my-points {
            display: inline-block;
            position: absolute;
        }
        .map-container {
            margin: 20px;
        }
        .point-title {
            font-weight: bold;
            font-size: 1em;
            margin-left: 20px;
        }
        div#data_url { display: none; }
    </style>
{% endblock %}


text:
/**
 * pageTitle - Directive for set Page title - mata title
 */
function pageTitle($rootScope, $timeout) {
    return {
        link: function(scope, element) {
            var listener = function(event, toState, toParams, fromState, fromParams) {
                // Default title - load on Dashboard 1
                var title = 'Kactus.io | L\'outil pour votre activité freelance !';
                // Create your own title pattern
                if (toState.data && toState.data.pageTitle) title = 'Kactus | ' + toState.data.pageTitle;
                $timeout(function() {
                    element.text(title);
                });
            };
            $rootScope.$on('$stateChangeStart', listener);
        }
    }
};

/**
 * sideNavigation - Directive for run metsiMenu on sidebar navigation
 */
function sideNavigation() {
    return {
        restrict: 'A',
        link: function(scope, element) {
            // Call the metsiMenu plugin and plug it to sidebar navigation
            element.metisMenu();
        }
    };
};

/**
 * iboxTools - Directive for iBox tools elements in right corner of ibox
 */
function iboxTools($timeout) {
    return {
        restrict: 'A',
        scope: true,
        templateUrl: 'views/common/ibox_tools.html',
        controller: function ($scope, $element) {
            // Function for collapse ibox
            $scope.showhide = function () {
                var ibox = $element.closest('div.ibox');
                var icon = $element.find('i:first');
                var content = ibox.find('div.ibox-content');
                content.slideToggle(200);
                // Toggle icon from up to down
                icon.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
                ibox.toggleClass('').toggleClass('border-bottom');
                $timeout(function () {
                    ibox.resize();
                    ibox.find('[id^=map-]').resize();
                }, 50);
            },
                // Function for close ibox
                $scope.closebox = function () {
                    var ibox = $element.closest('div.ibox');
                    ibox.remove();
                }
        }
    };
};

/**
 * minimalizaSidebar - Directive for minimalize sidebar
*/
function minimalizaSidebar($timeout) {
    return {
        restrict: 'A',
        template: '',
        controller: function ($scope, $element) {
            $scope.minimalize = function () {
                $("body").toggleClass("mini-navbar");
                if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) {
                    // Hide menu in order to smoothly turn on when maximize menu
                    $('#side-menu').hide();
                    // For smoothly turn on menu
                    $timeout(function () {
                        $('#side-menu').fadeIn(500);
                        }, 100);
                } else {
                    // Remove all inline style from jquery fadeIn function to reset menu state
                    $('#side-menu').removeAttr('style');
                }
            }
        }
    };
};

/**
 *
 * Pass all functions into module
 */
angular
    .module('inspinia')
    .directive('pageTitle', pageTitle)
    .directive('sideNavigation', sideNavigation)
    .directive('iboxTools', iboxTools)
    .directive('minimalizaSidebar', minimalizaSidebar)


text:
'use strict';

var jmap = require('../../dist/jmap-client.min'),
    q = require('q'),
    options = require('node-getopt')
    .create([ ['', 'authUrl=ARG', ''], ['', 'username=ARG', ''], ['', 'deviceName=ARG', ''] ])
    .parseSystem().options;

function continuationCallback(authContinuation) {
  return q.resolve(authContinuation.continuationToken);
}

var client = new jmap.Client(new jmap.RequestTransport(), new jmap.QPromiseProvider())
  .withAuthenticationUrl(options.authUrl)
  .authExternal(options.username, options.deviceName, continuationCallback)
  .then(function(authAccess) {
    client.withAuthenticationToken(authAccess.accessToken);
    console.log('client is authenticated, accesstoken=',authAccess.accessToken);
  }, function(err) {
    console.log('something went horribly wrong', err);
  });


text:
name             'lp2-cs'
maintainer       'Open English'
maintainer_email 'infrastructure@openenglish.com'
license          'All rights reserved'
description      'Installs/Configures lp2 Content Services'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.0.1'

depends 'oeinfra'
depends 'oe-ssl'
depends 'oe-tomcat'


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_namednodemapsetnameditem</title>
<link href="activity-home.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">

Test http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_namednodemapsetnameditem

Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C(r) Software License in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


text:
<!DOCTYPE html>

		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Multi-Level Push Menu - Demo 3</title>
		<meta name="description" content="Multi-Level Push Menu: Off-screen navigation with multiple levels" />
		<meta name="keywords" content="multi-level, menu, navigation, off-canvas, off-screen, mobile, levels, nested, transform" />
		<meta name="author" content="Codrops" />
		<link rel="shortcut icon" href="../favicon.ico">
		<link rel="stylesheet" type="text/css" href="css/normalize.css" />
		<link rel="stylesheet" type="text/css" href="css/demo.css" />
		<link rel="stylesheet" type="text/css" href="css/icons.css" />
		<link rel="stylesheet" type="text/css" href="css/component.css" />

All Categories

								Devices

Devices

									back

											Mobile Phones

Mobile Phones

												back

Super Smart Phone

Thin Magic Mobile

Performance Crusher

Futuristic Experience

											Televisions

Televisions

												back

Flat Superscreen

Gigantic LED

Power Eater

3D Experience

Classic Comfort

											Cameras

Cameras

												back

Smart Shot

Power Shooter

Easy Photo Maker

Super Pixel

								Magazines

Magazines

									back

National Geographic

Scientific American

The Spectator

The Rambler

Physics World

The New Scientist

								Store

Store

									back

											Clothes

Clothes

												back

														Women's Clothing

Women's Clothing

															back

Tops

Dresses

Trousers

Shoes

Sale

														Men's Clothing

Men's Clothing

															back

Shirts

Trousers

Shoes

Sale

											Jewelry

											Music

											Grocery

Collections

Credits

							Previous Demo
							Back to the Codrops Article

Multi-Level Push Menu Off-screen navigation with multiple levels

Open/Close Menu

									Demo 1: Overlapping levels
									Demo 2: Covering levels
									Demo 3: Overlapping levels with back links

Demo 3: Overlapping levels with back links

This menu will open by pushing the website content to the right. It has multi-level functionality, allowing endless nesting of navigation elements.

The next level can optionally overlap or cover the previous one.

If you enjoyed this you might also like:

Responsive Multi-Level Menu

Google Nexus Website Menu


text:
/**
 * This package package contains implementations of {@link org.eclipse.collections.api.set.MutableSet}.
 *

 *     This package contains the following mutable set implementations:
 *

 *

 *          {@link org.eclipse.collections.impl.set.mutable.MultiReaderUnifiedSet} -  a thread safe wrapper around UnifiedSet.
 *

 *

 *          {@link org.eclipse.collections.impl.set.mutable.SetAdapter} - a MutableSet wrapper around a JDK Collections Set interface instance.
 *

 *

 *          {@link org.eclipse.collections.impl.set.mutable.SynchronizedMutableSet} - a synchronized view of a set.
 *

 *

 *          {@link org.eclipse.collections.impl.set.mutable.UnifiedSet} - an implementation of a JCF Set which provides methods matching the Smalltalk Collection protocol.
 *

 *

 *          {@link org.eclipse.collections.impl.set.mutable.UnmodifiableMutableSet} - an unmodifiable view of a set.
 *

 *

 *

 *     This package contains 1 factory implementation:
 *

 *

 *          {@link org.eclipse.collections.impl.set.mutable.MutableSetFactoryImpl} - a factory which creates instances of type {@link org.eclipse.collections.api.set.MutableSet}.
 *

 *

 */
package org.eclipse.collections.impl.set.mutable;


text:
/**
 * Created by Xinan on 16/9/15.
 */
public final class Constants {
  final static public int BUFFER_SIZE = 65536;
  final static public String CACHE_PATH = "cache";
}


text:
"""This module will load all the configuration parameters."""

# pylint: disable=unused-import
from grr.config import aff4
from grr.config import api
from grr.config import artifacts
from grr.config import build
from grr.config import checks
from grr.config import client
from grr.config import config
from grr.config import contexts
from grr.config import data_server
from grr.config import data_store
from grr.config import local
from grr.config import logging
from grr.config import server
from grr.config import test


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;

#nullable disable

namespace Microsoft.Build.Logging.StructuredLogger
{
    internal static class ItemGroupParser
    {
        /// <summary>
        /// Parses a log output string to a list of Items (e.g. ItemGroup with metadata or property string).
        /// </summary>
        /// <param name="message">The message output from the logger.</param>
        /// <param name="prefix">The prefix parsed out (e.g. 'Output Item(s): '.).</param>
        /// <param name="name">Out: The name of the list.</param>
        /// <returns>List of items within the list and all metadata.</returns>
        public static IList<Item> ParseItemList(string message, string prefix, out string name)
        {
            name = null;

            var items = new List<Item>();
            var lines = message.Split('\n');

            if (lines.Length == 1)
            {
                var line = lines[0];
                line = line.Substring(prefix.Length);
                var nameValue = ParseNameValue(line);
                name = nameValue.Key;
                items.Add(new Item(nameValue.Value));
                return items;
            }

            if (lines[0].Length > prefix.Length)
            {
                // we have a weird case of multi-line value
                var nameValue = ParseNameValue(lines[0].Substring(prefix.Length));
                name = nameValue.Key;

                items.Add(new Item(nameValue.Value.Replace("\r", "")));
                for (int i = 1; i < lines.Length; i++)
                {
                    items.Add(new Item(lines[i].Replace("\r", "")));
                }

                return items;
            }

            Item currentItem = null;
            foreach (var line in lines)
            {
                switch (GetNumberOfLeadingSpaces(line))
                {
                    case 4:
                        if (line.EndsWith("=", StringComparison.Ordinal))
                        {
                            name = line.Substring(4, line.Length - 5);
                        }
                        break;
                    case 8:
                        currentItem = new Item(line.Substring(8));
                        items.Add(currentItem);
                        break;
                    case 16:
                        if (currentItem != null)
                        {
                            var nameValue = ParseNameValue(line.Substring(16));
                            currentItem.AddMetadata(nameValue.Key, nameValue.Value);
                        }
                        break;
                }
            }

            return items;
        }

        /// <summary>
        /// Parse a string for a name value pair (name=value).
        /// </summary>
        /// <param name="nameEqualsValue">The (name = value) string to parse.</param>
        /// <returns>KeyValuePair name and value</returns>
        private static KeyValuePair<string, string> ParseNameValue(string nameEqualsValue)
        {
            var equals = nameEqualsValue.IndexOf('=');
            var name = nameEqualsValue.Substring(0, equals);
            var value = nameEqualsValue.Substring(equals + 1);
            return new KeyValuePair<string, string>(name, value);
        }

        /// <summary>
        /// Gets the number of leading spaces from a string
        /// </summary>
        /// <param name="line">The string.</param>
        /// <returns>Number of spaces in the beginning of the string.</returns>
        private static int GetNumberOfLeadingSpaces(string line)
        {
            int result = 0;
            while (result < line.Length && line[result] == ' ')
            {
                result++;
            }

            return result;
        }
    }
}


text:
cask 'podman' do
  version '1.4.2'
  sha256 '73850911bb49f2e0a970ff44f785634e2aa9a7a1f20845ff508bdccbead17444'

  url "https://github.com/containers/libpod/releases/download/v#{version}/podman-v#{version}.dmg"
  appcast 'https://github.com/containers/libpod/releases.atom'
  name 'podman'
  homepage 'https://github.com/containers/libpod/'

  binary 'podman'
end


text:
namespace morda{

enum class mouse_cursor{
	none,
	arrow,
	left_right_arrow,
	up_down_arrow,
	all_directions_arrow,
	left_side,
	right_side,
	top_side,
	bottom_side,
	top_left_corner,
	top_right_corner,
	bottom_left_corner,
	bottom_right_corner,
	index_finger,
	grab,
	caret
};

}


text:
<?php

use Tests\TestCase;
use Tests\Traits\MakeLifeStageTrait;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class LifeStageApiTest extends TestCase
{
    use MakeLifeStageTrait, WithoutMiddleware, DatabaseTransactions;

    /**
     * @test
     */
    public function testCreateLifeStage()
    {
        $lifeStage = $this->fakeLifeStageData();
        $response = $this->json('POST', '/api/v1/lifestages', $lifeStage);

        $response->assertStatus(200);
    }

    /**
     * @test
     */
    public function testReadLifeStage()
    {
        $lifeStage = $this->makeLifeStage();
        $response = $this->json('GET', '/api/v1/lifestages/'.$lifeStage->id);

        $response->assertStatus(200);
    }

    /**
     * @test
     */
    public function testUpdateLifeStage()
    {
        $lifeStage = $this->makeLifeStage();
        $editedLifeStage = $this->fakeLifeStageData();

        $response = $this->json('PUT', '/api/v1/lifestages/'.$lifeStage->id, $editedLifeStage);

        $response->assertStatus(200);
    }

    /**
     * @test
     */
    public function testDeleteLifeStage()
    {
        $lifeStage = $this->makeLifeStage();
        $response = $this->json('DELETE', '/api/v1/lifestages/'.$lifeStage->id);

        $response->assertStatus(200);
        $response = $this->json('GET', '/api/v1/lifestages/'.$lifeStage->id);

        $response->assertStatus(404);
    }
}


text:
import React from 'react';
import {BaseMixin, ElementaryMixin, Tools} from './../common/common.js';

import Backdrop from './../bricks/backdrop.js';

import TextInput from './internal/text-input.js';
import Time from './time.js';

import TextInputMixin from './mixins/text-input-mixin.js'

import './timepicker.less';

const FORMAT_AM = 'AM';
const FORMAT_PM = 'PM';
const FORMAT_12 = '12';
const FORMAT_24 = '24';
export const Timepicker = React.createClass({

  //@@viewOn:mixins
  mixins: [
    BaseMixin,
    ElementaryMixin,
    TextInputMixin
  ],
  //@@viewOff:mixins

  //@@viewOn:statics
  statics: {
    tagName: 'UU5.Forms.Timepicker',
    classNames: {
      main: 'uu5-forms-timepicker',
      open: 'uu5-forms-timepicker-open',
      menu: 'uu5-forms-input-menu'
    }
  },
  //@@viewOff:statics

  //@@viewOn:propTypes
  propTypes: {
    value: React.PropTypes.string,
    buttonHidden: React.PropTypes.bool,
    glyphiconOpened: React.PropTypes.string,
    glyphiconClosed: React.PropTypes.string,
    format: React.PropTypes.oneOf([FORMAT_24, FORMAT_12]),
    nanMessage: React.PropTypes.any
  },
  //@@viewOff:propTypes

  //@@viewOn:getDefaultProps
  getDefaultProps() {
    return {
      value: '',
      isButtonHidden: false,
      glyphiconOpened: 'uu-glyphicon-clock',
      glyphiconClosed: 'uu-glyphicon-clock',
      format: FORMAT_24,
      nanMessage: 'Please insert a valid date.'
    };
  },
  //@@viewOff:getDefaultProps

  //@@viewOn:standardComponentLifeCycle
  getInitialState() {
    return {
      opened: false
    };
  },

  componentWillMount(){
    if (typeof this.props.onValidate === 'function') {
      let result = this._isValidTimeResult({ value: this._formatTime(this._parseTime(this.state.value), true) });
      if (result) {
        if (typeof result === 'object') {
          if (result.feedback) {
            this.setFeedback(result.feedback, result.message, this._formatTime(this._parseTime(result.value), true));
          } else {
            this._validateOnChange({
              value: this._formatTime(this._parseTime(this.state.value), true),
              event: null,
              component: this
            })
          }
        }
      }
    } else  {
      this.setState({ value: this._formatTime(this._parseTime(this.state.value), true) });
    }
    return this;
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.controlled) {
      let result = this._isValidTimeResult({ value: nextProps.value });
      if (result) {
        if (typeof result === 'object') {
          if (result.feedback) {
            this.setFeedback(result.feedback, result.message, result.value);
          } else {
            this.setFeedback(nextProps.feedback, nextProps.message, nextProps.value)
          }
        }
      }
    }
    return this;
  },
  //@@viewOff:standardComponentLifeCycle

  //@@viewOn:interface

  open (setStateCallback) {
    this.setState({ opened: true }, setStateCallback);
    return this;
  },

  toggle (setStateCallback) {
    this.setState((state) => ({ opened: !state.opened }), setStateCallback);
    return this;
  },
  //@@viewOff:interface

  //@@viewOn:overridingMethods
  setValue_(value, setStateCallback){
    if (this._checkRequired({ value: value })) {
      if (typeof this.props.onValidate === 'function') {
        this._validateOnChange({ value: value, event: null, component: this });
      } else {
        this.props.required ? this.setSuccess(null, value, setStateCallback) : this.setInitial(null, value, setStateCallback);
      }
    }
    return this;
  },

  isOpened_(){
    return this.state.opened;
  },

  close_ (setStateCallback) {
    this.setState({ opened: false }, setStateCallback);
    return this;
  },
  //@@viewOff:overridingMethods

  //@@viewOn:componentSpecificHelpers
  _onChange(e){
    let opt = { value: e.target.value, event: e, component: this };

    if (opt.value === '' || this._parseTime(opt.value)) {
      if (!this.isDisabled() && !this.isReadOnly()) {
        if (typeof this.props.onChange === 'function') {
          this.props.onChange(opt);
        } else {
          if (this.props.validateOnChange) {
            this._validateOnChange(opt);
          } else {
            if (opt.value === '') {
              this.setState({ value: opt.value });
            } else if (this._checkRequired({ value: opt.value })) {
              opt.required = this.props.required;
              let result = this.getChangeFeedback(opt);

              if (!result.value ||
                (this.props.format === FORMAT_12 && result.value.match(/^\d{1,2}:?\d{0,2} ?[PpAa]?\.?[Mm]?\.?$/)) ||
                (this.props.format === FORMAT_24 && result.value.match(/^\d{1,2}:?\d{0,2}$/))) {
                this.setFeedback(result.feedback, result.message, result.value);
              }
            }
          }
        }
      }
    }

    return this;
  },

  _onBlur(e){
    let opt = { value: e.target.value, event: e, component: this };
    if (typeof this.props.onBlur === 'function') {
      this.props.onBlur(opt);
    } else {
      if (this._checkRequired({ value: opt.value }) && !this.props.validateOnChange) {
        opt.required = this.props.required;
        let blurResult = this.getBlurFeedback(opt);
        let result = this._isValidTimeResult(blurResult);
        this.setFeedback(result.feedback, result.message, this._formatTime(this._parseTime(blurResult.value), true));
      }
    }
    return this;
  },

  _isValidTimeResult(opt){
    let result = opt;
    let time = this._parseTime(opt.value);
    if (!time && opt.value) {
      result.feedback = 'error';
      result.message = this.props.nanMessage;
    }
    return result;
  },

  _validateOnChange(opt){
    let result = typeof this.props.onValidate === 'function' ? this.props.onValidate(opt) : null;
    if (result) {
      if (typeof result === 'object') {
        if (result.feedback) {
          this.setFeedback(result.feedback, result.message, result.value);
        } else {
          this.setState({ value: opt.value });
        }
      } else {
        this.showError('validateError', null, { context: { event: e, func: this.props.onValidate, result: result } });
      }
    } else if (this.props.required && this.state.value) {
      this.setSuccess(null, this.state.value)
    }
    return this;
  },

  _getFeedbackIcon(){
    let icon = this.props.required ? this.props.successGlyphicon : null;
    switch (this.getFeedback()) {
      case 'success':
        icon = this.props.successGlyphicon;
        break;
      case 'warning':
        icon = this.props.warningGlyphicon;
        break;
      case 'error':
        icon = this.props.errorGlyphicon;
        break;
    }
    return icon;
  },

  _onTimeChange(opt) {
    this.setState({ value: this._formatTime(opt.value, true) });
    return this;
  },

  _getTimeProps(value) {
    return {
      className: this.getClassName().menu,
      value: value,
      ref_: this._refCalendar,
      hidden: !this.isOpened(),
      onChange: this._onTimeChange,
      format: this.props.format,
      controlled: true
    };
  },

  _formatTime(value, fill0) {
    let time = '';
    if (value) {
      if (fill0) {
        time = Tools.rjust(value.hours, 2, '0') + ':' + Tools.rjust(value.minutes, 2, '0');
      } else {
        time = value.hours + ':' + value.minutes;
      }
      if (this.props.format === FORMAT_12) {
        time += ' ' + (value.dayPart || FORMAT_AM);
      }
    }
    return time;
  },

  _parseTime (stringTime) {
    stringTime = stringTime.trim();
    let value = null;

    if (typeof stringTime === 'string' && stringTime !== '') {
      value = {
        hours: 0,
        minutes: 0
      };

      if (stringTime.indexOf(':') !== -1) {
        let dateArray = stringTime.split(':');
        value.hours = parseInt(dateArray[0].trim()) || 0;
        value.minutes = parseInt(dateArray[1].trim()) || 0;
      } else {
        value.hours = parseInt(stringTime) || 0;
      }

      if (value.hours < 0 || value.hours > 23 || value.minutes < 0 || value.minutes > 59) {
        value = null;
      } else if (this.props.format === FORMAT_12) {
        if (value.hours > 12) {
          value.hours -= 12;
        } else if (value.hours == 0) {
          value.hours = 12;
        }

        if (stringTime.match(/[Pp]\.?([Mm]\.?)?/)) {
          value.dayPart = FORMAT_PM;
        } else {
          value.dayPart = FORMAT_AM;
        }
      }
    }
    return value;
  },

  _getTextInputAttrs() {
    let props = {};
    if (!this.isReadOnly() && !this.isDisabled()) {
      props.onClick = () => {
        this.open();
      };
    }
    return props;
  },

  _getMainAttrs(){
    let attrs = this._getInputAttrs();
    if (this.isOpened()) {
      attrs.className += ' ' + this.getClassName().open;
    }
    return attrs;
  },
  //@@viewOff:componentSpecificHelpers

  //@@viewOn:render
  render() {
    let inputId = this.getId() + '-input';
    let buttons = !this.isReadOnly() && !this.props.buttonHidden ?
      [{
        glyphicon: this.isOpened() ? this.props.glyphiconOpened : this.props.glyphiconClosed,
        disabled: this.isDisabled(),
        onClick: () => this.toggle(),
        pressed: this.isOpened(),
        colorSchema: 'default'
      }]
      : null;

    let value = this._parseTime(this.state.value);

    return (
      <div {...this._getMainAttrs()}>
        {this.getLabel(inputId)}
        {this.getInputWrapper([
            <TextInput
              id={inputId}
              name={this.props.name || inputId}
              value={this.state.value || ''}
              placeholder={this.props.placeholder}
              type='text'
              onChange={this._onChange}
              onBlur={this._onBlur}
              onFocus={this.onFocus}
              mainAttrs={this._getTextInputAttrs() || this.props.inputAttrs}
              disabled={this.isDisabled() || this.isLoading()}
              readonly={this.isReadOnly()}
              glyphicon={this._getFeedbackIcon()}
              loading={this.isLoading()}
            />,

            <Time {...this._getTimeProps(value)} />,
            <Backdrop {...this._getBackdropProps()} />
          ],
          buttons)}

      </div>
    );
  }
  //@@viewOn:render
});

export default Timepicker;


text:
package com.elytradev.concrete.resgen;

import com.elytradev.concrete.common.ConcreteLog;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import net.minecraft.block.Block;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by darkevilmac on 5/24/17.
 */
public class BlockStateResourceProvider extends ResourceProvider {

	private static String SIMPLE_BLOCK_STATE;

	static {
		try {
			SIMPLE_BLOCK_STATE = Resources.toString(BlockStateResourceProvider.class.getResource("concreteblockstate.json"), Charsets.UTF_8);
		} catch (IOException e) {
			ConcreteLog.error("Caught IOException loading concrete blockstate, things will definitely not work.", e);
		}
	}

	public BlockStateResourceProvider(ConcreteResourcePack resourcePack) {
		super(resourcePack);
	}

	/**
	 * Can this provider provide a resource for the given name?
	 *
	 * @param name the resource name.
	 * @return true if the required resource can be provided, false otherwise.
	 */
	@Override
	public boolean canProvide(String name) {
		return name.startsWith(("assets/" + modID + "/blockstates/")) && name.endsWith(".json");
	}

	/**
	 * Provides an input stream for the given resource name.
	 *
	 * @param name the resource name
	 * @return
	 */
	@Override
	public InputStream provide(String name) {
		String blockID = name.substring(name.lastIndexOf("/") + 1, name.lastIndexOf("."));
		Block blockFromLocation = Block.getBlockFromName(modID + ":" + blockID);
		String modelLocation = modID + ":" + blockID;
		if (blockFromLocation instanceof IResourceHolder) {
			modelLocation = ((IResourceHolder) blockFromLocation).getResource(EnumResourceType.MODEL, 0).toString();
			modelLocation = modelLocation.substring(modelLocation.lastIndexOf("/" + 1));
			modelLocation = modID + ":" + modelLocation;
		}

		String simpleBlockState = SIMPLE_BLOCK_STATE;
		simpleBlockState = simpleBlockState.replaceAll("%MDL%", modelLocation);
		return IOUtils.toInputStream(simpleBlockState);
	}
}


text:
/**
 * This package defines connections between the virtual machine
 * using the JDI and the target virtual machine.
 * In concert with {@link com.sun.jdi.VirtualMachineManager}
 * it is the mechanism for launching, attaching, etc to
 * target virtual machines.
 * <p>
 * Methods may be added to the interfaces in the JDI packages in future
 * releases. Existing packages may be renamed if the JDI becomes a standard
 * extension.
 */

@jdk.Exported
package com.sun.jdi.connect;


text:
'use strict';

const sequelize = require('sequelize');

module.exports = db =>
	db.define('cartItem', {
		quantity: {
			type: sequelize.INTEGER,
			allowNull: false,
			validate: {
				min: 1
			}
		}
	});

module.exports.associations = (CartItem, { Beer, User }) => {
	CartItem.belongsTo(User);
	CartItem.belongsTo(Beer);
};


text:
package com.anji_ahni.neat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.jgapcustomised.Chromosome;
import org.jgapcustomised.ChromosomeMaterial;
import org.jgapcustomised.Configuration;
import org.jgapcustomised.Genotype;
import org.jgapcustomised.InvalidConfigurationException;
import org.jgapcustomised.MutationOperator;

import com.anji_ahni.util.Properties;
import com.ojcoleman.ahni.hyperneat.HyperNEATEvolver;

/**
 * Modifies JGAP Genotype to allow more flexibility in how initial population is generated.
 *
 * @author Oliver Coleman
 */
public class NEATGenotype extends Genotype {
	private static Logger logger = Logger.getLogger(NEATGenotype.class);

	public NEATGenotype(Properties props, Configuration a_activeConfiguration, List<Chromosome> a_initialChromosomes) throws InvalidConfigurationException {
		super(props, a_activeConfiguration, a_initialChromosomes);
	}

	/**
	 * Convenience method that returns a newly constructed NEATGenotype instance configured according to the given
	 * Configuration instance. The population of Chromosomes will created according to the setup of the sample
	 * Chromosome in the Configuration object, but the gene values (alleles) will be set to random legal values.
	 * <p>
	 * Note that the given Configuration instance must be in a valid state at the time this method is invoked, or an
	 * InvalidConfigurationException will be thrown.
	 *
	 * @param a_activeConfiguration
	 * @return A newly constructed NEATGenotype instance.
	 * @throws InvalidConfigurationException if the given Configuration instance not in a valid state.
	 */
	public static NEATGenotype randomInitialGenotype(Properties props, NeatConfiguration a_activeConfiguration) throws InvalidConfigurationException {
		if (a_activeConfiguration == null) {
			throw new IllegalArgumentException("The Configuration instance may not be null.");
		}

		a_activeConfiguration.lockSettings();

		// Create an array of chromosomes equal to the desired size in the
		// active Configuration and then populate that array with Chromosome
		// instances constructed according to the setup in the sample
		// Chromosome, but with random gene values (alleles). The Chromosome
		// class' randomInitialChromosome() method will take care of that for
		// us.
		// ------------------------------------------------------------------
		int populationSize = a_activeConfiguration.getPopulationSize();
		List<Chromosome> chroms = new ArrayList<Chromosome>(populationSize);

		HashMap<MutationOperator, Double> origMutatationRates = new HashMap<MutationOperator, Double>();
		double mutRateFactor = 0;
		if (!props.getBooleanProperty(NeatConfiguration.INITIAL_TOPOLOGY_FULLY_CONNECTED_KEY, true)) {
			logger.info("Generating initial population with random structure generated by mutation operators:");

			mutRateFactor = props.getDoubleProperty(NeatConfiguration.INITIAL_TOPOLOGY_MUTATION_FACTOR_KEY, 0);
			if (mutRateFactor > 1) {
				logger.info("\tTemporary mutation rates are:");
				// Temporarily increase mutation rates to create varied initial population.
				for (MutationOperator operator : a_activeConfiguration.getMutationOperators()) {
					origMutatationRates.put(operator, operator.getMutationRate());
					operator.setMutationRate(operator.getMutationRate() * mutRateFactor);
					logger.info("\t\t" + operator.getClass().getSimpleName() + ": " + operator.getMutationRate());
				}
			}
		}

		ChromosomeMaterial sample = a_activeConfiguration.getSampleChromosomeMaterial();

		// Add the sample chromosome unchanged, in case it's a seed provided by the user rather than randomly generated.
		chroms.add(new Chromosome(sample.clone(null), a_activeConfiguration.nextChromosomeId(), a_activeConfiguration.getObjectiveCount(), a_activeConfiguration.getNoveltyObjectiveCount()));

		double avgAddedGenes = 0;
		for (int i = 1; i < populationSize; i++) {
			ChromosomeMaterial material = null;
			// If the sample network is already fully connected don't add additional structure.
			if (props.getBooleanProperty(NeatConfiguration.INITIAL_TOPOLOGY_FULLY_CONNECTED_KEY, true)) {
				material = ChromosomeMaterial.randomInitialChromosomeMaterial(a_activeConfiguration);
			}
			else {
				material = sample.clone(null);
				for (MutationOperator operator : a_activeConfiguration.getMutationOperators()) {
					operator.mutate(a_activeConfiguration, material);
				}
				avgAddedGenes += material.size() - sample.size();
			}

			chroms.add(new Chromosome(material, a_activeConfiguration.nextChromosomeId(), a_activeConfiguration.getObjectiveCount(), a_activeConfiguration.getNoveltyObjectiveCount()));
		}

		if (!props.getBooleanProperty(NeatConfiguration.INITIAL_TOPOLOGY_FULLY_CONNECTED_KEY, true)) {
			logger.info("\tAdded " + (avgAddedGenes / populationSize) + " extra genes on average.");
			if (mutRateFactor > 1) {
				// Restore original mutation rates.
				for (MutationOperator operator : a_activeConfiguration.getMutationOperators()) {
					operator.setMutationRate(origMutatationRates.get(operator));
				}
			}
		}

		return new NEATGenotype(props, a_activeConfiguration, chroms);
	}
}


text:
static const NSInteger KProductTypeIphone = 1;
static const NSInteger KProductTypeIpad = 2;

@interface SimRuntime (Latest)
+ (SimRuntime *)latest;
@end

@implementation SimRuntime (Latest)

+ (SimRuntime *)latest
{
  NSArray *sorted = [[SimRuntime supportedRuntimes] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"version" ascending:YES]]];
  return [sorted lastObject];
}

@end

@implementation SimulatorInfoXcode6
@synthesize buildSettings = _buildSettings;
@synthesize cpuType = _cpuType;
@synthesize deviceName = _deviceName;
@synthesize OSVersion = _OSVersion;

- (void)dealloc
{
  [_buildSettings release];
  [_deviceName release];
  [_OSVersion release];
  [super dealloc];
}

#pragma mark -
#pragma mark Public methods

- (NSNumber *)simulatedDeviceFamily
{
  return @([_buildSettings[Xcode_TARGETED_DEVICE_FAMILY] integerValue]);
}

- (NSString *)simulatedDeviceInfoName
{
  if (_deviceName) {
    return _deviceName;
  }

  switch ([[self simulatedDeviceFamily] integerValue]) {
    case KProductTypeIphone:
      self.deviceName = @"iPhone 4s";
      break;

    case KProductTypeIpad:
      self.deviceName = @"iPad 2";
      break;
  }

  DTiPhoneSimulatorSystemRoot *systemRoot = [SimulatorInfoXcode6 _systemRootWithSDKPath:_buildSettings[Xcode_SDKROOT]];
  if (!systemRoot) {
    return _deviceName;
  }

  // return lowest device that supports simulated sdk
  SimRuntime *runtime = systemRoot.runtime;
  NSMutableArray *supportedDeviceTypes = [NSMutableArray array];
  for (SimDeviceType *deviceType in [SimDeviceType supportedDeviceTypes]) {
    if ([runtime supportsDeviceType:deviceType]) {
      [supportedDeviceTypes addObject:deviceType];
    }
  }

  NSAssert([supportedDeviceTypes count] > 0, @"There are no available devices that support provided sdk: %@. Supported devices: %@", [systemRoot sdkVersion], [[SimDeviceType supportedDevices] valueForKeyPath:@"name"]);
  self.deviceName = [supportedDeviceTypes[0] name];
  return _deviceName;
}

- (NSString *)simulatedArchitecture
{
  switch (self.cpuType) {
    case CPU_TYPE_I386:
      return @"i386";

    case CPU_TYPE_X86_64:
      return @"x86_64";
  }
  return @"i386";
}

- (NSString *)maxSdkVersionForSimulatedDevice
{
  NSMutableArray *runtimes = [SimulatorInfoXcode6 _runtimesSupportedByDevice:[self simulatedDeviceInfoName]];
  [runtimes sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"version" ascending:YES]]];
  return [[runtimes lastObject] versionString];
}

- (NSString *)simulatedSdkVersion
{
  if (_OSVersion) {
    if ([_OSVersion isEqualTo:@"latest"]) {
      return [[SimRuntime latest] versionString];
    } else {
      return _OSVersion;
    }
  } else {
    return [self maxSdkVersionForSimulatedDevice];
  }
}

- (NSString *)simulatedSdkRootPath
{
  return [[self systemRootForSimulatedSdk] sdkRootPath];
}

- (NSString *)simulatedSdkShortVersion
{
  return [[[self systemRootForSimulatedSdk] runtime] versionString];
}

- (DTiPhoneSimulatorSystemRoot *)systemRootForSimulatedSdk
{
  NSString *sdkVersion = [self simulatedSdkVersion];
  DTiPhoneSimulatorSystemRoot *systemRoot = [SimulatorInfoXcode6 _systemRootWithSDKVersion:sdkVersion];
  if (systemRoot) {
    return systemRoot;
  }

  systemRoot = [SimulatorInfoXcode6 _systemRootWithSDKVersion:sdkVersion];
  NSAssert(systemRoot != nil, @"Unable to instantiate DTiPhoneSimulatorSystemRoot for sdk version: %@. Available roots: %@", sdkVersion, [DTiPhoneSimulatorSystemRoot knownRoots]);
  return systemRoot;
}

#pragma mark -
#pragma mark v6 methods

- (SimRuntime *)simulatedRuntime
{
  return [[self systemRootForSimulatedSdk] runtime];
}

- (SimDevice *)simulatedDevice
{
  SimRuntime *runtime = [self simulatedRuntime];
  SimDeviceType *deviceType = [SimDeviceType supportedDeviceTypesByAlias][[self simulatedDeviceInfoName]];
  for (SimDevice *device in [[SimDeviceSet defaultSet] availableDevices]) {
    if ([device.deviceType isEqual:deviceType] &&
        [device.runtime isEqual:runtime]) {
      return device;
    }
  }
  return nil;
}

#pragma mark -
#pragma mark Class Methods

+ (NSArray *)availableDevices
{
  return [[SimDeviceType supportedDeviceTypesByName] allKeys];
}

+ (BOOL)isDeviceAvailableWithAlias:(NSString *)deviceName
{
  return [[SimDeviceType supportedDeviceTypesByAlias] objectForKey:deviceName] != nil;
}

+ (NSString *)deviceNameForAlias:(NSString *)deviceAlias
{
  SimDeviceType *deviceType = [[SimDeviceType supportedDeviceTypesByAlias] objectForKey:deviceAlias];
  return [deviceType name];
}

+ (BOOL)isSdkVersion:(NSString *)sdkVersion supportedByDevice:(NSString *)deviceName
{
  SimDeviceType *deviceType = [SimDeviceType supportedDeviceTypesByAlias][deviceName];
  SimRuntime *runtime = [self _runtimeForSdkVersion:sdkVersion];

  return [runtime supportsDeviceType:deviceType];
}

+ (NSString *)sdkVersionForOSVersion:(NSString *)osVersion
{
  if ([osVersion isEqualToString:@"latest"]) {
    return [[SimRuntime latest] versionString];
  } else {
    return [[self _runtimeForSdkVersion:osVersion] versionString];
  }
}

+ (NSArray *)availableSdkVersions
{
  return [[SimRuntime supportedRuntimes] valueForKeyPath:@"versionString"];
}

+ (NSArray *)sdksSupportedByDevice:(NSString *)deviceName
{
  NSArray *runtimes = [self _runtimesSupportedByDevice:deviceName];
  return [runtimes valueForKeyPath:@"versionString"];
}

+ (cpu_type_t)cpuTypeForDevice:(NSString *)deviceName
{
  SimDeviceType *deviceType = [SimDeviceType supportedDeviceTypesByAlias][deviceName];
  if ([deviceType.supportedArchs containsObject:@(CPU_TYPE_X86_64)]) {
    return CPU_TYPE_X86_64;
  } else {
    return CPU_TYPE_I386;
  }
}

+ (NSString *)baseVersionForSDKShortVersion:(NSString *)shortVersionString
{
  DTiPhoneSimulatorSystemRoot *root = [self _systemRootWithSDKVersion:shortVersionString];
  NSArray *components = [[root sdkVersion] componentsSeparatedByString:@"."];
  if ([components count] < 2) {
    return [root sdkVersion];
  }
  return [[components objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)]] componentsJoinedByString:@"."];
}

#pragma mark -
#pragma mark Helpers

+ (NSMutableArray *)_runtimesSupportedByDevice:(NSString *)deviceName
{
  NSMutableArray *supportedRuntimes = [NSMutableArray array];
  SimDeviceType *deviceType = [SimDeviceType supportedDeviceTypesByAlias][deviceName];
  NSAssert(deviceType != nil, @"SimDeviceType wasn't found for device with alias: %@. Available aliases: %@", deviceName, [SimDeviceType supportedDeviceTypesByAlias]);
  for (SimRuntime *runtime in [SimRuntime supportedRuntimes]) {
    if ([runtime supportsDeviceType:deviceType]) {
      [supportedRuntimes addObject:runtime];
    }
  }
  return supportedRuntimes;
}

+ (SimRuntime *)_runtimeForSdkVersion:(NSString *)sdkVersion
{
  NSAssert(sdkVersion != nil, @"Sdk version shouldn't be nil.");
  NSArray *runtimes = [SimRuntime supportedRuntimes];
  for (SimRuntime *runtime in runtimes) {
    if ([runtime.versionString hasPrefix:sdkVersion]) {
      return runtime;
    }
  }
  return nil;
}

+ (SimRuntime *)_runtimeForSDKPath:(NSString *)sdkPath
{
  DTiPhoneSimulatorSystemRoot *root = [SimulatorInfoXcode6 _systemRootWithSDKPath:sdkPath];
  return [root runtime];
}

#pragma mark -
#pragma mark Caching methods

+ (DTiPhoneSimulatorSystemRoot *)_systemRootWithSDKPath:(NSString *)path
{
  static NSMutableDictionary *map;
  static dispatch_once_t onceToken;
  static dispatch_queue_t accessQueue;
  dispatch_once(&onceToken, ^{
    map = [@{} mutableCopy];
    accessQueue = dispatch_queue_create("com.xctool.access_root_with_sdk_path", NULL);
  });

  __block DTiPhoneSimulatorSystemRoot *root = nil;
  dispatch_sync(accessQueue, ^{
    root = map[path];
  });

  if (root) {
    return root;
  }

  [[DTiPhoneSimulatorSystemRoot knownRoots] enumerateObjectsUsingBlock:^(DTiPhoneSimulatorSystemRoot *obj, NSUInteger idx, BOOL *stop) {
    if ([obj.sdkRootPath isEqual:path]) {
      root = obj;
      *stop = YES;
    }
  }];

  if (root) {
    dispatch_async(accessQueue, ^{
      map[path] = root;
    });
  }

  return root;
}

+ (DTiPhoneSimulatorSystemRoot *)_systemRootWithSDKVersion:(NSString *)version
{
  static NSMutableDictionary *map;
  static dispatch_once_t onceToken;
  static dispatch_queue_t accessQueue;
  dispatch_once(&onceToken, ^{
    map = [@{} mutableCopy];
    accessQueue = dispatch_queue_create("com.xctool.access_root_with_sdk_version", NULL);
  });

  __block DTiPhoneSimulatorSystemRoot *root = nil;
  dispatch_sync(accessQueue, ^{
    root = map[version];
  });

  if (root) {
    return root;
  }

  [[DTiPhoneSimulatorSystemRoot knownRoots] enumerateObjectsUsingBlock:^(DTiPhoneSimulatorSystemRoot *obj, NSUInteger idx, BOOL *stop) {
    if ([obj.sdkVersion hasPrefix:version]) {
      root = obj;
      *stop = YES;
    }
  }];

  if (root) {
    dispatch_async(accessQueue, ^{
      map[version] = root;
    });
  }

  return root;
}

@end


text:
using UnityEngine;
using UnityEditor;

public class ResourceInspector : EditorWindow {

	[MenuItem("Window/Inspector/Resources")]
	private static void OpenConfigEditor()
	{
		ResourceInspector window = (ResourceInspector)EditorWindow.GetWindow(typeof(ResourceInspector));
		window.Show();
	}

	private Vector2 scrollPos;

	private void OnGUI()
	{
		scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
		object NullObj = null;
		DataInspectorUtility.inspect(ref NullObj, typeof(AssetBundleLoader), "Resources");
		EditorGUILayout.EndScrollView();
	}
}


text:
namespace media {

// PlatformMojoMediaClient default implementations.

PlatformMojoMediaClient::~PlatformMojoMediaClient(){};

scoped_ptr<RendererFactory> PlatformMojoMediaClient::CreateRendererFactory(
    const scoped_refptr<MediaLog>& media_log) {
  return nullptr;
};

ScopedVector<AudioDecoder> PlatformMojoMediaClient::CreateAudioDecoders(
    const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
    const scoped_refptr<MediaLog>& media_log) {
  return ScopedVector<AudioDecoder>();
};

ScopedVector<VideoDecoder> PlatformMojoMediaClient::CreateVideoDecoders(
    const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
    const scoped_refptr<MediaLog>& media_log) {
  return ScopedVector<VideoDecoder>();
}

scoped_refptr<AudioRendererSink>
PlatformMojoMediaClient::CreateAudioRendererSink() {
  return nullptr;
};

scoped_ptr<VideoRendererSink> PlatformMojoMediaClient::CreateVideoRendererSink(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) {
  return nullptr;
}

const AudioHardwareConfig* PlatformMojoMediaClient::GetAudioHardwareConfig() {
  return nullptr;
}

scoped_ptr<CdmFactory> PlatformMojoMediaClient::CreateCdmFactory(
    mojo::ServiceProvider* service_provider) {
  return nullptr;
}

namespace internal {
extern scoped_ptr<PlatformMojoMediaClient> CreatePlatformMojoMediaClient();
}  // namespace internal

static base::LazyInstance<MojoMediaClient>::Leaky g_mojo_media_client =
    LAZY_INSTANCE_INITIALIZER;

// static
MojoMediaClient* MojoMediaClient::Get() {
  return g_mojo_media_client.Pointer();
}

scoped_ptr<RendererFactory> MojoMediaClient::CreateRendererFactory(
    const scoped_refptr<MediaLog>& media_log) {
  return mojo_media_client_->CreateRendererFactory(media_log);
}

ScopedVector<AudioDecoder> MojoMediaClient::CreateAudioDecoders(
    const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
    const scoped_refptr<MediaLog>& media_log) {
  return mojo_media_client_->CreateAudioDecoders(media_task_runner, media_log);
}

ScopedVector<VideoDecoder> MojoMediaClient::CreateVideoDecoders(
    const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
    const scoped_refptr<MediaLog>& media_log) {
  return mojo_media_client_->CreateVideoDecoders(media_task_runner, media_log);
}

scoped_refptr<AudioRendererSink> MojoMediaClient::CreateAudioRendererSink() {
  return mojo_media_client_->CreateAudioRendererSink();
}

scoped_ptr<VideoRendererSink> MojoMediaClient::CreateVideoRendererSink(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) {
  return mojo_media_client_->CreateVideoRendererSink(task_runner);
}

const AudioHardwareConfig* MojoMediaClient::GetAudioHardwareConfig() {
  return mojo_media_client_->GetAudioHardwareConfig();
}

scoped_ptr<CdmFactory> MojoMediaClient::CreateCdmFactory(
    mojo::ServiceProvider* service_provider) {
  return mojo_media_client_->CreateCdmFactory(service_provider);
}

MojoMediaClient::MojoMediaClient()
    : mojo_media_client_(internal::CreatePlatformMojoMediaClient()) {
  DCHECK(mojo_media_client_);
}

MojoMediaClient::~MojoMediaClient() {
}

}  // namespace media


text:
:man_page: mongoc_apm_command_succeeded_get_server_connection_id

mongoc_apm_command_succeeded_get_server_connection_id()
=======================================================

Synopsis
--------

.. code-block:: c

  int32_t
  mongoc_apm_command_succeeded_get_server_connection_id (
     const mongoc_apm_command_succeeded_t *event);

Returns the server connection ID for the command. The server connection ID is
distinct from the server ID
(:symbol:`mongoc_apm_command_succeeded_get_server_id`) and is returned by the
hello or legacy hello response as "connectionId" from the server on 4.2+.

Parameters
----------

* ``event``: A :symbol:`mongoc_apm_command_succeeded_t`.

Returns
-------

The server connection ID as a positive integer or -1 if it is not available.

.. seealso::

  | :doc:`Introduction to Application Performance Monitoring <application-performance-monitoring>`


text:
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level2" level="2" version="1" xmlns:html="http://www.w3.org/1999/xhtml">
<model id="kb_g_213558_fbamdl0" name="Staphylococcus_aureus_T69721_SEED_model">
<listOfUnitDefinitions>
	<unitDefinition id="mmol_per_gDW_per_hr">
		<listOfUnits>
			<unit kind="mole" scale="-3"/>
			<unit kind="gram" exponent="-1"/>
			<unit kind="second" multiplier=".00027777" exponent="-1"/>
		</listOfUnits>
	</unitDefinition>
</listOfUnitDefinitions>
<listOfCompartments>
<compartment id="c" name="Cytosol_0" />
<compartment id="e" name="Extracellular_0" />
</listOfCompartments>
<listOfSpecies>
<species id="cpd99989_c" name="ACP_c" compartment="c" charge="-2" boundaryCondition="false">
  <notes>

FORMULA: C

CHARGE: -2

  </notes>
</species>
<species id="cpd99990_c" name="Apo-ACP_c" compartment="c" charge="-2" boundaryCondition="false">
  <notes>

FORMULA: C

CHARGE: -2

  </notes>
</species>
<species id="cpd99996_e" name="A_e" compartment="e" charge="-2" boundaryCondition="false">
  <notes>

FORMULA: C

CHARGE: -2

  </notes>
</species>
<species id="cpd99996_c" name="A_c" compartment="c" charge="-2" boundaryCondition="false">
  <notes>

FORMULA: C

CHARGE: -2

  </notes>
</species>
<species id="cpd99997_c" name="B_c" compartment="c" charge="-2" boundaryCondition="false">
  <notes>

FORMULA: C

CHARGE: -2

  </notes>
</species>
<species id="cpd99997_e" name="B_e" compartment="e" charge="-2" boundaryCondition="false">
  <notes>

FORMULA: C

CHARGE: -2

  </notes>
</species>
<species id="cpd99998_c" name="C_c" compartment="c" charge="-2" boundaryCondition="false">
  <notes>

FORMULA: C

CHARGE: -2

  </notes>
</species>
<species id="cpd99999_c" name="D_c" compartment="c" charge="-2" boundaryCondition="false">
  <notes>

FORMULA: C

CHARGE: -2

  </notes>
</species>
<species id="cpd11416_c" name="Biomass_c" compartment="c" charge="0" boundaryCondition="false">
</species>
</listOfSpecies>
<listOfReactions>
<reaction id="my99990_c" name="my99990_c" reversible="false">
<notes>
</notes>
<listOfReactants>
<speciesReference species="cpd99990_c" stoichiometry="1"/>
</listOfReactants>
<listOfProducts>
<speciesReference species="cpd99989_c" stoichiometry="1"/>
</listOfProducts>
<kineticLaw>
	<math xmlns="http://www.w3.org/1998/Math/MathML">
			<ci> FLUX_VALUE </ci>
	</math>
	<listOfParameters>
		<parameter id="LOWER_BOUND" value="0" name="mmol_per_gDW_per_hr"/>
		<parameter id="UPPER_BOUND" value="100" name="mmol_per_gDW_per_hr"/>
		<parameter id="OBJECTIVE_COEFFICIENT" value="0"/>
		<parameter id="FLUX_VALUE" value="0.0" name="mmol_per_gDW_per_hr"/>
	</listOfParameters>
</kineticLaw>
</reaction>
<reaction id="my99991_c" name="my99991_c" reversible="false">
<notes>
</notes>
<listOfReactants>
<speciesReference species="cpd99996_e" stoichiometry="1"/>
</listOfReactants>
<listOfProducts>
<speciesReference species="cpd99996_c" stoichiometry="1"/>
</listOfProducts>
<kineticLaw>
	<math xmlns="http://www.w3.org/1998/Math/MathML">
			<ci> FLUX_VALUE </ci>
	</math>
	<listOfParameters>
		<parameter id="LOWER_BOUND" value="0" name="mmol_per_gDW_per_hr"/>
		<parameter id="UPPER_BOUND" value="100" name="mmol_per_gDW_per_hr"/>
		<parameter id="OBJECTIVE_COEFFICIENT" value="0"/>
		<parameter id="FLUX_VALUE" value="0.0" name="mmol_per_gDW_per_hr"/>
	</listOfParameters>
</kineticLaw>
</reaction>
<reaction id="my99992_c" name="my99992_c" reversible="false">
<notes>
</notes>
<listOfReactants>
<speciesReference species="cpd99996_c" stoichiometry="1"/>
</listOfReactants>
<listOfProducts>
<speciesReference species="cpd99997_c" stoichiometry="1"/>
</listOfProducts>
<kineticLaw>
	<math xmlns="http://www.w3.org/1998/Math/MathML">
			<ci> FLUX_VALUE </ci>
	</math>
	<listOfParameters>
		<parameter id="LOWER_BOUND" value="0" name="mmol_per_gDW_per_hr"/>
		<parameter id="UPPER_BOUND" value="100" name="mmol_per_gDW_per_hr"/>
		<parameter id="OBJECTIVE_COEFFICIENT" value="0"/>
		<parameter id="FLUX_VALUE" value="0.0" name="mmol_per_gDW_per_hr"/>
	</listOfParameters>
</kineticLaw>
</reaction>
<reaction id="my99997_c" name="my99997_c" reversible="false">
<notes>
</notes>
<listOfReactants>
<speciesReference species="cpd99997_c" stoichiometry="1"/>
</listOfReactants>
<listOfProducts>
<speciesReference species="cpd99997_e" stoichiometry="1"/>
</listOfProducts>
<kineticLaw>
	<math xmlns="http://www.w3.org/1998/Math/MathML">
			<ci> FLUX_VALUE </ci>
	</math>
	<listOfParameters>
		<parameter id="LOWER_BOUND" value="0" name="mmol_per_gDW_per_hr"/>
		<parameter id="UPPER_BOUND" value="100" name="mmol_per_gDW_per_hr"/>
		<parameter id="OBJECTIVE_COEFFICIENT" value="0"/>
		<parameter id="FLUX_VALUE" value="0.0" name="mmol_per_gDW_per_hr"/>
	</listOfParameters>
</kineticLaw>
</reaction>
<reaction id="my99993_c" name="my99993_c" reversible="false">
<notes>
</notes>
<listOfReactants>
<speciesReference species="cpd99997_c" stoichiometry="1"/>
</listOfReactants>
<listOfProducts>
<speciesReference species="cpd99998_c" stoichiometry="1"/>
</listOfProducts>
<kineticLaw>
	<math xmlns="http://www.w3.org/1998/Math/MathML">
			<ci> FLUX_VALUE </ci>
	</math>
	<listOfParameters>
		<parameter id="LOWER_BOUND" value="0" name="mmol_per_gDW_per_hr"/>
		<parameter id="UPPER_BOUND" value="100" name="mmol_per_gDW_per_hr"/>
		<parameter id="OBJECTIVE_COEFFICIENT" value="0"/>
		<parameter id="FLUX_VALUE" value="0.0" name="mmol_per_gDW_per_hr"/>
	</listOfParameters>
</kineticLaw>
</reaction>
<reaction id="my99994_c" name="my99994_c" reversible="false">
<notes>
</notes>
<listOfReactants>
<speciesReference species="cpd99998_c" stoichiometry="1"/>
</listOfReactants>
<listOfProducts>
<speciesReference species="cpd99999_c" stoichiometry="2"/>
</listOfProducts>
<kineticLaw>
	<math xmlns="http://www.w3.org/1998/Math/MathML">
			<ci> FLUX_VALUE </ci>
	</math>
	<listOfParameters>
		<parameter id="LOWER_BOUND" value="0" name="mmol_per_gDW_per_hr"/>
		<parameter id="UPPER_BOUND" value="100" name="mmol_per_gDW_per_hr"/>
		<parameter id="OBJECTIVE_COEFFICIENT" value="0"/>
		<parameter id="FLUX_VALUE" value="0.0" name="mmol_per_gDW_per_hr"/>
	</listOfParameters>
</kineticLaw>
</reaction>
<reaction id="my99995_c" name="my99995_c" reversible="false">
<notes>
</notes>
<listOfReactants>
<speciesReference species="cpd99997_c" stoichiometry="1"/>
</listOfReactants>
<listOfProducts>
<speciesReference species="cpd99999_c" stoichiometry="1"/>
</listOfProducts>
<kineticLaw>
	<math xmlns="http://www.w3.org/1998/Math/MathML">
			<ci> FLUX_VALUE </ci>
	</math>
	<listOfParameters>
		<parameter id="LOWER_BOUND" value="0" name="mmol_per_gDW_per_hr"/>
		<parameter id="UPPER_BOUND" value="100" name="mmol_per_gDW_per_hr"/>
		<parameter id="OBJECTIVE_COEFFICIENT" value="0"/>
		<parameter id="FLUX_VALUE" value="0.0" name="mmol_per_gDW_per_hr"/>
	</listOfParameters>
</kineticLaw>
</reaction>
<reaction id="biomass0" name="biomass" reversible="false">
<notes>
GENE_ASSOCIATION:
PROTEIN_ASSOCIATION:
SUBSYSTEM:
PROTEIN_CLASS:
</notes>
<listOfReactants>
<speciesReference species="cpd99999_c" stoichiometry="2"/>
<speciesReference species="cpd99989_c" stoichiometry="1"/>
</listOfReactants>
<listOfProducts>
<speciesReference species="cpd11416_c" stoichiometry="1"/>
<speciesReference species="cpd99990_c" stoichiometry="1"/>
</listOfProducts>
<kineticLaw>
	<math xmlns="http://www.w3.org/1998/Math/MathML">
			<ci> FLUX_VALUE </ci>
	</math>
	<listOfParameters>
		<parameter id="LOWER_BOUND" value="0.0" name="mmol_per_gDW_per_hr"/>
		<parameter id="UPPER_BOUND" value="100" name="mmol_per_gDW_per_hr"/>
		<parameter id="OBJECTIVE_COEFFICIENT" value="1"/>
		<parameter id="FLUX_VALUE" value="0.0" name="mmol_per_gDW_per_hr"/>
	</listOfParameters>
</kineticLaw>
</reaction>
</listOfReactions>
</model>
</sbml>


text:
import unittest
import re
from hashlib import md5 as basic_md5
from flask import Flask
from flask_httpauth import HTTPDigestAuth
from werkzeug.http import parse_dict_header

def md5(str):
    if type(str).__name__ == 'str':
        str = str.encode('utf-8')
    return basic_md5(str)

def get_ha1(user, pw, realm):
    a1 = user + ":" + realm + ":" + pw
    return md5(a1).hexdigest()

class HTTPAuthTestCase(unittest.TestCase):
    def setUp(self):
        app = Flask(__name__)
        app.config['SECRET_KEY'] = 'my secret'

        digest_auth = HTTPDigestAuth()

        @digest_auth.get_password
        def get_digest_password_2(username):
            if username == 'susan':
                return 'hello'
            elif username == 'john':
                return 'bye'
            else:
                return None

        @app.route('/')
        def index():
            return 'index'

        @app.route('/digest')
        @digest_auth.login_required
        def digest_auth_route():
            return 'digest_auth:' + digest_auth.username()

        self.app = app
        self.digest_auth = digest_auth
        self.client = app.test_client()

    def test_digest_auth_prompt(self):
        response = self.client.get('/digest')
        self.assertEqual(response.status_code, 401)
        self.assertTrue('WWW-Authenticate' in response.headers)
        self.assertTrue(re.match(r'^Digest realm="Authentication Required",'
                                 r'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$',
                                 response.headers['WWW-Authenticate']))

    def test_digest_auth_ignore_options(self):
        response = self.client.options('/digest')
        self.assertEqual(response.status_code, 200)
        self.assertTrue('WWW-Authenticate' not in response.headers)

    def test_digest_auth_login_valid(self):
        response = self.client.get('/digest')
        self.assertTrue(response.status_code == 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = 'john:' + d['realm'] + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest', headers={
                'Authorization': 'Digest username="john",realm="{0}",'
                                 'nonce="{1}",uri="/digest",response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'])})
        self.assertEqual(response.data, b'digest_auth:john')

    def test_digest_auth_login_bad_realm(self):
        response = self.client.get('/digest')
        self.assertTrue(response.status_code == 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = 'john:' + 'Wrong Realm' + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest', headers={
                'Authorization': 'Digest username="john",realm="{0}",'
                                 'nonce="{1}",uri="/digest",response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'])})
        self.assertEqual(response.status_code, 401)
        self.assertTrue('WWW-Authenticate' in response.headers)
        self.assertTrue(re.match(r'^Digest realm="Authentication Required",'
                                 r'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$',
                                 response.headers['WWW-Authenticate']))

    def test_digest_auth_login_invalid2(self):
        response = self.client.get('/digest')
        self.assertEqual(response.status_code, 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = 'david:' + 'Authentication Required' + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest', headers={
                'Authorization': 'Digest username="david",realm="{0}",'
                                 'nonce="{1}",uri="/digest",response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'])})
        self.assertEqual(response.status_code, 401)
        self.assertTrue('WWW-Authenticate' in response.headers)
        self.assertTrue(re.match(r'^Digest realm="Authentication Required",'
                                 r'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$',
                                 response.headers['WWW-Authenticate']))

    def test_digest_generate_ha1(self):
        ha1 = self.digest_auth.generate_ha1('pawel', 'test')
        ha1_expected = get_ha1('pawel', 'test', self.digest_auth.realm)
        self.assertEqual(ha1, ha1_expected)

    def test_digest_custom_nonce_checker(self):
        @self.digest_auth.generate_nonce
        def noncemaker():
            return 'not a good nonce'

        @self.digest_auth.generate_opaque
        def opaquemaker():
            return 'some opaque'

        verify_nonce_called = []

        @self.digest_auth.verify_nonce
        def verify_nonce(provided_nonce):
            verify_nonce_called.append(provided_nonce)
            return True

        verify_opaque_called = []

        @self.digest_auth.verify_opaque
        def verify_opaque(provided_opaque):
            verify_opaque_called.append(provided_opaque)
            return True

        response = self.client.get('/digest')
        self.assertEqual(response.status_code, 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        self.assertEqual(d['nonce'], 'not a good nonce')
        self.assertEqual(d['opaque'], 'some opaque')

        a1 = 'john:' + d['realm'] + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest', headers={
                'Authorization': 'Digest username="john",realm="{0}",'
                                 'nonce="{1}",uri="/digest",response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'])})
        self.assertEqual(response.data, b'digest_auth:john')
        self.assertEqual(verify_nonce_called, ['not a good nonce'],
                         "Should have verified the nonce.")
        self.assertEqual(verify_opaque_called, ['some opaque'],
                         "Should have verified the opaque.")