text:
package org.apache.olingo.server.core.uri.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edm.EdmAction;
import org.apache.olingo.commons.api.edm.EdmActionImport;
import org.apache.olingo.commons.api.edm.EdmEntityContainer;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmFunctionImport;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmSingleton;
import org.apache.olingo.commons.api.edm.EdmStructuredType;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.queryoption.AliasQueryOption;
import org.apache.olingo.server.core.uri.UriResourceActionImpl;
import org.apache.olingo.server.core.uri.UriResourceComplexPropertyImpl;
import org.apache.olingo.server.core.uri.UriResourceCountImpl;
import org.apache.olingo.server.core.uri.UriResourceEntitySetImpl;
import org.apache.olingo.server.core.uri.UriResourceFunctionImpl;
import org.apache.olingo.server.core.uri.UriResourceNavigationPropertyImpl;
import org.apache.olingo.server.core.uri.UriResourcePrimitivePropertyImpl;
import org.apache.olingo.server.core.uri.UriResourceRefImpl;
import org.apache.olingo.server.core.uri.UriResourceSingletonImpl;
import org.apache.olingo.server.core.uri.UriResourceTypedImpl;
import org.apache.olingo.server.core.uri.UriResourceValueImpl;
import org.apache.olingo.server.core.uri.UriResourceWithKeysImpl;
import org.apache.olingo.server.core.uri.parser.UriTokenizer.TokenKind;
import org.apache.olingo.server.core.uri.validator.UriValidationException;

public class ResourcePathParser {

  private final Edm edm;
  private final EdmEntityContainer edmEntityContainer;
  private final Map<String, AliasQueryOption> aliases;
  private UriTokenizer tokenizer;

  public ResourcePathParser(final Edm edm, final Map<String, AliasQueryOption> aliases) {
    this.edm = edm;
    this.aliases = aliases;
    edmEntityContainer = edm.getEntityContainer();
  }

  public UriResource parsePathSegment(final String pathSegment, UriResource previous)
      throws UriParserException, UriValidationException {
    tokenizer = new UriTokenizer(pathSegment);

    // The order is important.
    // A qualified name should not be parsed as identifier and let the tokenizer halt at '.'.

    if (previous == null) {
      if (tokenizer.next(TokenKind.QualifiedName)) {
        throw new UriParserSemanticException("The initial segment must not be namespace-qualified.",
            UriParserSemanticException.MessageKeys.NAMESPACE_NOT_ALLOWED_AT_FIRST_ELEMENT,
            new FullQualifiedName(tokenizer.getText()).getNamespace());
      } else if (tokenizer.next(TokenKind.ODataIdentifier)) {
        return leadingResourcePathSegment();
      }

    } else {
      if (tokenizer.next(TokenKind.REF)) {
        return ref(previous);
      } else if (tokenizer.next(TokenKind.VALUE)) {
        return value(previous);
      } else if (tokenizer.next(TokenKind.COUNT)) {
        return count(previous);
      } else if (tokenizer.next(TokenKind.QualifiedName)) {
        return boundOperationOrTypeCast(previous);
      } else if (tokenizer.next(TokenKind.ODataIdentifier)) {
        return navigationOrProperty(previous);
      }
    }

    throw new UriParserSyntaxException("Unexpected start of resource-path segment.",
        UriParserSyntaxException.MessageKeys.SYNTAX);
  }

  public EdmEntityType parseDollarEntityTypeCast(final String pathSegment) throws UriParserException {
    tokenizer = new UriTokenizer(pathSegment);
    ParserHelper.requireNext(tokenizer, TokenKind.QualifiedName);
    final String name = tokenizer.getText();
    ParserHelper.requireTokenEnd(tokenizer);
    final EdmEntityType type = edm.getEntityType(new FullQualifiedName(name));
    if (type == null) {
      throw new UriParserSemanticException("Type '" + name + "' not found.",
          UriParserSemanticException.MessageKeys.UNKNOWN_TYPE, name);
    }
    return type;
  }

  public List<String> parseCrossjoinSegment(final String pathSegment) throws UriParserException {
    tokenizer = new UriTokenizer(pathSegment);
    ParserHelper.requireNext(tokenizer, TokenKind.CROSSJOIN);
    ParserHelper.requireNext(tokenizer, TokenKind.OPEN);
    // At least one entity-set name is mandatory. Try to fetch all.
    List<String> entitySetNames = new ArrayList<>();
    do {
      ParserHelper.requireNext(tokenizer, TokenKind.ODataIdentifier);
      final String name = tokenizer.getText();
      final EdmEntitySet edmEntitySet = edmEntityContainer.getEntitySet(name);
      if (edmEntitySet == null) {
        throw new UriParserSemanticException("Expected Entity Set Name.",
            UriParserSemanticException.MessageKeys.UNKNOWN_PART, name);
      } else {
        entitySetNames.add(name);
      }
    } while (tokenizer.next(TokenKind.COMMA));
    ParserHelper.requireNext(tokenizer, TokenKind.CLOSE);
    ParserHelper.requireTokenEnd(tokenizer);
    return entitySetNames;
  }

  private UriResource ref(final UriResource previous) throws UriParserException {
    ParserHelper.requireTokenEnd(tokenizer);
    requireTyped(previous, "$ref");
    if (((UriResourcePartTyped) previous).getType() instanceof EdmEntityType) {
      return new UriResourceRefImpl();
    } else {
      throw new UriParserSemanticException("$ref is only allowed on entity types.",
          UriParserSemanticException.MessageKeys.ONLY_FOR_ENTITY_TYPES, "$ref");
    }
  }

  private UriResource value(final UriResource previous) throws UriParserException {
    ParserHelper.requireTokenEnd(tokenizer);
    requireTyped(previous, "$value");
    if (!((UriResourcePartTyped) previous).isCollection()) {
      requireMediaResourceInCaseOfEntity(previous);
      return new UriResourceValueImpl();
    } else {
      throw new UriParserSemanticException("$value is only allowed on typed path segments.",
          UriParserSemanticException.MessageKeys.ONLY_FOR_TYPED_PARTS, "$value");
    }
  }

  private void requireMediaResourceInCaseOfEntity(UriResource resource) throws UriParserSemanticException {
    // If the resource is an entity or navigatio
    if (resource instanceof UriResourceEntitySet && !((UriResourceEntitySet) resource).getEntityType().hasStream()
        || resource instanceof UriResourceNavigation
        && !((EdmEntityType) ((UriResourceNavigation) resource).getType()).hasStream()) {
      throw new UriParserSemanticException("$value on entity is only allowed on media resources.",
          UriParserSemanticException.MessageKeys.NOT_A_MEDIA_RESOURCE, resource.getSegmentValue());
    }

    // Functions can also deliver an entity. In this case we have to check if the returned entity is a media resource
    if (resource instanceof UriResourceFunction) {
      EdmType returnType = ((UriResourceFunction) resource).getFunction().getReturnType().getType();
      //Collection check is above so not needed here
      if (returnType instanceof EdmEntityType && !((EdmEntityType) returnType).hasStream()) {
        throw new UriParserSemanticException("$value on returned entity is only allowed on media resources.",
            UriParserSemanticException.MessageKeys.NOT_A_MEDIA_RESOURCE, resource.getSegmentValue());
      }
    }
  }

  private UriResource count(final UriResource previous) throws UriParserException {
    ParserHelper.requireTokenEnd(tokenizer);
    requireTyped(previous, "$count");
    if (((UriResourcePartTyped) previous).isCollection()) {
      return new UriResourceCountImpl();
    } else {
      throw new UriParserSemanticException("$count is only allowed on collections.",
          UriParserSemanticException.MessageKeys.ONLY_FOR_COLLECTIONS, "$count");
    }
  }

  private UriResource leadingResourcePathSegment() throws UriParserException, UriValidationException {
    final String oDataIdentifier = tokenizer.getText();

    final EdmEntitySet edmEntitySet = edmEntityContainer.getEntitySet(oDataIdentifier);
    if (edmEntitySet != null) {
      final UriResourceEntitySetImpl entitySetResource = new UriResourceEntitySetImpl(edmEntitySet);

      if (tokenizer.next(TokenKind.OPEN)) {
        final List<UriParameter> keyPredicates =
            ParserHelper.parseKeyPredicate(tokenizer, entitySetResource.getEntityType(), null, edm, null, aliases);
        entitySetResource.setKeyPredicates(keyPredicates);
      }

      ParserHelper.requireTokenEnd(tokenizer);
      return entitySetResource;
    }

    final EdmSingleton edmSingleton = edmEntityContainer.getSingleton(oDataIdentifier);
    if (edmSingleton != null) {
      ParserHelper.requireTokenEnd(tokenizer);
      return new UriResourceSingletonImpl(edmSingleton);
    }

    final EdmActionImport edmActionImport = edmEntityContainer.getActionImport(oDataIdentifier);
    if (edmActionImport != null) {
      ParserHelper.requireTokenEnd(tokenizer);
      return new UriResourceActionImpl(edmActionImport);
    }

    final EdmFunctionImport edmFunctionImport = edmEntityContainer.getFunctionImport(oDataIdentifier);
    if (edmFunctionImport != null) {
      return functionCall(edmFunctionImport, null, null, false);
    }

    if (tokenizer.next(TokenKind.OPEN) || tokenizer.next(TokenKind.EOF)) {
      throw new UriParserSemanticException("Unexpected start of resource-path segment.",
          UriParserSemanticException.MessageKeys.RESOURCE_NOT_FOUND, oDataIdentifier);
    } else {
      throw new UriParserSyntaxException("Unexpected start of resource-path segment.",
          UriParserSyntaxException.MessageKeys.SYNTAX);
    }
  }

  private UriResource navigationOrProperty(final UriResource previous)
      throws UriParserException, UriValidationException {
    final String name = tokenizer.getText();

    UriResourcePartTyped previousTyped = null;
    EdmStructuredType structType = null;
    requireTyped(previous, name);
    if (((UriResourcePartTyped) previous).getType() instanceof EdmStructuredType) {
      previousTyped = (UriResourcePartTyped) previous;
      final EdmType previousTypeFilter = getPreviousTypeFilter(previousTyped);
      structType = (EdmStructuredType) (previousTypeFilter == null ? previousTyped.getType() : previousTypeFilter);
    } else {
      throw new UriParserSemanticException(
          "Cannot parse '" + name + "'; previous path segment is not a structural type.",
          UriParserSemanticException.MessageKeys.RESOURCE_PART_MUST_BE_PRECEDED_BY_STRUCTURAL_TYPE, name);
    }

    if (previousTyped.isCollection()) {
      throw new UriParserSemanticException("Property '" + name + "' is not allowed after collection.",
          UriParserSemanticException.MessageKeys.PROPERTY_AFTER_COLLECTION, name);
    }

    final EdmProperty property = structType.getStructuralProperty(name);
    if (property != null) {
      return property.isPrimitive()
          || property.getType().getKind() == EdmTypeKind.ENUM
          || property.getType().getKind() == EdmTypeKind.DEFINITION ?
          new UriResourcePrimitivePropertyImpl(property) :
          new UriResourceComplexPropertyImpl(property);
    }
    final EdmNavigationProperty navigationProperty = structType.getNavigationProperty(name);
    if (navigationProperty == null) {
      throw new UriParserSemanticException("Property '" + name + "' not found in type '"
          + structType.getFullQualifiedName().getFullQualifiedNameAsString() + "'",
          UriParserSemanticException.MessageKeys.PROPERTY_NOT_IN_TYPE,
          structType.getFullQualifiedName().getFullQualifiedNameAsString(), name);
    }
    List<UriParameter> keyPredicate =
        ParserHelper.parseNavigationKeyPredicate(tokenizer, navigationProperty, edm, null, aliases);
    ParserHelper.requireTokenEnd(tokenizer);
    return new UriResourceNavigationPropertyImpl(navigationProperty)
        .setKeyPredicates(keyPredicate);
  }

