text:
#include "View/MessagesMenuView.h"

#include <iostream>

using namespace std;

void MessagesMenuView::showMessagesList(const MessageList& messageList, const size_t selectedMessage)
{
	for(size_t i = 0 ; i < messageList.size(); ++i)
	{
		if(i == selectedMessage)
		{
			cout << "=>";
		}
		else
		{
			cout << "  ";
		}
		cout << i << " - " << messageList.getItem(i).m_title << endl;
	}
}

void MessagesMenuView::displayMessage(const Message& message)
{
	cout << "TITLE:" << endl;
	cout << message.m_title << endl<<endl;

	cout << "MESSAGE:" << endl;
	cout << message.m_body << endl<<endl;
}

redpajama_set_name: RedPajamaGithub


text:
package com.microsoft.azure.management.edgegateway.v2019_03_01.implementation;

import com.microsoft.azure.management.edgegateway.v2019_03_01.OperationDisplay;
import com.microsoft.azure.management.edgegateway.v2019_03_01.ServiceSpecification;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;

/**
 * Operations.
 */
@JsonFlatten
public class OperationInner {
    /**
     * Name of the operation.
     */
    @JsonProperty(value = "name")
    private String name;

    /**
     * Properties displayed for the operation.
     */
    @JsonProperty(value = "display")
    private OperationDisplay display;

    /**
     * Origin of the operation.
     */
    @JsonProperty(value = "origin")
    private String origin;

    /**
     * Service specification.
     */
    @JsonProperty(value = "properties.serviceSpecification")
    private ServiceSpecification serviceSpecification;

    /**
     * Get name of the operation.
     *
     * @return the name value
     */
    public String name() {
        return this.name;
    }

    /**
     * Set name of the operation.
     *
     * @param name the name value to set
     * @return the OperationInner object itself.
     */
    public OperationInner withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get properties displayed for the operation.
     *
     * @return the display value
     */
    public OperationDisplay display() {
        return this.display;
    }

    /**
     * Set properties displayed for the operation.
     *
     * @param display the display value to set
     * @return the OperationInner object itself.
     */
    public OperationInner withDisplay(OperationDisplay display) {
        this.display = display;
        return this;
    }

    /**
     * Get origin of the operation.
     *
     * @return the origin value
     */
    public String origin() {
        return this.origin;
    }

    /**
     * Set origin of the operation.
     *
     * @param origin the origin value to set
     * @return the OperationInner object itself.
     */
    public OperationInner withOrigin(String origin) {
        this.origin = origin;
        return this;
    }

    /**
     * Get service specification.
     *
     * @return the serviceSpecification value
     */
    public ServiceSpecification serviceSpecification() {
        return this.serviceSpecification;
    }

    /**
     * Set service specification.
     *
     * @param serviceSpecification the serviceSpecification value to set
     * @return the OperationInner object itself.
     */
    public OperationInner withServiceSpecification(ServiceSpecification serviceSpecification) {
        this.serviceSpecification = serviceSpecification;
        return this;
    }

}


text:
module KnowsAboutPrices
  def get_prices_for_books(books)
    if books.kind_of?(Array)
      ids = books.map { |book| book["id"] }
    else
      ids = books["id"]
    end
    set_query_param("book", ids)
    http_get :api, "/prices"
  end
end

World(KnowsAboutPrices)


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.overridesResolver = void 0;

var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var React = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _clsx = _interopRequireDefault(require("clsx"));

var _unstyled = require("@material-ui/unstyled");

var _system = require("@material-ui/system");

var _styled = _interopRequireWildcard(require("../styles/styled"));

var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));

var _ListContext = _interopRequireDefault(require("../List/ListContext"));

var _ButtonBase = _interopRequireDefault(require("../ButtonBase"));

var _useEnhancedEffect = _interopRequireDefault(require("../utils/useEnhancedEffect"));

var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));

var _Divider = require("../Divider");

var _ListItemIcon = require("../ListItemIcon");

var _ListItemText = require("../ListItemText");

var _menuItemClasses = _interopRequireWildcard(require("./menuItemClasses"));

var _jsxRuntime = require("react/jsx-runtime");

const _excluded = ["autoFocus", "component", "dense", "divider", "disableGutters", "focusVisibleClassName", "role", "tabIndex"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

const overridesResolver = (props, styles) => {
  const {
    styleProps
  } = props;
  return [styles.root, styleProps.dense && styles.dense, styleProps.divider && styles.divider, !styleProps.disableGutters && styles.gutters];
};

exports.overridesResolver = overridesResolver;

const useUtilityClasses = styleProps => {
  const {
    disabled,
    dense,
    divider,
    disableGutters,
    selected,
    classes
  } = styleProps;
  const slots = {
    root: ['root', dense && 'dense', disabled && 'disabled', !disableGutters && 'gutters', divider && 'divider', selected && 'selected']
  };
  const composedClasses = (0, _unstyled.unstable_composeClasses)(slots, _menuItemClasses.getMenuItemUtilityClass, classes);
  return (0, _extends2.default)({}, classes, composedClasses);
};

const MenuItemRoot = (0, _styled.default)(_ButtonBase.default, {
  shouldForwardProp: prop => (0, _styled.rootShouldForwardProp)(prop) || prop === 'classes',
  name: 'MuiMenuItem',
  slot: 'Root',
  overridesResolver
})(({
  theme,
  styleProps
}) => (0, _extends2.default)({}, theme.typography.body1, {
  display: 'flex',
  justifyContent: 'flex-start',
  alignItems: 'center',
  position: 'relative',
  textDecoration: 'none',
  minHeight: 48,
  paddingTop: 6,
  paddingBottom: 6,
  boxSizing: 'border-box',
  whiteSpace: 'nowrap'
}, !styleProps.disableGutters && {
  paddingLeft: 16,
  paddingRight: 16
}, styleProps.divider && {
  borderBottom: `1px solid ${theme.palette.divider}`,
  backgroundClip: 'padding-box'
}, {
  '&:hover': {
    textDecoration: 'none',
    backgroundColor: theme.palette.action.hover,
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: 'transparent'
    }
  },
  [`&.${_menuItemClasses.default.selected}`]: {
    backgroundColor: (0, _system.alpha)(theme.palette.primary.main, theme.palette.action.selectedOpacity),
    [`&.${_menuItemClasses.default.focusVisible}`]: {
      backgroundColor: (0, _system.alpha)(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)
    }
  },
  [`&.${_menuItemClasses.default.selected}:hover`]: {
    backgroundColor: (0, _system.alpha)(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: (0, _system.alpha)(theme.palette.primary.main, theme.palette.action.selectedOpacity)
    }
  },
  [`&.${_menuItemClasses.default.focusVisible}`]: {
    backgroundColor: theme.palette.action.focus
  },
  [`&.${_menuItemClasses.default.disabled}`]: {
    opacity: theme.palette.action.disabledOpacity
  },
  [`& + .${_Divider.dividerClasses.root}`]: {
    marginTop: theme.spacing(1),
    marginBottom: theme.spacing(1)
  },
  [`& + .${_Divider.dividerClasses.inset}`]: {
    marginLeft: 52
  },
  [`& .${_ListItemText.listItemTextClasses.root}`]: {
    marginTop: 0,
    marginBottom: 0
  },
  [`& .${_ListItemText.listItemTextClasses.inset}`]: {
    paddingLeft: 36
  },
  [`& .${_ListItemIcon.listItemIconClasses.root}`]: {
    minWidth: 36
  }
}, !styleProps.dense && {
  [theme.breakpoints.up('sm')]: {
    minHeight: 'auto'
  }
}, styleProps.dense && (0, _extends2.default)({
  minHeight: 36
}, theme.typography.body2, {
  [`& .${_ListItemIcon.listItemIconClasses.root} svg`]: {
    fontSize: '1.25rem'
  }
})));
const MenuItem = /*#__PURE__*/React.forwardRef(function MenuItem(inProps, ref) {
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: 'MuiMenuItem'
  });
  const {
    autoFocus = false,
    component = 'li',
    dense = false,
    divider = false,
    disableGutters = false,
    focusVisibleClassName,
    role = 'menuitem',
    tabIndex: tabIndexProp
  } = props,
        other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
  const context = React.useContext(_ListContext.default);
  const childContext = {
    dense: dense || context.dense || false,
    disableGutters
  };
  const menuItemRef = React.useRef(null);
  (0, _useEnhancedEffect.default)(() => {
    if (autoFocus) {
      if (menuItemRef.current) {
        menuItemRef.current.focus();
      } else if (process.env.NODE_ENV !== 'production') {
        console.error('Material-UI: Unable to set focus to a MenuItem whose component has not been rendered.');
      }
    }
  }, [autoFocus]);
  const styleProps = (0, _extends2.default)({}, props, {
    dense: childContext.dense,
    divider,
    disableGutters
  });
  const classes = useUtilityClasses(props);
  const handleRef = (0, _useForkRef.default)(menuItemRef, ref);
  let tabIndex;

  if (!props.disabled) {
    tabIndex = tabIndexProp !== undefined ? tabIndexProp : -1;
  }

  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_ListContext.default.Provider, {
    value: childContext,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(MenuItemRoot, (0, _extends2.default)({
      ref: handleRef,
      role: role,
      tabIndex: tabIndex,
      component: component,
      focusVisibleClassName: (0, _clsx.default)(classes.focusVisible, focusVisibleClassName)
    }, other, {
      styleProps: styleProps,
      classes: classes
    }))
  });
});
process.env.NODE_ENV !== "production" ? MenuItem.propTypes
/* remove-proptypes */
= {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * If `true`, the list item is focused during the first mount.
   * Focus will also be triggered if the value changes from false to true.
   * @default false
   */
  autoFocus: _propTypes.default.bool,

  /**
   * The content of the component.
   */
  children: _propTypes.default.node,

  /**
   * Override or extend the styles applied to the component.
   */
  classes: _propTypes.default.object,

  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: _propTypes.default.elementType,

  /**
   * If `true`, compact vertical padding designed for keyboard and mouse input is used.
   * The prop defaults to the value inherited from the parent Menu component.
   * @default false
   */
  dense: _propTypes.default.bool,

  /**
   * @ignore
   */
  disabled: _propTypes.default.bool,

  /**
   * If `true`, the left and right padding is removed.
   * @default false
   */
  disableGutters: _propTypes.default.bool,

  /**
   * If `true`, a 1px light border is added to the bottom of the menu item.
   * @default false
   */
  divider: _propTypes.default.bool,

  /**
   * This prop can help identify which element has keyboard focus.
   * The class name will be applied when the element gains the focus through keyboard interaction.
   * It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo).
   * The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/master/explainer.md).
   * A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components
   * if needed.
   */
  focusVisibleClassName: _propTypes.default.string,

  /**
   * @ignore
   */
  role: _propTypes.default
  /* @typescript-to-proptypes-ignore */
  .string,

  /**
   * @ignore
   */
  selected: _propTypes.default.bool,

  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: _propTypes.default.object,

  /**
   * @default 0
   */
  tabIndex: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string])
} : void 0;
var _default = MenuItem;
exports.default = _default;


