text:
var win = Ti.UI.createWindow();

var imageButton = Ti.UI.createImageButton({
	image: 'images/play_button.png',
	imagePressed: 'images/play_button_pressed.png',
	imageDisabled: 'images/appcelerator_small.png'
});

imageButton.addEventListener('click', function(){
	alert('ImageButton Clicked')
});

var btn = Ti.UI.createButton({
	bottom: 10,
	title: 'disable image button'
});

var enabled = true;
btn.addEventListener('click', function(){
	imageButton.enabled = enabled;
	enabled = !enabled;
});

win.add(btn);

win.add(imageButton);
win.open();

redpajama_set_name: RedPajamaGithub


text:
using System.IO;
using System.IO.Compression;

namespace Cauldron.Core
{
    internal static class Compression
    {
        public static byte[] Compress(byte[] bytes)
        {
            using (var msi = new MemoryStream(bytes))
            {
                using (var mso = new MemoryStream())
                {
                    using (var gs = new GZipStream(mso, CompressionMode.Compress))
                        CopyTo(msi, gs);

                    return mso.ToArray();
                }
            }
        }

        public static byte[] Decompress(byte[] bytes)
        {
            using (var msi = new MemoryStream(bytes))
            {
                using (var mso = new MemoryStream())
                {
                    using (var gs = new GZipStream(msi, CompressionMode.Decompress))
                        CopyTo(gs, mso);

                    return mso.ToArray();
                }
            }
        }

        private static void CopyTo(Stream src, Stream dest)
        {
            byte[] bytes = new byte[4096];

            int cnt;

            while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
                dest.Write(bytes, 0, cnt);
        }
    }
}


text:
package com.thinkgem.jeesite.modules.ftc.rest.customer;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.rest.BaseRestController;
import com.thinkgem.jeesite.common.rest.RestResult;
import com.thinkgem.jeesite.modules.ftc.constant.WishlistTypeEnum;
import com.thinkgem.jeesite.modules.ftc.convert.customer.WishlistConverter;
import com.thinkgem.jeesite.modules.ftc.entity.customer.Customer;
import com.thinkgem.jeesite.modules.ftc.entity.customer.Wishlist;
import com.thinkgem.jeesite.modules.ftc.entity.product.Product;
import com.thinkgem.jeesite.modules.ftc.service.customer.CustomerService;
import com.thinkgem.jeesite.modules.ftc.service.customer.WishlistService;
import com.thinkgem.jeesite.modules.ftc.service.product.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by bingbing on 2017/7/6.
 */
@RestController
@RequestMapping(value = "/rest/ftc/wishlist/")
@Api(value = "收藏管理", description = "收藏")
public class WishlistRestController extends BaseRestController {

    @Autowired
    private WishlistService wishlistService;

    @Autowired
    private ProductService productService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private WishlistConverter wishlistConverter;
    /**
     * 我的收藏
     *
     * @param
     * @return
     */
    @ApiOperation(value = "我的收藏列表", notes = "我收藏的商品和店铺")
    @RequestMapping(value = {"list"}, method = {RequestMethod.POST})
    public RestResult list(@RequestParam("token") String token, @RequestParam("type") String type,
                           HttpServletRequest request, HttpServletResponse response) {
        Customer customer = findCustomerByToken(token);
        if (customer != null) {
            Wishlist wishlist = new Wishlist();
            wishlist.setType(type);
            wishlist.setCustomer(customer);
            Page<Wishlist> wishlistPage = wishlistService.findPage(
                    new Page<Wishlist>(request, response), wishlist
            );
            if(wishlistPage.getCount()==0){
                return new RestResult(CODE_SUCCESS, "没有收藏");
            }
            List<Wishlist> wishlists=new ArrayList<>();
            if(type.equals("1")){
                //商品
                for(Wishlist wish:wishlistPage.getList()){

                    Product product=productService.getWithSpec(wish.getProduct().getId());
                    wish.setProduct(product);
                    wishlists.add(wish);
                }

            }else{
                //店铺
                for(Wishlist wish:wishlistPage.getList()){
                    Customer result = customerService.get(wish.getCustomer());
                    wish.setCustomer(result);
                    wishlists.add(wish);
                }

            }

            return new RestResult(CODE_SUCCESS, MSG_SUCCESS, wishlistConverter.convertListFromModelToDto(wishlists));
        } else {
            return new RestResult(CODE_ERROR, "没有找到用户信息");
        }

    }

    /**
     * 加入收藏
     *
     * @param
     * @return
     */
    @ApiOperation(value = "加入收藏", notes = "我收藏的商品和店铺")
    @RequestMapping(value = {"add"}, method = {RequestMethod.POST})
    public RestResult add(@RequestParam("token") String token, @RequestParam("id") String id,
                          @RequestParam("type") String type) {
        Customer customer = findCustomerByToken(token);
        if (customer != null) {
            Wishlist wishlist = new Wishlist();
            wishlist.setType(type);
            if (WishlistTypeEnum.WISHLIST_PRODUCT.getValue().equals(type)) {
                wishlist.setProduct(new Product(id));
            } else {
                wishlist.setDesigner(new Customer(id));
            }
            wishlist.setCustomer(customer);
            List<Wishlist> result = wishlistService.findList(wishlist);
            if(CollectionUtils.isNotEmpty(result)){
                if (WishlistTypeEnum.WISHLIST_PRODUCT.getValue().equals(type)) {
                    return new RestResult(CODE_ERROR, "您已经收藏过了");
                } else {
                    return new RestResult(CODE_ERROR, "您已经关注过了");
                }

            }else {
                wishlistService.save(wishlist);
            }
            return new RestResult(CODE_SUCCESS, MSG_SUCCESS, null);
        } else {
            return new RestResult(CODE_ERROR, "没有找到用户信息");
        }

    }

    /**
     * 取消收藏
     *
     * @param
     * @return
     */
    @ApiOperation(value = "取消收藏", notes = "取消收藏")
    @RequestMapping(value = {"delete"}, method = {RequestMethod.POST})
    public RestResult delete(@RequestParam("token") String token, @RequestParam("id") String id,@RequestParam("type") String type) {
        Customer customer = findCustomerByToken(token);
        if (customer != null) {
            Wishlist wishlist = new Wishlist();
            if (WishlistTypeEnum.WISHLIST_PRODUCT.getValue().equals(type)) {
                wishlist.setProduct(new Product(id));
            } else {
                wishlist.setDesigner(new Customer(id));
            }
            wishlist.setCustomer(customer);
            List<Wishlist> result = wishlistService.findList(wishlist);
            if(result!=null){
                wishlistService.delete(wishlist);
            }

            return new RestResult(CODE_SUCCESS, MSG_SUCCESS);
        } else {
            return new RestResult(CODE_ERROR, "没有找到用户信息");
        }

    }
}


text:
package net.estinet.gFeatures.Feature.gWarsSuite.Multiplayer.Kits;

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

import net.estinet.gFeatures.API.Inventory.ClearInventory;
import net.estinet.gFeatures.Feature.gWarsSuite.MainMenu.Finish;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import com.shampaggon.crackshot.CSUtility;

public class TierTwo{
	Player p;
	ClearInventory ci = new ClearInventory();
	ItemStack sniper2, shotgun2, special2, autorifle2, ammo, jetpackammo;
	public TierTwo(Player player) {
		p = player;
		sniper2 = createItem(Material.GOLDEN_PICKAXE, ChatColor.AQUA + "Sniper", ChatColor.GOLD + "SilSil69");
		shotgun2 = createItem(Material.GOLDEN_SHOVEL, ChatColor.AQUA + "Shotgun", ChatColor.GOLD + "SPAS Regular");
		special2 = createItem(Material.GOLDEN_HOE, ChatColor.AQUA + "Special", ChatColor.GOLD + "Flamethrower");
		autorifle2 = createItem(Material.GOLDEN_AXE, ChatColor.AQUA + "Auto-Rifle", ChatColor.GOLD + "AK47 Silver");

		ammo = new ItemStack(Material.MELON_SEEDS, 16);
		ItemMeta meta = ammo.getItemMeta();
		meta.setDisplayName(ChatColor.GOLD + "Ammo");
		ammo.setItemMeta(meta);

		jetpackammo = new ItemStack(Material.COAL, 1);
		ItemMeta jmeta = jetpackammo.getItemMeta();
		jmeta.setDisplayName(ChatColor.GOLD + "Jetpack Fuel");
		jetpackammo.setItemMeta(jmeta);
	}
	public void initialize(String value){
		switch(value){
		case "AUTORIFLE":
			autorifle();
			break;
		case "SHOTGUN":
			shotgun();
			break;
		case "SNIPER":
			sniper();
			break;
		case "SPECIAL":
			special();
			break;
		}
	}
	public void autorifle(){
		ci.clearInv(p);
		CSUtility cs = new CSUtility();
		cs.giveWeapon(p, "AK47-Silver", 1);
		cs.giveWeapon(p, "Python", 1);
		Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "jetpacks cheat jetpackplus "+ p.getName());
    	jetpackammo = new ItemStack(Material.COAL, 3);
		ItemMeta jmeta = jetpackammo.getItemMeta();
		jmeta.setDisplayName(ChatColor.GOLD + "Jetpack Fuel");
		jetpackammo.setItemMeta(jmeta);
		finali();
	}
	public void shotgun(){
		ci.clearInv(p);
		CSUtility cs = new CSUtility();
		cs.giveWeapon(p, "SPAS", 1);
		cs.giveWeapon(p, "Python", 1);
		Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "jetpacks cheat jetpack "+ p.getName());
		finali();
	}
	public void sniper(){
		ci.clearInv(p);
		CSUtility cs = new CSUtility();
		cs.giveWeapon(p, "SilSil69", 1);
		cs.giveWeapon(p, "Python", 1);
		Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "jetpacks cheat jetpack "+ p.getName());
		finali();
	}
	public void special(){
		ci.clearInv(p);
		CSUtility cs = new CSUtility();
		cs.giveWeapon(p, "Flamethrower", 1);
		cs.giveWeapon(p, "Python", 1);
		Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "jetpacks cheat jetpack "+ p.getName());
		finali();
	}
	public void interact(PlayerInteractEvent event){
		Player p = event.getPlayer();
		if(p.getInventory().getItemInMainHand().equals(sniper2)){
			sniper();
		}
		else if(p.getInventory().getItemInMainHand().equals(shotgun2)){
			shotgun();
		}
		else if(p.getInventory().getItemInMainHand().equals(special2)){
			special();
		}
		else if(p.getInventory().getItemInMainHand().equals(autorifle2)){
			autorifle();
		}
	}
	public ItemStack createItem(Material material, String name, String ... lore){
		ItemStack item = new ItemStack(material, 1);
		List<String> lores = new ArrayList<>();
		for(String lor : lore){
		lores.add(lor);
		}
		ItemMeta meta = item.getItemMeta();
		meta.setDisplayName(name);
		meta.setLore(lores);
		item.setItemMeta(meta);
		return item;
	}
	public void finali(){
		p.getInventory().setItem(8, ammo);
		p.getInventory().setItem(6, jetpackammo);
		Finish finish = new Finish();
		finish.intialize(p);
	}
}