  private UriResource boundOperationOrTypeCast(UriResource previous)
      throws UriParserException, UriValidationException {
    final FullQualifiedName name = new FullQualifiedName(tokenizer.getText());
    requireTyped(previous, name.getFullQualifiedNameAsString());
    final UriResourcePartTyped previousTyped = (UriResourcePartTyped) previous;
    final EdmType previousTypeFilter = getPreviousTypeFilter(previousTyped);
    final EdmType previousType = previousTypeFilter == null ? previousTyped.getType() : previousTypeFilter;

    // We check for bound actions first because they cannot be followed by anything.
    final EdmAction boundAction =
        edm.getBoundAction(name, previousType.getFullQualifiedName(), previousTyped.isCollection());
    if (boundAction != null) {
      ParserHelper.requireTokenEnd(tokenizer);
      return new UriResourceActionImpl(boundAction);
    }

    // Type casts can be syntactically indistinguishable from bound function calls in the case of additional keys.
    // But normally they are shorter, so they come next.
    final EdmStructuredType type = previousTyped.getType() instanceof EdmEntityType ?
        edm.getEntityType(name) :
        edm.getComplexType(name);
    if (type != null) {
      return typeCast(name, type, previousTyped);
    }
    if (tokenizer.next(TokenKind.EOF)) {
      throw new UriParserSemanticException("Type '" + name.getFullQualifiedNameAsString() + "' not found.",
          UriParserSemanticException.MessageKeys.UNKNOWN_TYPE, name.getFullQualifiedNameAsString());
    }

    // Now a bound function call is the only remaining option.
    return functionCall(null, name, previousType.getFullQualifiedName(), previousTyped.isCollection());
  }

  private void requireTyped(final UriResource previous, final String forWhat) throws UriParserException {
    if (!(previous instanceof UriResourcePartTyped)) {
      throw new UriParserSemanticException("Path segment before '" + forWhat + "' is not typed.",
          UriParserSemanticException.MessageKeys.PREVIOUS_PART_NOT_TYPED, forWhat);
    }
  }

  private UriResource typeCast(final FullQualifiedName name, final EdmStructuredType type,
      final UriResourcePartTyped previousTyped) throws UriParserException, UriValidationException {
    if (type.compatibleTo(previousTyped.getType())) {
      EdmType previousTypeFilter = null;
      if (previousTyped instanceof UriResourceWithKeysImpl) {
        if (previousTyped.isCollection()) {
          previousTypeFilter = ((UriResourceWithKeysImpl) previousTyped).getTypeFilterOnCollection();
          if (previousTypeFilter != null) {
            throw new UriParserSemanticException("Type filters are not chainable.",
                UriParserSemanticException.MessageKeys.TYPE_FILTER_NOT_CHAINABLE,
                previousTypeFilter.getName(), type.getName());
          }
          ((UriResourceWithKeysImpl) previousTyped).setCollectionTypeFilter(type);
        } else {
          previousTypeFilter = ((UriResourceWithKeysImpl) previousTyped).getTypeFilterOnEntry();
          if (previousTypeFilter != null) {
            throw new UriParserSemanticException("Type filters are not chainable.",
                UriParserSemanticException.MessageKeys.TYPE_FILTER_NOT_CHAINABLE,
                previousTypeFilter.getName(), type.getName());
          }
          ((UriResourceWithKeysImpl) previousTyped).setEntryTypeFilter(type);
        }
        if (tokenizer.next(TokenKind.OPEN)) {
          final List<UriParameter> keys =
              ParserHelper.parseKeyPredicate(tokenizer, (EdmEntityType) type, null, edm, null, aliases);
          if (previousTyped.isCollection()) {
            ((UriResourceWithKeysImpl) previousTyped).setKeyPredicates(keys);
          } else {
            throw new UriParserSemanticException("Key not allowed here.",
                UriParserSemanticException.MessageKeys.KEY_NOT_ALLOWED);
          }
        }
      } else {
        previousTypeFilter = ((UriResourceTypedImpl) previousTyped).getTypeFilter();
        if (previousTypeFilter != null) {
          throw new UriParserSemanticException("Type filters are not chainable.",
              UriParserSemanticException.MessageKeys.TYPE_FILTER_NOT_CHAINABLE,
              previousTypeFilter.getName(), type.getName());
        }
        ((UriResourceTypedImpl) previousTyped).setTypeFilter(type);
      }
      ParserHelper.requireTokenEnd(tokenizer);
      return null;
    } else {
      throw new UriParserSemanticException(
          "Type filter not compatible to previous path segment: " + name.getFullQualifiedNameAsString(),
          UriParserSemanticException.MessageKeys.INCOMPATIBLE_TYPE_FILTER, name.getFullQualifiedNameAsString());
    }
  }

  private EdmType getPreviousTypeFilter(final UriResourcePartTyped previousTyped) {
    if (previousTyped instanceof UriResourceWithKeysImpl) {
      return ((UriResourceWithKeysImpl) previousTyped).getTypeFilterOnEntry() == null ?
          ((UriResourceWithKeysImpl) previousTyped).getTypeFilterOnCollection() :
          ((UriResourceWithKeysImpl) previousTyped).getTypeFilterOnEntry();
    } else {
      return ((UriResourceTypedImpl) previousTyped).getTypeFilter();
    }
  }

  private UriResource functionCall(final EdmFunctionImport edmFunctionImport,
      final FullQualifiedName boundFunctionName, final FullQualifiedName bindingParameterTypeName,
      final boolean isBindingParameterCollection) throws UriParserException, UriValidationException {
    final List<UriParameter> parameters = ParserHelper.parseFunctionParameters(tokenizer, edm, null, false, aliases);
    final List<String> names = ParserHelper.getParameterNames(parameters);
    EdmFunction function = null;
    if (edmFunctionImport != null) {
      function = edmFunctionImport.getUnboundFunction(names);
      if (function == null) {
        throw new UriParserSemanticException(
            "Function of function import '" + edmFunctionImport.getName() + "' "
                + "with parameters " + names.toString() + " not found.",
            UriParserSemanticException.MessageKeys.FUNCTION_NOT_FOUND, edmFunctionImport.getName(), names.toString());
      }
    } else {
      function = edm.getBoundFunction(boundFunctionName,
          bindingParameterTypeName, isBindingParameterCollection, names);
      if (function == null) {
        throw new UriParserSemanticException(
            "Function " + boundFunctionName + " not found.",
            UriParserSemanticException.MessageKeys.UNKNOWN_PART, boundFunctionName.getFullQualifiedNameAsString());
      }
    }
    ParserHelper.validateFunctionParameters(function, parameters, edm, null, aliases);
    ParserHelper.validateFunctionParameterFacets(function, parameters, edm, aliases);
    UriResourceFunctionImpl resource = new UriResourceFunctionImpl(edmFunctionImport, function, parameters);
    if (tokenizer.next(TokenKind.OPEN)) {
      if (function.getReturnType() != null
          && function.getReturnType().getType().getKind() == EdmTypeKind.ENTITY
          && function.getReturnType().isCollection()) {
        resource.setKeyPredicates(
            ParserHelper.parseKeyPredicate(tokenizer,
                (EdmEntityType) function.getReturnType().getType(), null, edm, null, aliases));
      } else {
        throw new UriParserSemanticException("A key is not allowed.",
            UriParserSemanticException.MessageKeys.KEY_NOT_ALLOWED);
      }
    }
    ParserHelper.requireTokenEnd(tokenizer);
    return resource;
  }
}


text:
using System.Diagnostics;
using System.IO.PortsTests;
using Legacy.Support;
using Xunit;

namespace System.IO.Ports.Tests
{
    public class GetPortNames : PortsTest
    {
        #region Test Cases

        [Fact]
        private void OpenEveryPortName()
        {
            string[] portNames = SerialPort.GetPortNames();

            for (int i = 0; i < portNames.Length; ++i)
            {
                Debug.WriteLine("Opening port " + portNames[i]);
                bool portExists = false;
                foreach (string str in PortHelper.GetPorts())
                {
                    if (str == portNames[i])
                    {
                        portExists = true;
                        break;
                    }
                }
                if (!portExists)
                {
                    Debug.WriteLine("Real Port does not exist. Ignore the output from SerialPort.GetPortNames()");
                    continue;
                }
                using (SerialPort serialPort = new SerialPort(portNames[i]))
                {
                    try
                    {
                        serialPort.Open();
                    }
                    catch (UnauthorizedAccessException) { }
                }
            }
        }
        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef MN_SOCKET_WIN32_H
#define MN_SOCKET_WIN32_H

/**
 * @file
 * @ingroup socket
 * @{
 */

/* Socket module for Win32 */

#include <winsock2.h>

typedef int socklen_t;
typedef SOCKET mn_socket_t;

#define MN_SOCKET_INVALID (INVALID_SOCKET)

int inet_aton(const char *cp, struct sockaddr_in *inp);
int inet_pton(int family, const char *src, void *dst);

/** @} */

#endif


text:
require "marketplace/engine"

module Marketplace
end


text:
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.Queries
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    public interface IOrderQueries
    {
        Task<Order> GetOrderAsync(int id);

        Task<IEnumerable<OrderSummary>> GetOrdersFromUserAsync(Guid userId);

        Task<IEnumerable<CardType>> GetCardTypesAsync();
    }
}


text:
package com.dotweblabs.friendscube.rest.services.gae;

import com.dotweblabs.friendscube.app.client.shared.entity.Notification;
import com.dotweblabs.friendscube.app.client.shared.entity.User;
import com.dotweblabs.friendscube.app.client.shared.entity.actions.Like;
import com.dotweblabs.friendscube.app.client.shared.entity.activities.Activity;
import com.dotweblabs.friendscube.rest.services.ActivityService;
import com.dotweblabs.friendscube.rest.services.LikeService;
import com.dotweblabs.friendscube.rest.services.StatusService;
import com.dotweblabs.friendscube.rest.services.UserService;
import com.google.appengine.api.datastore.Key;
import com.google.inject.Inject;
import com.hunchee.twist.types.Function;
import java.util.Date;
import java.util.List;
import static com.hunchee.twist.ObjectStoreService.store;

/**
 * @author Kerby Martino
 * @version 1.0
 * @since 1.0
 */
public class GaeLikeService implements LikeService {

    @Inject
    ActivityService activityService;

    @Inject
    UserService userService;

    @Inject
    StatusService statusService;