text:
module HelpHelper

  #provides a link to a help page in our documentation, defined by the key and in lib/seek/help/help_links.yml
  #options include:
  # - link_text - the text of the link - default help
  def help_link key, options={}
    options = default_help_options.merge(options)
    if options[:url_only]
      Seek::Help::HelpDictionary.instance.help_link(key)
    else
      link_to options[:link_text],Seek::Help::HelpDictionary.instance.help_link(key),target: :_blank
    end

  end

  def default_help_options
    {
        link_text: 'help'
    }
  end

end


text:
package org.keycloak.authentication.authenticators.client;

import java.security.PublicKey;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import org.jboss.logging.Logger;
import org.keycloak.OAuth2Constants;
import org.keycloak.authentication.AuthenticationFlowError;
import org.keycloak.authentication.ClientAuthenticationFlowContext;
import org.keycloak.common.util.Time;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.keys.loader.PublicKeyStorageManager;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.SingleUseTokenStoreProvider;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.representations.JsonWebToken;
import org.keycloak.services.ServicesLogger;
import org.keycloak.services.Urls;

/**
 * Client authentication based on JWT signed by client private key .
 * See specs for more details.
 *
 * This is server side, which verifies JWT from client_assertion parameter, where the assertion was created on adapter side by
 * org.keycloak.adapters.authentication.JWTClientCredentialsProvider
 *
 * @author Marek Posolda
 */
public class JWTClientAuthenticator extends AbstractClientAuthenticator {

    private static final Logger logger = Logger.getLogger(JWTClientAuthenticator.class);

    public static final String PROVIDER_ID = "client-jwt";
    public static final String ATTR_PREFIX = "jwt.credential";
    public static final String CERTIFICATE_ATTR = "jwt.credential.certificate";

    @Override
    public void authenticateClient(ClientAuthenticationFlowContext context) {
        MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();

        String clientAssertionType = params.getFirst(OAuth2Constants.CLIENT_ASSERTION_TYPE);
        String clientAssertion = params.getFirst(OAuth2Constants.CLIENT_ASSERTION);

        if (clientAssertionType == null) {
            Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type is missing");
            context.challenge(challengeResponse);
            return;
        }

        if (!clientAssertionType.equals(OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT)) {
            Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Parameter client_assertion_type has value '"
                    + clientAssertionType + "' but expected is '" + OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT + "'");
            context.challenge(challengeResponse);
            return;
        }

        if (clientAssertion == null) {
            Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "client_assertion parameter missing");
            context.failure(AuthenticationFlowError.INVALID_CLIENT_CREDENTIALS, challengeResponse);
            return;
        }

        try {
            JWSInput jws = new JWSInput(clientAssertion);
            JsonWebToken token = jws.readJsonContent(JsonWebToken.class);

            RealmModel realm = context.getRealm();
            String clientId = token.getSubject();
            if (clientId == null) {
                throw new RuntimeException("Can't identify client. Issuer missing on JWT token");
            }

            context.getEvent().client(clientId);
            ClientModel client = realm.getClientByClientId(clientId);
            if (client == null) {
                context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
                return;
            } else {
                context.setClient(client);
            }

            if (!client.isEnabled()) {
                context.failure(AuthenticationFlowError.CLIENT_DISABLED, null);
                return;
            }

            // Get client key and validate signature
            PublicKey clientPublicKey = getSignatureValidationKey(client, context, jws);
            if (clientPublicKey == null) {
                // Error response already set to context
                return;
            }

            boolean signatureValid;
            try {
                JsonWebToken jwt = context.getSession().tokens().decodeClientJWT(clientAssertion, client, JsonWebToken.class);
                signatureValid = jwt == null ? false : true;
            } catch (RuntimeException e) {
                Throwable cause = e.getCause() != null ? e.getCause() : e;
                throw new RuntimeException("Signature on JWT token failed validation", cause);
            }
            if (!signatureValid) {
                throw new RuntimeException("Signature on JWT token failed validation");
            }

            // Allow both "issuer" or "token-endpoint" as audience
            String issuerUrl = Urls.realmIssuer(context.getUriInfo().getBaseUri(), realm.getName());
            String tokenUrl = OIDCLoginProtocolService.tokenUrl(context.getUriInfo().getBaseUriBuilder()).build(realm.getName()).toString();
            if (!token.hasAudience(issuerUrl) && !token.hasAudience(tokenUrl)) {
                throw new RuntimeException("Token audience doesn't match domain. Realm issuer is '" + issuerUrl + "' but audience from token is '" + Arrays.asList(token.getAudience()).toString() + "'");
            }

            if (!token.isActive()) {
                throw new RuntimeException("Token is not active");
            }

            // KEYCLOAK-2986
            int currentTime = Time.currentTime();
            if (token.getExpiration() == 0 && token.getIssuedAt() + 10 < currentTime) {
                throw new RuntimeException("Token is not active");
            }

            if (token.getId() == null) {
                throw new RuntimeException("Missing ID on the token");
            }

            SingleUseTokenStoreProvider singleUseCache = context.getSession().getProvider(SingleUseTokenStoreProvider.class);
            int lifespanInSecs = Math.max(token.getExpiration() - currentTime, 10);
            if (singleUseCache.putIfAbsent(token.getId(), lifespanInSecs)) {
                logger.tracef("Added token '%s' to single-use cache. Lifespan: %d seconds, client: %s", token.getId(), lifespanInSecs, clientId);

            } else {
                logger.warnf("Token '%s' already used when authenticating client '%s'.", token.getId(), clientId);
                throw new RuntimeException("Token reuse detected");
            }

            context.success();
        } catch (Exception e) {
            ServicesLogger.LOGGER.errorValidatingAssertion(e);
            Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "unauthorized_client", "Client authentication with signed JWT failed: " + e.getMessage());
            context.failure(AuthenticationFlowError.INVALID_CLIENT_CREDENTIALS, challengeResponse);
        }
    }

    protected PublicKey getSignatureValidationKey(ClientModel client, ClientAuthenticationFlowContext context, JWSInput jws) {
        PublicKey publicKey = PublicKeyStorageManager.getClientPublicKey(context.getSession(), client, jws);
        if (publicKey == null) {
            Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "unauthorized_client", "Unable to load public key");
            context.failure(AuthenticationFlowError.CLIENT_CREDENTIALS_SETUP_REQUIRED, challengeResponse);
            return null;
        } else {
            return publicKey;
        }
    }

    @Override
    public String getDisplayType() {
        return "Signed Jwt";
    }

    @Override
    public boolean isConfigurable() {
        return false;
    }

    @Override
    public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
        return REQUIREMENT_CHOICES;
    }

    @Override
    public String getHelpText() {
        return "Validates client based on signed JWT issued by client and signed with the Client private key";
    }

    @Override
    public List<ProviderConfigProperty> getConfigProperties() {
        return new LinkedList<>();
    }

    @Override
    public List<ProviderConfigProperty> getConfigPropertiesPerClient() {
        // This impl doesn't use generic screen in admin console, but has its own screen. So no need to return anything here
        return Collections.emptyList();
    }

    @Override
    public Map<String, Object> getAdapterConfiguration(ClientModel client) {
        Map<String, Object> props = new HashMap<>();
        props.put("client-keystore-file", "REPLACE WITH THE LOCATION OF YOUR KEYSTORE FILE");
        props.put("client-keystore-type", "jks");
        props.put("client-keystore-password", "REPLACE WITH THE KEYSTORE PASSWORD");
        props.put("client-key-password", "REPLACE WITH THE KEY PASSWORD IN KEYSTORE");
        props.put("client-key-alias", client.getClientId());
        props.put("token-timeout", 10);

        Map<String, Object> config = new HashMap<>();
        config.put("jwt", props);
        return config;
    }

    @Override
    public String getId() {
        return PROVIDER_ID;
    }

    @Override
    public Set<String> getProtocolAuthenticatorMethods(String loginProtocol) {
        if (loginProtocol.equals(OIDCLoginProtocol.LOGIN_PROTOCOL)) {
            Set<String> results = new HashSet<>();
            results.add(OIDCLoginProtocol.PRIVATE_KEY_JWT);
            return results;
        } else {
            return Collections.emptySet();
        }
    }
}


text:
This exercise was birthed trying to find a simpler way to deploy NextGen architecture in development. A glaringly obvious observation was that NextGen is more than just services, it is also the infrastructure (KV stores, service discovery, databases, tooling) that go into making our microservices run.

Initial Goals:

  1. Automate infrastructure for single instance deployment
  2. On-demand deployment of microservices, more on this below
  3. Support declarative service definitions

Motivations:

  1. It's cubersome to spin up NextGen infrastructure. Intimate knowledge of docker/linux networking is required to get an environment working. How do we make microservice development easier?

  2. Our first pass had us deploying containers manually with `nomad run`.  This is not production worthy. How can we automate service deployment?  How do we manage the service definitions?

  3. How do we run services on demand? If there are no indexing jobs, why should there be indexing services running?  What about in development?  Why would we want to run 500 microservices in development when we're only working with a handful?

On Demand Service Deployment:

There are several pieces to this experiment.

  1. Gateway - the front-facing application that will interact with microservices. In theory it could exist inside a docker infrastructure. For the sake of this example (and because our current monolith is not in docker, it will be deployed separately from the rest of the infrastructure.

  2. On-Demand Services - the microservices that do the heavy lifting.

Additionally, I've created an abstraction for managing the actual services.  This is by no-means compulsory as there are other ways that services could be lauched, such as directly invoking service deployments.


text:
<ion-modal-view>
	<ion-header-bar class="bar-dark">
		<button class="button button-clear button-light" ng-click="replyMessage()">Reply</button>

{{message.subject}}

		<button class="button button-clear button-light" ng-click="closeMessage()">Close</button>
	</ion-header-bar>

	<ion-content style="background-color:black;">

	</ion-content>

</ion-modal-view>


text:
String.prototype.width = function(font) {
  var f = font || '12px arial',
      o = $('<div>' + this + '</div>')
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}

angular.module( 'ngFitText', [] )
.directive( 'fittext', [ function() {
	return {
		restrict: 'A',
		scope: true,
		transclude: true,
		replace: true,
		template: function( element, attrs ) {
			var tag = element[0].nodeName;
			return "<"+tag+" data-ng-transclude data-ng-style='{fontSize:fontSize}'></"+tag+">";
		},
		link: function( scope, element, attrs ) {
			scope.compressor = attrs.fittext || 1;
			scope.minFontSize = attrs.fittextMin || Number.NEGATIVE_INFINITY;
			scope.maxFontSize = attrs.fittextMax || Number.POSITIVE_INFINITY;

			var resizer = function(text) {
                var blockContents = text || element[0].innerText;
                scope.fontSize = Math.max(
                    Math.min(
                        scope.compressor * 12 * window.innerWidth / blockContents.width(),
                        parseFloat(scope.maxFontSize)
                    ),
                    parseFloat(scope.minFontSize)
                ) + 'px';
                console.log(blockContents, blockContents.width(), scope.fontSize, scope.minFontSize, scope.maxFontSize);
			};

			angular.element( document ).ready( function() {
				resizer();
                scope.$on('changedword', function(event, text) { resizer(text); });
			});

			angular.element( window ).bind( 'resize', function() {
				scope.$apply(resizer);
			});

		}
	}
}]);


text:
PUT List containing Map of floats with PHP serializer.

--FILE--
<?php
include dirname(__FILE__)."/../../astestframework/astest-phpt-loader.inc";
aerospike_phpt_runtest("Put", "testPutListMapObjectsWithPHPSerializer");
--EXPECT--
OK


text:
from typing import Union

import torch
from torch.nn.modules.loss import _Loss

from monai.metrics.utils import do_metric_reduction
from monai.utils import MetricReduction

from .metric import CumulativeIterationMetric

class LossMetric(CumulativeIterationMetric):
    """
    A wrapper to make ``loss_fn`` available as a cumulative metric. That is, the loss values computed from
    mini-batches can be combined in the ``reduction`` mode across multiple iterations, as a quantitative measurement
    of a model.

    Example:

    .. code-block:: python

        import torch
        from monai.losses import DiceLoss
        from monai.metrics import LossMetric

        dice_loss = DiceLoss(include_background=True)
        loss_metric = LossMetric(loss_fn=dice_loss)

        # first iteration
        y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 1.0]]]])  # shape [batch=1, channel=1, 2, 2]
        y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])  # shape [batch=1, channel=1, 2, 2]
        loss_metric(y_pred, y)

        # second iteration
        y_pred = torch.tensor([[[[1.0, 0.0], [0.0, 0.0]]]])  # shape [batch=1, channel=1, 2, 2]
        y = torch.tensor([[[[1.0, 0.0], [1.0, 1.0]]]])  # shape [batch=1, channel=1, 2, 2]
        loss_metric(y_pred, y)

        # aggregate
        print(loss_metric.aggregate(reduction="none"))  # tensor([[0.2000], [0.5000]]) (shape [batch=2, channel=1])

        # reset
        loss_metric.reset()
        print(loss_metric.aggregate())

    Args:
        loss_fn: a callable function that takes ``y_pred`` and optionally ``y`` as input (in the "batch-first" format),
            returns a "batch-first" tensor of loss values.
        reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values,
            available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``,
            ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction.
        get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans).
            Here `not_nans` count the number of not nans for the metric, thus its shape equals to the shape of the metric.

    """

    def __init__(
        self, loss_fn: _Loss, reduction: Union[MetricReduction, str] = MetricReduction.MEAN, get_not_nans: bool = False
    ) -> None:
        super().__init__()
        self.loss_fn = loss_fn
        self.reduction = reduction
        self.get_not_nans = get_not_nans

    def aggregate(self, reduction: Union[MetricReduction, str, None] = None):
        """
        Returns the aggregated loss value across multiple iterations.

        Args:
            reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values,
                available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``,
                ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction.
        """
        data = self.get_buffer()
        if data is None:
            return (torch.tensor(0.0), torch.tensor(0.0)) if self.get_not_nans else torch.tensor(0.0)
        f, not_nans = do_metric_reduction(data, reduction or self.reduction)
        return (f, not_nans) if self.get_not_nans else f

    def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor = None):  # type: ignore
        """
        Input `y_pred` is compared with ground truth `y`.
        Both `y_pred` and `y` are expected to be a batch-first Tensor (BC[HWD]).

        Returns:
             a tensor with shape (BC[HWD]), or a list of tensors, each tensor with shape (C[HWD]).
        """
        iter_loss = self.loss_fn(y_pred) if y is None else self.loss_fn(y_pred, y)
        if isinstance(iter_loss, torch.Tensor):
            while iter_loss.dim() < 2:
                iter_loss = iter_loss[None]
        # to be compatible with `Cumulative`, iter_loss should at least have a batch dim.
        # to be compatible with `do_metric_reduction`, iter_loss should at least have a batch and a channel dim.
        return iter_loss


text:
import React, { useState, useCallback, useEffect } from 'react';
import Episode from './episode';
import { ISeason } from '../lib/types';

type Props = {
  showId: string;
  seasons: Array<ISeason>;
};

export default function Seasons({ showId, seasons }: Props) {
  const [currentSeasonNum, setCurrentSeasonNum] = useState(1);
  const [currentSeason, setCurrentSeason] = useState<ISeason>(null);

  const selectOnChange = useCallback(
    (e) => {
      setCurrentSeasonNum(parseInt(e.target.value));
    },
    [setCurrentSeasonNum],
  );

  useEffect(() => {
    if (!seasons || seasons.length === 0) return setCurrentSeason(null);
    const filtered = seasons.filter((s) => s.number === currentSeasonNum);
    setCurrentSeason(filtered[0]);
  }, [seasons, currentSeasonNum]);

  const selector = (

        <svg
          className="w-6 h-6"
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 20 20"
          fill="currentColor"
        >
          <path
            fillRule="evenodd"
            d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
            clipRule="evenodd"
          />
        </svg>

      <select
        className="px-3 py-2 pr-10 rounded-md font-medium bg-gray-200 text-gray-800 appearance-none"
        value={currentSeasonNum}
        onChange={selectOnChange}
      >
        {seasons.map((season) => {
          const { number } = season;
          return (
            <option key={number} value={number}>
              Season {number}
            </option>
          );
        })}
      </select>

  );

  return !currentSeason ? null : (

{selector}

          {currentSeason.episodes.length || '0'} episodes

        {currentSeason.episodes.map((episode) => {
          const { season, number } = episode;
          return (
            <Episode
              key={getEpisodeId(season, number)}
              ratingsAPIPath={`/api/shows/${showId}/seasons/${season}/episode/${number}/ratings`}
              getEpisodeId={getEpisodeId}
              {...episode}
            />
          );
        })}

  );
}

function getEpisodeId(season: number, episode: number) {
  const episodeFormatted = episode.toLocaleString('en-US', {
    minimumIntegerDigits: 2,
  });
  return `${season}×${episodeFormatted}`;
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("eventstore", "0030_add_covid19_confirmed_contact_fields")]

    operations = [
        migrations.AddIndex(
            model_name="covid19triage",
            index=models.Index(
                fields=["msisdn", "timestamp"], name="eventstore__msisdn_dbf292_idx"
            ),
        )
    ]


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ScrollView
        android:id="@+id/controller_scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:scrollbars="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/radio_selector"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:text="TextView" />

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/radio_selector"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:text="TextView" />
            </LinearLayout>

            <RadioGroup
                android:id="@+id/radioGroup1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <RadioButton
                    android:id="@+id/radio0"
                    style="@style/radioButton"
                    android:checked="true"
                    android:text="RadioButton" />

                <RadioButton
                    android:id="@+id/radio1"
                    style="@style/radioButton"
                    android:checked="false"
                    android:text="RadioButton" />
            </RadioGroup>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginTop="10dp"
                android:background="#000000"
                android:text="layout_margin"
                android:textColor="#ff0000"
                android:textSize="30sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#000000"
                android:padding="20sp"
                android:text="padding"
                android:textColor="#ff0000"
                android:textSize="30sp" />

            <TextView
                android:layout_width="150dp"
                android:layout_height="50dp"
                android:layout_margin="1sp"
                android:background="#000000"
                android:padding="1sp"
                android:singleLine="true"
                android:text="singleLine   singleLine   b  singleLine"
                android:textColor="#ff0000"
                android:textSize="20sp" />

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button" />

            <TextView
                android:id="@+id/controller_txtmarquee"
                android:layout_width="150sp"
                android:layout_height="wrap_content"
                android:layout_margin="5sp"
                android:background="#000000"
                android:ellipsize="marquee"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:marqueeRepeatLimit="2"
                android:padding="1sp"
                android:singleLine="true"
                android:text="跑马灯效果,循环次数 跑马灯效果,循环次数跑循环次数跑马灯效果,循环次数======"
                android:textColor="#ff0000"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/controller_textView1"
                style="@style/myTxt_Style"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:text="focusable" />

            <TextView
                style="@style/myTxt_Style"
                android:text="style:123456" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="3sp"
                android:autoLink="phone"
                android:background="#000000"
                android:padding="3sp"
                android:text="phone:18055150837"
                android:textColor="#ff0000"
                android:textSize="30sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="3sp"
                android:autoLink="email"
                android:background="#000000"
                android:padding="1px"
                android:text="ppok21@163.com"
                android:textColor="#ff0000"
                android:textSize="30sp" />

            <TextView
                android:id="@+id/txtweb"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="all"
                android:text="@string/controller_myweb"
                android:textColor="#ff0000"
                android:textSize="30sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawableLeft="@drawable/ic_launcher"
                android:shadowColor="#0000ff"
                android:shadowDx="10"
                android:shadowDy="10"
                android:shadowRadius="3"
                android:text="测试阴影"
                android:textColor="#ff0000"
                android:textSize="50sp" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>


text:
package org.javamoney.moneta.spi.loader;

import javax.money.MonetaryException;
import java.io.*;
import java.nio.file.Files;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Default implementation of {@link ResourceCache}, using the local file system.
 *
 * @author Anatole Tresch
 */
public class DefaultResourceCache implements ResourceCache {
    /**
     * The logger used.
     */
    private static final Logger LOG = Logger.getLogger(DefaultResourceCache.class.getName());
    /**
     * Suffix for files created.
     */
    private static final String SUFFIX = ".dat";
    /**
     * Local temp directory.
     */
    private File localDir = new File(System.getProperty("temp.dir", ".resourceCache"));
    /**
     * Cached resources.
     */
    private final Map<String, File> cachedResources = new ConcurrentHashMap<>();

