text:
CGFloat const WPTableViewFixedWidth = 600;

@implementation WPTableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setClipsToBounds:YES];
    }
    return self;
}

- (void)setFrame:(CGRect)frame {
    CGFloat width = self.superview.frame.size.width;
    // On iPad, add a margin around tables
    if (IS_IPAD && width > WPTableViewFixedWidth) {
        CGFloat x = (width - WPTableViewFixedWidth) / 2;
        // If origin.x is not equal to x we add the value.
        // This is a semi-fix / work around for an issue positioning cells on
        // iOS 8 when editing a table view and the delete button is visible.
        if (x != frame.origin.x) {
            frame.origin.x += x;
        } else {
            frame.origin.x = x;
        }
        frame.size.width = WPTableViewFixedWidth;
    }
    [super setFrame:frame];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    // Need to set the origin again on iPad (for margins)
    CGFloat width = self.superview.frame.size.width;
    if (IS_IPAD && width > WPTableViewFixedWidth) {
        CGRect frame = self.frame;
        frame.origin.x = (width - WPTableViewFixedWidth) / 2;
        self.frame = frame;
    }
}

@end


text:
package com.happydroids.droidtowers.pipeline;

import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.GdxNativesLoader;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.happydroids.droidtowers.utils.PNG;
import com.happydroids.error.ErrorUtil;

import java.io.IOException;

public class GenerateAssetManagerFileList {
  private static FileHandle assetsDir = new FileHandle("assets/");
  private static AssetList managedFiles = new AssetList();

  public static void main(String[] args) {
    GdxNativesLoader.load();

    preloadDirectory("swatches/", ".png", Texture.class);

    preloadFile(assetsDir.child("backgrounds/splash1.txt"), TextureAtlas.class);
    preloadFile(assetsDir.child("backgrounds/splash2.txt"), TextureAtlas.class);
    preloadFile(assetsDir.child("backgrounds/cityscape-middle.png"), Texture.class);
    preloadFile(assetsDir.child("happydroid.txt"), TextureAtlas.class);
    preloadFile(assetsDir.child("droid-santa-hat.png"), Texture.class);

    preloadFile(assetsDir.child("default-skin.json"), Skin.class);
    preloadFile(assetsDir.child("backgrounds/clouds.txt"), TextureAtlas.class);
    preloadFile(assetsDir.child("hud/skin.txt"), TextureAtlas.class);
    preloadFile(assetsDir.child("hud/menus.txt"), TextureAtlas.class);
    preloadFile(assetsDir.child("hud/buttons.txt"), TextureAtlas.class);
    preloadFile(assetsDir.child("hud/heyzap-checkin.txt"), TextureAtlas.class);
    preloadFile(assetsDir.child("hud/window-bg.png"), Texture.class);
    preloadFile(assetsDir.child("hud/dialog-bg.png"), Texture.class);

    addDirectoryToAssetManager("backgrounds/", ".txt", TextureAtlas.class);
    addDirectoryToAssetManager("designer/housing/", ".txt", TextureAtlas.class);
    addDirectoryToAssetManager("movies/", ".txt", TextureAtlas.class);
    addDirectoryToAssetManager("backgrounds/", ".png", Texture.class);
    addDirectoryToAssetManager("hud/rating-bars/", ".png", Texture.class);
    addDirectoryToAssetManager("hud/", ".txt", TextureAtlas.class);
    addDirectoryToAssetManager("rooms/", ".txt", TextureAtlas.class);

    addFileEntry(assetsDir.child("characters.txt"), TextureAtlas.class);
    addFileEntry(assetsDir.child("transport.txt"), TextureAtlas.class);
    addFileEntry(assetsDir.child("rain-drop.png"), Texture.class);
    addFileEntry(assetsDir.child("snow.png"), Texture.class);
    addFileEntry(assetsDir.child("decals.png"), Texture.class);
    addFileEntry(assetsDir.child("tower-sign.png"), Texture.class);
    addFileEntry(assetsDir.child("tower-sign-poll.png"), Texture.class);

    for (FileHandle file : assetsDir.child("sound/").child("music/").list()) {
      managedFiles.addMusic(cleanFilename(file.path()));
    }

    try {
      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      new FileHandle("assets/assets.json").writeString(mapper.writeValueAsString(managedFiles), false);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private static void makeSwatch(FileHandle swatchesDir, String swatchFilename, Color color) {
    FileHandle swatchFile = swatchesDir.child(swatchFilename);
    if (swatchFile.exists()) {
      return;
    }

    try {
      Pixmap pixmap = new Pixmap(2, 2, Pixmap.Format.RGB888);
      pixmap.setColor(color);
      pixmap.fill();

      byte[] bytes = PNG.toPNG(pixmap);
      swatchFile.writeBytes(bytes, false);
    } catch (IOException e) {
      ErrorUtil.rethrowError(e);
    }
  }

  private static void preloadDirectory(String folder, String suffix, Class clazz) {
    for (FileHandle child : assetsDir.child(folder).list(suffix)) {
      preloadFile(child, clazz);
    }
  }

  private static void preloadFile(FileHandle child, Class clazz) {
    if (!verifyFile(child)) {
      managedFiles.preload(cleanFilename(child.path()), checkForHDVersion(child), clazz);
    }
  }

  private static void addDirectoryToAssetManager(String folder, String suffix, Class clazz) {
    for (FileHandle child : assetsDir.child(folder).list(suffix)) {
      addFileEntry(child, clazz);
    }
  }

  private static void addFileEntry(FileHandle child, Class clazz) {
    if (!verifyFile(child)) {
      managedFiles.normal(cleanFilename(child.path()), checkForHDVersion(child), clazz);
    }
  }

  private static boolean verifyFile(FileHandle child) {
    if (!child.exists()) {
      throw new RuntimeException("File not found: " + child.path());
    } else if (child.name().contains("-hd")) {
      System.out.println("Skipping HD asset: " + child.path());
      return true;
    }
    return false;
  }

  public static String checkForHDVersion(FileHandle fileHandle) {
    String hdpiFileName = fileHandle.parent() + "/" + fileHandle.nameWithoutExtension() + "-hd." + fileHandle.extension();
    if (hdpiFileName.startsWith("/")) {
      hdpiFileName = hdpiFileName.substring(1);
    }

    if (new FileHandle(hdpiFileName).exists()) {
      return cleanFilename(hdpiFileName);
    }

    return null;
  }

  private static String cleanFilename(String fileName) {
    return fileName.replace("assets/", "");
  }
}

redpajama_set_name: RedPajamaGithub


text:
@interface UdeskPhotographyHelper () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, copy) DidFinishTakeMediaCompledBlock didFinishTakeMediaCompled;
@property (nonatomic, copy) DidFinishTakeMediaGIFCompledBlock didFinishTakeMediaGIFCompled;
@property (nonatomic, copy) DidFinishTakeMediaVideoCompledBlock didFinishTakeMediaVideoCompled;

@end

@implementation UdeskPhotographyHelper

- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)dealloc {
    self.didFinishTakeMediaCompled = nil;
}

- (void)showImagePickerControllerSourceType:(UIImagePickerControllerSourceType)sourceType
                           onViewController:(UIViewController *)viewController
                                hiddenVideo:(BOOL)hiddenVideo
                                    compled:(DidFinishTakeMediaCompledBlock)compled
                                 compledGif:(DidFinishTakeMediaGIFCompledBlock)compledGif
                               compledVideo:(DidFinishTakeMediaVideoCompledBlock)compledVideo {

    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        compled(nil);
        return;
    }
    self.didFinishTakeMediaCompled = [compled copy];
    self.didFinishTakeMediaGIFCompled = [compledGif copy];
    self.didFinishTakeMediaVideoCompled = [compledVideo copy];

    //兼容ipad打不开相册问题,使用队列延迟
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{

        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];

        NSString *movieType = (NSString *)kUTTypeMovie;
        NSString *imageType = (NSString *)kUTTypeImage;
        NSArray *arrMediaTypes=[NSArray arrayWithObjects:imageType,movieType,nil];
        if (hiddenVideo) {
            arrMediaTypes = [NSArray arrayWithObjects:imageType,nil];
        }
        [imagePickerController setMediaTypes: arrMediaTypes];

        imagePickerController.editing = YES;
        imagePickerController.delegate = self;
        imagePickerController.sourceType = sourceType;
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;

        if ([UdeskSDKConfig sharedConfig].sdkStyle.albumCancelColor) {
            imagePickerController.navigationBar.tintColor = [UdeskSDKConfig sharedConfig].sdkStyle.albumCancelColor;
        }

        [viewController presentViewController:imagePickerController animated:YES completion:NULL];
    }];
}

- (void)dismissPickerViewController:(UIImagePickerController *)picker {

    @udWeakify(self);
    [picker dismissViewControllerAnimated:YES completion:^{
        @udStrongify(self);
        self.didFinishTakeMediaCompled = nil;
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    if (refURL) {

        ALAssetsLibrary* assetLibrary = [[ALAssetsLibrary alloc] init];
        @udWeakify(self);
        void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *) = ^(ALAsset *asset) {

            @udStrongify(self);
            if (asset != nil) {

                ALAssetRepresentation *rep = [asset defaultRepresentation];
                NSString *type = info[UIImagePickerControllerMediaType];
                if ([type isEqualToString:(NSString *)kUTTypeMovie]) {

                    NSString *videoPath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
                    NSData *videoData = [NSData dataWithContentsOfFile:videoPath];

                    if (self.didFinishTakeMediaVideoCompled) {
                        self.didFinishTakeMediaVideoCompled(videoData,[rep filename]);
                    }
                }
                else {

                    Byte *imageBuffer = (Byte*)malloc(rep.size);
                    NSUInteger bufferSize = [rep getBytes:imageBuffer fromOffset:0.0 length:rep.size error:nil];
                    NSData *imageData = [NSData dataWithBytesNoCopy:imageBuffer length:bufferSize freeWhenDone:YES];

                    NSString *type = [self contentTypeForImageData:imageData];

                    if ([type isEqualToString:@"gif"]) {

                        if (self.didFinishTakeMediaGIFCompled) {
                            self.didFinishTakeMediaGIFCompled(imageData);
                        }
                    }
                    else {

                        if (self.didFinishTakeMediaCompled) {
                            self.didFinishTakeMediaCompled(info[UIImagePickerControllerOriginalImage]);
                        }
                    }
                }
            }
        };

        [assetLibrary assetForURL:refURL
                      resultBlock:ALAssetsLibraryAssetForURLResultBlock
                     failureBlock:^(NSError *error){
                     }];

    }
    else {

        NSString *type = info[UIImagePickerControllerMediaType];
        if ([type isEqualToString:(NSString *)kUTTypeMovie]) {

            NSString *videoPath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
            NSData *videoData = [NSData dataWithContentsOfFile:videoPath];

            if (self.didFinishTakeMediaVideoCompled) {
                self.didFinishTakeMediaVideoCompled(videoData,[NSString stringWithFormat:@"%@.mp4",[UdeskTools soleString]]);
            }
        }
        else {

            if (self.didFinishTakeMediaCompled) {
                self.didFinishTakeMediaCompled(info[UIImagePickerControllerOriginalImage]);
            }
        }
    }

    [self dismissPickerViewController:picker];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissPickerViewController:picker];
}