    @Override
    public Like create(final Like like) {
        Key likeKey = store().transact(new Function<Key>() {
            @Override
            public Key execute() {
                System.out.println("item id: " + like.getItemId());
                Activity activity = new Activity();
                activity.setCreatorId(like.getUserId());
                activity.setType(Activity.ActivityType.LIKED.toString());
                User user = userService.read(like.getUserId());
                activity.setVerb(user.getProfile().getFirstName() + " liked your " + like.getItemType());
                activityService.createActivity(activity);

                Notification notification = new Notification();
                notification.setCreated(new Date());
                notification.setSeen(false);
                notification.setReferenceActivityId(activity.getActivityId());
                if(Like.LikeType.STATUS.equals(Like.LikeType.valueOf(like.getItemType()))){
                    Long userId = statusService.read(like.getItemId()).getUserId();
                    notification.setUserId(userId);
                }
                System.out.println("saving...");
                store().put(notification);
                return store().put(like);
            }
        });

        return like;
    }

    @Override
    public Like read(Long id) {
        return store().get(Like.class, id);
    }

    @Override
    public Like update(Like like) {
        return null;
    }

    @Override
    public void delete(Long id) {

    }

    @Override
    public List<Like> findLikeByCommentId(Long commentId) {
        return null;
    }

    @Override
    public List<Like> findLikeByStatusId(Long statusId) {
        return null;
    }

    @Override
    public Like readLikeByCommentId(Long commentId, Long userId) {
        return null;
    }

    @Override
    public Like readLikeByStatusId(Long statusId, Long userId) {
        return null;
    }
}


text:
package com.elmakers.mine.bukkit.entity;

import java.lang.ref.WeakReference;
import java.util.UUID;
import javax.annotation.Nullable;

import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.util.BlockVector;

import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.block.UndoList;
import com.elmakers.mine.bukkit.utility.CompatibilityLib;

public class SpawnedEntity {
    private final String worldName;
    private final BlockVector location;
    private final UUID id;
    private final WeakReference<Entity> entity;

    public SpawnedEntity(Entity entity) {
        this.entity = new WeakReference<>(entity);
        worldName = entity.getWorld().getName();
        location = new BlockVector(entity.getLocation().toVector());
        id = entity.getUniqueId();
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof SpawnedEntity)) return false;
        SpawnedEntity other = (SpawnedEntity)o;
        return other.id.equals(id);
    }

    @Nullable
    public Entity getEntity() {
        return this.entity.get();
    }

    public void despawn(MageController controller, CastContext context) {
        Entity entity = this.getEntity();
        if (entity == null || !entity.isValid()) {
            World world = controller.getPlugin().getServer().getWorld(worldName);

            // Not force-loading worlds for this, so this entity gets to live to fight another day
            if (world == null) {
                return;
            }
            Location entityLocation = new Location(world, location.getX(), location.getY(), location.getZ());
            if (!CompatibilityLib.getCompatibilityUtils().isChunkLoaded(entityLocation)) {
                CompatibilityLib.getCompatibilityUtils().loadChunk(entityLocation, false, chunk -> {
                    Entity removeEntity = CompatibilityLib.getCompatibilityUtils().getEntity(world, id);
                    if (removeEntity != null) {
                        UndoList.setUndoList(removeEntity, null);
                        removeEntity.remove();
                    }
                });
            } else {
                entity = CompatibilityLib.getCompatibilityUtils().getEntity(world, id);
            }
        }
        if (entity != null && entity.isValid()) {
            if (context != null && context.hasEffects("undo_entity")) {
                context.playEffects("undo_entity", 1.0f, null, null, entity.getLocation(), entity, null);
            }
            UndoList.setUndoList(entity, null);
            entity.remove();
        }
    }
}


text:
layout: webgl
title: Boids
image: /public/experiments/boids.jpeg
date: 2017-05-11
excerpt: Made with Canvas
datgui: true
---

<style>
.webgl-container {
    background: #4499d6;
}
</style>

<script>
{% include boids.js %}

var startTime = Date.now() / 1000,
    time = startTime;

function resize() {
    var canvas = document.getElementById("canvas");
    // Lookup the size the browser is displaying the canvas.
    var displayWidth = canvas.parentNode.clientWidth;
    var displayHeight = canvas.parentNode.clientHeight;

    // Check if the canvas is not the same size.
    if (canvas.width !== displayWidth ||
        canvas.height !== displayHeight) {

        // Make the canvas the same size
        canvas.width = displayWidth;
        canvas.height = displayHeight;

        canvas.style.width = displayWidth + "px";
        canvas.style.height = displayHeight + "px";
    }

    return displayHeight / displayWidth;
}

function defineCanvasProperties(canvas) {
    canvas.cursor = {
        x: 0,
        y: 0,
        z: 0
    };
    canvas.setCursor = function(x, y, z) {
        var r = this.getBoundingClientRect();
        this.cursor.x = x - r.left;
        this.cursor.y = y - r.top;
        if (z !== undefined)
            this.cursor.z = z;
    }
    canvas.onmousedown = function(e) {
        this.setCursor(e.clientX, e.clientY, 1);
    }
    canvas.onmousemove = function(e) {
        this.setCursor(e.clientX, e.clientY);
    }
    canvas.onmouseup = function(e) {
        this.setCursor(e.clientX, e.clientY, 0);
    }

}

function drawCanvases(canvases) {
    window.canvases = canvases;
    for (var i = 0; i < canvases.length; i++)
        defineCanvasProperties(canvases[i]);
    setInterval(function() {
        resize();
        var i, canvas, context;
        time = Date.now() / 1000 - startTime;
        for (i = 0; i < canvases.length; i++)
            if ((canvas = canvases[i]).update) {
                context = canvas.getContext("2d");
                context.clearRect(0, 0, canvas.width, canvas.height);
                canvas.update(context);
            }
    }, 30);
}

var boids, gui;

window.onload = function() {
    defineCanvasProperties(canvas);
    boids = new Swarm(canvas.getContext("2d"));
    gui = new dat.GUI();
    gui.addColor(boids, 'background');
    gui.add(boids, 'numBoids', 10, 1000).step(1);

    var yellow = gui.addFolder('Yellow Swarm'),
        salmon= gui.addFolder('Salmon Swarm'),
        pred = gui.addFolder('Predator');

    var controllers = [];
    controllers.push(yellow.addColor(boids.config.yellow, 'fillStyle'));
    controllers.push(yellow.add(boids.config.yellow, 'radius', 1, 15));
    controllers.push(yellow.add(boids.config.yellow, 'radialSpeed', .00005, .3));
    controllers.push(yellow.add(boids.config.yellow, 'speed', 1, 10));
    controllers.push(yellow.add(boids.config.yellow, 'vision', 10, 200));
    controllers.push(salmon.addColor(boids.config.salmon , 'fillStyle'));
    controllers.push(salmon.add(boids.config.salmon, 'radius', 1, 15));
    controllers.push(salmon.add(boids.config.salmon, 'radialSpeed', .00005, .3));
    controllers.push(salmon.add(boids.config.salmon, 'speed', 1, 10));
    controllers.push(salmon.add(boids.config.salmon, 'vision', 10, 200));
    for (var i = 0; i < controllers.length; i++)
        controllers[i].onChange(function(value) {
            boids.update();
        });

    controllers = [];
    pred.add(boids, 'activePred');
    controllers.push(pred.add(boids.config.pred, 'radius', 1, 15));
    controllers.push(pred.add(boids.config.pred, 'radialSpeed', .00005, .3));
    controllers.push(pred.add(boids.config.pred, 'speed', 1, 10));
    controllers.push(pred.add(boids.config.pred, 'vision', 10, 200));
    controllers.push(pred.addColor(boids.config.pred, 'fillStyle'));
     for (var i = 0; i < controllers.length; i++)
        controllers[i].onChange(function(value) {
            boids.updatePred();
        });

    boids.id = setInterval(boids.animate, 50);
    boids.animate();
    boids.clear();
    boids.createBoids(600);
}

</script>