    /**
     * Constructor.
     */
    public DefaultResourceCache() {
        if (!localDir.exists()) {
            if (!localDir.mkdirs()) {
                LOG.severe("Error creating cache dir  " + localDir + ", resource cache disabled!");
                localDir = null;
            } else {
                LOG.finest("Created cache dir  " + localDir);
            }
        } else if (!localDir.isDirectory()) {
            LOG.severe("Error initializing cache dir  " + localDir + ", not a directory, resource cache disabled!");
            localDir = null;
        } else if (!localDir.canWrite()) {
            LOG.severe("Error initializing cache dir  " + localDir + ", not writable, resource cache disabled!");
            localDir = null;
        }
        if (localDir!=null) {
            File[] files = localDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        String resourceId = file.getName().substring(0, file.getName().length() - 4);
                        cachedResources.put(resourceId, file);
                    }
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.javamoney.moneta.loader.format.ResourceCache#write(java.lang.String
     * , byte[])
     */
    @Override
    public void write(String resourceId, byte[] data) {
        try {
            File file = this.cachedResources.get(resourceId);
            if (file==null) {
                file = new File(localDir, resourceId + SUFFIX);
                Files.write(file.toPath(), data);
                this.cachedResources.put(resourceId, file);
            } else {
                Files.write(file.toPath(), data);
            }
        } catch (Exception e) {
            LOG.log(Level.WARNING, "Caching of resource failed: " + resourceId, e);
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.javamoney.moneta.loader.format.ResourceCache#isCached(java.lang
     * .String)
     */
    @Override
    public boolean isCached(String resourceId) {
        return this.cachedResources.containsKey(resourceId);
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.javamoney.moneta.loader.format.ResourceCache#read(java.lang.String)
     */
    @Override
    public byte[] read(String resourceId) {
        File f = this.cachedResources.get(resourceId);
        if (f==null) {
            return null;
        }
        try {
			return Files.readAllBytes(f.toPath());
		} catch (IOException exception) {
			throw new MonetaryException("An error on retrieve the resource id: " + resourceId, exception);
		}
    }

    @Override
    public void clear(String resourceId) {
        File f = this.cachedResources.get(resourceId);
        if (f != null) {
            if (f.exists()) {
                if (!f.delete()) {
                    LOG.warning("Failed to delete caching file: " + f.getAbsolutePath());
                }
            }
            this.cachedResources.remove(resourceId);
        }
    }

    @Override
    public String toString() {
        return "DefaultResourceCache [localDir=" + localDir + ", cachedResources=" + cachedResources + ']';
    }

}


text:
package cz.metacentrum.perun.core.impl.modules.attributes;

import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.bl.AttributesManagerBl;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class urn_perun_user_attribute_def_virt_optional_login_namespaceTest {

	private static urn_perun_user_attribute_def_virt_optional_login_namespace classInstance;
	private static PerunSessionImpl session;
	private static User user;
	private static Attribute attributeToCheck;

	@Before
	public void setUp() throws Exception {
		classInstance = new urn_perun_user_attribute_def_virt_optional_login_namespace();
		session = mock(PerunSessionImpl.class);

		attributeToCheck = new Attribute();
		attributeToCheck.setNamespace(AttributesManager.NS_USER_ATTR_DEF);
		attributeToCheck.setFriendlyName("login-namespace:einfra");
		attributeToCheck.setValue("test");

		String namespace = AttributesManager.NS_USER_ATTR_DEF + ":login-namespace:" + attributeToCheck.getFriendlyNameParameter();
		when(session.getPerunBl()).thenReturn(mock(PerunBl.class));
		when(session.getPerunBl().getAttributesManagerBl()).thenReturn(mock(AttributesManagerBl.class));
		when(session.getPerunBl().getAttributesManagerBl().getAttribute(session, user, namespace)).thenReturn(attributeToCheck);
	}

	@Test
	public void testCheckWithAttribute() {
		System.out.println("testCheckWithAttribute()");
		attributeToCheck.setValue("test-value");

		Attribute attr = new Attribute();
		attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT);
		attr.setFriendlyName("optional-login-namespace:einfra");

		assertEquals(attributeToCheck.getValue(), classInstance.getAttributeValue(session, user, attr).getValue());
	}

	@Test
	public void testCheckWithNull() {
		System.out.println("testCheckWithNull()");
		attributeToCheck.setValue(null);

		Attribute attr = new Attribute();
		attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT);
		attr.setFriendlyName("optional-login-namespace:einfra");

		assertNull(classInstance.getAttributeValue(session, user, attr).getValue());
	}
}


text:
var models = require('../../models')
  , lib = require('../../lib')
  , NotifModel = models.NotifModel
  ;

exports.show = function(req, res) {
  NotifModel.find({username:'you'}, function(err, docs){
		if (err)
			throw err;
  res.render('notifications/display', {
    title: 'Notifications',
	Notifications: docs
	});
});
};


text:
@interface PetsSellerViewModel :BaseViewModel
//UI
//头部广告

//cell
//商家信息
-(NSURL *)sellerHeadPic:(NSInteger)section;//商家头像
-(NSString *)sellerName:(NSInteger)section;//商家名称
-(NSString *)sellerAddress:(NSInteger)section;//商家地址
-(NSString *)weekCount:(NSInteger)section;//周发布量
//宠物信息
-(NSURL *)petsPic:(NSInteger)section item:(NSInteger)item;//宠物图片
-(NSString *)petsName:(NSInteger)section item:(NSInteger)item;//宠物名字
-(NSString *)petsPrice:(NSInteger)section item:(NSInteger)item;//宠物价格
-(NSString *)createdTime:(NSInteger)section item:(NSInteger)item;// 信息发布时间
//宠物详情页URL
-(NSURL *)petsURLForItem:(NSInteger)section item:(NSInteger)item;
//宠物个数(item个数)
-(NSInteger)numberPets:(NSInteger)section;
//分区个数
@property(nonatomic,readonly)NSInteger sectionNumber;

//商家页面
//vip认证
-(NSString *)vip:(NSInteger)section;
//星星分数
-(NSInteger)score:(NSInteger)section;

//商家简介 地址同上面sellerAddress
-(NSString *)contactName:(NSInteger)section;//联系名称
-(NSString *)contactAbout:(NSInteger)section;//商家简介描述

//商家电话 电话按钮
-(NSString *)contactMobile:(NSInteger)section;

//宝贝页面
//是否在售
-(BOOL)hasClosed:(NSInteger)row;
//是否商家认证
-(BOOL)hasVip:(NSInteger)row;
-(NSURL *)spetsPic:(NSInteger)row ;//宠物图片
-(NSString *)spetsName:(NSInteger)row;//宠物名字
-(NSString *)spetsPrice:(NSInteger)row;//宠物价格
-(NSURL *)spetsURLForItem:(NSInteger)row;//宠物详情页URL
@property(nonatomic,readonly)NSInteger rowNumber;

-(NSString *)areaName:(NSInteger)row;//地区
-(NSInteger)petsID:(NSInteger)row;//宠物ID;

//商家id
-(NSInteger)sellerID:(NSInteger)section;

//Model
@property(nonatomic,readonly)NSInteger cityID;//商家ID
@property(nonatomic,assign)NSInteger start;//起始offset位置
@property(nonatomic)NSMutableArray<PetsSellerValuesModel *> *sellerData;//商家数据
-(void)getData:(NSInteger)cityID  WithMode:(RequestMode)requestMode completionHandler:(void (^)(NSError *error))completionHandler;

@property(nonatomic)NSMutableArray<SPetsValuesModel *> *sPetsData;//商家宝贝数据

-(void)getDataPets:(NSInteger)sellerID  WithMode:(RequestMode)requestMode completionHandler:(void (^)(NSError *error))completionHandler;

@end


text:
package org.vibur.dbcp.util;

import org.vibur.dbcp.ViburConfig;
import org.vibur.objectpool.BasePool;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;

import static java.lang.Integer.toHexString;

/**
 * @author Simeon Malchev
 */
public final class ViburUtils {

    private ViburUtils() { }

    /**
     * Returns the extended pool name formatted as:
     * <blockquote>{@code poolName@hashCode(currentlyTakenConns/remainingCreatedConns/poolMaxSize/poolState/threadInterruptedStatus)}</blockquote>
     * For example, {@code p1@2db7a79b(1/1/10/w/n)}.
     *
     * @param config the Vibur config
     */
    public static String getPoolName(ViburConfig config) {
        BasePool pool = config.getPool();
        boolean initialState = pool.isTerminated();
        String result = config.getName() + '@' + toHexString(config.hashCode())
                + '(' + pool.taken() + '/' + pool.remainingCreated() + '/' + pool.maxSize()
                + '/' + (!initialState ? 'w' : 't')  // poolState: w == working, t == terminated
                + '/' + (Thread.currentThread().isInterrupted() ? 'i' : 'n') + ')';
        if (initialState == pool.isTerminated()) { // make sure the pool state has not changed in the meantime
            return result;
        }
        return getPoolName(config); // this is one level of recursion only, pool state changes only once
    }

    public static String getStackTraceAsString(Pattern logLinePattern, StackTraceElement[] stackTrace) {
        if (stackTrace == null || stackTrace.length == 0) {
            return "EMPTY STACK TRACE\n";
        }

        int i;
        for (i = 0; i < stackTrace.length; i++) {
            if (!stackTrace[i].getClassName().startsWith("org.vibur")
                || stackTrace[i].getMethodName().equals("getConnection")) {
                break;
            }
        }

        StringBuilder builder = new StringBuilder(4096);
        for (i++; i < stackTrace.length; i++) {
            String stackTraceStr = stackTrace[i].toString();
            if (logLinePattern == null || logLinePattern.matcher(stackTraceStr).matches()) {
                builder.append("  at ").append(stackTraceStr).append('\n');
            }
        }
        return builder.toString();
    }

    public static String formatSql(String sqlQuery, List<Object[]> sqlQueryParams) {
        StringBuilder result = new StringBuilder(1024).append("-- ").append(sqlQuery);

        if (sqlQueryParams != null && !sqlQueryParams.isEmpty()) {
            Object[] params = sqlQueryParams.toArray();
            Arrays.sort(params, new Comparator<Object>() {
                @Override
                public int compare(Object o1, Object o2) {
                    return ((Object[]) o1)[1].toString().compareTo(((Object[]) o2)[1].toString());
                }
            });

            result.append("\n-- Parameters:\n-- ").append(Arrays.deepToString(params));
        }
        return result.toString();
    }
}


text:
package com.syncleus.aethermud.entity;