//通过图片Data数据第一个字节 来获取图片扩展名
- (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52:
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}

@end


text:
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity"
    >

    <item android:id="@+id/action_search"
        android:title="@string/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView" />

    <item android:id="@+id/action_debug_prefs"
        android:title="Debug Preferences"
        app:showAsAction="never" />

</menu>


text:
package org.talend.sdk.component.api;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target({ FIELD, PARAMETER })
@Retention(RUNTIME)
public @interface DecryptedServer {

    /**
     * @return the settings.xml serverId to match.
     */
    String value();

    /**
     * @return the list of conditions to meet to activate this decrypting.
     */
    Conditions conditions() default @Conditions({ @Condition(forSystemProperty = "talend.junit.http.passthrough"),
            @Condition(forSystemProperty = "talend.maven.decrypter.active") });

    /**
     * @return true to always try to read the server whatever the condition state
     * and fallback on the mock values if not found and conditions are met.
     */
    boolean alwaysTryLookup() default true;

    /**
     * @return the username when forSystemProperty test fails.
     */
    String defaultUsername() default "username";

    /**
     * @return the username when forSystemProperty test fails.
     */
    String defaultPassword() default "password";

    @Target(ANNOTATION_TYPE)
    @Retention(RUNTIME)
    @interface Conditions {

        /**
         * @return the list of conditions to meet to use an actual server.
         */
        Condition[] value();

        /**
         * @return the way to combine the conditions.
         */
        Combination combination() default Combination.OR;
    }

    enum Combination {
        AND,
        OR
    }

    @Target(ANNOTATION_TYPE)
    @Retention(RUNTIME)
    @interface Condition {

        /**
         * @return a system property name to use for the test.
         */
        String forSystemProperty();

        /**
         * @return the expected system property to activate the condition.
         */
        String expectedValue() default "true";

        /**
         * @return true if the system property can be null.
         */
        boolean supportsNull() default false;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SpentBook.Domain
{
    public interface IRepository<TEntity>
    {
        IEnumerable<TEntity> GetAll();

        IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = ""
        );

        IQueryable<TEntity> AsQueryable();

        TEntity GetById(Guid id);
        void Insert(TEntity entity);
        void Delete(Guid id);
        void Delete(TEntity entityToDelete);
        void Update(TEntity entityToUpdate);
    }
}


text:
import os

class PidFile:
    """Concrete class that represents a PID file."""

    def __init__(self, pid_path):
        self.pid_path = pid_path
        self.exists = False

    def read(self):
        """Read PID file."""
        with open(self.pid_path) as pid_file:
            return int(pid_file.read())

    def write(self):
        """Write PID file."""
        if self.exists or not self.pid_path:
            return
        with open(self.pid_path, 'w') as pid_file:
            pid_file.write(str(os.getpid()))
            self.exists = True

    def remove(self):
        """Remove PID file."""
        if not self.exists:
            return
        try:
            os.unlink(self.pid_path)
        finally:
            self.exists = False

    def __enter__(self):
        self.write()

    def __exit__(self, *args):
        self.remove()


text:
<!DOCTYPE html >

          <title>sparkpipe - sparkpipe-core 1.0.0 API - software.uncharted.sparkpipe</title>
          <meta name="description" content="sparkpipe - sparkpipe - core 1.0.0 API - software.uncharted.sparkpipe" />
          <meta name="keywords" content="sparkpipe sparkpipe core 1.0.0 API software.uncharted.sparkpipe" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

software.uncharted

sparkpipe

        package

        sparkpipe

This package contains a pipeline implementation for Spark
See the README or software.uncharted.sparkpipe.Pipe for more information.

          Linear Supertypes

AnyRef, Any

<input id="mbrsel-input" type="text" accesskey="/" />

              Ordering

Alphabetic

By Inheritance

                Inherited

sparkpipe

AnyRef

Any

Hide All

Show All

            Visibility

Public

All

Type Members

        class

        Pipe[O] extends AnyRef

An immutable chain of sequential operations which
can be extended, forming a new Pipe.

An immutable chain of sequential operations which
can be extended, forming a new Pipe. It can also be
run, producing an output value which is cached after
the first run.

Value Members

        object

        Pipe

Factory for software.uncharted.sparkpipe.Pipes
from various inputs, such as raw values or other Pipes

        package

        ops

Inherited from AnyRef

Inherited from Any

Ungrouped


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

<TITLE>
org.apache.tools.ant.taskdefs.optional.javacc (Apache Ant API)
</TITLE>

<META NAME="date" CONTENT="2012-02-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

org.apache.tools.ant.taskdefs.optional.javacc

Classes

JavaCC

JJDoc

JJTree


text:
package org.apache.geode.management.internal.cli.help;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;
import org.springframework.shell.core.MethodTarget;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;

import org.apache.geode.management.cli.CliMetaData;
import org.apache.geode.management.internal.cli.GfshParser;
import org.apache.geode.management.internal.cli.i18n.CliStrings;

/**
 *
 *
 * @since GemFire 7.0
 */
public class Helper {

  static final String NAME_NAME = "NAME";
  static final String SYNONYMS_NAME = "SYNONYMS";
  static final String SYNOPSIS_NAME = "SYNOPSIS";
  static final String SYNTAX_NAME = "SYNTAX";
  static final String OPTIONS_NAME = "PARAMETERS";
  static final String IS_AVAILABLE_NAME = "IS AVAILABLE";

  static final String REQUIRED_SUB_NAME = "Required: ";
  static final String SYNONYMS_SUB_NAME = "Synonyms: ";
  static final String SPECIFIEDDEFAULTVALUE_SUB_NAME =
      "Default (if the parameter is specified without value): ";
  static final String UNSPECIFIEDDEFAULTVALUE_VALUE_SUB_NAME =
      "Default (if the parameter is not specified): ";

  static final String VALUE_FIELD = "value";
  static final String TRUE_TOKEN = "true";
  static final String FALSE_TOKEN = "false";
  static final String AVAILABLE = "Available";
  static final String NOT_AVAILABLE = "Not Available";

  private final Map<String, Topic> topics = new HashMap<>();
  private final Map<String, Method> commands = new TreeMap<String, Method>();
  private final Map<String, MethodTarget> availabilityIndicators =
      new HashMap<String, MethodTarget>();

  public Helper() {
    initTopic(CliStrings.DEFAULT_TOPIC_GEODE, CliStrings.DEFAULT_TOPIC_GEODE__DESC);
    initTopic(CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_REGION__DESC);
    initTopic(CliStrings.TOPIC_GEODE_WAN, CliStrings.TOPIC_GEODE_WAN__DESC);
    initTopic(CliStrings.TOPIC_GEODE_JMX, CliStrings.TOPIC_GEODE_JMX__DESC);
    initTopic(CliStrings.TOPIC_GEODE_DISKSTORE, CliStrings.TOPIC_GEODE_DISKSTORE__DESC);
    initTopic(CliStrings.TOPIC_GEODE_LOCATOR, CliStrings.TOPIC_GEODE_LOCATOR__DESC);
    initTopic(CliStrings.TOPIC_GEODE_SERVER, CliStrings.TOPIC_GEODE_SERVER__DESC);
    initTopic(CliStrings.TOPIC_GEODE_MANAGER, CliStrings.TOPIC_GEODE_MANAGER__DESC);
    initTopic(CliStrings.TOPIC_GEODE_STATISTICS, CliStrings.TOPIC_GEODE_STATISTICS__DESC);
    initTopic(CliStrings.TOPIC_GEODE_LIFECYCLE, CliStrings.TOPIC_GEODE_LIFECYCLE__DESC);
    initTopic(CliStrings.TOPIC_GEODE_M_AND_M, CliStrings.TOPIC_GEODE_M_AND_M__DESC);
    initTopic(CliStrings.TOPIC_GEODE_DATA, CliStrings.TOPIC_GEODE_DATA__DESC);
    initTopic(CliStrings.TOPIC_GEODE_CONFIG, CliStrings.TOPIC_GEODE_CONFIG__DESC);
    initTopic(CliStrings.TOPIC_GEODE_FUNCTION, CliStrings.TOPIC_GEODE_FUNCTION__DESC);
    initTopic(CliStrings.TOPIC_GEODE_HELP, CliStrings.TOPIC_GEODE_HELP__DESC);
    initTopic(CliStrings.TOPIC_GEODE_DEBUG_UTIL, CliStrings.TOPIC_GEODE_DEBUG_UTIL__DESC);
    initTopic(CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GFSH__DESC);
    initTopic(CliStrings.TOPIC_LOGS, CliStrings.TOPIC_LOGS__DESC);
    initTopic(CliStrings.TOPIC_CLIENT, CliStrings.TOPIC_CLIENT__DESC);
  }

  private void initTopic(String topic, String desc) {
    topics.put(topic, new Topic(topic, desc));
  }

  public void addCommand(CliCommand command, Method commandMethod) {
    // put all the command synonyms in the command map
    Arrays.stream(command.value()).forEach(cmd -> {
      commands.put(cmd, commandMethod);
    });

    // resolve the hint message for each method
    CliMetaData cliMetaData = commandMethod.getDeclaredAnnotation(CliMetaData.class);
    if (cliMetaData == null)
      return;
    String[] related = cliMetaData.relatedTopic();

    // for hint message, we only need to show the first synonym
    String commandString = command.value()[0];
    if (related == null) {
      return;
    }
    Arrays.stream(related).forEach(topic -> {
      Topic foundTopic = topics.get(topic);
      if (foundTopic == null) {
        throw new IllegalArgumentException("No such topic found in the initial map: " + topic);
      }
      foundTopic.addRelatedCommand(commandString, command.help());
    });
  }

  public void addAvailabilityIndicator(CliAvailabilityIndicator availability, MethodTarget target) {
    Arrays.stream(availability.value()).forEach(command -> {
      availabilityIndicators.put(command, target);
    });
  }

  /**
   * get help string for a specific command, or a brief description of all the commands if buffer is
   * null or empty
   */
  public String getHelp(String buffer, int terminalWidth) {
    if (StringUtils.isBlank(buffer)) {
      return getHelp().toString(terminalWidth);
    }

    Method method = commands.get(buffer);
    if (method == null) {
      return "no help exists for this command.";
    }

    HelpBlock helpBlock = getHelp(method.getDeclaredAnnotation(CliCommand.class),
        method.getParameterAnnotations(), method.getParameterTypes());
    return helpBlock.toString(terminalWidth);
  }

