text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
  ~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied. See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<Analytics>
    <Name>sensor_temp_spark_script</Name>
    <Script>
        CREATE TEMPORARY TABLE Devicesensor_tempData USING CarbonAnalytics OPTIONS(tableName
        "ORG_WSO2_IOT_DEVICES_sensor_temp");
        CREATE TEMPORARY TABLE Devicesensor_tempSummaryData USING CarbonAnalytics OPTIONS (tableName
        "DEVICE_sensor_temp_SUMMARY", schema "sensor_temp FLOAT, deviceType STRING -i, deviceId
        STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
        insert overwrite table Devicesensor_tempSummaryData select sensor_temp, meta_deviceType as
        deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time as BIGINT)as time
        from Devicesensor_tempData group by sensor_temp, meta_deviceType, meta_deviceId, meta_owner,
        cast(meta_time as BIGINT);
    </Script>
    <CronExpression>0 * * * * ?</CronExpression>
</Analytics>


text:
from .inducing_variables import InducingPoints

class InducingPatches(InducingPoints):
    pass

redpajama_set_name: RedPajamaGithub


text:
.body-padding{padding: 25px;}
.input:focus{outline: none !important;border:1px solid #3594f1;box-shadow: 0 0 10px #719ECE;}
.form-control{padding:2px 12px}
.totals .table > tbody > tr > td{
    padding: 0;
}


text:
package codemonkey800.org.baseconverter.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import codemonkey800.org.baseconverter.R;

public class BinaryConverterFragment extends BaseConverterFragment {

    public BinaryConverterFragment() {
    }

    public static BinaryConverterFragment instance() {
        return new BinaryConverterFragment();
    }

    @Nullable
    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
        View view = super.onCreateView( inflater, container, savedInstanceState );
        mMode = BaseMode.BinToDec;

        Button modeOneKey = ( Button ) view.findViewById( R.id.mode_one_key );
        Button modeTwoKey = ( Button ) view.findViewById( R.id.mode_two_key );
        final TextView baseMode = ( TextView ) view.findViewById( R.id.base_mode );

        baseMode.setText( "10" );

        modeOneKey.setText( "10" );
        modeOneKey.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick( View v ) {
                mMode = BaseMode.BinToDec;
                baseMode.setText( "10" );
            }
        } );
        modeTwoKey.setText( "0x" );
        modeTwoKey.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick( View v ) {
                mMode = BaseMode.BinToHex;
                baseMode.setText( "0x" );
            }
        } );

        return view;
    }
}


text:
package dev.jeka.core.api.depmanagement;

import dev.jeka.core.api.utils.JkUtilsIterable;

import java.util.List;

/**
 * In Maven repositories, modules are published along a pom.xml metadata containing
 * the transitive dependencies of the module. Here, transitive dependencies can be
 * published with only 2 scopes : either 'compile' nor 'runtime'.<p>
 * This enum specifies how a dependency must take in account its transitive ones.
 */
public class  JkTransitivity {

    private final String value;

    private JkTransitivity(String value) {
        this.value = value;
    }

    /**
     * Dependency will be fetched without any transitive dependencies
     */
    public static final JkTransitivity NONE = new JkTransitivity("NONE");

    /**
     * Dependency will be fetched along transitive dependencies declared as 'compile'
     */
    public static final JkTransitivity COMPILE = new JkTransitivity("COMPILE");

    /**
     * Dependency will be fetched along transitive dependencies declared as 'runtime'
     * or 'compile'
     */
    public static final JkTransitivity RUNTIME = new JkTransitivity("RUNTIME");

    private static final List<JkTransitivity> ORDER = JkUtilsIterable.listOf(NONE, COMPILE, RUNTIME);

    public static JkTransitivity ofDeepest(JkTransitivity left, JkTransitivity right) {
        if (left == null) {
            return right;
        }
        if (right == null) {
            return left;
        }
        return ORDER.indexOf(left) > ORDER.indexOf(right)? left : right;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        JkTransitivity that = (JkTransitivity) o;
        return value.equals(that.value);
    }

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

    @Override
    public String toString() {
        return value;
    }
}


text:
<?php
declare(strict_types=1);

namespace App\Security\EventListener;

use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTDecodedEvent;

class JWTDecodedListener
{
    public function onJWTDecoded(JWTDecodedEvent $event): void
    {
        // $request = $this->requestStack->getCurrentRequest();
        //
        // $payload = $event->getPayload();
        //
        // if (!isset($payload['ip']) || $payload['ip'] !== $request->getClientIp()) {
        //     $event->markAsInvalid();
        // }
    }
}


text:
export function onError(e: any) {
  // TODO: (misko): We seem to not have a stack trace here!
  if (console.error) {
    console.error(e, e.stack);
  } else {
    // tslint:disable-next-line:no-console
    console.log(e, e.stack);
  }
  throw e;
}

export function controllerKey(name: string): string {
  return '$' + name + 'Controller';
}

export function getAttributesAsArray(node: Node): [string, string][] {
  const attributes = node.attributes;
  let asArray: [string, string][];
  if (attributes) {
    let attrLen = attributes.length;
    asArray = new Array(attrLen);
    for (let i = 0; i < attrLen; i++) {
      asArray[i] = [attributes[i].nodeName, attributes[i].nodeValue];
    }
  }
  return asArray || [];
}

export class Deferred<R> {
  promise: Promise<R>;
  resolve: (value?: R|PromiseLike<R>) => void;
  reject: (error?: any) => void;

  constructor() {
    this.promise = new Promise((res, rej) => {
      this.resolve = res;
      this.reject = rej;
    });
  }
}


text:
package bmdiff.test;

import bmdiff.BMDiffCodec;
import bmdiff.Utils;

/**
 * The input strings have been carefully chosen to stress most of the boundary
 * conditions that could possibly make the implementation falter. If you are
 * implementing your own version then this test set would immensely help as it
 * helped uncover all the corner cases.
 * @author srikchan
 */
public class SimpleTests {

    private static final int blockSize = 8;
    private final String[] inputStrings = new String[] {
        "abcdefghijklmnopqrstuvwxijklmnopabcdefghqrstuvwx",
        "abcdefghijabcdefghij",
        "aaaabcdeaabcde",
        "aaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbb",
        "aabaaaaaaaaabbbbbbbbbbbbbb",
        "abcabcabcabcabcabc",
        "               intended by the author                                     CHAPTER IV                                    SAMPOORNESHBABU",
        "aaaaaaaaaaaaaaaaINTENDED BY THE AUTHORaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaCHAPTER IVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaSAMPOORNESHBABU",
        "-------------+---------------------+--------------------------------------",
        "+---------------------+--------------+---------------------+--------------",
        "abcdefghijklmnopq<12345",
        "Michael S. Hart <hart@pobox.com> abcdefg gfedcba <hart@pobox.com>hijklmnopqrstuv",
        "Michael S. Hart <hart@pobox.com> abcdefg gfedcba <hart@pobox.com>hijklmnopqrstuv gefdbca <hart@pobox.com> zebra"
    };

    public static void main(String[] args) {
        SimpleTests test = new SimpleTests();
            test.test();
//        for (int i = 0;i < 10;i++)
//            test.test("/home/srikalyc/NetBeansProjects/big");
    }