import com.google.common.base.Function;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
import com.syncleus.aethermud.Main;
import com.syncleus.aethermud.core.SentryManager;
import com.syncleus.aethermud.items.ItemInstance;
import com.syncleus.aethermud.items.ItemBuilder;
import com.syncleus.aethermud.npc.NpcSpawn;
import com.syncleus.aethermud.player.Player;
import com.syncleus.aethermud.player.PlayerManager;
import com.syncleus.aethermud.storage.graphdb.GraphDbAetherMudStorage;
import com.syncleus.aethermud.storage.graphdb.GraphStorageFactory;
import com.syncleus.aethermud.storage.graphdb.model.ItemInstanceData;
import com.syncleus.aethermud.world.RoomManager;
import com.syncleus.aethermud.world.model.Room;
import org.apache.log4j.Logger;

import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

import static com.codahale.metrics.MetricRegistry.name;

public class EntityManager {

    private static final Logger log = Logger.getLogger(EntityManager.class);

    private final GraphStorageFactory graphStorageFactory;
    private final RoomManager roomManager;
    private final PlayerManager playerManager;
    private final Map<String, NpcSpawn> npcs = new ConcurrentHashMap<>();
    private final Map<String, AetherMudEntity> entities = new ConcurrentHashMap<>();
    private final ExecutorService mainTickExecutorService = Executors.newFixedThreadPool(50);
    private final Interner<String> interner = Interners.newWeakInterner();

    public EntityManager(GraphStorageFactory graphStorageFactory, RoomManager roomManager, PlayerManager playerManager) {
        this.graphStorageFactory = graphStorageFactory;
        this.roomManager = roomManager;
        this.playerManager = playerManager;
        ExecutorService tickOrchestratorService = Executors.newFixedThreadPool(5);
        tickOrchestratorService.submit(new PlayerTicker());
        tickOrchestratorService.submit(new RoomTicker());
        tickOrchestratorService.submit(new NpcTicker());
        tickOrchestratorService.submit(new EntityTicker());
    }

    public Map<String, NpcSpawn> getNpcs() {
        return npcs;
    }

    public Map<String, AetherMudEntity> getEntities() {
        return entities;
    }

    public void addEntity(AetherMudEntity aetherMudEntity) {
        if (aetherMudEntity instanceof NpcSpawn) {
            NpcSpawn npcSpawn = (NpcSpawn) aetherMudEntity;
            npcs.put(aetherMudEntity.getEntityId(), npcSpawn);
        } else if (aetherMudEntity instanceof Room) {
            roomManager.addRoom((Room) aetherMudEntity);
        } else {
            entities.put(aetherMudEntity.getEntityId(), aetherMudEntity);
        }
    }

    public void saveItem(ItemInstance item) {
        synchronized (interner.intern(item.getItemId())) {
            this.transact(storage -> storage.saveItemEntity(item));
        }
    }

    public void removeItem(ItemInstance item) {
        synchronized (interner.intern(item.getItemId())) {
            this.consume(storage -> storage.removeItemEntity(item.getItemId()));
        }
    }

    public void removeItem(String itemId) {
        synchronized (interner.intern(itemId)) {
            this.consume(storage -> storage.removeItemEntity(itemId));
        }
    }

    public Optional<ItemInstance> getItemEntity(String itemId) {
        synchronized (interner.intern(itemId)) {
            return this.transactRead(storage -> {
                Optional<ItemInstanceData> item = storage.getItemEntity(itemId);
                return item.map(itemData -> new ItemBuilder().from(ItemInstanceData.copyItem(itemData)).create());
            });
        }
    }

    public void deleteNpcEntity(String npcId) {
        npcs.remove(npcId);
    }

    public NpcSpawn getNpcEntity(String npcId) {
        return npcs.get(npcId);
    }

    public static final int SLEEP_MILLIS = 500;

    private <T> T transact(Function<GraphDbAetherMudStorage, T> func) {
        try( GraphStorageFactory.AetherMudTx tx = this.graphStorageFactory.beginTransaction() ) {
            T retVal = func.apply(tx.getStorage());
            tx.success();
            return retVal;
        }
    }

    private void consume(Consumer<GraphDbAetherMudStorage> func) {
        try( GraphStorageFactory.AetherMudTx tx = this.graphStorageFactory.beginTransaction() ) {
            func.accept(tx.getStorage());
            tx.success();
        }
    }

    private <T> T transactRead(Function<GraphDbAetherMudStorage, T> func) {
        try( GraphStorageFactory.AetherMudTx tx = this.graphStorageFactory.beginTransaction() ) {
            return func.apply(tx.getStorage());
        }
    }

    class PlayerTicker implements Runnable {
        private final com.codahale.metrics.Timer ticktime = Main.metrics.timer(name(EntityManager.class, "player_tick_time"));

        @Override
        public void run() {
            while (true) {
                try {
                    final com.codahale.metrics.Timer.Context context = ticktime.time();
                    Iterator<Map.Entry<String, Player>> players = playerManager.getPlayers();
                    while (players.hasNext()) {
                        Map.Entry<String, Player> next = players.next();
                        mainTickExecutorService.submit(next.getValue());
                    }
                    context.stop();
                    Thread.sleep(SLEEP_MILLIS);
                } catch (Exception e) {
                    log.error("Problem with player ticker!", e);
                    SentryManager.logSentry(this.getClass(), e, "Problem with player ticker!");
                }
            }
        }
    }

    class RoomTicker implements Runnable {
        private final com.codahale.metrics.Timer ticktime = Main.metrics.timer(name(EntityManager.class, "room_tick_time"));

        @Override
        public void run() {
            while (true) {
                try {
                    final com.codahale.metrics.Timer.Context context = ticktime.time();
                    Iterator<Map.Entry<Integer, Room>> rooms = roomManager.getRoomsIterator();
                    while (rooms.hasNext()) {
                        Map.Entry<Integer, Room> next = rooms.next();
                        mainTickExecutorService.submit(next.getValue());
                    }
                    context.stop();
                    Thread.sleep(SLEEP_MILLIS);
                } catch (Exception e) {
                    log.error("Problem with room ticker!", e);
                    SentryManager.logSentry(this.getClass(), e, "Problem with room ticker!");
                }
            }
        }
    }

    class NpcTicker implements Runnable {
        private final com.codahale.metrics.Timer ticktime = Main.metrics.timer(name(EntityManager.class, "npc_tick_time"));

        @Override
        public void run() {
            while (true) {
                try {
                    final com.codahale.metrics.Timer.Context context = ticktime.time();
                    for (Map.Entry<String, NpcSpawn> next : npcs.entrySet()) {
                        mainTickExecutorService.submit(next.getValue());
                    }
                    context.stop();
                    Thread.sleep(SLEEP_MILLIS);
                } catch (Exception e) {
                    log.error("Problem with npc ticker!", e);
                    SentryManager.logSentry(this.getClass(), e, "Problem with npc ticker!");
                }
            }
        }
    }

    class EntityTicker implements Runnable {
        private final com.codahale.metrics.Timer ticktime = Main.metrics.timer(name(EntityManager.class, "entity_tick_time"));

        @Override
        public void run() {
            while (true) {
                try {
                    final com.codahale.metrics.Timer.Context context = ticktime.time();
                    for (Map.Entry<String, AetherMudEntity> next : entities.entrySet()) {
                        mainTickExecutorService.submit(next.getValue());
                    }
                    context.stop();
                    Thread.sleep(SLEEP_MILLIS);
                } catch (Exception e) {
                    log.error("Problem with entity ticker!", e);
                    SentryManager.logSentry(this.getClass(), e, "Problem with entity ticker!");
                }
            }
        }
    }
}


text:
<?php

namespace Sylius\Bundle\ProductBundle;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use Sylius\Bundle\ResourceBundle\DependencyInjection\Compiler\ResolveDoctrineTargetEntitiesPass;
use Sylius\Bundle\ResourceBundle\SyliusResourceBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Product management bundle with highly flexible architecture.
 * Implements basic product model with properties support.
 *
 * Use *SyliusVariableProductBundle* to get variants, options and
 * customizations support.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
class SyliusProductBundle extends Bundle
{
    /**
     * Return array with currently supported drivers.
     *
     * @return array
     */
    public static function getSupportedDrivers()
    {
        return array(
            SyliusResourceBundle::DRIVER_DOCTRINE_ORM
        );
    }

    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        $interfaces = array(
            'Sylius\Bundle\ProductBundle\Model\ProductInterface'         => 'sylius.model.product.class',
            'Sylius\Bundle\ProductBundle\Model\PropertyInterface'        => 'sylius.model.property.class',
            'Sylius\Bundle\ProductBundle\Model\ProductPropertyInterface' => 'sylius.model.product_property.class',
            'Sylius\Bundle\ProductBundle\Model\PrototypeInterface'       => 'sylius.model.prototype.class',
        );

        $container->addCompilerPass(new ResolveDoctrineTargetEntitiesPass('sylius_product', $interfaces));

        $mappings = array(
            realpath(__DIR__ . '/Resources/config/doctrine/model') => 'Sylius\Bundle\ProductBundle\Model',
        );

        $container->addCompilerPass(DoctrineOrmMappingsPass::createXmlMappingDriver($mappings, array('doctrine.orm.entity_manager'), 'sylius_product.driver.doctrine/orm'));
    }
}


text:
package org.drools.guvnor.client.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * The GWT StackPanel is not working as we want. So doing a custom one.
 */
