text:
package com.scavi.brainsqueeze.career;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.google.common.truth.Truth.*;
import static com.scavi.brainsqueeze.career.LongestPath.GraphNode;

public class LongestPathTest {

    @Test
    public void test1() {
        GraphNode node1_1 = new GraphNode(1);
        GraphNode node1_2 = new GraphNode(1);
        GraphNode node2 = new GraphNode(2);
        GraphNode node3 = new GraphNode(3);
        GraphNode node4 = new GraphNode(4);
        GraphNode node5 = new GraphNode(5);
        GraphNode node6 = new GraphNode(6);
        GraphNode node7 = new GraphNode(7);

        node1_1.neighbors.add(node1_2);
        node1_1.neighbors.add(node3);

        node1_2.neighbors.add(node1_1);
        node1_2.neighbors.add(node4);

        node2.neighbors.add(node3);

        node4.neighbors.add(node3);
        node4.neighbors.add(node5);
        node4.neighbors.add(node1_2);

        node3.neighbors.add(node1_1);
        node3.neighbors.add(node2);
        node3.neighbors.add(node4);

        node5.neighbors.add(node4);
        node5.neighbors.add(node6);

        node6.neighbors.add(node5);
        node6.neighbors.add(node7);

        node6.neighbors.add(node7);

        List<GraphNode> nodes = new ArrayList<>();
        nodes.addAll(Arrays.asList(node1_1, node1_2, node2, node3, node4, node5, node6, node7));

        int longestPath = new LongestPath().findLongestUniqueValuePath(nodes);
        assertThat(longestPath).isEqualTo(6);
    }

    /**
     * . 4 11
     * . | |
     * . 3 10
     * . | |
     * .1-2-5-6-12-13
     * .| ....|
     * 14....7-8-9
     * .|
     * 15
     */
    @Test
    public void testDAG() {
        GraphNode node1 = new GraphNode(1);
        GraphNode node2 = new GraphNode(2);
        GraphNode node3 = new GraphNode(3);
        GraphNode node4 = new GraphNode(4);
        GraphNode node5 = new GraphNode(5);
        GraphNode node6 = new GraphNode(6);
        GraphNode node7 = new GraphNode(7);
        GraphNode node8 = new GraphNode(8);
        GraphNode node9 = new GraphNode(9);
        GraphNode node10 = new GraphNode(10);
        GraphNode node11 = new GraphNode(11);
        GraphNode node12 = new GraphNode(12);
        GraphNode node13 = new GraphNode(13);
        GraphNode node14 = new GraphNode(14);
        GraphNode node15 = new GraphNode(15);

        node1.neighbors.add(node2);
        node1.neighbors.add(node14);

        node2.neighbors.add(node3);
        node2.neighbors.add(node5);

        node3.neighbors.add(node4);

        node5.neighbors.add(node10);
        node5.neighbors.add(node6);

        node6.neighbors.add(node12);
        node6.neighbors.add(node7);

        node7.neighbors.add(node8);
        node8.neighbors.add(node9);

        node10.neighbors.add(node11);
        node12.neighbors.add(node13);
        node14.neighbors.add(node15);

        List<Integer> expectedLongestPath = new ArrayList<>(Arrays.asList(1, 2, 5, 6, 7, 8, 9));
        List<Integer> longestPath = new LongestPath().findLongestPathInDAG(node1);
        assertThat(longestPath).isEqualTo(expectedLongestPath);
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>websocket::permessage_deflate::server_no_context_takeover</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Beast">
<link rel="up" href="../boost__beast__websocket__permessage_deflate.html" title="websocket::permessage_deflate">
<link rel="prev" href="client_max_window_bits.html" title="websocket::permessage_deflate::client_max_window_bits">
<link rel="next" href="client_no_context_takeover.html" title="websocket::permessage_deflate::client_no_context_takeover">

Home
Libraries
People
FAQ
More

websocket::permessage_deflate::server_no_context_takeover

          true if server_no_context_takeover
          desired

          Synopsis

bool server_no_context_takeover = false;

          Description

Copyright © 2016-2019 Vinnie
      Falco

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

redpajama_set_name: RedPajamaGithub


text:
class YieldStrategy : public IStrategy {

	public:
		Action* getHighestYieldingAction(const funcSensor* sensors,BMap* map, int curOr, int curXBel, int curYBel, int tProb);

};


text:
@interface AssistiveTouch ()
@property(nonatomic,assign)float alphas;
@end

@implementation AssistiveTouch

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        self.windowLevel = UIWindowLevelAlert;
        _myControl = [[UIViewController alloc] init];
        self.rootViewController = _myControl;
        [self makeKeyAndVisible];

        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(locationChange:)];
        pan.delaysTouchesBegan = YES;
        [_myControl.view addGestureRecognizer:pan];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickTouch:)];
        [_myControl.view addGestureRecognizer:tap];
        _alphas = 0.4;
        _myControl.view.alpha = _alphas;
    }
    return self;
}

//添加视图
-(void)addView:(UIView *) views{
     [_myControl.view addSubview:views];
}

//改变位置
-(void)locationChange:(UIPanGestureRecognizer*)p
{
    CGPoint panPoint = [p locationInView:[[UIApplication sharedApplication] keyWindow]];

    if(p.state == UIGestureRecognizerStateBegan)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(changeColor) object:nil];
        _myControl.view.alpha = 1.0;
    }
    else if (p.state == UIGestureRecognizerStateEnded)
    {
        [self performSelector:@selector(changeColor) withObject:nil afterDelay:4.0];
    }
    if(p.state == UIGestureRecognizerStateChanged)
    {
        self.center = CGPointMake(panPoint.x, panPoint.y);
    }
    else if(p.state == UIGestureRecognizerStateEnded)
    {
        if(panPoint.x <= kScreenWidth/2)
        {
            if(panPoint.y <= 40+kHEIGHT/2 && panPoint.x >= 20+kWIDTH/2)
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(panPoint.x, kHEIGHT/2);
                }];
            }
            else if(panPoint.y >= kScreenHeight-kHEIGHT/2-40 && panPoint.x >= 20+kWIDTH/2)
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(panPoint.x, kScreenHeight-kHEIGHT/2);
                }];
            }
            else if (panPoint.x < kWIDTH/2+15 && panPoint.y > kScreenHeight-kHEIGHT/2)
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(kWIDTH/2, kScreenHeight-kHEIGHT/2);
                }];
            }
            else
            {
                CGFloat pointy = panPoint.y < kHEIGHT/2 ? kHEIGHT/2 :panPoint.y;
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(kWIDTH/2, pointy);
                }];
            }
        }
        else if(panPoint.x > kScreenWidth/2)
        {
            if(panPoint.y <= 40+kHEIGHT/2 && panPoint.x < kScreenWidth-kWIDTH/2-20 )
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(panPoint.x, kHEIGHT/2);
                }];
            }
            else if(panPoint.y >= kScreenHeight-40-kHEIGHT/2 && panPoint.x < kScreenWidth-kWIDTH/2-20)
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(panPoint.x, kScreenHeight-kHEIGHT/2);
                }];
            }
            else if (panPoint.x > kScreenWidth-kWIDTH/2-15 && panPoint.y < kHEIGHT/2)
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(kScreenWidth-kWIDTH/2, kHEIGHT/2);
                }];
            }
            else
            {
                CGFloat pointy = panPoint.y > kScreenHeight-kHEIGHT/2 ? kScreenHeight-kHEIGHT/2 :panPoint.y;
                [UIView animateWithDuration:0.2 animations:^{
                    self.center = CGPointMake(kScreenWidth-kWIDTH/2, pointy);
                }];
            }
        }
    }
}

//点击事件
-(void)clickTouch:(UITapGestureRecognizer*)t
{
    _myControl.view.alpha = 1.0;
    [self performSelector:@selector(changeColor) withObject:nil afterDelay:4.0];
    if(_delegate && [_delegate respondsToSelector:@selector(assistiveTocuhs)])
    {
        [_delegate assistiveTocuhs];
    }
}

//颜色改变
-(void)changeColor
{
    [UIView animateWithDuration:2.0 animations:^{
        _myControl.view.alpha = _alphas;
    }];
}

//透明度
-(void)setTouchBeginAlpha:(float) alpha{
    _alphas = alpha;
    _myControl.view.alpha = alpha;
}

@end


text:
@interface TCSUserStore ()

@property (nonatomic, strong) NSMutableArray *friendsList;
@property (nonatomic, strong) RACReplaySubject *friendListCountSignal;

@end

@implementation TCSUserStore

- (id)init{
  self = [super init];
  if (self) {
    self.friendListCountSignal = [RACReplaySubject subject];
    [self load];
  }
  return self;
}

- (void)dealloc{
  [self.friendListCountSignal sendCompleted];
}

- (void)setUser:(User *)user{
  if (_user != user){
    _user = user;
    [self save];
  }
}

- (NSInteger)friendsCount{
  return [self.friendsList count];
}