    public void test() {
        BMDiffCodec bmdiff = new BMDiffCodec(blockSize);
        for (String inputString : inputStrings) {
            char[] enc = bmdiff.encode(inputString.toCharArray());
            char[] dec = bmdiff.decode();
            System.out.println(inputString);
            System.out.println(enc);
            System.out.println(dec);
            System.out.println("----------------------------------------------------");
            System.out.println(inputString.equals(new String(dec)) ? "PASS" : "FAIL");
            System.out.println("----------------------------------------------------");
        }
    }
    /**
     * FileName without extension.
     * @param fileName
     */
    public void test(String fileName) {
        BMDiffCodec bmdiff = new BMDiffCodec(blockSize);
        char[] enc = bmdiff.encode(Utils.readFileInChars(fileName + ".txt"));
        Utils.writeFileInChars(enc, fileName + ".enc");
        Utils.writeFileInChars(bmdiff.decode(), fileName + ".dec");

    }
}


text:
package org.drools.core.command;

import org.kie.api.command.ExecutableCommand;
import org.kie.api.runtime.Context;

public class StartConversationCommand<Void> implements ExecutableCommand<Void> {
    public StartConversationCommand() {
    }

    @Override
    public Void execute(Context context) {
        RequestContextImpl         reqContext = (RequestContextImpl)context;
        ConversationContextManager cvnManager = reqContext.getConversationManager();
        cvnManager.startConversation(reqContext);

        return (Void) null;
    }
}


text:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { AlertService, SimpleRegistrationService } from '../_services/index';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  model: any = {};
  loading = false;
  returnUrl: string;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private simpleRegistrationService: SimpleRegistrationService,
    private alertService: AlertService) { }

  ngOnInit() {
    // reset login status
    this.simpleRegistrationService.logout();

    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  }

  login() {
    this.loading = true;
    this.simpleRegistrationService.register(this.model.email)
      .subscribe(
        data => {
          this.router.navigate([this.returnUrl]);
        },
        error => {
          this.alertService.error(error);
          this.loading = false;
        });
  }

}


text:
package org.lnu.is.web.rest.handler.request;

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

import org.lnu.is.resource.message.MessageResource;
import org.lnu.is.resource.message.MessageType;
import org.lnu.is.resource.message.Pair;
import org.lnu.is.resource.message.validation.ValidationMessageResource;
import org.lnu.is.web.rest.handler.BaseExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * Default validation exception handler.
 * @author ivanursul
 *
 */
@ControllerAdvice
public class BindExceptionHandler implements BaseExceptionHandler<BindException> {
	private static final Logger LOGGER =  LoggerFactory.getLogger(BindExceptionHandler.class);

	@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY)
    @ExceptionHandler(value = { BindException.class })
    @ResponseBody
    @Override
    public MessageResource handle(final BindException e) throws Exception {
    	LOGGER.error("Handling bind validation exception", e);

        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        List<Pair<String, String>> errors = new ArrayList<Pair<String, String>>();

        for (FieldError error : fieldErrors) {

        	Pair<String, String> pair = new Pair<String, String>();
        	pair.setName(error.getField());
        	pair.setValue(error.getDefaultMessage());

        	errors.add(pair);
        }

        return new ValidationMessageResource(MessageType.ERROR, "Validation failed, please see following errors", errors);
    }

}


text:
package com.gemstone.gemfire.cache30;

import java.util.Map;
import java.util.Properties;

import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheException;

import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.DataPolicy;
import com.gemstone.gemfire.cache.DiskWriteAttributesFactory;
import com.gemstone.gemfire.cache.EvictionAction;
import com.gemstone.gemfire.cache.EvictionAlgorithm;
import com.gemstone.gemfire.cache.EvictionAttributes;
import com.gemstone.gemfire.cache.ExpirationAction;
import com.gemstone.gemfire.cache.ExpirationAttributes;
import com.gemstone.gemfire.cache.PartitionAttributes;
import com.gemstone.gemfire.cache.PartitionAttributesFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.execute.Function;
import com.gemstone.gemfire.cache.execute.FunctionService;
import com.gemstone.gemfire.cache.util.ObjectSizerImpl;
import com.gemstone.gemfire.internal.cache.DistributedRegion;
import com.gemstone.gemfire.internal.cache.functions.*;
import com.gemstone.gemfire.internal.cache.lru.MemLRUCapacityController;
import com.gemstone.gemfire.internal.cache.xmlcache.CacheCreation;
import com.gemstone.gemfire.internal.cache.xmlcache.CacheXml;
import com.gemstone.gemfire.internal.cache.xmlcache.FunctionServiceCreation;
import com.gemstone.gemfire.internal.cache.xmlcache.RegionAttributesCreation;
import com.gemstone.gemfire.internal.cache.xmlcache.ResourceManagerCreation;

/**
 * Tests 5.8 cache.xml features.
 *
 * @author skumar
 * @since 5.8
 */

public class CacheXml58DUnitTest extends CacheXml57DUnitTest
{

  // ////// Constructors

  public CacheXml58DUnitTest(String name) {
    super(name);
  }

  // ////// Helper methods

  protected String getGemFireVersion()
  {
    return CacheXml.VERSION_5_8;
  }

  /**
   * Tests that a region created with a named attributes set programmatically
   * for partition-resolver has the correct attributes.
   *
   */
  public void testPartitionedRegionAttributesForCustomPartitioning() throws CacheException
  {
    CacheCreation cache = new CacheCreation();
    RegionAttributesCreation attrs = new RegionAttributesCreation(cache);

    CacheXMLPartitionResolver partitionResolver = new CacheXMLPartitionResolver();
    Properties params = new Properties();
    params.setProperty("initial-index-value", "1000");
    params.setProperty("secondary-index-value", "5000");
    partitionResolver.init(params);

    PartitionAttributesFactory paf = new PartitionAttributesFactory();
    paf.setRedundantCopies(1);
    paf.setTotalMaxMemory(500);
    paf.setLocalMaxMemory(100);
    paf.setPartitionResolver(partitionResolver);

    attrs.setPartitionAttributes(paf.create());

    cache.createRegion("parRoot", attrs);

    Region r = cache.getRegion("parRoot");
    assertEquals(r.getAttributes().getPartitionAttributes().getRedundantCopies(),1);
    assertEquals(r.getAttributes().getPartitionAttributes().getLocalMaxMemory(),100);
    assertEquals(r.getAttributes().getPartitionAttributes().getTotalMaxMemory(),500);
    assertEquals(r.getAttributes().getPartitionAttributes().getPartitionResolver(),partitionResolver);

    testXml(cache);

    Cache c = getCache();
    assertNotNull(c);

    Region region = c.getRegion("parRoot");
    assertNotNull(region);

    RegionAttributes regionAttrs = region.getAttributes();
    PartitionAttributes pa = regionAttrs.getPartitionAttributes();

    assertEquals(pa.getRedundantCopies(), 1);
    assertEquals(pa.getLocalMaxMemory(), 100);
    assertEquals(pa.getTotalMaxMemory(), 500);
    assertNotNull(pa.getPartitionResolver().getClass());
    assertEquals(pa.getPartitionResolver(), partitionResolver);
  }