text:
Imports ControlLibrary
Imports ControlLibrary.Kesoft.Windows.Forms.Win7StyleTreeView
Imports mzkit.DockSample

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class frmMsImagingTweaks
    Inherits ToolWindow
    ' Inherits Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmMsImagingTweaks))
        Me.PropertyGrid1 = New System.Windows.Forms.PropertyGrid()
        Me.ContextMenuStrip1 = New System.Windows.Forms.ContextMenuStrip(Me.components)
        Me.RenderLayerCompositionModeToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
        Me.RenderingToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
        Me.ToolStripMenuItem1 = New System.Windows.Forms.ToolStripSeparator()
        Me.LoadAllIonsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
        Me.ClearSelectionToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
        Me.SplitContainer1 = New System.Windows.Forms.SplitContainer()
        Me.Win7StyleTreeView1 = New ControlLibrary.Kesoft.Windows.Forms.Win7StyleTreeView.Win7StyleTreeView(Me.components)
        Me.ImageList1 = New System.Windows.Forms.ImageList(Me.components)
        Me.ToolStrip1 = New System.Windows.Forms.ToolStrip()
        Me.ToolStripLabel1 = New System.Windows.Forms.ToolStripLabel()
        Me.ToolStripSpringTextBox1 = New ControlLibrary.ToolStripSpringTextBox()
        Me.ToolStripButton1 = New System.Windows.Forms.ToolStripButton()
        Me.ToolStripButton2 = New System.Windows.Forms.ToolStripButton()
        Me.ToolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator()
        Me.ToolStripButton3 = New System.Windows.Forms.ToolStripButton()
        Me.LoadBasePeakIonsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
        Me.ToolStripMenuItem2 = New System.Windows.Forms.ToolStripSeparator()
        Me.ContextMenuStrip1.SuspendLayout()
        CType(Me.SplitContainer1, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SplitContainer1.Panel1.SuspendLayout()
        Me.SplitContainer1.Panel2.SuspendLayout()
        Me.SplitContainer1.SuspendLayout()
        Me.ToolStrip1.SuspendLayout()
        Me.SuspendLayout()
        '
        'PropertyGrid1
        '
        Me.PropertyGrid1.AllowDrop = True
        Me.PropertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.PropertyGrid1.LineColor = System.Drawing.SystemColors.ScrollBar
        Me.PropertyGrid1.Location = New System.Drawing.Point(0, 0)
        Me.PropertyGrid1.Name = "PropertyGrid1"
        Me.PropertyGrid1.Size = New System.Drawing.Size(377, 414)
        Me.PropertyGrid1.TabIndex = 0
        '
        'ContextMenuStrip1
        '
        Me.ContextMenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.RenderLayerCompositionModeToolStripMenuItem, Me.RenderingToolStripMenuItem, Me.ToolStripMenuItem1, Me.LoadAllIonsToolStripMenuItem, Me.LoadBasePeakIonsToolStripMenuItem, Me.ToolStripMenuItem2, Me.ClearSelectionToolStripMenuItem})
        Me.ContextMenuStrip1.Name = "ContextMenuStrip1"
        Me.ContextMenuStrip1.Size = New System.Drawing.Size(285, 148)
        '
        'RenderLayerCompositionModeToolStripMenuItem
        '
        Me.RenderLayerCompositionModeToolStripMenuItem.Name = "RenderLayerCompositionModeToolStripMenuItem"
        Me.RenderLayerCompositionModeToolStripMenuItem.Size = New System.Drawing.Size(284, 22)
        Me.RenderLayerCompositionModeToolStripMenuItem.Text = "Render (Layers Composition Mode)"
        '
        'RenderingToolStripMenuItem
        '
        Me.RenderingToolStripMenuItem.Image = CType(resources.GetObject("RenderingToolStripMenuItem.Image"), System.Drawing.Image)
        Me.RenderingToolStripMenuItem.Name = "RenderingToolStripMenuItem"
        Me.RenderingToolStripMenuItem.Size = New System.Drawing.Size(284, 22)
        Me.RenderingToolStripMenuItem.Text = "Render"
        '
        'ToolStripMenuItem1
        '
        Me.ToolStripMenuItem1.Name = "ToolStripMenuItem1"
        Me.ToolStripMenuItem1.Size = New System.Drawing.Size(281, 6)
        '
        'LoadAllIonsToolStripMenuItem
        '
        Me.LoadAllIonsToolStripMenuItem.Name = "LoadAllIonsToolStripMenuItem"
        Me.LoadAllIonsToolStripMenuItem.Size = New System.Drawing.Size(284, 22)
        Me.LoadAllIonsToolStripMenuItem.Text = "Load All Ions"
        '
        'ClearSelectionToolStripMenuItem
        '
        Me.ClearSelectionToolStripMenuItem.Image = CType(resources.GetObject("ClearSelectionToolStripMenuItem.Image"), System.Drawing.Image)
        Me.ClearSelectionToolStripMenuItem.Name = "ClearSelectionToolStripMenuItem"
        Me.ClearSelectionToolStripMenuItem.Size = New System.Drawing.Size(284, 22)
        Me.ClearSelectionToolStripMenuItem.Text = "Clear Selection"
        '
        'SplitContainer1
        '
        Me.SplitContainer1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.SplitContainer1.Location = New System.Drawing.Point(0, 25)
        Me.SplitContainer1.Name = "SplitContainer1"
        Me.SplitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal
        '
        'SplitContainer1.Panel1
        '
        Me.SplitContainer1.Panel1.Controls.Add(Me.Win7StyleTreeView1)
        '
        'SplitContainer1.Panel2
        '
        Me.SplitContainer1.Panel2.Controls.Add(Me.PropertyGrid1)
        Me.SplitContainer1.Size = New System.Drawing.Size(377, 529)
        Me.SplitContainer1.SplitterDistance = 111
        Me.SplitContainer1.TabIndex = 2
        '
        'Win7StyleTreeView1
        '
        Me.Win7StyleTreeView1.CheckBoxes = True
        Me.Win7StyleTreeView1.ContextMenuStrip = Me.ContextMenuStrip1
        Me.Win7StyleTreeView1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.Win7StyleTreeView1.FullRowSelect = True
        Me.Win7StyleTreeView1.HotTracking = True
        Me.Win7StyleTreeView1.Location = New System.Drawing.Point(0, 0)
        Me.Win7StyleTreeView1.Name = "Win7StyleTreeView1"
        Me.Win7StyleTreeView1.ShowLines = False
        Me.Win7StyleTreeView1.ShowNodeToolTips = True
        Me.Win7StyleTreeView1.Size = New System.Drawing.Size(377, 111)
        Me.Win7StyleTreeView1.TabIndex = 0
        '
        'ImageList1
        '
        Me.ImageList1.ImageStream = CType(resources.GetObject("ImageList1.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.ImageList1.TransparentColor = System.Drawing.Color.Transparent
        Me.ImageList1.Images.SetKeyName(0, "folder-pictures.png")
        Me.ImageList1.Images.SetKeyName(1, "pix.png")
        '
        'ToolStrip1
        '
        Me.ToolStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripLabel1, Me.ToolStripSpringTextBox1, Me.ToolStripButton1, Me.ToolStripButton2, Me.ToolStripSeparator1, Me.ToolStripButton3})
        Me.ToolStrip1.Location = New System.Drawing.Point(0, 0)
        Me.ToolStrip1.Name = "ToolStrip1"
        Me.ToolStrip1.Size = New System.Drawing.Size(377, 25)
        Me.ToolStrip1.TabIndex = 3
        Me.ToolStrip1.Text = "ToolStrip1"
        '
        'ToolStripLabel1
        '
        Me.ToolStripLabel1.Name = "ToolStripLabel1"
        Me.ToolStripLabel1.Size = New System.Drawing.Size(33, 22)
        Me.ToolStripLabel1.Text = "m/z:"
        '
        'ToolStripSpringTextBox1
        '
        Me.ToolStripSpringTextBox1.Font = New System.Drawing.Font("Segoe UI", 9.0!)
        Me.ToolStripSpringTextBox1.Name = "ToolStripSpringTextBox1"
        Me.ToolStripSpringTextBox1.Size = New System.Drawing.Size(226, 25)
        '
        'ToolStripButton1
        '
        Me.ToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
        Me.ToolStripButton1.Image = CType(resources.GetObject("ToolStripButton1.Image"), System.Drawing.Image)
        Me.ToolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta
        Me.ToolStripButton1.Name = "ToolStripButton1"
        Me.ToolStripButton1.Size = New System.Drawing.Size(23, 22)
        Me.ToolStripButton1.Text = "View Layer"
        '
        'ToolStripButton2
        '
        Me.ToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
        Me.ToolStripButton2.Image = CType(resources.GetObject("ToolStripButton2.Image"), System.Drawing.Image)
        Me.ToolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta
        Me.ToolStripButton2.Name = "ToolStripButton2"
        Me.ToolStripButton2.Size = New System.Drawing.Size(23, 22)
        Me.ToolStripButton2.Text = "Add Ion Layer"
        '
        'ToolStripSeparator1
        '
        Me.ToolStripSeparator1.Name = "ToolStripSeparator1"
        Me.ToolStripSeparator1.Size = New System.Drawing.Size(6, 25)
        '
        'ToolStripButton3
        '
        Me.ToolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
        Me.ToolStripButton3.Image = CType(resources.GetObject("ToolStripButton3.Image"), System.Drawing.Image)
        Me.ToolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta
        Me.ToolStripButton3.Name = "ToolStripButton3"
        Me.ToolStripButton3.Size = New System.Drawing.Size(23, 22)
        Me.ToolStripButton3.Text = "Clear Layers"
        '
        'LoadBasePeakIonsToolStripMenuItem
        '
        Me.LoadBasePeakIonsToolStripMenuItem.Name = "LoadBasePeakIonsToolStripMenuItem"
        Me.LoadBasePeakIonsToolStripMenuItem.Size = New System.Drawing.Size(284, 22)
        Me.LoadBasePeakIonsToolStripMenuItem.Text = "Load BasePeak Ions"
        '
        'ToolStripMenuItem2
        '
        Me.ToolStripMenuItem2.Name = "ToolStripMenuItem2"
        Me.ToolStripMenuItem2.Size = New System.Drawing.Size(281, 6)
        '
        'frmMsImagingTweaks
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 12.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackColor = System.Drawing.Color.White
        Me.ClientSize = New System.Drawing.Size(377, 554)
        Me.Controls.Add(Me.SplitContainer1)
        Me.Controls.Add(Me.ToolStrip1)
        Me.DoubleBuffered = True
        Me.Name = "frmMsImagingTweaks"
        Me.ContextMenuStrip1.ResumeLayout(False)
        Me.SplitContainer1.Panel1.ResumeLayout(False)
        Me.SplitContainer1.Panel2.ResumeLayout(False)
        CType(Me.SplitContainer1, System.ComponentModel.ISupportInitialize).EndInit()
        Me.SplitContainer1.ResumeLayout(False)
        Me.ToolStrip1.ResumeLayout(False)
        Me.ToolStrip1.PerformLayout()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

    Friend WithEvents PropertyGrid1 As PropertyGrid
    Friend WithEvents ContextMenuStrip1 As ContextMenuStrip
    Friend WithEvents RenderingToolStripMenuItem As ToolStripMenuItem
    Friend WithEvents SplitContainer1 As SplitContainer
    Friend WithEvents ClearSelectionToolStripMenuItem As ToolStripMenuItem
    Friend WithEvents ToolStrip1 As ToolStrip
    Friend WithEvents ToolStripLabel1 As ToolStripLabel
    Friend WithEvents ToolStripSpringTextBox1 As ToolStripSpringTextBox
    Friend WithEvents ToolStripButton1 As ToolStripButton
    Friend WithEvents ImageList1 As ImageList
    Friend WithEvents ToolStripButton2 As ToolStripButton
    Friend WithEvents ToolStripSeparator1 As ToolStripSeparator
    Friend WithEvents ToolStripButton3 As ToolStripButton
    Friend WithEvents ToolStripMenuItem1 As ToolStripSeparator
    Friend WithEvents Win7StyleTreeView1 As Win7StyleTreeView
    Friend WithEvents RenderLayerCompositionModeToolStripMenuItem As ToolStripMenuItem
    Friend WithEvents LoadAllIonsToolStripMenuItem As ToolStripMenuItem
    Friend WithEvents LoadBasePeakIonsToolStripMenuItem As ToolStripMenuItem
    Friend WithEvents ToolStripMenuItem2 As ToolStripSeparator
End Class


text:
package ec2