- (void)friendCountChanged{
  [self.friendListCountSignal sendNext:@([self friendsCount])];
}

- (User *)friendAtIndex:(NSUInteger)index{
  if (index < [self friendsCount]){
    return [self.friendsList objectAtIndex:index];
  }
  return nil;
}

- (void)addFriend:(User *)user{
  [self addFriends:@[user]];
}

- (void)addFriends:(NSArray *)friends{
  if (friends != nil){
    // Start with all new friends and remove those that are already in
    // the user's friend list
    NSMutableArray *friendsToAdd = [friends mutableCopy];
    for (User *newFriend in friends){
      for (User *oldFriend in self.friendsList) {
        if ([oldFriend.userName isEqualToString:newFriend.userName]){
          [friendsToAdd removeObject:newFriend];
        }
      }
    }

    if ([friendsToAdd count] > 0){
      [self.friendsList addObjectsFromArray:friendsToAdd];
      [self friendCountChanged];
      [self save];
    }
  }
}

- (void)removeFriendAtIndex:(NSUInteger)index{
  if (index < [self friendsCount]){
    [self.friendsList removeObjectAtIndex:index];
    [self friendCountChanged];
    [self save];
  }
}

- (void)removeAllFriends{
  [self.friendsList removeAllObjects];
  [self friendCountChanged];
  [self save];
}

- (void)replaceFriendAtIndex:(NSUInteger)index withFriend:(User *)user{
  if (index < [self friendsCount]){
    [self.friendsList replaceObjectAtIndex:index withObject:user];
    [self save];
  }
}

- (void)moveFriendAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex{
  if (toIndex != fromIndex) {
    NSMutableArray* list = self.friendsList;
		id obj = [list objectAtIndex:fromIndex];
    [list removeObjectAtIndex:fromIndex];
    if (toIndex >= [self friendsCount]) {
      [list addObject:obj];
    } else {
      [list insertObject:obj atIndex:toIndex];
    }
		[self save];
  }
}

- (void)save{
  NSData *friendsData = [NSKeyedArchiver archivedDataWithRootObject:self.friendsList];
  NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:self.user];
  [[NSUserDefaults standardUserDefaults] setObject:friendsData forKey:kTCSUserDefaultsLastFMFriendsList];
  [[NSUserDefaults standardUserDefaults] setObject:userData forKey:kTCSUserDefaultsLastFMUserName];
  [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)load{
  NSData *storedUserData = [[NSUserDefaults standardUserDefaults] objectForKey:kTCSUserDefaultsLastFMUserName];
  NSData *storedFriendsListData = [[NSUserDefaults standardUserDefaults] objectForKey:kTCSUserDefaultsLastFMFriendsList];
  User *storedUser = [NSKeyedUnarchiver unarchiveObjectWithData:storedUserData];
  NSArray *storedFriendsList = [NSKeyedUnarchiver unarchiveObjectWithData:storedFriendsListData];

  if (storedFriendsList == nil){
    storedFriendsList = [NSArray array];
  }

  _user = storedUser;
  _friendsList = [storedFriendsList mutableCopy];

  [self friendCountChanged];

  DLog(@"loaded username: %@", self.user.userName);
  DLog(@"loaded friends: %@", self.friendsList);
}

@end


text:
package org.jb2011.lnf.beautyeye.ch3_button;

import org.jb2011.lnf.beautyeye.utils.NinePatchHelper;
import org.jb2011.lnf.beautyeye.utils.RawCache;
import org.jb2011.ninepatch4j.NinePatch;

/**
 * NinePatch图片(*.9.png)工厂类.
 *
 * @author Jack Jiang
 * @version 1.0
 */
public class __Icon9Factory__ extends RawCache<NinePatch>
{

	/** 相对路径根(默认是相对于本类的相对物理路径). */
	public final static String IMGS_ROOT="imgs/np";

	/** The instance. */
	private static __Icon9Factory__ instance = null;

	/**
	 * Gets the single instance of __Icon9Factory__.
	 *
	 * @return single instance of __Icon9Factory__
	 */
	public static __Icon9Factory__ getInstance()
	{
		if(instance==null)
			instance = new __Icon9Factory__();
		return instance;
	}

	/* (non-Javadoc)
	 * @see org.jb2011.lnf.beautyeye.utils.RawCache#getResource(java.lang.String, java.lang.Class)
	 */
	@Override
	protected NinePatch getResource(String relativePath, Class baseClass)
	{
		return NinePatchHelper.createNinePatch(baseClass.getResource(relativePath), false);
	}

	/**
	 * Gets the raw.
	 *
	 * @param relativePath the relative path
	 * @return the raw
	 */
	public NinePatch getRaw(String relativePath)
	{
		return  getRaw(relativePath,this.getClass());
	}

	/**
	 * Gets the button icon_ normal green.
	 *
	 * @return the button icon_ normal green
	 */
	public NinePatch getButtonIcon_NormalGreen()
	{
		return getRaw(IMGS_ROOT+"/btn_special_default.9.png");
	}

	/**
	 * Gets the button icon_ normal gray.
	 *
	 * @return the button icon_ normal gray
	 */
	public NinePatch getButtonIcon_NormalGray()
	{
		return getRaw(IMGS_ROOT+"/btn_general_default.9.png");
	}

	/**
	 * Gets the button icon_ disable gray.
	 *
	 * @return the button icon_ disable gray
	 */
	public NinePatch getButtonIcon_DisableGray()
	{
		return getRaw(IMGS_ROOT+"/btn_special_disabled.9.png");
	}

	/**
	 * Gets the button icon_ pressed orange.
	 *
	 * @return the button icon_ pressed orange
	 */
	public NinePatch getButtonIcon_PressedOrange()
	{
		return getRaw(IMGS_ROOT+"/btn_general_pressed.9.png");
	}

	/**
	 * Gets the button icon_rover.
	 *
	 * @return the button icon_rover
	 */
	public NinePatch getButtonIcon_rover()
	{
		return getRaw(IMGS_ROOT+"/btn_general_rover.9.png");
	}

	/**
	 * Gets the button icon_ normal light blue.
	 *
	 * @return the button icon_ normal light blue
	 */
	public NinePatch getButtonIcon_NormalLightBlue()
	{
		return getRaw(IMGS_ROOT+"/btn_special_lightblue.9.png");
	}

	/**
	 * Gets the button icon_ normal red.
	 *
	 * @return the button icon_ normal red
	 */
	public NinePatch getButtonIcon_NormalRed()
	{
		return getRaw(IMGS_ROOT+"/btn_special_red.9.png");
	}

	/**
	 * Gets the button icon_ normal blue.
	 *
	 * @return the button icon_ normal blue
	 */
	public NinePatch getButtonIcon_NormalBlue()
	{
		return getRaw(IMGS_ROOT+"/btn_special_blue.9.png");
	}

	/**
	 * Gets the toggle button icon_ checked green.
	 *
	 * @return the toggle button icon_ checked green
	 */
	public NinePatch getToggleButtonIcon_CheckedGreen()
	{
		return getRaw(IMGS_ROOT+"/toggle_button_selected.9.png");
	}

	/**
	 * Gets the toggle button icon_ rover green.
	 *
	 * @return the toggle button icon_ rover green
	 */
	public NinePatch getToggleButtonIcon_RoverGreen()
	{
		return getRaw(IMGS_ROOT+"/toggle_button_rover.9.png");
	}

}


text:
{{currentUser.name}}

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>

Home

Portfolio

Resume

Contact

About


text:
package nl.xillio.migrationtool.gui;

import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.scene.control.TableView;

/**
 * Utility class to make table columns autosize to a certain percentage instead of a fixed width.
 *
 * @author Xillio
 */
public class PTableColumn<S, T> extends javafx.scene.control.TableColumn<S, T> {

    private final DoubleProperty percentageWidth = new SimpleDoubleProperty(1);

    public PTableColumn() {
        tableViewProperty().addListener((ChangeListener<TableView<S>>) (ov, t, t1) -> {
            if (PTableColumn.this.prefWidthProperty().isBound()) {
                PTableColumn.this.prefWidthProperty().unbind();
            }

            PTableColumn.this.prefWidthProperty().bind(t1.widthProperty().multiply(percentageWidth));
        });
    }

    public final DoubleProperty percentageWidthProperty() {
        return this.percentageWidth;
    }

    public final double getPercentageWidth() {
        return this.percentageWidthProperty().get();
    }

    public final void setPercentageWidth(final double value) throws IllegalArgumentException {
        if (value >= 0 && value <= 1) {
            this.percentageWidthProperty().set(value);
        } else {
            throw new IllegalArgumentException(String.format("The provided percentage width is not between 0.0 and 1.0. Value is: %1$s", value));
        }
    }
}


text:
if (Get-Service LittleBeat -ErrorAction SilentlyContinue) {
  $service = Get-WmiObject -Class Win32_Service -Filter "name='LittleBeat'"
  $service.delete()
}