  /**
   * Tests that a cache created with FunctionService and registered FabricFunction
   * has correct registered Function
   *
   */
  public void testCacheCreationWithFuntionService() throws CacheException
  {
    CacheCreation cache = new CacheCreation();
    FunctionServiceCreation fsc = new FunctionServiceCreation();
    TestFunction function1 = new TestFunction(true,TestFunction.TEST_FUNCTION2);
    TestFunction function2 = new TestFunction(true, TestFunction.TEST_FUNCTION3);
    TestFunction function3 = new TestFunction(true, TestFunction.TEST_FUNCTION4);
    fsc.registerFunction(function1);
    fsc.registerFunction(function2);
    fsc.registerFunction(function3);
    fsc.create();
    cache.setFunctionServiceCreation(fsc);

    testXml(cache);
    getCache();
    Map<String, Function> functionIdMap = FunctionService.getRegisteredFunctions();
    assertEquals(3, functionIdMap.size());

    assertTrue(function1.equals(functionIdMap.get(function1.getId())));
    assertTrue(function2.equals(functionIdMap.get(function2.getId())));
    assertTrue(function3.equals(functionIdMap.get(function3.getId())));
  }

  /**
   * Tests that a Partitioned Region can be created with a named attributes set programmatically
   * for ExpirationAttributes
   *
   */
  public void testPartitionedRegionAttributesForExpiration() throws CacheException
  {
    CacheCreation cache = new CacheCreation();
    RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
    attrs.setStatisticsEnabled(true);
    RegionAttributes rootAttrs = null;
    ExpirationAttributes expiration = new ExpirationAttributes(60,ExpirationAction.DESTROY);

    CacheXMLPartitionResolver partitionResolver = new CacheXMLPartitionResolver();
    Properties params = new Properties();
    params.setProperty("initial-index-value", "1000");
    params.setProperty("secondary-index-value", "5000");
    partitionResolver.init(params);

    PartitionAttributesFactory paf = new PartitionAttributesFactory();
    paf.setRedundantCopies(1);
    paf.setTotalMaxMemory(500);
    paf.setLocalMaxMemory(100);
    paf.setPartitionResolver(partitionResolver);

    AttributesFactory fac = new AttributesFactory(attrs);
    fac.setEntryTimeToLive(expiration);
    fac.setEntryIdleTimeout(expiration);

    fac.setPartitionAttributes(paf.create());
    rootAttrs = fac.create();
    cache.createRegion("parRoot", rootAttrs);

    Region r = cache.getRegion("parRoot");
    assertNotNull(r);
    assertEquals(r.getAttributes().getPartitionAttributes().getRedundantCopies(),1);
    assertEquals(r.getAttributes().getPartitionAttributes().getLocalMaxMemory(),100);
    assertEquals(r.getAttributes().getPartitionAttributes().getTotalMaxMemory(),500);
    assertEquals(r.getAttributes().getPartitionAttributes().getPartitionResolver(),partitionResolver);

    assertEquals(r.getAttributes().getEntryIdleTimeout().getTimeout(),expiration.getTimeout());
    assertEquals(r.getAttributes().getEntryTimeToLive().getTimeout(), expiration.getTimeout());

    testXml(cache);

    Cache c = getCache();
    assertNotNull(c);

    Region region = c.getRegion("parRoot");
    assertNotNull(region);

    RegionAttributes regionAttrs = region.getAttributes();
    PartitionAttributes pa = regionAttrs.getPartitionAttributes();

    assertEquals(pa.getRedundantCopies(), 1);
    assertEquals(pa.getLocalMaxMemory(), 100);
    assertEquals(pa.getTotalMaxMemory(), 500);
    assertNotNull(pa.getPartitionResolver().getClass());
    assertEquals(pa.getPartitionResolver(), partitionResolver);

    assertEquals(regionAttrs.getEntryIdleTimeout().getTimeout(), expiration.getTimeout());
    assertEquals(regionAttrs.getEntryTimeToLive().getTimeout(), expiration.getTimeout());

  }

  /**
   * Tests that a Partitioned Region can be created with a named attributes set programmatically
   * for ExpirationAttributes
   *
   */
  public void testPartitionedRegionAttributesForEviction() throws CacheException
  {
    final int redundantCopies = 1;
    CacheCreation cache = new CacheCreation();
    if (getGemFireVersion().equals(CacheXml.VERSION_6_0)) {
      ResourceManagerCreation rm = new ResourceManagerCreation();
      rm.setCriticalHeapPercentage(95);
      cache.setResourceManagerCreation(rm);
    }
    RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
    attrs.setStatisticsEnabled(true);
    RegionAttributes rootAttrs = null;

    ExpirationAttributes expiration = new ExpirationAttributes(60,ExpirationAction.DESTROY);

    CacheXMLPartitionResolver partitionResolver = new CacheXMLPartitionResolver();
    Properties params = new Properties();
    params.setProperty("initial-index-value", "1000");
    params.setProperty("secondary-index-value", "5000");
    partitionResolver.init(params);

    PartitionAttributesFactory paf = new PartitionAttributesFactory();
    paf.setRedundantCopies(redundantCopies);
    paf.setTotalMaxMemory(500);
    paf.setLocalMaxMemory(100);
    paf.setPartitionResolver(partitionResolver);

    AttributesFactory fac = new AttributesFactory(attrs);

//  TODO mthomas 01/20/09 Move test back to using LRUHeap when config issues have settled
//    if (getGemFireVersion().equals(CacheXml.VERSION_6_0)) {
//      fac.setEvictionAttributes(EvictionAttributes.createLRUHeapAttributes(null,
//          EvictionAction.OVERFLOW_TO_DISK));
//    } else {
      fac.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes(100, null,
          EvictionAction.OVERFLOW_TO_DISK));
//    }

    fac.setEntryTimeToLive(expiration);
    fac.setEntryIdleTimeout(expiration);

    DiskWriteAttributesFactory dwaf = new DiskWriteAttributesFactory();
    dwaf.setSynchronous(true);
    /*fac.setDiskWriteAttributes(dwaf.create());
    File[] diskDirs = new File[1];
    diskDirs[0] = new File("overflowDir/" + "_"
        + OSProcess.getId());
    diskDirs[0].mkdirs();
    fac.setDiskDirs(diskDirs);*/

    fac.setPartitionAttributes(paf.create());
    rootAttrs = fac.create();
    cache.createRegion("parRoot", rootAttrs);

    Region r = cache.getRegion("parRoot");
    assertNotNull(r);
    assertEquals(r.getAttributes().getPartitionAttributes().getRedundantCopies(),redundantCopies);
    assertEquals(r.getAttributes().getPartitionAttributes().getLocalMaxMemory(),100);
    assertEquals(r.getAttributes().getPartitionAttributes().getTotalMaxMemory(),500);
    assertEquals(r.getAttributes().getPartitionAttributes().getPartitionResolver(),partitionResolver);

    assertEquals(r.getAttributes().getEntryIdleTimeout().getTimeout(),expiration.getTimeout());
    assertEquals(r.getAttributes().getEntryTimeToLive().getTimeout(), expiration.getTimeout());

    testXml(cache);

    Cache c = getCache();
    assertNotNull(c);

    Region region = c.getRegion("parRoot");
    assertNotNull(region);

    RegionAttributes regionAttrs = region.getAttributes();
    PartitionAttributes pa = regionAttrs.getPartitionAttributes();
    EvictionAttributes ea = regionAttrs.getEvictionAttributes();

    assertEquals(pa.getRedundantCopies(), 1);
    assertEquals(pa.getLocalMaxMemory(), 100);
    assertEquals(pa.getTotalMaxMemory(), 500);
    assertNotNull(pa.getPartitionResolver().getClass());
    assertEquals(pa.getPartitionResolver(), partitionResolver);