text:
FROM debian:jessie

RUN useradd -d "/var/jenkins_home" -u 1000 -m -s /bin/bash jenkins
RUN apt-get update && apt-get install -y curl

RUN mkdir -p /var/jenkins_home/plugins
RUN chown -R jenkins:jenkins /var/jenkins_home/plugins

USER jenkins
WORKDIR /var/jenkins_home/plugins

RUN curl -O http://updates.jenkins-ci.org/latest/ant.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/antisamy-markup-formatter.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/build-timeout.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/cloudbees-folder.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/credentials-binding.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/docker-build-step.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/email-ext.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/git.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/git-client.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/gradle.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/handlebars.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/icon-shim.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/junit.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/jquery-detached.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/ldap.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/mapdb-api.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/mailer.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/matrix-auth.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/matrix-project.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/momentjs.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/pam-auth.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/pipeline-build-step.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/pipeline-rest-api.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/pipeline-stage-view.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-scm-step.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/pipeline-stage-view.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/plain-credentials.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/scm-api.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/script-security.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/ssh-credentials.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/ssh-slaves.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/structs.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/swarm.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/token-macro.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/windows-slaves.jpi

RUN curl -O http://updates.jenkins-ci.org/latest/workflow-api.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-job.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-step-api.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-support.jpi
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-multibranch.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-durable-task-step.
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-cps-global-lib.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-cps.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-basic-steps.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/pipeline-stage-step.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/pipeline-input-step.hpi
RUN curl -O http://updates.jenkins-ci.org/latest/workflow-aggregator.hpi

VOLUME ["/var/jenkins_home/plugins"]

CMD ["echo", "Plugin container for Jenkins2"]


text:
<?php

namespace unit\StateMachine\Collection;

use StateMachine\Collection\OutOfRangeException;
use StateMachine\Collection\States;
use StateMachine\State;

class StatesTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var State|\PHPUnit_Framework_MockObject_MockObject
     */
    private $states;

    public function setUp()
    {
        $this->states = new State('foo');
    }

    public function testGet()
    {
        $collection = new States([$this->states]);
        $this->assertEquals($this->states, $collection->get('foo'));
    }

    public function testGetUndefinedOffset()
    {
        $this->expectException(OutOfRangeException::class);
        $this->expectExceptionMessage('Element for offset "undefined" not found');

        $collection = new States();
        $collection->get('undefined');
    }

    public function testAdd()
    {
        $collection = new States([]);
        $collection->add($this->states);
        $this->assertEquals('foo', $collection->get('foo'));
    }

    public function testAll()
    {
        $collection = new States([$this->states]);
        $this->assertEquals(['foo' => $this->states], $collection->all());
    }

    public function testCount()
    {
        $collection = new States([$this->states]);
        $this->assertEquals(1, $collection->count());
    }
}


text:
//
//  LHLoginViewController.m
//  LovingHeart
//
//  Created by Edward Chiang on 2014/3/27.
//  Copyright (c) 2014年 LovineHeart. All rights reserved.
//

#import "LHLoginViewController.h"
#import <SVProgressHUD.h>
#import "LHSignUpViewController.h"
#import <UIAlertView+BlocksKit.h>
#import "LHGraphicImage.h"

@implementation LHLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
      self.fields = PFLogInFieldsDefault | PFLogInFieldsFacebook;
  }
  return self;
}

- (void)viewDidLoad {
  [super viewDidLoad];

  self.signUpController = [[LHSignUpViewController alloc] init];

  self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-red"]];
  self.logInView.usernameField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-red-2"]];
  self.logInView.passwordField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-red-2"]];

  UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lovingheart_black_red_clear_logo"]];
  self.logInView.logo = imageView;
  if (!self.delegate) {
      self.delegate = self;
  }

  self.logInView.passwordForgottenButton.hidden = YES;

}

#pragma mark - PFLogInViewControllerDelegate

/*! @name Responding to Actions */
/// Sent to the delegate when a PFUser is logged in.
- (void)logInViewController:(PFLogInViewController *)logInController didLogInUser:(LHUser *)user {

  [[NSNotificationCenter defaultCenter] postNotificationName:kUserProfileRefreshNotification object:nil];

  [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"Login Success. %@", user.email]];
  [logInController dismissViewControllerAnimated:YES completion:nil];

  if (![user objectForKey:@"name"] || ![user objectForKey:@"avatar"]) {
    // Create request for user's Facebook data
    FBRequest *request = [FBRequest requestForMe];

    // Send request to Facebook
    [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
      if (!error) {
        // result is a dictionary with the user's Facebook data
        NSDictionary *userData = (NSDictionary *)result;

        NSString *facebookID = userData[@"id"];
        NSString *name = userData[@"name"];
        NSString *location = userData[@"location"][@"name"];
        NSString *gender = userData[@"gender"];
        NSString *birthday = userData[@"birthday"];
        NSString *relationship = userData[@"relationship_status"];

        [user setObject:name forKey:@"name"];

        LHGraphicImage *graphicImage = [[LHGraphicImage alloc] init];
        graphicImage.imageType = @"url";
        graphicImage.imageUrl = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", facebookID];
        [graphicImage saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
          if (succeeded) {
            [user setObject:graphicImage forKey:@"avatar"];
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
              NSLog(@"User Object Facebook name, image updated.");
            }];
          }
        }];
      }
    }];
  }

  // Check and ask user to sign up
  BOOL hasAskUserNotification = [[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultHasBeenAskUser];
  if (!hasAskUserNotification) {
    [UIAlertView bk_showAlertViewWithTitle:@"Send message" message:@"Let LovingHeart can push message to me." cancelButtonTitle:@"Cancel" otherButtonTitles:[NSArray arrayWithObjects:@"OK", @"No", nil] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
      NSLog(@"Ask and click: %i", (int)buttonIndex);
      switch (buttonIndex) {
        case 0:
          break;
        case 1:
          [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
          [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kUserDefaultHasBeenAskUser];
          [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kUserDefaultUserWantPushNotification];
          [[NSUserDefaults standardUserDefaults] synchronize];
          break;
        case 2:
          [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kUserDefaultHasBeenAskUser];
          [[NSUserDefaults standardUserDefaults] synchronize];
          break;
        default:
          break;
      }
    }];
  }
}

/// Sent to the delegate when the log in attempt fails.
- (void)logInViewController:(PFLogInViewController *)logInController didFailToLogInWithError:(NSError *)error {
  NSLog(@"didFailToLogInWithError: %@", error);

  [SVProgressHUD showErrorWithStatus:[error.userInfo objectForKey:@"error"]];
}