text:
@interface DetailViewController : UIViewController {
    IBOutlet UITextView *detailTextView;
}

@property (strong, nonatomic) NSDictionary *detailItem;

@end


text:
package jsettlers.common.resources;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This is a object that provides access to resources needed for the game.
 *
 * @author michael
 */
public interface IResourceProvider {
	/**
	 * Gets a input steam for a resources file name.
	 *
	 * @param name
	 *            The name of the file. With directory, separated by "/"
	 * @return The InputStream
	 * @throws IOException
	 *             If no stream could be generated
	 */
	InputStream getResourcesFileStream(String name) throws IOException;

	/**
	 * Gets a output steam to write a file with the name.<br>
	 * It also creates parent folders as needed.
	 *
	 * @param name
	 *            The name of the file. With directory, separated by "/"
	 * @return The InputStream
	 * @throws IOException
	 *             If no stream could be generated
	 */
	OutputStream writeFile(String name) throws IOException;

	/**
	 * Gets a directory to store settings and other stuff.
	 *
	 * @see ResourceManager#getResourcesDirectory()
	 * @return The directory, where the user has write permissions.
	 */
	File getResourcesDirectory();

	/**
	 * Gets the folder containing the original maps.
	 *
	 * @return The folder containing the original maps.
	 */
	File getOriginalMapsDirectory();

}


text:
class BrowserChildProcessHost : public ChildProcessHost,
                                public ChildProcessInfo,
                                public ChildProcessLauncher::Client {
 public:
  virtual ~BrowserChildProcessHost();

  // Terminates all child processes and deletes each ChildProcessHost instance.
  static void TerminateAll();

  // The Iterator class allows iteration through either all child processes, or
  // ones of a specific type, depending on which constructor is used.  Note that
  // this should be done from the IO thread and that the iterator should not be
  // kept around as it may be invalidated on subsequent event processing in the
  // event loop.
  class Iterator {
   public:
    Iterator();
    explicit Iterator(ChildProcessInfo::ProcessType type);
    BrowserChildProcessHost* operator->() { return *iterator_; }
    BrowserChildProcessHost* operator*() { return *iterator_; }
    BrowserChildProcessHost* operator++();
    bool Done();

   private:
    bool all_;
    ChildProcessInfo::ProcessType type_;
    std::list<BrowserChildProcessHost*>::iterator iterator_;
  };

 protected:
  explicit BrowserChildProcessHost(ChildProcessInfo::ProcessType type);

  // Derived classes call this to launch the child process asynchronously.
  void Launch(
#if defined(OS_WIN)
      const FilePath& exposed_dir,
#elif defined(OS_POSIX)
      bool use_zygote,
      const base::environment_vector& environ,
#endif
      CommandLine* cmd_line);

  // Returns the handle of the child process. This can be called only after
  // OnProcessLaunched is called or it will be invalid and may crash.
  base::ProcessHandle GetChildProcessHandle() const;

  // ChildProcessLauncher::Client implementation.
  virtual void OnProcessLaunched() {}

  // Derived classes can override this to know if the process crashed.
  // |exit_code| is the status returned when the process crashed (for
  // posix, as returned from waitpid(), for Windows, as returned from
  // GetExitCodeProcess()).
  virtual void OnProcessCrashed(int exit_code) {}

  // Derived classes can override this to know if the process was
  // killed.  |exit_code| is the status returned when the process
  // was killed (for posix, as returned from waitpid(), for Windows,
  // as returned from GetExitCodeProcess()).
  virtual void OnProcessWasKilled(int exit_code) {}

  // Returns the termination status of a child.  |exit_code| is the
  // status returned when the process exited (for posix, as returned
  // from waitpid(), for Windows, as returned from
  // GetExitCodeProcess()).  |exit_code| may be NULL.
  virtual base::TerminationStatus GetChildTerminationStatus(int* exit_code);

  // Overrides from ChildProcessHost
  virtual void OnChildDied();
  virtual void ShutdownStarted();
  virtual void Notify(NotificationType type);
  // Extends the base class implementation and removes this host from
  // the host list. Calls ChildProcessHost::ForceShutdown
  virtual void ForceShutdown();

 private:
  // By using an internal class as the ChildProcessLauncher::Client, we can
  // intercept OnProcessLaunched and do our own processing before
  // calling the subclass' implementation.
  class ClientHook : public ChildProcessLauncher::Client {
   public:
    explicit ClientHook(BrowserChildProcessHost* host);
    virtual void OnProcessLaunched();
   private:
    BrowserChildProcessHost* host_;
  };
  ClientHook client_;
  scoped_ptr<ChildProcessLauncher> child_process_;
};

#endif  // CONTENT_BROWSER_BROWSER_CHILD_PROCESS_HOST_H_


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace gxt_workspace
{
    // http://www.pinvoke.net/default.aspx/user32/EnumWindows.html
    public class Movement
    {
        public Movement(ListBox debug)
        {
            this.debug = debug;
        }
        private ListBox debug { get; set; }
        //public delegate bool CallBackPtr(IntPtr hWnd, int lParam);
        public delegate bool CallBackPtr(IntPtr hWnd, ref ReportData data);
        private CallBackPtr callBackPtr;

        [DllImport("user32.dll", SetLastError = true)]
        private static extern int EnumWindows(CallBackPtr callPtr, int lPar);
        [DllImport("user32.Dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumWindows(CallBackPtr callPtr, /*[MarshalAsAttribute(UnmanagedType.Struct)]*/ ref ReportData data);

        public class ReportData
        {
            // You can put any dicks or Doms in here...
            public MovementDirection md;
            public ListBox debug;
        }

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, uint wFlags);

        public static bool Report(IntPtr hWnd, ref ReportData data)
        {
            Rectangle rectangle;
            MovementDirection md = (MovementDirection)data.md;
            var visible = IsWindowVisible(hWnd);
            if (visible)
            {
                RECT rect = new RECT();
                GetWindowRect(hWnd, ref rect);
                rectangle = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);

                WINDOWPLACEMENT wndpl = new WINDOWPLACEMENT();
                wndpl.Lenght = (uint)Marshal.SizeOf(typeof(WINDOWPLACEMENT));
                if (!GetWindowPlacement(hWnd, ref wndpl))
                {
                    MessageBox.Show("Bad size!");
                }
                var seeable = wndpl.ShowCmd == (uint)ShowCmd.SW_SHOWMAXIMIZED || wndpl.ShowCmd == (uint)ShowCmd.SW_SHOWNORMAL;

                if (seeable && IsOnScreen(rectangle))
                {
                    uint pid;
                    GetWindowThreadProcessId(hWnd, out pid);
                    //MessageBox.Show("Visible Control Window handle is " + hWnd + " at " + rectangle.ToString() + " of pid " + pid);
                    data.debug.Items.Add("hWnd:" + hWnd + ", rectangle:" + rectangle.ToString() + ", pid:" + pid);
                    int dLeft = 0, dTop = 0;
                    switch (md)
                    {
                        case MovementDirection.Left:
                            dLeft = -100;
                            break;
                        case MovementDirection.Right:
                            dLeft = 100;
                            break;
                        case MovementDirection.Up:
                            dTop = -100;
                            break;
                        case MovementDirection.Down:
                            dTop = 100;
                            break;
                    }
                    SetWindowPos(hWnd, 0, rectangle.Left + dLeft, rectangle.Top + dTop, 0, 0, (uint) (SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_SHOWWINDOW));
                }
            }
            return true;
        }

        public void Move(MovementDirection md)
        {
            // note in other situations, it is important to keep
            // callBackPtr as a member variable so it doesnt GC while you're calling EnumWindows

            callBackPtr = new CallBackPtr(Movement.Report);
            var data = new ReportData();
            data.md = md;
            data.debug = debug;
            Movement.EnumWindows(callBackPtr, ref data);
        }

        [Flags]
        public enum MovementDirection : int
        {
            Left, Right, Up, Down
        }

        // http://stackoverflow.com/a/11655557
        public static bool IsOnScreen(Rectangle rectangle)
        {
            return Screen.AllScreens.Any(s => s.WorkingArea.IntersectsWith(rectangle));
        }

        // http://stackoverflow.com/a/1434577
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool IsWindowVisible(IntPtr hWnd);
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpWndpl);
        [StructLayout(LayoutKind.Sequential)]
        private struct POINT
        {
            public long X;
            public long Y;
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct WINDOWPLACEMENT
        {
            public uint Lenght;
            public uint Flags;

            public uint ShowCmd;
            public POINT PtMinPosition;
            public POINT PtMaxPosition;
            public RECT RcNormalPosition;
        }

        private enum ShowCmd : uint
        {
            SW_SHOWMAXIMIZED = 3,
            SW_SHOWMINIMIZED = 2,
            SW_SHOWNORMAL = 1
        }

        [Flags]
        private enum SetWindowPosFlags : uint
        {
            SWP_SHOWWINDOW = 0x0040,
            SWP_NOZORDER = 0x0004,
            SWP_NOSIZE = 0x0001
        }
    }
}