    assertEquals(regionAttrs.getEntryIdleTimeout().getTimeout(), expiration.getTimeout());
    assertEquals(regionAttrs.getEntryTimeToLive().getTimeout(), expiration.getTimeout());
//  TODO mthomas 01/20/09 Move test back to using LRUHeap when config issues have settled
//    if (getGemFireVersion().equals(CacheXml.VERSION_6_0)) {
//      assertEquals(ea.getAlgorithm(),EvictionAlgorithm.LRU_HEAP);
//    } else {
    assertEquals(ea.getAlgorithm(),EvictionAlgorithm.LRU_MEMORY);
//    }
    assertEquals(ea.getAction(), EvictionAction.OVERFLOW_TO_DISK);
  }

  public void testPartitionedRegionAttributesForCoLocation(){
    closeCache();
    CacheCreation cache = new CacheCreation();
    RegionAttributesCreation custAttrs = new RegionAttributesCreation(cache);
    RegionAttributesCreation orderAttrs = new RegionAttributesCreation(cache);
    PartitionAttributesFactory custPaf = new PartitionAttributesFactory();
    PartitionAttributesFactory orderPaf = new PartitionAttributesFactory();
    custPaf.setRedundantCopies(1);
    custPaf.setTotalMaxMemory(500);
    custPaf.setLocalMaxMemory(100);
    custAttrs.setPartitionAttributes(custPaf.create());
    cache.createRegion("Customer",custAttrs);

    orderPaf.setRedundantCopies(1);
    orderPaf.setTotalMaxMemory(500);
    orderPaf.setLocalMaxMemory(100);
    orderPaf.setColocatedWith("Customer");
    orderAttrs.setPartitionAttributes(orderPaf.create());
    cache.createRegion("Order", orderAttrs);

    testXml(cache);

    Cache c = getCache();
    assertNotNull(c);

    Region cust = c.getRegion(Region.SEPARATOR+"Customer");
    assertNotNull(cust);
    Region order = c.getRegion(Region.SEPARATOR+"Order");
    assertNotNull(order);
    String coLocatedRegion = order.getAttributes().getPartitionAttributes().getColocatedWith();
    assertEquals("Customer", coLocatedRegion);

  }

  public void testPartitionedRegionAttributesForCoLocation2(){
    closeCache();
    setXmlFile(findFile("coLocation.xml"));
    Cache c = getCache();
    assertNotNull(c);
    Region cust = c.getRegion(Region.SEPARATOR+"Customer");
    assertNotNull(cust);
    Region order = c.getRegion(Region.SEPARATOR+"Order");
    assertNotNull(order);

    assertTrue(cust.getAttributes().getPartitionAttributes().getColocatedWith()==null);
    assertTrue(order.getAttributes().getPartitionAttributes().getColocatedWith().equals("Customer"));

  }

  public void testPartitionedRegionAttributesForMemLruWithoutMaxMem() throws CacheException
  {
    final int redundantCopies = 1;
    CacheCreation cache = new CacheCreation();

    RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
    attrs.setStatisticsEnabled(true);
    PartitionAttributesFactory paf = new PartitionAttributesFactory();
    paf.setRedundantCopies(redundantCopies);
    paf.setTotalMaxMemory(500);
    paf.setLocalMaxMemory(100);

    AttributesFactory fac = new AttributesFactory(attrs);
    fac.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes( null,
          EvictionAction.LOCAL_DESTROY));
    fac.setPartitionAttributes(paf.create());
     cache.createRegion("parRoot", fac.create());

    testXml(cache);

    Cache c = getCache();
    assertNotNull(c);

    Region region = c.getRegion("parRoot");
    assertNotNull(region);

    RegionAttributes regionAttrs = region.getAttributes();
    PartitionAttributes pa = regionAttrs.getPartitionAttributes();
    EvictionAttributes ea = regionAttrs.getEvictionAttributes();

    assertEquals(pa.getRedundantCopies(), 1);
    assertEquals(pa.getLocalMaxMemory(), 100);
    assertEquals(pa.getTotalMaxMemory(), 500);

    assertEquals(ea.getAlgorithm(),EvictionAlgorithm.LRU_MEMORY);
    assertEquals(ea.getAction(), EvictionAction.LOCAL_DESTROY);
    assertEquals(ea.getMaximum(), pa.getLocalMaxMemory());
  }

  public void testPartitionedRegionAttributesForMemLruWithMaxMem() throws CacheException
  {
    final int redundantCopies = 1;
    final int maxMem=25;
    CacheCreation cache = new CacheCreation();

    RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
    attrs.setStatisticsEnabled(true);
    PartitionAttributesFactory paf = new PartitionAttributesFactory();
    paf.setRedundantCopies(redundantCopies);
    paf.setTotalMaxMemory(500);
    paf.setLocalMaxMemory(100);

    AttributesFactory fac = new AttributesFactory(attrs);
    fac.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes(maxMem, null,
          EvictionAction.LOCAL_DESTROY));
    fac.setPartitionAttributes(paf.create());
     cache.createRegion("parRoot", fac.create());

    testXml(cache);

    Cache c = getCache();
    assertNotNull(c);

    Region region = c.getRegion("parRoot");
    assertNotNull(region);

    RegionAttributes regionAttrs = region.getAttributes();
    PartitionAttributes pa = regionAttrs.getPartitionAttributes();
    EvictionAttributes ea = regionAttrs.getEvictionAttributes();

    assertEquals(pa.getRedundantCopies(), 1);
    assertEquals(pa.getLocalMaxMemory(), 100);
    assertEquals(pa.getTotalMaxMemory(), 500);

    assertEquals(ea.getAlgorithm(),EvictionAlgorithm.LRU_MEMORY);
    assertEquals(ea.getAction(), EvictionAction.LOCAL_DESTROY);
    assertNotSame(ea.getMaximum(), maxMem);
    assertEquals(ea.getMaximum(), pa.getLocalMaxMemory());
  }

  public void testReplicatedRegionAttributesForMemLruWithoutMaxMem() throws CacheException
  {
    final int redundantCopies = 1;
    CacheCreation cache = new CacheCreation();

    AttributesFactory fac = new AttributesFactory();
    fac.setDataPolicy(DataPolicy.REPLICATE);
    fac.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes( null,
          EvictionAction.OVERFLOW_TO_DISK));
    cache.createRegion("parRoot", fac.create());

    testXml(cache);

    Cache c = getCache();
    assertNotNull(c);

    Region region = c.getRegion("parRoot");
    assertNotNull(region);

    RegionAttributes regionAttrs = region.getAttributes();
    EvictionAttributes ea = regionAttrs.getEvictionAttributes();

    assertEquals(ea.getAlgorithm(),EvictionAlgorithm.LRU_MEMORY);
    assertEquals(ea.getAction(), EvictionAction.OVERFLOW_TO_DISK);
    assertEquals(ea.getMaximum(), MemLRUCapacityController.DEFAULT_MAXIMUM_MEGABYTES);
  }

  public void testReplicatedRegionAttributesForMemLruWithMaxMem() throws CacheException
  {
    final int redundantCopies = 1;
    final int maxMem=25;
    CacheCreation cache = new CacheCreation();

    AttributesFactory fac = new AttributesFactory();
    fac.setDataPolicy(DataPolicy.REPLICATE);
    fac.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes( maxMem,null,
          EvictionAction.OVERFLOW_TO_DISK));
    cache.createRegion("parRoot", fac.create());

    testXml(cache);

    Cache c = getCache();
    assertNotNull(c);

    Region region = c.getRegion("parRoot");
    assertNotNull(region);

    RegionAttributes regionAttrs = region.getAttributes();
    EvictionAttributes ea = regionAttrs.getEvictionAttributes();
    assertEquals(ea.getAlgorithm(),EvictionAlgorithm.LRU_MEMORY);
    assertEquals(ea.getAction(), EvictionAction.OVERFLOW_TO_DISK);
    assertEquals(ea.getMaximum(), maxMem);
  }

}