  public String getHint(String buffer) {
    StringBuilder builder = new StringBuilder();
    // if no topic is provided, return a list of topics
    if (StringUtils.isBlank(buffer)) {
      builder.append(CliStrings.HINT__MSG__TOPICS_AVAILABLE).append(GfshParser.LINE_SEPARATOR)
          .append(GfshParser.LINE_SEPARATOR);

      List<String> sortedTopics = new ArrayList<>(topics.keySet());
      Collections.sort(sortedTopics);
      sortedTopics.stream()
          .forEachOrdered(topic -> builder.append(topic).append(GfshParser.LINE_SEPARATOR));
      return builder.toString();
    }

    Topic topic = topics.get(buffer);
    if (topic == null) {
      return CliStrings.format(CliStrings.HINT__MSG__UNKNOWN_TOPIC, buffer);
    }

    builder.append(topic.desc).append(GfshParser.LINE_SEPARATOR).append(GfshParser.LINE_SEPARATOR);
    Collections.sort(topic.relatedCommands);
    topic.relatedCommands.stream().forEachOrdered(command -> builder.append(command.command)
        .append(": ").append(command.desc).append(GfshParser.LINE_SEPARATOR));
    return builder.toString();
  }

  public Set<String> getTopicNames() {
    return topics.keySet();
  }

  boolean isAvailable(String command) {
    MethodTarget target = availabilityIndicators.get(command);
    if (target == null) {
      return true;
    }
    try {
      return (Boolean) target.getMethod().invoke(target.getTarget());
    } catch (Exception e) {
      return false;
    }
  }

  public boolean hasAvailabilityIndicator(String command) {
    return availabilityIndicators.get(command) != null;
  }

  HelpBlock getHelp() {
    HelpBlock root = new HelpBlock();
    commands.keySet().stream().sorted().map(commands::get).forEach(method -> {
      root.addChild(getHelp(method.getDeclaredAnnotation(CliCommand.class), null, null));
    });
    return root;
  }

  /**
   * returns a short description and help string of the command if annotations is null or returns a
   * details description of the command with the syntax and parameter description
   */
  HelpBlock getHelp(CliCommand cliCommand, Annotation[][] annotations, Class<?>[] parameterTypes) {
    String commandName = cliCommand.value()[0];
    boolean isAvailable = isAvailable(commandName);

    if (annotations == null && parameterTypes == null) {
      String available = isAvailable ? AVAILABLE : NOT_AVAILABLE;
      HelpBlock help = new HelpBlock(commandName + " (" + available + ")");
      help.addChild(new HelpBlock(cliCommand.help()));
      return help;
    }

    HelpBlock root = new HelpBlock();
    // First we will have the block for NAME of the command
    HelpBlock name = new HelpBlock(NAME_NAME);
    name.addChild(new HelpBlock(commandName));
    root.addChild(name);

    // add the availability flag
    HelpBlock availability = new HelpBlock(IS_AVAILABLE_NAME);
    availability.addChild(new HelpBlock(isAvailable + ""));
    root.addChild(availability);

    // Now add synonyms if any
    String[] allNames = cliCommand.value();
    if (allNames.length > 1) {
      HelpBlock synonyms = new HelpBlock(SYNONYMS_NAME);
      for (int i = 1; i < allNames.length; i++) {
        synonyms.addChild(new HelpBlock(allNames[i]));
      }
      root.addChild(synonyms);
    }

    // Now comes the turn to display synopsis if any
    if (StringUtils.isNotBlank(cliCommand.help())) {
      HelpBlock synopsis = new HelpBlock(SYNOPSIS_NAME);
      synopsis.addChild(new HelpBlock(cliCommand.help()));
      root.addChild(synopsis);
    }

    // Now display the syntax for the command
    HelpBlock syntaxBlock = new HelpBlock(SYNTAX_NAME);
    String syntax = getSyntaxString(commandName, annotations, parameterTypes);
    syntaxBlock.addChild(new HelpBlock(syntax));
    root.addChild(syntaxBlock);

    // Detailed description of all the Options
    if (annotations.length > 0) {
      HelpBlock options = new HelpBlock(OPTIONS_NAME);
      for (int i = 0; i < annotations.length; i++) {
        CliOption cliOption = getAnnotation(annotations[i], CliOption.class);
        HelpBlock optionNode = getOptionDetail(cliOption);
        options.addChild(optionNode);
      }
      root.addChild(options);
    }
    return root;
  }

  HelpBlock getOptionDetail(CliOption cliOption) {
    HelpBlock optionNode = new HelpBlock(getPrimaryKey(cliOption));
    String help = cliOption.help();
    optionNode.addChild(new HelpBlock((StringUtils.isNotBlank(help) ? help : "")));
    if (getSynonyms(cliOption).size() > 0) {
      StringBuilder builder = new StringBuilder();
      for (String string : getSynonyms(cliOption)) {
        if (builder.length() > 0) {
          builder.append(",");
        }
        builder.append(string);
      }
      optionNode.addChild(new HelpBlock(SYNONYMS_SUB_NAME + builder.toString()));
    }
    optionNode.addChild(
        new HelpBlock(REQUIRED_SUB_NAME + ((cliOption.mandatory()) ? TRUE_TOKEN : FALSE_TOKEN)));
    if (!isNullOrBlank(cliOption.specifiedDefaultValue())) {
      optionNode.addChild(
          new HelpBlock(SPECIFIEDDEFAULTVALUE_SUB_NAME + cliOption.specifiedDefaultValue()));
    }
    if (!isNullOrBlank(cliOption.unspecifiedDefaultValue())) {
      optionNode.addChild(new HelpBlock(
          UNSPECIFIEDDEFAULTVALUE_VALUE_SUB_NAME + cliOption.unspecifiedDefaultValue()));
    }
    return optionNode;
  }

  private <T> T getAnnotation(Annotation[] annotations, Class<?> klass) {
    for (Annotation annotation : annotations) {
      if (klass.isAssignableFrom(annotation.getClass())) {
        return (T) annotation;
      }
    }
    return null;
  }

  String getSyntaxString(String commandName, Annotation[][] annotations, Class[] parameterTypes) {
    StringBuffer buffer = new StringBuffer();
    buffer.append(commandName);
    for (int i = 0; i < annotations.length; i++) {
      CliOption cliOption = getAnnotation(annotations[i], CliOption.class);
      String optionString = getOptionString(cliOption, parameterTypes[i]);
      if (cliOption.mandatory()) {
        buffer.append(" ").append(optionString);
      } else {
        buffer.append(" [").append(optionString).append("]");
      }
    }
    return buffer.toString();
  }

  /**
   * this builds the following format of strings: key (as in sh and help) --key=value --key(=value)?
   * (if has specifiedDefaultValue) --key=value(,value)* (if the value is a list)
   *
   * @return option string
   */
  private static String getOptionString(CliOption cliOption, Class<?> optionType) {
    String key0 = cliOption.key()[0];
    if ("".equals(key0)) {
      return (cliOption.key()[1]);
    }

    StringBuffer buffer = new StringBuffer();
    buffer.append(GfshParser.LONG_OPTION_SPECIFIER).append(key0);

    boolean hasSpecifiedDefault = !isNullOrBlank(cliOption.specifiedDefaultValue());

    if (hasSpecifiedDefault) {
      buffer.append("(");
    }

    buffer.append(GfshParser.OPTION_VALUE_SPECIFIER).append(VALUE_FIELD);

    if (hasSpecifiedDefault) {
      buffer.append(")?");
    }

    if (isCollectionOrArrayType(optionType)) {
      buffer.append("(").append(",").append(VALUE_FIELD).append(")*");
    }

    return buffer.toString();
  }

  private static boolean isCollectionOrArrayType(Class<?> typeToCheck) {
    return typeToCheck != null
        && (typeToCheck.isArray() || Collection.class.isAssignableFrom(typeToCheck));
  }

  private static String getPrimaryKey(CliOption option) {
    String[] keys = option.key();
    if (keys.length == 0) {
      throw new RuntimeException("Invalid option keys");
    } else if ("".equals(keys[0])) {
      return keys[1];
    } else {
      return keys[0];
    }
  }

  private static List<String> getSynonyms(CliOption option) {
    List<String> synonyms = new ArrayList<>();
    String[] keys = option.key();
    if (keys.length < 2)
      return synonyms;
    // if the primary key is empty (like sh and help command), then there should be no synonyms.
    if ("".equals(keys[0]))
      return synonyms;

    for (int i = 1; i < keys.length; i++) {
      synonyms.add(keys[i]);
    }
    return synonyms;
  }

  private static boolean isNullOrBlank(String value) {
    return StringUtils.isBlank(value) || CliMetaData.ANNOTATION_NULL_VALUE.equals(value);
  }

  public Set<String> getCommands() {
    return commands.keySet();
  }
}


text:
package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JSpinnerCreateDemo extends JFrame {
    public JSpinnerCreateDemo() {
        initializeUI();
    }

    private void initializeUI() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Creating an array of color name that we'll use as the
        // source of our SpinnerListMode.
        String[] colors = new String[] {
            "Red", "Orange", "Yellow", "Green", "Blue", "Purple"
        };
        SpinnerListModel model = new SpinnerListModel(colors);

        // Create a JSpinner instance with a spinner model as the value.
        // This JSpinner will allow us to select a colour name when we
        // press the JButton below.
        final JSpinner spinner = new JSpinner(model);
        getContentPane().add(spinner, BorderLayout.NORTH);

        JButton okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String color = (String) spinner.getValue();
                System.out.println("Color = " + color);
            }
        });
        getContentPane().add(okButton, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JSpinnerCreateDemo().setVisible(true);
            }
        });
    }
}


text:
import supertest from 'supertest';
const newFoo = {
    foo: {
        name: 'Interrupt Fooooooo!',
        myBar: 1
    }
};
const updateFoo = {
    foo: {
        name: 'Updated Interrupt Fooooooo!',
        myBar: 2
    }
};
let FooController;
let tempFoo;

describe('Integration | Interrupt | beforeUpdate', function() {
    before(function(done) {
        Object.keys(require.cache).forEach(k => {
            if (k.indexOf('FooController') !== -1) {
                FooController = require.cache[k].exports;
            }
        });
        if (!FooController) {
            return done(new Error('Could not find FooController!'));
        }
        Foo.create(newFoo.foo).exec((err, record) => {
            if (err) {
                return done(err);
            }
            tempFoo = record;
            done();
        });
    });
    after(function(done) {
        Foo.destroy(tempFoo.id).exec(done);
    });
    afterEach(function() {
        FooController.setServiceInterrupt('beforeUpdate', (req, res, next) => {
            next();
        });
    });

    describe(':: invocation arguments', function() {
        it('should call interrupt with 5 arguments', function(done) {
            FooController.setServiceInterrupt('beforeUpdate', function(req, res, next) {
                expect(arguments.length).to.equal(5);
                next();
            });
            supertest(sails.hooks.http.app)
                .patch(`/foos/${tempFoo.id}`)
                .send(updateFoo)
                .end(done);
        });
        it('should return the contextual request object', function(done) {
            FooController.setServiceInterrupt('beforeUpdate', function(req, res, next) {
                expect(req).to.be.instanceof(Object);
                expect(req.headers).to.be.instanceof(Object);
                expect(req.url).to.be.a('string');
                next();
            });
            supertest(sails.hooks.http.app)
                .patch(`/foos/${tempFoo.id}`)
                .send(updateFoo)
                .end(done);
        });
        it('should return the contextual response object', function(done) {
            FooController.setServiceInterrupt('beforeUpdate', function(req, res, next) {
                expect(res).to.be.instanceof(Object);
                expect(res.locals).to.be.a('object');
                next();
            });
            supertest(sails.hooks.http.app)
                .patch(`/foos/${tempFoo.id}`)
                .send(updateFoo)
                .end(done);
        });
        it('should return a next() function', function(done) {
            FooController.setServiceInterrupt('beforeUpdate', function(req, res, next) {
                expect(next).to.be.a('function');
                next();
            });
            supertest(sails.hooks.http.app)
                .patch(`/foos/${tempFoo.id}`)
                .send(updateFoo)
                .end(done);
        });
        it('should return the parsed model class', function(done) {
            FooController.setServiceInterrupt('beforeUpdate', function(req, res, next, Model) {
                expect(Model.globalId).to.equal('Foo');
                next();
            });
            supertest(sails.hooks.http.app)
                .patch(`/foos/${tempFoo.id}`)
                .send(updateFoo)
                .end(done);
        });
        it('should return only the values to be used for the update', function(done) {
            FooController.setServiceInterrupt('beforeUpdate', function(req, res, next, Model, values) {
                expect(values).to.be.an.instanceof(Object);
                expect(values).to.not.have.property('id');
                expect(values)
                    .to.have.property('name')
                    .that.equals(updateFoo.foo.name);
                next();
            });
            supertest(sails.hooks.http.app)
                .patch(`/foos/${tempFoo.id}`)
                .send(updateFoo)
                .end(done);
        });
    });
});