import (
	"context"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	"github.com/aws/aws-sdk-go-v2/service/ec2/types"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

// You can modify several parameters of an existing EBS volume, including volume
// size, volume type, and IOPS capacity. If your EBS volume is attached to a
// current-generation EC2 instance type, you might be able to apply these changes
// without stopping the instance or detaching the volume from it. For more
// information about modifying an EBS volume running Linux, see Modifying the size,
// IOPS, or type of an EBS volume on Linux
// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html).
// For more information about modifying an EBS volume running Windows, see
// Modifying the size, IOPS, or type of an EBS volume on Windows
// (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html).
// When you complete a resize operation on your volume, you need to extend the
// volume's file-system size to take advantage of the new storage capacity. For
// information about extending a Linux file system, see Extending a Linux file
// system
// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#recognize-expanded-volume-linux).
// For information about extending a Windows file system, see Extending a Windows
// file system
// (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html#recognize-expanded-volume-windows).
// You can use CloudWatch Events to check the status of a modification to an EBS
// volume. For information about CloudWatch Events, see the Amazon CloudWatch
// Events User Guide (https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/).
// You can also track the status of a modification using
// DescribeVolumesModifications. For information about tracking status changes
// using either method, see Monitoring volume modifications
// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods).
// With previous-generation instance types, resizing an EBS volume might require
// detaching and reattaching the volume or stopping and restarting the instance.
// For more information, see Amazon EBS Elastic Volumes
// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modify-volume.html)
// (Linux) or Amazon EBS Elastic Volumes
// (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-modify-volume.html)
// (Windows). If you reach the maximum volume modification rate per volume limit,
// you will need to wait at least six hours before applying further modifications
// to the affected EBS volume.
func (c *Client) ModifyVolume(ctx context.Context, params *ModifyVolumeInput, optFns ...func(*Options)) (*ModifyVolumeOutput, error) {
	if params == nil {
		params = &ModifyVolumeInput{}
	}

	result, metadata, err := c.invokeOperation(ctx, "ModifyVolume", params, optFns, addOperationModifyVolumeMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*ModifyVolumeOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type ModifyVolumeInput struct {

	// The ID of the volume.
	//
	// This member is required.
	VolumeId *string

	// Checks whether you have the required permissions for the action, without
	// actually making the request, and provides an error response. If you have the
	// required permissions, the error response is DryRunOperation. Otherwise, it is
	// UnauthorizedOperation.
	DryRun bool

	// The target IOPS rate of the volume. This parameter is valid only for gp3, io1,
	// and io2 volumes. The following are the supported values for each volume type:
	//
	// *
	// gp3: 3,000-16,000 IOPS
	//
	// * io1: 100-64,000 IOPS
	//
	// * io2: 100-64,000 IOPS
	//
	// Default:
	// If no IOPS value is specified, the existing value is retained, unless a volume
	// type is modified that supports different values.
	Iops int32

	// Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach,
	// you can attach the volume to up to 16  Nitro-based instances
	// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances)
	// in the same Availability Zone. This parameter is supported with io1 and io2
	// volumes only. For more information, see  Amazon EBS Multi-Attach
	// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html) in
	// the Amazon Elastic Compute Cloud User Guide.
	MultiAttachEnabled bool

	// The target size of the volume, in GiB. The target volume size must be greater
	// than or equal to the existing size of the volume. The following are the
	// supported volumes sizes for each volume type:
	//
	// * gp2 and gp3: 1-16,384
	//
	// * io1
	// and io2: 4-16,384
	//
	// * st1 and sc1: 125-16,384
	//
	// * standard: 1-1,024
	//
	// Default: If
	// no size is specified, the existing size is retained.
	Size int32

	// The target throughput of the volume, in MiB/s. This parameter is valid only for
	// gp3 volumes. The maximum value is 1,000. Default: If no throughput value is
	// specified, the existing value is retained. Valid Range: Minimum value of 125.
	// Maximum value of 1000.
	Throughput int32

	// The target EBS volume type of the volume. For more information, see Amazon EBS
	// volume types
	// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the
	// Amazon Elastic Compute Cloud User Guide. Default: If no type is specified, the
	// existing type is retained.
	VolumeType types.VolumeType
}

type ModifyVolumeOutput struct {

	// Information about the volume modification.
	VolumeModification *types.VolumeModification

	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata
}

func addOperationModifyVolumeMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsEc2query_serializeOpModifyVolume{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsEc2query_deserializeOpModifyVolume{}, middleware.After)
	if err != nil {
		return err
	}
	if err = addSetLoggerMiddleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
		return err
	}
	if err = addRetryMiddlewares(stack, options); err != nil {
		return err
	}
	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = addClientUserAgent(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = addOpModifyVolumeValidationMiddleware(stack); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opModifyVolume(options.Region), middleware.Before); err != nil {
		return err
	}
	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	return nil
}

func newServiceMetadataMiddleware_opModifyVolume(region string) *awsmiddleware.RegisterServiceMetadata {
	return &awsmiddleware.RegisterServiceMetadata{
		Region:        region,
		ServiceID:     ServiceID,
		SigningName:   "ec2",
		OperationName: "ModifyVolume",
	}
}


text: this is a html partial


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>First:  - Wash your hands well with soap and warm water.</value>
		<pattern_crowdsource> First:  - Wash your [[hands|C0018563]] well with [[soap|C0037392]] and warm water.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>First</surface-form>
				<RDF-ID>C1279901</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hands</surface-form>
				<RDF-ID>C0018563</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>well</surface-form>
				<RDF-ID>C0205170</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>soap</surface-form>
				<RDF-ID>C0037392</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>water</surface-form>
				<RDF-ID>C0020311</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0037392 PART_OF C0018563</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- The medicine should be liquid, or finely crushed and dissolved in water, so that the tube does not get blocked.</value>
		<pattern_crowdsource> - The [[medicine|C0013227]] should be liquid, or finely crushed and dissolved in [[water|C0043047]], so that the tube does not get blocked.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>medicine</surface-form>
				<RDF-ID>C0013227</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>water</surface-form>
				<RDF-ID>C0043047</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>tube</surface-form>
				<RDF-ID>C1561954</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>not</surface-form>
				<RDF-ID>C1518422</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0013227 COEXISTS_WITH C0043047</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Call your child's health care provider if your child:  - Seems hungry after the feeding  - Has diarrhea after feedings  - Has a hard and swollen belly 1 hour after feedings  - Seems to be in pain  - Has changes in their condition  - Is on new medicine  - Is constipated and passing hard, dry stools    Also call the doctor if:  - The feeding tube has come out and you do not know how to replace it.</value>
		<pattern_crowdsource> Call your child's [[health care provider|C0018724]] if your child:  - Seems hungry after the feeding  - Has diarrhea after feedings  - Has a hard and swollen belly 1 hour after feedings  - Seems to be in [[pain|C0030193]]  - Has changes in their condition  - Is on new medicine  - Is constipated and passing hard, dry stools    Also call the doctor if:  - The feeding tube has come out and you do not know how to replace it.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>child's</surface-form>
				<RDF-ID>C0008059</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>health care provider</surface-form>
				<RDF-ID>C0018724</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>child</surface-form>
				<RDF-ID>C0008059</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hungry</surface-form>
				<RDF-ID>C0020175</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>diarrhea</surface-form>
				<RDF-ID>C0011991</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hard</surface-form>
				<RDF-ID>C0018599</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>swollen</surface-form>
				<RDF-ID>C0038999</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hour</surface-form>
				<RDF-ID>C0439227</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>pain</surface-form>
				<RDF-ID>C0030193</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>condition</surface-form>
				<RDF-ID>C0348080</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>new</surface-form>
				<RDF-ID>C0205314</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>medicine</surface-form>
				<RDF-ID>C0025118</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>dry</surface-form>
				<RDF-ID>C0205222</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hard, dry stools</surface-form>
				<RDF-ID>C0278016</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>doctor</surface-form>
				<RDF-ID>C0031831</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>feeding tube</surface-form>
				<RDF-ID>C0086337</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>out</surface-form>
				<RDF-ID>C0439787</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>not</surface-form>
				<RDF-ID>C1518422</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>know</surface-form>
				<RDF-ID>C0205309</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0018724 DIAGNOSES C0030193</triple>
		</triples>
	</Sentence>

</Document>


text:
"""
    wechatpy.parser
    ~~~~~~~~~~~~~~~~
    This module provides functions for parsing WeChat messages

    :copyright: (c) 2014 by messense.
    :license: MIT, see LICENSE for more details.
"""
from __future__ import absolute_import, unicode_literals
import xmltodict

from wechatpy.messages import MESSAGE_TYPES, UnknownMessage
from wechatpy.events import EVENT_TYPES
from wechatpy.utils import to_text

def parse_message(xml):
    """
    解析微信服务器推送的 XML 消息

    :param xml: XML 消息
    :return: 解析成功返回对应的消息或事件,否则返回 ``UnknownMessage``
    """
    if not xml:
        return
    message = xmltodict.parse(to_text(xml))['xml']
    message_type = message['MsgType'].lower()
    event_type = None
    if message_type == 'event' or message_type.startswith('device_'):
        if 'Event' in message:
            event_type = message['Event'].lower()
        # special event type for device_event
        if event_type is None and message_type.startswith('device_'):
            event_type = message_type
        elif message_type.startswith('device_'):
            event_type = 'device_{event}'.format(event=event_type)

        if event_type == 'subscribe' and message.get('EventKey'):
            event_key = message['EventKey']
            if event_key.startswith(('scanbarcode|', 'scanimage|')):
                event_type = 'subscribe_scan_product'
                message['Event'] = event_type
            elif event_key.startswith('qrscene_'):
                # Scan to subscribe with scene id event
                event_type = 'subscribe_scan'
                message['Event'] = event_type
                message['EventKey'] = event_key.replace('qrscene_', '')
        message_class = EVENT_TYPES.get(event_type, UnknownMessage)
    else:
        message_class = MESSAGE_TYPES.get(message_type, UnknownMessage)
    return message_class(message)


text:
namespace chromeos {

namespace {

const char kSharedProfilePath[] = "/profile/default";

void PassEmptyDictionary(
    const ShillProfileClient::DictionaryValueCallbackWithoutStatus& callback) {
  base::DictionaryValue dictionary;
  if (callback.is_null())
    return;
  callback.Run(dictionary);
}

void PassDictionary(
    const ShillProfileClient::DictionaryValueCallbackWithoutStatus& callback,
    const base::DictionaryValue* dictionary) {
  if (callback.is_null())
    return;
  callback.Run(*dictionary);
}

base::DictionaryValue* GetOrCreateDictionary(const std::string& key,
                                             base::DictionaryValue* dict) {
  base::DictionaryValue* nested_dict = NULL;
  dict->GetDictionaryWithoutPathExpansion(key, &nested_dict);
  if (!nested_dict) {
    nested_dict = new base::DictionaryValue;
    dict->SetWithoutPathExpansion(key, nested_dict);
  }
  return nested_dict;
}

}  // namespace

ShillProfileClientStub::ShillProfileClientStub() {
  AddProfile(kSharedProfilePath);
}

ShillProfileClientStub::~ShillProfileClientStub() {
}

void ShillProfileClientStub::AddPropertyChangedObserver(
    const dbus::ObjectPath& profile_path,
    ShillPropertyChangedObserver* observer) {
}

void ShillProfileClientStub::RemovePropertyChangedObserver(
    const dbus::ObjectPath& profile_path,
    ShillPropertyChangedObserver* observer) {
}

void ShillProfileClientStub::GetProperties(
    const dbus::ObjectPath& profile_path,
    const DictionaryValueCallbackWithoutStatus& callback,
    const ErrorCallback& error_callback) {
  base::DictionaryValue* profile = GetProfile(profile_path, error_callback);
  if (!profile)
    return;

  scoped_ptr<base::DictionaryValue> properties(new base::DictionaryValue);
  base::ListValue* entry_paths = new base::ListValue;
  properties->SetWithoutPathExpansion(flimflam::kEntriesProperty, entry_paths);
  for (base::DictionaryValue::Iterator it(*profile); !it.IsAtEnd();
       it.Advance()) {
    entry_paths->AppendString(it.key());
  }

  MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&PassDictionary, callback, base::Owned(properties.release())));
}

void ShillProfileClientStub::GetEntry(
    const dbus::ObjectPath& profile_path,
    const std::string& entry_path,
    const DictionaryValueCallbackWithoutStatus& callback,
    const ErrorCallback& error_callback) {
  base::DictionaryValue* profile = GetProfile(profile_path, error_callback);
  if (!profile)
    return;

  base::DictionaryValue* entry = NULL;
  profile->GetDictionaryWithoutPathExpansion(entry_path, &entry);
  if (!entry) {
    error_callback.Run("Error.InvalidProfileEntry", "Invalid profile entry");
    return;
  }

  MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&PassDictionary, callback, base::Owned(entry->DeepCopy())));
}

void ShillProfileClientStub::DeleteEntry(const dbus::ObjectPath& profile_path,
                                         const std::string& entry_path,
                                         const base::Closure& callback,
                                         const ErrorCallback& error_callback) {
  base::DictionaryValue* profile = GetProfile(profile_path, error_callback);
  if (!profile)
    return;

  if (!profile->RemoveWithoutPathExpansion(entry_path, NULL)) {
    error_callback.Run("Error.InvalidProfileEntry", "Invalid profile entry");
    return;
  }

  MessageLoop::current()->PostTask(FROM_HERE, callback);
}