text:
(function() {
    'use strict';

    angular.module('app').directive('userShortcut', userShortcut);

    function userShortcut() {
        // Usage:
        // <userShortcut user="theUser"
        //          showYou="true/false" imgOnly="true/false"
        //          anoMode="true/false"></...>
        // user is needed
        // showYou adds (you) if its the logged in user
        // imgOnly only shows the user image / user logo
        // anoMode shows anoProfile user image

        return {
            restrict: 'E',
            replace: true,
            transclude: true,
            scope: {
                user: '=', // same as =user
                showYou: '=',
                imgOnly: '=',
                anoMode: '='
            },
            templateUrl: 'client/directives/userShortcutTemplate.ng.html'//,

        }
    }

})();


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

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Package org.apache.solr.client.solrj.response (Solr 4.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2013-04-29">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.apache.solr.client.solrj.response

Packages that use org.apache.solr.client.solrj.response

org.apache.solr.client.solrj
Primary APIs for communicating with a Solr Server from a Java client.

org.apache.solr.client.solrj.impl
Concrete implementations of client API classes.

org.apache.solr.client.solrj.request
Convenience classes for dealing with various types of Solr requests.

org.apache.solr.client.solrj.response
Convenience classes for dealing with various types of Solr responses.

Classes in org.apache.solr.client.solrj.response used by org.apache.solr.client.solrj

QueryResponse

SolrPingResponse

UpdateResponse

          TODO -- mostly a stub until we have a defined output format

Classes in org.apache.solr.client.solrj.response used by org.apache.solr.client.solrj.impl

UpdateResponse

          TODO -- mostly a stub until we have a defined output format

Classes in org.apache.solr.client.solrj.response used by org.apache.solr.client.solrj.request

CoreAdminResponse

DocumentAnalysisResponse

          A response that is returned by processing the DocumentAnalysisRequest.

FieldAnalysisResponse

          A response that is returned by processing the FieldAnalysisRequest.

LukeResponse

          This is an incomplete representation of the data returned from Luke

QueryResponse

SolrPingResponse

UpdateResponse

          TODO -- mostly a stub until we have a defined output format

Classes in org.apache.solr.client.solrj.response used by org.apache.solr.client.solrj.response

AnalysisResponseBase

          A base class for all analysis responses.

AnalysisResponseBase.AnalysisPhase

          A phase in the analysis process.

AnalysisResponseBase.TokenInfo

          Holds all information of a token as part of an analysis phase.

DocumentAnalysisResponse.DocumentAnalysis

          An analysis process breakdown of a document.

DocumentAnalysisResponse.FieldAnalysis

          An analysis process breakdown for a specific field.

FacetField

          A utility class to hold the facet response.

FacetField.Count

FieldAnalysisResponse.Analysis

          The analysis of a field.

FieldStatsInfo

          Holds stats info

Group

          Represents a group.

GroupCommand

          This class represents the result of a group command.

GroupResponse

          Overall grouping result.

LukeResponse.FieldInfo

LukeResponse.FieldTypeInfo

PivotField

RangeFacet

          Represents a range facet result

RangeFacet.Count

SolrResponseBase

SpellCheckResponse

          Encapsulates responses from SpellCheckComponent

SpellCheckResponse.Collation

SpellCheckResponse.Correction

SpellCheckResponse.Suggestion

TermsResponse

          Encapsulates responses from TermsComponent

TermsResponse.Term

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

          Copyright © 2000-2013 Apache Software Foundation.  All Rights Reserved.


text:
#include <k52/optimization/grid_search.h>

#include <cmath>
#include <stdexcept>
#include <algorithm>

#include <k52/optimization/params/i_continuous_parameters.h>

#include "objective_function_counter.h"

using ::std::vector;

namespace k52
{
namespace optimization
{

GridSearch::GridSearch(double precision, double lower_bound, double upper_bound)
{
    fitness_counter_ = ObjectiveFunctionCounter::shared_ptr(new ObjectiveFunctionCounter(-1));
    lower_bound_ = lower_bound;
    upper_bound_ = upper_bound;
    precision_ = precision;
}

void GridSearch::Optimize(const IObjectiveFunction& function_to_optimize, IParameters* parameters_to_optimize)
{
    IContinuousParameters* continuous_parameters = dynamic_cast<IContinuousParameters*> (parameters_to_optimize);
    if(!continuous_parameters)
    {
        throw std::runtime_error("GridSearch accepts only IContinuousParameters as parameters");
    }

    vector<double> initial_parameters = continuous_parameters->GetValues();

    int size_per_parameter = (int)std::floor((upper_bound_ - lower_bound_)/precision_) + 1;

    if(size_per_parameter <= 0)
    {
        throw std::invalid_argument("upperBound, lowerBound, or precision was set incorrect");
    }

    size_t number_of_parameters = initial_parameters.size();
    size_t total_size = IntegerPow(size_per_parameter, number_of_parameters);

    vector<IContinuousParameters::shared_ptr> parameters_storages(total_size);
    vector<const IParameters*> parameters(total_size);
    //Fill all parameters
    for(size_t i = 0; i < total_size; i++)
    {
        vector<double> values(number_of_parameters);

        for(size_t j = 0; j < number_of_parameters; j++)
        {
            size_t index = i / IntegerPow(size_per_parameter, j);
            values[j] = (index % size_per_parameter) * precision_ + lower_bound_;
        }

        continuous_parameters->SetValues(values);
        parameters_storages[i] = IContinuousParameters::shared_ptr(continuous_parameters->Clone());

        //TODO FIX do not return local ptr
        parameters[i] = parameters_storages[i].get();
    }

    vector<double> counted_values = fitness_counter_->CountObjectiveFunctionValues(parameters, function_to_optimize);
    size_t best_index = std::distance(counted_values.begin(), max_element(counted_values.begin(), counted_values.end()));

    continuous_parameters->SetValues( parameters_storages[best_index]->GetValues() );
}

GridSearch* GridSearch::Clone() const
{
    throw std::logic_error("Cloning is not implemented for GridSearch");
}

std::string GridSearch::get_name() const
{
    return "Grid Search";
}

#ifdef BUILD_WITH_MPI
void GridSearch::Send(boost::mpi::communicator* communicator, int target) const
{
    throw std::logic_error("Send is not implemented for GridSearch");
}

void GridSearch::Receive(boost::mpi::communicator* communicator)
{
    throw std::logic_error("Receive is not implemented for GridSearch");
}
#endif

size_t GridSearch::IntegerPow(size_t value, size_t pow)
{
    size_t result = 1;

    for(size_t i = 0; i < pow; i++)
    {
        result *= value;
    }

    return result;
}

}/* namespace optimization */
}/* namespace k52 */


text:
import React, { Component } from 'react';
import styles from '../../index.scss';
import ContentRowTemplate from './ContentRowTemplate';
import config from '../../config';
import { setContentId } from '../../helpers/contents';

class ContentRowContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      contents: [],
      ratio: 169,
    };
  }
  componentDidMount() {
    // Fetch content
    fetch(config('rest.contentRow')).then(response => response.json()).then((json) => {
      setContentId(json.contents);
      this.setState({
        contents: json.contents,
      });
    });
  }

  changeRatio(e) {
    this.setState({
      ratio: parseInt(e.currentTarget.value, 10),
    });
  }

  render() {
    return (

        <form name="changeRatio">
          Choose ratio

              166
              <input
                id="166"
                onChange={e => this.changeRatio(e)}
                type="radio"
                value={166}
                checked={this.state.ratio === 166}
              />

              169
              <input
                id="169"
                onChange={e => this.changeRatio(e)}
                type="radio"
                value={169}
                checked={this.state.ratio === 169}
              />

              34
              <input
                id="34"
                onChange={e => this.changeRatio(e)}
                type="radio"
                value={34}
                checked={this.state.ratio === 34}
              />

        </form>
        <ContentRowTemplate ratio={this.state.ratio} contents={this.state.contents} />

    );
  }
}