text:
"use strict";

// uglifyjs table.js -b  --comments all
/**
 * FacilityListCtrl
 * view of engity list
 * save pagination and filter params in session?
 */
//function FacilityListCtrl($scope, $routeParams, $http,  sessionService, entity, common) {
var module = angular.module("maboss.FacilityTableCtrl", []);

module.controller("FacilityTableCtrl", [ "$scope", "$routeParams", "$http", "sessionService", "dataService", "$log", function($scope, $routeParams, $http, sessionService, dataService, $log) {
    //table name
    $scope.table = "facility";
    //primary key
    $scope.pkey = "facility";
    //configuration for datatables

    //var texts_languageid = {msgid:text};

    var _t = function(msgid){

        return "更新时间";

    };

    $scope.columns = [ {
        data: "facility",
        title: "Facility Code",
         "render": function ( data, type, row ) {
                    return  ''+data+'';
                }
    }, {
        data: "texths",
        title: "Facility"
    }, {
        data: "company",
        orderable: false,
        title: "公司",
        name: "company"
    },{
        data: "modifiedon",
        title: _t('modifiedon')
    },

    {
        data: "createdon",
        title: "Created On"
    }, {
        data: "createdby",
        title: "Created By",
        orderable: false,
    } ];
    /*
     call service
    */
    var fetch = function(data, callback) {
        var cols = [];
        var i;
        for (i = 0; i < data.columns.length; i++) {
            cols.push(data.columns[i].data);
        }
        // construct jsonrpc params
        var params = {
            table: $scope.table,
            pkey: $scope.pkey,
            cols: cols,
            orderby: [ parseInt(data.order[0].column) + 1, data.order[0].dir ].join(" "),
            offset: data.start,
            domain: [ [ [ cols[0], "ilike", data.search.value + "%" ] ] ],
            limit: data.length,
            //hardcode
            languageid: "1033"
        };
        //fetch
        dataService.fetch(params).then(function(result) {
            //$log.debug(JSON.stringify(result));
                $log.debug("fetch success", result);
                result.recordsTotal = result.total,
                result.recordsFiltered= result.count

           $log.debug(JSON.stringify(result));
            callback(result);
        }, function(result) {
            $log.error("error", result);
            var rdata = {
                data: []
            };
            callback(rdata);
        });
    };
    /*
    table config
    */
    $("#main_table").dataTable({
        //"processing": true,
        serverSide: true,
        //data:get_data(),
        aaSorting: [ [ 0, "desc" ] ],
        sPaginationType: "bootstrap",
        oLanguage: {
            sSearch: "Search",
            sLengthMenu: "_MENU_"
        },
        ajax: function(data, callback, setting) {
           // $log.debug(JSON.stringify(data));
            fetch(data, callback);
        },
        columns: $scope.columns,
        columnDefs:{
            "render": function ( data, type, row ) {
                    return data +' ('+ row[3]+')';
                },
            }
    });
} ]);


text:
{% include anchor.html edit="true" title="Get database information" hash="database_information" %}

{% highlight js %}
db.info([callback])
{% endhighlight %}

Get information about a database.

#### Example Usage:

{% include code/start.html id="dbinfo" type="callback" %}
{% highlight js %}
db.info(function(err, info) {
  if (err) { return console.log(err); }
  // handle result
});
{% endhighlight %}
{% include code/end.html %}

{% include code/start.html id="dbinfo" type="async" %}
{% highlight js %}
try {
  var result = await db.info();
} catch (err) {
  console.log(err);
}
{% endhighlight %}
{% include code/end.html %}

{% include code/start.html id="dbinfo" type="promise" %}
{% highlight js %}
db.info().then(function (result) {
  // handle result
}).catch(function (err) {
  console.log(err);
});
{% endhighlight %}
{% include code/end.html %}

#### Example Response:
{% highlight js %}
{
  "db_name": "test",
  "doc_count": 4,
  "update_seq": 5
}
{% endhighlight %}

**Response object:**

* `db_name` is the name of the database you gave when you called `new PouchDB()`, and also the unique identifier for the database.
* `doc_count` is the total number of non-deleted documents in the database.
* `update_seq` is the sequence number of the database.  It starts at 0 and gets incremented every time a document is added or modified.

There are also some details you can use for debugging. These are unofficial and may change at any time:

* `adapter`: The name of the adapter being used (idb, leveldb, ...).
* `idb_attachment_format`: (IndexedDB) either `'base64'` or `'binary'`, depending on whether the browser [supports binary blobs](/faq.html#data_types).
* `backend_adapter`: (Node.JS) the backend *DOWN adapter being used (MemDOWN, RiakDOWN, ...).


text:
<nodeTypes xmlns:nt="ht exo://www.jcp.org/jcr/nt/1.0"
           xmlns:mix="ht exo://www.jcp.org/jcr/mix/1.0"
           xmlns:jcr="ht exo://www.jcp.org/jcr/1.0">

  <nodeType name="exo:category" isMixin="false" hasOrderableChildNodes="false">
    <supertypes>
      <supertype>nt:base</supertype>
      <supertype>mix:referenceable</supertype>
    </supertypes>
    <propertyDefinitions>

      <propertyDefinition name="exo:categoryname" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>

    </propertyDefinitions>

  </nodeType>

  <nodeType name="exo:question" isMixin="false" hasOrderableChildNodes="false">
    <supertypes>
      <supertype>nt:base</supertype>
      <supertype>mix:referenceable</supertype>
    </supertypes>
    <propertyDefinitions>

      <propertyDefinition name="exo:title" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>

       <propertyDefinition name="exo:answer" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="true">
        <valueConstraints/>
      </propertyDefinition>

      <propertyDefinition name="exo:correct" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="true">
        <valueConstraints/>
      </propertyDefinition>

       <propertyDefinition name="exo:answered" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="true">
        <valueConstraints/>
      </propertyDefinition>

      <propertyDefinition name="exo:point" requiredType="long" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>

    </propertyDefinitions>

  </nodeType>

  <nodeType name="exo:testing" isMixin="false" hasOrderableChildNodes="false">
    <supertypes>
      <supertype>nt:base</supertype>
      <supertype>mix:referenceable</supertype>
    </supertypes>
    <propertyDefinitions>

      <propertyDefinition name="exo:time" requiredType="long" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>

       <propertyDefinition name="exo:point" requiredType="long" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>

      <propertyDefinition name="exo:note" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>

      <propertyDefinition name="exo:result" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="true">
        <valueConstraints/>
      </propertyDefinition>
    </propertyDefinitions>

  </nodeType>
 <nodeType  name="exo:attachment" isMixin="false" hasOrderableChildNodes="false" primaryItemName="">
      <supertypes>
        <supertype>nt:file</supertype>
      </supertypes>
      <propertyDefinitions>
        <propertyDefinition name="exo:fileName" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
          <valueConstraints/>
        </propertyDefinition>
      </propertyDefinitions>
    </nodeType>

  <nodeType name="exo:session" isMixin="false" hasOrderableChildNodes="false">
    <supertypes>
      <supertype>nt:base</supertype>
    </supertypes>
    <propertyDefinitions>
      <propertyDefinition name="exo:title" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>
      <propertyDefinition name="exo:description" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>
      <propertyDefinition name="exo:catId" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>
      <propertyDefinition name="exo:questId" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="true">
        <valueConstraints/>
      </propertyDefinition>
      <propertyDefinition name="exo:rflink" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>
      <propertyDefinition name="exo:vlink" requiredType="String" autoCreated="false" mandatory="false" onParentVersion="COPY" protected="false" multiple="false">
        <valueConstraints/>
      </propertyDefinition>
    </propertyDefinitions>

  </nodeType>

</nodeTypes>


text:
package org.openspaces.itest.core.space.filter.replication;

import com.j_spaces.core.IJSpace;
import com.j_spaces.core.cluster.IReplicationFilter;
import com.j_spaces.core.cluster.IReplicationFilterEntry;
import com.j_spaces.core.cluster.ReplicationPolicy;
import org.openspaces.core.GigaSpace;
import org.openspaces.core.context.GigaSpaceLateContext;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author kimchy
 */
public class SimpleReplicationFilter implements IReplicationFilter {

    @GigaSpaceLateContext(name = "gigaSpace1")
    GigaSpace gigaSpace1;

    @GigaSpaceLateContext(name = "gigaSpace2")
    GigaSpace gigaSpace2;

    AtomicInteger initCalled = new AtomicInteger();

    AtomicInteger closeCalled = new AtomicInteger();

    boolean processCalled;

    List<ProcessEntry> processEntries = new ArrayList<ProcessEntry>();

    public void init(IJSpace space, String paramUrl, ReplicationPolicy replicationPolicy) {
        initCalled.incrementAndGet();
    }

    public void process(int direction, IReplicationFilterEntry replicationFilterEntry, String remoteSpaceMemberName) {
        ProcessEntry processEntry = new ProcessEntry();
        processEntry.direction = direction;
        processEntry.replicationFilterEntry = replicationFilterEntry;
        processEntry.remoteSpaceMemberName = remoteSpaceMemberName;
        processEntries.add(processEntry);
    }

    public void close() {
        closeCalled.incrementAndGet();
    }

    public static class ProcessEntry {
        int direction;

        IReplicationFilterEntry replicationFilterEntry;

        String remoteSpaceMemberName;
    }
}


text:
#include "compiler/glsl_types.h"
#include "loop_analysis.h"
#include "ir_hierarchical_visitor.h"

static bool is_loop_terminator(ir_if *ir);

static bool all_expression_operands_are_loop_constant(ir_rvalue *,
						      hash_table *);

static ir_rvalue *get_basic_induction_increment(ir_assignment *, hash_table *);

/**
 * Record the fact that the given loop variable was referenced inside the loop.
 *
 * \arg in_assignee is true if the reference was on the LHS of an assignment.
 *
 * \arg in_conditional_code_or_nested_loop is true if the reference occurred
 * inside an if statement or a nested loop.
 *
 * \arg current_assignment is the ir_assignment node that the loop variable is
 * on the LHS of, if any (ignored if \c in_assignee is false).
 */
void
loop_variable::record_reference(bool in_assignee,
                                bool in_conditional_code_or_nested_loop,
                                ir_assignment *current_assignment)
{
   if (in_assignee) {
      assert(current_assignment != NULL);

      if (in_conditional_code_or_nested_loop ||
          current_assignment->condition != NULL) {
         this->conditional_or_nested_assignment = true;
      }

      if (this->first_assignment == NULL) {
         assert(this->num_assignments == 0);

         this->first_assignment = current_assignment;
      }

      this->num_assignments++;
   } else if (this->first_assignment == current_assignment) {
      /* This catches the case where the variable is used in the RHS of an
       * assignment where it is also in the LHS.
       */
      this->read_before_write = true;
   }
}

loop_state::loop_state()
{
   this->ht = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
                                      _mesa_key_pointer_equal);
   this->mem_ctx = ralloc_context(NULL);
   this->loop_found = false;
}