- (void)logInViewControllerDidCancelLogIn:(PFLogInViewController *)logInController {
  [logInController dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
if ckBlockIp() then
    say_html_error()
elseif not ckWhiteIp() then
    -- the url need check
    if ckUrl() then
        -- the args need check
        ckArgs()
    end
end


text: require 'usesguid'


text:
package org.broadleafcommerce.core.search.service.solr;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.broadleafcommerce.common.exception.ServiceException;
import org.broadleafcommerce.common.locale.domain.Locale;
import org.broadleafcommerce.core.catalog.domain.Product;
import org.broadleafcommerce.core.catalog.domain.Sku;
import org.broadleafcommerce.core.search.domain.Field;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

/**
 * Service exposing several methods for creating a Solr index based on catalog product data.
 *
 * @see org.broadleafcommerce.core.search.service.solr.SolrIndexCachedOperation
 * @author Andre Azzolini (apazzolini)
 * @author Jeff Fischer
 */
public interface SolrIndexService {

    /**
     * Rebuilds the current index.
     *
     * @throws IOException
     * @throws ServiceException
     */
    public void rebuildIndex() throws ServiceException, IOException;

    /**
     * Allows a query to determine if a full reindex is currently being performed.
     *
     * NOTE: There is no guarantee that reindexing is not happening in another process or another server.  This
     * method simply indicates whether this instance, within a single JVM is currently performing a reindex.
     *
     * @return
     */
    public boolean isReindexInProcess();

    /**
     * The internal method for building indexes. This is exposed via this interface in case someone would like to
     * more granularly control the indexing strategy.
     *
     * @see #restoreState(Object[])
     * @param page
     * @param pageSize
     * @param useReindexServer - if set to false will index directly on the primary server
     * @throws ServiceException
     */
    public void buildIncrementalIndex(int page, int pageSize, boolean useReindexServer) throws ServiceException;

    /**
     * This can be used in lieu of passing in page sizes,  The reason is that one might want to apply filters or only
     * index certain skus.
     * @param skus
     * @param useReindexServer
     * @throws ServiceException
     */
    public void buildIncrementalSkuIndex(List<Sku> skus, boolean useReindexServer) throws ServiceException;

    /**
     * This can be used in lieu of passing in page sizes,  The reason is that one might want to apply filters or only
     * index certain products.
     * @param products
     * @param useReindexServer
     * @throws ServiceException
     */
    public void buildIncrementalProductIndex(List<Product> products, boolean useReindexServer) throws ServiceException;

    /**
     * Saves some global context that might be altered during indexing.
     *
     * @return
     */
    public Object[] saveState();

    /**
     * Restores state that was saved prior to indexing that might have been altered.
     *
     * @see #saveState()
     * @param pack
     */
    public void restoreState(Object[] pack);

    /**
     * Triggers the Solr optimize index function on the given server.
     *
     * NOTE: This should rarely be called.
     *
     * @param server
     * @throws ServiceException
     * @throws IOException
     */
    public void optimizeIndex(SolrServer server) throws ServiceException, IOException;

    /**
     * Allows a commit to be called.  By default, the details of the commit will depend on system properties, including:
     *
     * solr.index.commit - if false, then no commit will be performed. autoCommit (and autoSoftCommit) should be configured in Solr.
     * solr.index.softCommit - indicates if a soft commit should be performed
     * solr.index.waitSearcher - indicates if the process should wait for a searcher to be configured
     * solr.index.waitFlush - indicates if the process should wait for a flush to disk
     *
     * @param server
     * @throws ServiceException
     * @throws IOException
     */

    public void commit(SolrServer server) throws ServiceException, IOException;

    /**
     * This allows an external caller to force a commit to the SolrServer.  See Solr Documentation for
     * additional details.  If using softCommit, you should ensure that a hardCommit is performed, either
     * using autoCommit, or at the end of the commit process to flush the changes to the disk.
     *
     * Note that this method will force a commit even if solr.index.commit=false
     *
     * @param server - the SolrServer to update
     * @param softCommit - soft commit is an efficient commit that does not write the data to the file system
     * @param waitSearcher - whether or not to wait for a new searcher to be created
     * @param waitFlush - whether or not to wait for a flush to disk.
     * @throws ServiceException
     * @throws IOException
     */
    public void commit(SolrServer server, boolean softCommit, boolean waitSearcher, boolean waitFlush) throws ServiceException, IOException;

    /**
     * Prints out the docs to the trace logger
     *
     * @param documents
     */
    public void logDocuments(Collection<SolrInputDocument> documents);

    /**
     * @return a list of all possible locale prefixes to consider
     */
    public List<Locale> getAllLocales();

    /**
     * Given a product, fields that relate to that product, and a list of locales and pricelists, builds a
     * SolrInputDocument to be added to the Solr index.
     *
     * @param product
     * @param fields
     * @param locales
     * @return the document
     */
    public SolrInputDocument buildDocument(Product product, List<Field> fields, List<Locale> locales);

    /**
     * Given a sku, fields that relate to that sku, and a list of locales and pricelists, builds a
     * SolrInputDocument to be added to the Solr index.
     *
     * @param sku
     * @param fields
     * @param locales
     * @return the document
     */
    public SolrInputDocument buildDocument(Sku sku, List<Field> fields, List<Locale> locales);

    /**
     * SolrIndexService exposes {@link #buildIncrementalIndex(int, int, boolean)}.
     * By wrapping the call to this method inside of a {@link org.broadleafcommerce.core.search.service.solr.SolrIndexCachedOperation.CacheOperation},
     * a single cache will be used for all the contained calls to buildIncrementalIndex. Here's an example:
     * {@code
     *  performCachedOperation(new SolrIndexCachedOperation.CacheOperation() {
     *        @Override
     *        public void execute() throws ServiceException {
     *            int page = 0;
     *            while ((page * pageSize) < numProducts) {
     *                buildIncrementalIndex(page, pageSize);
     *                page++;
     *            }
     *        }
     *    });
     * }
     * Note {@link #rebuildIndex()} already internally wraps its call using CacheOperation, so it is not necessary to call performCacheOperation
     * for calls to rebuildIndex().
     *
     * @param cacheOperation the block of code to perform using a single cache for best performance
     * @throws ServiceException
     */
    public void performCachedOperation(SolrIndexCachedOperation.CacheOperation cacheOperation) throws ServiceException;
}


text:
layout: tag
section-type: tag
title: swagger
---
## Tag


text:
import { CallbackPromise } from '../../utils.js';
import Layer from '../Layer.js';
import PCCCPacket from './packet.js';

function incrementTransaction(self) {
  self._transaction++;
  return self._transaction % 0x10000;
}

function getError(status) {
  if (status.code === 0) return null;

  if (status.extended.description != null && status.extended.description.length > 0) {
    return status.extended.description;
  }

  return status.description;
}

const Commands = Object.freeze({
  Connected: 0x0A,
  Unconnected: 0x0B,
});

function send(self, internal, request, contextOrCallback) {
  let context;
  if (internal) {
    if (typeof contextOrCallback === 'function') {
      context = self.contextCallback(contextOrCallback);
    }
  } else {
    context = contextOrCallback;
  }

  self.setContextForID(request.transaction, {
    context,
    internal,
    request,
  });

  self.send(request.encode(), null, false);
}

/**
 * Uses transactions to map responses to requests
 */

export default class PCCCLayer extends Layer {
  constructor(lowerLayer) {
    super('pccc', lowerLayer);
    this._transaction = 0;
  }

  wordRangeRead(address, words, callback) {
    if (callback == null && typeof words === 'function') {
      callback = words;
      words = undefined;
    }

    if (words == null) {
      words = 1;
    }

    return CallbackPromise(callback, (resolver) => {
      const message = PCCCPacket.WordRangeReadRequest(
        incrementTransaction(this),
        address,
        words,
      );

      send(this, true, message, (error, reply) => {
        if (error) {
          resolver.reject(error, reply);
        } else {
          resolver.resolve(reply.data);
        }
      });
    });
  }

  typedRead(address, items, callback) {
    if (callback == null && typeof items === 'function') {
      callback = items;
      items = undefined;
    }

    return CallbackPromise(callback, (resolver) => {
      const itemsSpecified = items != null;

      if (itemsSpecified) {
        if ((!Number.isFinite(items) || items <= 0 || items > 0xFFFF)) {
          resolver.reject('If specified, items must be a positive integer between 1 and 65535');
          return;
        }
      } else {
        items = 1;
      }

      const message = PCCCPacket.TypedReadRequest(
        incrementTransaction(this),
        address,
        items,
      );

      send(this, true, message, (error, reply) => {
        if (error) {
          resolver.reject(error, reply);
        } else {
          const value = PCCCPacket.ParseTypedReadData(reply.data);
          if (items === 1 && Array.isArray(value) && value.length > 0) {
            resolver.resolve(value[0]);
          } else {
            resolver.resolve(value);
          }
        }
      });
    });
  }

  /**
   * value argument can be an array of values
   */
  typedWrite(address, value, callback) {
    return CallbackPromise(callback, (resolver) => {
      if (value == null) {
        resolver.reject(`Unable to write value: ${value}`);
        return;
      }

      value = Array.isArray(value) ? value : [value];

      const message = PCCCPacket.TypedWriteRequest(
        incrementTransaction(this),
        address,
        value,
      );

      send(this, true, message, (error, reply) => {
        if (error) {
          resolver.reject(error, reply);
        } else {
          resolver.resolve(reply);
        }
      });
    });
  }

  // unprotectedRead(address, size, callback) {
  //   if (callback == null) return;

  //   if (size === 0 || size % 2 !== 0) {
  //     callback('size must be an even number');
  //     return;
  //   }

  //   let transaction = incrementTransaction(this);
  //   let message = PCCCPacket.UnprotectedReadRequest(transaction, address, size);

  //   this.send(message, INFO, false, this.contextCallback(function(error, reply) {
  //     if (error) {
  //       callback(error);
  //     } else {
  //       callback(null, reply);
  //     }
  //   }, transaction));
  // }

  diagnosticStatus(callback) {
    return CallbackPromise(callback, (resolver) => {
      const message = PCCCPacket.DiagnosticStatusRequest(
        incrementTransaction(this),
      );

      send(this, true, message, (error, reply) => {
        if (error) {
          resolver.reject(error, reply);
        } else {
          resolver.resolve(reply.data);
        }
      });
    });
  }

  echo(data, callback) {
    return CallbackPromise(callback, (resolver) => {
      const message = PCCCPacket.EchoRequest(
        incrementTransaction(this),
        data,
      );

      send(this, true, message, (error, reply) => {
        if (error) {
          resolver.reject(error, reply);
        } else {
          resolver.resolve(reply.data);
        }
      });
    });
  }

  /** For sending CIP requests over PCCC */
  sendNextMessage() {
    const request = this.getNextRequest();
    if (request != null) {
      // requests can either be
      // - unconnected (0x0B)
      // - connected (0x0A)

      // Fragmentation protocol is currently not supported

      let packet;
      const transaction = incrementTransaction(this);

      const { info, message } = request;

      if (info != null && info.connectionID != null && info.transportHeader != null) {
        const data = Buffer.allocUnsafe(6 + message.length);
        data.writeUInt8(0, 0); // FNC
        data.writeUInt8(0, 1); // Extra
        data.writeUInt16LE(info.connectionID, 2);
        data.writeUInt16LE(info.transportHeader, 4);
        message.copy(data, 6);
        packet = new PCCCPacket(Commands.Connected, 0, transaction, data);
      } else {
        const data = Buffer.allocUnsafe(2 + message.length);
        data.writeUInt8(0, 0); // FNC
        data.writeUInt8(0, 1); // Extra
        message.copy(data, 2);
        packet = new PCCCPacket(Commands.Unconnected, 0, transaction, data);
      }

      send(this, false, packet, request.context);

      setImmediate(() => this.sendNextMessage());
    }
  }

  handleData(data, info, context) {
    const packet = PCCCPacket.fromBufferReply(data, { current: 0 });

    const savedContext = this.getContextForID(packet.transaction);
    if (!savedContext) {
      console.log('PCCC Layer unhandled data', data, info, context);
      return;
    }

    if (savedContext.internal) {
      const callback = this.callbackForContext(savedContext.context);
      if (callback != null) {
        callback(getError(packet.status), packet, info);
        return;
      }
    }

    this.forward(packet.data, info, savedContext.context);
  }
}

/*
  PLC-2 Communication Commands
    -Uprotected Read
    -Protected Write
    -Uprotected Write
    -Protected Bit Write
    -Unprotected Bit Write

  PLC-5 Communication Commands
    -Read MOdify Write
    -Read Modify Write N
    -Typed Read
    -Typed Write
    -Word Range Read
    -Word Range Write
    -Bit Write

  SLC Communication Commands
    -SLC Protected Typed Logical Read with 3 Address Fields
    -SLC Protected Typed Logical Write with 3 Address Fields
    -SLC Protected Typed Logical Read with 2 Address Fields
    -SLC Protected Typed Logical Write with 2 Address Fields
*/

// /** Ref. CIP and PCCC v1, Appendix B, pg. 17 */
// const FragmentationFunctions = Object.freeze({
//   Only: 0x00,
//   FirstRequest: 0x01,
//   Middle: 0x02,
//   Last: 0x03,
//   FirstResponse: 0x04,
//   SendMore: 0x05,
//   Abort: 0x06,
//   AckResponse: 0x07,
//   NakResponse: 0x08
// });

// class Fragger {
//   constructor(data, info) {
//     this.data = data;
//     this.info = info || {};
//     this.connected = this.info.connectionID && this.info.transportHeader;
//   }
// }


text:
<rss version="2.0">
<channel>
<item>

</item>
</channel>
</rss>


text:
var config = require('../config')
var fs = require('../utils/fs-plus2')
var consts = require('./consts')
var _ = require('lodash')
var logger = require('./logger')
  // it's not reliable in multi process calling
var tmpdir = config.paths.tmp
var expire = 3600 * 1000
var __DATA__ = {}

function createTemp(createData, prefix) {
  prefix = prefix || ''
  if (typeof createData === 'string') {
    prefix = createData
    createData = null
  }
  return {
    createData: createData,
    prefix: prefix,
    isExpired: function(tempData, lastModifyTime) {
      return false
    },
    expiredBy: function(isExpired) {
      this.isExpired = isExpired
      return this
    },
    get: function(name, defaults) {
      var fullName = prefix + name
      var tempFile = tmpdir + '/' + fullName
      var data = '',
        tempContent, lastModifyTime;
      if (fullName in __DATA__) {
        var tmpData = __DATA__[fullName]
        data = tmpData.data
        lastModifyTime = tmpData.lastModifyTime
      } else if (fs.existsSync(tempFile)) {
        tempContent = fs.readFileSync(tempFile, 'utf-8')
        var tmpData
        try {
          tmpData = JSON.parse(tempContent)
          __DATA__[fullName] = tmpData
          data = tmpData.data
          lastModifyTime = tmpData.lastModifyTime
        } catch (e) {
          logger.error(e)
        }
      }

      if (!data || this.isExpired(name, data, lastModifyTime)) { //exists temp and it's expired
        try{
          data = this.createData && this.createData(name)
        }catch(e){
          logger.warn(e)
        }
        this.set(name, data)
      }
      return data || defaults || null
    },
    set: function(name, value) {
      var fullName = prefix + name
      var tempFile = tmpdir + '/' + fullName
      if (value === null) {
        fs.removeSync(tempFile)
        delete __DATA__[fullName]
      } else {
        var tempData = {
          data: value,
          lastModifyTime: new Date().getTime()
        }
        var tempContent = JSON.stringify(tempData)
        fs.writeFileSync(tempFile, tempContent, 'utf-8')
        __DATA__[fullName] = tempData
      }
      return value
    }
  }
}

var tempInstance = createTemp()
module.exports = {
  TIME_EXPIRE: function(data, lastModifyTime) {
    if (lastModifyTime + expire < new Date().getTime()) {
      return true
    }
    return false
  },
  create: createTemp,
  temp: tempInstance,
  getBuildInfo: function(name, defaults) {
    var buildInfo = this.get('buildInfo') || {}
    defaults = defaults === undefined ? null : defaults
    return buildInfo[name] || defaults
  },
  updateBuildInfo: function(props) {
    var buildInfo = this.get('buildInfo') || {}
    return this.set('buildInfo', _.merge(buildInfo, props))
  },
  clear: function() {
    __DATA__ = {}
    fs.removeSync(config.paths.tmp)
  }
}
_.assign(module.exports, tempInstance)


text:
//---------------------------------------------------------------------------
//
// <copyright file="Transform3DGroup.cs" company="Microsoft">
//    Copyright (C) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------

using MS.Internal;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Markup;
using System.Windows.Media.Media3D.Converters;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using System.Windows.Media.Imaging;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;

namespace System.Windows.Media.Media3D
{

    sealed partial class Transform3DGroup : Transform3D
    {
        //------------------------------------------------------
        //
        //  Public Methods
        //
        //------------------------------------------------------

        #region Public Methods

        /// <summary>
        ///     Shadows inherited Clone() with a strongly typed
        ///     version for convenience.
        /// </summary>
        public new Transform3DGroup Clone()
        {
            return (Transform3DGroup)base.Clone();
        }

        /// <summary>
        ///     Shadows inherited CloneCurrentValue() with a strongly typed
        ///     version for convenience.
        /// </summary>
        public new Transform3DGroup CloneCurrentValue()
        {
            return (Transform3DGroup)base.CloneCurrentValue();
        }

        #endregion Public Methods

        //------------------------------------------------------
        //
        //  Public Properties
        //
        //------------------------------------------------------

        private static void ChildrenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

            // The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
            // will promote the property value from a default value to a local value. This is technically a sub-property
            // change because the collection was changed and not a new collection set (GeometryGroup.Children.
            // Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
            // the default value to the compositor. If the property changes from a default value, the new local value
            // needs to be marshalled to the compositor. We detect this scenario with the second condition
            // e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
            // Default and the NewValueSource will be Local.
            if (e.IsASubPropertyChange &&
               (e.OldValueSource == e.NewValueSource))
            {
                return;
            }

            Transform3DGroup target = ((Transform3DGroup) d);

            // If this is both non-null and mutable, we need to unhook the Changed event.
            Transform3DCollection oldCollection = null;
            Transform3DCollection newCollection = null;

            if ((e.OldValueSource != BaseValueSourceInternal.Default) || e.IsOldValueModified)
            {
                oldCollection = (Transform3DCollection) e.OldValue;
                if ((oldCollection != null) && !oldCollection.IsFrozen)
                {
                    oldCollection.ItemRemoved -= target.ChildrenItemRemoved;
                    oldCollection.ItemInserted -= target.ChildrenItemInserted;
                }
            }

            // If this is both non-null and mutable, we need to hook the Changed event.
            if ((e.NewValueSource != BaseValueSourceInternal.Default) || e.IsNewValueModified)
            {
                newCollection = (Transform3DCollection) e.NewValue;
                if ((newCollection != null) && !newCollection.IsFrozen)
                {
                    newCollection.ItemInserted += target.ChildrenItemInserted;
                    newCollection.ItemRemoved += target.ChildrenItemRemoved;
                }
            }
            if (oldCollection != newCollection && target.Dispatcher != null)
            {
                using (CompositionEngineLock.Acquire())
                {
                    DUCE.IResource targetResource = (DUCE.IResource)target;
                    int channelCount = targetResource.GetChannelCount();

                    for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
                    {
                        DUCE.Channel channel = targetResource.GetChannel(channelIndex);
                        Debug.Assert(!channel.IsOutOfBandChannel);
                        Debug.Assert(!targetResource.GetHandle(channel).IsNull);
                        // resource shouldn't be null because
                        // 1) If the field is one of our collections, we don't allow null elements
                        // 2) Codegen already made sure the collection contains DUCE.IResources
                        // ... so we'll Assert it

                        if (newCollection != null)
                        {
                            int count = newCollection.Count;
                            for (int i = 0; i < count; i++)
                            {
                                DUCE.IResource resource = newCollection.Internal_GetItem(i) as DUCE.IResource;
                                Debug.Assert(resource != null);
                                resource.AddRefOnChannel(channel);
                            }
                        }

                        if (oldCollection != null)
                        {
                            int count = oldCollection.Count;
                            for (int i = 0; i < count; i++)
                            {
                                DUCE.IResource resource = oldCollection.Internal_GetItem(i) as DUCE.IResource;
                                Debug.Assert(resource != null);
                                resource.ReleaseOnChannel(channel);
                            }
                        }
                    }
                }
            }
            target.PropertyChanged(ChildrenProperty);
        }

        #region Public Properties

        /// <summary>
        ///     Children - Transform3DCollection.  Default value is new FreezableDefaultValueFactory(Transform3DCollection.Empty).
        /// </summary>
        public Transform3DCollection Children
        {
            get
            {
                return (Transform3DCollection) GetValue(ChildrenProperty);
            }
            set
            {
                SetValueInternal(ChildrenProperty, value);
            }
        }

        #endregion Public Properties

        //------------------------------------------------------
        //
        //  Protected Methods
        //
        //------------------------------------------------------

        #region Protected Methods

        /// <summary>
        /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
        /// </summary>
        /// <returns>The new Freezable.</returns>
        protected override Freezable CreateInstanceCore()
        {
            return new Transform3DGroup();
        }

        #endregion ProtectedMethods

        //------------------------------------------------------
        //
        //  Internal Methods
        //
        //------------------------------------------------------

        #region Internal Methods

        /// <SecurityNote>
        ///     Critical: This code calls into an unsafe code block
        ///     TreatAsSafe: This code does not return any critical data.It is ok to expose
        ///     Channels are safe to call into and do not go cross domain and cross process
        /// </SecurityNote>
        [SecurityCritical,SecurityTreatAsSafe]
        internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
        {
            // If we're told we can skip the channel check, then we must be on channel
            Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));

            if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
            {
                base.UpdateResource(channel, skipOnChannelCheck);

                // Read values of properties into local variables
                Transform3DCollection vChildren = Children;

                // Store the count of this resource's contained collections in local variables.
                int ChildrenCount = (vChildren == null) ? 0 : vChildren.Count;

                // Pack & send command packet
                DUCE.MILCMD_TRANSFORM3DGROUP data;
                unsafe
                {
                    data.Type = MILCMD.MilCmdTransform3DGroup;
                    data.Handle = _duceResource.GetHandle(channel);
                    data.ChildrenSize = (uint)(sizeof(DUCE.ResourceHandle) * ChildrenCount);

                    channel.BeginCommand(
                        (byte*)&data,
                        sizeof(DUCE.MILCMD_TRANSFORM3DGROUP),
                        (int)(data.ChildrenSize)
                        );

                    // Copy this collection's elements (or their handles) to reserved data
                    for(int i = 0; i < ChildrenCount; i++)
                    {
                        DUCE.ResourceHandle resource = ((DUCE.IResource)vChildren.Internal_GetItem(i)).GetHandle(channel);;
                        channel.AppendCommandData(
                            (byte*)&resource,
                            sizeof(DUCE.ResourceHandle)
                            );
                    }

                    channel.EndCommand();
                }
            }
        }
        internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
        {

                if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_TRANSFORM3DGROUP))
                {

                    Transform3DCollection vChildren = Children;

                    if (vChildren != null)
                    {
                        int count = vChildren.Count;
                        for (int i = 0; i < count; i++)
                        {
                            ((DUCE.IResource) vChildren.Internal_GetItem(i)).AddRefOnChannel(channel);
                        }
                    }
                    AddRefOnChannelAnimations(channel);

                    UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
                }

                return _duceResource.GetHandle(channel);

        }
        internal override void ReleaseOnChannelCore(DUCE.Channel channel)
        {

                Debug.Assert(_duceResource.IsOnChannel(channel));

                if (_duceResource.ReleaseOnChannel(channel))
                {

                    Transform3DCollection vChildren = Children;

                    if (vChildren != null)
                    {
                        int count = vChildren.Count;
                        for (int i = 0; i < count; i++)
                        {
                            ((DUCE.IResource) vChildren.Internal_GetItem(i)).ReleaseOnChannel(channel);
                        }
                    }
                    ReleaseOnChannelAnimations(channel);

                }

        }
        internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
        {
            // Note that we are in a lock here already.
            return _duceResource.GetHandle(channel);
        }
        internal override int GetChannelCountCore()
        {
            // must already be in composition lock here
            return _duceResource.GetChannelCount();
        }
        internal override DUCE.Channel GetChannelCore(int index)
        {
            // Note that we are in a lock here already.
            return _duceResource.GetChannel(index);
        }

        private void ChildrenItemInserted(object sender, object item)
        {
            if (this.Dispatcher != null)
            {
                DUCE.IResource thisResource = (DUCE.IResource)this;
                using (CompositionEngineLock.Acquire())
                {
                    int channelCount = thisResource.GetChannelCount();

                    for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
                    {
                        DUCE.Channel channel = thisResource.GetChannel(channelIndex);
                        Debug.Assert(!channel.IsOutOfBandChannel);
                        Debug.Assert(!thisResource.GetHandle(channel).IsNull);

                        // We're on a channel, which means our dependents are also on the channel.
                        DUCE.IResource addResource = item as DUCE.IResource;
                        if (addResource != null)
                        {
                            addResource.AddRefOnChannel(channel);
                        }

                        UpdateResource(channel, true /* skip on channel check */);
                    }
                }
            }
        }

        private void ChildrenItemRemoved(object sender, object item)
        {
            if (this.Dispatcher != null)
            {
                DUCE.IResource thisResource = (DUCE.IResource)this;
                using (CompositionEngineLock.Acquire())
                {
                    int channelCount = thisResource.GetChannelCount();

                    for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
                    {
                        DUCE.Channel channel = thisResource.GetChannel(channelIndex);
                        Debug.Assert(!channel.IsOutOfBandChannel);
                        Debug.Assert(!thisResource.GetHandle(channel).IsNull);

                        UpdateResource(channel, true /* is on channel check */);

                        // We're on a channel, which means our dependents are also on the channel.
                        DUCE.IResource releaseResource = item as DUCE.IResource;
                        if (releaseResource != null)
                        {
                            releaseResource.ReleaseOnChannel(channel);
                        }
                    }
                }
            }
        }

        #endregion Internal Methods

        //------------------------------------------------------
        //
        //  Internal Properties
        //
        //------------------------------------------------------

        #region Internal Properties

        //
        //  This property finds the correct initial size for the _effectiveValues store on the
        //  current DependencyObject as a performance optimization
        //
        //  This includes:
        //    Children
        //
        internal override int EffectiveValuesInitialSize
        {
            get
            {
                return 1;
            }
        }

        #endregion Internal Properties

        //------------------------------------------------------
        //
        //  Dependency Properties
        //
        //------------------------------------------------------

        #region Dependency Properties

        /// <summary>
        ///     The DependencyProperty for the Transform3DGroup.Children property.
        /// </summary>
        public static readonly DependencyProperty ChildrenProperty;

        #endregion Dependency Properties

        //------------------------------------------------------
        //
        //  Internal Fields
        //
        //------------------------------------------------------

        #region Internal Fields

        internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();

        internal static Transform3DCollection s_Children = Transform3DCollection.Empty;

        #endregion Internal Fields

        #region Constructors

        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------

        static Transform3DGroup()
        {
            // We check our static default fields which are of type Freezable
            // to make sure that they are not mutable, otherwise we will throw
            // if these get touched by more than one thread in the lifetime
            // of your app.  (Windows OS Bug #947272)
            //
            Debug.Assert(s_Children == null || s_Children.IsFrozen,
                "Detected context bound default value Transform3DGroup.s_Children (See OS Bug #947272).");

            // Initializations
            Type typeofThis = typeof(Transform3DGroup);
            ChildrenProperty =
                  RegisterProperty("Children",
                                   typeof(Transform3DCollection),
                                   typeofThis,
                                   new FreezableDefaultValueFactory(Transform3DCollection.Empty),
                                   new PropertyChangedCallback(ChildrenPropertyChanged),
                                   null,
                                   /* isIndependentlyAnimated  = */ false,
                                   /* coerceValueCallback */ null);
        }

        #endregion Constructors

    }
}