export default ContentRowContainer;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
alert("guwno");
jQuery(document).ready(function()
{
$('#search_suggest').keyup(function(key)
{
    var value = this.value;
    var x;
    $.ajax({
        type: "POST",
        url: path_to_controller,
        data: { "value" : value},
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            alert('Error: ' + errorThrown + '\n' + textStatus);
        }

    }).done(function(result)
    {
        if(result.suggestionsArray)
        {
            var suggestions = result.suggestionsArray;
            console.log(suggestions);
            $('#search_suggest').autocomplete({
                position: { my: "right top", at: "right bottom" },
                autoFocus: true,
                disabled: false,
                minLength: 0
            });
            $( "#search_suggest" ).autocomplete({
                        source: function( request, response ) {
                        var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
                        response( $.grep( suggestions, function( item ){
                        return matcher.test( item );
                        }) );
                        }
                        });
        }
    });
});
});


text:
package websocket

import (
	"reflect"

	"github.com/OpenFactorioServerManager/factorio-server-manager/bootstrap"
)

// the hub, that is exported and can be used anywhere to work with the websocket
var WebsocketHub *wsHub

var LogCache []string

// a controlHandler is used to determine, if something has to be done, on a specific command.
// register a handler with `wsHub.RegisterControlHandler`
// unregister a handler with `wsHub.UnregisterControlHandler`
type controlHandler func(controls WsControls)

// The type for of control messages.
// Type ans Value both have to be set, if controls are sent.
// Currently supported Type:
// - `subscribe` - Value used as room name
// - `unsubscribe` - Value used as room name
// - `command` - Value contains the command to execute
type WsControls struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

// the main message of our websocket protocol.
// if the room_name is an empty string, this will be sent as broadcast
// if controls is not empty, this will not be sent anywhere, but used as commands, to join/leave rooms and to send commands to the factorio server
type wsMessage struct {
	RoomName string      `json:"room_name"`
	Message  interface{} `json:"message,omitempty"`
	Controls WsControls  `json:"controls,omitempty"`
}

type wsRoom struct {
	// same as the key of the map in the wsHub
	name string

	// clients that are in this room. This list is a sublist of the one inside the hub
	clients map[*wsClient]bool

	// register a client to this room
	register chan *wsClient

	// unregister a client from this room, if no clients remain, this room will be deleted
	unregister chan *wsClient

	// send a message to all clients in this room
	send chan wsMessage
}

// Hub is the basic setup of the server.
// It contains everything needed for the websocket to run.
// Only the controlHandler Subscriptions are public, everything else can be controlled with the functions and the wsClient.
type wsHub struct {
	// list of all connected clients
	clients map[*wsClient]bool

	// Messages that should be sent to ALL clients
	broadcast chan wsMessage

	// a list of all rooms
	rooms map[string]*wsRoom

	// register a client to this hub
	register chan *wsClient

	// unregister a client from this hub
	unregister chan *wsClient

	// run a control message on all registered controlHandler
	runControl chan WsControls

	// list of all registered controlHandlers
	controlHandlers map[reflect.Value]controlHandler

	// register a controlHandler
	RegisterControlHandler chan controlHandler

	// unregister a controlHandler
	UnregisterControlHandler chan controlHandler
}

// initialize and run the mein websocket hub.
func init() {
	WebsocketHub = &wsHub{
		broadcast:                make(chan wsMessage),
		register:                 make(chan *wsClient),
		rooms:                    make(map[string]*wsRoom),
		unregister:               make(chan *wsClient),
		clients:                  make(map[*wsClient]bool),
		runControl:               make(chan WsControls),
		controlHandlers:          make(map[reflect.Value]controlHandler),
		RegisterControlHandler:   make(chan controlHandler),
		UnregisterControlHandler: make(chan controlHandler),
	}

	go WebsocketHub.run()
}

// remove a client from this hub and all of its rooms
func (hub *wsHub) removeClient(client *wsClient) {
	delete(hub.clients, client)
	close(client.send)
	for _, room := range hub.rooms {
		room.unregister <- client
	}
}

// run starts a websocket hub, this has to be done in a subroutine `go hub.run()`
func (hub *wsHub) run() {
	for {
		select {
		case client := <-hub.register:
			hub.clients[client] = true
		case client := <-hub.unregister:
			if _, ok := hub.clients[client]; ok {
				hub.removeClient(client)
			}
		case message := <-hub.broadcast:
			for client := range hub.clients {
				select {
				case client.send <- message:
				default:
					hub.removeClient(client)
				}
			}
		case function := <-hub.RegisterControlHandler:
			hub.controlHandlers[reflect.ValueOf(function)] = function
		case function := <-hub.UnregisterControlHandler:
			delete(hub.controlHandlers, reflect.ValueOf(function))
		}
	}
}

// Broadcast a message to all connected clients (only clients connected to this room).
func (hub *wsHub) Broadcast(message interface{}) {
	hub.broadcast <- wsMessage{
		RoomName: "",
		Message:  message,
	}
}

// get a websocket room or create it, if it doesn't exist yet.
// Also starts the rooms subroutine `wsRoom.run()`
func (hub *wsHub) GetRoom(name string) *wsRoom {
	if room, ok := hub.rooms[name]; ok {
		return room
	} else {
		room := &wsRoom{
			name:       name,
			clients:    make(map[*wsClient]bool),
			register:   make(chan *wsClient),
			unregister: make(chan *wsClient),
			send:       make(chan wsMessage),
		}
		hub.rooms[name] = room
		go room.run()
		return room
	}
}