loop_state::~loop_state()
{
   _mesa_hash_table_destroy(this->ht, NULL);
   ralloc_free(this->mem_ctx);
}

loop_variable_state *
loop_state::insert(ir_loop *ir)
{
   loop_variable_state *ls = new(this->mem_ctx) loop_variable_state;

   _mesa_hash_table_insert(this->ht, ir, ls);
   this->loop_found = true;

   return ls;
}

loop_variable_state *
loop_state::get(const ir_loop *ir)
{
   hash_entry *entry = _mesa_hash_table_search(this->ht, ir);
   return entry ? (loop_variable_state *) entry->data : NULL;
}

loop_variable *
loop_variable_state::get(const ir_variable *ir)
{
   hash_entry *entry = _mesa_hash_table_search(this->var_hash, ir);
   return entry ? (loop_variable *) entry->data : NULL;
}

loop_variable *
loop_variable_state::insert(ir_variable *var)
{
   void *mem_ctx = ralloc_parent(this);
   loop_variable *lv = rzalloc(mem_ctx, loop_variable);

   lv->var = var;

   _mesa_hash_table_insert(this->var_hash, lv->var, lv);
   this->variables.push_tail(lv);

   return lv;
}

loop_terminator *
loop_variable_state::insert(ir_if *if_stmt)
{
   void *mem_ctx = ralloc_parent(this);
   loop_terminator *t = new(mem_ctx) loop_terminator();

   t->ir = if_stmt;
   this->terminators.push_tail(t);

   return t;
}

/**
 * If the given variable already is recorded in the state for this loop,
 * return the corresponding loop_variable object that records information
 * about it.
 *
 * Otherwise, create a new loop_variable object to record information about
 * the variable, and set its \c read_before_write field appropriately based on
 * \c in_assignee.
 *
 * \arg in_assignee is true if this variable was encountered on the LHS of an
 * assignment.
 */
loop_variable *
loop_variable_state::get_or_insert(ir_variable *var, bool in_assignee)
{
   loop_variable *lv = this->get(var);

   if (lv == NULL) {
      lv = this->insert(var);
      lv->read_before_write = !in_assignee;
   }

   return lv;
}

namespace {

class loop_analysis : public ir_hierarchical_visitor {
public:
   loop_analysis(loop_state *loops);

   virtual ir_visitor_status visit(ir_loop_jump *);
   virtual ir_visitor_status visit(ir_dereference_variable *);

   virtual ir_visitor_status visit_enter(ir_call *);

   virtual ir_visitor_status visit_enter(ir_loop *);
   virtual ir_visitor_status visit_leave(ir_loop *);
   virtual ir_visitor_status visit_enter(ir_assignment *);
   virtual ir_visitor_status visit_leave(ir_assignment *);
   virtual ir_visitor_status visit_enter(ir_if *);
   virtual ir_visitor_status visit_leave(ir_if *);

   loop_state *loops;

   int if_statement_depth;

   ir_assignment *current_assignment;

   exec_list state;
};

} /* anonymous namespace */

loop_analysis::loop_analysis(loop_state *loops)
   : loops(loops), if_statement_depth(0), current_assignment(NULL)
{
   /* empty */
}

ir_visitor_status
loop_analysis::visit(ir_loop_jump *ir)
{
   (void) ir;

   assert(!this->state.is_empty());

   loop_variable_state *const ls =
      (loop_variable_state *) this->state.get_head();

   ls->num_loop_jumps++;

   return visit_continue;
}

ir_visitor_status
loop_analysis::visit_enter(ir_call *)
{
   /* Mark every loop that we're currently analyzing as containing an ir_call
    * (even those at outer nesting levels).
    */
   foreach_in_list(loop_variable_state, ls, &this->state) {
      ls->contains_calls = true;
   }

   return visit_continue_with_parent;
}

ir_visitor_status
loop_analysis::visit(ir_dereference_variable *ir)
{
   /* If we're not somewhere inside a loop, there's nothing to do.
    */
   if (this->state.is_empty())
      return visit_continue;

   bool nested = false;

   foreach_in_list(loop_variable_state, ls, &this->state) {
      ir_variable *var = ir->variable_referenced();
      loop_variable *lv = ls->get_or_insert(var, this->in_assignee);

      lv->record_reference(this->in_assignee,
                           nested || this->if_statement_depth > 0,
                           this->current_assignment);
      nested = true;
   }

   return visit_continue;
}

ir_visitor_status
loop_analysis::visit_enter(ir_loop *ir)
{
   loop_variable_state *ls = this->loops->insert(ir);
   this->state.push_head(ls);

   return visit_continue;
}

ir_visitor_status
loop_analysis::visit_leave(ir_loop *ir)
{
   loop_variable_state *const ls =
      (loop_variable_state *) this->state.pop_head();

   /* Function calls may contain side effects.  These could alter any of our
    * variables in ways that cannot be known, and may even terminate shader
    * execution (say, calling discard in the fragment shader).  So we can't
    * rely on any of our analysis about assignments to variables.
    *
    * We could perform some conservative analysis (prove there's no statically
    * possible assignment, etc.) but it isn't worth it for now; function
    * inlining will allow us to unroll loops anyway.
    */
   if (ls->contains_calls)
      return visit_continue;

   foreach_in_list(ir_instruction, node, &ir->body_instructions) {
      /* Skip over declarations at the start of a loop.
       */
      if (node->as_variable())
	 continue;

      ir_if *if_stmt = ((ir_instruction *) node)->as_if();

      if ((if_stmt != NULL) && is_loop_terminator(if_stmt))
	 ls->insert(if_stmt);
      else
	 break;
   }

   foreach_in_list_safe(loop_variable, lv, &ls->variables) {
      /* Move variables that are already marked as being loop constant to
       * a separate list.  These trivially don't need to be tested.
       */
      if (lv->is_loop_constant()) {
	 lv->remove();
	 ls->constants.push_tail(lv);
      }
   }

   /* Each variable assigned in the loop that isn't already marked as being loop
    * constant might still be loop constant.  The requirements at this point
    * are:
    *
    *    - Variable is written before it is read.
    *
    *    - Only one assignment to the variable.
    *
    *    - All operands on the RHS of the assignment are also loop constants.
    *
    * The last requirement is the reason for the progress loop.  A variable
    * marked as a loop constant on one pass may allow other variables to be
    * marked as loop constant on following passes.
    */
   bool progress;
   do {
      progress = false;

      foreach_in_list_safe(loop_variable, lv, &ls->variables) {
	 if (lv->conditional_or_nested_assignment || (lv->num_assignments > 1))
	    continue;

	 /* Process the RHS of the assignment.  If all of the variables
	  * accessed there are loop constants, then add this
	  */
	 ir_rvalue *const rhs = lv->first_assignment->rhs;
	 if (all_expression_operands_are_loop_constant(rhs, ls->var_hash)) {
	    lv->rhs_clean = true;

	    if (lv->is_loop_constant()) {
	       progress = true;

	       lv->remove();
	       ls->constants.push_tail(lv);
	    }
	 }
      }
   } while (progress);

   /* The remaining variables that are not loop invariant might be loop
    * induction variables.
    */
   foreach_in_list_safe(loop_variable, lv, &ls->variables) {
      /* If there is more than one assignment to a variable, it cannot be a
       * loop induction variable.  This isn't strictly true, but this is a
       * very simple induction variable detector, and it can't handle more
       * complex cases.
       */
      if (lv->num_assignments > 1)
	 continue;

      /* All of the variables with zero assignments in the loop are loop
       * invariant, and they should have already been filtered out.
       */
      assert(lv->num_assignments == 1);
      assert(lv->first_assignment != NULL);

      /* The assignment to the variable in the loop must be unconditional and
       * not inside a nested loop.
       */
      if (lv->conditional_or_nested_assignment)
	 continue;

      /* Basic loop induction variables have a single assignment in the loop
       * that has the form 'VAR = VAR + i' or 'VAR = VAR - i' where i is a
       * loop invariant.
       */
      ir_rvalue *const inc =
	 get_basic_induction_increment(lv->first_assignment, ls->var_hash);
      if (inc != NULL) {
	 lv->increment = inc;

	 lv->remove();
	 ls->induction_variables.push_tail(lv);
      }
   }

   /* Search the loop terminating conditions for those of the form 'i < c'
    * where i is a loop induction variable, c is a constant, and < is any
    * relative operator.  From each of these we can infer an iteration count.
    * Also figure out which terminator (if any) produces the smallest
    * iteration count--this is the limiting terminator.
    */
   foreach_in_list(loop_terminator, t, &ls->terminators) {
      ir_if *if_stmt = t->ir;

      /* If-statements can be either 'if (expr)' or 'if (deref)'.  We only care
       * about the former here.
       */
      ir_expression *cond = if_stmt->condition->as_expression();
      if (cond == NULL)
	 continue;

      switch (cond->operation) {
      case ir_binop_less:
      case ir_binop_greater:
      case ir_binop_lequal:
      case ir_binop_gequal: {
	 /* The expressions that we care about will either be of the form
	  * 'counter < limit' or 'limit < counter'.  Figure out which is
	  * which.
	  */
	 ir_rvalue *counter = cond->operands[0]->as_dereference_variable();
	 ir_constant *limit = cond->operands[1]->as_constant();
	 enum ir_expression_operation cmp = cond->operation;

	 if (limit == NULL) {
	    counter = cond->operands[1]->as_dereference_variable();
	    limit = cond->operands[0]->as_constant();

	    switch (cmp) {
	    case ir_binop_less:    cmp = ir_binop_greater; break;
	    case ir_binop_greater: cmp = ir_binop_less;    break;
	    case ir_binop_lequal:  cmp = ir_binop_gequal;  break;
	    case ir_binop_gequal:  cmp = ir_binop_lequal;  break;
	    default: assert(!"Should not get here.");
	    }
	 }

	 if ((counter == NULL) || (limit == NULL))
	    break;

	 ir_variable *var = counter->variable_referenced();

	 ir_rvalue *init = find_initial_value(ir, var);

         loop_variable *lv = ls->get(var);
         if (lv != NULL && lv->is_induction_var()) {
            t->iterations = calculate_iterations(init, limit, lv->increment,
                                                 cmp);

            if (t->iterations >= 0 &&
                (ls->limiting_terminator == NULL ||
                 t->iterations < ls->limiting_terminator->iterations)) {
               ls->limiting_terminator = t;
            }
         }
         break;
      }

      default:
         break;
      }
   }

   return visit_continue;
}