ShillProfileClient::TestInterface* ShillProfileClientStub::GetTestInterface() {
  return this;
}

void ShillProfileClientStub::AddProfile(const std::string& profile_path) {
  profile_entries_.SetWithoutPathExpansion(profile_path,
                                           new base::DictionaryValue);
}

void ShillProfileClientStub::AddEntry(const std::string& profile_path,
                                      const std::string& entry_path,
                                      const base::DictionaryValue& properties) {
  base::DictionaryValue* profile = GetOrCreateDictionary(profile_path,
                                                         &profile_entries_);
  profile->SetWithoutPathExpansion(entry_path,
                                   properties.DeepCopy());
}

bool ShillProfileClientStub::AddService(const std::string& service_path) {
  ShillServiceClient::TestInterface* service_test =
      DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface();
  const base::DictionaryValue* properties =
      service_test->GetServiceProperties(service_path);
  std::string profile_path;
  if (!properties)
    return false;

  properties->GetStringWithoutPathExpansion(flimflam::kProfileProperty,
                                            &profile_path);
  if (profile_path.empty())
    return false;

  AddEntry(profile_path, service_path, *properties);
  return true;
}

base::DictionaryValue* ShillProfileClientStub::GetProfile(
    const dbus::ObjectPath& profile_path,
    const ErrorCallback& error_callback) {
  base::DictionaryValue* profile = NULL;
  profile_entries_.GetDictionaryWithoutPathExpansion(profile_path.value(),
                                                     &profile);
  if (!profile)
    error_callback.Run("Error.InvalidProfile", "Invalid profile");
  return profile;
}

}  // namespace chromeos


text:
namespace llvm {

inline std::ostream &operator<<(std::ostream &os, StringRef s) {
  return os.write(s.data(), ofp::Signed_cast(s.size()));
}

}  // namespace llvm

using namespace ofp::yaml;

const char *const kMessagePrefix = R"""(  version: !opt UInt8
  datapath_id: !opt DatapathID
  xid: !opt UInt32
  conn_id: !opt UInt64
  auxiliary_id: !opt UInt8
  flags: !optout [MultipartFlags]
  time: !optout Timestamp
  src: !optout IPEndpoint
  dst: !optout IPEndpoint
  _file: !optout String
)""";

const char *const kBriefMessagePrefix = "  datapath_id: !opt DatapathID\n";

static bool equalsAlnum(llvm::StringRef lhs, llvm::StringRef rhs);
static std::string stringJoin(const std::vector<llvm::StringRef> &vec,
                              const char *sep);
static void replaceAll(std::string &str, const std::string &from,
                       const std::string &to);
static std::string unsignedTypeName(size_t size);
static std::string unsignedTypeEnum(size_t size);
static bool isTypeName(llvm::StringRef s);

bool Schema::equals(llvm::StringRef s) const {
  return equalsAlnum(name_, s) || equalsAlnum(type_, s);
}

/// Return a set of schemas that this schema depends on.
///
/// This is implemented by scanning each line of the schema value looking for
/// the pattern "key: Type ..." where Type starts with a capital letter, but
/// is not all caps. This function also checks for a type enclosed in brackets,
/// and recognizes YAML tags. (e.g. "key: !tag Type").
std::set<std::string> Schema::dependsOnSchemas() const {
  std::set<std::string> result;
  std::stringstream iss{value_.str()};

  std::string line;
  while (std::getline(iss, line)) {
    auto pair = llvm::StringRef{line}.split(':');
    if (!pair.second.empty()) {
      auto type = pair.second.trim();
      auto endType = type.find_first_of(" \t\n\v\f\r]");
      // If the first word begins with '!', get the second word.
      if (type.startswith("!")) {
        type = type.drop_front(endType < type.size() ? endType : type.size());
        type = type.ltrim();
        endType = type.find_first_of(" \t\n\v\f\r]");
      }
      if (endType < type.size()) {
        type = type.drop_back(type.size() - endType);
      }
      if (type.startswith("[")) {
        type = type.drop_front(1);
      }
      if (isTypeName(type)) {
        result.insert(type.str());
      }
    }
  }

  return result;
}

void Schema::print(std::ostream &os, bool brief) const {
  os << type() << '/' << name().str() << ": ";
  if (isObject_) {
    os << '\n';
    if (type().equals("Message")) {
      if (brief) {
        os << kBriefMessagePrefix;
      } else {
        os << kMessagePrefix;
      }
    }
    printValue(os, 2);
  } else {
    printValue(os);
  }
  os << '\n';
}

void Schema::printValue(std::ostream &os, unsigned indent) const {
  std::string val = value().str();

  if (indent > 0) {
    std::string spaces(indent, ' ');
    val = spaces + val;
    replaceAll(val, "\n", "\n" + spaces);
  }

  os << val;
}

void Schema::init(const char *schema) {
  // Split first line from the rest.
  auto p = llvm::StringRef{schema}.split('\n');

  // Set value to the rest.
  value_ = p.second;

  //  If the first line is enclosed in braces, we trim them and set isObject_
  //  to true.
  if (p.first.startswith("{")) {
    p.first = p.first.ltrim("{").rtrim("}");
    isObject_ = true;
  }

  // Parse the first line of form `type/name` or just `name`.
  std::tie(type_, name_) = p.first.split('/');
  if (name_.empty()) {
    std::swap(type_, name_);
  }
}

std::string Schema::MakeSchemaString(const char *const name,
                                     const std::vector<llvm::StringRef> &values,
                                     size_t size) {
  std::string result = stringJoin(values, " | ");
  auto line = llvm::StringRef{name};

  if (line.startswith_lower("mixed/")) {
    result = unsignedTypeName(size) + " | " + result;
  } else if (line.startswith_lower("enum/")) {
    result += " | " + unsignedTypeEnum(size);
  }

  return std::string(name) + "\n" + result + "\n";
}

std::string Schema::MakeFlagSchemaString(const char *name,
                                         const std::string &values,
                                         size_t size) {
  llvm::SmallVector<llvm::StringRef, 25> vals;
  llvm::StringRef{values}.split(vals, ",");

  std::vector<llvm::StringRef> words;
  for (auto val : vals) {
    if (!val.ltrim().startswith("'0x"))
      words.push_back(val.trim());
  }

  // Sometimes `name` will be formatted as "type/name=VAL1,VAL2,...,VALN". Check
  // for this syntax and include the extra values in the list. This is used
  // to include values that consist of multiple masked bits.
  llvm::StringRef key;
  llvm::StringRef extraValues;
  std::tie(key, extraValues) = llvm::StringRef{name}.split('=');

  if (!extraValues.empty()) {
    vals.clear();
    llvm::StringRef{extraValues}.split(vals, ",");
    for (auto val : vals) {
      words.push_back(val.trim());
    }
  }

  std::string result = stringJoin(words, " | ");
  result += " | " + unsignedTypeEnum(size);

  return std::string(key) + '\n' + result + '\n';
}

// Compare two strings case insensitively skipping non-alphanumeric chars.
static bool equalsAlnum(llvm::StringRef lhs, llvm::StringRef rhs) {
  size_t i = 0;
  size_t j = 0;

  while (i < lhs.size() && j < rhs.size()) {
    if (!std::isalnum(lhs[i])) {
      ++i;
      continue;
    }
    if (!std::isalnum(rhs[j])) {
      ++j;
      continue;
    }
    if (std::tolower(lhs[i]) != std::tolower(rhs[j])) {
      return false;
    }
    ++i;
    ++j;
  }

  return i >= lhs.size() && j >= rhs.size();
}

static std::string stringJoin(const std::vector<llvm::StringRef> &vec,
                              const char *sep) {
  std::string result;
  if (vec.empty())
    return result;
  for (size_t i = 0; i < vec.size() - 1; ++i) {
    result += vec[i];
    result += sep;
  }
  result += vec[vec.size() - 1];
  return result;
}

static void replaceAll(std::string &str, const std::string &from,
                       const std::string &to) {
  size_t start = 0;
  while ((start = str.find(from, start)) != std::string::npos) {
    str.replace(start, from.length(), to);
    start += to.length();
  }
}

/// Return a string that represents an unsigned type of the specified size.
static std::string unsignedTypeName(size_t size) {
  switch (size) {
    case 1:
      return "UInt8";
    case 2:
      return "UInt16";
    case 4:
      return "UInt32";
    case 8:
      return "UInt64";
    default:
      return "UIntXX";
  }
}

/// Return a string that represents an hexadecimal enum representation.
static std::string unsignedTypeEnum(size_t size) {
  switch (size) {
    case 1:
      return "Hex8";
    case 2:
      return "Hex16";
    case 4:
      return "Hex32";
    case 8:
      return "Hex64";
    default:
      return "HexXX";
  }
}

/// Return true if s begins with a capital letter, but is _not_ all caps.
/// Ignores underscore and hyphen.
static bool isTypeName(llvm::StringRef s) {
  if (s.empty() || !std::isalpha(s[0]) || !std::isupper(s[0]))
    return false;

  for (char ch : s) {
    if (ch == '_' || ch == '-')
      continue;
    if (std::isalpha(ch) && !std::isupper(ch)) {
      return true;
    }
  }

  return false;
}


text:
require"imlua"
require"cdlua"
require"cdluaim"

local image = im.ImageCreate(500, 500, im.RGB, im.BYTE)
image:AddAlpha()
local canvas = image:cdCreateCanvas()  -- Creates a CD_IMAGERGB canvas

canvas:Activate()

-- Use SetBackground instead of Background to avoid conflict with cd.QUERY
canvas:SetBackground(cd.EncodeAlpha(cd.EncodeColor(255, 255, 255), 0)) -- full transparent white
canvas:Clear()

fgcolor = cd.EncodeAlpha(cd.EncodeColor(255, 0, 0), 50) -- semi transparent red
canvas:Foreground(fgcolor)
canvas:Font("Times", cd.BOLD, 24)
canvas:Text(100, 100, "Test")
canvas:Line(0,0,100,100)

fgcolor = cd.EncodeColor(0, 0, 255)
canvas:Foreground(fgcolor)
canvas:Line(0,50,150,50)

canvas:Kill()

image:Save("new.png", "PNG")


text:
package com.xrosstools.idea.gef;

import com.intellij.openapi.vfs.VirtualFile;
import com.xrosstools.idea.gef.parts.EditContext;
import com.xrosstools.idea.gef.parts.EditPartFactory;
import com.xrosstools.idea.gef.util.IPropertySource;

import javax.swing.*;
import java.beans.PropertyChangeListener;

public interface PanelContentProvider<T extends IPropertySource> extends PropertyChangeListener {
    VirtualFile getFile();
    void setEditorPanel(EditorPanel editorPanel);
    EditorPanel getEditorPanel();

    T getContent() throws Exception;
    void saveContent() throws Exception;
    ContextMenuProvider getContextMenuProvider();
    ContextMenuProvider getOutlineContextMenuProvider();
    void buildPalette(JPanel palette);
    void buildToolbar(JToolBar toolbar);
    EditPartFactory createEditPartFactory();
    EditPartFactory createTreePartFactory();