text:
from keystoneplayground.common import config

_opt_lists = [(config.keystoneplaygroundGroup, config.keystoneplaygroundOpts)]

def list_opts():
    return _opt_lists


text:
import jps
import time

def callback(msg):
    print(msg)

sub = jps.Subscriber('/hoge1', callback)
try:
    while True:
        sub.spin_once()
        time.sleep(0.1)
except KeyboardInterrupt:
    pass


text:
package nl.knaw.dans.common.ldap.repo;

import nl.knaw.dans.common.lang.ldap.DateTimeTranslator;
import nl.knaw.dans.common.lang.ldap.OperationalAttributes;

import org.joda.time.DateTime;

public class LdapOperationalAttributes implements OperationalAttributes
{

    private static DateTimeTranslator TRANSLATOR = new DateTimeTranslator();

    private DateTime createTimestamp;

    private DateTime modifyTimestamp;

    protected LdapOperationalAttributes()
    {

    }

    public DateTime getCreateTimestamp()
    {
        return createTimestamp;
    }

    public DateTime getModifyTimestamp()
    {
        return modifyTimestamp;
    }

    protected void setCreateTime(String creationTime)
    {
        createTimestamp = parseDateTime(creationTime);
    }

    protected void setModifyTime(String modifyTime)
    {
        modifyTimestamp = parseDateTime(modifyTime);
    }