ir_visitor_status
loop_analysis::visit_enter(ir_if *ir)
{
   (void) ir;

   if (!this->state.is_empty())
      this->if_statement_depth++;

   return visit_continue;
}

ir_visitor_status
loop_analysis::visit_leave(ir_if *ir)
{
   (void) ir;

   if (!this->state.is_empty())
      this->if_statement_depth--;

   return visit_continue;
}

ir_visitor_status
loop_analysis::visit_enter(ir_assignment *ir)
{
   /* If we're not somewhere inside a loop, there's nothing to do.
    */
   if (this->state.is_empty())
      return visit_continue_with_parent;

   this->current_assignment = ir;

   return visit_continue;
}

ir_visitor_status
loop_analysis::visit_leave(ir_assignment *ir)
{
   /* Since the visit_enter exits with visit_continue_with_parent for this
    * case, the loop state stack should never be empty here.
    */
   assert(!this->state.is_empty());

   assert(this->current_assignment == ir);
   this->current_assignment = NULL;

   return visit_continue;
}

class examine_rhs : public ir_hierarchical_visitor {
public:
   examine_rhs(hash_table *loop_variables)
   {
      this->only_uses_loop_constants = true;
      this->loop_variables = loop_variables;
   }

   virtual ir_visitor_status visit(ir_dereference_variable *ir)
   {
      hash_entry *entry = _mesa_hash_table_search(this->loop_variables,
                                                  ir->var);
      loop_variable *lv = entry ? (loop_variable *) entry->data : NULL;

      assert(lv != NULL);

      if (lv->is_loop_constant()) {
	 return visit_continue;
      } else {
	 this->only_uses_loop_constants = false;
	 return visit_stop;
      }
   }

   hash_table *loop_variables;
   bool only_uses_loop_constants;
};

bool
all_expression_operands_are_loop_constant(ir_rvalue *ir, hash_table *variables)
{
   examine_rhs v(variables);

   ir->accept(&v);

   return v.only_uses_loop_constants;
}

ir_rvalue *
get_basic_induction_increment(ir_assignment *ir, hash_table *var_hash)
{
   /* The RHS must be a binary expression.
    */
   ir_expression *const rhs = ir->rhs->as_expression();
   if ((rhs == NULL)
       || ((rhs->operation != ir_binop_add)
	   && (rhs->operation != ir_binop_sub)))
      return NULL;

   /* One of the of operands of the expression must be the variable assigned.
    * If the operation is subtraction, the variable in question must be the
    * "left" operand.
    */
   ir_variable *const var = ir->lhs->variable_referenced();

   ir_variable *const op0 = rhs->operands[0]->variable_referenced();
   ir_variable *const op1 = rhs->operands[1]->variable_referenced();

   if (((op0 != var) && (op1 != var))
       || ((op1 == var) && (rhs->operation == ir_binop_sub)))
      return NULL;

   ir_rvalue *inc = (op0 == var) ? rhs->operands[1] : rhs->operands[0];

   if (inc->as_constant() == NULL) {
      ir_variable *const inc_var = inc->variable_referenced();
      if (inc_var != NULL) {
         hash_entry *entry = _mesa_hash_table_search(var_hash, inc_var);
         loop_variable *lv = entry ? (loop_variable *) entry->data : NULL;

         if (lv == NULL || !lv->is_loop_constant()) {
            assert(lv != NULL);
            inc = NULL;
         }
      } else
	 inc = NULL;
   }

   if ((inc != NULL) && (rhs->operation == ir_binop_sub)) {
      void *mem_ctx = ralloc_parent(ir);

      inc = new(mem_ctx) ir_expression(ir_unop_neg,
				       inc->type,
				       inc->clone(mem_ctx, NULL),
				       NULL);
   }

   return inc;
}

/**
 * Detect whether an if-statement is a loop terminating condition
 *
 * Detects if-statements of the form
 *
 *  (if (expression bool ...) (break))
 */
bool
is_loop_terminator(ir_if *ir)
{
   if (!ir->else_instructions.is_empty())
      return false;

   ir_instruction *const inst =
      (ir_instruction *) ir->then_instructions.get_head();
   if (inst == NULL)
      return false;

   if (inst->ir_type != ir_type_loop_jump)
      return false;

   ir_loop_jump *const jump = (ir_loop_jump *) inst;
   if (jump->mode != ir_loop_jump::jump_break)
      return false;

   return true;
}

loop_state *
analyze_loop_variables(exec_list *instructions)
{
   loop_state *loops = new loop_state;
   loop_analysis v(loops);

   v.run(instructions);
   return v.loops;
}


text:
<?php

// src/AppBundle/Controller/SecurityController.php
namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Acme\UserBundle\Entity\User;

class SecurityController extends Controller
{

	const MIN_PASSWORD_LENGTH = 4;
	const MAX_PASSWORD_LENGTH = 4096;

    /**
     * @Route("/login", name="login")
     */
    public function loginAction(Request $request)
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render(
            'AppBundle::security/login.html.twig',
            array(
                // last username entered by the user
                'last_username' => $lastUsername,
                'error'         => $error,
            )
        );
    }

    /**
     * @Route("/login_check", name="login_check")
     */
    public function loginCheckAction()
    {
    }

    /**
     * @Route("/registration", name="registration")
     */
    public function registrationAction(Request $request) {
    	$encoder = $this->container->get('security.password_encoder');

    	$errors = array();
    	$username = $request->request->get('username');
    	$password = $request->request->get('password');

    	// length validation
    	if (strlen($password) >= self::MAX_PASSWORD_LENGTH) {
    		$r = new Response();
    		$r->setStatusCode(400);
    		return $r;
    	}

    	$repeatPassword = $request->request->get('repeat_password');
    	$email = $request->request->get('email');
    	if ($request->isMethod('POST')) {

    		$errors = $this->validate($username,$password,$repeatPassword,$email);

    		// create user
    		if (empty($errors)) {

    			return $this->createUser($username,$password,$email);
    		}
    	}
    	return $this->render(
    			'AppBundle::security/registration.html.twig',
    			array(
    					'errors' => $errors,
    					'username' => $username,
    					'email' => $email,
    			)
    	);
    }

    private function createUser($username, $password, $email) {
    	$em = $this->getDoctrine()->getManager();

    	$u = new User();
    	$u->setUsername($username);
    	$u->setIsActive(true);
    	$u->setEmail($email);

    	$encoder = $this->container->get('security.password_encoder');
    	$u->setPassword($encoder->encodePassword($u, $password));

    	$em->persist($u);
    	$em->flush();

    	return $this->redirect($this->generateUrl('/login'));
    }

    private function validate ($username, $password, $repeatPassword, $email) {
    	$em = $this->getDoctrine()->getManager();
    	$errors = array();

    	// check username is present
    	if (empty($username)){
    		$errors[] = 'Username is mandatory';
    	}

    	// check email is present
    	if (empty($email)) {
    		$errors[] = 'Email is mandatory';
    	}

    	// check passwords match
    	if ($password != $repeatPassword) {
    		$errors[] = 'Passwords don\'t match';
    	}

    	// check password length
    	if (strlen($password) < self::MIN_PASSWORD_LENGTH) {
    		$errors[] = 'Password must be at least 4 characters long';
    	}

    	// check password simple
    	if (!preg_match('/[0-9]/', $password)) {
    		$errors[] = 'Password should contain a number or a unicorn horn';
    	}

    	// username in use
    	$prevUser = $em->getRepository('CWUserBundle:User')->findOneBy(array(
    			'username' => $username
    	));
    	if (isset($prevUser)) {
    		$errors[] = 'Username already in use';
    	}

    	// email in use
    	$prevUser = $em->getRepository('CWUserBundle:User')->findOneBy(array(
    			'email' => $email
    	));
    	if (isset($prevUser)) {
    		$errors[] = 'Email already in use';
    	}
    	return $errors;
    }
}


text:
package org.apache.jackrabbit.oak.segment.standby;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.jackrabbit.oak.commons.junit.TemporaryPort;
import org.apache.jackrabbit.oak.segment.standby.client.StandbyClientSync;
import org.apache.jackrabbit.oak.segment.standby.jmx.StandbyStatusMBean;
import org.apache.jackrabbit.oak.segment.standby.server.StandbyServerSync;
import org.apache.jackrabbit.oak.segment.test.TemporaryFileStore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TemporaryFolder;

public class MBeanIT extends TestBase {

    private TemporaryFolder folder = new TemporaryFolder(new File("target"));

    private TemporaryFileStore serverFileStore = new TemporaryFileStore(folder, false);

    private TemporaryFileStore clientFileStore = new TemporaryFileStore(folder, true);

    @Rule
    public TemporaryPort serverPort = new TemporaryPort();

    @Rule
    public RuleChain chain = RuleChain.outerRule(folder)
            .around(serverFileStore)
            .around(clientFileStore);

    @Test
    public void testServerEmptyConfig() throws Exception {
        MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName status = new ObjectName(StandbyStatusMBean.JMX_NAME + ",id=*");
        try (
            StandbyServerSync serverSync = StandbyServerSync.builder()
                .withPort(serverPort.getPort())
                .withFileStore(serverFileStore.fileStore())
                .withBlobChunkSize(1 * MB)
                .build()
        ) {
            serverSync.start();

            Set<ObjectName> instances = jmxServer.queryNames(status, null);
            assertEquals(1, instances.size());
            status = instances.toArray(new ObjectName[0])[0];
            assertEquals(new ObjectName(serverSync.getMBeanName()), status);
            assertTrue(jmxServer.isRegistered(status));

            assertEquals("primary", jmxServer.getAttribute(status, "Mode"));
            String m = jmxServer.getAttribute(status, "Status").toString();
            if (!m.equals(StandbyStatusMBean.STATUS_RUNNING) && !m.equals("channel unregistered")) {
                fail("unexpected Status " + m);
            }

            assertEquals(StandbyStatusMBean.STATUS_RUNNING, jmxServer.getAttribute(status, "Status"));
            assertEquals(true, jmxServer.getAttribute(status, "Running"));
            jmxServer.invoke(status, "stop", null, null);
            assertEquals(false, jmxServer.getAttribute(status, "Running"));
            assertEquals(StandbyStatusMBean.STATUS_STOPPED, jmxServer.getAttribute(status, "Status"));
            jmxServer.invoke(status, "start", null, null);

            assertEquals(true, jmxServer.getAttribute(status, "Running"));
            assertEquals(StandbyStatusMBean.STATUS_RUNNING, jmxServer.getAttribute(status, "Status"));
        }
        assertTrue(!jmxServer.isRegistered(status));
    }