text:
package net.emaze.dysfunctional.collections;

import java.util.Collection;
import net.emaze.dysfunctional.contracts.dbc;
import java.util.function.Predicate;

/**
 * A predicate accepting elements contained in the collection.
 *
 * @param <T> the element type
 * @author rferranti
 */
public class IsContainedIn<T> implements Predicate<T> {

    private final Collection<T> collection;

    public IsContainedIn(Collection<T> collection) {
        dbc.precondition(collection != null, "cannot create IsContainedIn predicate with a null collection");
        this.collection = collection;
    }

    @Override
    public boolean test(T element) {
        return collection.contains(element);
    }
}


text:
/*
 * (c) 2010 by David Nies (nies.david@googlemail.com)
 *     http://www.twitter.com/Sh4pe
 *
 * Use of this source code is governed by a license
 * that can be found in the LICENSE file.
 */
package komoku

import (
    "testing"
    //"fmt"
)

// Stuff for TestParseLine
type testParseLineCase struct {
    Line string
    Empty, HasId bool
    Id uint
    CommandName string
    Args []string
}

func TestParseLine(t *testing.T) {
    cases := []testParseLineCase {
        testParseLineCase{
            Line: "33 command_name argument1\n",
            Empty: false,
            HasId: true,
            Id: 33,
            CommandName: "command_name",
            Args: []string {
                "argument1",
            },
        },
        testParseLineCase{
            Line: "33 command_name argument1 argument2\n",
            Empty: false,
            HasId: true,
            Id: 33,
            CommandName: "command_name",
            Args: []string {
                "argument1",
                "argument2",
            },
        },
        testParseLineCase{
            Line: "33 command_name\n",
            Empty: false,
            HasId: true,
            Id: 33,
            CommandName: "command_name",
            Args: []string { },
        },
        testParseLineCase{
            Line: "command_name argument1 argument2\n",
            Empty: false,
            HasId: false,
            Id: 0,
            CommandName: "command_name",
            Args: []string {
                "argument1",
                "argument2",
            },
        },
        testParseLineCase{
            Line: "command_name argument1 \n",
            Empty: false,
            HasId: false,
            Id: 0,
            CommandName: "command_name",
            Args: []string {
                "argument1",
            },
        },
        testParseLineCase{
            Line: "command_name \n",
            Empty: false,
            HasId: false,
            Id: 0,
            CommandName: "command_name",
            Args: []string { },
        },
        testParseLineCase{
            Line: "\n",
            Empty: true,
            HasId: false,
            Id: 0,
            CommandName: "",
            Args: []string { },
        },
        testParseLineCase{
            Line: "23\n",
            Empty: true,
            HasId: false,
            Id: 0,
            CommandName: "",
            Args: []string { },
        },
    }

    obj := NewGTPObject()
    for _, testCase := range cases {
        failed := false
        empty, hasId, id, commandName, args := obj.parseLine(testCase.Line)
        if empty != testCase.Empty { failed = true }
        if hasId != testCase.HasId { failed = true }
        if id != testCase.Id { failed = true }
        if commandName != testCase.CommandName { failed = true }
        if len(args) != len(testCase.Args) {
            failed = true
        } else {
            for i, a := range args {
                if testCase.Args[i] != a {
                    failed = true
                    break
                }
            }
        }
        if failed {
            // fmt.Printf("empty: %v\nhasId: %v\nid: %v\ncommandName: %v\nargs: %v\n",
                // testCase.Empty, testCase.HasId, testCase.Id, testCase.CommandName, testCase.Args)
            t.Fatalf("parseLine seems not to parse this line well:\n%s", testCase.Line)
        }
    }

    return
}