    protected static DateTime parseDateTime(String s)
    {
        return TRANSLATOR.fromLdap(s);
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.plugin.base.security;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.prestosql.spi.QueryId;
import io.prestosql.spi.connector.ColumnMetadata;
import io.prestosql.spi.connector.ConnectorAccessControl;
import io.prestosql.spi.connector.ConnectorSecurityContext;
import io.prestosql.spi.connector.ConnectorTransactionHandle;
import io.prestosql.spi.connector.SchemaTableName;
import io.prestosql.spi.security.AccessDeniedException;
import io.prestosql.spi.security.ConnectorIdentity;
import io.prestosql.spi.security.PrestoPrincipal;
import io.prestosql.spi.security.PrincipalType;
import io.prestosql.spi.type.VarcharType;
import org.testng.Assert.ThrowingRunnable;
import org.testng.annotations.Test;

import java.util.Set;

import static io.prestosql.spi.testing.InterfaceTestUtils.assertAllMethodsOverridden;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;

public class TestFileBasedAccessControl
{
    private static final ConnectorSecurityContext ADMIN = user("admin", ImmutableSet.of("admin", "staff"));
    private static final ConnectorSecurityContext ALICE = user("alice", ImmutableSet.of("staff"));
    private static final ConnectorSecurityContext BOB = user("bob", ImmutableSet.of("staff"));
    private static final ConnectorSecurityContext CHARLIE = user("charlie", ImmutableSet.of("guests"));
    private static final ConnectorSecurityContext JOE = user("joe", ImmutableSet.of());

    @Test
    public void testSchemaRules()
    {
        ConnectorAccessControl accessControl = createAccessControl("schema.json");

        accessControl.checkCanCreateSchema(ADMIN, "bob");
        accessControl.checkCanCreateSchema(ADMIN, "staff");
        accessControl.checkCanCreateSchema(ADMIN, "authenticated");
        accessControl.checkCanCreateSchema(ADMIN, "test");

        accessControl.checkCanCreateSchema(BOB, "bob");
        accessControl.checkCanCreateSchema(BOB, "staff");
        accessControl.checkCanCreateSchema(BOB, "authenticated");
        assertDenied(() -> accessControl.checkCanCreateSchema(BOB, "test"));

        assertDenied(() -> accessControl.checkCanCreateSchema(CHARLIE, "bob"));
        assertDenied(() -> accessControl.checkCanCreateSchema(CHARLIE, "staff"));
        accessControl.checkCanCreateSchema(CHARLIE, "authenticated");
        assertDenied(() -> accessControl.checkCanCreateSchema(CHARLIE, "test"));

        accessControl.checkCanDropSchema(ADMIN, "bob");
        accessControl.checkCanDropSchema(ADMIN, "staff");
        accessControl.checkCanDropSchema(ADMIN, "authenticated");
        accessControl.checkCanDropSchema(ADMIN, "test");

        accessControl.checkCanDropSchema(BOB, "bob");
        accessControl.checkCanDropSchema(BOB, "staff");
        accessControl.checkCanDropSchema(BOB, "authenticated");
        assertDenied(() -> accessControl.checkCanDropSchema(BOB, "test"));

        assertDenied(() -> accessControl.checkCanDropSchema(CHARLIE, "bob"));
        assertDenied(() -> accessControl.checkCanDropSchema(CHARLIE, "staff"));
        accessControl.checkCanDropSchema(CHARLIE, "authenticated");
        assertDenied(() -> accessControl.checkCanDropSchema(CHARLIE, "test"));

        accessControl.checkCanRenameSchema(ADMIN, "bob", "new_schema");
        accessControl.checkCanRenameSchema(ADMIN, "staff", "new_schema");
        accessControl.checkCanRenameSchema(ADMIN, "authenticated", "new_schema");
        accessControl.checkCanRenameSchema(ADMIN, "test", "new_schema");

        accessControl.checkCanRenameSchema(BOB, "bob", "staff");
        accessControl.checkCanRenameSchema(BOB, "staff", "authenticated");
        accessControl.checkCanRenameSchema(BOB, "authenticated", "bob");
        assertDenied(() -> accessControl.checkCanRenameSchema(BOB, "test", "bob"));
        assertDenied(() -> accessControl.checkCanRenameSchema(BOB, "bob", "test"));

        assertDenied(() -> accessControl.checkCanRenameSchema(CHARLIE, "bob", "new_schema"));
        assertDenied(() -> accessControl.checkCanRenameSchema(CHARLIE, "staff", "new_schema"));
        accessControl.checkCanRenameSchema(CHARLIE, "authenticated", "authenticated");
        assertDenied(() -> accessControl.checkCanRenameSchema(CHARLIE, "test", "new_schema"));

        accessControl.checkCanCreateTable(ADMIN, new SchemaTableName("bob", "test"));
        accessControl.checkCanCreateTable(ADMIN, new SchemaTableName("test", "test"));
        accessControl.checkCanCreateTable(ADMIN, new SchemaTableName("authenticated", "test"));
        assertDenied(() -> accessControl.checkCanCreateTable(ADMIN, new SchemaTableName("secret", "test")));

        accessControl.checkCanCreateTable(BOB, new SchemaTableName("bob", "test"));
        assertDenied(() -> accessControl.checkCanCreateTable(BOB, new SchemaTableName("test", "test")));
        accessControl.checkCanCreateTable(BOB, new SchemaTableName("authenticated", "test"));
        assertDenied(() -> accessControl.checkCanCreateTable(BOB, new SchemaTableName("secret", "test")));

        assertDenied(() -> accessControl.checkCanCreateTable(CHARLIE, new SchemaTableName("bob", "test")));
        assertDenied(() -> accessControl.checkCanCreateTable(CHARLIE, new SchemaTableName("test", "test")));
        accessControl.checkCanCreateTable(CHARLIE, new SchemaTableName("authenticated", "test"));
        assertDenied(() -> accessControl.checkCanCreateTable(CHARLIE, new SchemaTableName("secret", "test")));

        accessControl.checkCanSetSchemaAuthorization(ADMIN, "test", new PrestoPrincipal(PrincipalType.ROLE, "some_role"));
        accessControl.checkCanSetSchemaAuthorization(ADMIN, "test", new PrestoPrincipal(PrincipalType.USER, "some_user"));
        accessControl.checkCanSetSchemaAuthorization(BOB, "bob", new PrestoPrincipal(PrincipalType.ROLE, "some_role"));
        accessControl.checkCanSetSchemaAuthorization(BOB, "bob", new PrestoPrincipal(PrincipalType.USER, "some_user"));
        assertDenied(() -> accessControl.checkCanSetSchemaAuthorization(BOB, "test", new PrestoPrincipal(PrincipalType.ROLE, "some_role")));
        assertDenied(() -> accessControl.checkCanSetSchemaAuthorization(BOB, "test", new PrestoPrincipal(PrincipalType.USER, "some_user")));

        accessControl.checkCanShowCreateSchema(ADMIN, "bob");
        accessControl.checkCanShowCreateSchema(ADMIN, "staff");
        accessControl.checkCanShowCreateSchema(ADMIN, "authenticated");
        accessControl.checkCanShowCreateSchema(ADMIN, "test");

        accessControl.checkCanShowCreateSchema(BOB, "bob");
        accessControl.checkCanShowCreateSchema(BOB, "staff");
        accessControl.checkCanShowCreateSchema(BOB, "authenticated");
        assertDenied(() -> accessControl.checkCanShowCreateSchema(BOB, "test"));

        assertDenied(() -> accessControl.checkCanShowCreateSchema(CHARLIE, "bob"));
        assertDenied(() -> accessControl.checkCanShowCreateSchema(CHARLIE, "staff"));
        accessControl.checkCanShowCreateSchema(CHARLIE, "authenticated");
        assertDenied(() -> accessControl.checkCanShowCreateSchema(CHARLIE, "test"));
    }

    @Test
    public void testTableRules()
    {
        ConnectorAccessControl accessControl = createAccessControl("table.json");
        accessControl.checkCanSelectFromColumns(ALICE, new SchemaTableName("test", "test"), ImmutableSet.of());
        accessControl.checkCanSelectFromColumns(ALICE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
        accessControl.checkCanSelectFromColumns(ALICE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of("bobcolumn"));
        accessControl.checkCanShowColumns(ALICE, new SchemaTableName("bobschema", "bobtable"));
        assertEquals(
                accessControl.filterColumns(ALICE, new SchemaTableName("bobschema", "bobtable"), ImmutableList.of(column("a"))),
                ImmutableList.of(column("a")));
        accessControl.checkCanSelectFromColumns(BOB, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
        accessControl.checkCanShowColumns(BOB, new SchemaTableName("bobschema", "bobtable"));
        assertEquals(
                accessControl.filterColumns(BOB, new SchemaTableName("bobschema", "bobtable"), ImmutableList.of(column("a"))),
                ImmutableList.of(column("a")));
        accessControl.checkCanInsertIntoTable(BOB, new SchemaTableName("bobschema", "bobtable"));
        accessControl.checkCanDeleteFromTable(BOB, new SchemaTableName("bobschema", "bobtable"));
        accessControl.checkCanSelectFromColumns(CHARLIE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
        accessControl.checkCanSelectFromColumns(CHARLIE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of("bobcolumn"));
        accessControl.checkCanInsertIntoTable(CHARLIE, new SchemaTableName("bobschema", "bobtable"));
        accessControl.checkCanSelectFromColumns(JOE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
        accessControl.checkCanCreateViewWithSelectFromColumns(BOB, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
        accessControl.checkCanDropTable(ADMIN, new SchemaTableName("bobschema", "bobtable"));
        accessControl.checkCanRenameTable(ADMIN, new SchemaTableName("bobschema", "bobtable"), new SchemaTableName("aliceschema", "newbobtable"));
        accessControl.checkCanRenameTable(ALICE, new SchemaTableName("aliceschema", "alicetable"), new SchemaTableName("aliceschema", "newalicetable"));
        accessControl.checkCanRenameView(ADMIN, new SchemaTableName("bobschema", "bobview"), new SchemaTableName("aliceschema", "newbobview"));
        accessControl.checkCanRenameView(ALICE, new SchemaTableName("aliceschema", "aliceview"), new SchemaTableName("aliceschema", "newaliceview"));
        assertDenied(() -> accessControl.checkCanInsertIntoTable(ALICE, new SchemaTableName("bobschema", "bobtable")));
        assertDenied(() -> accessControl.checkCanDropTable(BOB, new SchemaTableName("bobschema", "bobtable")));
        assertDenied(() -> accessControl.checkCanRenameTable(BOB, new SchemaTableName("bobschema", "bobtable"), new SchemaTableName("bobschema", "newbobtable")));
        assertDenied(() -> accessControl.checkCanRenameTable(ALICE, new SchemaTableName("aliceschema", "alicetable"), new SchemaTableName("bobschema", "newalicetable")));
        assertDenied(() -> accessControl.checkCanInsertIntoTable(BOB, new SchemaTableName("test", "test")));
        assertDenied(() -> accessControl.checkCanSelectFromColumns(ADMIN, new SchemaTableName("secret", "secret"), ImmutableSet.of()));
        assertDenied(() -> accessControl.checkCanSelectFromColumns(JOE, new SchemaTableName("secret", "secret"), ImmutableSet.of()));
        assertDenied(() -> accessControl.checkCanCreateViewWithSelectFromColumns(JOE, new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of()));
        assertDenied(() -> accessControl.checkCanRenameView(BOB, new SchemaTableName("bobschema", "bobview"), new SchemaTableName("bobschema", "newbobview")));
        assertDenied(() -> accessControl.checkCanRenameView(ALICE, new SchemaTableName("aliceschema", "alicetable"), new SchemaTableName("bobschema", "newalicetable")));
    }

    @Test
    public void testNoTableRules()
    {
        ConnectorAccessControl accessControl = createAccessControl("no-access.json");
        assertDenied(() -> accessControl.checkCanShowColumns(BOB, new SchemaTableName("bobschema", "bobtable")));
        accessControl.checkCanShowTables(BOB, "bobschema");
        assertEquals(
                accessControl.filterColumns(BOB, new SchemaTableName("bobschema", "bobtable"), ImmutableList.of(column("a"))),
                ImmutableList.of());
    }

    @Test
    public void testSessionPropertyRules()
    {
        ConnectorAccessControl accessControl = createAccessControl("session_property.json");
        accessControl.checkCanSetCatalogSessionProperty(ADMIN, "dangerous");
        accessControl.checkCanSetCatalogSessionProperty(ALICE, "safe");
        accessControl.checkCanSetCatalogSessionProperty(ALICE, "unsafe");
        accessControl.checkCanSetCatalogSessionProperty(ALICE, "staff");
        accessControl.checkCanSetCatalogSessionProperty(BOB, "safe");
        accessControl.checkCanSetCatalogSessionProperty(BOB, "staff");
        assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(BOB, "unsafe"));
        assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(ALICE, "dangerous"));
        assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(CHARLIE, "safe"));
        assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(CHARLIE, "staff"));
        assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(JOE, "staff"));
    }

    @Test
    public void testInvalidRules()
    {
        assertThatThrownBy(() -> createAccessControl("invalid.json"))
                .hasMessageContaining("Invalid JSON");
    }

    @Test
    public void testEverythingImplemented()
    {
        assertAllMethodsOverridden(ConnectorAccessControl.class, FileBasedAccessControl.class);
    }

    private static ConnectorSecurityContext user(String name, Set<String> groups)
    {
        return new ConnectorSecurityContext(
                new ConnectorTransactionHandle() {},
                ConnectorIdentity.forUser(name).withGroups(groups).build(),
                new QueryId("query_id"));
    }

    private ConnectorAccessControl createAccessControl(String fileName)
    {
        String path = this.getClass().getClassLoader().getResource(fileName).getPath();
        FileBasedAccessControlConfig config = new FileBasedAccessControlConfig();
        config.setConfigFile(path);
        return new FileBasedAccessControl(config);
    }

    private static void assertDenied(ThrowingRunnable runnable)
    {
        assertThrows(AccessDeniedException.class, runnable);
    }

    private static ColumnMetadata column(String columnName)
    {
        return new ColumnMetadata(columnName, VarcharType.VARCHAR);
    }
}


text:
""" Setup script for the pelican-mboxreader plugin.
"""

# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name='pelican-mboxreader',

    # Versions should comply with PEP440.  For a discussion on single-sourcing
    # the version across setup.py and the project code, see
    # https://packaging.python.org/en/latest/single_source_version.html
    version='0.1.4',

    description='Pelican plugin that can load articles via email (mailbox / maildir)',
    long_description=long_description,
    long_description_content_type="text/markdown",

    # The project's main homepage.
    url='https://github.com/TC01/pelican-mboxreader/',

    # Author details
    author='Ben Rosser',
    author_email='rosser.bjr@gmail.com',

    # Choose your license
    license='MIT',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 4 - Beta',

        # Indicate who your project is intended for
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',

        # Pick your license as you wish (should match "license" above)
        'License :: OSI Approved :: MIT License',

        # Specify the Python versions you support here. In particular, ensure
        # that you indicate whether you support Python 2, Python 3 or both.
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',

        # Other.
        'Topic :: Communications :: Email',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Text Processing',
    ],

    # What does your project relate to?
    keywords='mbox mail pelican markdown blog',

    # You can just specify the packages manually here if your project is
    # simple. Or you can use find_packages().
    packages=find_packages(exclude=['contrib', 'docs', 'tests*']),

    # List run-time dependencies here.  These will be installed by pip when
    # your project is installed. For an analysis of "install_requires" vs pip's
    # requirements files see:
    # https://packaging.python.org/en/latest/requirements.html
    install_requires=['pelican', 'python-dateutil']

)


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.bounswe.group7.config (services-api 1.0-SNAPSHOT API)</title>
<meta name="date" content="2016-12-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.bounswe.group7.config

Classes

SimpleCORSFilter

StaticResourceConfiguration

WebSecurityConfig


text:
---
title: spring生命周期实例
tags: [spring]
---

参考:https://www.cnblogs.com/zrtqsk/p/3735273.html

1)创建BeanInitialDemo类

该类实现Bean级生命周期接口BeanNameAware,BeanFactoryAware,InitializingBean,DisposableBean和ApplicationContextAware