// run starts a websocket room. This has to be run as a subroutine `go room.run()`
func (room *wsRoom) run() {
	for {
		select {
		case client := <-room.register:
			room.clients[client] = true

			// some hardcoded stuff for gamelog room
			if room.name == "gamelog" {
				// send cached log to registered client
				for _, logLine := range LogCache {
					client.send <- wsMessage{
						RoomName: "gamelog",
						Message:  logLine,
					}
				}
			}
		case client := <-room.unregister:
			if _, ok := room.clients[client]; ok {
				delete(room.clients, client)
				// FIXME when more rooms are used, remove empty rooms.
				// Since we only have a few rooms at the same time, just keep them.
				// This is code, that will cause a concurrent call on `wsHub.rooms`.
				// To fix this, move the deletion into the hub.
				// Be careful to think about race conditions, if a user registered to the room, before room was really deleted.
				//if len(room.clients) == 0 {
				//	//remove this room
				//	delete(room.hub.rooms, room.name)
				//	return
				//}
			}
		case message := <-room.send:
			for client := range room.clients {
				select {
				case client.send <- message:
				default:
					room.unregister <- client
				}
			}

			// some hardcoded stuff for gamelog room
			if room.name == "gamelog" {
				// add the line to the cache
				LogCache = append(LogCache, message.Message.(string))
				config := bootstrap.GetConfig()

				// When cache is bigger than max size, delete one line
				if len(LogCache) > config.ConsoleCacheSize {
					LogCache = LogCache[1:]
				}
			}
		}
	}
}

// Send a message into this room.
func (room *wsRoom) Send(message interface{}) {
	room.send <- wsMessage{
		RoomName: room.name,
		Message:  message,
	}
}


text:
@implementation TuijianViewController (Delegate)

@end


text:
import logging

from pin import machine
from pin.lib import p, ui
from pin.lib.ui import effects
from pin.lib.handler import Handler
from . import banner, display

log = logging.getLogger("pin")

class Mode(Handler):

    def setup(self):
        self.timer = None
        self.panel = None
        machine.user_bypass(self, self.done)

    def on_enable(self):
        if p.data.get("cleared", False):
            p.mixer.play("settings_cleared")
            self.panel = display.Info()
            self.show(self.panel)
            self.panel.description.update(padding_top=1)
            self.panel.description.show("Settings Cleared")
            self.panel.description.effect("fill_blink", duration=0.25, repeat=2)
            self.wait(5.0, self.done)
        elif p.data.get("simulator_enabled", False):
            p.mixer.play("warning")
            self.panel = display.Warning()
            self.show(self.panel)
            self.panel.description.show("Simulator On")
            self.panel.title.effect("blink", on=0.4, off=0.1, repeat=4)
            self.wait(5.0, self.done)
        else:
            self.disable()

    def on_disable(self):
        p.modes["banner"].enable()

    def done(self):
        self.cancel(self.timer)
        self.disable()


text:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;

public class HitBox : NetworkBehaviour
{
    /// <summary>
    /// 技能的施放者
    /// </summary>
    [Tooltip("动态分配不需填写"), SyncVar]
    public NetworkIdentity player;

    /// <summary>
    /// 子弹的旋转
    /// </summary>
    [SyncVar]
    protected Quaternion rotate;

    /// <summary>
    /// 技能编号
    /// </summary>
    [SyncVar]
    protected int skillNo;

    /// <summary>
    /// 技能编号
    /// </summary>
    public int SkillNo
    {
        get
        {
            return skillNo;
        }
    }

    /// <summary>
    /// 保护期
    /// </summary>
    public bool ProtectTime { get; set; }

    /// <summary>
    /// 当下一次可能的时候删除对象
    /// </summary>
    protected bool DestroyWhenPossible { get; set; }

    /// <summary>
    /// 技能作为攻击方的种类
    /// 一般和防御方种类是一致的
    /// </summary>
    public Skill.SkillType skillType;

    /// <summary>
    /// 受伤方式,如果有可能的话影响受伤后的动画
    /// 不影响游戏机制
    /// </summary>
    public enum HurtStyle
    {
        NoHurt,
        LightHurt,
        HeavyHurt,
        BlowAway,

        /// <summary>
        /// 目前游戏机制里就没倒地设定QAQ……
        /// </summary>
        KnockDown,
    }
    public HurtStyle hurtStyle = HurtStyle.LightHurt;

    /// <summary>
    /// 屏蔽列表,在此列表中的角色不会再次参与判定
    /// </summary>
    protected List<NetworkIdentity> maskList;

    /// <summary>
    /// 存续时间
    /// </summary>
    [SyncVar]
    protected float lifeTime;

    void Awake()
    {
        maskList = new List<NetworkIdentity>();
        ProtectTime = false;
        DestroyWhenPossible = false;
    }

    protected virtual void Start()
    {
        if (gameObject.layer != LayerMask.NameToLayer("HitBox"))
        {
            throw new UnityException("判定盒必须位于HitBox层");
        }

        transform.rotation = this.rotate;
        Invoke("KillSelf", lifeTime);
    }

    protected void KillSelf()
    {
        DestroyWhenPossible = true;
    }

    /// <summary>
    /// 在防御方OnHit后调用
    /// 只在服务器调用
    /// </summary>
    /// <param name="target">命中的目标角色</param>
    /// <param name="holdType">防御方技能种类</param>
    /// <returns>改变后的技能种类</returns>
    /// <remarks>大部分情况并不需要重载这个函数</remarks>
    public virtual Skill.SkillType OnHitType(GameObject target, Skill.SkillType holdType)
    {
        return skillType;
    }

    /// <summary>
    /// 刚刚命中某个目标时的判定
    /// </summary>
    /// <param name="isServer">是否是服务器</param>
    /// <param name="target">命中目标角色</param>
    /// <returns>命中是否有效</returns>
    /// <remarks>大部分情况并不需要重载这个函数</remarks>
    public virtual bool OnHitStart(bool isServer, GameObject target)
    {
        if (target.GetComponent<NetworkIdentity>() == player)
        {
            return false;
        }
        if (maskList.Exists(obj => obj == target.GetComponent<NetworkIdentity>()))
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// 命中判定已经成功,产生特定效果时调用
    /// </summary>
    /// <param name="isServer">是否是服务器</param>
    /// <param name="target">命中目标角色</param>
    /// <param name="isBlocked">是否被防御(是确定计算的防御)</param>
    public virtual void OnTakeEffect(bool isServer, GameObject target, bool isBlocked)
    {
        maskList.Add(target.GetComponent<NetworkIdentity>());
    }

    /// <summary>
    /// <para>创建HitBox对象并设置基本属性</para>
    /// 之后需要手动Spawn
    /// </summary>
    /// <param name="prefab">HitBox的预制件</param>
    /// <param name="pos">创建位置</param>
    /// <param name="rotate">创建方位</param>
    /// <param name="skill">创建的技能</param>
    /// <param name="lifeTime">存续时间</param>
    /// <returns>新创建的HitBox</returns>
    public static GameObject Create(Object prefab, Vector3 pos, Quaternion rotate, Skill skill, float lifeTime)
    {
        pos += Vector3.up * 1.6f; //身高补正
        var ret = (GameObject)Instantiate(prefab, pos, rotate);
        var hitBox = ret.GetComponent<HitBox>();
        hitBox.rotate = rotate;
        hitBox.player = skill.Player.GetComponent<NetworkIdentity>();
        hitBox.skillNo = skill.SkillNo;
        hitBox.lifeTime = lifeTime;
        return ret;
    }

    virtual protected void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.layer == LayerMask.NameToLayer("Player"))
        {
            //此时仍然不能判断击中的是否是玩家,因为有可能是创造物
            //所以交给对方处理
        }
        else if (other.gameObject.layer == LayerMask.NameToLayer("HitBox"))
        {
            //相杀,这里选择不处理
        }
        else if (other.gameObject.layer == LayerMask.NameToLayer("Default"))
        {
            //默认层的是障碍物,如果是服务器,则直接删除对象
            if(isServer)
                DestroyWhenPossible = true;
        }
    }

    protected Vector3 GetHitDir(GameObject target)
    {
        var ret = target.transform.position - transform.position;
        ret.y = 0.0f; //消除身高的补正
        ret.Normalize();
        return ret;
    }

    protected virtual void Update()
    {
        if (isServer && DestroyWhenPossible && !ProtectTime)
            Destroy(gameObject);
    }
}