    void preBuildRoot();
    void postBuildRoot();

    void createConnection(Object connModel);
    void createModel(Object model);
}


text:
@implementation LCBook (CoreDataProperties)

+ (NSFetchRequest<LCBook *> *)fetchRequest {
	return [[NSFetchRequest alloc] initWithEntityName:@"LCBook"];
}

@dynamic author;
@dynamic chapterCount;
@dynamic hasRead;
@dynamic language;
@dynamic name;
@dynamic pageCount;
@dynamic readingPlan;

@end


text:
#include "SkBmpCodec.h"
#include "SkImageInfo.h"
#include "SkMaskSwizzler.h"
#include "SkTypes.h"

/*
 * This class implements the decoding for bmp images using bit masks
 */
class SkBmpMaskCodec : public SkBmpCodec {
public:

    /*
     * Creates an instance of the decoder
     *
     * Called only by SkBmpCodec::NewFromStream
     * There should be no other callers despite this being public
     *
     * @param srcInfo contains the source width and height
     * @param stream the stream of encoded image data
     * @param bitsPerPixel the number of bits used to store each pixel
     * @param masks color masks for certain bmp formats
     * @param rowOrder indicates whether rows are ordered top-down or bottom-up
     */
    SkBmpMaskCodec(const SkImageInfo& srcInfo, SkStream* stream,
                   uint16_t bitsPerPixel, SkMasks* masks, RowOrder rowOrder);

protected:

    Result onGetPixels(const SkImageInfo& dstInfo, void* dst,
                       size_t dstRowBytes, const Options&, SkPMColor*,
                       int*) override;

private:

    bool initializeSwizzler(const SkImageInfo& dstInfo);

    Result decode(const SkImageInfo& dstInfo, void* dst, size_t dstRowBytes,
                  const Options& opts);

    SkAutoTDelete<SkMasks>              fMasks;        // owned
    SkAutoTDelete<SkMaskSwizzler>       fMaskSwizzler;
    SkAutoTDeleteArray<uint8_t>         fSrcBuffer;

    typedef SkBmpCodec INHERITED;
};


text:
Contribute
==========

This page is intended for developers of (or contributing to) PyPubSub.

.. contents:: In this section:
   :depth: 1
   :local:

.. _label-contributing:

Contributing
------------

Contributions are welcome! There are many ways you could contribute:

- bug fixes
- new features
- test results on different platforms
- documentation
- screencasts! (of applications using PyPubSub with output when user clicks)
- example topic trees (using ``pubsub.utils.printTopicTree()`` in latest
  version, or ``print Publisher`` in versions 1)
- other improvements
- money!

Please contact by posting on the forum pypubsub-dev forum (link in the
:ref:`label-support` section) or via http://github/schollii/pypubsub.

System Requirements
-------------------

In addition to the :ref:`label-install-reqs`, the following are required:

- To run unit tests:

  - pytest

- To generate the docs:

  - sphinx >= 1.4.8
  - In PyPubSub 3.3, which used an older version of sphinx, sphinx had to be patched as per post on
    sphinx-dev, but this no longer seems to be the required:

    .. literalinclude:: sphinx_patch1.txt
    .. literalinclude:: sphinx_patch2.txt

- To change code: PyCharm is recommended (Community Edition is sufficient). Various
  build configurations are available via the PyPubSub project when loaded into PyCharm.

Scripts Available
-----------------

*Unit Testing*:
    The test suite is most conveniently run from PyCharm via the "py.test in suite"
    build configuration. The tests can also be run automatically via pytest suite from
    the :file:`tests` folder.

    Once this passes using the project's default interpreter, a Terminal can be
    opened in PyCharm (or alternately a command shell from Windows), and from
    the PyPubSub root folder, run :command:`tox`. This will attempt to run the
    test suite in every 3.x version of Python, x>=3 (ie 3.3, 3.4, etc).

    After changes are committed to github, the Travis CI will automatically
    run the tests on a Linux platform, for all versions of Python supported
    by PyPubSub. The results will be at https://travis-ci.org/schollii/pypubsub/builds.

    There is also a buildbot maintained by Jerome Laheurte to test on additional
    \*nix flavors, including OSX. Test results can be viewed at
    https://jeromelaheurte.net/buildbot/pubsub/console.

*Performance Test*:
    A small performance test is available in the :file:`tests` folder.
    It can be run from PyCharm via the perf build configuration. This will
    generate a new :file:`.pstats` file which can be analysed.
    The test can also be run directly from command shell via
    :command:`python perf.py 1000`. The test is meant to compare the impact
    of changes before/after and is designed to compare on results on the
    same system (hardwards, OS).

*Documentation*:
    The documentation can be generated locally on Windows via the Gen Docs build
    configuration in PyCharm. Alternatively, it can be generated by running
    :command:`make html` from the :file:`docs` folder of source
    distribution.

    The documentation is automatically built and available online at
    http://pypubsub.readthedocs.io. The latest from master branch is at
    http://pypubsub.readthedocs.io/en/master/. The stable (released)
    documentation is at http://pypubsub.readthedocs.io/en/stable/.

Releases
--------

PyPubSub uses the latest stable Python packaging and distribution tools:
wheel, twine, and pypi.

Generating a new release involves the following sequence of steps:

- Verify that tox, sphinx, wheel, twine, and setuptools are installed.
- Ensure that pytest suite runs 100%, and that the examples run without error in
  examples/ folder (one of the examples requires wxPython -- install latest stable)
- Ensure that `tox` (run from pypubsub root folder) runs to completion without errors or
  warnings on all versions of Python (3.x)
- Update version number via a search-replace in the `Version Change` scope of PyCharm:

  - src/pubsub/__init__.py: version
  - docs/changelog.rst
  - src/pubsub/RELEASE_NOTES.txt
  - README.rst

- Add section at top of `docs/changelog.rst` with details of what changed (audience: pypubsub developers)
- Update `src/pubsub/RELEASE_NOTES.txt` (audience: pypubsub end-users) to have high-level summary
  of changes for this release, handling incompatibilities, etc
- Update the setup.py classifiers (such as adding a new version of Python supported)
- In docs folder:

  - Update index.rst and docs/installation.rst
  - Regenerate HTML docs via `make`, confirm ok (no warnings etc)

Persist to server:

- Commit and push to remote master repository
- Confirm that travis CI all pass

Distribute:

- Clean out the `dist/` folder
- Generate the source and wheel distributions: `python setup.py bdist_wheel sdist`
- Upload to PyPI: `twine upload dist/\*`
- Verify new release info and links on https://pypi.python.org
- Create new branch (tag) in github
- Verify documentation updated on pypubsub.readthedocs.io
- Confirm installation will work: attempt to install locally via PyPI, then import
  from Python shell and verify version

Py2Exe and cx_Freeze
--------------------

For packaging py2exe or cx_Freeze, see (possibly out of date):

.. toctree::

   py2exe.rst


text:
@implementation FKFlickrGalleriesEditPhoto

- (BOOL) needsLogin {
    return YES;
}

- (BOOL) needsSigning {
    return YES;
}

- (FKPermission) requiredPerms {
    return 1;
}

- (NSString *) name {
    return @"flickr.galleries.editPhoto";
}

- (BOOL) isValid:(NSError **)error {
    BOOL valid = YES;
	NSMutableString *errorDescription = [[NSMutableString alloc] initWithString:@"You are missing required params: "];
	if(!self.gallery_id) {
		valid = NO;
		[errorDescription appendString:@"'gallery_id', "];
	}
	if(!self.photo_id) {
		valid = NO;
		[errorDescription appendString:@"'photo_id', "];
	}
	if(!self.comment) {
		valid = NO;
		[errorDescription appendString:@"'comment', "];
	}

	if(error != NULL) {
		if(!valid) {
			NSDictionary *userInfo = @{NSLocalizedDescriptionKey: errorDescription};
			*error = [NSError errorWithDomain:FKFlickrKitErrorDomain code:FKErrorInvalidArgs userInfo:userInfo];
		}
	}
    return valid;
}

- (NSDictionary *) args {
    NSMutableDictionary *args = [NSMutableDictionary dictionary];
	if(self.gallery_id) {
		[args setValue:self.gallery_id forKey:@"gallery_id"];
	}
	if(self.photo_id) {
		[args setValue:self.photo_id forKey:@"photo_id"];
	}
	if(self.comment) {
		[args setValue:self.comment forKey:@"comment"];
	}

    return [args copy];
}

- (NSString *) descriptionForError:(NSInteger)error {
    switch(error) {
		case FKFlickrGalleriesEditPhotoError_InvalidGalleryID:
			return @"Invalid gallery ID";
		case FKFlickrGalleriesEditPhotoError_SSLIsRequired:
			return @"SSL is required";
		case FKFlickrGalleriesEditPhotoError_InvalidSignature:
			return @"Invalid signature";
		case FKFlickrGalleriesEditPhotoError_MissingSignature:
			return @"Missing signature";
		case FKFlickrGalleriesEditPhotoError_LoginFailedOrInvalidAuthToken:
			return @"Login failed / Invalid auth token";
		case FKFlickrGalleriesEditPhotoError_UserNotLoggedInOrInsufficientPermissions:
			return @"User not logged in / Insufficient permissions";
		case FKFlickrGalleriesEditPhotoError_InvalidAPIKey:
			return @"Invalid API Key";
		case FKFlickrGalleriesEditPhotoError_ServiceCurrentlyUnavailable:
			return @"Service currently unavailable";
		case FKFlickrGalleriesEditPhotoError_WriteOperationFailed:
			return @"Write operation failed";
		case FKFlickrGalleriesEditPhotoError_FormatXXXNotFound:
			return @"Format \"xxx\" not found";
		case FKFlickrGalleriesEditPhotoError_MethodXXXNotFound:
			return @"Method \"xxx\" not found";
		case FKFlickrGalleriesEditPhotoError_InvalidSOAPEnvelope:
			return @"Invalid SOAP envelope";
		case FKFlickrGalleriesEditPhotoError_InvalidXMLRPCMethodCall:
			return @"Invalid XML-RPC Method Call";
		case FKFlickrGalleriesEditPhotoError_BadURLFound:
			return @"Bad URL found";

		default:
			return @"Unknown error code";
    }
}

@end


text:
package com.syshuman.kadir.haircolor3.dagger.modules;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.syshuman.kadir.haircolor3.model.BluetoothLeUart;
import com.syshuman.kadir.haircolor3.model.RestServer;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

/**
 * Created by kerturkx on 2017-09-01.
 */

@Module(includes = ContextModule.class)
public class HC3Module {

    @Provides
    public BluetoothLeUart getBluetoothLeUart(Context context) {
        return new BluetoothLeUart(context);
    }

    @Provides
    public RestServer getRestServer(Context context) {
        return new RestServer(context);
    }

    @Provides
    public SharedPreferences getSharedPreferences(Context context) {
        return  PreferenceManager.getDefaultSharedPreferences(context);
    }

}


text:
import path from 'path';
import feathers from 'feathers';
import rest from 'feathers-rest';
import bodyParser from 'body-parser';
import Sequelize from 'sequelize';
import service from '../lib';