```
package com.sjq.bean.container;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class BeanInitialDemo implements BeanFactoryAware, BeanNameAware,
         InitializingBean, DisposableBean, ApplicationContextAware{
    // 对象属性
    private String name;

    // 对象引用属性
    private Student student;

    // 接收spring注入到bean实例的beanFactory
    private BeanFactory beanFactory;

    // 接收spring实例化该bean的ID
    private String beanName;

    // 接收spring注入到bean实例的ApplicationContext实例(容器应用上下文)
    private ApplicationContext applicationContext;

    public BeanInitialDemo() {
        System.out.println("第一步:【构造器】调用构造器实例化");
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        System.out.println("第二步:【注入属性】注入属性name");
        this.name = name;
    }

    public Student getStudent() {
        return student;
    }

    @Autowired
    public void setStudent(Student student) {
        System.out.println("第二步:【装配属性】spring装配引用对象Student");
        this.student = student;
    }

    // 用于获取容器的BeanFactory实例
    public BeanFactory getBeanFactory() {
        return beanFactory;
    }
    // 用于获取该bean在容器的ID
    public String getBeanName() {
        return beanName;
    }
    // 用于获取spring容器引用上下文对象
    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    // BeanNameAware接口
    @Override
    public void setBeanName(String beanName) {
        System.out.println("第三步:【BeanNameAware接口】调用BeanNameAware.setBeanName()");
        this.beanName=beanName;
    }

    // BeanFactoryAware接口
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("第四步:【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
        this.beanFactory=beanFactory;
    }

    // ApplicationContextAware接口
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("第五步:【ApplicationContextAware接口】调用ApplicationContextAware.setApplicationContext()");
        this.applicationContext=applicationContext;
    }

    // InitializingBean接口
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("第七步:【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");
    }

    // 对象自定义的init方法
    public void initMethod() {
        System.out.println("第八步:【init-method】调用<bean>的init-method属性指定的初始化方法");
    }

    // DisposableBean接口
    @Override
    public void destroy() throws Exception {
        System.out.println("第十一步:【DiposibleBean接口】调用DiposibleBean.destory()");
    }

    // 对象自定义的destroy方法
    public void destroyMethod() {
        System.out.println("第十二步:【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
    }
}
```

注:这里同时创建了一个student类,该类用于完成属性注入工作

```
package com.sjq.bean.container;

public class Student {
    private String name;

    public Student() {
        System.out.println("【student类】构造函数");
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
```

2)创建BeanPostProcessorDemo

该类实现BeanPostProcessor接口,同时观察,在容器创建Student和BeanInitialDemo对象时,都会调用实现了BeanPostProcessor接口的方法。

```
package com.sjq.bean.container;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class BeanPostProcessorDemo implements BeanPostProcessor{

    public BeanPostProcessorDemo() {
        super();
        System.out.println("【BeanPostProcessor】实现类构造器!!");
    }
    /**
     * 第一个参数都是要处理的Bean对象,第二个参数都是Bean的name。
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第六步:【BeanPostProcessor接口】方法postProcessBeforeInitialization对属性进行更改!");
        System.out.println("【BeanPostProcessor接口】方法postProcessBeforeInitialization,beanName="+beanName);
        return bean;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("第九步:【BeanPostProcessor接口】方法postProcessAfterInitialization对属性进行更改!");
        System.out.println("【BeanPostProcessor接口】方法postProcessAfterInitialization,beanName="+beanName);
        return bean;
    }
}
```

注:BeanPostProcessor接口两个方法的参数分别为实例化的bean对象和bean的id属性值。

3)创建注解配置类

使用@Configuration注解来表示该类是一个配置类,同时将容器管理的bean都在配置类中初始化

```
package com.sjq.bean.container;

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

@Configuration
public class BeaninitialConfig {

    @Bean(initMethod="initMethod",destroyMethod="destroyMethod")
    public BeanInitialDemo beanInitialDemo() {
        return new BeanInitialDemo();
    }

    @Bean
    public BeanPostProcessorDemo beanPostProcessorDemo() {
        return new BeanPostProcessorDemo();
    }

    @Bean
    public Student student() {
        return new Student();
    }
}
```

4)初始化容器

运行该类实现容器的初始化,从而观察到容器中bean初始化的过程。由于BeanInitialDemo需要依赖student类,因此会先创建student类实例,然后再创建BeanInitialDemo实例,并将student实例对象注入到BeanInitialDemo实例中

```
package com.sjq.bean.container;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AnnotationApplicationRun {
    public static void main(String[] args) {
        System.out.println("************************************************************************");

        System.out.println("开始初始化容器并创建对象.........");

        ApplicationContext context=new AnnotationConfigApplicationContext(BeaninitialConfig.class);

        System.out.println("************************************************************************");

        System.out.println("第十步:对象创建就绪,可以使用容器内的对象了");

        BeanInitialDemo demo=context.getBean(BeanInitialDemo.class);

        System.out.println(demo.getBeanName());

        System.out.println("现在开始关闭容器!");

        System.out.println("************************************************************************");

        ((AnnotationConfigApplicationContext)context).registerShutdownHook();
    }
}
```

5)运行结果查看

```
************************************************************************
开始初始化容器并创建对象.........
【BeanPostProcessor】实现类构造器!!

# 以上为BeanPostProcessorDemo的实例构造过程

第一步:【构造器】调用构造器实例化

# 构造beanInitialDemo实例,发现属性需要依赖student,因此转而构造student实例

【student类】构造函数
第六步:【BeanPostProcessor接口】方法postProcessBeforeInitialization对属性进行更改!
【BeanPostProcessor接口】方法postProcessBeforeInitialization,beanName=student
第九步:【BeanPostProcessor接口】方法postProcessAfterInitialization对属性进行更改!
【BeanPostProcessor接口】方法postProcessAfterInitialization,beanName=student

# 上面为student类的构造过程,会调用BeanPostProcessor接口的实现方法

第二步:【装配属性】spring装配引用对象Student
第三步:【BeanNameAware接口】调用BeanNameAware.setBeanName()
第四步:【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
第五步:【ApplicationContextAware接口】调用ApplicationContextAware.setApplicationContext()
第六步:【BeanPostProcessor接口】方法postProcessBeforeInitialization对属性进行更改!
【BeanPostProcessor接口】方法postProcessBeforeInitialization,beanName=beanInitialDemo
第七步:【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
第八步:【init-method】调用<bean>的init-method属性指定的初始化方法
第九步:【BeanPostProcessor接口】方法postProcessAfterInitialization对属性进行更改!
【BeanPostProcessor接口】方法postProcessAfterInitialization,beanName=beanInitialDemo

************************************************************************
第十步:对象创建就绪,可以使用容器内的对象了
beanInitialDemo
现在开始关闭容器!

************************************************************************
第十一步:【DiposibleBean接口】调用DiposibleBean.destory()
第十二步:【destroy-method】调用<bean>的destroy-method属性指定的初始化方法
```

6)xml方式配置

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="beanInitialDemo" class="com.sjq.bean.container.BeanInitialDemo" init-method="initMethod"
        destroy-method="destroyMethod" scope="singleton" p:name="张三"/>

    <bean id="beanPostProcessorDemo" class="com.sjq.bean.container.BeanPostProcessorDemo"/>

    <bean id="student" class="com.sjq.bean.container.Student"/>