public class LazyStackPanel extends Composite
        implements
        HasSelectionHandlers<LazyStackPanelRow> {

    private FlexTable flexTable = new FlexTable();
    private int rowIndex = 0;

    public LazyStackPanel() {

        initWidget(flexTable);

        flexTable.setStyleName("guvnor-lazyStackPanel");

        addSelectionHandler(new SelectionHandler<LazyStackPanelRow>() {

            public void onSelection(SelectionEvent<LazyStackPanelRow> event) {
                LazyStackPanelRow row = event.getSelectedItem();
                if (row.isExpanded()) {
                    row.compress();
                } else {
                    row.expand();
                }
            }
        });
    }

    /**
     * Add a new (collapsed) element to the stack.
     * @param headerText
     * @param contentLoad
     */
    public void add(String headerText,
            LoadContentCommand contentLoad) {
        this.add(headerText, contentLoad, false);
    }

    public void add(String headerText,
            LoadContentCommand contentLoad, boolean expanded) {

        LazyStackPanelHeader header = new LazyStackPanelHeader(headerText);

        add(header,
                contentLoad, expanded);

    }

    /**
     * Add a new (collapsed) element to the stack.
     * @param headerText
     * @param contentLoad
     */
    public void add(AbstractLazyStackPanelHeader header,
            LoadContentCommand contentLoad) {
        this.add(header, contentLoad, false);
    }

    public void add(AbstractLazyStackPanelHeader header,
            LoadContentCommand contentLoad, boolean expanded) {
        final LazyStackPanelRow row = new LazyStackPanelRow(header,
                contentLoad);

        header.addOpenHandler(new OpenHandler<AbstractLazyStackPanelHeader>() {

            public void onOpen(OpenEvent<AbstractLazyStackPanelHeader> event) {
                selectRow(row);
            }
        });

        header.addCloseHandler(new CloseHandler<AbstractLazyStackPanelHeader>() {

            public void onClose(com.google.gwt.event.logical.shared.CloseEvent<AbstractLazyStackPanelHeader> event) {
                selectRow(row);
            }
        });

        addHeaderRow(row);

        addContentRow(row.getContentPanel());

        if (expanded){
            header.expand();
        }
    }

    private void addHeaderRow(final LazyStackPanelRow row) {
        flexTable.setWidget(rowIndex,
                0,
                row);
        flexTable.getFlexCellFormatter().setStyleName(rowIndex,
                0,
                "guvnor-LazyStackPanel-row-header");
        rowIndex++;
    }

    private void addContentRow(final SimplePanel panel) {
        flexTable.setWidget(rowIndex++,
                0,
                panel);
    }

    private void selectRow(LazyStackPanelRow row) {
        SelectionEvent.fire(this,
                row);
    }

    public HandlerRegistration addSelectionHandler(SelectionHandler<LazyStackPanelRow> handler) {
        return addHandler(handler,
                SelectionEvent.getType());
    }

    public void swap(int firstIndex,
            int secondIndex) {

        // Every list item is made of the header and content row.
        // So we have twice as many rows.
        firstIndex = firstIndex * 2;
        secondIndex = secondIndex * 2;

        Widget firstHeader = flexTable.getWidget(firstIndex,
                0);
        Widget firstContent = flexTable.getWidget(firstIndex + 1,
                0);
        Widget secondHeader = flexTable.getWidget(secondIndex,
                0);
        Widget secondContent = flexTable.getWidget(secondIndex + 1,
                0);

        flexTable.setWidget(firstIndex,
                0,
                secondHeader);
        flexTable.setWidget(firstIndex + 1,
                0,
                secondContent);
        flexTable.setWidget(secondIndex,
                0,
                firstHeader);
        flexTable.setWidget(secondIndex + 1,
                0,
                firstContent);
    }

    public Iterator<AbstractLazyStackPanelHeader> getHeaderIterator() {
        List<AbstractLazyStackPanelHeader> result = new ArrayList<AbstractLazyStackPanelHeader>();
        Iterator<Widget> iterator = flexTable.iterator();

        while (iterator.hasNext()) {
            Widget widget = (Widget) iterator.next();
            if (widget instanceof LazyStackPanelRow) {
                result.add(((LazyStackPanelRow) widget).getHeader());
            }
        }

        return result.iterator();
    }

    public void remove(int index) {

        index = index * 2;

        flexTable.removeRow(index + 1);
        flexTable.removeRow(index);
    }
}


text:
'use strict';

var _ym = require('util/ym.js');

var _payment = {
    //获取支付信息
    getPaymentInfo : function(orderNumber, resolve, reject) {
        _ym.request({
            url     : _ym.getServerUrl('/order/pay.do'),
            data    : {
                orderNo : orderNumber
            },
            success : resolve,
            error   : reject,
        });
    },
    //查看订单状态(轮询)
    getPaymentStatus : function(orderNumber, resolve, reject) {
        _ym.request({
            url     : _ym.getServerUrl('/order/query_order_pay_status.do'),
            data    : {
                orderNo : orderNumber
            },
            success : resolve,
            error   : reject,
        });
    },
};

module.exports = _payment;


text:
#ifndef DRAKEGRADIENTUTIL_H_
#define DRAKEGRADIENTUTIL_H_

#include <Eigen/Core>
#include <Eigen/Dense>
#include <unsupported/Eigen/AutoDiff>
#include <cmath>
#include <vector>
#include <array>
#include <cassert>
#include <stdexcept>

template<std::size_t Size>
std::array<int, Size> intRange(int start)
{
  std::array<int, Size> ret;
  for (unsigned int i = 0; i < Size; i++) {
    ret[i] = i + start;
  }
  return ret;
}

namespace Drake {
  // todo: recursive template to get arbitrary gradient order

  // note: tried using template default values (e.g. Eigen::Dynamic), but they didn't seem to work on my mac clang
  template <int num_vars> using TaylorVar = Eigen::AutoDiffScalar< Eigen::Matrix<double,num_vars,1> >;
  template <int num_vars, int rows> using TaylorVec = Eigen::Matrix< TaylorVar<num_vars>, rows, 1>;
  template <int num_vars, int rows, int cols> using TaylorMat = Eigen::Matrix< TaylorVar<num_vars>, rows, cols>;

  typedef TaylorVar<Eigen::Dynamic> TaylorVarX;
  typedef TaylorVec<Eigen::Dynamic,Eigen::Dynamic> TaylorVecX;
  typedef TaylorMat<Eigen::Dynamic,Eigen::Dynamic,Eigen::Dynamic> TaylorMatX;

  // initializes the vector with x=val and dx=eye(numel(val))
  template <typename Derived>
  TaylorVecX initTaylorVecX(const Eigen::MatrixBase<Derived>& val) {
    TaylorVecX x(val.rows());
    Eigen::MatrixXd der = Eigen::MatrixXd::Identity(val.rows(),val.rows());
    for (int i=0; i<val.rows(); i++) {
      x(i).value() = val(i);
      x(i).derivatives() = der.col(i);
    }
    return x;
  }
}

/*
 * Recursively defined template specifying a matrix type of the correct size for a gradient of a matrix function with respect to Nq variables, of any order.
 */
template<typename Derived, int Nq, int DerivativeOrder = 1>
struct Gradient {
  typedef typename Eigen::Matrix<typename Derived::Scalar, ((Derived::SizeAtCompileTime == Eigen::Dynamic || Nq == Eigen::Dynamic) ? Eigen::Dynamic : Gradient<Derived, Nq, DerivativeOrder - 1>::type::SizeAtCompileTime), Nq> type;
};

/*
 * Base case for recursively defined gradient template.
 */
template<typename Derived, int Nq>
struct Gradient<Derived, Nq, 1> {
  typedef typename Eigen::Matrix<typename Derived::Scalar, Derived::SizeAtCompileTime, Nq> type;
};

/*
 * Output type of matGradMultMat
 */
template<typename DerivedA, typename DerivedB, typename DerivedDA>
struct MatGradMultMat {
  typedef typename Eigen::Matrix<typename DerivedA::Scalar, (DerivedA::RowsAtCompileTime == Eigen::Dynamic || DerivedB::ColsAtCompileTime == Eigen::Dynamic ? Eigen::Dynamic : DerivedA::RowsAtCompileTime * DerivedB::ColsAtCompileTime), DerivedDA::ColsAtCompileTime> type;
};

/*
 * Output type of matGradMult
 */
template<typename DerivedDA, typename DerivedB>
struct MatGradMult {
  typedef typename Eigen::Matrix<typename DerivedDA::Scalar, (DerivedDA::RowsAtCompileTime == Eigen::Dynamic || DerivedB::SizeAtCompileTime == Eigen::Dynamic ? Eigen::Dynamic : DerivedDA::RowsAtCompileTime / DerivedB::RowsAtCompileTime * DerivedB::ColsAtCompileTime), DerivedDA::ColsAtCompileTime> type;
};

/*
 * Output type and array types of getSubMatrixGradient for std::arrays specifying rows and columns
 */
template<int QSubvectorSize, typename Derived, std::size_t NRows, std::size_t NCols>
struct GetSubMatrixGradientArray {
  typedef typename Eigen::Matrix<typename Derived::Scalar, (NRows * NCols), ((QSubvectorSize == Eigen::Dynamic) ? Derived::ColsAtCompileTime : QSubvectorSize)> type;
};

/*
 * Output type of getSubMatrixGradient for a single element of the input matrix
 */
template<int QSubvectorSize, typename Derived>
struct GetSubMatrixGradientSingleElement {
  typedef typename Eigen::Block<const Derived, 1, ((QSubvectorSize == Eigen::Dynamic) ? Derived::ColsAtCompileTime : QSubvectorSize)> type;
};

template <typename Derived>
struct AutoDiffToValueMatrix {
  typedef typename Eigen::Matrix<typename Derived::Scalar::Scalar, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime> type;
};

template <typename Derived>
struct AutoDiffToGradientMatrix {
  typedef typename Gradient<Eigen::Matrix<typename Derived::Scalar::Scalar, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>, Eigen::Dynamic>::type type;
};

/*
 * Profile results: looks like return value optimization works; a version that sets a reference
 * instead of returning a value is just as fast and this is cleaner.
 */
template <typename Derived>
typename Derived::PlainObject transposeGrad(
    const Eigen::MatrixBase<Derived>& dX, typename Derived::Index rows_X)
{
  typename Derived::PlainObject dX_transpose(dX.rows(), dX.cols());
  typename Derived::Index numel = dX.rows();
  typename Derived::Index index = 0;
  for (int i = 0; i < numel; i++) {
    dX_transpose.row(i) = dX.row(index);
    index += rows_X;
    if (index >= numel) {
      index = (index % numel) + 1;
    }
  }
  return dX_transpose;
}

template <typename DerivedA, typename DerivedB, typename DerivedDA, typename DerivedDB>
typename MatGradMultMat<DerivedA, DerivedB, DerivedDA>::type
matGradMultMat(
    const Eigen::MatrixBase<DerivedA>& A,
    const Eigen::MatrixBase<DerivedB>& B,
    const Eigen::MatrixBase<DerivedDA>& dA,
    const Eigen::MatrixBase<DerivedDB>& dB) {
  assert(dA.cols() == dB.cols());

  typename MatGradMultMat<DerivedA, DerivedB, DerivedDA>::type ret(A.rows() * B.cols(), dA.cols());

  for (int col = 0; col < B.cols(); col++) {
    auto block = ret.template block<DerivedA::RowsAtCompileTime, DerivedDA::ColsAtCompileTime>(col * A.rows(), 0, A.rows(), dA.cols());

    // A * dB part:
    block.noalias() = A * dB.template block<DerivedA::ColsAtCompileTime, DerivedDA::ColsAtCompileTime>(col * A.cols(), 0, A.cols(), dA.cols());

    for (int row = 0; row < B.rows(); row++) {
      // B * dA part:
      block.noalias() += B(row, col) * dA.template block<DerivedA::RowsAtCompileTime, DerivedDA::ColsAtCompileTime>(row * A.rows(), 0, A.rows(), dA.cols());
    }
  }
  return ret;

  // much slower and requires eigen/unsupported:
//  return Eigen::kroneckerProduct(Eigen::MatrixXd::Identity(B.cols(), B.cols()), A) * dB + Eigen::kroneckerProduct(B.transpose(), Eigen::MatrixXd::Identity(A.rows(), A.rows())) * dA;
}