    @Test
    public void testClientEmptyConfigNoServer() throws Exception {
        MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName status = new ObjectName(StandbyStatusMBean.JMX_NAME + ",id=*");
        try (StandbyClientSync clientSync = new StandbyClientSync(getServerHost(), serverPort.getPort(), clientFileStore.fileStore(), false, getClientTimeout(), false, folder.newFolder())) {
            clientSync.start();
            clientSync.run();

            Set<ObjectName> instances = jmxServer.queryNames(status, null);
            assertEquals(1, instances.size());
            status = instances.toArray(new ObjectName[0])[0];
            assertEquals(new ObjectName(clientSync.getMBeanName()), status);
            assertTrue(jmxServer.isRegistered(status));

            String m = jmxServer.getAttribute(status, "Mode").toString();
            if (!m.startsWith("client: ")) {
                fail("unexpected mode " + m);
            }

            assertEquals("1", jmxServer.getAttribute(status, "FailedRequests").toString());
            assertEquals("-1", jmxServer.getAttribute(status, "SecondsSinceLastSuccess").toString());

            assertEquals(StandbyStatusMBean.STATUS_RUNNING, jmxServer.getAttribute(status, "Status"));

            assertEquals(true, jmxServer.getAttribute(status, "Running"));
            jmxServer.invoke(status, "stop", null, null);
            assertEquals(false, jmxServer.getAttribute(status, "Running"));
            assertEquals(StandbyStatusMBean.STATUS_STOPPED, jmxServer.getAttribute(status, "Status"));
            jmxServer.invoke(status, "start", null, null);
            assertEquals(true, jmxServer.getAttribute(status, "Running"));
            assertEquals(StandbyStatusMBean.STATUS_RUNNING, jmxServer.getAttribute(status, "Status"));

        }
        assertTrue(!jmxServer.isRegistered(status));
    }

    @Test
    public void testClientNoServer() throws Exception {
        System.setProperty(StandbyClientSync.CLIENT_ID_PROPERTY_NAME, "Foo");
        MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName status;
        try (StandbyClientSync clientSync = new StandbyClientSync(getServerHost(), serverPort.getPort(), clientFileStore.fileStore(), false, getClientTimeout(), false, folder.newFolder())) {
            clientSync.start();
            clientSync.run();

            status = new ObjectName(clientSync.getMBeanName());
            assertTrue(jmxServer.isRegistered(status));
            assertEquals("client: Foo", jmxServer.getAttribute(status, "Mode"));

            assertEquals("1", jmxServer.getAttribute(status, "FailedRequests").toString());
            assertEquals("-1", jmxServer.getAttribute(status, "SecondsSinceLastSuccess").toString());

            assertEquals("1", jmxServer.invoke(status, "calcFailedRequests", null, null).toString());
            assertEquals("-1", jmxServer.invoke(status, "calcSecondsSinceLastSuccess", null, null).toString());
        }
        assertTrue(!jmxServer.isRegistered(status));
    }

    @Test
    public void testClientAndServerEmptyConfig() throws Exception {
        System.setProperty(StandbyClientSync.CLIENT_ID_PROPERTY_NAME, "Bar");
        MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName clientStatus, serverStatus;
        try (
            StandbyServerSync serverSync = StandbyServerSync.builder()
                .withPort(serverPort.getPort())
                .withFileStore(serverFileStore.fileStore())
                .withBlobChunkSize(MB)
                .build();
            StandbyClientSync clientSync = new StandbyClientSync(getServerHost(), serverPort.getPort(), clientFileStore.fileStore(), false, getClientTimeout(), false, folder.newFolder())
        ) {
            serverSync.start();
            serverFileStore.fileStore().flush();

            clientSync.start();
            clientSync.run();

            clientStatus = new ObjectName(clientSync.getMBeanName());
            serverStatus = new ObjectName(serverSync.getMBeanName());
            ObjectName status = new ObjectName(StandbyStatusMBean.JMX_NAME + ",id=*");
            Set<ObjectName> instances = jmxServer.queryNames(status, null);
            assertEquals(3, instances.size());

            ObjectName connectionStatus = null;
            for (ObjectName s : instances) {
                if (!s.equals(clientStatus) && !s.equals(serverStatus)) {
                    connectionStatus = s;
                }
            }
            assertNotNull(connectionStatus);

            assertTrue(jmxServer.isRegistered(clientStatus));
            assertTrue(jmxServer.isRegistered(serverStatus));
            assertTrue(jmxServer.isRegistered(connectionStatus));

            String m = jmxServer.getAttribute(clientStatus, "Mode").toString();
            if (!m.startsWith("client: ")) {
                fail("unexpected mode " + m);
            }

            assertEquals("primary", jmxServer.getAttribute(serverStatus, "Mode"));

            assertEquals(true, jmxServer.getAttribute(serverStatus, "Running"));
            assertEquals(true, jmxServer.getAttribute(clientStatus, "Running"));

            assertEquals("0", jmxServer.getAttribute(clientStatus, "FailedRequests").toString());
            assertEquals("0", jmxServer.getAttribute(clientStatus, "SecondsSinceLastSuccess").toString());
            assertEquals("0", jmxServer.invoke(clientStatus, "calcFailedRequests", null, null).toString());
            assertEquals("0", jmxServer.invoke(clientStatus, "calcSecondsSinceLastSuccess", null, null).toString());

            Thread.sleep(1000);

            assertEquals("0", jmxServer.getAttribute(clientStatus, "FailedRequests").toString());
            assertEquals("1", jmxServer.getAttribute(clientStatus, "SecondsSinceLastSuccess").toString());
            assertEquals("0", jmxServer.invoke(clientStatus, "calcFailedRequests", null, null).toString());
            assertEquals("1", jmxServer.invoke(clientStatus, "calcSecondsSinceLastSuccess", null, null).toString());

            assertEquals(1L, jmxServer.getAttribute(connectionStatus, "TransferredSegments"));

            // stop the master
            jmxServer.invoke(serverStatus, "stop", null, null);
            assertEquals(false, jmxServer.getAttribute(serverStatus, "Running"));
            m = jmxServer.getAttribute(serverStatus, "Status").toString();
            if (!m.equals(StandbyStatusMBean.STATUS_STOPPED) && !m.equals("channel unregistered")) {
                fail("unexpected Status" + m);
            }

            // restart the master
            jmxServer.invoke(serverStatus, "start", null, null);
            assertEquals(true, jmxServer.getAttribute(serverStatus, "Running"));
            assertEquals(true, jmxServer.getAttribute(clientStatus, "Running"));
            m = jmxServer.getAttribute(serverStatus, "Status").toString();
            if (!m.equals(StandbyStatusMBean.STATUS_RUNNING) && !m.equals("channel unregistered")) {
                fail("unexpected Status" + m);
            }

            // stop the slave
            jmxServer.invoke(clientStatus, "stop", null, null);
            assertEquals(true, jmxServer.getAttribute(serverStatus, "Running"));
            assertEquals(false, jmxServer.getAttribute(clientStatus, "Running"));
            assertEquals(StandbyStatusMBean.STATUS_STOPPED, jmxServer.getAttribute(clientStatus, "Status"));

            // restart the slave
            jmxServer.invoke(clientStatus, "start", null, null);
            assertEquals(true, jmxServer.getAttribute(clientStatus, "Running"));
            assertEquals(StandbyStatusMBean.STATUS_RUNNING, jmxServer.getAttribute(clientStatus, "Status"));
        }
        assertTrue(!jmxServer.isRegistered(clientStatus));
        assertTrue(!jmxServer.isRegistered(serverStatus));
    }

}


text:
import arrayFilter from './_arrayFilter';
import baseXor from './_baseXor';
import isArrayLikeObject from './isArrayLikeObject';
import rest from './rest';

/**
 * Creates an array of unique values that is the
 * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
 * of the given arrays. The order of result values is determined by the order
 * they occur in the arrays.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Array
 * @param {...Array} [arrays] The arrays to inspect.
 * @returns {Array} Returns the new array of values.
 * @see _.difference, _.without
 * @example
 *
 * _.xor([2, 1], [4, 2]);
 * // => [1, 4]
 */
var xor = rest(function(arrays) {
  return baseXor(arrayFilter(arrays, isArrayLikeObject));
});

export default xor;


text:
namespace media {
class MediaGpuChannelManager;
}

namespace content {

// Customization of ServiceFactory for the GPU process.
class GpuServiceFactory : public ServiceFactory {
 public:
  explicit GpuServiceFactory(
      base::WeakPtr<media::MediaGpuChannelManager> media_gpu_channel_manager);
  ~GpuServiceFactory() override;

  // ServiceFactory overrides:
  void RegisterServices(ServiceMap* services) override;

 private:
#if defined(ENABLE_MOJO_MEDIA_IN_GPU_PROCESS)
  // Task runner we were constructed on, and that |media_gpu_channel_manager_|
  // must be accessed from (the GPU main thread task runner). We expect
  // RegisterServices() to be called on this task runner as well, but the
  // implementation doesn't care.
  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  base::WeakPtr<media::MediaGpuChannelManager> media_gpu_channel_manager_;
#endif

  DISALLOW_COPY_AND_ASSIGN(GpuServiceFactory);
};

}  // namespace content

#endif  // CONTENT_GPU_GPU_SERVICE_FACTORY_H_


text:
package org.sparklinedata.druid

import org.apache.spark.Logging
import org.json4s.jackson.JsonMethods._
import org.json4s.{Extraction, ShortTypeHints, FullTypeHints, DefaultFormats}
import org.json4s.ext.EnumNameSerializer
import org.json4s.jackson.Serialization
import org.sparklinedata.druid.client.QueryResultRowSerializer
import org.sparklinedata.druid.metadata.FunctionalDependencyType

object Utils extends Logging {

  implicit val jsonFormat = Serialization.formats(
    ShortTypeHints(
      List(
        classOf[AlphaNumericTopNMetricSpec],
        classOf[ArithmeticPostAggregationSpec],
        classOf[CardinalityAggregationSpec],
        classOf[ComparisonHavingSpec],
        classOf[ConstantPostAggregationSpec],
        classOf[DefaultDimensionSpec],
        classOf[DurationGranularitySpec],
        classOf[ExtractionDimensionSpec],
        classOf[ExtractionFunctionSpec],
        classOf[FieldAccessPostAggregationSpec],
        classOf[FilteredAggregationSpec],
        classOf[FunctionAggregationSpec],
        classOf[GroupByQuerySpec],
        classOf[HavingSpec],
        classOf[HyperUniqueCardinalityPostAggregationSpec],
        classOf[InvertedTopNMetricSpec],
        classOf[JavascriptAggregationSpec],
        classOf[JavaScriptExtractionFunctionSpec],
        classOf[JavascriptFilterSpec],
        classOf[JavascriptPostAggregationSpec],
        classOf[LexiographicTopNMetricSpec],
        classOf[LimitSpec],
        classOf[LogicalBinaryOpHavingSpec],
        classOf[LogicalFilterSpec],
        classOf[NotFilterSpec],
        classOf[NotOpHavingSpec],
        classOf[NumericTopNMetricSpec],
        classOf[OrderByColumnSpec],
        classOf[PartialExtractionFunctionSpec],
        classOf[PeriodGranularitySpec],
        classOf[RegexExtractionFunctionSpec],
        classOf[RegexFilterSpec],
        classOf[SearchQueryExtractionFunctionSpec],
        classOf[SelectorFilterSpec],
        classOf[TimeFormatExtractionFunctionSpec],
        classOf[TimeParsingExtractionFunctionSpec],
        classOf[TimeSeriesQuerySpec],
        classOf[TopNMetricSpec],
        classOf[TopNQuerySpec]
      )
    )
  ) +
    new EnumNameSerializer(FunctionalDependencyType) + new QueryResultRowSerializer ++
    org.json4s.ext.JodaTimeSerializers.all