</beans>
```

7)初始化容器

```
package com.sjq.bean.container;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ClasspathXmlApplicationRun {
    public static void main(String[] args) {
        System.out.println("************************************************************************");

        System.out.println("开始初始化容器并创建对象.........");

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext_Container.xml");

        System.out.println("************************************************************************");

        System.out.println("第十步:对象创建就绪,可以使用容器内的对象了");

        BeanInitialDemo demo=context.getBean(BeanInitialDemo.class);

        System.out.println(demo.getBeanName());

        System.out.println("现在开始关闭容器!");

        System.out.println("************************************************************************");

        ((ClassPathXmlApplicationContext)context).registerShutdownHook();
    }
}
```


text: Tests that the execution context is changed to match new selected node.


text:
#import <Foundation/Foundation.h>
#import "DynamoDBResponseUnmarshaller.h"
#import "DynamoDBBatchWriteItemResponse.h"

/**
 * Batch Write Item Result Unmarshaller
 */
@interface DynamoDBBatchWriteItemResponseUnmarshaller:DynamoDBResponseUnmarshaller {
    DynamoDBBatchWriteItemResponse *response;
}

+(DynamoDBBatchWriteItemResponse *)unmarshall:(NSDictionary *)jsonObject;

@end


text:
Find a career home

{{ profileName}}


text:
package org.diirt.datasource.sample.graphene;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextField;
import org.diirt.datasource.PVManager;
import org.diirt.datasource.PVReader;
import org.diirt.datasource.PVReaderEvent;
import org.diirt.datasource.PVReaderListener;
import static org.diirt.datasource.formula.ExpressionLanguage.formula;
import static org.diirt.datasource.graphene.ExpressionLanguage.*;
import org.diirt.datasource.graphene.Graph2DResult;
import org.diirt.datasource.graphene.SparklineGraph2DExpression;
import org.diirt.datasource.sample.ImagePanel;
import org.diirt.datasource.sample.SetupUtil;
import static org.diirt.util.concurrent.Executors.swingEDT;
import static org.diirt.util.time.TimeDuration.ofHertz;
import org.diirt.vtype.ValueUtil;

/**
 *
 * @author carcassi
 */
public class SparklineApp extends javax.swing.JFrame {

    /**
     * Creates new form SimpleScatterGraph
     */
    public SparklineApp() {
        SetupUtil.defaultCASetupForSwing();
        initComponents();
        int nFields = 4;
        pvFields.add(pvField1);
        imagePanels.add(imagePanel1);
        pvFields.add(pvField2);
        imagePanels.add(imagePanel2);
        pvFields.add(pvField3);
        imagePanels.add(imagePanel3);
        pvFields.add(pvField4);
        imagePanels.add(imagePanel4);
        for (int i = 0; i < nFields; i++) {
            pvs.add(null);
            plots.add(null);
            bindResize(i);
            bindPvChange(i);
        }
    }

    private PVReader<Graph2DResult> pv;
    protected SparklineGraph2DExpression plot1;
    protected List<ImagePanel> imagePanels = new ArrayList<>();
    protected List<SparklineGraph2DExpression> plots = new ArrayList<>();
    private List<PVReader<Graph2DResult>> pvs = new ArrayList<>();
    private List<JTextField> pvFields = new ArrayList<>();

    private void bindResize(final int i) {
        imagePanels.get(i).addComponentListener(new ComponentAdapter() {

            @Override
            public void componentResized(ComponentEvent e) {
                if (plots.get(i) != null) {
                    plots.get(i).update(plots.get(i).newUpdate().imageHeight(imagePanels.get(i).getHeight()).imageWidth(imagePanels.get(i).getWidth()));
                }
            }
        });
    }

    private void bindPvChange(final int i) {
        pvFields.get(i).addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                pvChange(i);
            }
        });
        pvChange(i);
    }

    private void pvChange(final int i) {
        if (pvs.get(i) != null) {
            pvs.get(i).close();
            imagePanels.get(i).setImage(null);
            plots.set(i, null);
        }

        if (pvFields.get(i).getText() == null || pvFields.get(i).getText().trim().isEmpty()) {
            return;
        }

        SparklineGraph2DExpression plot = sparklineGraphOf(formula(pvFields.get(i).getText()),
                    null,
                    null);

        plots.set(i, plot);

        plots.get(i).update(plots.get(i).newUpdate().imageHeight(imagePanels.get(i).getHeight())
                .imageWidth(imagePanels.get(i).getWidth()));
        pvs.set(i, PVManager.read(plots.get(i))
                .notifyOn(swingEDT())
                .readListener(new PVReaderListener<Graph2DResult>() {

                    @Override
                    public void pvChanged(PVReaderEvent<Graph2DResult> event) {
                        setLastError(event.getPvReader().lastException());
                        if (event.getPvReader().getValue() != null) {
                            BufferedImage image = ValueUtil.toImage(event.getPvReader().getValue().getImage());
                            imagePanels.get(i).setImage(image);
                        }
                    }
                })
                .maxRate(ofHertz(50)));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        lastErrorField = new javax.swing.JTextField();
        configureButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        pvField1 = new javax.swing.JTextField();
        imagePanel1 = new org.diirt.datasource.sample.ImagePanel();
        pvField2 = new javax.swing.JTextField();
        imagePanel2 = new org.diirt.datasource.sample.ImagePanel();
        pvField3 = new javax.swing.JTextField();
        imagePanel3 = new org.diirt.datasource.sample.ImagePanel();
        pvField4 = new javax.swing.JTextField();
        imagePanel4 = new org.diirt.datasource.sample.ImagePanel();
        jPanel2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lastErrorField.setEditable(false);

        configureButton.setText("Configure");
        configureButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                configureButtonActionPerformed(evt);
            }
        });

        jPanel1.setLayout(new java.awt.GridBagLayout());

        pvField1.setText("sim://sineWaveform(1, 100, 100, 0.01)");
        pvField1.setMinimumSize(new java.awt.Dimension(200, 22));
        pvField1.setPreferredSize(new java.awt.Dimension(200, 22));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 0.1;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
        jPanel1.add(pvField1, gridBagConstraints);

        javax.swing.GroupLayout imagePanel1Layout = new javax.swing.GroupLayout(imagePanel1);
        imagePanel1.setLayout(imagePanel1Layout);
        imagePanel1Layout.setHorizontalGroup(
            imagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        imagePanel1Layout.setVerticalGroup(
            imagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 0.9;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
        jPanel1.add(imagePanel1, gridBagConstraints);

        pvField2.setText("sim://squareWaveform(1.5, 300, 300, 0.01)");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
        jPanel1.add(pvField2, gridBagConstraints);

        javax.swing.GroupLayout imagePanel2Layout = new javax.swing.GroupLayout(imagePanel2);
        imagePanel2.setLayout(imagePanel2Layout);
        imagePanel2Layout.setHorizontalGroup(
            imagePanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 370, Short.MAX_VALUE)
        );
        imagePanel2Layout.setVerticalGroup(
            imagePanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 22, Short.MAX_VALUE)
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
        jPanel1.add(imagePanel2, gridBagConstraints);

        pvField3.setText("sim://triangleWaveform(0.5, 30,200, 0.01)");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
        jPanel1.add(pvField3, gridBagConstraints);

        javax.swing.GroupLayout imagePanel3Layout = new javax.swing.GroupLayout(imagePanel3);
        imagePanel3.setLayout(imagePanel3Layout);
        imagePanel3Layout.setHorizontalGroup(
            imagePanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 370, Short.MAX_VALUE)
        );
        imagePanel3Layout.setVerticalGroup(
            imagePanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 22, Short.MAX_VALUE)
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
        jPanel1.add(imagePanel3, gridBagConstraints);

        pvField4.setText("sim://gaussianWaveform(2,30,300,0.01)");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
        jPanel1.add(pvField4, gridBagConstraints);

        javax.swing.GroupLayout imagePanel4Layout = new javax.swing.GroupLayout(imagePanel4);
        imagePanel4.setLayout(imagePanel4Layout);
        imagePanel4Layout.setHorizontalGroup(
            imagePanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 370, Short.MAX_VALUE)
        );
        imagePanel4Layout.setVerticalGroup(
            imagePanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 22, Short.MAX_VALUE)
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
        jPanel1.add(imagePanel4, gridBagConstraints);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weighty = 1.0;
        jPanel1.add(jPanel2, gridBagConstraints);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
                    .addComponent(lastErrorField)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(configureButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(configureButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lastErrorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    protected void openConfigurationDialog() {

    }

    private void configureButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configureButtonActionPerformed
        openConfigurationDialog();
    }//GEN-LAST:event_configureButtonActionPerformed

    private void setLastError(Exception ex) {
        if (ex != null) {
            lastErrorField.setText(ex.getMessage());
            ex.printStackTrace();
        } else {
            lastErrorField.setText("");
        }
    }

    public static void main(String[] args) {
        main(SparklineApp.class);
    }

    public static void main(final Class<? extends SparklineApp> clazz) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SparklineApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SparklineApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SparklineApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SparklineApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    clazz.newInstance().setVisible(true);
                } catch (InstantiationException ex) {
                    Logger.getLogger(SparklineApp.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(SparklineApp.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton configureButton;
    private org.diirt.datasource.sample.ImagePanel imagePanel1;
    private org.diirt.datasource.sample.ImagePanel imagePanel2;
    private org.diirt.datasource.sample.ImagePanel imagePanel3;
    private org.diirt.datasource.sample.ImagePanel imagePanel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField lastErrorField;
    private javax.swing.JTextField pvField1;
    private javax.swing.JTextField pvField2;
    private javax.swing.JTextField pvField3;
    private javax.swing.JTextField pvField4;
    // End of variables declaration//GEN-END:variables
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>jsqis: features</title>

    <link rel="stylesheet" href="../jsqis-view.css">

jsqis: features

jsqis, at its core, is a quantum computer simulator written in Javascript.  It allows initialization of quantum registers and their manipulation by means of quantum gates.

Additionally, when used in the browser, jsqis provides a lucid visual representation of a system of quantum bits (qubits).  This representation is mathematically precise, allowing people to reason about quantum computing without having mastered any topics in mathematics.

In the language of mathematics, we do this by enumerating all the computational basis states and, beside each basis state, displaying its amplitude (which is a complex number) using a simple graphical representation.

Single qubit

A single bit can be in either of two classical states, zero or one.

A quantum bit can also be in an equal superposition of those two states.

Not only that, but the states can have a relative phase difference.

And they can of course have different amplitudes as well.

When a quantum bit is measured, it will assume a definite value (either zero or one).  The probability that the bit will be measured in a given state is proportional to the area of the corresponding box.

In addition to the arrow representing the relative phase, we color code it as well, choosing a continuous hue based on an amplitude's phase.  This is redundant (as the arrow already encodes the full information), but stresses the fact that phase information is incredibly important in quantum mechanics.

Just as in the mathematical representation of quantum mechanics, our states are invariant up to a change in overall magnitude and global phase.  In other words, it is the relative difference between the sizes and the directions of the arrows that matter.  For instance, the following states are all equivalent.

Multiple qubits

Operations

Single qubit gates

Multiple qubit gates

Other operations

Randomize

Rescale

Measure

Quantum circuit diagrams

Physical realizations

Photon polarization

The various states of a single qubit can be understood in terms of photon polarization.  Unfortunately, these animations can take quite a bit of CPU time, so this page only enables them when you hover the mouse over a given element.

We define the states 0 and 1 to be represented by vertically- and horizontally-polarized photons, respectively.

A an equal weighted superposition can then be in many different states.  If the phases point in parallel directions, we will get diagonal polarization.

Other possibilities include left and right circular polarization.

Elliptical polarization is also possible.

Any other one-qubit quantum state can be represented this way as well.

Planned features

Bloch sphere representation (most likely using three.js)


text:
package PAR::Repository::Client::HTTP;

use 5.006;
use strict;
use warnings;

use vars qw/$ua/;
require LWP::Simple;
LWP::Simple->import('$ua');

use base 'PAR::Repository::Client';

use Carp qw/croak/;

our $VERSION = '0.24';

=head1 NAME

PAR::Repository::Client::HTTP - PAR repository via HTTP

=head1 SYNOPSIS

  use PAR::Repository::Client;

  my $client = PAR::Repository::Client->new(
    uri => 'http:///foo/repository',
    http_timeout => 20, # but default is 180s
  );

=head1 DESCRIPTION

This module implements repository accesses via HTTP.

If you create a new L<PAR::Repository::Client> object and pass it
an uri parameter which starts with C<http://> or C<https://>,
it will create an object of this class. It inherits from
C<PAR::Repository::Client>.

The repository is accessed using L<LWP::Simple>.

=head2 EXPORT

None.

=head1 METHODS

Following is a list of class and instance methods.
(Instance methods until otherwise mentioned.)

=cut

=head2 fetch_par

Fetches a .par distribution from the repository and stores it
locally. Returns the name of the local file or the empty list on
failure.

First argument must be the distribution name to fetch.

=cut

sub fetch_par {
  my $self = shift;
  $self->{error} = undef;
  my $dist = shift;
  return() if not defined $dist;

  my $url = $self->{uri};
  $url =~ s/\/$//;

  my ($n, $v, $a, $p) = PAR::Dist::parse_dist_name($dist);
  $url .= "/$a/$p/$n-$v-$a-$p.par";

  my $file = $self->_fetch_file($url);

  if (not defined $file) {
    $self->{error} = "Could not fetch distribution from URI '$url'";
    return();
  }

  return $file;
}

{
  my %escapes;
  sub _fetch_file {
    my $self = shift;
    $self->{error} = undef;
    my $file = shift;
    #warn "FETCHING FILE: $file";

    my $cache_dir = $self->{cache_dir}; # used to be PAR_TEMP, but now configurable
    %escapes = map { chr($_) => sprintf("%%%02X", $_) } 0..255 unless %escapes;

    $file =~ m!/([^/]+)$!;
    my $local_file = (defined($1) ? $1 : $file);
    $local_file =~ s/([^\w\._])/$escapes{$1}/g;
    $local_file = File::Spec->catfile( $self->{cache_dir}, $local_file );

    my $timeout = $self->{http_timeout};
    my $old_timeout = $ua->timeout();
    $ua->timeout($timeout) if defined $timeout;
    my $rc = LWP::Simple::mirror( $file, $local_file );
    $ua->timeout($old_timeout) if defined $timeout;
    if (!LWP::Simple::is_success($rc) and not $rc == HTTP::Status::RC_NOT_MODIFIED()) {
      $self->{error} = "Error $rc: " . LWP::Simple::status_message($rc) . " ($file)\n";
      return();
    }

    return $local_file if -f $local_file;
    return();
  }
}

sub _fetch_as_data {
  my $self = shift;
  $self->{error} = undef;
  my $file = shift;
  #warn "FETCHING DATA: $file";

  my $timeout = $self->{http_timeout};
  my $old_timeout = $ua->timeout();
  $ua->timeout($timeout) if defined $timeout;
  my $data = LWP::Simple::get( $file );
  $ua->timeout($old_timeout) if defined $timeout;

  return $data if defined $data;

  $self->{error} = "Could not get '$file' from repository";
  return();
}

=head2 validate_repository

Makes sure the repository is valid. Returns the empty list
if that is not so and a true value if the repository is valid.

Checks that the repository version is compatible.

The error message is available as C<$client->error()> on
failure.

=cut

sub validate_repository {
  my $self = shift;
  $self->{error} = undef;

  my $mod_db = $self->modules_dbm;
  return() if not defined $mod_db;

  return() if not $self->validate_repository_version;

  return 1;
}

=head2 _repository_info

Returns a YAML::Tiny object representing the repository meta
information.

This is a private method.

=cut

sub _repository_info {
  my $self = shift;
  $self->{error} = undef;
  return $self->{info} if defined $self->{info};

  my $url = $self->{uri};
  $url =~ s/\/$//;

  my $file = $self->_fetch_file(
    $url.'/'.PAR::Repository::Client::REPOSITORY_INFO_FILE()
  );

  return() if not defined $file;

  my $yaml = YAML::Tiny->new->read($file);
  if (not defined $yaml) {
    $self->{error} = "Error reading repository info from YAML file.";
    return();
  }

  # workaround for possible YAML::Syck/YAML::Tiny bug
  # This is not the right way to do it!
  @$yaml = ($yaml->[1]) if @$yaml > 1;

  $self->{info} = $yaml;
  return $yaml;
}

=head2 _fetch_dbm_file

This is a private method.

Fetches a dbm (index) file from the repository and
returns the name of the temporary local file or the
empty list on failure.

An error message is available via the C<error()>
method in case of failure.

=cut

sub _fetch_dbm_file {
  my $self = shift;
  $self->{error} = undef;
  my $file = shift;
  return if not defined $file;

  my $url = $self->{uri};
  $url =~ s/\/$//;

  my $local = $self->_fetch_file("$url/$file");
  return() if not defined $local or not -f $local;

  return $local;
}

=head2 _dbm_checksums

This is a private method.

If the repository has a checksums file (new feature of
C<PAR::Repository> 0.15), this method returns a hash
associating the DBM file names (e.g. C<foo_bar.dbm.zip>)
with their MD5 hashes (base 64).

This method B<always> queries the repository and never caches
the information locally. That's the whole point of having the
checksums.

In case the repository does not have checksums, this method
returns the empty list, so check the return value!
The error message (see the C<error()> method) will be
I<"Repository does not support checksums"> in that case.

=cut

sub _dbm_checksums {
  my $self = shift;
  $self->{error} = undef;

  my $url = $self->{uri};
  $url =~ s/\/$//;

  # if we're running on a "trust-the-checksums-for-this-long" basis...
  # ... return if the timeout hasn't elapsed
  if ($self->{checksums} and $self->{checksums_timeout}) {
    my $time = time();
    if ($time - $self->{last_checksums_refresh} < $self->{checksums_timeout}) {
      return($self->{checksums});
    }
  }

  my $data = $self->_fetch_as_data(
    $url.'/'.PAR::Repository::Client::DBM_CHECKSUMS_FILE()
  );

  if (not defined $data) {
    $self->{error} = "Repository does not support checksums";
    return();
  }

  return $self->_parse_dbm_checksums(\$data);
}

=head2 _init

This private method is called by the C<new()> method of
L<PAR::Repository::Client>. It is used to initialize
the client object and C<new()> passes it a hash ref to
its arguments.

Should return a true value on success.

=cut

sub _init {
  my $self = shift;
  my $args = shift || {};
  # We implement additional object attributes here
  $self->{http_timeout} = $args->{http_timeout};
  $self->{http_timeout} = 180 if not defined $self->{http_timeout};

  return 1;
}

1;
__END__

=head1 SEE ALSO

This module is part of the L<PAR::Repository::Client> distribution.

This module is directly related to the C<PAR> project. You need to have
basic familiarity with it. The PAR homepage is at L<http://par.perl.org>.

See L<PAR>, L<PAR::Dist>, L<PAR::Repository>, etc.

L<PAR::Repository> implements the server side creation and manipulation
of PAR repositories.

L<PAR::WebStart> is doing something similar but is otherwise unrelated.

The repository access is done via L<LWP::Simple>.

=head1 AUTHOR

Steffen Mueller, E<lt>smueller@cpan.orgE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2006-2009 by Steffen Mueller

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.6 or,
at your option, any later version of Perl 5 you may have available.

=cut