template<typename DerivedDA, typename DerivedB>
typename MatGradMult<DerivedDA, DerivedB>::type
matGradMult(const Eigen::MatrixBase<DerivedDA>& dA, const Eigen::MatrixBase<DerivedB>& B) {
  assert(B.rows() == 0 ? dA.rows() == 0 : dA.rows() % B.rows() == 0);
  typename DerivedDA::Index A_rows = B.rows() == 0 ? 0 : dA.rows() / B.rows();
  const int A_rows_at_compile_time = (DerivedDA::RowsAtCompileTime == Eigen::Dynamic || DerivedB::RowsAtCompileTime == Eigen::Dynamic) ?
                                     Eigen::Dynamic :
                                     static_cast<int>(DerivedDA::RowsAtCompileTime / DerivedB::RowsAtCompileTime);

  typename MatGradMult<DerivedDA, DerivedB>::type ret(A_rows * B.cols(), dA.cols());
  ret.setZero();
  for (int col = 0; col < B.cols(); col++) {
    auto block = ret.template block<A_rows_at_compile_time, DerivedDA::ColsAtCompileTime>(col * A_rows, 0, A_rows, dA.cols());
    for (int row = 0; row < B.rows(); row++) {
      // B * dA part:
      block.noalias() += B(row, col) * dA.template block<A_rows_at_compile_time, DerivedDA::ColsAtCompileTime>(row * A_rows, 0, A_rows, dA.cols());
    }
  }
  return ret;
}

// TODO: could save copies once http://eigen.tuxfamily.org/bz/show_bug.cgi?id=329 is fixed
template<typename Derived>
Eigen::Matrix<typename Derived::Scalar, Eigen::Dynamic, Eigen::Dynamic> getSubMatrixGradient(
    const Eigen::MatrixBase<Derived>& dM, const std::vector<int>& rows, const std::vector<int>& cols,
    typename Derived::Index M_rows, int q_start = 0, typename Derived::Index q_subvector_size = -1) {
  if (q_subvector_size < 0) {
    q_subvector_size = dM.cols() - q_start;
  }
  Eigen::MatrixXd dM_submatrix(rows.size() * cols.size(), q_subvector_size);
  int index = 0;
  for (std::vector<int>::const_iterator col = cols.begin(); col != cols.end(); ++col) {
    for (std::vector<int>::const_iterator row = rows.begin(); row != rows.end(); ++row) {
      dM_submatrix.row(index) = dM.block(*row + *col * M_rows, q_start, 1, q_subvector_size);
      index++;
    }
  }
  return dM_submatrix;
}

template<int QSubvectorSize, typename Derived, std::size_t NRows, std::size_t NCols>
typename GetSubMatrixGradientArray<QSubvectorSize, Derived, NRows, NCols>::type
getSubMatrixGradient(const Eigen::MatrixBase<Derived>& dM,
  const std::array<int, NRows>& rows,
  const std::array<int, NCols>& cols,
  typename Derived::Index M_rows, int q_start = 0, typename Derived::Index q_subvector_size = QSubvectorSize) {
  if (q_subvector_size == Eigen::Dynamic) {
    q_subvector_size = dM.cols() - q_start;
  }
  Eigen::Matrix<typename Derived::Scalar, NRows * NCols, Derived::ColsAtCompileTime> dM_submatrix(NRows * NCols, q_subvector_size);
  int index = 0;
  for (typename std::array<int, NCols>::const_iterator col = cols.begin(); col != cols.end(); ++col) {
    for (typename std::array<int, NRows>::const_iterator row = rows.begin(); row != rows.end(); ++row) {
      dM_submatrix.row(index++) = dM.template block<1, QSubvectorSize> ((*row) + (*col) * M_rows, q_start, 1, q_subvector_size);
    }
  }
  return dM_submatrix;
};

template<int QSubvectorSize, typename Derived>
typename GetSubMatrixGradientSingleElement<QSubvectorSize, Derived>::type
getSubMatrixGradient(const Eigen::MatrixBase<Derived>& dM, int row, int col, typename Derived::Index M_rows,
    typename Derived::Index q_start = 0, typename Derived::Index q_subvector_size = QSubvectorSize) {
  if (q_subvector_size == Eigen::Dynamic) {
    q_subvector_size = dM.cols() - q_start;
  }
  return dM.template block<1, QSubvectorSize>(row + col * M_rows, q_start, 1, q_subvector_size);
};

template<typename DerivedA, typename DerivedB>
void setSubMatrixGradient(Eigen::MatrixBase<DerivedA>& dM, const Eigen::MatrixBase<DerivedB>& dM_submatrix,
    const std::vector<int>& rows, const std::vector<int>& cols, typename DerivedA::Index M_rows, typename DerivedA::Index q_start = 0, typename DerivedA::Index q_subvector_size = -1) {
  if (q_subvector_size < 0) {
    q_subvector_size = dM.cols() - q_start;
  }
  int index = 0;
  for (typename std::vector<int>::const_iterator col = cols.begin(); col != cols.end(); ++col) {
    for (typename std::vector<int>::const_iterator row = rows.begin(); row != rows.end(); ++row) {
      dM.block((*row) + (*col) * M_rows, q_start, 1, q_subvector_size) = dM_submatrix.row(index++);
    }
  }
};

template<int QSubvectorSize, typename DerivedA, typename DerivedB, std::size_t NRows, std::size_t NCols>
void setSubMatrixGradient(Eigen::MatrixBase<DerivedA>& dM, const Eigen::MatrixBase<DerivedB>& dM_submatrix,
    const std::array<int, NRows>& rows, const std::array<int, NCols>& cols, typename DerivedA::Index M_rows, typename DerivedA::Index q_start = 0, typename DerivedA::Index q_subvector_size = QSubvectorSize) {
  if (q_subvector_size == Eigen::Dynamic) {
    q_subvector_size = dM.cols() - q_start;
  }
  int index = 0;
  for (typename std::array<int, NCols>::const_iterator col = cols.begin(); col != cols.end(); ++col) {
    for (typename std::array<int, NRows>::const_iterator row = rows.begin(); row != rows.end(); ++row) {
      dM.template block<1, QSubvectorSize> ((*row) + (*col) * M_rows, q_start, 1, q_subvector_size) = dM_submatrix.row(index++);
    }
  }
};

template<int QSubvectorSize, typename DerivedDM, typename DerivedDMSub>
void setSubMatrixGradient(Eigen::MatrixBase<DerivedDM>& dM, const Eigen::MatrixBase<DerivedDMSub>& dM_submatrix, int row, int col, typename DerivedDM::Index M_rows,
    typename DerivedDM::Index q_start = 0, typename DerivedDM::Index q_subvector_size = QSubvectorSize) {
  if (q_subvector_size == Eigen::Dynamic) {
    q_subvector_size = dM.cols() - q_start;
  }
  dM.template block<1, QSubvectorSize>(row + col * M_rows, q_start, 1, q_subvector_size) = dM_submatrix;
};

template <typename Derived>
typename AutoDiffToValueMatrix<Derived>::type autoDiffToValueMatrix(const Eigen::MatrixBase<Derived>& auto_diff_matrix) {
  typename AutoDiffToValueMatrix<Derived>::type ret(auto_diff_matrix.rows(), auto_diff_matrix.cols());
  for (int i = 0; i < auto_diff_matrix.rows(); i++) {
    for (int j = 0; j < auto_diff_matrix.cols(); ++j) {
      ret(i, j) = auto_diff_matrix(i, j).value();
    }
  }
  return ret;
};

template<typename Derived>
typename AutoDiffToGradientMatrix<Derived>::type autoDiffToGradientMatrix(
        const Eigen::MatrixBase<Derived>& auto_diff_matrix, int num_variables = Eigen::Dynamic)
{
  int num_variables_from_matrix = 0;
  for (int i = 0; i < auto_diff_matrix.size(); ++i) {
    num_variables_from_matrix = std::max(num_variables_from_matrix, static_cast<int>(auto_diff_matrix(i).derivatives().size()));
  }
  if (num_variables == Eigen::Dynamic) {
    num_variables = num_variables_from_matrix;
  }
  else if (num_variables_from_matrix != 0 && num_variables_from_matrix != num_variables) {
    std::stringstream buf;
    buf << "Input matrix has derivatives w.r.t " << num_variables_from_matrix << " variables, whereas num_variables is " << num_variables << ".\n";
    buf << "Either num_variables_from_matrix should be zero, or it should match num_variables.";
    throw std::runtime_error(buf.str());
  }

  typename AutoDiffToGradientMatrix<Derived>::type gradient(auto_diff_matrix.size(), num_variables);
  for (int row = 0; row < auto_diff_matrix.rows(); row++) {
    for (int col = 0; col < auto_diff_matrix.cols(); col++) {
      auto gradient_row = gradient.row(row + col * auto_diff_matrix.rows()).transpose();
      if (auto_diff_matrix(row, col).derivatives().size() == 0) {
        gradient_row.setZero();
      } else {
        gradient_row = auto_diff_matrix(row, col).derivatives();
      }
    }
  }
  return gradient;
}

template<typename DerivedGradient, typename DerivedAutoDiff>
void gradientMatrixToAutoDiff(const Eigen::MatrixBase<DerivedGradient>& gradient, Eigen::MatrixBase<DerivedAutoDiff>& auto_diff_matrix)
{
  typedef typename Eigen::MatrixBase<DerivedGradient>::Index Index;
  auto nx = gradient.cols();
  for (Index row = 0; row < auto_diff_matrix.rows(); row++) {
    for (Index col = 0; col < auto_diff_matrix.cols(); col++) {
      auto_diff_matrix(row, col).derivatives().resize(nx, 1);
      auto_diff_matrix(row, col).derivatives() = gradient.row(row + col * auto_diff_matrix.rows()).transpose();
    }
  }
}

namespace Drake {
  namespace internal {
    template <typename Derived, typename Scalar>
    struct ResizeDerivativesToMatchScalarImpl {
      static void run(Eigen::MatrixBase<Derived>& mat, const Scalar& scalar) {};
    };