func Testsuite() []testing.Test {
    return []testing.Test { testing.Test{"TestParseLine", TestParseLine},
                          }
}


text:
using UnityEngine;
using System.Collections;

public class testSocket : MonoBehaviour {

    void Awake()
    {
        SocketClient.setServer("127.0.0.1", 10019);
    }

	// Use this for initialization
	void Start () {
        //SocketClient.send("123");
        ItemData itemData =  ItemData.GetItemDataFromNetwork(4);
        print(itemData.id);
        print(itemData.name);
        print(itemData.addHp);
        print(itemData.addAttack);
        print(itemData.addDefence);
        print(itemData.addGold);

        MonsterData monsterData = MonsterData.GetMonsterDataFromNetwork(4);
        print(monsterData.id);
        print(monsterData.name);
        print(monsterData.hp);
        print(monsterData.attack);
        print(monsterData.defence);
        print(monsterData.gold);
    }

	// Update is called once per frame
	void Update () {

	}
}


text:
package io.druid.query.aggregation.histogram;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import io.druid.data.input.Row;
import io.druid.query.QueryRunner;
import io.druid.query.QueryRunnerTestHelper;
import io.druid.query.aggregation.PostAggregator;
import io.druid.query.dimension.DefaultDimensionSpec;
import io.druid.query.dimension.DimensionSpec;
import io.druid.query.groupby.GroupByQuery;
import io.druid.query.groupby.GroupByQueryConfig;
import io.druid.query.groupby.GroupByQueryRunnerFactory;
import io.druid.query.groupby.GroupByQueryRunnerTest;
import io.druid.query.groupby.GroupByQueryRunnerTestHelper;
import io.druid.query.groupby.orderby.DefaultLimitSpec;
import io.druid.query.groupby.orderby.OrderByColumnSpec;
import io.druid.query.groupby.strategy.GroupByStrategySelector;
import io.druid.segment.TestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 */
@RunWith(Parameterized.class)
public class ApproximateHistogramGroupByQueryTest
{
  private final QueryRunner<Row> runner;
  private GroupByQueryRunnerFactory factory;