  def logQuery(dq : DruidQuery) : Unit = {
    log.info("\nDruid Query:\n" + pretty(render(Extraction.decompose(dq))))
  }

  def queryToString(dq : DruidQuery) : String = pretty(render(Extraction.decompose(dq)))

  /**
   * from fpinscala book
   * @param a
   * @tparam A
   * @return
   */
  def sequence[A](a: List[Option[A]]): Option[List[A]] =
    a match {
      case Nil => Some(Nil)
      case h :: t => h flatMap (hh => sequence(t) map (hh :: _))
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<translate 	android:interpolator="@android:anim/decelerate_interpolator"
		    android:duration="500"
		    android:fromYDelta="-100.0%p"
		    android:toYDelta="0.0"
		  	xmlns:android="http://schemas.android.com/apk/res/android" />


text:
Template.admin_news_edit.rendered = function() {
  $('.date').datetimepicker({
    pick12HourFormat: false,
    pickSeconds: false,
    language: 'de'
  });
};

Template.admin_news_edit.events({
  'click .save': function(event, target) {
    event.preventDefault();
    var newsId = $(event.currentTarget).attr("id");
    var news = {
      headline: target.find('#headline').value,
      date: moment(target.find('#date').value)._d,
      text: target.find('#text').value,
      locale: target.find('#locale').value
    };
    var cb = function(error) {
      console.log(error);
      if (error && error.reason) {
        FlashMessages.sendError({
          text: error.reason
        });
      } else {
        FlashMessages.sendSuccess({
          text: "Die News ist gespeichert worden"
        });
        Router.go("/admin/news");
      }
    };

    if (newsId) {
      News.update(newsId, {
        $set: news
      }, cb);
    } else {
      News.insert(news, cb);
    }

    // Meteor.call('save-news',
    //   newsId, {
    //     headline: target.find('#headline').value,
    //     date: target.find('#date').value,
    //     text: target.find('#text').value,
    //     locale: target.find('#locale').value
    //   },
    //   function(error) {
    //     if (error && error.reason) {
    //       FlashMessages.sendError(error.reason);
    //     } else {
    //       FlashMessages.sendSuccess("Die News ist gespeichert worden");
    //       Router.go("/admin/news");
    //     }
    //   });
  },
  'click .cancel': function() {
    history.back();
  }
});


text:
def astar(graph, start, end):
    frontier = list()
    costs = {}
    explored = list()
    path = {}
    frontier.append(start)
    costs[start] = 0
    while len(frontier) > 0:
        #take cheapest one. Implement with priority queue
        index = 0
        minv = costs[frontier[index]]
        for i in range(len(frontier)):
            if costs[frontier[i]] < minv:
                minv = costs[frontier[i]]
                index = i
        node = frontier.pop(index)
        if node == end:
            respath = [node]
            while True:
                respath.insert(0, path[node])
                node = path[node]
                if node == start:
                    return respath
        explored.append(node)
        for child in graph[node]:
            if not child[0] in explored or not child[0] in frontier:
                path[child[0]] = node
                frontier.append(child[0])
                costs[child[0]] = costs[node] + child[1]
            elif costs[child[0]] > (costs[node] + child[1]):
                path[child[0]] = node
                costs[child[0]] = costs[node] + child[1]

    return None


text:
import binascii

import dns.exception
import dns.immutable
import dns.rdata
import dns.tokenizer

@dns.immutable.immutable
class NSAP(dns.rdata.Rdata):

    """NSAP record."""

    # see: RFC 1706

    __slots__ = ['address']

    def __init__(self, rdclass, rdtype, address):
        super().__init__(rdclass, rdtype)
        self.address = self._as_bytes(address)

    def to_text(self, origin=None, relativize=True, **kw):
        return "0x%s" % binascii.hexlify(self.address).decode()

    @classmethod
    def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True,
                  relativize_to=None):
        address = tok.get_string()
        if address[0:2] != '0x':
            raise dns.exception.SyntaxError('string does not start with 0x')
        address = address[2:].replace('.', '')
        if len(address) % 2 != 0:
            raise dns.exception.SyntaxError('hexstring has odd length')
        address = binascii.unhexlify(address.encode())
        return cls(rdclass, rdtype, address)

    def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
        file.write(self.address)

    @classmethod
    def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
        address = parser.get_remaining()
        return cls(rdclass, rdtype, address)


text:
typedef short Spin;
typedef std::vector<Spin> SpinConfiguration;
typedef std::function<double(const SpinConfiguration&,
                             const double)> QuantityCalculator;

template <typename URNG>
SpinConfiguration randomConfiguration(const size_t side_length, URNG &rng) {
  static std::uniform_int_distribution<Spin> dist(0, 1);
  SpinConfiguration sc(side_length * side_length);
  std::generate(std::begin(sc), std::end(sc), [&] () {
    if (dist(rng) == 1) {
      return 1;  // up
    }
    return -1;  // down
  });
  return sc;  // use return value optimisation
}

void saveToFile(const std::string &filename, const SpinConfiguration &sc) {
  const size_t L = std::sqrt(sc.size());
  std::ofstream ofs(filename);
  for (size_t y = 0; y < L; y++) {
    for (size_t x = 0; x < L; x++) {
      ofs << sc[y * L + x] << ' ';
    }
    ofs << '\n';
  }
  ofs.close();
}

double calculateHamiltonian(
  const SpinConfiguration &sc,
  const double coupling_x=1,
  const double coupling_y=1
) {
  const size_t side_length = std::sqrt(sc.size());
  double energy = 0;
  for (size_t pos = 0; pos < sc.size(); pos++) {
    if ((pos + 1) % side_length == 0) {  // right edge
      energy += coupling_x * sc[pos] * sc[pos + 1 - side_length];
    } else {
      energy += coupling_x * sc[pos] * sc[pos + 1];
    }

    if ((pos + side_length) >= sc.size()) {  // bottom edge
      energy += coupling_y * sc[pos] * sc[pos % side_length];
    } else {
      energy += coupling_y * sc[pos] * sc[pos + side_length];
    }
  }
  return -energy;
}

double calculateHamiltonianDifference(
  const SpinConfiguration &sc,
  const size_t pos,
  const double coupling_x=1,
  const double coupling_y=1
) {
const size_t L = std::sqrt(sc.size()),
               x = pos % L,
               y = pos / L;
  Spin top,
       right,
       bottom,
       left;
  if (y > 0) {
    top = sc[pos - L];
  } else {
    top = sc[x + (L - 1) * L];
  }
  if (x < L - 1) {
    right = sc[pos + 1];
  } else {
    right = sc[pos + 1 - L];
  }
  if (y < L - 1) {
    bottom = sc[pos + L];
  } else {
    bottom = sc[x];
  }
  if (x > 0) {
    left = sc[pos - 1];
  } else {
    left = sc[pos - 1 + L];
  }

  return 2 * sc[pos] * (coupling_y * top + coupling_x * right
                      + coupling_y * bottom + coupling_x * left);
}

template <typename URNG>
double metropolisStep(
  const double temperature,
  const double hamiltonian_before,
  const size_t pos,
  SpinConfiguration &sc,
  URNG &rng,
  const double coupling_x,
  const double coupling_y
) {
  static std::uniform_real_distribution<double> dist_p(0, 1);
  const double diff = calculateHamiltonianDifference(sc, pos, coupling_x,
                                                     coupling_y);
  if (diff > 0 && dist_p(rng) > std::exp(-1. / temperature * diff)) {
    return hamiltonian_before;  // reject flip
  }
  sc[pos] *= -1;
  return hamiltonian_before + diff;
}

template <typename URNG>
double metropolisRandomStep(
  const double temperature,
  const double hamiltonian_before,
  SpinConfiguration &sc,
  URNG &rng,
  const double coupling_x,
  const double coupling_y
) {
  std::uniform_int_distribution<size_t> dist_pos(0, sc.size() - 1);
  return metropolisStep(temperature, hamiltonian_before, dist_pos(rng), sc,
                        rng, coupling_x, coupling_y);
}

template <typename URNG>
double metropolisSweep(
  const double temperature,
  const double hamiltonian_before,
  SpinConfiguration &sc,
  URNG &rng,
  const double coupling_x,
  const double coupling_y
) {
  double hamiltonian = hamiltonian_before;
  for (size_t pos = 0; pos < sc.size(); pos++) {
    hamiltonian = metropolisStep(temperature, hamiltonian, pos, sc, rng,
                                 coupling_x, coupling_y);
  }
  return hamiltonian;
}

template <typename URNG>
double metropolis(
  const double temperature,
  const size_t side_length,
  const unsigned long num_sweeps_burnin,
  const unsigned long num_sweeps_measurement,
  QuantityCalculator calculate_quantity,
  URNG &rng,
  const double coupling_x=1,
  const double coupling_y=1,
  const std::string &filename = std::string()
) {
  SpinConfiguration sc = randomConfiguration(side_length, rng);
  double hamiltonian = calculateHamiltonian(sc);
  for (unsigned long i = 0; i < num_sweeps_burnin; i++) {
    hamiltonian = metropolisSweep(temperature, hamiltonian, sc, rng,
                                  coupling_x, coupling_y);
  }
  double quantity = calculate_quantity(sc, hamiltonian);
  for (unsigned long i = 0; i < num_sweeps_measurement; i++) {
    hamiltonian = metropolisSweep(temperature, hamiltonian, sc, rng,
                                  coupling_x, coupling_y);
    quantity = calculate_quantity(sc, hamiltonian);
  }

  if (filename != "") {
    saveToFile(filename, sc);
  }

  return quantity;
}

#endif  // __METROPOLIS_HPP__


text:
package mcjty.rftools.playerprops;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import mcjty.rftools.PlayerBuff;
import mcjty.rftools.RenderGameOverlayEventHandler;

import java.util.ArrayList;

@SideOnly(Side.CLIENT)
public class SendBuffsToClientHelper {

    public static void setBuffs(PacketSendBuffsToClient buffs) {
        RenderGameOverlayEventHandler.buffs = new ArrayList<PlayerBuff>(buffs.getBuffs());
    }
}


text:
<!DOCTYPE html>

<title>CalendarAlarm_extend</title>
<meta charset="utf-8"/>