text:
'''
Created on May 11, 2015

@author: yunli
'''

#### ================================================================
#### ================================================================
####                    OpenClos Error Code
#### ================================================================
#### ================================================================

EC_OK                                       = 0

# client side
# validation error at 1000 level
EC_INVALID_CONFIGURATION                    = 1000
EC_INVALID_REQUEST                          = 1001
EC_MISSING_MANDATORY_ATTRIBUTE              = 1002
EC_INSUFFICIENT_LOOPBACK_IP                 = 1003
EC_INSUFFICIENT_VLAN_IP                     = 1004
EC_INSUFFICIENT_INTERCONNECT_IP             = 1005
EC_INSUFFICIENT_MANAGEMENT_IP               = 1006
EC_CAPACITY_CANNOT_CHANGE                   = 1007
EC_CAPACITY_MISMATCH                        = 1008
EC_ENUMERATION_MISMATCH                     = 1009
EC_INVALID_UPLINK_THRESHOLD                 = 1010
EC_INVALID_IP_FORMAT                        = 1011
# "not found" error at 1100 level
EC_POD_NOT_FOUND                            = 1100
EC_CABLING_PLAN_NOT_FOUND                   = 1101
EC_DEVICE_CONFIGURATION_NOT_FOUND           = 1102
EC_DEVICE_NOT_FOUND                         = 1103
EC_IMAGE_NOT_FOUND                          = 1104

# server side
# error at 2000 level
EC_CREATE_POD_FAILED                        = 2000
EC_UPDATE_POD_FAILED                        = 2001
EC_DEVICE_CONNECT_FAILED                    = 2002
EC_DEVICE_RPC_FAILED                        = 2003
EC_L2_DATA_COLLECTION_FAILED                = 2004
EC_L3_DATA_COLLECTION_FAILED                = 2005
EC_TWO_STAGE_CONFIGURATION_FAILED           = 2006
EC_TRAP_DAEMON_ERROR                        = 2007

dictErrorCode = {
    EC_OK                                       :   "Success",
    EC_INVALID_CONFIGURATION                    :   "Invalid configuration: %s",
    EC_INVALID_REQUEST                          :   "Invalid request: %s",
    EC_MISSING_MANDATORY_ATTRIBUTE              :   "Missing mandatory attribute: %s",
    EC_INSUFFICIENT_LOOPBACK_IP                 :   "Insufficient loopback ip: %s",
    EC_INSUFFICIENT_VLAN_IP                     :   "Insufficient vlan ip: %s",
    EC_INSUFFICIENT_INTERCONNECT_IP             :   "Insufficient interconnect ip: %s",
    EC_INSUFFICIENT_MANAGEMENT_IP               :   "Insufficient management ip: %s",
    EC_CAPACITY_CANNOT_CHANGE                   :   "Capacity cannot be changed: %s",
    EC_CAPACITY_MISMATCH                        :   "Device count does not match capacity: %s",
    EC_ENUMERATION_MISMATCH                     :   "Invalid enumeration value: %s",
    EC_INVALID_UPLINK_THRESHOLD                 :   "Invalid uplink threshold: %s",
    EC_INVALID_IP_FORMAT                        :   "Invalid ip format: %s",
    EC_POD_NOT_FOUND                            :   "Pod not found: %s",
    EC_CABLING_PLAN_NOT_FOUND                   :   "Cabling plan not found: %s",
    EC_DEVICE_NOT_FOUND                         :   "Device not found: %s",
    EC_DEVICE_CONFIGURATION_NOT_FOUND           :   "Device configuration not found: %s",
    EC_IMAGE_NOT_FOUND                          :   "Image not found: %s",
    EC_CREATE_POD_FAILED                        :   "Failed to create pod: %s",
    EC_UPDATE_POD_FAILED                        :   "Failed to update pod: %s",
    EC_DEVICE_CONNECT_FAILED                    :   "Failed to connect to device: %s",
    EC_DEVICE_RPC_FAILED                        :   "Failed to execute RPC command on device: %s",
    EC_L2_DATA_COLLECTION_FAILED                :   "Failed to collect L2 data: %s",
    EC_L3_DATA_COLLECTION_FAILED                :   "Failed to collect L3 data: %s",
    EC_TWO_STAGE_CONFIGURATION_FAILED           :   "Failed to execute two stage configuration: %s",
    EC_TRAP_DAEMON_ERROR                        :   "Trap daemon error: %s",
}

def getErrorMessage(errorCode):
    assert errorCode in dictErrorCode.keys()
    return dictErrorCode[errorCode]


text:
<#assign bathPath=springMacroRequestContext.getContextPath() />

<#include "/tags/tag.html"/>

<#include "/tags/local_tags.html"/>
<!DOCTYPE html>

<#include "/public/header.html"/>

${title}

					<form method="post" class="form-horizontal" id="searchForm">

							 <@input_local id="category_search" name="category" value="" text="字典类型"/>

							 <@select_tag id='enable_search' name='enable' value='ENABLE' text='状态' check='true'/>

								<button type="button" class="btn btn-sm btn-success" id="searchBtn">
									 查询
								</button>
								<button type="button" class="btn btn-sm btn-reset" id="reset">
									 重置
								</button>

					</form>

					<@shiro.hasPermission name="sys.dic.add">
					<button id="add" type="button" class="btn btn-outline btn-default">
						 新增
					</button>
					</@shiro.hasPermission>
					<@shiro.hasPermission name="sys.dic.update">
					<button id="edit" type="button" class="btn btn-outline btn-default">
						 编辑
					</button>
					</@shiro.hasPermission>
					<@shiro.hasPermission name="sys.dic.cancel">
					<button id="cancel" type="button" class="btn btn-outline btn-default">
						 锁定
					</button>
					</@shiro.hasPermission>
					<@shiro.hasPermission name="sys.dic.delete">
					<button id="delete" type="button" class="btn btn-outline btn-default">
						 删除
					</button>
					</@shiro.hasPermission>

					<button type="button" class="close" data-dismiss="modal">
						×Close
					</button>

新增字典

					 <form class="form-horizontal m-t" action="save" method="post" id="signupForm">
					 		<input id="id" name="id" type="text" style="display:none"/>
					 		<@input_local id="category" name="category" value="" text="字典类型:" />
                             <@input_local id="categoryName" name="categoryName" value="" text="字典描述:" />
                             <@input_local id="codeValue" name="codeValue" value="" text="字典属性:" />
                             <@input_local id="codeText" name="codeText" value="" text="字典含义:" />
                             <@input_local id="sortNo" name="sortNo" value="" text="字典排序:" />
                        </form>

					<button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="save">保存</button>

<#include "/public/base_js.html"/>


text:
'use strict';

const ResourceBase = require('./resourceBase');

class USAutocompletions extends ResourceBase {

  constructor (config) {
    super('us_autocompletions', config);
  }

  autocomplete (params, query_param, callback) {
    if (typeof query_param === 'function') {
      callback = query_param;
      query_param = {};
    }
    return this._transmit('POST', null, query_param, params, null, callback);
  }

}

module.exports = USAutocompletions;