  @Parameterized.Parameters
  public static Iterable<Object[]> constructorFeeder() throws IOException
  {
    final GroupByQueryConfig defaultConfig = new GroupByQueryConfig();
    final GroupByQueryConfig singleThreadedConfig = new GroupByQueryConfig()
    {
      @Override
      public boolean isSingleThreaded()
      {
        return true;
      }
    };
    final GroupByQueryConfig v2Config = new GroupByQueryConfig()
    {
      @Override
      public String getDefaultStrategy()
      {
        return GroupByStrategySelector.STRATEGY_V2;
      }
    };

    defaultConfig.setMaxIntermediateRows(10000);
    singleThreadedConfig.setMaxIntermediateRows(10000);

    final List<Object[]> constructors = Lists.newArrayList();
    final List<GroupByQueryConfig> configs = ImmutableList.of(
        defaultConfig,
        singleThreadedConfig,
        v2Config
    );

    for (GroupByQueryConfig config : configs) {
      final GroupByQueryRunnerFactory factory = GroupByQueryRunnerTest.makeQueryRunnerFactory(config);
      for (QueryRunner<Row> runner : QueryRunnerTestHelper.makeQueryRunners(factory)) {
        constructors.add(new Object[]{factory, runner});
      }
    }

    return constructors;
  }

  public ApproximateHistogramGroupByQueryTest(GroupByQueryRunnerFactory factory, QueryRunner runner)
  {
    this.factory = factory;
    this.runner = runner;
  }

  @Test
  public void testGroupByWithApproximateHistogramAgg()
  {
    ApproximateHistogramAggregatorFactory aggFactory = new ApproximateHistogramAggregatorFactory(
        "apphisto",
        "index",
        10,
        5,
        Float.NEGATIVE_INFINITY,
        Float.POSITIVE_INFINITY
    );

    GroupByQuery query = new GroupByQuery.Builder()
        .setDataSource(QueryRunnerTestHelper.dataSource)
        .setGranularity(QueryRunnerTestHelper.allGran)
        .setDimensions(
            Arrays.<DimensionSpec>asList(
                new DefaultDimensionSpec(
                    QueryRunnerTestHelper.marketDimension,
                    "marketalias"
                )
            )
        )
        .setInterval(QueryRunnerTestHelper.fullOnInterval)
        .setLimitSpec(
            new DefaultLimitSpec(
                Lists.newArrayList(
                    new OrderByColumnSpec(
                        "marketalias",
                        OrderByColumnSpec.Direction.DESCENDING
                    )
                ), 1
            )
        )
        .setAggregatorSpecs(
            Lists.newArrayList(
                QueryRunnerTestHelper.rowsCount,
                aggFactory
            )
        )
        .setPostAggregatorSpecs(
            Arrays.<PostAggregator>asList(
                new QuantilePostAggregator("quantile", "apphisto", 0.5f)
            )
        )
        .build();

    List<Row> expectedResults = Arrays.asList(
        GroupByQueryRunnerTestHelper.createExpectedRow(
            "1970-01-01T00:00:00.000Z",
            "marketalias", "upfront",
            "rows", 186L,
            "quantile", 880.9881f,
            "apphisto",
            new Histogram(
                new float[]{
                    214.97299194335938f,
                    545.9906005859375f,
                    877.0081787109375f,
                    1208.0257568359375f,
                    1539.0433349609375f,
                    1870.06103515625f
                },
                new double[]{
                    0.0, 67.53287506103516, 72.22068786621094, 31.984678268432617, 14.261756896972656
                }
            )
        )
    );

    Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query);
    TestHelper.assertExpectedObjects(expectedResults, results, "approx-histo");
  }

  @Test(expected = IllegalArgumentException.class)
  public void testGroupByWithSameNameComplexPostAgg()
  {
    ApproximateHistogramAggregatorFactory aggFactory = new ApproximateHistogramAggregatorFactory(
        "quantile",
        "index",
        10,
        5,
        Float.NEGATIVE_INFINITY,
        Float.POSITIVE_INFINITY
    );

    GroupByQuery query = new GroupByQuery.Builder()
        .setDataSource(QueryRunnerTestHelper.dataSource)
        .setGranularity(QueryRunnerTestHelper.allGran)
        .setDimensions(
            Arrays.<DimensionSpec>asList(
                new DefaultDimensionSpec(
                    QueryRunnerTestHelper.marketDimension,
                    "marketalias"
                )
            )
        )
        .setInterval(QueryRunnerTestHelper.fullOnInterval)
        .setLimitSpec(
            new DefaultLimitSpec(
                Lists.newArrayList(
                    new OrderByColumnSpec(
                        "marketalias",
                        OrderByColumnSpec.Direction.DESCENDING
                    )
                ), 1
            )
        )
        .setAggregatorSpecs(
            Lists.newArrayList(
                QueryRunnerTestHelper.rowsCount,
                aggFactory
            )
        )
        .setPostAggregatorSpecs(
            Arrays.<PostAggregator>asList(
                new QuantilePostAggregator("quantile", "quantile", 0.5f)
            )
        )
        .build();

    List<Row> expectedResults = Arrays.asList(
        GroupByQueryRunnerTestHelper.createExpectedRow(
            "1970-01-01T00:00:00.000Z",
            "marketalias", "upfront",
            "rows", 186L,
            "quantile", 880.9881f
        )
    );

    Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query);
    TestHelper.assertExpectedObjects(expectedResults, results, "approx-histo");
  }
}


text:
package com.amazonaws.services.ec2.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * AllocateIpamPoolCidrResult StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AllocateIpamPoolCidrResultStaxUnmarshaller implements Unmarshaller<AllocateIpamPoolCidrResult, StaxUnmarshallerContext> {

    public AllocateIpamPoolCidrResult unmarshall(StaxUnmarshallerContext context) throws Exception {
        AllocateIpamPoolCidrResult allocateIpamPoolCidrResult = new AllocateIpamPoolCidrResult();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return allocateIpamPoolCidrResult;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("ipamPoolAllocation", targetDepth)) {
                    allocateIpamPoolCidrResult.setIpamPoolAllocation(IpamPoolAllocationStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return allocateIpamPoolCidrResult;
                }
            }
        }
    }

    private static AllocateIpamPoolCidrResultStaxUnmarshaller instance;

    public static AllocateIpamPoolCidrResultStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new AllocateIpamPoolCidrResultStaxUnmarshaller();
        return instance;
    }
}


text:
import React from 'react' // eslint-disable-line no-unused-vars

import TodoApp from '../../components/TodoApp'
import Header from '../../components/Header'
import Menu from '../../components/Menu'
import Chat from '../../components/Chat'
import menuItem from '../../data/menu.json'

const Todo = () => (

          <Menu items={menuItem} />

          <TodoApp />

          <Chat />

)

export default Todo


text:
#import "CKHttpServletInputStream.h"
#import "protocol/CKServletConnection.h"

@interface CKHttpServletInputStream(Private)

- (void)shrinkBuffer;

@end

@implementation CKHttpServletInputStream(Private)

- (void)shrinkBuffer
{
    if (bufferPosition > 4096) {
        [buffer autorelease];
        buffer = [[buffer subdataWithRange:NSMakeRange(bufferPosition, [buffer length] - bufferPosition)] mutableCopy];
        bufferPosition = 0;
    }
}

@end

@implementation CKHttpServletInputStream

- initWithConnection:(CKServletConnection *)aServletConnection
{
    servletConnection = [aServletConnection retain];

    return self;
}

- (void)dealloc
{
    [servletConnection release];

    [super dealloc];
}

- (NSData *)readData
{
    NSData  *data;
    if([buffer length] > bufferPosition) {
        //there is something in the buffer return the buffer
        data =[buffer subdataWithRange:NSMakeRange(bufferPosition, [buffer length] - bufferPosition)];
    }
    else {
        data = [servletConnection readPayload];
    }

    [buffer release];
    buffer = nil;
    bufferPosition = 0;

    return data;
}

- (int)peek
{
    if([buffer length] > bufferPosition) {
        return ((unsigned char *)[buffer bytes])[bufferPosition];
    }
    else {
        buffer = [[servletConnection readPayload] mutableCopy];
        bufferPosition = 0;
        if ([buffer length] == 0) {
            return EOF;
        }
        else {
            return ((unsigned char *)[buffer bytes])[0];
        }
    }
}

- (int)read
{
    unsigned char b = [self peek];
    bufferPosition++;
    return b;
}

- (NSData *)readData:(unsigned int)length
{

    while ([buffer length] < length + bufferPosition) {
        NSData  *data = [servletConnection readPayload];
        if ([data length] == 0) {
            unsigned int remaining = [buffer length] - bufferPosition;
            unsigned int rangeLength = MIN(remaining, length);
            if (rangeLength == 0) {
                [buffer release];
                buffer = nil;
                return nil;
            }
            else {
                NSData *returnData = [buffer subdataWithRange:NSMakeRange(bufferPosition, rangeLength)];
                [buffer release];
                buffer = nil;
                return returnData;
            }
        }
        else {
            if (buffer == nil) {
                buffer = [[NSMutableData alloc] initWithData:data];
            }
            else {
                [buffer appendData:data];
            }
        }
    }

    NSData  *data = [buffer subdataWithRange:NSMakeRange(bufferPosition, length)];

    bufferPosition += length;

    [self shrinkBuffer];

    return data;
}

@end


text:
require_relative '../spec_helper_min'