    template <typename Derived, typename DerivType>
    struct ResizeDerivativesToMatchScalarImpl<Derived, Eigen::AutoDiffScalar<DerivType> > {
      using Scalar = Eigen::AutoDiffScalar<DerivType>;
      static void run(Eigen::MatrixBase<Derived>& mat, const Scalar& scalar) {
        for (int i = 0; i < mat.size(); i++) {
          auto& derivs = mat(i).derivatives();
          if (derivs.size() == 0) {
            derivs.resize(scalar.derivatives().size());
            derivs.setZero();
          }
        }
      };
    };
  }

  /** Resize derivatives vector of each element of a matrix to to match the size of the derivatives vector of a given scalar.
   * \brief If the mat and scalar inputs are AutoDiffScalars, resize the derivatives vector of each element of the matrix mat to match
   * the number of derivatives of the scalar. This is useful in functions that return matrices that do not depend on an AutoDiffScalar
   * argument (e.g. a function with a constant output), while it is desired that information about the number of derivatives is preserved.
   * \param mat matrix, for which the derivative vectors of the elements will be resized
   * \param scalar scalar to match the derivative size vector against.
   */
  template <typename Derived>
  void resizeDerivativesToMatchScalar(Eigen::MatrixBase<Derived>& mat, const typename Derived::Scalar& scalar) {
    internal::ResizeDerivativesToMatchScalarImpl<Derived, typename Derived::Scalar>::run(mat, scalar);
  }
}

#endif /* DRAKEGRADIENTUTIL_H_ */


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid itemid: path-leading-colon-backslash</title>


text:
package patterns.trash;

public interface Fillable<T extends Trash> {
  void addTrash(T t);
}


text:
package service;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import util.DataUtils;
import util.FacesContextUtils;
import dao.MovCaixaFechamentoDao;
import model.MovCaixaFechamento;

public class MovCaixaFechamentoService extends Service implements
		BO<MovCaixaFechamento> {

	@Inject
	private MovCaixaFechamentoDao movCaixaFechamentoDao;

	@Inject
	private LancaCaixaService lancaCaixaService;

	@Override
	public void salvar(MovCaixaFechamento movCaixaFechamento)
			throws ServiceException {
		try {
			beginTransaction();
			movCaixaFechamentoDao.salvar(movCaixaFechamento);
			commitTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}

	}

	@Override
	public void excluir(Long entidadeId) throws ServiceException {
		// TODO Auto-generated method stub

	}

	public MovCaixaFechamento obterUltimoFechamentoAnteriorAData(Date data)
			throws ServiceException {
		try {
			return movCaixaFechamentoDao.obterFechamentoAnteriorData(data);
		} catch (Exception e) {
			throw new ServiceException(e.getMessage());
		}
	}

	public MovCaixaFechamento obterUltimoFechamento()
			throws ServiceException {
		try {
			return movCaixaFechamentoDao.obterUltimoFechamento();
		} catch (Exception e) {
			throw new ServiceException(e.getMessage());
		}
	}

	public void fecharCaixa(Date data, Double saldoAnterior, Double saldoAtual)
			throws ServiceException {
		try {

			MovCaixaFechamento ultimoFechamento = obterUltimoFechamentoAnteriorAData(data);
			if (ultimoFechamento != null) {

				Date ontem = DataUtils.retrocedeDiasData(data, 1);
				if (ontem.compareTo(ultimoFechamento.getDataMovimento()) != 0) {
					throw new ServiceException(
							"Existem caixas pendentes a serem fechados \n (Ultimo fechamento: "
									+ DataUtils
											.formataDataParaString(ultimoFechamento
													.getDataMovimento()) + ")");
				}
			}else{
				MovCaixaFechamento fechamentoPosterior = movCaixaFechamentoDao.obterFechamentoPosteriorAData(data);
				if(fechamentoPosterior != null){
					throw new ServiceException("Caixa menor que o fechamento inicial \n (Fechamento Inicial: "
							+ DataUtils.formataDataParaString(fechamentoPosterior.getDataMovimento()) + ")");
				}
				//este é o primeiro fechamento de caixa
				else{
					if(lancaCaixaService.existeMovimentoAnteriorData(data)){
						throw new ServiceException("Existe(m) caixa(s) pendente(s) a serem fechados");
					}
				}
			}

			MovCaixaFechamento mcf = new MovCaixaFechamento();
			mcf.setDataMovimento(data);
			mcf.setDataFechamento(new Date());
			mcf.setSaldoAnterior(saldoAnterior);
			mcf.setSaldoAtual(saldoAtual);

			salvar(mcf);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
	}

	public void estornarFechamento(Date dataUltimoFechamento, Date dataAnt) throws ServiceException{
		try {

			String ultimoFechamento = DataUtils.formataDataParaString(dataUltimoFechamento);
			String ant = DataUtils.formataDataParaString(dataAnt);

			if(DataUtils.DiferencaEntreDatas(ant, ultimoFechamento) < 0){
				throw new ServiceException("Data não pode ser maior que a do último fechamento.");
			}else{

				int difData = DataUtils.DiferencaEntreDatas(ant, ultimoFechamento);

				beginTransaction();

				for (int i = 0; i <= difData; i++) {

					Date retrocede = DataUtils.retrocedeDiasData(dataUltimoFechamento, i);
					MovCaixaFechamento mcf = movCaixaFechamentoDao.obterFechamentoPorDataMov(retrocede);
					if(mcf != null){
						movCaixaFechamentoDao.excluir(mcf);
					}

				}

				commitTransaction();
			}

		} catch (Exception e) {
			rollbackTransaction();
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
	}

	public Boolean caixaFechado(Date data) throws ServiceException {
		try {
			MovCaixaFechamento mcf = movCaixaFechamentoDao
					.obterFechamentoPorDataMov(data);
			return mcf != null ? true : false;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
	}

	@Override
	public List<MovCaixaFechamento> listar() throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean validar(MovCaixaFechamento entidade) {
		// TODO Auto-generated method stub
		return false;
	}

	public MovCaixaFechamento obterPorId(Long id) throws ServiceException {
		try {
			return movCaixaFechamentoDao.carregar(id, MovCaixaFechamento.class);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e.getMessage());
		}
	}

}


text:
layout: page
title: Contributing to the Open Tree of Life
permalink: /contribute
---

# Phylogenetic Study Curator
[https://tree.opentreeoflife.org/curator](https://tree.opentreeoflife.org/curator)
is our curation application.

You can contribute to the synthetic tree by uploading trees
    through our curation interface.
These can be trees from TreeBASE or trees uploaded from your computer.

There will be a delay before uploaded trees appear in the
  synthetic tree.

There are detailed instructions [here](https://github.com/OpenTreeOfLife/opentree/wiki/Submitting-phylogenies-to-Open-Tree-of-Life) on how to use
the curation application.


text:
@interface CoreDataTest : GHTestCase { }
@end

@implementation CoreDataTest

-(void)setUp {

    [MagicalRecord setDefaultModelFromClass:[self class]];
	[MagicalRecord setupCoreDataStackWithInMemoryStore];

}

-(void)tearDown {

    [Work MR_truncateAll];
    [MagicalRecord cleanUp];

}

-(void)testSeedData {

    CMDataCreater *dataCreater = [[CMDataCreater alloc] init];

    NSArray *allWorks = [Work MR_findAll];

    int resultsCount = [allWorks count];
    GHAssertEquals(resultsCount, 0, @"should be 0");

    [dataCreater createDummyData];

    NSArray *nextResults = [Work MR_findAll];
    int nextCount = [nextResults count];
    GHAssertEquals(nextCount, 10, @"should be 10 elements, got %d", nextCount);

}

@end


text:
declare class Ractive {
    constructor(option : any);
    on(action : string, func : any);
    on(params : any);
    get(name : string) : any;
    set(name : string, value : any);
    push(keypath : string, item : any);
    pop(keypath : string);
    unshift(keypath : string, item : any);
    shift(keypath : string, item : any);
    splice(keypath : string, index : number, count : number);
    observe(params : any);
    observe(keypath : string, func : any);
    update();
}


text:
set -e

command -v z >/dev/null || brew install z


text:
from data_importers.ems_importers import BaseDemocracyCountsCsvImporter

class Command(BaseDemocracyCountsCsvImporter):
    council_id = "LND"
    addresses_name = "2021-03-24T11:43:05.269487146/Polling Districts - CoL.csv"
    stations_name = "2021-03-24T11:43:05.269487146/Polling Stations - CoL.csv"
    elections = ["2021-05-06"]

    def station_record_to_dict(self, record):
        # "St Bride Foundation Institute"
        if record.stationcode == "AL":
            record = record._replace(xordinate="531586")
            record = record._replace(yordinate="181081")
        # "St Giles' Cripplegate"
        if record.stationcode == "BL_1":
            record = record._replace(xordinate="532350")
            record = record._replace(yordinate="181702")
        # "St Giles' Cripplegate"
        if record.stationcode == "BL_2":
            record = record._replace(xordinate="532350")
            record = record._replace(yordinate="181702")

        return super().station_record_to_dict(record)


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.commons.math3.stat.descriptive.moment (Apache Commons Math 3.6.1 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

org.apache.commons.math3.stat.descriptive.moment

Classes

GeometricMean

Kurtosis

Mean

SecondMoment

SemiVariance

Skewness

StandardDeviation

Variance

VectorialCovariance

VectorialMean

Enums

SemiVariance.Direction


text:
// Copyright (C) 2011 Vicente J. Botet Escriba
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// <boost/thread/recursive_mutex.hpp>

// class recursive_mutex;

// recursive_mutex& operator=(const recursive_mutex&) = delete;

#include <boost/thread/recursive_mutex.hpp>
#include <boost/detail/lightweight_test.hpp>

int main()
{
  boost::recursive_mutex m0;
  boost::recursive_mutex m1(m0);
}

#include "../../../remove_error_code_unused_warning.hpp"


text:
const { timer, getIntMatrixFromFile, range } = require('../utilities');

timer.start();

const update = (value, subject) => (value * subject) % 20201227;

const transform = (subject, loopSize) => range(0, loopSize).reduce((value, _) => update(value, subject), 1)

const crack = pk => {
    let loopSize = 0;
    let value = 1;

    while (value !== pk) {
        value = update(value, 7);
        loopSize++;
    }
    return loopSize;
}

const [cardPK, doorPK] = getIntMatrixFromFile(25).flat();

const doorLoopSize = crack(doorPK);

console.log(transform(cardPK, doorLoopSize))

timer.stop();


text:
typedef enum : NSInteger {
    NGContactEntryTypePhone,
    NGContactEntryTypeEmail
} NGContactEntryType;

@interface NGContactEntry : NSObject<NSCoding, NSCopying>

@property (nonatomic) NGContactEntryType type;
@property (nonatomic) NSString *key;
@property (nonatomic) NSString *value;

- (NSString *)formattedValue;

@end