const sequelize = new Sequelize('sequelize', '', '', {
  dialect: 'sqlite',
  storage: path.join(__dirname, 'db.sqlite'),
  logging: false
});
const Todo = sequelize.define('todo', {
  text: {
    type: Sequelize.STRING,
    allowNull: false
  },
  complete: {
    type: Sequelize.BOOLEAN,
    defaultValue: false
  }
}, {
  freezeTableName: true
});

// Removes all database content
Todo.sync({ force: true });

// Create a feathers instance.
var app = feathers()
  // Enable REST services
  .configure(rest())
  // Turn on JSON parser for REST services
  .use(bodyParser.json())
  // Turn on URL-encoded parser for REST services
  .use(bodyParser.urlencoded({ extended: true }));

// Create an in-memory Feathers service with a default page size of 2 items
// and a maximum size of 4
app.use('/todos', service({
  Model: Todo,
  paginate: {
    default: 2,
    max: 4
  }
}));

// A basic error handler, just like Express
app.use(function (error, req, res, next) {
  res.json(error);
});

// Start the server
export default app.listen(3030);

console.log('Feathers Todo sequelize service running on 127.0.0.1:3030');


text:
module Google
  module Bigquery
    module Data
      # A class to manage data for CsvOptions for table.
      class TableCsvOptions
        include Comparable

        attr_reader :allow_jagged_rows
        attr_reader :allow_quoted_newlines
        attr_reader :encoding
        attr_reader :field_delimiter
        attr_reader :quote
        attr_reader :skip_leading_rows

        def to_json(_arg = nil)
          {
            'allowJaggedRows' => allow_jagged_rows,
            'allowQuotedNewlines' => allow_quoted_newlines,
            'encoding' => encoding,
            'fieldDelimiter' => field_delimiter,
            'quote' => quote,
            'skipLeadingRows' => skip_leading_rows
          }.reject { |_k, v| v.nil? }.to_json
        end

        def to_s
          {
            allow_jagged_rows: allow_jagged_rows.to_s,
            allow_quoted_newlines: allow_quoted_newlines.to_s,
            encoding: encoding.to_s,
            field_delimiter: field_delimiter.to_s,
            quote: quote.to_s,
            skip_leading_rows: skip_leading_rows.to_s
          }.map { |k, v| "#{k}: #{v}" }.join(', ')
        end

        def ==(other)
          return false unless other.is_a? TableCsvOptions
          compare_fields(other).each do |compare|
            next if compare[:self].nil? || compare[:other].nil?
            return false if compare[:self] != compare[:other]
          end
          true
        end

        def <=>(other)
          return false unless other.is_a? TableCsvOptions
          compare_fields(other).each do |compare|
            next if compare[:self].nil? || compare[:other].nil?
            result = compare[:self] <=> compare[:other]
            return result unless result.zero?
          end
          0
        end

        def inspect
          to_json
        end

        private

        def compare_fields(other)
          [
            { self: allow_jagged_rows, other: other.allow_jagged_rows },
            { self: allow_quoted_newlines, other: other.allow_quoted_newlines },
            { self: encoding, other: other.encoding },
            { self: field_delimiter, other: other.field_delimiter },
            { self: quote, other: other.quote },
            { self: skip_leading_rows, other: other.skip_leading_rows }
          ]
        end
      end

      # Manages a TableCsvOptions nested object
      # Data is coming from the GCP API
      class TableCsvOptionsApi < TableCsvOptions
        def initialize(args)
          @allow_jagged_rows =
            Google::Bigquery::Property::Boolean.api_parse(args['allowJaggedRows'])
          @allow_quoted_newlines =
            Google::Bigquery::Property::Boolean.api_parse(args['allowQuotedNewlines'])
          @encoding = Google::Bigquery::Property::Enum.api_parse(args['encoding'])
          @field_delimiter = Google::Bigquery::Property::String.api_parse(args['fieldDelimiter'])
          @quote = Google::Bigquery::Property::String.api_parse(args['quote'])
          @skip_leading_rows =
            Google::Bigquery::Property::Integer.api_parse(args['skipLeadingRows'])
        end
      end

      # Manages a TableCsvOptions nested object
      # Data is coming from the Chef catalog
      class TableCsvOptionsCatalog < TableCsvOptions
        def initialize(args)
          @allow_jagged_rows =
            Google::Bigquery::Property::Boolean.catalog_parse(args[:allow_jagged_rows])
          @allow_quoted_newlines =
            Google::Bigquery::Property::Boolean.catalog_parse(args[:allow_quoted_newlines])
          @encoding = Google::Bigquery::Property::Enum.catalog_parse(args[:encoding])
          @field_delimiter =
            Google::Bigquery::Property::String.catalog_parse(args[:field_delimiter])
          @quote = Google::Bigquery::Property::String.catalog_parse(args[:quote])
          @skip_leading_rows =
            Google::Bigquery::Property::Integer.catalog_parse(args[:skip_leading_rows])
        end
      end
    end

    module Property
      # A class to manage input to CsvOptions for table.
      class TableCsvOptions
        def self.coerce
          ->(x) { ::Google::Bigquery::Property::TableCsvOptions.catalog_parse(x) }
        end

        # Used for parsing Chef catalog
        def self.catalog_parse(value)
          return if value.nil?
          return value if value.is_a? Data::TableCsvOptions
          Data::TableCsvOptionsCatalog.new(value)
        end

        # Used for parsing GCP API responses
        def self.api_parse(value)
          return if value.nil?
          return value if value.is_a? Data::TableCsvOptions
          Data::TableCsvOptionsApi.new(value)
        end
      end
    end
  end
end


text:
This provider is used to configure the behavior of somes directives and debug stuff.

### debugInfoEnabled

You should always enable it on development and disable it on production.

**Description:**

It can helps to debug the DOM by adding some stuff in it like:

- `ng-binding`, `ng-scope` and `ng-isolated-scope` CSS class
- `$binding` data property containing an array of the binding expressions
- `ngBind` and `ngBindHtml` attributes
- `ng-if` comments

Obviously, this option will slow down the application and it is useless in production.
So, **disable** it !

### Example

```
$compileProvider.debugInfoEnabled(false);
```

### Bonus

If you want to debug easily a production which have this option disable,
You can enter `angular.reloadWithDebugInfo();` in your browser console to enable the debug.

### Want more ?

[See the official documentation](https://docs.angularjs.org/api/ng/provider/$compileProvider)


text:
/**
 * @author Mihai Şucan
 * @fileOverview This script allows the user to create a new image to edit
 * inside PaintWeb, directly from TinyMCE.
 */

tinyMCEPopup.requireLangPack();

tinyMCEPopup.onInit.add(function() {
  var newImageForm = document.getElementById('newimageform'),
      imgWidth     = document.getElementById('imgWidth'),
      imgHeight    = document.getElementById('imgHeight'),
      imgBgrColor  = document.getElementById('imgBgrColor'),
      imgTitle     = document.getElementById('imgTitle'),
      altText      = document.getElementById('altText'),
      btnCancel    = document.getElementById('cancel');

  newImageForm.onsubmit = function (ev) {
    var fn = tinyMCEPopup.getWindowArg('newImageFn');

    if (fn) {
      fn(imgWidth.value, imgHeight.value, imgBgrColor.value, altText.value,
        imgTitle.value);
    }

    tinyMCEPopup.close();
  };

  imgBgrColor.parentNode.lastChild.innerHTML
    = ' ' + getColorPickerHTML('imgBgrColor_pick',
    'imgBgrColor');

  imgBgrColor.onchange = function () { updateColor('imgBgrColor_pick',
      'imgBgrColor'); };

  updateColor('imgBgrColor_pick', 'imgBgrColor');

  btnCancel.onclick = function () { tinyMCEPopup.close(); };
});

// vim:set spell spl=en fo=wan1croqlt tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:


text:
.AgendaCardComposer-send {
  text-align: right;
}


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

    <tab name="Setting">
        <!--
          * The WLD will launch repeatly by this period value.
          * The unit of time is millisecond. (ms)
        -->
        <item name="DetectPeriod" value="1800000" />
        <!--
          * In order to get CPU usage of the specific wakelock,
          * The WLD will sleep and wait until time's up.
          * The unit of time is millisecond. (ms)
        -->
        <item name="SleepTime" value="300000" />
    </tab>

    <tab name="Criteria">
        <!--
          * The wakelock would be a candidate of abnormal wakelock
          * if it is held for more than this time.
          * The unit of time is millisecond. (ms)
        -->
        <item name="HeldTime" value="1800000" />
        <!--
          * The wakelock would be a candidate of abnormal wakelock
          * if its CPU usage is smaller than this percentage.
          * The unit of value is percentage. (%)
        -->
        <item name="CpuUsage" value="1" />
        <!--
          * The wakelock would be a candidate of abnormal wakelock
          * if its throughput is smaller than this value.
          * The unit of value is bytes per second. (bytes/s)
        -->
        <item name="Throughput" value="20480" />
        <!--
          * The package would be a candidate of abnormal package
          * if its CPU usage is greater than this value.
          * The unit of value is percentage. (%)
        -->
        <item name="CCUCpuUsage" value="3" />
        <!--
          * The package would be a candidate of abnormal package
          * if its throughput is greater than this value.
          * The unit of value is bytes per second. (bytes/s)
        -->
        <item name="CCUThroughput" value="20480" />
        <!--
          * The candidate will be skipped if the package importance
          * level is smaller than this given value.
          * More detail for value to see "ActivityManager.RunningAppProcessInfo".
        -->
        <item name="CCUImportance" value="300" />
    </tab>

    <tab name="IgnoreList">
        <!--
          * All abnormal wakelocks would be released if white list
          * is disable. The abnormal wakelock in white list would be
          * released if white list is enable.
        -->
        <items name="WhiteList" enable="false">
            <item name="audio.core.uap.WakeLockUtil" />
        </items>

        <!--
          * The abnormal wakelock would be skipped if black list is
          * enable and it is in.
          * category: package, process, wakelock
          * operation: equal, contain
        -->
        <items name="BlackList" enable="true">
            <item name="com.htc" category="package" operation="contain" />
            <item name="com.htc" category="process" operation="contain" />
            <item name="android" category="package" operation="equal" />
        </items>
    </tab>

</WldConfig>


text:
var ctrl = function ($scope, $state, accountService) {

  accountService.create().then(
    function() {
      $state.go('addOrEditTransaction');
    }, function(error) {
      console.error(error);
    });

};

ctrl.$inject = ['$scope', '$state', 'accountService'];

export default {
  name: 'AddAccountCtrl',
  fn: ctrl
};


text: java -jar target\org.reldb*.jar < test01.sli


text:
module ContentControl
  class PageContent < ActiveRecord::Base
    attr_accessible :page_content_content, :page_content_handle

    has_and_belongs_to_many :pages, :join_table => "content_control_page_page_contents"
  end
end


text:
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

import java.io.IOException;

/**
 * An exception thrown when a DNS message is invalid.
 *
 * @author Brian Wellington
 */
public class WireParseException extends IOException {

  public WireParseException() {
    super();
  }

  public WireParseException(String s) {
    super(s);
  }

  public WireParseException(String s, Throwable cause) {
    super(s);
    initCause(cause);
  }
}