feature "Forgot password" do

  before(:all) do
    @user = create(:user)
  end

  before(:each) do
    visit login_path
    click_link 'Forgot?'
    fill_in 'email', with: @user.email
  end

  after(:all) do
    @user.destroy
  end

  scenario "Reset password view shows an error if the email is blank" do
    fill_in 'email', with: ''
    click_button "Send"

    page.should have_css "[data-content=\"Email cannot be blank.\"]"
  end

  scenario "Reset password view redirects to the right page if the email does not exist" do
    fill_in 'email', with: 'notfound@example.com'
    click_button "Send"

    page.should have_content("Ok, we have sent you an email")
  end

  scenario "Reset password redirects to the right view" do
    click_button "Send"

    page.should have_content("Ok, we have sent you an email")
  end

  scenario "Reset password link allows to change the password" do
    click_button "Send"

    @user.reload # so password_reset_token is loaded

    visit edit_password_reset_path(@user.password_reset_token)

    original_crypted_password = @user.crypted_password

    fill_in "carto_user_password", with: "newpass"
    fill_in "carto_user_password_confirmation", with: "newpass"
    click_button "Save"

    @user.reload # so password is loaded
    @user.crypted_password.should_not eql original_crypted_password
  end

  scenario "It shows the right view after changing the password" do
    click_button "Send"

    @user.reload # so password_reset_token is loaded

    visit edit_password_reset_path(@user.password_reset_token)

    fill_in "carto_user_password", with: "newpass2"
    fill_in "carto_user_password_confirmation", with: "newpass2"
    click_button "Save"

    current_path.should == changed_password_reset_path
    page.should have_content("Your password has been updated successfully")
  end

  scenario "Change password view shows an error when token has expired (>48h)" do
    Delorean.time_travel_to("49 hours ago") do
      click_button "Send"
    end

    Delorean.back_to_the_present
    @user.reload # so password_reset_token is loaded

    visit edit_password_reset_path(@user.password_reset_token)

    original_crypted_password = @user.crypted_password

    fill_in "carto_user_password", with: "newpass"
    fill_in "carto_user_password_confirmation", with: "newpass"
    click_button "Save"

    page.should have_css "[data-content='Password reset has expired.']"
    current_path.should == new_password_reset_path

    @user.reload.crypted_password.should == original_crypted_password
  end

  scenario "Change password view shows an error when the passwords do not match" do
    click_button "Send"

    @user.reload # so password_reset_token is loaded

    visit edit_password_reset_path(@user.password_reset_token)

    original_crypted_password = @user.crypted_password

    fill_in "carto_user_password", with: "newpass"
    fill_in "carto_user_password_confirmation", with: "newpa"
    click_button "Save"

    page.should have_css "[data-content='Please ensure your passwords match.']"

    @user.reload.crypted_password.should == original_crypted_password
  end
end


text:
<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
		<title>Invocation list for thyol tests</title>

pages examples

Click here for "example1.html"

Click here for "example1a.html"

Click here for "example1b.html"

Click here for "example1c.html"

Click here for "example2.html"

Click here for "example3.html"

Click here for "example4.html"

Click here for "example4a.html"

Click here for "example4b.html"

Click here for "example5.html"

Click here for "example6.html"

Click here for "example7.html"

Click here for "login.html"

Back


text:
using System;
using System.Diagnostics;

namespace Sharpen
{
	public class SystemProcess
	{
		Process proc;

		public SystemProcess ()
		{
		}

		public SystemProcess (Process proc)
		{
			this.proc = proc;
		}

		public static SystemProcess Start (ProcessStartInfo psi)
		{
			var p = Process.Start (psi);
			return new SystemProcess (p);
		}

		public virtual InputStream GetInputStream()
		{
			return InputStream.Wrap (proc.StandardOutput.BaseStream);
		}

		public virtual OutputStream GetOutputStream()
		{
			return OutputStream.Wrap (proc.StandardInput.BaseStream);
		}

		public virtual InputStream GetErrorStream()
		{
			return InputStream.Wrap (proc.StandardError.BaseStream);
		}

		public virtual int ExitValue()
		{
			return proc.ExitCode;
		}

		public virtual void Destroy()
		{
			if (!proc.HasExited) {
				try {
					proc.Kill ();
				} catch (InvalidOperationException) {
					// Already exited. Do nothing
				}
			}
		}

		public virtual int WaitFor()
		{
			proc.WaitForExit ();
			return proc.ExitCode;
		}
	}
}


text:
<template>

summary

		<input id=expand class=expand type=checkbox>
		<slot name=expand-icon>▶</slot>

test

</template>


text:
package com.bugull.mongo.fs;

import java.awt.Color;
import java.awt.Font;

/**
 *
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class Watermark {

    public final static int CENTER = 1;
    public final static int BOTTOM_RIGHT = 2;
    public final static int BOTTOM_LEFT = 3;

    private String imagePath;
    private String text;

    private String fontName = "Arial";
    private int fontStyle = Font.PLAIN;
    private Color color = Color.GRAY;
    private int fontSize = 30;
    private float alpha = 0.5f;

    private int align = CENTER;  //default align is center

    //margin
    private int right = 20;
    private int left = 20;
    private int bottom = 20;

    public int getAlign() {
        return align;
    }

    public void setAlign(int align) {
        this.align = align;
    }

    public String getImagePath() {
        return imagePath;
    }

    /**
     * set the absolute path of the image file
     * @param imagePath
     */
    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

    public int getBottom() {
        return bottom;
    }

    /**
     * set margin bottom
     * @param bottom
     */
    public void setBottom(int bottom) {
        this.bottom = bottom;
    }

    public int getRight() {
        return right;
    }

    /**
     * set margin right
     * @param right
     */
    public void setRight(int right) {
        this.right = right;
    }

    public int getLeft() {
        return left;
    }

    /**
     * set margin left
     * @param left
     */
    public void setLeft(int left) {
        this.left = left;
    }

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
    }

    public int getFontSize() {
        return fontSize;
    }

    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public float getAlpha() {
        return alpha;
    }

    public void setAlpha(float alpha) {
        this.alpha = alpha;
    }

    public String getFontName() {
        return fontName;
    }

    public void setFontName(String fontName) {
        this.fontName = fontName;
    }

    public int getFontStyle() {
        return fontStyle;
    }

    public void setFontStyle(int fontStyle) {
        this.fontStyle = fontStyle;
    }

}


text:
package org.openengsb.domain.example.model;

import org.openengsb.core.api.Constants;
import org.openengsb.core.api.model.annotation.Model;
import org.openengsb.core.api.model.annotation.OpenEngSBModelId;
import org.openengsb.labs.delegation.service.Provide;

@Provide(context = { Constants.DELEGATION_CONTEXT_MODELS })
@Model
public class SourceModelB {
    @OpenEngSBModelId
    private String edbId;
    private String name;
    private String shared;

    public SourceModelB() {
    }

    public SourceModelB(String edbId, String name, String shared) {
        this.edbId = edbId;
        this.name = name;
        this.shared = shared;
    }

    public String getEdbId() {
        return edbId;
    }

    public void setEdbId(String edbId) {
        this.edbId = edbId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getShared() {
        return shared;
    }

    public void setShared(String shared) {
        this.shared = shared;
    }
}


text:
package org.apache.lucene.util.packed;

import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.RamUsageEstimator;

import java.io.IOException;
import java.util.Arrays;

/**
 * Space optimized random access capable array of values with a fixed number of
 * bits. The maximum number of bits/value is 31. Use {@link Packed64} for higher
 * numbers.
 *

 * The implementation strives to avoid conditionals and expensive operations,
 * sacrificing code clarity to achieve better performance.
 */

class Packed32 extends PackedInts.ReaderImpl implements PackedInts.Mutable {
  static final int BLOCK_SIZE = 32; // 32 = int, 64 = long
  static final int BLOCK_BITS = 5; // The #bits representing BLOCK_SIZE
  static final int MOD_MASK = BLOCK_SIZE - 1; // x % BLOCK_SIZE

  private static final int ENTRY_SIZE = BLOCK_SIZE + 1;
  private static final int FAC_BITPOS = 3;

  /*
   * In order to make an efficient value-getter, conditionals should be
   * avoided. A value can be positioned inside of a block, requiring shifting
   * left or right or it can span two blocks, requiring a left-shift on the
   * first block and a right-shift on the right block.
   *

   * By always shifting the first block both left and right, we get exactly
   * the right bits. By always shifting the second block right and applying
   * a mask, we get the right bits there. After that, we | the two bitsets.
  */
  private static final int[][] SHIFTS =
          new int[ENTRY_SIZE][ENTRY_SIZE * FAC_BITPOS];
  private static final int[][] MASKS = new int[ENTRY_SIZE][ENTRY_SIZE];

  static { // Generate shifts
    for (int elementBits = 1 ; elementBits <= BLOCK_SIZE ; elementBits++) {
      for (int bitPos = 0 ; bitPos < BLOCK_SIZE ; bitPos++) {
        int[] currentShifts = SHIFTS[elementBits];
        int base = bitPos * FAC_BITPOS;
        currentShifts[base    ] = bitPos;
        currentShifts[base + 1] = BLOCK_SIZE - elementBits;
        if (bitPos <= BLOCK_SIZE - elementBits) { // Single block
          currentShifts[base + 2] = 0;
          MASKS[elementBits][bitPos] = 0;
        } else { // Two blocks
          int rBits = elementBits - (BLOCK_SIZE - bitPos);
          currentShifts[base + 2] = BLOCK_SIZE - rBits;
          MASKS[elementBits][bitPos] = ~(~0 << rBits);
        }
      }
    }
  }

  /*
   * The setter requires more masking than the getter.
  */
  private static final int[][] WRITE_MASKS =
          new int[ENTRY_SIZE][ENTRY_SIZE * FAC_BITPOS];
  static {
    for (int elementBits = 1 ; elementBits <= BLOCK_SIZE ; elementBits++) {
      int elementPosMask = ~(~0 << elementBits);
      int[] currentShifts = SHIFTS[elementBits];
      int[] currentMasks = WRITE_MASKS[elementBits];
      for (int bitPos = 0 ; bitPos < BLOCK_SIZE ; bitPos++) {
        int base = bitPos * FAC_BITPOS;
        currentMasks[base  ] =~((elementPosMask
                << currentShifts[base + 1])
                >>> currentShifts[base]);
        currentMasks[base+1] = ~(elementPosMask
                << currentShifts[base + 2]);
        currentMasks[base+2] = currentShifts[base + 2] == 0 ? 0 : ~0;
        if (bitPos <= BLOCK_SIZE - elementBits) { // Second block not used
          currentMasks[base+1] = ~0; // Keep all bits
          currentMasks[base+2] = 0;  // Or with 0
        }
      }
    }
  }

  /* The bits */
  private int[] blocks;

  // Cached calculations
  private int maxPos;      // blocks.length * BLOCK_SIZE / bitsPerValue - 1
  private int[] shifts;    // The shifts for the current bitsPerValue
  private int[] readMasks;
  private int[] writeMasks;

  /**
   * Creates an array with the internal structures adjusted for the given
   * limits and initialized to 0.
   * @param valueCount   the number of elements.
   * @param bitsPerValue the number of bits available for any given value.
   *        Note: bitsPerValue >32 is not supported by this implementation.
   */
  public Packed32(int valueCount, int bitsPerValue) {
    this(new int[(int)(((long)valueCount) * bitsPerValue / BLOCK_SIZE + 2)],
            valueCount, bitsPerValue);
  }

  /**
   * Creates an array with content retrieved from the given IndexInput.
   * @param in       an IndexInput, positioned at the start of Packed64-content.
   * @param valueCount  the number of elements.
   * @param bitsPerValue the number of bits available for any given value.
   * @throws java.io.IOException if the values for the backing array could not
   *                             be retrieved.
   */
  public Packed32(IndexInput in, int valueCount, int bitsPerValue)
                                                            throws IOException {
    super(valueCount, bitsPerValue);
    int size = size(bitsPerValue, valueCount);
    blocks = new int[size + 1]; // +1 due to non-conditional tricks
    for(int i = 0 ; i < size ; i++) {
      blocks[i] = in.readInt();
    }
    if (size % 2 == 1) {
      in.readInt(); // Align to long
    }
    updateCached();
  }

  private static int size(int bitsPerValue, int valueCount) {
    final long totBitCount = (long) valueCount * bitsPerValue;
    return (int) (totBitCount/32 + ((totBitCount % 32 == 0 ) ? 0:1));
  }

  /**
   * Creates an array backed by the given blocks.
   *

   * Note: The blocks are used directly, so changes to the given block will
   * affect the Packed32-structure.
   * @param blocks   used as the internal backing array.
   * @param valueCount   the number of values.
   * @param bitsPerValue the number of bits available for any given value.
   *        Note: bitsPerValue >32 is not supported by this implementation.
   */
  public Packed32(int[] blocks, int valueCount, int bitsPerValue) {
    // TODO: Check that blocks.length is sufficient for holding length values
    super(valueCount, bitsPerValue);
    if (bitsPerValue > 31) {
      throw new IllegalArgumentException(String.format(
              "This array only supports values of 31 bits or less. The "
                      + "required number of bits was %d. The Packed64 "
                      + "implementation allows values with more than 31 bits",
              bitsPerValue));
    }
    this.blocks = blocks;
    updateCached();
  }

  private void updateCached() {
    readMasks = MASKS[bitsPerValue];
    maxPos = (int)((((long)blocks.length) * BLOCK_SIZE / bitsPerValue) - 2);
    shifts = SHIFTS[bitsPerValue];
    writeMasks = WRITE_MASKS[bitsPerValue];
  }

  /**
   * @param index the position of the value.
   * @return the value at the given index.
   */
  public long get(final int index) {
    final long majorBitPos = index * bitsPerValue;
    final int elementPos = (int)(majorBitPos >>> BLOCK_BITS); // / BLOCK_SIZE
    final int bitPos =     (int)(majorBitPos & MOD_MASK); // % BLOCK_SIZE);

    final int base = bitPos * FAC_BITPOS;

    return ((blocks[elementPos] << shifts[base]) >>> shifts[base+1]) |
            ((blocks[elementPos+1] >>> shifts[base+2]) & readMasks[bitPos]);
  }

  public void set(final int index, final long value) {
    final int intValue = (int)value;
    final long majorBitPos = index * bitsPerValue;
    final int elementPos = (int)(majorBitPos >>> BLOCK_BITS); // / BLOCK_SIZE
    final int bitPos =     (int)(majorBitPos & MOD_MASK); // % BLOCK_SIZE);
    final int base = bitPos * FAC_BITPOS;

    blocks[elementPos  ] = (blocks[elementPos  ] & writeMasks[base])
            | (intValue << shifts[base + 1] >>> shifts[base]);
    blocks[elementPos+1] = (blocks[elementPos+1] & writeMasks[base+1])
            | ((intValue << shifts[base + 2])
            & writeMasks[base+2]);
  }

  public void clear() {
    Arrays.fill(blocks, 0);
  }

  public String toString() {
    return "Packed32(bitsPerValue=" + bitsPerValue + ", maxPos=" + maxPos
            + ", elements.length=" + blocks.length + ")";
  }

  public long ramBytesUsed() {
    return RamUsageEstimator.NUM_BYTES_ARRAY_HEADER
            + blocks.length * RamUsageEstimator.NUM_BYTES_INT;
  }
}


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

<title>Uses of Class org.springframework.asm.Label (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.springframework.asm.Label

Packages that use Label

Package
Description

org.springframework.asm

Spring's repackaging of
 ASM 7.0
 (with Spring-specific patches; for internal use only).

Uses of Label in org.springframework.asm

Methods in org.springframework.asm that return Label

Modifier and Type
Method and Description

protected Label[]
Attribute.getLabels()

Returns the labels corresponding to this attribute.

protected Label
ClassReader.readLabel(int bytecodeOffset,
         Label[] labels)

Returns the label corresponding to the given bytecode offset.

Methods in org.springframework.asm with parameters of type Label

Modifier and Type
Method and Description

protected Attribute
Attribute.read(ClassReader classReader,
    int offset,
    int length,
    char[] charBuffer,
    int codeAttributeOffset,
    Label[] labels)

Reads a Attribute.type attribute.

protected Label
ClassReader.readLabel(int bytecodeOffset,
         Label[] labels)

Returns the label corresponding to the given bytecode offset.

void
MethodVisitor.visitJumpInsn(int opcode,
             Label label)

Visits a jump instruction.

void
MethodVisitor.visitLabel(Label label)

Visits a label.

void
MethodVisitor.visitLineNumber(int line,
               Label start)

Visits a line number declaration.

void
MethodVisitor.visitLocalVariable(String name,
                  String descriptor,
                  String signature,
                  Label start,
                  Label end,
                  int index)

Visits a local variable declaration.

AnnotationVisitor
MethodVisitor.visitLocalVariableAnnotation(int typeRef,
                            TypePath typePath,
                            Label[] start,
                            Label[] end,
                            int[] index,
                            String descriptor,
                            boolean visible)

Visits an annotation on a local variable type.

AnnotationVisitor
MethodVisitor.visitLocalVariableAnnotation(int typeRef,
                            TypePath typePath,
                            Label[] start,
                            Label[] end,
                            int[] index,
                            String descriptor,
                            boolean visible)

Visits an annotation on a local variable type.

void
MethodVisitor.visitLookupSwitchInsn(Label dflt,
                     int[] keys,
                     Label[] labels)

Visits a LOOKUPSWITCH instruction.

void
MethodVisitor.visitLookupSwitchInsn(Label dflt,
                     int[] keys,
                     Label[] labels)

Visits a LOOKUPSWITCH instruction.

void
MethodVisitor.visitTableSwitchInsn(int min,
                    int max,
                    Label dflt,
                    Label... labels)

Visits a TABLESWITCH instruction.

void
MethodVisitor.visitTableSwitchInsn(int min,
                    int max,
                    Label dflt,
                    Label... labels)

Visits a TABLESWITCH instruction.

void
MethodVisitor.visitTryCatchBlock(Label start,
                  Label end,
                  Label handler,
                  String type)

Visits a try catch block.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes


text:
package com.sharksharding.util.xml;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 生成基于c3p0的数据源配置文件
 *
 * @author gaoxianglong
 *
 * @version 1.3.5
 */
@XmlRootElement(name = "bean")
@XmlAccessorType(XmlAccessType.FIELD)
public class Property {
	@XmlAttribute(name = "name")
	private String name;

	@XmlAttribute(name = "ref")
	private String ref;

	@XmlAttribute(name = "value")
	private String value;

	@XmlElement(name = "map")
	private Map map;

	public Map getMap() {
		return map;
	}

	public void setMap(Map map) {
		this.map = map;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRef() {
		return ref;
	}

	public void setRef(String ref) {
		this.ref = ref;
	}
}


text:
function displayPromo(){  //display the promo code, you could get this from PHP to be more secure
	$('.fb-button').replaceWith('
Thank you for sharing!
 Use the promo code "FB10" during checkout to receive 10% off your plan!
');
}

window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
  appId      : '591990517558339',               // Replace with your Facebook APP ID
  channelUrl : '//flwebsites.biz/channel.html', // Replace with your domain //Channel file for x-domain comms
  xfbml      : true                             // Look for social plugins on the page
});

$processed = false;

$('.jSave').on('click', function(){
	$.fn.jAlert({
		'title': 'Share and Save',
		'message': "
It's Easy, Fast, and FREE.

1. Connect via Facebook (below).

2. We'll auto-post to your wall.
\"This is a preview of what we will be posting.\"

3. You'll get a coupon to save 10%!

 Connect & Post",
		'theme': 'dark',
		'size': 'small'
	});
});

$('body').on('click', '.fb-button', function(e){
	e.preventDefault();

	FB.login(function(response) {
	   if(response.authResponse) {
			FB.api('/me', function(userInfo) {
			if(userInfo.name){
				/* HERE YOU COULD OPTIONALLY USE THEIR NAME, EMAIL, ETC */
				// console.log(userInfo);
				var body = "Check that out. I just used http://flwebsites.biz/jAlert to post this to my wall!"; var link = 'http://flwebsites.biz/jAlert'; // you don't need to send link if you just want to post text
				FB.api('/me/feed', 'post', { message: body, link: link }, function(response) {
					if(response.error){ // if there was an error
						if(response.error.code != 200){ // 200 means they denied the permission to post to their wall, don't do anything
						if(response.error.code != 506){ //506 means the message was posted more than once and denied, just show the discount again
							alert(response.error.message); //show them the error that was returned by facebook for reporting
						}else{
							displayPromo();
						}
						}
					}else{
						displayPromo();
						}
				});
			}
			});
	   }
  }, {scope: 'email, publish_stream'}); //you don't need the email permission, but I'd assume you'll want to store it somewhere

});

};
// Load the SDK asynchronously
(function(d, s, id){
 var js, fjs = d.getElementsByTagName(s)[0];
 if (d.getElementById(id)) {return;}
 js = d.createElement(s); js.id = id;
 js.src = "//connect.facebook.net/en_US/all.js";
 fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));