repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
liuguoquan727/library
|
core/src/main/java/com/mdroid/lib/core/base/BaseWebView.java
|
package com.mdroid.lib.core.base;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.mdroid.lib.core.dialog.CenterDialog;
import com.mdroid.lib.core.dialog.IDialog;
import com.mdroid.utils.AndroidUtils;
import com.orhanobut.dialogplus.DialogPlus;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class BaseWebView extends WebView {
protected boolean mIsDestroy;
public BaseWebView(Context context) {
this(context, null);
}
public BaseWebView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BaseWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setWebViewClient(new MyWebViewClient());
setWebChromeClient(new MyWebChromeClient());
WebSettings webSettings = getSettings();
webSettings.setUserAgentString(webSettings.getUserAgentString() + "/ydbus");
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
setBackgroundColor(0xFFFFFFFF);
}
@Override protected void onDraw(Canvas canvas) {
try {
super.onDraw(canvas);
} catch (Exception ignored) {
}
}
@Override public void loadUrl(String url) {
Map<String, String> header = getHeader();
header.put("pageDataType", "web");
super.loadUrl(url, header);
}
@Override public void destroy() {
mIsDestroy = true;
ViewParent view = getParent();
if (view instanceof ViewGroup) {
((ViewGroup) view).removeView(this);
}
removeAllViews();
super.destroy();
}
private Map<String, String> getHeader() {
Map<String, String> map = new HashMap<String, String>();
map.put("device", getAppInfo());
return map;
}
private String getAppInfo() {
Map<String, Object> map = new HashMap<>();
map.put("client", "android");
map.put("os_version", Build.VERSION.SDK_INT + "");
map.put("ver", AndroidUtils.getVersionCode(getContext()) + "");
map.put("network", AndroidUtils.getNetworkType(getContext()));
return format(map);
}
private String format(Map<String, Object> params) {
try {
final StringBuilder result = new StringBuilder();
Set<String> keys = params.keySet();
for (final String key : keys) {
final Object value = params.get(key);
if (value == null) continue;
if (result.length() > 0) result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
} catch (UnsupportedEncodingException e) {
// Impossible!
throw new IllegalArgumentException(e);
}
}
public class MyWebChromeClient extends BaseChromeClient {
@Override public void onGeolocationPermissionsShowPrompt(final String origin,
final GeolocationPermissions.Callback callback) {
if (mIsDestroy) return;
CenterDialog.create(getContext(), null, origin + "需要获取您的地理位置", "拒绝",
new IDialog.OnClickListener() {
@Override public void onClick(DialogPlus dialog, View view) {
dialog.dismiss();
callback.invoke(origin, false, false);
}
}, "允许", new IDialog.OnClickListener() {
@Override public void onClick(DialogPlus dialog, View view) {
dialog.dismiss();
callback.invoke(origin, true, true);
}
}).show();
}
}
/**
* 自定义WebViewClient,否则会自动跳转到系统的浏览器的
*/
public class MyWebViewClient extends WebViewClient {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (TextUtils.isEmpty(url)) {
return false;
}
// 电话短信拦截
if (url.startsWith("sms:") || url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
getContext().startActivity(intent);
return true;
}
return true;
}
}
}
|
Nuclear-Liu/Learning
|
Base/src/test/java/org/nuclear/ch03/StringBuilderTest.java
|
package org.nuclear.ch03;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringBuilderTest {
@Test
public void testStringBuilder() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("HELLO");
assertEquals(stringBuilder.toString(), "HELLO");
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("HELLO");
}
}
|
kevinnguyenai/my-ddd-backend
|
src/interfaces/http/Server.js
|
const express = require('express');
const https = require('https');
const fs = require('fs');
const path = require('path');
const { Enforcer } = require('casbin');
class Server {
constructor({ config, router, logger, auth }) {
this.config = config;
this.logger = logger;
this.https = https;
this.fs = fs;
this.enforcer = new Enforcer(config.casbinModel, config.casbinPolicy);
this.express = express();
this.express.disable('x-powered-by');
this.express.use(auth.initialize());
this.express.use(router);
}
start() {
return new Promise((resolve) => {
const options = {
key: this.fs.readFileSync(path.join(__dirname, './ssl/key.pem')),
cert: this.fs.readFileSync(path.join(__dirname,'./ssl/cert.pem'))
}
const http = this.https.createServer(options, this.express).listen(this.config.web.port, ()=> {
const { port } = http.address();
this.logger.info(`[p ${process.pid}] Listening at port ${port}`);
resolve();
});
});
}
/*
start() {
return new Promise((resolve) => {
const http = this.express
.listen(this.config.web.port, () => {
const { port } = http.address();
this.logger.info(`[p ${process.pid}] Listening at port ${port}`);
resolve();
});
});
}
*/
}
module.exports = Server;
|
nokok/masq
|
src/main/java/net/nokok/masq/cli/ArgsParser.java
|
package net.nokok.masq.cli;
import net.nokok.masq.args.Arguments;
import net.nokok.masq.args.NoArgumentException;
import net.nokok.masq.args.UnknownOptionException;
import net.nokok.masq.cli.context.Context;
import net.nokok.masq.cli.context.ErrorContext;
import net.nokok.masq.cli.context.StandardContext;
import net.nokok.masq.impl.SupportedFileTypes;
import net.nokok.masq.io.InputFile;
import net.nokok.masq.io.InputFiles;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
public class ArgsParser {
private final SupportOptionSet supportOptionSet;
public ArgsParser() {
this(SupportOptionSet.DEFAULT);
}
public ArgsParser(SupportOptionSet supportOptionSet) {
this.supportOptionSet = supportOptionSet;
}
public Context parse(String... rawArgs) {
Objects.requireNonNull(rawArgs);
if (rawArgs.length == 0) {
return new ErrorContext();
}
Arguments arguments = new Arguments(supportOptionSet, rawArgs);
List<Flag> flags = new ArrayList<>();
List<Path> files = new ArrayList<>();
SupportedFileTypes fileTypes = SupportedFileTypes.DEFAULT;
String replaceString = "<mask>";
while (arguments.hasNext()) {
arguments.next();
try {
if (arguments.wasOption()) {
Option option = arguments.asOption();
switch (option) {
case HELP -> flags.add(Flag.SHOW_HELP);
case INPUT_FORMAT -> fileTypes = arguments.nextOptionString(SupportedFileTypes::fromOptionString, formatType -> "Invalid format type : " + formatType);
case REPLACE_STRING -> replaceString = arguments.nextOptionString(() -> "No Replace String");
}
} else if (arguments.wasFile()) {
files.add(arguments.asPath());
}
} catch (UnknownOptionException | NoArgumentException e) {
return new ErrorContext(e.getMessage());
}
}
if (flags.contains(Flag.SHOW_HELP)) {
// show usage
return new ErrorContext();
}
if (files.isEmpty()) {
return new ErrorContext("No input files");
}
final SupportedFileTypes confirmedFileType = fileTypes;
return new StandardContext(System.out, new InputFiles(files.stream().map(f -> InputFile.of(f, confirmedFileType)).toList()), new Flags(new HashSet<>(flags)), replaceString);
}
}
|
pulibrary/figgy
|
spec/helpers/bounding_box_helper_spec.rb
|
# frozen_string_literal: true
require "rails_helper"
describe BoundingBoxHelper do
let(:property) { :coverage }
let(:coverage) { ["northlimit=37.894363; eastlimit=-121.988754; southlimit=37.622934; westlimit=-122.481766; units=degrees; projection=EPSG:4326"] }
let(:change_set) { ScannedMapChangeSet.new(ScannedMap.new(coverage: coverage)) }
describe "#bbox_input" do
it "builds bounding box selector" do
expect(helper.bbox_input(property, change_set)).to include("data-input-id='scanned_map_coverage'")
expect(helper.bbox_input(property, change_set)).to include("data-coverage='#{coverage}'")
end
end
describe "#bbox_display_inputs" do
subject { helper.bbox_display_inputs }
it { is_expected.to include("North", "East", "South", "West") }
end
end
|
seigtm/meov
|
src/utils/utils.hpp
|
#pragma once
#include <memory>
namespace meov::utils {
/** @warning Use this class only for final classes! */
template<class Base>
class AsReference {
public:
using Ref = std::shared_ptr<Base>;
using WeakRef = std::weak_ptr<Base>;
using Ptr = std::unique_ptr<Base>;
};
template<class Base>
class NonCopyable {
public:
NonCopyable(const NonCopyable &) = delete;
NonCopyable &operator=(const NonCopyable &) = delete;
Base &operator=(const Base &) = delete;
protected:
NonCopyable() = default;
~NonCopyable() = default;
};
template<class Base>
class Singleton : public NonCopyable<Base> {
public:
static Base *Instance() {
static Base inst;
return &inst;
}
protected:
Singleton() = default;
~Singleton() = default;
};
} // namespace meov::utils
|
DenisBuserski/-Softuni_Programming_Fundamentals_Java
|
05_Programming_Fundamentals_Final_Exam/Activation_Keys_01.java
|
import java.util.Scanner;
public class Activation_Keys_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String startKey = scanner.nextLine();
String input = scanner.nextLine();
while (!input.equals("Generate")) {
String[] inputArray = input.split(">>>");
String command = inputArray[0];
switch (command) {
case "Contains":
String substring = inputArray[1];
if (startKey.contains(substring)) {
System.out.printf("%s contains %s%n", startKey, substring);
} else {
System.out.printf("Substring not found!%n");
}
break;
case "Flip":
String secondCommand = inputArray[1];
int startIndexF = Integer.parseInt(inputArray[2]);
int endIndexF = Integer.parseInt(inputArray[3]);
String selectedPart = "";
String newInput = "";
if (secondCommand.equals("Upper")) {
selectedPart = startKey.substring(startIndexF, endIndexF);
newInput = selectedPart.toUpperCase();
startKey = startKey.replaceAll(selectedPart, newInput);
System.out.printf("%s%n", startKey);
} else if (secondCommand.equals("Lower")) {
selectedPart = startKey.substring(startIndexF, endIndexF);
newInput = selectedPart.toLowerCase();
startKey = startKey.replaceAll(selectedPart, newInput);
System.out.printf("%s%n", startKey);
}
break;
case "Slice":
String toDelete = "";
int startIndex = Integer.parseInt(inputArray[1]);
int endIndex = Integer.parseInt(inputArray[2]);
toDelete = startKey.substring(startIndex, endIndex);
startKey = startKey.replaceAll(toDelete, "");
System.out.printf("%s%n", startKey);
break;
}
input = scanner.nextLine();
}
System.out.printf("Your activation key is: %s%n", startKey);
}
}
|
bulain/boot-demo
|
mybatis-demo/src/main/java/com/bulain/mybatis/demo/pojo/BlogSearch.java
|
package com.bulain.mybatis.demo.pojo;
import com.bulain.mybatis.core.pojo.Search;
public class BlogSearch extends Search {
private static final long serialVersionUID = 1L;
private String title;
private String descr;
private String activeFlag;
private String createdVia;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
public String getActiveFlag() {
return activeFlag;
}
public void setActiveFlag(String activeFlag) {
this.activeFlag = activeFlag;
}
public String getCreatedVia() {
return createdVia;
}
public void setCreatedVia(String createdVia) {
this.createdVia = createdVia;
}
}
|
bufsize/akka
|
akka-stream/src/main/scala/akka/stream/impl/ActorProcessor.scala
|
<reponame>bufsize/akka
/*
* Copyright (C) 2014-2019 Lightbend Inc. <https://www.lightbend.com>
*/
package akka.stream.impl
import akka.actor._
import akka.annotation.InternalApi
import akka.stream.{ AbruptTerminationException, ActorMaterializerSettings, Attributes }
import akka.stream.actor.ActorSubscriber.OnSubscribe
import akka.stream.actor.ActorSubscriberMessage.{ OnComplete, OnError, OnNext }
import org.reactivestreams.{ Processor, Subscriber, Subscription }
import akka.event.Logging
import akka.util.unused
/**
* INTERNAL API
*/
@InternalApi private[akka] object ActorProcessor {
def apply[I, O](impl: ActorRef): ActorProcessor[I, O] = {
val p = new ActorProcessor[I, O](impl)
// Resolve cyclic dependency with actor. This MUST be the first message no matter what.
impl ! ExposedPublisher(p.asInstanceOf[ActorPublisher[Any]])
p
}
}
/**
* INTERNAL API
*/
@InternalApi private[akka] class ActorProcessor[I, O](impl: ActorRef)
extends ActorPublisher[O](impl)
with Processor[I, O] {
override def onSubscribe(s: Subscription): Unit = {
ReactiveStreamsCompliance.requireNonNullSubscription(s)
impl ! OnSubscribe(s)
}
override def onError(t: Throwable): Unit = {
ReactiveStreamsCompliance.requireNonNullException(t)
impl ! OnError(t)
}
override def onComplete(): Unit = impl ! OnComplete
override def onNext(elem: I): Unit = {
ReactiveStreamsCompliance.requireNonNullElement(elem)
impl ! OnNext(elem)
}
}
/**
* INTERNAL API
*/
@InternalApi private[akka] abstract class BatchingInputBuffer(val size: Int, val pump: Pump)
extends DefaultInputTransferStates {
if (size < 1) throw new IllegalArgumentException(s"buffer size must be positive (was: $size)")
if ((size & (size - 1)) != 0) throw new IllegalArgumentException(s"buffer size must be a power of two (was: $size)")
// TODO: buffer and batch sizing heuristics
private var upstream: Subscription = _
private val inputBuffer = new Array[AnyRef](size)
private var inputBufferElements = 0
private var nextInputElementCursor = 0
private var upstreamCompleted = false
private val IndexMask = size - 1
private def requestBatchSize = math.max(1, inputBuffer.length / 2)
private var batchRemaining = requestBatchSize
override def toString: String =
s"BatchingInputBuffer(size=$size, elems=$inputBufferElements, completed=$upstreamCompleted, remaining=$batchRemaining)"
override val subreceive: SubReceive = new SubReceive(waitingForUpstream)
override def dequeueInputElement(): Any = {
val elem = inputBuffer(nextInputElementCursor)
inputBuffer(nextInputElementCursor) = null
batchRemaining -= 1
if (batchRemaining == 0 && !upstreamCompleted) {
upstream.request(requestBatchSize)
batchRemaining = requestBatchSize
}
inputBufferElements -= 1
nextInputElementCursor += 1
nextInputElementCursor &= IndexMask
elem
}
protected final def enqueueInputElement(elem: Any): Unit = {
if (isOpen) {
if (inputBufferElements == size) throw new IllegalStateException("Input buffer overrun")
inputBuffer((nextInputElementCursor + inputBufferElements) & IndexMask) = elem.asInstanceOf[AnyRef]
inputBufferElements += 1
}
pump.pump()
}
override def cancel(): Unit = {
if (!upstreamCompleted) {
upstreamCompleted = true
if (upstream ne null) upstream.cancel()
clear()
}
}
override def isClosed: Boolean = upstreamCompleted
private def clear(): Unit = {
java.util.Arrays.fill(inputBuffer, 0, inputBuffer.length, null)
inputBufferElements = 0
}
override def inputsDepleted = upstreamCompleted && inputBufferElements == 0
override def inputsAvailable = inputBufferElements > 0
protected def onComplete(): Unit = {
upstreamCompleted = true
subreceive.become(completed)
pump.pump()
}
protected def onSubscribe(subscription: Subscription): Unit = {
ReactiveStreamsCompliance.requireNonNullSubscription(subscription)
if (upstreamCompleted) subscription.cancel()
else {
upstream = subscription
// Prefetch
upstream.request(inputBuffer.length)
subreceive.become(upstreamRunning)
}
pump.gotUpstreamSubscription()
}
protected def onError(e: Throwable): Unit = {
upstreamCompleted = true
subreceive.become(completed)
inputOnError(e)
}
protected def waitingForUpstream: Actor.Receive = {
case OnComplete => onComplete()
case OnSubscribe(subscription) => onSubscribe(subscription)
case OnError(cause) => onError(cause)
}
protected def upstreamRunning: Actor.Receive = {
case OnNext(element) => enqueueInputElement(element)
case OnComplete => onComplete()
case OnError(cause) => onError(cause)
case OnSubscribe(subscription) => subscription.cancel() // spec rule 2.5
}
protected def completed: Actor.Receive = {
case OnSubscribe(_) => throw new IllegalStateException("onSubscribe called after onError or onComplete")
}
protected def inputOnError(@unused e: Throwable): Unit = {
clear()
}
}
/**
* INTERNAL API
*/
@InternalApi private[akka] class SimpleOutputs(val actor: ActorRef, val pump: Pump)
extends DefaultOutputTransferStates {
import ReactiveStreamsCompliance._
protected var exposedPublisher: ActorPublisher[Any] = _
protected var subscriber: Subscriber[Any] = _
protected var downstreamDemand: Long = 0L
protected var downstreamCompleted = false
override def demandAvailable = downstreamDemand > 0
override def demandCount: Long = downstreamDemand
override def subreceive = _subreceive
private val _subreceive = new SubReceive(waitingExposedPublisher)
def isSubscribed = subscriber ne null
def enqueueOutputElement(elem: Any): Unit = {
ReactiveStreamsCompliance.requireNonNullElement(elem)
downstreamDemand -= 1
tryOnNext(subscriber, elem)
}
override def complete(): Unit = {
if (!downstreamCompleted) {
downstreamCompleted = true
if (exposedPublisher ne null) exposedPublisher.shutdown(None)
if (subscriber ne null) tryOnComplete(subscriber)
}
}
override def cancel(): Unit = {
if (!downstreamCompleted) {
downstreamCompleted = true
if (exposedPublisher ne null) exposedPublisher.shutdown(None)
}
}
override def error(e: Throwable): Unit = {
if (!downstreamCompleted) {
downstreamCompleted = true
if (exposedPublisher ne null) exposedPublisher.shutdown(Some(e))
if ((subscriber ne null) && !e.isInstanceOf[SpecViolation]) tryOnError(subscriber, e)
}
}
override def isClosed: Boolean = downstreamCompleted && (subscriber ne null)
protected def createSubscription(): Subscription = new ActorSubscription(actor, subscriber)
private def subscribePending(subscribers: Seq[Subscriber[Any]]): Unit =
subscribers.foreach { sub =>
if (subscriber eq null) {
subscriber = sub
tryOnSubscribe(subscriber, createSubscription())
} else
rejectAdditionalSubscriber(sub, s"${Logging.simpleName(this)}")
}
protected def waitingExposedPublisher: Actor.Receive = {
case ExposedPublisher(publisher) =>
exposedPublisher = publisher
subreceive.become(downstreamRunning)
case other =>
throw new IllegalStateException(s"The first message must be ExposedPublisher but was [$other]")
}
protected def downstreamRunning: Actor.Receive = {
case SubscribePending =>
subscribePending(exposedPublisher.takePendingSubscribers())
case RequestMore(_, elements) =>
if (elements < 1) {
error(ReactiveStreamsCompliance.numberOfElementsInRequestMustBePositiveException)
} else {
downstreamDemand += elements
if (downstreamDemand < 1)
downstreamDemand = Long.MaxValue // Long overflow, Reactive Streams Spec 3:17: effectively unbounded
pump.pump()
}
case Cancel(_) =>
downstreamCompleted = true
exposedPublisher.shutdown(Some(new ActorPublisher.NormalShutdownException))
pump.pump()
}
}
/**
* INTERNAL API
*/
@InternalApi private[akka] abstract class ActorProcessorImpl(
attributes: Attributes,
val settings: ActorMaterializerSettings)
extends Actor
with ActorLogging
with Pump {
protected val primaryInputs: Inputs = {
val initialInputBufferSize = attributes.mandatoryAttribute[Attributes.InputBuffer].initial
new BatchingInputBuffer(initialInputBufferSize, this) {
override def inputOnError(e: Throwable): Unit = ActorProcessorImpl.this.onError(e)
}
}
protected val primaryOutputs: Outputs = new SimpleOutputs(self, this)
/**
* Subclass may override [[#activeReceive]]
*/
final override def receive = new ExposedPublisherReceive(activeReceive, unhandled) {
override def receiveExposedPublisher(ep: ExposedPublisher): Unit = {
primaryOutputs.subreceive(ep)
context.become(activeReceive)
}
}
def activeReceive: Receive = primaryInputs.subreceive.orElse[Any, Unit](primaryOutputs.subreceive)
protected def onError(e: Throwable): Unit = fail(e)
protected def fail(e: Throwable): Unit = {
if (settings.debugLogging)
log.debug("fail due to: {}", e.getMessage)
primaryInputs.cancel()
primaryOutputs.error(e)
context.stop(self)
}
override def pumpFinished(): Unit = {
primaryInputs.cancel()
primaryOutputs.complete()
context.stop(self)
}
override def pumpFailed(e: Throwable): Unit = fail(e)
override def postStop(): Unit = {
primaryInputs.cancel()
primaryOutputs.error(AbruptTerminationException(self))
}
override def postRestart(reason: Throwable): Unit = {
super.postRestart(reason)
throw new IllegalStateException("This actor cannot be restarted", reason)
}
}
|
Tokelon/tokTales
|
tokTales-core/tokTales-core-library/src/main/java/com/tokelon/toktales/core/resources/ResourceLookup.java
|
<filename>tokTales-core/tokTales-core-library/src/main/java/com/tokelon/toktales/core/resources/ResourceLookup.java
package com.tokelon.toktales.core.resources;
import com.tokelon.toktales.tools.core.objects.pools.SynchronizedPool;
import com.tokelon.toktales.tools.core.objects.pools.SynchronizedPool.PoolObjectFactory;
public class ResourceLookup implements IResourceLookup {
private static final SynchronizedPool<ResourceLookup> pool = new SynchronizedPool<ResourceLookup>(new ResourceLookupFactory(), 4); // This is optimized for 4 concurrent threads
private ResourceTypeFilter currentTypeFilter;
private String currentNameFilter;
private int currentNameMatchingType = STRING_FILTER_TYPE_NONE;
@Override
public boolean filterNameApplies(String value) {
if(currentNameFilter == null) {
return true;
}
if(value == null) {
throw new NullPointerException();
}
boolean result;
switch (currentNameMatchingType) {
case STRING_FILTER_TYPE_EQUALS:
result = value.equals(currentNameFilter);
break;
case STRING_FILTER_TYPE_STARTS_WITH:
result = value.startsWith(currentNameFilter);
break;
case STRING_FILTER_TYPE_REGEX:
result = value.matches(currentNameFilter);
break;
case STRING_FILTER_TYPE_NONE:
result = true;
break;
default:
result = false;
break;
}
return result;
}
@Override
public boolean filterTypeApplies(IResourceType type) {
if(currentTypeFilter == null) {
return true;
}
if(type == null) {
throw new NullPointerException();
}
return currentTypeFilter.applies(type);
}
@Override
public ResourceTypeFilter getFilterType() {
return currentTypeFilter;
}
public void setFilterType(ResourceTypeFilter typeFilter) {
currentTypeFilter = typeFilter;
}
@Override
public String getFilterName() {
return currentNameFilter;
}
public void setFilterName(String nameFilter) {
currentNameFilter = nameFilter;
}
@Override
public int getNameMatchingType() {
return currentNameMatchingType;
}
public void setNameMatchingType(int stringFilterType) {
currentNameMatchingType = stringFilterType;
}
public void objectReset() {
currentTypeFilter = null;
currentNameFilter = null;
currentNameMatchingType = STRING_FILTER_TYPE_NONE;
}
public static SynchronizedPool<ResourceLookup> getObjectPool() {
return pool;
}
private static class ResourceLookupFactory implements PoolObjectFactory<ResourceLookup> {
@Override
public ResourceLookup createObject() {
return new ResourceLookup();
}
}
}
|
pmotyka/tymly
|
plugins/tymly-express-plugin/test/express-spec.js
|
<reponame>pmotyka/tymly
/* eslint-env mocha */
'use strict'
const PORT = 3003
const jwt = require('jsonwebtoken')
const request = require('request')
const expect = require('chai').expect
const tymly = require('tymly')
const path = require('path')
const Buffer = require('safe-buffer').Buffer
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason)
// application specific logging, throwing an error, or other logic here
})
function sendToken (adminToken) {
const options = {
Accept: '*/*'
}
if (adminToken) {
options.authorization = 'Bearer ' + adminToken
}
return options
}
describe('Simple Express tests', function () {
this.timeout(process.env.TIMEOUT || 5000)
let tymlyService, server, adminToken, rupert, alan, statebox
const secret = 'Shhh!'
const audience = 'IAmTheAudience!'
const executionsUrl = `http://localhost:${PORT}/executions/`
const testEndpointUrl = `http://localhost:${PORT}/test-endpoint/`
const GET_FROM_API_STATE_MACHINE = 'tymlyTest_getFromApi_1_0'
it('should create a usable admin token for Dave', () => {
adminToken = jwt.sign(
{},
new Buffer(secret, 'base64'),
{
subject: 'Dave',
audience: audience
}
)
})
it('should create some basic tymly services to run a simple cat blueprint', (done) => {
process.env.TEST_API_URL = testEndpointUrl
process.env.TEST_TOKEN = 'Bearer ' + adminToken
tymly.boot(
{
pluginPaths: [
path.resolve(__dirname, './../lib'),
path.resolve(__dirname, './fixtures/plugins/cats-plugin'),
path.resolve(__dirname, './fixtures/plugins/endpoint-plugin'),
path.resolve(__dirname, '../node_modules/tymly-test-helpers/plugins/allow-everything-rbac-plugin'),
require.resolve('tymly-solr-plugin'),
require.resolve('tymly-users-plugin')
],
blueprintPaths: [
path.resolve(__dirname, './fixtures/blueprints/cats-blueprint'),
path.resolve(__dirname, './fixtures/blueprints/website-blueprint')
],
config: {
staticRootDir: path.resolve(__dirname, './output'),
auth: {
secret: secret,
audience: audience
},
defaultUsers: {
'Dave': ['tymlyTest_tymlyTestAdmin'],
'Steve': ['spaceCadet']
}
}
},
(err, tymlyServices) => {
expect(err).to.eql(null)
tymlyService = tymlyServices.tymly
server = tymlyServices.server
statebox = tymlyServices.statebox
tymlyServices.rbac.debug()
done()
}
)
})
it('should start Express app', (done) => {
server.listen(
PORT,
() => {
console.log('\n')
console.log(`Example app listening on port ${PORT}!\n`)
done()
}
)
})
// CHECK THAT A VALID JWT REQUIRED TO USE /TYMLY'S API
// ---------------------------------------------------
it('should fail to create a new Tymly without a JWT', (done) => {
request(
{
url: executionsUrl,
method: 'POST',
json: {
stateMachineName: 'tymlyTest_cat_1_0',
data: {petName: 'Rupert'}
}
},
(err, res, body) => {
expect(res.statusCode).to.equal(401)
done(err)
})
})
it('should fail updating a Tymly without a JWT', (done) => {
request(
{
url: executionsUrl + alan,
method: 'PUT',
json: {
action: 'SendTaskHeartbeat',
output: {
sound: 'Car engine'
}
}
},
(err, res, body) => {
expect(res.statusCode).to.equal(401)
done(err)
})
})
it('should fail getting a Tymly without a JWT', (done) => {
request(
{
url: executionsUrl + rupert,
method: 'GET'
},
(err, res, body) => {
expect(res.statusCode).to.equal(401)
done(err)
}
)
})
// VALID JWTs SHOULD WORK
// ----------------------
it('should create a new Rupert execution', (done) => {
request(
{
url: executionsUrl,
method: 'POST',
json: {
stateMachineName: 'tymlyTest_cat_1_0',
input: {
petName: 'Rupert',
gender: 'male',
hoursSinceLastMotion: 11,
hoursSinceLastMeal: 5,
petDiary: []
},
options: {
instigatingClient: {
appName: 'tymly-express-plugin',
domain: 'express-spec.js'
}
}
},
headers: sendToken(adminToken)
},
(err, res, body) => {
expect(res.statusCode).to.equal(201)
expect(body.status).to.eql('RUNNING')
expect(body.currentStateName).to.eql('WakingUp')
expect(body.ctx.petName).to.eql('Rupert')
expect(body.executionOptions).to.eql(
{
action: 'startExecution',
instigatingClient: {
appName: 'tymly-express-plugin',
domain: 'express-spec.js'
},
'stateMachineName': 'tymlyTest_cat_1_0',
userId: 'Dave'
}
)
rupert = body.executionName
done(err)
}
)
})
it('should get Rupert execution description', (done) => {
request(
{
url: executionsUrl + rupert,
method: 'GET',
headers: sendToken(adminToken),
json: true
},
(err, res, body) => {
expect(res.statusCode).to.equal(200)
expect(body.ctx.petName).to.equal('Rupert')
done(err)
}
)
})
it('should successfully complete Rupert\'s day', (done) => {
statebox.waitUntilStoppedRunning(
rupert,
(err, executionDescription) => {
try {
expect(err).to.eql(null)
expect(executionDescription.status).to.eql('SUCCEEDED')
expect(executionDescription.stateMachineName).to.eql('tymlyTest_cat_1_0')
expect(executionDescription.currentStateName).to.eql('Sleeping')
expect(executionDescription.ctx.hoursSinceLastMeal).to.eql(0)
expect(executionDescription.ctx.hoursSinceLastMotion).to.eql(0)
expect(executionDescription.ctx.gender).to.eql('male')
expect(executionDescription.ctx.petDiary).to.be.an('array')
expect(executionDescription.ctx.petDiary[0]).to.equal('Look out, Rupert is waking up!')
expect(executionDescription.ctx.petDiary[2]).to.equal('Rupert is walking... where\'s he off to?')
expect(executionDescription.ctx.petDiary[6]).to.equal('Shh, Rupert is eating...')
done()
} catch (e) {
done(e)
}
}
)
})
it('should create a new Alan execution', (done) => {
request(
{
url: executionsUrl,
method: 'POST',
json: {
stateMachineName: 'tymlyTest_listeningCat_1_0',
input: {
petName: 'Alan',
gender: 'male',
petDiary: []
}
},
headers: sendToken(adminToken)
},
(err, res, body) => {
expect(res.statusCode).to.equal(201)
expect(body.status).to.eql('RUNNING')
expect(body.currentStateName).to.eql('WakingUp')
expect(body.ctx.petName).to.eql('Alan')
alan = body.executionName
done(err)
}
)
})
it('should wait a while', (done) => {
setTimeout(done, 250)
})
it('should update Alan execution with a heartbeat', (done) => {
request(
{
url: executionsUrl + alan,
method: 'PUT',
json: {
action: 'SendTaskHeartbeat',
output: {
sound: 'Car engine'
}
},
headers: sendToken(adminToken)
},
(err, res, body) => {
console.log('>>>>', res)
expect(res.statusCode).to.equal(200)
expect(body.status).to.equal('RUNNING')
expect(body.currentStateName).to.equal('Listening')
expect(body.ctx.sound).to.equal('Car engine')
done(err)
}
)
})
it('should wait a while longer', (done) => {
setTimeout(done, 250)
})
it('should sendTaskSuccess() to the Alan execution', (done) => {
request(
{
url: executionsUrl + alan,
method: 'PUT',
json: {
action: 'SendTaskSuccess',
output: {
order: [
{
product: 'Fresh Tuna',
quantity: 25
}
]
}
},
headers: sendToken(adminToken)
},
(err, res, body) => {
expect(res.statusCode).to.equal(200)
done(err)
}
)
})
it('should successfully complete Alans\'s awakening', (done) => {
statebox.waitUntilStoppedRunning(
alan,
(err, executionDescription) => {
try {
expect(err).to.eql(null)
expect(executionDescription.status).to.eql('SUCCEEDED')
expect(executionDescription.stateMachineName).to.eql('tymlyTest_listeningCat_1_0')
expect(executionDescription.currentStateName).to.eql('Sleeping')
expect(executionDescription.ctx.gender).to.eql('male')
expect(executionDescription.ctx.petDiary).to.be.an('array')
expect(executionDescription.ctx.petDiary[0]).to.equal('Look out, Alan is waking up!')
expect(executionDescription.ctx.petDiary[1]).to.equal('Alan is listening for something... what will he hear?')
expect(executionDescription.ctx.petDiary[2]).to.equal('Sweet dreams Alan! x')
expect(executionDescription.ctx.formData.order[0]).to.eql(
{
product: 'Fresh Tuna',
quantity: 25
}
)
done()
} catch (err) {
done(err)
}
}
)
})
it('should create another new Alan execution', (done) => {
request(
{
url: executionsUrl,
method: 'POST',
json: {
stateMachineName: 'tymlyTest_listeningCat_1_0',
input: {
petName: 'Alan',
gender: 'male',
petDiary: []
}
},
headers: sendToken(adminToken)
},
(err, res, body) => {
expect(res.statusCode).to.equal(201)
expect(body.status).to.eql('RUNNING')
expect(body.currentStateName).to.eql('WakingUp')
expect(body.ctx.petName).to.eql('Alan')
alan = body.executionName
done(err)
}
)
})
it('should cancel a new Alan tymly', (done) => {
request(
{
url: executionsUrl + alan,
method: 'DELETE',
headers: sendToken(adminToken)
},
(err, res, body) => {
expect(res.statusCode).to.equal(204)
done(err)
}
)
})
it('should get stopped Alan execution-description', (done) => {
request(
{
url: executionsUrl + alan,
method: 'GET',
headers: sendToken(adminToken),
json: true
},
(err, res, body) => {
expect(res.statusCode).to.equal(200)
expect(body.ctx.petName).to.equal('Alan')
expect(body.status).to.equal('STOPPED')
expect(body.errorCode).to.equal('STOPPED')
expect(body.errorCause).to.equal('Execution stopped externally')
done(err)
}
)
})
it('should start state machine to claim from an API (our localhost booted address [remit]) and expect the header to be taken through, and sensible data to be returned', (done) => {
statebox.startExecution(
{},
GET_FROM_API_STATE_MACHINE,
{
sendResponse: 'COMPLETE'
},
(err, executionDescription) => {
expect(err).to.eql(null)
expect(executionDescription.currentStateName).to.eql('GetDataFromRestApi')
expect(executionDescription.stateMachineName).to.eql('tymlyTest_getFromApi_1_0')
expect(executionDescription.ctx.stateMachinesUserCanStart)
expect(executionDescription.ctx.forms)
expect(executionDescription.status).to.eql('SUCCEEDED')
done(err)
}
)
})
it('should shutdown Tymly', async () => {
await tymlyService.shutdown()
})
})
|
nomos/go-lokas
|
network/redisclient/reply.go
|
<filename>network/redisclient/reply.go<gh_stars>1-10
package redisclient
import "github.com/gomodule/redigo/redis"
type RedisReply struct {
Value interface{}
Error error
}
func NewReply(v interface{},e error)*RedisReply{
return &RedisReply{
Value: v,
Error: e,
}
}
func (this *RedisReply) Interface()(interface{},error) {
return this.Value,this.Error
}
func (this *RedisReply) Int()(int,error) {
return redis.Int(this.Value,this.Error)
}
func (this *RedisReply) Int64()(int64,error) {
return redis.Int64(this.Value,this.Error)
}
func (this *RedisReply) Uint64()(uint64,error) {
return redis.Uint64(this.Value,this.Error)
}
func (this *RedisReply) Float64()(float64,error) {
return redis.Float64(this.Value,this.Error)
}
func (this *RedisReply) String()(string,error) {
return redis.String(this.Value,this.Error)
}
func (this *RedisReply) Bytes()([]byte,error) {
return redis.Bytes(this.Value,this.Error)
}
func (this *RedisReply) Bool()(bool,error) {
return redis.Bool(this.Value,this.Error)
}
func (this *RedisReply) MultiBulk()([]interface{},error) {
return redis.MultiBulk(this.Value,this.Error)
}
func (this *RedisReply) Values()([]interface{},error) {
return redis.Values(this.Value,this.Error)
}
func (this *RedisReply) Float64s()([]float64,error) {
return redis.Float64s(this.Value,this.Error)
}
func (this *RedisReply) Strings()([]string,error) {
return redis.Strings(this.Value,this.Error)
}
func (this *RedisReply) ByteSlices()([][]byte,error) {
return redis.ByteSlices(this.Value,this.Error)
}
func (this *RedisReply) Int64s()([]int64,error) {
return redis.Int64s(this.Value,this.Error)
}
func (this *RedisReply) Ints()([]int,error) {
return redis.Ints(this.Value,this.Error)
}
func (this *RedisReply) StringMap()(map[string]string,error) {
return redis.StringMap(this.Value,this.Error)
}
func (this *RedisReply) IntMap()(map[string]int,error) {
return redis.IntMap(this.Value,this.Error)
}
func (this *RedisReply) Int64Map()(map[string]int64,error) {
return redis.Int64Map(this.Value,this.Error)
}
func (this *RedisReply) Positions()([]*[2]float64,error) {
return redis.Positions(this.Value,this.Error)
}
func (this *RedisReply) Uint64s()([]uint64,error) {
return redis.Uint64s(this.Value,this.Error)
}
func (this *RedisReply) Uint64Map()(map[string]uint64,error) {
return redis.Uint64Map(this.Value,this.Error)
}
func (this *RedisReply) SlowLogs()([]redis.SlowLog,error) {
return redis.SlowLogs(this.Value,this.Error)
}
|
lechium/iOS1351Headers
|
System/Library/PrivateFrameworks/DiagnosticExtensionsDaemon.framework/DEDActivity.h
|
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:17:52 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/DiagnosticExtensionsDaemon.framework/DiagnosticExtensionsDaemon
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
@protocol OS_os_activity;
@class NSObject;
@interface DEDActivity : NSObject {
NSObject*<OS_os_activity> _cleanup;
}
@property (retain) NSObject*<OS_os_activity> cleanup; //@synthesize cleanup=_cleanup - In the implementation block
+(id)sharedInstance;
-(NSObject*<OS_os_activity>)cleanup;
-(id)currentCleanupActivity;
-(void)setCleanup:(NSObject*<OS_os_activity>)arg1 ;
-(id)newCleanupActivity;
@end
|
softcontext/spring1107
|
spring-boot-mybatis-restful-angular/src/main/java/com/example/demo/web/dto/ServerResponseBoardMulti.java
|
package com.example.demo.web.dto;
import java.util.List;
import com.example.demo.board.model.Board;
import com.example.demo.common.dto.Pager;
import lombok.Data;
@Data
public class ServerResponseBoardMulti {
private String status = "Success";
private String message;
private List<Board> boards;
private Pager pager;
private String errorCode;
private String errorMessage;
public ServerResponseBoardMulti() {
// Default Constructor
}
public ServerResponseBoardMulti(List<Board> boards) {
this.boards = boards;
}
public ServerResponseBoardMulti(List<Board> boards, Pager pager) {
this.boards = boards;
this.pager = pager;
}
}
|
rLadia-demo/AttacknidPatch
|
decompiled_src/JDGui/com/badlogic/gdx/physics/box2d/Filter.java
|
<reponame>rLadia-demo/AttacknidPatch
package com.badlogic.gdx.physics.box2d;
public class Filter
{
public short categoryBits = 1;
public short groupIndex = 0;
public short maskBits = -1;
}
/* Location: C:\Users\Rodelle\Desktop\Attacknid\Tools\Attacknids-dex2jar.jar
* Qualified Name: com.badlogic.gdx.physics.box2d.Filter
* JD-Core Version: 0.7.0.1
*/
|
npocmaka/Windows-Server-2003
|
base/cluster/mgmt/cluscfg/server/cphysicaldisk.cpp
|
<reponame>npocmaka/Windows-Server-2003
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000-2002 Microsoft Corporation
//
// Module Name:
// CPhysicalDisk.cpp
//
// Description:
// This file contains the definition of the CPhysicalDisk
// class.
//
// The class CPhysicalDisk represents a cluster manageable
// device. It implements the IClusCfgManagedResourceInfo interface.
//
// Maintained By:
// <NAME> (GalenB) 23-FEB-2000
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Include Files
//////////////////////////////////////////////////////////////////////////////
#include "Pch.h"
#include "CPhysicalDisk.h"
#include "CClusCfgPartitionInfo.h"
#include <devioctl.h>
#include <ntddvol.h>
#include <ntddstor.h>
#include <ntddscsi.h>
#define _NTSCSI_USER_MODE_
#include <scsi.h>
#undef _NTSCSI_USER_MODE_
//////////////////////////////////////////////////////////////////////////////
// Constant Definitions
//////////////////////////////////////////////////////////////////////////////
DEFINE_THISCLASS( "CPhysicalDisk" );
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk class
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::S_HrCreateInstance
//
// Description:
// Create a CPhysicalDisk instance.
//
// Arguments:
// None.
//
// Return Values:
// Pointer to CPhysicalDisk instance.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::S_HrCreateInstance( IUnknown ** ppunkOut )
{
TraceFunc( "" );
HRESULT hr = S_OK;
CPhysicalDisk * ppd = NULL;
if ( ppunkOut == NULL )
{
hr = THR( E_POINTER );
goto Cleanup;
} // if:
ppd = new CPhysicalDisk();
if ( ppd == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if: error allocating object
hr = THR( ppd->HrInit() );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if: HrInit() failed
hr = THR( ppd->TypeSafeQI( IUnknown, ppunkOut ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if: QI failed
Cleanup:
if ( FAILED( hr ) )
{
LogMsg( L"[SRV] CPhysicalDisk::S_HrCreateInstance() failed. (hr = %#08x)", hr );
} // if:
if ( ppd != NULL )
{
ppd->Release();
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::S_HrCreateInstance
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::CPhysicalDisk
//
// Description:
// Constructor of the CPhysicalDisk class. This initializes
// the m_cRef variable to 1 instead of 0 to account of possible
// QueryInterface failure in DllGetClassObject.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
CPhysicalDisk::CPhysicalDisk( void )
: m_cRef( 1 )
{
TraceFunc( "" );
// Increment the count of components in memory so the DLL hosting this
// object cannot be unloaded.
InterlockedIncrement( &g_cObjects );
Assert( m_pIWbemServices == NULL );
Assert( m_bstrName == NULL );
Assert( m_bstrDeviceID == NULL );
Assert( m_bstrDescription == NULL );
Assert( m_idxNextPartition == 0 );
Assert( m_ulSCSIBus == 0 );
Assert( m_ulSCSITid == 0 );
Assert( m_ulSCSIPort == 0 );
Assert( m_ulSCSILun == 0 );
Assert( m_idxEnumPartitionNext == 0 );
Assert( m_prgPartitions == NULL );
Assert( m_lcid == 0 );
Assert( m_picccCallback == NULL );
Assert( m_dwSignature == 0 );
Assert( m_bstrFriendlyName == NULL );
// Assert( m_bstrFirmwareSerialNumber == NULL );
Assert( m_fIsManaged == FALSE );
Assert( m_fIsManagedByDefault == FALSE );
Assert( m_cPartitions == 0 );
Assert( m_idxDevice == 0 );
Assert( m_fIsDynamicDisk == FALSE );
Assert( m_fIsGPTDisk == FALSE );
TraceFuncExit();
} //*** CPhysicalDisk::CPhysicalDisk
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::~CPhysicalDisk
//
// Description:
// Desstructor of the CPhysicalDisk class.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
CPhysicalDisk::~CPhysicalDisk( void )
{
TraceFunc( "" );
ULONG idx;
TraceSysFreeString( m_bstrName );
TraceSysFreeString( m_bstrDeviceID );
TraceSysFreeString( m_bstrDescription );
TraceSysFreeString( m_bstrFriendlyName );
// TraceSysFreeString( m_bstrFirmwareSerialNumber );
for ( idx = 0; idx < m_idxNextPartition; idx++ )
{
((*m_prgPartitions)[ idx ])->Release();
} // for:
TraceFree( m_prgPartitions );
if ( m_pIWbemServices != NULL )
{
m_pIWbemServices->Release();
} // if:
if ( m_picccCallback != NULL )
{
m_picccCallback->Release();
} // if:
// There's going to be one less component in memory. Decrement component count.
InterlockedDecrement( &g_cObjects );
TraceFuncExit();
} //*** CPhysicalDisk::~CPhysicalDisk
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk -- IUknkown interface.
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::AddRef
//
// Description:
// Increment the reference count of this object by one.
//
// Arguments:
// None.
//
// Return Value:
// The new reference count.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP_( ULONG )
CPhysicalDisk::AddRef( void )
{
TraceFunc( "[IUnknown]" );
InterlockedIncrement( & m_cRef );
CRETURN( m_cRef );
} //*** CPhysicalDisk::AddRef
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Release
//
// Description:
// Decrement the reference count of this object by one.
//
// Arguments:
// None.
//
// Return Value:
// The new reference count.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP_( ULONG )
CPhysicalDisk::Release( void )
{
TraceFunc( "[IUnknown]" );
LONG cRef;
cRef = InterlockedDecrement( &m_cRef );
if ( cRef == 0 )
{
TraceDo( delete this );
} // if: reference count equal to zero
CRETURN( cRef );
} //*** CPhysicalDisk::Release
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::QueryInterface
//
// Description:
// Query this object for the passed in interface.
//
// Arguments:
// riidIn
// Id of interface requested.
//
// ppvOut
// Pointer to the requested interface.
//
// Return Value:
// S_OK
// If the interface is available on this object.
//
// E_NOINTERFACE
// If the interface is not available.
//
// E_POINTER
// ppvOut was NULL.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::QueryInterface(
REFIID riidIn
, void ** ppvOut
)
{
TraceQIFunc( riidIn, ppvOut );
HRESULT hr = S_OK;
//
// Validate arguments.
//
Assert( ppvOut != NULL );
if ( ppvOut == NULL )
{
hr = THR( E_POINTER );
goto Cleanup;
}
//
// Handle known interfaces.
//
if ( IsEqualIID( riidIn, IID_IUnknown ) )
{
*ppvOut = static_cast< IClusCfgManagedResourceInfo * >( this );
} // if: IUnknown
else if ( IsEqualIID( riidIn, IID_IClusCfgManagedResourceInfo ) )
{
*ppvOut = TraceInterface( __THISCLASS__, IClusCfgManagedResourceInfo, this, 0 );
} // else if: IClusCfgManagedResourceInfo
else if ( IsEqualIID( riidIn, IID_IClusCfgWbemServices ) )
{
*ppvOut = TraceInterface( __THISCLASS__, IClusCfgWbemServices, this, 0 );
} // else if: IClusCfgWbemServices
else if ( IsEqualIID( riidIn, IID_IClusCfgSetWbemObject ) )
{
*ppvOut = TraceInterface( __THISCLASS__, IClusCfgSetWbemObject, this, 0 );
} // else if: IClusCfgSetWbemObject
else if ( IsEqualIID( riidIn, IID_IEnumClusCfgPartitions ) )
{
*ppvOut = TraceInterface( __THISCLASS__, IEnumClusCfgPartitions, this, 0 );
} // else if: IEnumClusCfgPartitions
else if ( IsEqualIID( riidIn, IID_IClusCfgPhysicalDiskProperties ) )
{
*ppvOut = TraceInterface( __THISCLASS__, IClusCfgPhysicalDiskProperties, this, 0 );
} // else if: IClusCfgPhysicalDiskProperties
else if ( IsEqualIID( riidIn, IID_IClusCfgInitialize ) )
{
*ppvOut = TraceInterface( __THISCLASS__, IClusCfgInitialize, this, 0 );
} // else if: IClusCfgInitialize
else if ( IsEqualIID( riidIn, IID_IClusCfgManagedResourceCfg ) )
{
*ppvOut = TraceInterface( __THISCLASS__, IClusCfgManagedResourceCfg, this, 0 );
} // else if: IClusCfgManagedResourceCfg
else if ( IsEqualIID( riidIn, IID_IClusCfgVerifyQuorum ) )
{
*ppvOut = TraceInterface( __THISCLASS__, IClusCfgVerifyQuorum, this, 0 );
} // else if: IClusCfgVerifyQuorum
else
{
*ppvOut = NULL;
hr = E_NOINTERFACE;
}
//
// Add a reference to the interface if successful.
//
if ( SUCCEEDED( hr ) )
{
((IUnknown *) *ppvOut)->AddRef();
} // if: success
Cleanup:
QIRETURN_IGNORESTDMARSHALLING1(
hr
, riidIn
, IID_IClusCfgManagedResourceData
);
} //*** CPhysicalDisk::QueryInterface
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk -- IClusCfgWbemServices interface.
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::SetWbemServices
//
// Description:
// Set the WBEM services provider.
//
// Arguments:
// IN IWbemServices pIWbemServicesIn
//
// Return Value:
// S_OK
// Success
//
// E_POINTER
// The pIWbemServicesIn param is NULL.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::SetWbemServices( IWbemServices * pIWbemServicesIn )
{
TraceFunc( "[IClusCfgWbemServices]" );
HRESULT hr = S_OK;
if ( pIWbemServicesIn == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_SetWbemServices_PhysDisk, IDS_ERROR_NULL_POINTER, hr );
goto Cleanup;
} // if:
m_pIWbemServices = pIWbemServicesIn;
m_pIWbemServices->AddRef();
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::SetWbemServices
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk -- IClusCfgInitialize interface.
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Initialize
//
// Description:
// Initialize this component.
//
// Arguments:
// IN IUknown * punkCallbackIn
//
// IN LCID lcidIn
//
// Return Value:
// S_OK
// Success
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::Initialize(
IUnknown * punkCallbackIn,
LCID lcidIn
)
{
TraceFunc( "[IClusCfgInitialize]" );
Assert( m_picccCallback == NULL );
HRESULT hr = S_OK;
m_lcid = lcidIn;
if ( punkCallbackIn == NULL )
{
hr = THR( E_POINTER );
goto Cleanup;
} // if:
hr = THR( punkCallbackIn->TypeSafeQI( IClusCfgCallback, &m_picccCallback ) );
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::Initialize
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk -- IEnumClusCfgPartitions interface.
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Next
//
// Description:
//
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// E_POINTER
// The rgpPartitionInfoOut param is NULL.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::Next(
ULONG cNumberRequestedIn,
IClusCfgPartitionInfo ** rgpPartitionInfoOut,
ULONG * pcNumberFetchedOut
)
{
TraceFunc( "[IEnumClusCfgPartitions]" );
HRESULT hr = S_FALSE;
ULONG cFetched = 0;
ULONG idx;
IClusCfgPartitionInfo * piccpi = NULL;
if ( rgpPartitionInfoOut == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_Next_PhysDisk, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr );
goto Cleanup;
} // if:
if ( pcNumberFetchedOut != NULL )
{
*pcNumberFetchedOut = 0;
} // if:
if ( m_prgPartitions == NULL )
{
LOG_STATUS_REPORT_MINOR( TASKID_Minor_PhysDisk_No_Partitions, L"A physical disk does not have a partitions enumerator", hr );
goto Cleanup;
} // if:
cFetched = min( cNumberRequestedIn, ( m_idxNextPartition - m_idxEnumPartitionNext ) );
for ( idx = 0; idx < cFetched; idx++, m_idxEnumPartitionNext++ )
{
hr = THR( ((*m_prgPartitions)[ m_idxEnumPartitionNext ])->TypeSafeQI( IClusCfgPartitionInfo, &piccpi ) );
if ( FAILED( hr ) )
{
LOG_STATUS_REPORT( L"CPhysicalDisk::Next() could not query for IClusCfgPartitionInfo.", hr );
break;
} // if:
rgpPartitionInfoOut[ idx ] = piccpi;
} // for:
if ( FAILED( hr ) )
{
ULONG idxStop = idx;
m_idxEnumPartitionNext -= idx;
for ( idx = 0; idx < idxStop; idx++ )
{
(rgpPartitionInfoOut[ idx ])->Release();
} // for:
cFetched = 0;
goto Cleanup;
} // if:
if ( pcNumberFetchedOut != NULL )
{
*pcNumberFetchedOut = cFetched;
} // if:
if ( cFetched < cNumberRequestedIn )
{
hr = S_FALSE;
} // if:
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::Next
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Skip
//
// Description:
//
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::Skip( ULONG cNumberToSkipIn )
{
TraceFunc( "[IEnumClusCfgPartitions]" );
HRESULT hr = S_OK;
m_idxEnumPartitionNext += cNumberToSkipIn;
if ( m_idxEnumPartitionNext > m_idxNextPartition )
{
m_idxEnumPartitionNext = m_idxNextPartition;
hr = S_FALSE;
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::Skip
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Reset
//
// Description:
//
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::Reset( void )
{
TraceFunc( "[IEnumClusCfgPartitions]" );
HRESULT hr = S_OK;
m_idxEnumPartitionNext = 0;
HRETURN( hr );
} //*** CPhysicalDisk::Reset
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Clone
//
// Description:
//
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// E_POINTER
// The ppEnumClusCfgPartitionsOut param is NULL.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::Clone( IEnumClusCfgPartitions ** ppEnumClusCfgPartitionsOut )
{
TraceFunc( "[IEnumClusCfgPartitions]" );
HRESULT hr = S_OK;
if ( ppEnumClusCfgPartitionsOut == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_Clone_PhysDisk, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr );
goto Cleanup;
} // if:
hr = THR( E_NOTIMPL );
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::Clone
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Count
//
// Description:
//
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// E_POINTER
// The pnCountOut param is NULL.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::Count( DWORD * pnCountOut )
{
TraceFunc( "[IEnumClusCfgPartitions]" );
HRESULT hr = THR( S_OK );
if ( pnCountOut == NULL )
{
hr = THR( E_POINTER );
goto Cleanup;
} // if:
*pnCountOut = m_cPartitions;
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::Count
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk -- IClusCfgSetWbemObject interface.
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::SetWbemObject
//
// Description:
// Set the disk information information provider.
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::SetWbemObject(
IWbemClassObject * pDiskIn
, bool * pfRetainObjectOut
)
{
TraceFunc( "[IClusCfgSetWbemObject]" );
Assert( pDiskIn != NULL );
Assert( pfRetainObjectOut != NULL );
HRESULT hr = S_FALSE;
VARIANT var;
CLSID clsidMinorId;
m_fIsQuorumCapable = TRUE;
m_fIsQuorumResourceMultiNodeCapable = TRUE;
VariantInit( &var );
hr = THR( HrGetWMIProperty( pDiskIn, L"Name", VT_BSTR, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = STHR( HrCreateFriendlyName( var.bstrVal ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
VariantClear( &var );
hr = THR( HrGetWMIProperty( pDiskIn, L"DeviceID", VT_BSTR, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
m_bstrDeviceID = TraceSysAllocString( var.bstrVal );
if (m_bstrDeviceID == NULL )
{
goto OutOfMemory;
} // if:
VariantClear( &var );
hr = THR( HrGetWMIProperty( pDiskIn, L"Description", VT_BSTR, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
m_bstrDescription = TraceSysAllocString( var.bstrVal );
if ( m_bstrDescription == NULL )
{
goto OutOfMemory;
} // if:
VariantClear( &var );
hr = THR( HrGetWMIProperty( pDiskIn, L"SCSIBus", VT_I4, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
m_ulSCSIBus = var.lVal;
VariantClear( &var );
hr = THR( HrGetWMIProperty( pDiskIn, L"SCSITargetId", VT_I4, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
m_ulSCSITid = var.lVal;
VariantClear( &var );
hr = THR( HrGetWMIProperty( pDiskIn, L"SCSIPort", VT_I4, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
m_ulSCSIPort = var.lVal;
VariantClear( &var );
hr = THR( HrGetWMIProperty( pDiskIn, L"SCSILogicalUnit", VT_I4, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
m_ulSCSILun = var.lVal;
VariantClear( &var );
hr = THR( HrGetWMIProperty( pDiskIn, L"Index", VT_I4, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
m_idxDevice = var.lVal;
VariantClear( &var );
hr = HrGetWMIProperty( pDiskIn, L"Signature", VT_I4, &var );
if ( hr == WBEM_E_NOT_FOUND )
{
//
// If the signature is not found then log it and let everything continue.
//
LOG_STATUS_REPORT_STRING( L"Physical disk %1!ws! does not have a signature property.", m_bstrName, hr );
var.lVal = 0L;
hr = S_OK;
} // if:
if ( FAILED( hr ) )
{
THR( hr );
goto Cleanup;
} // if:
//
// Did we actually get a value? Could be VT_NULL to indicate that it is empty.
// We only want VT_I4 values...
//
if ( var.vt == VT_I4 )
{
m_dwSignature = (DWORD) var.lVal;
} // else if:
LOG_STATUS_REPORT_STRING2( L"Physical disk %1!ws! has signature %2!x!.", m_bstrName, m_dwSignature, hr );
if ( FAILED( hr ) )
{
STATUS_REPORT_REF(
TASKID_Major_Find_Devices
, TASKID_Minor_PhysDisk_Signature
, IDS_ERROR_PHYSDISK_SIGNATURE
, IDS_ERROR_PHYSDISK_SIGNATURE_REF
, hr
);
THR( hr );
goto Cleanup;
} // if:
VariantClear( &var );
hr = STHR( HrGetPartitionInfo( pDiskIn, pfRetainObjectOut ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
//
// KB: 28-JUL-2000 GalenB
//
// HrGetPartitionInfo() returns S_FALSE when it cannot get the partition info for a disk.
// This is usually caused by the disk already being under ClusDisk control. This is not
// and error, it just means we cannot query the partition or logical drive info.
//
if ( hr == S_OK )
{
hr = STHR( HrCreateFriendlyName() );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
//
// Since we have partition info we also have a signature and need to see if this
// disk is cluster capable.
hr = STHR( HrIsClusterCapable() );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
//
// If the disk is not cluster capable then we don't want the enumerator
// to keep it.
//
if ( hr == S_FALSE )
{
HRESULT hrTemp;
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_PhysDisk_Cluster_Capable, IDS_INFO_PHYSDISK_CLUSTER_CAPABLE, hr );
hrTemp = THR( CoCreateGuid( &clsidMinorId ) );
if ( FAILED( hrTemp ) )
{
LOG_STATUS_REPORT( L"Could not create a guid for a not cluster capable disk minor task ID", hrTemp );
clsidMinorId = IID_NULL;
} // if:
*pfRetainObjectOut = false;
STATUS_REPORT_STRING_REF(
TASKID_Minor_PhysDisk_Cluster_Capable
, clsidMinorId
, IDS_INFO_PHYSDISK_NOT_CLUSTER_CAPABLE
, m_bstrFriendlyName
, IDS_INFO_PHYSDISK_NOT_CLUSTER_CAPABLE_REF
, hr
);
LOG_STATUS_REPORT_STRING( L"The '%1!ws!' physical disk is not cluster capable", m_bstrFriendlyName, hr );
} // if:
/* else
{
hr = THR( HrProcessMountPoints() );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
} // else:
*/
} // if:
//
// TODO: 15-MAR-2001 GalenB
//
// Need to check this error code when this feature is complete!
//
//hr = THR( HrGetDiskFirmwareSerialNumber() );
//THR( HrGetDiskFirmwareVitalData() );
goto Cleanup;
OutOfMemory:
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_SetWbemObject_PhysDisk, IDS_ERROR_OUTOFMEMORY, hr );
Cleanup:
VariantClear( &var );
HRETURN( hr );
} //*** CPhysicalDisk::SetWbemObject
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk -- IClusCfgManagedResourceInfo interface.
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::GetUID
//
// Description:
//
// Arguments:
// pbstrUIDOut
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::GetUID( BSTR * pbstrUIDOut )
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_OK;
WCHAR sz[ 256 ];
if ( pbstrUIDOut == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_PhysDisk_GetUID_Pointer, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr );
goto Cleanup;
} // if:
hr = THR( StringCchPrintfW( sz, ARRAYSIZE( sz ), L"SCSI Tid %ld, SCSI Lun %ld", m_ulSCSITid, m_ulSCSILun ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
*pbstrUIDOut = SysAllocString( sz );
if ( *pbstrUIDOut == NULL )
{
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_PhysDisk_GetUID_Memory, IDS_ERROR_OUTOFMEMORY, hr );
} // if:
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::GetUID
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::GetName
//
// Description:
//
// Arguments:
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::GetName( BSTR * pbstrNameOut )
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_OK;
if ( pbstrNameOut == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_GetName_Pointer, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr );
goto Cleanup;
} // if:
//
// Prefer the "friendly" name over the WMI name -- if we have it...
//
if ( m_bstrFriendlyName != NULL )
{
*pbstrNameOut = SysAllocString( m_bstrFriendlyName );
} // if:
else
{
LOG_STATUS_REPORT_STRING( L"There is not a \"friendly name\" for the physical disk \"%1!ws!\".", m_bstrName, hr );
*pbstrNameOut = SysAllocString( m_bstrName );
} // else:
if (*pbstrNameOut == NULL )
{
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_GetName_Memory, IDS_ERROR_OUTOFMEMORY, hr );
} // if:
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::GetName
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::SetName
//
// Description:
//
// Arguments:
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::SetName( LPCWSTR pcszNameIn )
{
TraceFunc1( "[IClusCfgManagedResourceInfo] pcszNameIn = '%ws'", pcszNameIn == NULL ? L"<null>" : pcszNameIn );
HRESULT hr = S_OK;
BSTR bstr = NULL;
if ( pcszNameIn == NULL )
{
hr = THR( E_INVALIDARG );
goto Cleanup;
} // if:
bstr = TraceSysAllocString( pcszNameIn );
if ( bstr == NULL )
{
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_SetName_PhysDisk, IDS_ERROR_OUTOFMEMORY, hr );
goto Cleanup;
} // if:
TraceSysFreeString( m_bstrName );
m_bstrName = bstr;
//
// Since we got asked from the outside to set a new name, this should actually be reflected in
// the friendly name, too, since that, ultimately, gets preference over the real name
//
hr = HrSetFriendlyName( pcszNameIn );
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::SetName
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::IsManaged
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// The device is managed.
//
// S_FALSE
// The device is not managed.
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::IsManaged( void )
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_FALSE;
if ( m_fIsManaged )
{
hr = S_OK;
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::IsManaged
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::SetManaged
//
// Description:
//
// Arguments:
// fIsManagedIn
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::SetManaged(
BOOL fIsManagedIn
)
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_OK;
m_fIsManaged = fIsManagedIn;
LOG_STATUS_REPORT_STRING2(
L"Physical disk '%1!ws!' '%2!ws!"
, ( m_bstrFriendlyName != NULL ) ? m_bstrFriendlyName : m_bstrName
, m_fIsManaged ? L"is managed" : L"is not managed"
, hr
);
HRETURN( hr );
} //*** CPhysicalDisk::SetManaged
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::IsQuorumResource
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// The device is the quorum device.
//
// S_FALSE
// The device is not the quorum device.
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::IsQuorumResource( void )
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_FALSE;
if ( m_fIsQuorumResource )
{
hr = S_OK;
} // if:
LOG_STATUS_REPORT_STRING2(
L"Physical disk '%1!ws!' '%2!ws!' the quorum device."
, ( m_bstrFriendlyName != NULL ) ? m_bstrFriendlyName : m_bstrDeviceID
, m_fIsQuorumResource ? L"is" : L"is not"
, hr
);
HRETURN( hr );
} //*** CPhysicalDisk::IsQuorumResource
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::SetQuorumResource
//
// Description:
//
// Arguments:
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::SetQuorumResource( BOOL fIsQuorumResourceIn )
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_OK;
//
// Since no accurate determination can be made about a disk's quorum capability
// when the node that it's on does not hold the SCSI reservation and have access
// to the media we must blindly accept the input given...
//
/*
//
// If we are not quorum capable then we should not allow ourself to be
// made the quorum resource.
//
if ( ( fIsQuorumResourceIn ) && ( m_fIsQuorumCapable == FALSE ) )
{
hr = HRESULT_FROM_WIN32( ERROR_NOT_QUORUM_CAPABLE );
goto Cleanup;
} // if:
*/
m_fIsQuorumResource = fIsQuorumResourceIn;
LOG_STATUS_REPORT_STRING2(
L"Setting physical disk '%1!ws!' '%2!ws!' the quorum device."
, ( m_bstrFriendlyName != NULL ) ? m_bstrFriendlyName : m_bstrDeviceID
, m_fIsQuorumResource ? L"to be" : L"to not be"
, hr
);
//Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::SetQuorumResource
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::IsQuorumCapable
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// The device is a quorum capable device.
//
// S_FALSE
// The device is not a quorum capable device.
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::IsQuorumCapable( void )
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_FALSE;
if ( m_fIsQuorumCapable )
{
hr = S_OK;
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::IsQuorumCapable
//////////////////////////////////////////////////////////////////////////
//
// CPhysicalDisk::SetQuorumCapable
//
// Description:
// Call this to set whether the resource is capable to be the quorum
// resource or not.
//
// Parameter:
// fIsQuorumCapableIn - If TRUE, the resource will be marked as quorum capable.
//
// Return Values:
// S_OK
// Call succeeded.
//
//////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::SetQuorumCapable(
BOOL fIsQuorumCapableIn
)
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_OK;
m_fIsQuorumCapable = fIsQuorumCapableIn;
HRETURN( hr );
} //*** CPhysicalDisk::SetQuorumCapable
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::GetDriveLetterMappings
//
// Description:
//
// Arguments:
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::GetDriveLetterMappings(
SDriveLetterMapping * pdlmDriveLetterMappingOut
)
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_FALSE;
IClusCfgPartitionInfo * piccpi = NULL;
ULONG idx;
if ( pdlmDriveLetterMappingOut == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_GetDriveLetterMappings_PhysDisk, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr );
goto Cleanup;
} // if:
for ( idx = 0; idx < m_idxNextPartition; idx++ )
{
hr = ( ((*m_prgPartitions)[ idx ])->TypeSafeQI( IClusCfgPartitionInfo, &piccpi ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = STHR( piccpi->GetDriveLetterMappings( pdlmDriveLetterMappingOut ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
piccpi->Release();
piccpi = NULL;
} // for:
Cleanup:
if ( piccpi != NULL )
{
piccpi->Release();
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::GetDriveLetterMappings
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::SetDriveLetterMappings
//
// Description:
//
// Arguments:
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::SetDriveLetterMappings(
SDriveLetterMapping dlmDriveLetterMappingIn
)
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = THR( E_NOTIMPL );
HRETURN( hr );
} //*** CPhysicalDisk::SetDriveLetterMappings
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::IsManagedByDefault
//
// Description:
// Should this resource be managed by the cluster by default?
//
// Arguments:
// None.
//
// Return Value:
// S_OK
// The device is managed by default.
//
// S_FALSE
// The device is not managed by default.
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::IsManagedByDefault( void )
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_FALSE;
if ( m_fIsManagedByDefault )
{
hr = S_OK;
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::IsManagedByDefault
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::SetManagedByDefault
//
// Description:
//
// Arguments:
// fIsManagedByDefaultIn
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::SetManagedByDefault(
BOOL fIsManagedByDefaultIn
)
{
TraceFunc( "[IClusCfgManagedResourceInfo]" );
HRESULT hr = S_OK;
m_fIsManagedByDefault = fIsManagedByDefaultIn;
LOG_STATUS_REPORT_STRING2(
L"Physical disk '%1!ws!' '%2!ws!"
, ( m_bstrFriendlyName != NULL ) ? m_bstrFriendlyName : m_bstrName
, fIsManagedByDefaultIn ? L"is manageable" : L"is not manageable"
, hr
);
HRETURN( hr );
} //*** CPhysicalDisk::SetManagedByDefault
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk class -- IClusCfgPhysicalDiskProperties Interface.
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::IsThisLogicalDisk
//
// Description:
//
// Arguments:
// None.
//
// Return Value:
//
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::IsThisLogicalDisk( WCHAR cLogicalDiskIn )
{
TraceFunc( "[IClusCfgPhysicalDiskProperties]" );
HRESULT hr = S_FALSE;
ULONG idx;
IClusCfgPartitionProperties * piccpp = NULL;
for ( idx = 0; idx < m_idxNextPartition; idx++ )
{
hr = ( ((*m_prgPartitions)[ idx ])->TypeSafeQI( IClusCfgPartitionProperties, &piccpp ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = STHR( piccpp->IsThisLogicalDisk( cLogicalDiskIn ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
if ( hr == S_OK )
{
break;
} // if:
piccpp->Release();
piccpp = NULL;
} // for:
Cleanup:
if ( piccpp != NULL )
{
piccpp->Release();
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::IsThisLogicalDisk
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrGetSCSIBus
//
// Description:
//
// Arguments:
// None.
//
// Return Value:
//
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::HrGetSCSIBus( ULONG * pulSCSIBusOut )
{
TraceFunc( "[IClusCfgPhysicalDiskProperties]" );
HRESULT hr = S_OK;
if ( pulSCSIBusOut == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_HrGetSCSIBus, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr );
goto Cleanup;
} // if:
*pulSCSIBusOut = m_ulSCSIBus;
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::HrGetSCSIBus
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrGetSCSIPort
//
// Description:
//
// Arguments:
// None.
//
// Return Value:
//
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::HrGetSCSIPort( ULONG * pulSCSIPortOut )
{
TraceFunc( "[IClusCfgPhysicalDiskProperties]" );
HRESULT hr = S_OK;
if ( pulSCSIPortOut == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_HrGetSCSIPort, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr );
goto Cleanup;
} // if:
*pulSCSIPortOut = m_ulSCSIPort;
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::HrGetSCSIPort
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrGetDeviceID
//
// Description:
//
// Arguments:
// None.
//
// Return Value:
//
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::HrGetDeviceID( BSTR * pbstrDeviceIDOut )
{
TraceFunc( "" );
Assert( m_bstrDeviceID != NULL );
HRESULT hr = S_OK;
if ( pbstrDeviceIDOut == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_HrGetDeviceID_Pointer, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr );
goto Cleanup;
} // if:
*pbstrDeviceIDOut = TraceSysAllocString( m_bstrDeviceID );
if ( *pbstrDeviceIDOut == NULL )
{
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_HrGetDeviceID_Memory, IDS_ERROR_OUTOFMEMORY, IDS_ERROR_OUTOFMEMORY_REF, hr );
} // if:
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::HrGetDeviceID
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrGetSignature
//
// Description:
//
// Arguments:
// None.
//
// Return Value:
//
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::HrGetSignature( DWORD * pdwSignatureOut )
{
TraceFunc( "" );
Assert( m_dwSignature != 0 );
HRESULT hr = S_OK;
if ( pdwSignatureOut == NULL )
{
hr = THR( E_POINTER );
STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_HrGetSignature_Pointer, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr );
goto Cleanup;
} // if:
*pdwSignatureOut = m_dwSignature;
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::HrGetSignature
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrSetFriendlyName
//
// Description:
//
// Arguments:
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::HrSetFriendlyName( LPCWSTR pcszFriendlyNameIn )
{
TraceFunc1( "[IClusCfgManagedResourceInfo] pcszFriendlyNameIn = '%ws'", pcszFriendlyNameIn == NULL ? L"<null>" : pcszFriendlyNameIn );
HRESULT hr = S_OK;
BSTR bstr = NULL;
if ( pcszFriendlyNameIn == NULL )
{
hr = THR( E_INVALIDARG );
goto Cleanup;
} // if:
bstr = TraceSysAllocString( pcszFriendlyNameIn );
if ( bstr == NULL )
{
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_HrSetFriendlyName_PhysDisk, IDS_ERROR_OUTOFMEMORY, hr );
goto Cleanup;
} // if:
TraceSysFreeString( m_bstrFriendlyName );
m_bstrFriendlyName = bstr;
LOG_STATUS_REPORT_STRING( L"Setting physical disk friendly name to \"%1!ws!\".", m_bstrFriendlyName, hr );
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::HrSetFriendlyName
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrGetDeviceIndex
//
// Description:
//
// Arguments:
//
// Return Value:
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::HrGetDeviceIndex( DWORD * pidxDeviceOut )
{
TraceFunc( "" );
HRESULT hr = S_OK;
if ( pidxDeviceOut == NULL )
{
hr = THR( E_POINTER );
goto Cleanup;
} // if:
*pidxDeviceOut = m_idxDevice;
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::HrGetDeviceIndex
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::CanBeManaged
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// The device is managed.
//
// S_FALSE
// The device is not managed.
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::CanBeManaged( void )
{
TraceFunc( "[IClusCfgPhysicalDiskProperties]" );
HRESULT hr = S_OK;
ULONG idx;
IClusCfgPartitionProperties * piccpp = NULL;
//
// Turn off the manageable state because this disk may already be managed by
// another node, or it may be RAW.
//
m_fIsManagedByDefault = FALSE;
//
// A disk must have at least one NTFS partition in order to be a quorum
// resource.
//
m_fIsQuorumCapable = FALSE;
m_fIsQuorumResourceMultiNodeCapable = FALSE;
//
// If this disk has no partitions then it may already be managed by
// another node, or it may be RAW.
//
if ( m_idxNextPartition == 0 )
{
hr = S_FALSE;
goto Cleanup;
} // if:
//
// Enum the partitions and set the quorum capable flag if an NTFS
// partition is found.
//
for ( idx = 0; idx < m_idxNextPartition; idx++ )
{
hr = ( ((*m_prgPartitions)[ idx ])->TypeSafeQI( IClusCfgPartitionProperties, &piccpp ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = STHR( piccpp->IsNTFS() );
if ( hr == S_OK )
{
m_fIsQuorumCapable = TRUE;
m_fIsQuorumResourceMultiNodeCapable = TRUE;
m_fIsManagedByDefault = TRUE;
break;
} // if:
piccpp->Release();
piccpp = NULL;
} // for:
Cleanup:
LOG_STATUS_REPORT_STRING2(
L"Physical disk '%1!ws!' %2!ws! quorum capable."
, ( ( m_bstrFriendlyName != NULL ) ? m_bstrFriendlyName : m_bstrName )
, ( ( m_fIsQuorumCapable == TRUE ) ? L"is" : L"is NOT" )
, hr
);
if ( FAILED( hr ) )
{
LOG_STATUS_REPORT( L"CPhysicalDisk::CanBeManaged failed.", hr );
} // if:
if ( piccpp != NULL )
{
piccpp->Release();
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::CanBeManaged
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrIsDynamicDisk
//
// Description:
// Is this disk a "dynamic" disk? Dynamic disks are those disks that
// contain LDM partitions.
//
// Arguments:
// None.
//
// Return Value:
// S_OK
// This is a dynamic disk.
//
// S_FALSE
// This is not a dynamic disk.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::HrIsDynamicDisk( void )
{
TraceFunc( "" );
HRESULT hr = S_OK;
if ( m_fIsDynamicDisk == FALSE )
{
hr = S_FALSE;
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::HrIsDynamicDisk
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrIsGPTDisk
//
// Description:
// Is this disk a "GPT" disk? GPT disks are those disks that
// contain GPT partitions.
//
// Arguments:
// None.
//
// Return Value:
// S_OK
// This is a GPT disk.
//
// S_FALSE
// This is not a GPT disk.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::HrIsGPTDisk( void )
{
TraceFunc( "" );
HRESULT hr = S_OK;
if ( m_fIsGPTDisk == FALSE )
{
hr = S_FALSE;
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::HrIsGPTDisk
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrGetDiskNames
//
// Description:
// Get the names of this disk, both its friendly and device names.
//
// Arguments:
// pbstrDiskNameOut
//
// pbstrDeviceNameOut
//
// Return Value:
// S_OK
// Success;
//
// E_OUTOFMEMORY
//
// E_POINTER
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::HrGetDiskNames(
BSTR * pbstrDiskNameOut
, BSTR * pbstrDeviceNameOut
)
{
TraceFunc( "" );
Assert( m_bstrName != NULL );
Assert( m_bstrFriendlyName != NULL );
Assert( pbstrDiskNameOut != NULL );
Assert( pbstrDeviceNameOut != NULL );
HRESULT hr = S_OK;
BSTR bstr = NULL;
if ( ( pbstrDiskNameOut == NULL ) || ( pbstrDeviceNameOut == NULL ) )
{
hr = THR( E_POINTER );
goto Cleanup;
} // if:
bstr = TraceSysAllocString( m_bstrFriendlyName );
if ( bstr == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
*pbstrDiskNameOut = bstr;
bstr = NULL;
bstr = TraceSysAllocString( m_bstrName );
if ( bstr == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
*pbstrDeviceNameOut = bstr;
bstr = NULL;
Cleanup:
TraceSysFreeString( bstr );
HRETURN( hr );
} //*** CPhysicalDisk::HrGetDiskNames
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk class -- IClusCfgManagedResourceCfg
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::PreCreate
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::PreCreate( IUnknown * punkServicesIn )
{
TraceFunc( "[IClusCfgManagedResourceCfg]" );
HRESULT hr = S_OK;
IClusCfgResourcePreCreate * pccrpc = NULL;
BSTR bstr = m_bstrFriendlyName != NULL ? m_bstrFriendlyName : m_bstrName;
hr = THR( punkServicesIn->TypeSafeQI( IClusCfgResourcePreCreate, &pccrpc ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( pccrpc->SetType( (LPCLSID) &RESTYPE_PhysicalDisk ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( pccrpc->SetClassType( (LPCLSID) &RESCLASSTYPE_StorageDevice ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
#if 0 // test code only
hr = THR( pccrpc->SetDependency( (LPCLSID) &IID_NULL, dfSHARED ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
#endif // test code only
Cleanup:
STATUS_REPORT_STRING( TASKID_Major_Configure_Resources, TASKID_Minor_PhysDisk_PreCreate, IDS_INFO_PHYSDISK_PRECREATE, bstr, hr );
if ( pccrpc != NULL )
{
pccrpc->Release();
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::PreCreate
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Create
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::Create( IUnknown * punkServicesIn )
{
TraceFunc( "[IClusCfgManagedResourceCfg]" );
HRESULT hr = S_OK;
IClusCfgResourceCreate * pccrc = NULL;
BSTR * pbstr = m_bstrFriendlyName != NULL ? &m_bstrFriendlyName : &m_bstrName;
hr = THR( punkServicesIn->TypeSafeQI( IClusCfgResourceCreate, &pccrc ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
if ( m_dwSignature != 0 )
{
LOG_STATUS_REPORT_STRING2( L"Setting signature to \"%1!u!\" on resource \"%2!ws!\".", m_dwSignature, *pbstr, hr );
hr = THR( pccrc->SetPropertyDWORD( L"Signature", m_dwSignature ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
} // if:
Cleanup:
STATUS_REPORT_STRING( TASKID_Major_Configure_Resources, TASKID_Minor_PhysDisk_Create, IDS_INFO_PHYSDISK_CREATE, *pbstr, hr );
if ( pccrc != NULL )
{
pccrc->Release();
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::Create
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::PostCreate
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::PostCreate( IUnknown * punkServicesIn )
{
TraceFunc( "[IClusCfgManagedResourceCfg]" );
HRETURN( S_OK );
} //*** CPhysicalDisk::PostCreate
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Evict
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// Success
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::Evict( IUnknown * punkServicesIn )
{
TraceFunc( "[IClusCfgManagedResourceCfg]" );
HRETURN( S_OK );
} //*** CPhysicalDisk::Evict
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk class -- Private Methods.
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrInit
//
// Description:
// Initialize this component.
//
// Arguments:
// None.
//
// Return Value:
//
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrInit( void )
{
TraceFunc( "" );
HRESULT hr = S_OK;
// IUnknown
Assert( m_cRef == 1 );
HRETURN( hr );
} //*** CPhysicalDisk::HrInit
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::HrGetPartitionInfo
//
// Description:
// Gather the partition information.
//
// Arguments:
// None.
//
// Return Value:
//
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrGetPartitionInfo(
IWbemClassObject * pDiskIn
, bool * pfRetainObjectOut
)
{
TraceFunc( "" );
Assert( pDiskIn != NULL );
Assert( pfRetainObjectOut != NULL );
HRESULT hr;
VARIANT var;
VARIANT varDiskName;
WCHAR szBuf[ 256 ];
IEnumWbemClassObject * pPartitions = NULL;
IWbemClassObject * pPartition = NULL;
ULONG ulReturned;
BSTR bstrQuery = NULL;
BSTR bstrWQL = NULL;
DWORD cPartitions;
bstrWQL = TraceSysAllocString( L"WQL" );
if ( bstrWQL == NULL )
{
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_HrGetPartitionInfo, IDS_ERROR_OUTOFMEMORY, hr );
goto Cleanup;
} // if:
VariantInit( &var );
VariantInit( &varDiskName );
//
// Need to enum the partition(s) of this disk to determine if it is booted
// bootable.
//
hr = THR( HrGetWMIProperty( pDiskIn, L"DeviceID", VT_BSTR, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( StringCchPrintfW(
szBuf
, ARRAYSIZE( szBuf )
, L"Associators of {Win32_DiskDrive.DeviceID='%ws'} where AssocClass=Win32_DiskDriveToDiskPartition"
, var.bstrVal
) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
bstrQuery = TraceSysAllocString( szBuf );
if ( bstrQuery == NULL )
{
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_HrGetPartitionInfo, IDS_ERROR_OUTOFMEMORY, hr );
goto Cleanup;
} // if:
hr = THR( m_pIWbemServices->ExecQuery( bstrWQL, bstrQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pPartitions ) );
if ( FAILED( hr ) )
{
STATUS_REPORT_STRING_REF(
TASKID_Major_Find_Devices
, TASKID_Minor_WMI_DiskDrivePartitions_Qry_Failed
, IDS_ERROR_WMI_DISKDRIVEPARTITIONS_QRY_FAILED
, var.bstrVal
, IDS_ERROR_WMI_DISKDRIVEPARTITIONS_QRY_FAILED_REF
, hr
);
goto Cleanup;
} // if:
for ( cPartitions = 0; ; cPartitions++ )
{
hr = STHR( pPartitions->Next( WBEM_INFINITE, 1, &pPartition, &ulReturned ) );
if ( ( hr == S_OK ) && ( ulReturned == 1 ) )
{
hr = STHR( HrIsPartitionLDM( pPartition ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
//
// If the partition is logical disk manager (LDM) then we cannot accept this disk therefore cannot manage it.
//
if ( hr == S_OK )
{
m_fIsDynamicDisk = TRUE;
} // if:
hr = STHR( HrIsPartitionGPT( pPartition ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
if ( hr == S_OK )
{
m_fIsGPTDisk = TRUE;
} // if:
hr = THR( HrCreatePartitionInfo( pPartition ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
pPartition->Release();
pPartition = NULL;
} // if:
else if ( ( hr == S_FALSE ) && ( ulReturned == 0 ) )
{
break;
} // else if:
else
{
STATUS_REPORT_STRING_REF(
TASKID_Major_Find_Devices
, TASKID_Minor_WQL_Partition_Qry_Next_Failed
, IDS_ERROR_WQL_QRY_NEXT_FAILED
, bstrQuery
, IDS_ERROR_WQL_QRY_NEXT_FAILED_REF
, hr
);
goto Cleanup;
} // else:
} // for:
//
// The enumerator can be empty because we cannot read the partition info from
// clustered disks. If the enumerator was empty retain the S_FALSE, otherwise
// return S_OK if count is greater than 0.
//
if ( cPartitions > 0 )
{
hr = S_OK;
} // if:
else
{
LOG_STATUS_REPORT_STRING( L"The physical disk '%1!ws!' does not have any partitions and will not be managed", var.bstrVal, hr );
m_fIsManagedByDefault = FALSE;
} // else:
Cleanup:
VariantClear( &var );
VariantClear( &varDiskName );
TraceSysFreeString( bstrQuery );
TraceSysFreeString( bstrWQL );
if ( pPartition != NULL )
{
pPartition->Release();
} // if:
if ( pPartitions != NULL )
{
pPartitions->Release();
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::HrGetPartitionInfo
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrAddPartitionToArray
//
// Description:
// Add the passed in partition to the array of punks that holds the
// partitions.
//
// Arguments:
//
//
// Return Value:
// S_OK
// Success
//
// E_OUTOFMEMORY
// Couldn't allocate memeory.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrAddPartitionToArray( IUnknown * punkIn )
{
TraceFunc( "" );
HRESULT hr = S_OK;
IUnknown * ((*prgpunks)[]) = NULL;
prgpunks = (IUnknown *((*)[])) TraceReAlloc( m_prgPartitions, sizeof( IUnknown * ) * ( m_idxNextPartition + 1 ), HEAP_ZERO_MEMORY );
if ( prgpunks == NULL )
{
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_HrAddPartitionToArray, IDS_ERROR_OUTOFMEMORY, hr );
goto Cleanup;
} // if:
m_prgPartitions = prgpunks;
(*m_prgPartitions)[ m_idxNextPartition++ ] = punkIn;
punkIn->AddRef();
m_cPartitions += 1;
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::HrAddPartitionToArray
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrCreatePartitionInfo
//
// Description:
// Create a partition info from the passes in WMI partition.
//
// Arguments:
//
//
// Return Value:
// S_OK
// Success
//
// S_FALSE
// The file system was not NTFS.
//
// E_OUTOFMEMORY
// Couldn't allocate memeory.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrCreatePartitionInfo( IWbemClassObject * pPartitionIn )
{
TraceFunc( "" );
Assert( m_bstrDeviceID != NULL );
HRESULT hr = S_OK;
IUnknown * punk = NULL;
IClusCfgSetWbemObject * piccswo = NULL;
bool fRetainObject = true;
hr = THR( CClusCfgPartitionInfo::S_HrCreateInstance( &punk, m_bstrDeviceID ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
punk = TraceInterface( L"CClusCfgPartitionInfo", IUnknown, punk, 1 );
hr = THR( HrSetInitialize( punk, m_picccCallback, m_lcid ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( HrSetWbemServices( punk, m_pIWbemServices ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( punk->TypeSafeQI( IClusCfgSetWbemObject, &piccswo ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( piccswo->SetWbemObject( pPartitionIn, &fRetainObject ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
if ( fRetainObject )
{
hr = THR( HrAddPartitionToArray( punk ) );
} // if:
Cleanup:
if ( piccswo != NULL )
{
piccswo->Release();
} // if:
if ( punk != NULL )
{
punk->Release();
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::HrCreatePartitionInfo
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrCreateFriendlyName
//
// Description:
// Create a cluster friendly name.
//
// Arguments:
//
//
// Return Value:
// S_OK
// Success
//
// S_FALSE
// Success, but a friendly name could not be created.
//
// E_OUTOFMEMORY
// Couldn't allocate memeory.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrCreateFriendlyName( void )
{
TraceFunc( "" );
HRESULT hr = S_FALSE;
WCHAR * psz = NULL;
WCHAR * pszTmp = NULL;
DWORD cch;
DWORD idx;
IClusCfgPartitionProperties * piccpp = NULL;
BSTR bstrName = NULL;
bool fFoundLogicalDisk = false;
BSTR bstr = NULL;
BSTR bstrDisk = NULL;
if ( m_idxNextPartition == 0 )
{
goto Cleanup;
} // if:
hr = THR( HrLoadStringIntoBSTR( g_hInstance, IDS_DISK, &bstrDisk ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
cch = (UINT) wcslen( bstrDisk ) + 1;
psz = new WCHAR[ cch ];
if ( psz == NULL )
{
goto OutOfMemory;
} // if:
hr = THR( StringCchCopyW( psz, cch, bstrDisk ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
for ( idx = 0; idx < m_idxNextPartition; idx++ )
{
hr = THR( ((*m_prgPartitions)[ idx ])->TypeSafeQI( IClusCfgPartitionProperties, &piccpp ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = STHR( piccpp->GetFriendlyName( &bstrName ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
if ( hr == S_FALSE )
{
continue;
} // if:
fFoundLogicalDisk = true;
cch += (UINT) wcslen( bstrName ) + 1;
pszTmp = new WCHAR[ cch ];
if ( pszTmp == NULL )
{
goto OutOfMemory;
} // if:
hr = THR( StringCchCopyW( pszTmp, cch, psz ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
delete [] psz;
psz = pszTmp;
pszTmp = NULL;
hr = THR( StringCchCatW( psz, cch, bstrName ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
TraceSysFreeString( bstrName );
bstrName = NULL;
piccpp->Release();
piccpp = NULL;
} // for:
//
// KB: 31-JUL-2000
//
// If we didn't find any logical disk IDs then we don't want
// to touch m_bstrFriendlyName.
//
if ( !fFoundLogicalDisk )
{
hr = S_OK; // ensure that that the caller doesn't fail since this is not a fatal error...
goto Cleanup;
} // if:
bstr = TraceSysAllocString( psz );
if ( bstr == NULL )
{
goto OutOfMemory;
} // if:
TraceSysFreeString( m_bstrFriendlyName );
m_bstrFriendlyName = bstr;
bstr = NULL;
goto Cleanup;
OutOfMemory:
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_HrCreateFriendlyName_VOID, IDS_ERROR_OUTOFMEMORY, hr );
Cleanup:
if ( piccpp != NULL )
{
piccpp->Release();
} // if:
delete [] psz;
delete [] pszTmp;
TraceSysFreeString( bstrName );
TraceSysFreeString( bstrDisk );
TraceSysFreeString( bstr );
HRETURN( hr );
} //*** CPhysicalDisk::HrCreateFriendlyName
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrCreateFriendlyName
//
// Description:
// Convert the WMI disk name into a more freindly version.
// Create a cluster friendly name.
//
// Arguments:
//
//
// Return Value:
// S_OK
// Success
//
// E_OUTOFMEMORY
// Couldn't allocate memeory.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrCreateFriendlyName( BSTR bstrNameIn )
{
TraceFunc1( "bstrNameIn = '%ws'", bstrNameIn == NULL ? L"<null>" : bstrNameIn );
HRESULT hr = S_OK;
WCHAR * psz = NULL;
BSTR bstr = NULL;
//
// KB: 27-JUN-2000 GalenB
//
// Disk names in WMI start with "\\.\". As a better and easy
// friendly name I am just going to trim these leading chars
// off.
//
psz = bstrNameIn + wcslen( L"\\\\.\\" );
bstr = TraceSysAllocString( psz );
if ( bstr == NULL )
{
hr = THR( E_OUTOFMEMORY );
STATUS_REPORT( TASKID_Major_Find_Devices, TASKID_Minor_HrCreateFriendlyName_BSTR, IDS_ERROR_OUTOFMEMORY, hr );
goto Cleanup;
} // if:
TraceSysFreeString( m_bstrName );
m_bstrName = bstr;
Cleanup:
HRETURN( hr );
} //*** CPhysicalDisk::HrCreateFriendlyName
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrIsPartitionGPT
//
// Description:
// Is the passed in partition a GPT partition.
//
// Arguments:
//
//
// Return Value:
// S_OK
// The partition is a GPT partition.
//
// S_FALSE
// The partition is not GPT.
//
// E_OUTOFMEMORY
// Couldn't allocate memeory.
//
// Remarks:
// If the type property of a Win32_DiskPartition starts with "GPT"
// then the whole spindle has GPT partitions.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrIsPartitionGPT( IWbemClassObject * pPartitionIn )
{
TraceFunc( "" );
HRESULT hr = S_OK;
VARIANT var;
WCHAR szData[ 4 ];
BSTR bstrGPT = NULL;
VariantInit( &var );
hr = THR( HrLoadStringIntoBSTR( g_hInstance, IDS_GPT, &bstrGPT ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( HrGetWMIProperty( pPartitionIn, L"Type", VT_BSTR, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
//
// Get the fist three characters. When the spindle has GPT partitions then
// these characters will be "GPT". I am unsure if this will be localized?
//
hr = THR( StringCchCopyNW( szData, ARRAYSIZE( szData ), var.bstrVal, 3 ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
CharUpper( szData );
if ( NStringCchCompareCase( szData, ARRAYSIZE( szData ), bstrGPT, SysStringLen( bstrGPT ) + 1 ) != 0 )
{
hr = S_FALSE;
} // if:
Cleanup:
VariantClear( &var );
TraceSysFreeString( bstrGPT );
HRETURN( hr );
} //*** CPhysicalDisk::HrIsPartitionGPT
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrIsPartitionLDM
//
// Description:
// Is the passed in partition an LDM partition.
//
// Arguments:
//
//
// Return Value:
// S_OK
// The partition is an LDM partition.
//
// S_FALSE
// The partition is not LDM.
//
// E_OUTOFMEMORY
// Couldn't allocate memeory.
//
// Remarks:
// If the type property of a Win32_DiskPartition is "logical disk
// manager" then this disk is an LDM disk.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrIsPartitionLDM( IWbemClassObject * pPartitionIn )
{
TraceFunc( "" );
HRESULT hr = S_OK;
VARIANT var;
BSTR bstrLDM = NULL;
VariantInit( &var );
hr = THR( HrLoadStringIntoBSTR( g_hInstance, IDS_LDM, &bstrLDM ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( HrGetWMIProperty( pPartitionIn, L"Type", VT_BSTR, &var ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
CharUpper( var.bstrVal );
if ( NBSTRCompareCase( var.bstrVal, bstrLDM ) != 0 )
{
hr = S_FALSE;
} // if:
Cleanup:
VariantClear( &var );
TraceSysFreeString( bstrLDM );
HRETURN( hr );
} //*** CPhysicalDisk::HrIsPartitionLDM
/*
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrGetDiskFirmwareSerialNumber
//
// Description:
// Get the disk firmware serial number.
//
// Arguments:
// None.
//
// Return Value:
// S_OK
// Success.
//
// S_FALSE
// There wasn't a firmware serial number.
//
// E_OUTOFMEMORY
// Couldn't allocate memeory.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrGetDiskFirmwareSerialNumber( void )
{
TraceFunc( "" );
HRESULT hr = S_OK;
HANDLE hVolume = NULL;
DWORD dwSize;
DWORD sc;
STORAGE_PROPERTY_QUERY spq;
BOOL fRet;
PSTORAGE_DEVICE_DESCRIPTOR pddBuffer = NULL;
DWORD cbBuffer;
PCHAR psz = NULL;
//
// get handle to disk
//
hVolume = CreateFileW(
m_bstrDeviceID
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
if ( hVolume == INVALID_HANDLE_VALUE )
{
sc = TW32( GetLastError() );
hr = HRESULT_FROM_WIN32( sc );
goto Cleanup;
} // if:
cbBuffer = sizeof( STORAGE_DEVICE_DESCRIPTOR ) + 2048;
pddBuffer = ( PSTORAGE_DEVICE_DESCRIPTOR ) TraceAlloc( 0, cbBuffer );
if ( pddBuffer == NULL )
{
goto OutOfMemory;
} // if:
ZeroMemory( pddBuffer, cbBuffer );
ZeroMemory( &spq, sizeof( spq ) );
spq.PropertyId = StorageDeviceProperty;
spq.QueryType = PropertyStandardQuery;
//
// issue storage class ioctl to get the disk's firmware serial number.
//
fRet = DeviceIoControl(
hVolume
, IOCTL_STORAGE_QUERY_PROPERTY
, &spq
, sizeof( spq )
, pddBuffer
, cbBuffer
, &dwSize
, NULL
);
if ( !fRet )
{
sc = TW32( GetLastError() );
hr = HRESULT_FROM_WIN32( sc );
goto Cleanup;
} // if:
if ( dwSize > 0 )
{
//
// Ensure that there is a serial number offset and that it is within the buffer extents.
//
if ( ( pddBuffer->SerialNumberOffset == 0 ) || ( pddBuffer->SerialNumberOffset > pddBuffer->Size ) )
{
LOG_STATUS_REPORT_STRING( L"The disk '%1!ws!' does not have a firmware serial number.", m_bstrDeviceID, hr );
hr = S_FALSE;
goto Cleanup;
} // if:
//
// Serial number string is a zero terminated ASCII string.
//
// The header ntddstor.h says the for devices with no serial number,
// the offset will be zero. This doesn't seem to be TRUE.
//
// For devices with no serial number, it looks like a string with a single
// null character '\0' is returned.
//
psz = (PCHAR) pddBuffer + (DWORD) pddBuffer->SerialNumberOffset;
hr = THR( HrAnsiStringToBSTR( psz, &m_bstrFirmwareSerialNumber ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
LOG_STATUS_REPORT_STRING3(
L"Disk '%1!ws!' has firmware serial number '%2!ws!' at offset '%3!#08x!'."
, m_bstrDeviceID
, m_bstrFirmwareSerialNumber
, pddBuffer->SerialNumberOffset
, hr
);
} // if:
goto Cleanup;
OutOfMemory:
hr = THR( E_OUTOFMEMORY );
LOG_STATUS_REPORT( L"HrGetDiskFirmwareSerialNumber() is out of memory.", hr );
Cleanup:
if ( hVolume != NULL )
{
CloseHandle( hVolume );
} // if:
TraceFree( pddBuffer );
HRETURN( hr );
} //*** CPhysicalDisk::HrGetDiskFirmwareSerialNumber
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrGetDiskFirmwareVitalData
//
// Description:
// Get the disk firmware vital data.
//
// Arguments:
// None.
//
// Return Value:
// S_OK
// Success.
//
// S_FALSE
// There wasn't a firmware serial number.
//
// E_OUTOFMEMORY
// Couldn't allocate memeory.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrGetDiskFirmwareVitalData( void )
{
TraceFunc( "" );
HRESULT hr = S_OK;
HANDLE hVolume = NULL;
DWORD dwSize;
DWORD sc;
STORAGE_PROPERTY_QUERY spq;
BOOL fRet;
PSTORAGE_DEVICE_ID_DESCRIPTOR psdidBuffer = NULL;
DWORD cbBuffer;
//
// get handle to disk
//
hVolume = CreateFileW(
m_bstrDeviceID
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
if ( hVolume == INVALID_HANDLE_VALUE )
{
sc = TW32( GetLastError() );
hr = HRESULT_FROM_WIN32( sc );
goto Cleanup;
} // if:
cbBuffer = sizeof( STORAGE_DEVICE_ID_DESCRIPTOR ) + 2048;
psdidBuffer = (PSTORAGE_DEVICE_ID_DESCRIPTOR) TraceAlloc( 0, cbBuffer );
if ( psdidBuffer == NULL )
{
goto OutOfMemory;
} // if:
ZeroMemory( psdidBuffer, cbBuffer );
ZeroMemory( &spq, sizeof( spq ) );
spq.PropertyId = StorageDeviceIdProperty;
spq.QueryType = PropertyStandardQuery;
//
// issue storage class ioctl to get the disk's firmware vital data
//
fRet = DeviceIoControl(
hVolume
, IOCTL_STORAGE_QUERY_PROPERTY
, &spq
, sizeof( spq )
, psdidBuffer
, cbBuffer
, &dwSize
, NULL
);
if ( !fRet )
{
sc = TW32( GetLastError() );
hr = HRESULT_FROM_WIN32( sc );
goto Cleanup;
} // if:
if ( dwSize > 0 )
{
} // if:
goto Cleanup;
OutOfMemory:
hr = THR( E_OUTOFMEMORY );
LOG_STATUS_REPORT( L"HrGetDiskFirmwareVitalData() is out of memory.", hr );
Cleanup:
if ( hVolume != NULL )
{
CloseHandle( hVolume );
} // if:
TraceFree( psdidBuffer );
HRETURN( hr );
} //*** CPhysicalDisk::HrGetDiskFirmwareVitalData
*/
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrIsClusterCapable
//
// Description:
// Is this disk cluster capable?
//
// Arguments:
// None.
//
// Return Value:
// S_OK
// The disk is cluster capable.
//
// S_FALSE
// The disk is not cluster capable.
//
// E_OUTOFMEMORY
// Couldn't allocate memeory.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrIsClusterCapable( void )
{
TraceFunc( "" );
HRESULT hr = S_OK;
HANDLE hSCSIPort = INVALID_HANDLE_VALUE;
DWORD dwSize;
DWORD sc;
BOOL fRet;
WCHAR szSCSIPort[ 32 ];
SRB_IO_CONTROL srb;
hr = THR( StringCchPrintfW( szSCSIPort, ARRAYSIZE( szSCSIPort ), L"\\\\.\\Scsi%d:", m_ulSCSIPort ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
//
// get handle to disk
//
hSCSIPort = CreateFileW(
szSCSIPort
, GENERIC_READ | GENERIC_WRITE
, FILE_SHARE_READ | FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
if ( hSCSIPort == INVALID_HANDLE_VALUE )
{
sc = TW32( GetLastError() );
hr = HRESULT_FROM_WIN32( sc );
LOG_STATUS_REPORT_STRING( L"Failed to open device %1!ws!.", szSCSIPort, hr );
goto Cleanup;
} // if:
#define CLUSDISK_SRB_SIGNATURE "CLUSDISK"
ZeroMemory( &srb, sizeof( srb ) );
srb.HeaderLength = sizeof( srb );
Assert( sizeof( srb.Signature ) <= sizeof( CLUSDISK_SRB_SIGNATURE ) );
CopyMemory( srb.Signature, CLUSDISK_SRB_SIGNATURE, sizeof( srb.Signature ) );
srb.ControlCode = IOCTL_SCSI_MINIPORT_NOT_QUORUM_CAPABLE;
//
// issue mini port ioctl to determine whether the disk is cluster capable
//
fRet = DeviceIoControl(
hSCSIPort
, IOCTL_SCSI_MINIPORT
, &srb
, sizeof( srb )
, NULL
, 0
, &dwSize
, NULL
);
//
// If the call succeeds then the disk is "not cluster capable". If the call
// fails then the disk is "not not cluster capable" and that means that it
// is cluster capable.
//
if ( fRet )
{
hr = S_FALSE;
} // if:
else
{
hr = S_OK;
} // else:
LogMsg( L"[SRV] The disks on SCSI port %d are%ws cluster capable.", m_ulSCSIPort, ( hr == S_FALSE ? L" not" : L"" ) );
Cleanup:
if ( FAILED( hr ) )
{
CLSID clsidMinorId;
HRESULT hrTemp;
hrTemp = THR( CoCreateGuid( &clsidMinorId ) );
if ( FAILED( hrTemp ) )
{
LOG_STATUS_REPORT( L"Could not create a guid for a not cluster capable disk minor task ID", hrTemp );
clsidMinorId = IID_NULL;
} // if:
STATUS_REPORT_STRING2_REF(
TASKID_Minor_PhysDisk_Cluster_Capable
, clsidMinorId
, IDS_ERROR_PHYSDISK_CLUSTER_CAPABLE
, m_bstrFriendlyName
, m_ulSCSIPort
, IDS_ERROR_PHYSDISK_CLUSTER_CAPABLE_REF
, hr
);
} // if:
if ( hSCSIPort != INVALID_HANDLE_VALUE )
{
CloseHandle( hSCSIPort );
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::HrIsClusterCapable
/*
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrProcessMountPoints
//
// Description:
// if any of the partitions on this spindle have reparse points then
// the mounted volumes are found and enumerated.
//
// Arguments:
// None.
//
// Return Value:
// S_OK
// Success.
//
// HRESULT errors.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrProcessMountPoints(
void
)
{
TraceFunc( "" );
HRESULT hr = S_OK;
ULONG idxOuter;
ULONG idxInner;
IClusCfgPartitionInfo * piccpi = NULL;
SDriveLetterMapping sdlm;
DWORD dwFlags;
WCHAR szRootPath[] = L"A:\\";
BSTR bstrFileSystem = NULL;
for ( idxOuter = 0; idxOuter < m_idxNextPartition; idxOuter++ )
{
hr = THR( ((*m_prgPartitions)[ idxOuter ])->TypeSafeQI( IClusCfgPartitionInfo, &piccpi ) );
if ( FAILED( hr ) )
{
LOG_STATUS_REPORT( L"CPhysicalDisk::HrHasReparsePoints() could not query for IClusCfgPartitionInfo.", hr );
goto Cleanup;
} // if:
InitDriveLetterMappings( &sdlm );
hr = THR( piccpi->GetDriveLetterMappings( &sdlm ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
if ( hr == S_OK )
{
for ( idxInner = 0; idxInner < 26; idxInner++)
{
if ( sdlm.dluDrives[ idxInner ] != dluUNUSED )
{
szRootPath[ 0 ] = L'A' + (WCHAR) idxInner;
hr = THR( HrGetVolumeInformation( szRootPath, &dwFlags, &bstrFileSystem ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
//
// If this spindle has reparse points then we need to return S_OK.
//
if ( dwFlags & FILE_SUPPORTS_REPARSE_POINTS )
{
hr = THR( HrEnumMountPoints( szRootPath ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
} // if:
TraceSysFreeString( bstrFileSystem );
bstrFileSystem = NULL;
} // if:
} // for:
} // if:
piccpi->Release();
piccpi = NULL;
} // for:
Cleanup:
if ( piccpi != NULL )
{
piccpi->Release();
} // if:
TraceSysFreeString( bstrFileSystem );
HRETURN( hr );
} //*** CPhysicalDisk::HrProcessMountPoints
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrEnumMountPoints
//
// Description:
// Enumerate the mounted volumes of the passed in root path.
//
// Arguments:
// pcszRootPathIn
//
// Return Value:
// S_OK
// Success.
//
// HRESULT errors.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrEnumMountPoints(
const WCHAR * pcszRootPathIn
)
{
TraceFunc( "" );
Assert( pcszRootPathIn != NULL );
HRESULT hr = S_OK;
HANDLE hEnum = NULL;
BOOL fRet;
WCHAR * psz = NULL;
DWORD cch = 512;
DWORD sc;
int cTemp;
psz = new WCHAR[ cch ];
if ( psz == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
for ( cTemp = 0; cTemp < 3; cTemp++ )
{
hEnum = FindFirstVolumeMountPointW( pcszRootPathIn, psz, cch );
if ( hEnum == INVALID_HANDLE_VALUE )
{
sc = GetLastError();
if ( sc == ERROR_NO_MORE_FILES )
{
hr = S_FALSE;
goto Cleanup;
} // if:
else if ( sc == ERROR_BAD_LENGTH )
{
//
// Grow the buffer and try again.
//
cch += 512;
delete [] psz;
psz = new WCHAR[ cch ];
if ( psz == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
continue;
} // else if:
else
{
hr = HRESULT_FROM_WIN32( TW32( sc ) );
goto Cleanup;
} // else:
} // if:
else
{
sc = ERROR_SUCCESS;
break;
} // else:
} // for:
if ( hEnum == INVALID_HANDLE_VALUE )
{
hr = HRESULT_FROM_WIN32( TW32( GetLastError() ) );
goto Cleanup;
} // if:
//
// psz has the first mounted volume
//
hr = STHR( HrProcessMountedVolume( pcszRootPathIn, psz ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
//
// Now find any remaining mount points.
//
for ( ; ; )
{
fRet = FindNextVolumeMountPointW( hEnum, psz, cch );
if ( fRet == FALSE )
{
sc = GetLastError();
if ( sc == ERROR_NO_MORE_FILES )
{
hr = S_OK;
break;
} // if:
else if ( sc == ERROR_BAD_LENGTH )
{
//
// Grow the buffer and try again.
//
cch += 512;
delete [] psz;
psz = new WCHAR[ cch ];
if ( psz == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
continue;
} // else if:
else
{
TW32( sc );
hr = HRESULT_FROM_WIN32( sc );
goto Cleanup;
} // else:
} // if:
else
{
hr = STHR( HrProcessMountedVolume( pcszRootPathIn, psz ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
} // else:
} // for:
Cleanup:
if ( hEnum != INVALID_HANDLE_VALUE )
{
FindVolumeMountPointClose( hEnum );
} // if:
delete [] psz;
HRETURN( hr );
} //*** CPhysicalDisk::HrEnumMountPoints
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:InitDriveLetterMappings
//
// Description:
// Initialize the drive letter mappings array.
//
// Arguments:
// pdlmDriveLetterMappingOut
//
// Return Value:
// None.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
void
CPhysicalDisk::InitDriveLetterMappings(
SDriveLetterMapping * pdlmDriveLetterMappingOut
)
{
TraceFunc( "" );
Assert( pdlmDriveLetterMappingOut != NULL );
ULONG idx;
for ( idx = 0 ; idx < 26 ; idx++ )
{
pdlmDriveLetterMappingOut->dluDrives[ idx ] = dluUNUSED;
} // for:
TraceFuncExit();
} // *** CPhysicalDisk::InitDriveLetterMappings
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrProcessMountedVolume
//
// Description:
// Process the mounted volume by finding each spindle that makes up
// the mount point volume and convert it into a WMI device ID.
//
// Arguments:
// pcszRootPathIn
//
// pcszMountPointIn
//
// Return Value:
// S_OK
// Success.
//
// S_FALSE
// The mounted volume was not a physical disk.
//
// HRESULT errors.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrProcessMountedVolume(
const WCHAR * pcszRootPathIn
, const WCHAR * pcszMountPointIn
)
{
TraceFunc( "" );
Assert( pcszRootPathIn != NULL );
Assert( pcszMountPointIn != NULL );
HRESULT hr = S_OK;
BOOL fRet;
WCHAR * pszPath = NULL;
DWORD cchPath;
WCHAR * psz = NULL;
DWORD cch = 512;
int cTemp;
DWORD sc = ERROR_SUCCESS;
BSTR bstr = NULL;
UINT uDriveType;
HANDLE hVolume = NULL;
PVOLUME_DISK_EXTENTS pvde = NULL;
DWORD cbvde;
DWORD dwSize;
WCHAR sz[ 32 ];
DWORD idx;
BSTR bstrFileSystem = NULL;
BOOL fIsNTFS;
cchPath = wcslen( pcszRootPathIn ) + wcslen( pcszMountPointIn ) + 1;
pszPath = new WCHAR[ cchPath ];
if ( pszPath == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
hr = THR( StringCchCopyW( pszPath, cchPath, pcszRootPathIn ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( StringCchCopyW( pszPath, cchPath, pcszMountPointIn ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
psz = new WCHAR[ cch ];
if ( psz == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
for ( cTemp = 0, fRet = FALSE; cTemp < 3; cTemp++ )
{
fRet = GetVolumeNameForVolumeMountPoint( pszPath, psz, cch );
if ( fRet == FALSE )
{
sc = GetLastError();
if ( sc == ERROR_BAD_LENGTH )
{
//
// Grow the buffer and try again.
//
cch += 512;
delete [] psz;
psz = new WCHAR[ cch ];
if ( psz == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
continue;
} // if:
else
{
hr = HRESULT_FROM_WIN32( TW32( sc ) );
goto Cleanup;
} // else:
} // if:
else
{
sc = ERROR_SUCCESS;
break;
} // else:
} // for:
if ( fRet == FALSE )
{
hr = HRESULT_FROM_WIN32( TW32( GetLastError() ) );
goto Cleanup;
} // if:
//
// Now psz has the "guid volume name" for the volume that is mounted.
//
//
// Now we need to ensure that the mounted volume is a fixed disk.
//
uDriveType = GetDriveType( psz );
if ( uDriveType != DRIVE_FIXED )
{
hr = S_FALSE;
goto Cleanup;
} // if:
hr = THR( HrGetVolumeInformation( psz, NULL, &bstrFileSystem ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
//
// We don't care about volumes that are not using NTFS.
//
fIsNTFS = ( NStringCchCompareCase( bstrFileSystem, SysStringLen( bstrFileSystem ) + 1, L"NTFS", RTL_NUMBER_OF( L"NTFS" ) ) == 0 );
if ( fIsNTFS == FALSE )
{
hr = S_FALSE;
goto Cleanup;
} // if:
//
// Trim off the trailing \ so we can open the device and poke it with
// an IOCTL.
//
psz[ wcslen( psz ) - 1 ] = L'\0';
//
// Get and handle to the device.
//
hVolume = CreateFileW(
psz
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
if ( hVolume == INVALID_HANDLE_VALUE )
{
sc = TW32( GetLastError() );
hr = HRESULT_FROM_WIN32( sc );
goto Cleanup;
} // if:
cbvde = sizeof( VOLUME_DISK_EXTENTS );
pvde = (PVOLUME_DISK_EXTENTS) TraceAlloc( 0, cbvde );
if ( pvde == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
for ( cTemp = 0; cTemp < 3; cTemp++ )
{
fRet = DeviceIoControl(
hVolume
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
, 0
, pvde
, cbvde
, &dwSize
, NULL
);
if ( fRet == FALSE )
{
sc = GetLastError();
if ( sc == ERROR_MORE_DATA )
{
PVOLUME_DISK_EXTENTS pvdeTemp = NULL;
cbvde = sizeof( VOLUME_DISK_EXTENTS ) + ( sizeof( DISK_EXTENT ) * pvde->NumberOfDiskExtents );
pvdeTemp = (PVOLUME_DISK_EXTENTS) TraceReAlloc( pvde, cbvde, HEAP_ZERO_MEMORY );
if ( pvdeTemp == NULL )
{
hr = THR( E_OUTOFMEMORY );
goto Cleanup;
} // if:
pvde = pvdeTemp;
continue;
} // if:
else
{
TW32( sc );
hr = HRESULT_FROM_WIN32( sc );
goto Cleanup;
} // else:
} // if:
else
{
sc = ERROR_SUCCESS;
break;
} // else:
} // for:
if ( sc != ERROR_SUCCESS )
{
hr = HRESULT_FROM_WIN32( TW32( sc ) );
goto Cleanup;
} // if:
//
// Now we have the disk number(s) of the mounted disk and we can convert that to
// a WMI device ID.
//
for ( idx = 0; idx < pvde->NumberOfDiskExtents; idx++ )
{
hr = THR( StringCchPrintfW( sz, ARRAYSIZE( sz ), g_szPhysicalDriveFormat, pvde->Extents[ idx ].DiskNumber ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
hr = THR( HrProcessSpindle( sz ) );
if ( FAILED( hr ) )
{
goto Cleanup;
} // if:
} // for:
Cleanup:
if ( hVolume != NULL )
{
CloseHandle( hVolume );
} // if:
TraceFree( pvde );
TraceSysFreeString( bstr );
TraceSysFreeString( bstrFileSystem );
delete [] psz;
delete [] pszPath;
HRETURN( hr );
} // *** CPhysicalDisk::HrProcessMountedVolume
/////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk:HrProcessSpindle
//
// Description:
// Process the mounted volume spindle by creating a CPhysicalDisk
// object and adding it to the physical disks enumerator.
//
// Arguments:
// pcszDeviceIDIn
//
// Return Value:
// S_OK
// Success.
//
// HRESULT errors.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPhysicalDisk::HrProcessSpindle(
const WCHAR * pcszDeviceIDIn
)
{
Assert( pcszDeviceIDIn != NULL );
TraceFunc( "" );
HRESULT hr = S_OK;
Cleanup:
HRETURN( hr );
} // *** CPhysicalDisk::HrProcessSpindle
*/
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// CPhysicalDisk class -- IClusCfgVerifyQuorum interface.
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::PrepareToHostQuorumResource
//
// Description:
// Do any configuration necessary in preparation for this node hosting
// the quorum.
//
// Arguments:
// None.
//
// Return Value:
// S_OK
// Success
//
// Win32 error as HRESULT when an error occurs.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::PrepareToHostQuorumResource( void )
{
TraceFunc( "[IClusCfgVerifyQuorum]" );
HRETURN( S_OK );
} //*** CPhysicalDisk::PrepareToHostQuorumResource
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::Cleanup
//
// Description:
// Do any necessay cleanup from the PrepareToHostQuorumResource()
// method.
//
// If the cleanup method is anything other than successful completion
// then the anything created above in PrepareToHostQuorumResource()
// needs to be cleaned up.
//
// Arguments:
// cccrReasonIn
//
// Return Value:
// S_OK
// Success
//
// Win32 error as HRESULT when an error occurs.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::Cleanup(
EClusCfgCleanupReason cccrReasonIn
)
{
TraceFunc( "[IClusCfgVerifyQuorum]" );
HRETURN( S_OK );
} //*** CPhysicalDisk::Cleanup
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::IsMultiNodeCapable
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// The quorumable device allows join.
//
// S_FALSE
// The device does not allow join.
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// None.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::IsMultiNodeCapable( void )
{
TraceFunc( "[IClusCfgVerifyQuorum]" );
HRESULT hr = S_FALSE;
if ( m_fIsQuorumResourceMultiNodeCapable )
{
hr = S_OK;
} // if:
HRETURN( hr );
} //*** CPhysicalDisk::IsMultiNodeCapable
//////////////////////////////////////////////////////////////////////////////
//++
//
// CPhysicalDisk::SetMultiNodeCapable
//
// Description:
//
// Arguments:
//
// Return Value:
// S_OK
// The quorumable device allows join.
//
// S_FALSE
// The device does not allow join.
//
// Win32 error as HRESULT when an error occurs.
//
// Remarks:
// This function should never be called
//
//--
//////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CPhysicalDisk::SetMultiNodeCapable(
BOOL fMultiNodeCapableIn
)
{
TraceFunc( "[IClusCfgVerifyQuorum]" );
HRETURN( S_FALSE );
} //*** CPhysicalDisk::SetMultiNodeCapable
|
Matheus-IT/lang-python-related
|
data_analysis/Matplotlib/04Histograma_idades.py
|
from matplotlib import pyplot as plt
idades = [22, 65, 45, 55, 21, 22, 34, 42, 41, 4, 99, 101, 120, 122, 130, 111, 115, 80, 75, 54, 44, 64, 13, 18, 48]
posicoes = [x for x in range(len(idades))]
bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130]
plt.hist(idades, bins, histtype='stepfilled', rwidth=0.8)
plt.show()
|
bopopescu/MQUIC
|
src/mojo/edk/system/mach_port_relay.cc
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mojo/edk/system/mach_port_relay.h"
#include <mach/mach.h>
#include <utility>
#include "base/logging.h"
#include "base/mac/mach_port_util.h"
#include "base/mac/scoped_mach_port.h"
#include "base/process/process.h"
#include "mojo/edk/embedder/platform_handle_vector.h"
namespace mojo {
namespace edk {
// static
bool MachPortRelay::ReceivePorts(PlatformHandleVector* handles) {
DCHECK(handles);
for (size_t i = 0; i < handles->size(); i++) {
PlatformHandle* handle = handles->data() + i;
DCHECK(handle->type != PlatformHandle::Type::MACH);
if (handle->type != PlatformHandle::Type::MACH_NAME)
continue;
base::mac::ScopedMachReceiveRight message_port(handle->port);
base::mac::ScopedMachSendRight received_port(
base::ReceiveMachPort(message_port.get()));
if (received_port.get() == MACH_PORT_NULL) {
handle->port = MACH_PORT_NULL;
LOG(ERROR) << "Error receiving mach port";
return false;
}
handle->port = received_port.release();
handle->type = PlatformHandle::Type::MACH;
}
return true;
}
MachPortRelay::MachPortRelay(base::PortProvider* port_provider)
: port_provider_(port_provider) {
DCHECK(port_provider);
port_provider_->AddObserver(this);
}
MachPortRelay::~MachPortRelay() {
port_provider_->RemoveObserver(this);
}
bool MachPortRelay::SendPortsToProcess(Channel::Message* message,
base::ProcessHandle process) {
DCHECK(message);
mach_port_t task_port = port_provider_->TaskForPid(process);
if (task_port == MACH_PORT_NULL)
return false;
size_t num_sent = 0;
bool error = false;
ScopedPlatformHandleVectorPtr handles = message->TakeHandles();
// Message should have handles, otherwise there's no point in calling this
// function.
DCHECK(handles);
for (size_t i = 0; i < handles->size(); i++) {
PlatformHandle* handle = &(*handles)[i];
DCHECK(handle->type != PlatformHandle::Type::MACH_NAME);
if (handle->type != PlatformHandle::Type::MACH)
continue;
mach_port_name_t intermediate_port;
DCHECK(handle->port != MACH_PORT_NULL);
intermediate_port = base::CreateIntermediateMachPort(
task_port, base::mac::ScopedMachSendRight(handle->port), nullptr);
if (intermediate_port == MACH_PORT_NULL) {
handle->port = MACH_PORT_NULL;
error = true;
break;
}
handle->port = intermediate_port;
handle->type = PlatformHandle::Type::MACH_NAME;
num_sent++;
}
DCHECK(error || num_sent);
message->SetHandles(std::move(handles));
return !error;
}
bool MachPortRelay::ExtractPortRights(Channel::Message* message,
base::ProcessHandle process) {
DCHECK(message);
mach_port_t task_port = port_provider_->TaskForPid(process);
if (task_port == MACH_PORT_NULL)
return false;
size_t num_received = 0;
bool error = false;
ScopedPlatformHandleVectorPtr handles = message->TakeHandles();
// Message should have handles, otherwise there's no point in calling this
// function.
DCHECK(handles);
for (size_t i = 0; i < handles->size(); i++) {
PlatformHandle* handle = handles->data() + i;
DCHECK(handle->type != PlatformHandle::Type::MACH);
if (handle->type != PlatformHandle::Type::MACH_NAME)
continue;
mach_port_t extracted_right = MACH_PORT_NULL;
mach_msg_type_name_t extracted_right_type;
kern_return_t kr =
mach_port_extract_right(task_port, handle->port,
MACH_MSG_TYPE_MOVE_SEND,
&extracted_right, &extracted_right_type);
if (kr != KERN_SUCCESS) {
error = true;
break;
}
DCHECK_EQ(static_cast<mach_msg_type_name_t>(MACH_MSG_TYPE_PORT_SEND),
extracted_right_type);
handle->port = extracted_right;
handle->type = PlatformHandle::Type::MACH;
num_received++;
}
DCHECK(error || num_received);
message->SetHandles(std::move(handles));
return !error;
}
void MachPortRelay::AddObserver(Observer* observer) {
base::AutoLock locker(observers_lock_);
bool inserted = observers_.insert(observer).second;
DCHECK(inserted);
}
void MachPortRelay::RemoveObserver(Observer* observer) {
base::AutoLock locker(observers_lock_);
observers_.erase(observer);
}
void MachPortRelay::OnReceivedTaskPort(base::ProcessHandle process) {
base::AutoLock locker(observers_lock_);
for (const auto observer : observers_)
observer->OnProcessReady(process);
}
} // namespace edk
} // namespace mojo
|
figassis/iso20022
|
ObligationType1Choice.go
|
package iso20022
// Indicates the type of obligation.
type ObligationType1Choice struct {
// Indicates the type of the obligation using a code.
Code *ObligationType1Code `xml:"Cd"`
// Indicates the type of the obligation using a proprietary format.
Proprietary *GenericIdentification30 `xml:"Prtry"`
}
func (o *ObligationType1Choice) SetCode(value string) {
o.Code = (*ObligationType1Code)(&value)
}
func (o *ObligationType1Choice) AddProprietary() *GenericIdentification30 {
o.Proprietary = new(GenericIdentification30)
return o.Proprietary
}
|
TheXerax/libro-de-actividades
|
actividades/prog/files/ruby/mil-ejemplos/aplicaciones/morse/clases/simbolo.rb
|
require 'modulos/to_from_cadena'
class Simbolo
include ToFromCadena
attr_reader :simbolo, :codigo
def initialize
tofromcadena_setup :simbolo, :codigo
tofromcadena_modo :simple
end
end
|
META-1-Official/meta1-core
|
libraries/chain/asset_limitation_object.cpp
|
#include <graphene/chain/asset_limitation_object.hpp>
#include <fc/io/raw.hpp>
using namespace graphene::chain;
FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::asset_limitation_object, (graphene::db::object),
(limit_symbol)(issuer))
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION(graphene::chain::asset_limitation_object)
FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::asset_price, (graphene::db::object),
(symbol)(usd_price)(publication_time))
GRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION(graphene::chain::asset_price)
|
gcomte/zeus
|
backend/src/main/java/ch/puzzle/ln/zeus/service/processors/TweetOrderProcessor.java
|
package ch.puzzle.ln.zeus.service.processors;
import ch.puzzle.ln.zeus.config.ApplicationProperties;
import ch.puzzle.ln.zeus.service.InvoiceEvent;
import ch.puzzle.ln.zeus.service.TwitterService;
import ch.puzzle.ln.zeus.service.dto.InvoiceDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
@Service
public class TweetOrderProcessor implements ApplicationListener<InvoiceEvent> {
private static final Logger LOG = LoggerFactory.getLogger(TweetOrderProcessor.class);
private final ApplicationProperties properties;
private final TwitterService twitterService;
public TweetOrderProcessor(ApplicationProperties properties, TwitterService twitterService) {
this.properties = properties;
this.twitterService = twitterService;
}
@Override
public void onApplicationEvent(InvoiceEvent event) {
if (!properties.getTwitter().isProcessorEnabled()) {
LOG.info("Sending tweets is disabled by configuration.");
return;
}
InvoiceDTO invoice = event.getInvoice();
// Make sure we only send an e-mail if the invoice has been settled
// for the first time.
if (invoice.isSettled() && event.isFirstSettleEvent()) {
twitterService.sendTweet(invoice);
}
}
}
|
akrzemi1/Mach7
|
code/test/unit/type_switchN-decl.cpp
|
//
// Mach7: Pattern Matching Library for C++
//
// Copyright 2011-2013, Texas A&M University.
// Copyright 2014 <NAME>.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the names of Mach7 project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///
/// \file
///
/// This file is a part of Mach7 library test suite.
///
/// \author <NAME> <<EMAIL>>
///
/// \see https://parasol.tamu.edu/mach7/
/// \see https://github.com/solodon4/Mach7
/// \see https://github.com/solodon4/SELL
///
#include <iostream>
#include <utility>
#include "type_switchN-decl.hpp"
//------------------------------------------------------------------------------
typedef std::pair<double,double> loc;
//------------------------------------------------------------------------------
// An Algebraic Data Type implemented through inheritance
struct Shape
{
virtual ~Shape() {}
};
//------------------------------------------------------------------------------
struct Circle : Shape
{
Circle(const loc& c, const double& r) : center(c), radius(r) {}
const loc& get_center() const { return center; }
loc center;
double radius;
};
//------------------------------------------------------------------------------
struct Square : Shape
{
Square(const loc& c, const double& s) : upper_left(c), side(s) {}
loc upper_left;
double side;
};
//------------------------------------------------------------------------------
struct Triangle : Shape
{
Triangle(const loc& a, const loc& b, const loc& c) : first(a), second(b), third(c) {}
loc first;
loc second;
loc third;
};
//------------------------------------------------------------------------------
void do_match(const Shape* s0)
{
const char* text = "unknown";
Match(s0)
{
Case(const Circle& a) text = "C"; XTL_UNUSED(a); break;
Case(const Square& a) text = "S"; XTL_UNUSED(a); break;
Case(const Triangle& a) text = "T"; XTL_UNUSED(a); break;
Otherwise() text = "other"; break;
}
EndMatch
std::cout << text << std::endl;
}
//------------------------------------------------------------------------------
void do_match(const Shape* s0, const Shape* s1)
{
const char* text = "unknown";
Match(s0,s1)
{
//Case(const Circle& a, const Circle& b) text = "C,C"; XTL_UNUSED(a); XTL_UNUSED(b); break;
Case(const Circle& a, const Square& b) text = "C,S"; XTL_UNUSED(a); XTL_UNUSED(b); break;
Case(const Square& a, const Circle& b) text = "S,C"; XTL_UNUSED(a); XTL_UNUSED(b); break;
//Case(const Square& a, const Square& b) text = "S,S"; XTL_UNUSED(a); XTL_UNUSED(b); break;
Case(const Square& a, const Triangle& b) text = "S,T"; XTL_UNUSED(a); XTL_UNUSED(b); break;
Case(const Triangle& a, const Square& b) text = "T,S"; XTL_UNUSED(a); XTL_UNUSED(b); break;
Case(const Triangle& a, const Triangle& b) text = "T,T"; XTL_UNUSED(a); XTL_UNUSED(b); break;
Case(const Triangle& a, const Circle& b) text = "T,C"; XTL_UNUSED(a); XTL_UNUSED(b); break;
Case(const Circle& a, const Triangle& b) text = "C,T"; XTL_UNUSED(a); XTL_UNUSED(b); break;
Otherwise() text = "other"; break;
}
EndMatch
std::cout << text << std::endl;
}
//------------------------------------------------------------------------------
void do_match(Shape* s0, const Shape* s1, const Shape* s2)
{
const char* text = "unknown";
Match(s0,s1,s2)
{
Case(Circle& a, const Circle& b, const Circle& c) text = "C,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Circle& a, const Circle& b, const Square& c) text = "C,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Circle& a, const Square& b, const Circle& c) text = "C,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Circle& a, const Square& b, const Square& c) text = "C,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Circle& a, const Square& b, const Triangle& c) text = "C,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Circle& a, const Triangle& b, const Square& c) text = "C,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Circle& a, const Triangle& b, const Triangle& c) text = "C,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Circle& a, const Triangle& b, const Circle& c) text = "C,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Circle& a, const Circle& b, const Triangle& c) text = "C,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
//Case(Square& a, const Circle& b, const Circle& c) text = "S,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
//Case(Square& a, const Circle& b, const Square& c) text = "S,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Square& a, const Square& b, const Circle& c) text = "S,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Square& a, const Square& b, const Square& c) text = "S,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Square& a, const Square& b, const Triangle& c) text = "S,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Square& a, const Triangle& b, const Square& c) text = "S,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Square& a, const Triangle& b, const Triangle& c) text = "S,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Square& a, const Triangle& b, const Circle& c) text = "S,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
//Case(Square& a, const Circle& b, const Triangle& c) text = "S,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Triangle& a, const Circle& b, const Circle& c) text = "T,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Triangle& a, const Circle& b, const Square& c) text = "T,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Triangle& a, const Square& b, const Circle& c) text = "T,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Triangle& a, const Square& b, const Square& c) text = "T,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Triangle& a, const Square& b, const Triangle& c) text = "T,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Triangle& a, const Triangle& b, const Square& c) text = "T,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Triangle& a, const Triangle& b, const Triangle& c) text = "T,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Triangle& a, const Triangle& b, const Circle& c) text = "T,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Case(Triangle& a, const Circle& b, const Triangle& c) text = "T,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); break;
Otherwise() text = "other"; break;
}
EndMatch
std::cout << text << std::endl;
}
//------------------------------------------------------------------------------
void do_match(Shape* s0, Shape* s1, Shape* s2, Shape* s3)
{
const char* text = "unknown";
Match(s0,s1,s2,s3)
{
Case(Circle& a, const Circle& b, const Circle& c, const Circle& t) text = "C,C,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Circle& b, const Circle& c, const Square& t) text = "C,C,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Circle& b, const Square& c, const Circle& t) text = "C,C,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Circle& b, const Square& c, const Square& t) text = "C,C,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Circle& b, const Square& c, const Triangle& t) text = "C,C,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Circle& b, const Triangle& c, const Square& t) text = "C,C,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Circle& b, const Triangle& c, const Triangle& t) text = "C,C,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Circle& b, const Triangle& c, const Circle& t) text = "C,C,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Circle& b, const Circle& c, const Triangle& t) text = "C,C,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Square& b, const Circle& c, const Circle& t) text = "C,S,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Square& b, const Circle& c, const Square& t) text = "C,S,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Square& b, const Square& c, const Circle& t) text = "C,S,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Square& b, const Square& c, const Square& t) text = "C,S,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Square& b, const Square& c, const Triangle& t) text = "C,S,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Square& b, const Triangle& c, const Square& t) text = "C,S,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Square& b, const Triangle& c, const Triangle& t) text = "C,S,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Square& b, const Triangle& c, const Circle& t) text = "C,S,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Square& b, const Circle& c, const Triangle& t) text = "C,S,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Triangle& b, const Circle& c, const Circle& t) text = "C,T,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Triangle& b, const Circle& c, const Square& t) text = "C,T,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Triangle& b, const Square& c, const Circle& t) text = "C,T,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Triangle& b, const Square& c, const Square& t) text = "C,T,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Triangle& b, const Square& c, const Triangle& t) text = "C,T,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Triangle& b, const Triangle& c, const Square& t) text = "C,T,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Triangle& b, const Triangle& c, const Triangle& t) text = "C,T,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Triangle& b, const Triangle& c, const Circle& t) text = "C,T,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Circle& a, const Triangle& b, const Circle& c, const Triangle& t) text = "C,T,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Circle& b, const Circle& c, const Circle& t) text = "S,C,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Circle& b, const Circle& c, const Square& t) text = "S,C,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Circle& b, const Square& c, const Circle& t) text = "S,C,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Circle& b, const Square& c, const Square& t) text = "S,C,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Circle& b, const Square& c, const Triangle& t) text = "S,C,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Circle& b, const Triangle& c, const Square& t) text = "S,C,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Circle& b, const Triangle& c, const Triangle& t) text = "S,C,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Circle& b, const Triangle& c, const Circle& t) text = "S,C,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Circle& b, const Circle& c, const Triangle& t) text = "S,C,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Square& b, const Circle& c, const Circle& t) text = "S,S,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Square& b, const Circle& c, const Square& t) text = "S,S,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Square& b, const Square& c, const Circle& t) text = "S,S,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Square& b, const Square& c, const Square& t) text = "S,S,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Square& b, const Square& c, const Triangle& t) text = "S,S,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Square& b, const Triangle& c, const Square& t) text = "S,S,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Square& b, const Triangle& c, const Triangle& t) text = "S,S,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Square& b, const Triangle& c, const Circle& t) text = "S,S,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Square& b, const Circle& c, const Triangle& t) text = "S,S,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Triangle& b, const Circle& c, const Circle& t) text = "S,T,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Triangle& b, const Circle& c, const Square& t) text = "S,T,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Triangle& b, const Square& c, const Circle& t) text = "S,T,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Triangle& b, const Square& c, const Square& t) text = "S,T,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Triangle& b, const Square& c, const Triangle& t) text = "S,T,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Triangle& b, const Triangle& c, const Square& t) text = "S,T,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Triangle& b, const Triangle& c, const Triangle& t) text = "S,T,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Triangle& b, const Triangle& c, const Circle& t) text = "S,T,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Square& a, const Triangle& b, const Circle& c, const Triangle& t) text = "S,T,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Circle& b, const Circle& c, const Circle& t) text = "T,C,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Circle& b, const Circle& c, const Square& t) text = "T,C,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Circle& b, const Square& c, const Circle& t) text = "T,C,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Circle& b, const Square& c, const Square& t) text = "T,C,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Circle& b, const Square& c, const Triangle& t) text = "T,C,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Circle& b, const Triangle& c, const Square& t) text = "T,C,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Circle& b, const Triangle& c, const Triangle& t) text = "T,C,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Circle& b, const Triangle& c, const Circle& t) text = "T,C,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Circle& b, const Circle& c, const Triangle& t) text = "T,C,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Square& b, const Circle& c, const Circle& t) text = "T,S,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Square& b, const Circle& c, const Square& t) text = "T,S,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Square& b, const Square& c, const Circle& t) text = "T,S,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Square& b, const Square& c, const Square& t) text = "T,S,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Square& b, const Square& c, const Triangle& t) text = "T,S,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Square& b, const Triangle& c, const Square& t) text = "T,S,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Square& b, const Triangle& c, const Triangle& t) text = "T,S,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Square& b, const Triangle& c, const Circle& t) text = "T,S,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Square& b, const Circle& c, const Triangle& t) text = "T,S,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Triangle& b, const Circle& c, const Circle& t) text = "T,T,C,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Triangle& b, const Circle& c, const Square& t) text = "T,T,C,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Triangle& b, const Square& c, const Circle& t) text = "T,T,S,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Triangle& b, const Square& c, const Square& t) text = "T,T,S,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Triangle& b, const Square& c, const Triangle& t) text = "T,T,S,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Triangle& b, const Triangle& c, const Square& t) text = "T,T,T,S"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Triangle& b, const Triangle& c, const Triangle& t) text = "T,T,T,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Triangle& b, const Triangle& c, const Circle& t) text = "T,T,T,C"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Case(Triangle& a, const Triangle& b, const Circle& c, const Triangle& t) text = "T,T,C,T"; XTL_UNUSED(a); XTL_UNUSED(b); XTL_UNUSED(c); XTL_UNUSED(t); break;
Otherwise() text = "other"; break;
}
EndMatch
std::cout << text << std::endl;
}
//------------------------------------------------------------------------------
int main()
{
Shape* c = new Circle(loc(1,1),7);
Shape* s = new Square(loc(1,1),2);
Shape* t = new Triangle(loc(1,1),loc(1,0),loc(0,0));
Shape* shapes[] = {c,s,t};
for (size_t n = 0; n < 3; n++)
{
// 1 argument
for (size_t i = 0; i < 3; ++i)
do_match(shapes[i]);
// 2 arguments
for (size_t i = 0; i < 3; ++i)
for (size_t j = 0; j < 3; ++j)
do_match(shapes[i], shapes[j]);
// 3 arguments
for (size_t i = 0; i < 3; ++i)
for (size_t j = 0; j < 3; ++j)
for (size_t k = 0; k < 3; ++k)
do_match(shapes[i], shapes[j], shapes[k]);
// 4 arguments
for (size_t i = 0; i < 3; ++i)
for (size_t j = 0; j < 3; ++j)
for (size_t k = 0; k < 3; ++k)
for (size_t l = 0; l < 3; ++l)
do_match(shapes[i], shapes[j], shapes[k], shapes[l]);
}
}
//------------------------------------------------------------------------------
|
wedataintelligence/vivaldi-source
|
chromium/content/common/gpu/gpu_stream_priority.h
|
<filename>chromium/content/common/gpu/gpu_stream_priority.h
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_COMMON_GPU_GPU_STREAM_PRIORITY_H_
#define CONTENT_COMMON_GPU_GPU_STREAM_PRIORITY_H_
namespace content {
enum class GpuStreamPriority {
REAL_TIME,
NORMAL,
LOW,
INHERIT,
LAST = INHERIT
};
} // namespace content
#endif // CONTENT_COMMON_GPU_GPU_STREAM_PRIORITY_H_
|
yssk22/go
|
number/float.go
|
<filename>number/float.go
package number
import "strconv"
// ParseFloat32Or parse string and return float64 value. The invalid string returns `or` value.
func ParseFloat32Or(s string, or float32) float32 {
f, err := strconv.ParseFloat(s, 32)
if err != nil {
return or
}
return float32(f)
}
// MustParseFloat32 parse string and return float64 value. it panics if an invalid string is passed.
func MustParseFloat32(s string) float32 {
f, err := strconv.ParseFloat(s, 32)
if err != nil {
panic(err)
}
return float32(f)
}
// ParseFloat64Or parse string and return float64 value. The invalid string returns `or` value.
func ParseFloat64Or(s string, or float64) float64 {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return or
}
return f
}
// MustParseFloat64 parse string and return float64 value. it panics if an invalid string is passed.
func MustParseFloat64(s string) float64 {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
panic(err)
}
return f
}
|
jiandequn/code
|
log_chart_manager/src/main/java/com/ppfuns/report/utils/QuartzTaskUtils.java
|
<filename>log_chart_manager/src/main/java/com/ppfuns/report/utils/QuartzTaskUtils.java
package com.ppfuns.report.utils;
import com.ppfuns.report.entity.base.PpfunsEntity;
import com.ppfuns.report.service.AppCountDayService;
import com.ppfuns.report.service.IAppAreaVisitCountDayService;
import com.ppfuns.report.service.INoappAreaVisitCountDayService;
import com.ppfuns.report.service.NoappCountDayService;
import com.ppfuns.report.service.impl.QuartzJob;
import com.ppfuns.util.PpfunsConfigBean;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.text.ParseException;
@Component
public class QuartzTaskUtils {
@Autowired
AppCountDayService appCountDayService;
@Autowired
NoappCountDayService noappCountDayService;
@Autowired
private IAppAreaVisitCountDayService iAppAreaVisitCountDayService;
@Autowired
private INoappAreaVisitCountDayService iNoappAreaVisitCountDayService;
@PostConstruct
public void countDayJobTask() throws ParseException, SchedulerException {
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.putIfAbsent("appCountDayService",appCountDayService);
jobDataMap.putIfAbsent("noappCountDayService",noappCountDayService);
jobDataMap.putIfAbsent("iAppAreaVisitCountDayService",iAppAreaVisitCountDayService);
jobDataMap.putIfAbsent("iNoappAreaVisitCountDayService",iNoappAreaVisitCountDayService);
JobDetail job = new JobDetail();
job.setName("count_day_job");
job.setJobClass(QuartzJob.class);
job.setJobDataMap(jobDataMap);
CronTrigger trigger = new CronTrigger();
trigger.setName("count_day_trigger");
trigger.setCronExpression("0 0 7 * * ?");
// trigger.setCronExpression("30 38 11 * * ?");
//schedule it
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}
|
Simplix-Softworks/Cirrus
|
cirrus-api/cirrus-api-common/src/main/java/dev/simplix/cirrus/api/business/InventoryItemWrapper.java
|
<reponame>Simplix-Softworks/Cirrus
package dev.simplix.cirrus.api.business;
import dev.simplix.protocolize.data.ItemType;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.md_5.bungee.api.chat.BaseComponent;
import net.querz.nbt.tag.CompoundTag;
import java.util.List;
@Accessors(fluent = true)
@Builder
public class InventoryItemWrapper implements ItemStackWrapper {
private final ItemStackWrapper handle;
@Getter
@Setter
private String actionHandler;
@Getter
@Setter
private List<String> actionArguments;
@Override
public String displayName() {
return handle.displayName();
}
@Override
public BaseComponent[] displayNameComponents() {
return handle.displayNameComponents();
}
@Override
public List<String> lore() {
return handle.lore();
}
@Override
public List<BaseComponent[]> loreComponents() {
return handle.loreComponents();
}
@Override
public ItemType type() {
return handle.type();
}
@Override
public CompoundTag nbt() {
return handle.nbt();
}
@Override
public int amount() {
return handle.amount();
}
@Override
public short durability() {
return handle.durability();
}
@Override
public void type(@NonNull ItemType type) {
handle.type(type);
}
@Override
public void displayName(@NonNull String displayName) {
handle.displayName(displayName);
}
@Override
public void displayNameComponents(@NonNull BaseComponent... baseComponents) {
handle.displayNameComponents(baseComponents);
}
@Override
public void lore(@NonNull List<String> lore) {
handle.lore(lore);
}
@Override
public void loreComponents(@NonNull List<BaseComponent[]> lore) {
handle.loreComponents(lore);
}
@Override
public void nbt(@NonNull CompoundTag tag) {
handle.nbt(tag);
}
@Override
public void amount(int amount) {
handle.amount(amount);
}
@Override
public void durability(short durability) {
handle.durability(durability);
}
@Override
public <T> T handle() {
return handle.handle();
}
public ItemStackWrapper wrapper() {
return handle;
}
@Override
public String toString() {
return "InventoryItemWrapper{" +
"handle=" + handle +
", actionHandler='" + actionHandler + '\'' +
", actionArguments=" + actionArguments +
'}';
}
}
|
r1sc/gam
|
actor/props.go
|
<filename>actor/props.go
package actor
//Props or properties of an actor, it defines how the actor should be created
type Props struct {
actorProducer Producer
mailboxProducer MailboxProducer
supervisionStrategy SupervisionStrategy
routerConfig RouterConfig
receivePluins []Receive
dispatcher Dispatcher
}
func (props Props) Dispatcher() Dispatcher {
if props.dispatcher == nil {
return defaultDispatcher
}
return props.dispatcher
}
func (props Props) RouterConfig() RouterConfig {
return props.routerConfig
}
func (props Props) ProduceActor() Actor {
return props.actorProducer()
}
func (props Props) Supervisor() SupervisionStrategy {
if props.supervisionStrategy == nil {
return DefaultSupervisionStrategy()
}
return props.supervisionStrategy
}
func (props Props) ProduceMailbox() Mailbox {
if props.mailboxProducer == nil {
return NewUnboundedMailbox()()
}
return props.mailboxProducer()
}
func (props Props) WithReceivers(plugin ...Receive) Props {
//pass by value, we only modify the copy
props.receivePluins = append(props.receivePluins, plugin...)
return props
}
func (props Props) WithMailbox(mailbox MailboxProducer) Props {
//pass by value, we only modify the copy
props.mailboxProducer = mailbox
return props
}
func (props Props) WithSupervisor(supervisor SupervisionStrategy) Props {
//pass by value, we only modify the copy
props.supervisionStrategy = supervisor
return props
}
func (props Props) WithPoolRouter(routerConfig PoolRouterConfig) Props {
//pass by value, we only modify the copy
props.routerConfig = routerConfig
return props
}
func (props Props) WithDispatcher(dispatcher Dispatcher) Props {
//pass by value, we only modify the copy
props.dispatcher = dispatcher
return props
}
func FromProducer(actorProducer Producer) Props {
return Props{
actorProducer: actorProducer,
mailboxProducer: nil,
routerConfig: nil,
}
}
func FromFunc(receive Receive) Props {
a := &emptyActor{
receive: receive,
}
p := FromProducer(func() Actor {
return a
})
return p
}
func FromInstance(template Actor) Props {
producer := func() Actor {
return template
}
p := FromProducer(producer)
return p
}
func FromGroupRouter(router GroupRouterConfig) Props {
return Props{
routerConfig: router,
actorProducer: nil,
}
}
|
maoxing2012/bdf3
|
bdf3-parent/bdf3-autoconfigure/src/main/java/com/bstek/bdf3/autoconfigure/jdbc/DataSources.java
|
package com.bstek.bdf3.autoconfigure.jdbc;
/**
* @author <NAME> (mailto:<EMAIL>)
* @since 2016年8月11日
*/
public abstract class DataSources {
public static final String dataSource = "dataSource";
public static final String dataSource1 = "dataSource1";
public static final String dataSource2 = "dataSource2";
public static final String dataSource3 = "dataSource3";
public static final String dataSource4 = "dataSource4";
public static final String dataSource5 = "dataSource5";
public static final String dataSource6 = "dataSource6";
}
|
morningdew830/generator-fountain-angular2
|
generators/component/templates/src/app/component.spec.js
|
<filename>generators/component/templates/src/app/component.spec.js
var <%- className %> = require('./<%- name %>');
var ngTest = require('@angular/core/testing');
describe('<%- componentName %> component', function () {
beforeEach(ngTest.async(function () {
ngTest.TestBed.configureTestingModule({declarations: [<%- componentName %>]});
ngTest.TestBed.compileComponents();
}));
it('should render...', function () {
const fixture = ngTest.TestBed.createComponent(<%- componentName %>);
fixture.detectChanges();
});
});
|
zgg-lang/zgg-go
|
stdgolibs/gen_crypto__x509__pkix_darwin_amd64.go
|
package stdgolibs
import (
pkg "crypto/x509/pkix"
"reflect"
)
func init() {
registerValues("crypto/x509/pkix", map[string]reflect.Value{
// Functions
// Consts
// Variables
})
registerTypes("crypto/x509/pkix", map[string]reflect.Type{
// Non interfaces
"AlgorithmIdentifier": reflect.TypeOf((*pkg.AlgorithmIdentifier)(nil)).Elem(),
"RDNSequence": reflect.TypeOf((*pkg.RDNSequence)(nil)).Elem(),
"RelativeDistinguishedNameSET": reflect.TypeOf((*pkg.RelativeDistinguishedNameSET)(nil)).Elem(),
"AttributeTypeAndValue": reflect.TypeOf((*pkg.AttributeTypeAndValue)(nil)).Elem(),
"AttributeTypeAndValueSET": reflect.TypeOf((*pkg.AttributeTypeAndValueSET)(nil)).Elem(),
"Extension": reflect.TypeOf((*pkg.Extension)(nil)).Elem(),
"Name": reflect.TypeOf((*pkg.Name)(nil)).Elem(),
"CertificateList": reflect.TypeOf((*pkg.CertificateList)(nil)).Elem(),
"TBSCertificateList": reflect.TypeOf((*pkg.TBSCertificateList)(nil)).Elem(),
"RevokedCertificate": reflect.TypeOf((*pkg.RevokedCertificate)(nil)).Elem(),
})
}
|
md678685/Denizen
|
plugin/src/main/java/com/denizenscript/denizen/objects/properties/item/ItemSkullskin.java
|
package com.denizenscript.denizen.objects.properties.item;
import com.denizenscript.denizen.nms.NMSHandler;
import com.denizenscript.denizen.nms.NMSVersion;
import com.denizenscript.denizen.nms.util.PlayerProfile;
import com.denizenscript.denizen.objects.ItemTag;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.Mechanism;
import com.denizenscript.denizencore.objects.core.ListTag;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.properties.Property;
import com.denizenscript.denizencore.tags.Attribute;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.UUID;
public class ItemSkullskin implements Property {
public static boolean describes(ObjectTag item) {
return item instanceof ItemTag
&& ((ItemTag) item).getItemStack().getItemMeta() instanceof SkullMeta;
}
public static ItemSkullskin getFrom(ObjectTag _item) {
if (!describes(_item)) {
return null;
}
else {
return new ItemSkullskin((ItemTag) _item);
}
}
public static final String[] handledTags = new String[] {
"skin", "has_skin"
};
public static final String[] handledMechs = new String[] {
"skull_skin"
};
private ItemSkullskin(ItemTag _item) {
item = _item;
}
ItemTag item;
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) {
return null;
}
// <--[tag]
// @attribute <ItemTag.skin>
// @returns ElementTag
// @mechanism ItemTag.skull_skin
// @group properties
// @description
// Returns the UUID of the player whose skin a skull item uses.
// Note: Item must be a 'skull_item' with a skin.
// -->
// <--[tag]
// @attribute <ItemTag.skin.full>
// @returns ElementTag|Element
// @mechanism ItemTag.skull_skin
// @group properties
// @description
// Returns the UUID of the player whose skin a skull item uses, along
// with the permanently cached texture property.
// Note: Item must be a 'skull_item' with a skin.
// -->
if (attribute.startsWith("skin")) {
String skin = getPropertyString();
if (skin != null) {
attribute = attribute.fulfill(1);
if (attribute.startsWith("full")) {
return new ElementTag(skin).getAttribute(attribute.fulfill(1));
}
return new ElementTag(CoreUtilities.split(skin, '|').get(0)).getAttribute(attribute);
}
else {
Debug.echoError("This skull item does not have a skin set!");
}
}
// <--[tag]
// @attribute <ItemTag.has_skin>
// @returns ElementTag(Boolean)
// @mechanism ItemTag.skull_skin
// @group properties
// @description
// Returns whether the item has a custom skin set.
// (Only for human 'skull_item's)
// -->
if (attribute.startsWith("has_skin")) {
return new ElementTag(getPropertyString() != null)
.getAttribute(attribute.fulfill(1));
}
return null;
}
public boolean isCorrectDurability() {
return NMSHandler.getVersion().isAtLeast(NMSVersion.v1_13) || item.getItemStack().getDurability() == 3;
}
@Override
public String getPropertyString() {
if (isCorrectDurability()) {
PlayerProfile playerProfile = NMSHandler.getItemHelper().getSkullSkin(item.getItemStack());
if (playerProfile != null) {
String name = playerProfile.getName();
UUID uuid = playerProfile.getUniqueId();
return (uuid != null ? uuid : name)
+ (playerProfile.hasTexture() ? "|" + playerProfile.getTexture() +
(uuid != null && name != null ? "|" + name : "") : "");
}
}
return null;
}
@Override
public String getPropertyId() {
return "skull_skin";
}
@Override
public void adjust(Mechanism mechanism) {
// <--[mechanism]
// @object ItemTag
// @name skull_skin
// @input Element(|Element(|Element))
// @description
// Sets the player skin on a skull_item.
// The first ElementTag is a UUID.
// Optionally, use the second ElementTag for the skin texture cache.
// Optionally, use the third ElementTag for a player name.
// @tags
// <ItemTag.skin>
// <ItemTag.skin.full>
// <ItemTag.has_skin>
// -->
if (mechanism.matches("skull_skin")) {
if (!isCorrectDurability()) {
item.getItemStack().setDurability((short) 3);
}
ListTag list = mechanism.valueAsType(ListTag.class);
String idString = list.get(0);
String texture = null;
if (list.size() > 1) {
texture = list.get(1);
}
PlayerProfile profile;
if (idString.contains("-")) {
UUID uuid = UUID.fromString(idString);
String name = null;
if (list.size() > 2) {
name = list.get(2);
}
profile = new PlayerProfile(name, uuid, texture);
}
else {
profile = new PlayerProfile(idString, null, texture);
}
profile = NMSHandler.getInstance().fillPlayerProfile(profile);
if (texture != null) { // Ensure we didn't get overwritten
profile.setTexture(texture);
}
item.setItemStack(NMSHandler.getItemHelper().setSkullSkin(item.getItemStack(), profile));
}
}
}
|
zonys/zonys
|
zonys/core/zfs/property.py
|
import zonys
import zonys.core
import zonys.core.zfs
ENABLED_VALUE = "on"
DISABLED_VALUE = "off"
class Error(RuntimeError):
pass
class InvalidValueError(Error):
def __init__(self, value, handle):
super().__init__(
"Value {} is not valid for property {}".format(
value,
handle.name,
)
)
class Handle(zonys.core.zfs.Handle):
def __init__(self, descriptor):
super().__init__(descriptor)
@property
def name(self):
return self._descriptor.name
@property
def value(self):
return self._descriptor.value
@property
def allowed_values(self):
return self._descriptor.allowed_values
@value.setter
def value(self, value):
if value not in self.allowed_values:
raise InvalidValueError(value, self)
self._descriptor.value = value
def is_enabled(self):
return self._descriptor.value == ENABLED_VALUE
def is_disabled(self):
return self._descriptor.value == DISABLED_VALUE
def enable(self):
self.value = ENABLED_VALUE
def disable(self):
self.value = DISABLED_VALUE
def is_on(self):
return self.is_enabled()
def is_off(self):
return self.is_off()
def on(self):
return self.enable()
def off(self):
return self.disable()
def inherit(self):
self._descriptor.inherit()
|
lsm1/incubator-kyuubi
|
kyuubi-common/src/main/scala/org/apache/kyuubi/util/SignalRegister.scala
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.
*/
package org.apache.kyuubi.util
import java.util.Collections
import scala.collection.JavaConverters._
import org.apache.commons.lang3.SystemUtils
import org.slf4j.Logger
import sun.misc.{Signal, SignalHandler}
import org.apache.kyuubi.Logging
object SignalRegister extends Logging {
private val handlers = new scala.collection.mutable.HashMap[String, ActionHandler]
def registerLogger(log: Logger): Unit = {
Seq("TERM", "HUP", "INT").foreach { sig =>
if (SystemUtils.IS_OS_UNIX) {
val signal = new Signal(sig)
try {
val handler = handlers.getOrElseUpdate(
sig, {
info(s"Registering signal handler for $sig")
ActionHandler(signal)
})
handler.register({
log.error(s"RECEIVED SIGNAL ${signal.getNumber}: " + sig)
false
})
} catch {
case ex: Exception => warn(s"Failed to register signal handler for $sig", ex)
}
}
}
}
case class ActionHandler(signal: Signal) extends SignalHandler {
private val actions = Collections.synchronizedList(new java.util.LinkedList[() => Boolean])
private val prevHandler: SignalHandler = Signal.handle(signal, this)
override def handle(sig: Signal): Unit = {
Signal.handle(signal, prevHandler)
val escalate = !actions.asScala.forall(action => action())
if (escalate) {
prevHandler.handle(sig)
}
Signal.handle(signal, this)
}
def register(action: => Boolean): Unit = actions.add(() => action)
}
}
|
UCLA-SEAL/RefFinder
|
Ref-Finder/code/tyRuBa/modes/CompositeType.java
|
/*
* Ref-Finder
* Copyright (C) <2015> <PLSE_UCLA>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tyRuBa.modes;
import java.util.HashMap;
import java.util.Map;
public class CompositeType
extends BoundaryType
{
private TypeConstructor typeConst = null;
boolean strict = false;
private TupleType args;
public CompositeType(TypeConstructor typeConst, boolean strict, TupleType args)
{
this.typeConst = typeConst;
this.strict = strict;
this.args = args;
}
public TypeConstructor getTypeConstructor()
{
return this.typeConst;
}
public int hashCode()
{
return getTypeConstructor().hashCode() + 13 * this.args.hashCode();
}
public void checkEqualTypes(Type other, boolean grow)
throws TypeModeError
{
if (((other instanceof TVar)) || ((other instanceof GrowableType)))
{
other.checkEqualTypes(this, grow);
}
else
{
check(other instanceof CompositeType, this, other);
CompositeType cother = (CompositeType)other;
check(getTypeConstructor().equals(cother.getTypeConstructor()), this, other);
try
{
this.args.checkEqualTypes(cother.args, grow);
}
catch (TypeModeError e)
{
throw new TypeModeError(e, this);
}
boolean newStrict = (this.strict) || (cother.strict);
cother.strict = newStrict;
this.strict = newStrict;
}
}
public boolean isSubTypeOf(Type other, Map renamings)
{
if ((other instanceof TVar)) {
other = ((TVar)other).getContents();
}
if (other == null) {
return false;
}
if (!(other instanceof CompositeType)) {
return false;
}
CompositeType declared = (CompositeType)other;
TypeConstructor declaredTypeConst = declared.getTypeConstructor();
if (isStrict()) {
return (this.typeConst.equals(declaredTypeConst)) && (declared.isStrict()) && (this.args.isSubTypeOf(declared.args, renamings));
}
if (this.typeConst.equals(declaredTypeConst)) {
return this.args.isSubTypeOf(declared.args, renamings);
}
if (declaredTypeConst.isSuperTypeOf(this.typeConst))
{
Map params = new HashMap();
for (int i = 0; i < this.typeConst.getTypeArity(); i++)
{
String currName = this.typeConst.getParameterName(i);
params.put(currName, this.args.getParamType(i, this.typeConst));
}
for (int i = 0; i < declaredTypeConst.getTypeArity(); i++)
{
String currName = declaredTypeConst.getParameterName(i);
Type paramType = (Type)params.get(currName);
if (paramType != null)
{
Type declaredType = declared.args.getParamType(i, declaredTypeConst);
if (declaredType == null) {
return false;
}
if (!paramType.isSubTypeOf(declaredType, renamings)) {
return false;
}
}
}
return true;
}
return false;
}
public boolean equals(Object other)
{
if (!(other instanceof CompositeType)) {
return false;
}
CompositeType cother = (CompositeType)other;
return (getTypeConstructor().equals(cother.getTypeConstructor())) && (isStrict() == cother.isStrict()) && (this.args.equals(cother.args));
}
public String toString()
{
String constName = this.typeConst.getName() + this.args;
if (isStrict()) {
return "=" + constName;
}
return constName;
}
public boolean isFreeFor(TVar var)
{
return this.args.isFreeFor(var);
}
public Type clone(Map tfact)
{
return new CompositeType(this.typeConst, this.strict, (TupleType)this.args.clone(tfact));
}
public String getName()
{
return getTypeConstructor().getName();
}
public TupleType getArgs()
{
return this.args;
}
public Type union(Type other)
throws TypeModeError
{
if (((other instanceof TVar)) || ((other instanceof GrowableType))) {
return other.union(this);
}
check(other instanceof CompositeType, this, other);
CompositeType cother = (CompositeType)other;
TypeConstructor otherTypeConst = cother.typeConst;
if (equals(other)) {
return this;
}
if (this.typeConst.equals(otherTypeConst))
{
TupleType resultArg = (TupleType)this.args.union(cother.args);
if ((this.strict) || (cother.strict)) {
return this.typeConst.applyStrict(resultArg, false);
}
return this.typeConst.apply(resultArg, false);
}
if (otherTypeConst.isSuperTypeOf(this.typeConst))
{
check(!isStrict(), this, other);
Map params = new HashMap();
for (int i = 0; i < this.typeConst.getTypeArity(); i++) {
params.put(this.typeConst.getParameterName(i), this.args.get(i));
}
TupleType resultArg = Factory.makeTupleType();
for (int i = 0; i < cother.typeConst.getTypeArity(); i++)
{
String currName = cother.typeConst.getParameterName(i);
Type paramValue = (Type)params.get(currName);
if (paramValue != null) {
resultArg.add(paramValue.union(cother.args.get(i)));
} else {
resultArg.add(cother.args.get(i));
}
}
if (cother.strict) {
return otherTypeConst.applyStrict(resultArg, false);
}
return otherTypeConst.apply(resultArg, false);
}
if (this.typeConst.isSuperTypeOf(otherTypeConst)) {
return cother.intersect(this);
}
check(!isStrict(), this, other);
check(!cother.isStrict(), this, other);
TypeConstructor superTypeConst = this.typeConst.lowerBound(otherTypeConst);
Map params = new HashMap();
for (int i = 0; i < this.typeConst.getTypeArity(); i++) {
params.put(this.typeConst.getParameterName(i), this.args.get(i));
}
for (int i = 0; i < otherTypeConst.getTypeArity(); i++)
{
String currName = otherTypeConst.getParameterName(i);
Type paramValue = (Type)params.get(currName);
if (paramValue == null) {
params.put(currName, cother.args.get(i));
} else {
params.put(currName, paramValue.union(cother.args.get(i)));
}
}
TupleType resultArg = Factory.makeTupleType();
for (int i = 0; i < superTypeConst.getTypeArity(); i++)
{
String currName = superTypeConst.getParameterName(i);
resultArg.add((Type)params.get(currName));
}
return superTypeConst.apply(resultArg, false);
}
public Type intersect(Type other)
throws TypeModeError
{
if (((other instanceof TVar)) || ((other instanceof GrowableType))) {
return other.intersect(this);
}
check(other instanceof CompositeType, this, other);
CompositeType cother = (CompositeType)other;
TypeConstructor otherTypeConst = cother.typeConst;
if (equals(other)) {
return this;
}
if (this.typeConst.equals(otherTypeConst))
{
TupleType resultArg = (TupleType)this.args.intersect(cother.args);
if ((this.strict) || (cother.strict)) {
return this.typeConst.applyStrict(resultArg, false);
}
return this.typeConst.apply(resultArg, false);
}
if (this.typeConst.isSuperTypeOf(otherTypeConst))
{
check(!cother.isStrict(), this, other);
Map params = new HashMap();
for (int i = 0; i < this.typeConst.getTypeArity(); i++) {
params.put(this.typeConst.getParameterName(i), this.args.get(i));
}
TupleType resultArg = Factory.makeTupleType();
for (int i = 0; i < cother.typeConst.getTypeArity(); i++)
{
String currName = cother.typeConst.getParameterName(i);
Type paramValue = (Type)params.get(currName);
check(paramValue != null, this, other);
resultArg.add(paramValue.intersect(cother.args.get(i)));
}
return cother.typeConst.apply(resultArg, false);
}
if (otherTypeConst.isSuperTypeOf(this.typeConst)) {
return cother.intersect(this);
}
throw new TypeModeError("Incompatible types: " + this + ", " + other);
}
public boolean hasOverlapWith(Type other)
{
if (((other instanceof TVar)) || ((other instanceof GrowableType))) {
return other.hasOverlapWith(this);
}
if (!(other instanceof CompositeType)) {
return false;
}
CompositeType cother = (CompositeType)other;
TypeConstructor otherTypeConst = cother.getTypeConstructor();
if (this.typeConst.equals(otherTypeConst)) {
return this.args.hasOverlapWith(cother.args);
}
if (this.typeConst.isSuperTypeOf(otherTypeConst))
{
Map params = new HashMap();
for (int i = 0; i < this.typeConst.getTypeArity(); i++) {
params.put(this.typeConst.getParameterName(i), this.args.get(i));
}
for (int i = 0; i < otherTypeConst.getTypeArity(); i++)
{
Type paramValue = (Type)params.get(otherTypeConst.getParameterName(i));
if ((paramValue != null) &&
(cother.args.get(i).hasOverlapWith(paramValue))) {
return true;
}
}
return false;
}
if (otherTypeConst.isSuperTypeOf(this.typeConst)) {
return other.hasOverlapWith(this);
}
return false;
}
boolean isStrict()
{
return this.strict;
}
public Type copyStrictPart()
{
if (isStrict()) {
return this.typeConst.applyStrict((TupleType)this.args.copyStrictPart(), false);
}
TypeConstructor resultTypeConst =
this.typeConst.getSuperestTypeConstructor();
Map params = new HashMap();
for (int i = 0; i < this.typeConst.getTypeArity(); i++) {
params.put(this.typeConst.getParameterName(i), this.args.get(i).copyStrictPart());
}
TupleType resultArg = Factory.makeTupleType();
for (int i = 0; i < resultTypeConst.getTypeArity(); i++)
{
String currName = resultTypeConst.getParameterName(i);
Type paramType = (Type)params.get(currName);
if (paramType == null) {
resultArg.add(Factory.makeTVar(currName));
} else {
resultArg.add(paramType);
}
}
return resultTypeConst.apply(resultArg, false);
}
public void makeStrict()
{
this.strict = true;
}
public void addSubType(Type subType)
throws TypeModeError
{
if (!(subType instanceof CompositeType)) {
throw new TypeModeError(subType + " is an illegal subtype for " + this);
}
this.typeConst.addSubTypeConst(((CompositeType)subType).getTypeConstructor());
}
public void setRepresentationType(Type repBy)
{
this.typeConst.setRepresentationType(repBy);
}
public Type getParamType(String currName, Type repAs)
{
if ((repAs instanceof TVar))
{
if (currName.equals(((TVar)repAs).getName())) {
return this;
}
return null;
}
if (!(repAs instanceof CompositeType)) {
return null;
}
CompositeType compositeRepAs = (CompositeType)repAs;
if (compositeRepAs.getTypeConstructor().equals(this.typeConst)) {
return this.args.getParamType(currName, compositeRepAs.args);
}
return null;
}
public Class javaEquivalent()
throws TypeModeError
{
return this.typeConst.javaEquivalent();
}
public boolean isJavaType()
{
return getTypeConstructor().isJavaTypeConstructor();
}
}
|
soker90/carpinteria-erp-api
|
api/services/log.service.js
|
class LogService {
constructor(type) {
this.type = type;
}
logInfo(...message) {
console.log(`${this.type} - ${message}`);
}
}
module.exports = LogService;
|
Unicon/cas-mfa
|
cas-mfa-java/src/test/java/net/unicon/cas/mfa/web/support/DefaultMultiFactorAuthenticationSupportingWebApplicationServiceTests.java
|
package net.unicon.cas.mfa.web.support;
import static org.junit.Assert.*;
import org.jasig.cas.authentication.principal.Response;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class DefaultMultiFactorAuthenticationSupportingWebApplicationServiceTests {
/**
* Test that an instance of {@link DefaultMultiFactorAuthenticationSupportingWebApplicationService}
* properly implements getAuthenticationMethod() and ability to get a Response to direct the user to redirect to
* the service with a ticket.
*/
@Test
public void testServiceness() {
final DefaultMultiFactorAuthenticationSupportingWebApplicationService svc =
new DefaultMultiFactorAuthenticationSupportingWebApplicationService("https://www.github.com",
"https://www.github.com", null, Response.ResponseType.REDIRECT,
"test_authn_method");
assertEquals(svc.getAuthenticationMethod(), "test_authn_method");
final Response res = svc.getResponse("testTicketId");
assertNotNull(res);
assertEquals(res.getResponseType(), Response.ResponseType.REDIRECT);
assertEquals(res.getUrl(), "https://www.github.com?ticket=testTicketId");
}
}
|
cypherdotXd/o3de
|
Gems/CrashReporting/Code/Platform/Common/UnixLike/GameCrashUploader_UnixLike.cpp
|
<gh_stars>10-100
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <CrashReporting/GameCrashUploader.h>
#include <CrashSupport.h>
namespace Lumberyard
{
bool GameCrashUploader::CheckConfirmation(const crashpad::CrashReportDatabase::Report& report)
{
return true;
}
}
|
skkuse-adv/2019Fall_team2
|
analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/com/google/android/gms/internal/firebase_remote_config/zzjx.java
|
<gh_stars>1-10
package com.google.android.gms.internal.firebase_remote_config;
import java.io.IOException;
abstract class zzjx<T, B> {
zzjx() {
}
/* access modifiers changed from: 0000 */
public abstract void zza(B b, int i, long j);
/* access modifiers changed from: 0000 */
public abstract void zza(B b, int i, zzfx zzfx);
/* access modifiers changed from: 0000 */
public abstract void zza(B b, int i, T t);
/* access modifiers changed from: 0000 */
public abstract void zza(T t, zzku zzku) throws IOException;
/* access modifiers changed from: 0000 */
public abstract boolean zza(zzjg zzjg);
/* access modifiers changed from: 0000 */
public abstract T zzaa(Object obj);
/* access modifiers changed from: 0000 */
public abstract B zzab(Object obj);
/* access modifiers changed from: 0000 */
public abstract int zzac(T t);
/* access modifiers changed from: 0000 */
public abstract void zzb(B b, int i, long j);
/* access modifiers changed from: 0000 */
public abstract void zzc(B b, int i, int i2);
/* access modifiers changed from: 0000 */
public abstract void zzc(T t, zzku zzku) throws IOException;
/* access modifiers changed from: 0000 */
public abstract void zzg(Object obj, T t);
/* access modifiers changed from: 0000 */
public abstract void zzh(Object obj, B b);
/* access modifiers changed from: 0000 */
public abstract T zzi(T t, T t2);
/* access modifiers changed from: 0000 */
public abstract B zziz();
/* access modifiers changed from: 0000 */
public abstract void zzm(Object obj);
/* access modifiers changed from: 0000 */
public abstract T zzs(B b);
/* access modifiers changed from: 0000 */
public abstract int zzw(T t);
/* access modifiers changed from: 0000 */
public final boolean zza(B b, zzjg zzjg) throws IOException {
int tag = zzjg.getTag();
int i = tag >>> 3;
int i2 = tag & 7;
if (i2 == 0) {
zza(b, i, zzjg.zzfd());
return true;
} else if (i2 == 1) {
zzb(b, i, zzjg.zzff());
return true;
} else if (i2 == 2) {
zza(b, i, zzjg.zzfj());
return true;
} else if (i2 == 3) {
Object zziz = zziz();
int i3 = 4 | (i << 3);
while (zzjg.zzfz() != Integer.MAX_VALUE) {
if (!zza((B) zziz, zzjg)) {
break;
}
}
if (i3 == zzjg.getTag()) {
zza(b, i, (T) zzs(zziz));
return true;
}
throw zzhq.zzhi();
} else if (i2 == 4) {
return false;
} else {
if (i2 == 5) {
zzc(b, i, zzjg.zzfg());
return true;
}
throw zzhq.zzhj();
}
}
}
|
antuniooh/ExercisesFEI
|
Desenvolvimento de Algoritmos/Aula 18/main1.c
|
<filename>Desenvolvimento de Algoritmos/Aula 18/main1.c<gh_stars>1-10
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <locale.h>
struct Disciplina{
char nomeDisc[40];
char nomeProf[40];
};
struct Aluno{
char nome[40];
char RA[20];
float N1;
float N2;
struct Disciplina* disc;
};
float calcMedia(struct Aluno a){
return a.N1*0.4 + a.N2*0.6;
}
float notaNecessaria(struct Aluno a){
float N3_N2 = (5.0 -0.4*a.N1)/0.6;
float N3_N1 = (5.0 -0.6*a.N2)/0.4;
if(N3_N1 < N3_N2)
return N3_N1;
else
return N3_N2;
}
void imprimeDisciplina(struct Disciplina d){
puts("Disciplina");
printf("Nome: %s\n", d.nomeDisc);
printf("Nome Prof: %s\n", d.nomeProf);
}
void imprimeAluno(struct Aluno a){
puts("\nInformacoes");
printf("Nome: %s\n", a.nome);
printf("RA: %s\n", a.RA);
printf("N1: %.1f\n", a.N1);
printf("N2: %.1f\n", a.N2);
imprimeDisciplina(*a.disc);
if(calcMedia(a) >=5){
puts("Aprovado");
printf("Media: %.1f\n", calcMedia(a));
} else{
puts(":(");
printf("Media Necessaria: %.1f\n", notaNecessaria(a));
}
}
int main(int argc, char *argv[]){
struct Aluno a1;
strcpy(a1.nome, "<NAME>");
strcpy(a1.RA, "22119001-0");
a1.N1 = 0;
a1.N2 = 5.6;
struct Aluno a2;
strcpy(a2.nome, "<NAME>");
strcpy(a2.RA, "22119001-0");
a2.N1 = 10;
a2.N2 = 5.6;
struct Disciplina d1;
strcpy(d1.nomeProf, "Toninho");
strcpy(d1.nomeDisc, "Teoria dos Grafos");
struct Disciplina d2;
strcpy(d2.nomeProf, "Silmara");
strcpy(d2.nomeDisc, "Calculo");
a1.disc = &d1;
a2.disc = &d2;
strcpy(a1.disc->nomeDisc, "Mudou o Nome");
imprimeAluno(a2);
imprimeAluno(a1);
return 0;
}
|
ovistoica/testing-javascript
|
lessons/2-mocking/src/no-framework/external-mock-modules.js
|
<gh_stars>0
/*
Out own implementation of jests.mock entire external module module
*/
//Prime the cache, so the object includes the path to the mock utils
require("../__no-framework-mocks__/utils");
const utilsPath = require.resolve("../utils");
const mockUtilsPath = require.resolve("../__no-framework-mocks__/utils");
require.cache[utilsPath] = require.cache[mockUtilsPath];
const assert = require("assert");
const thumbWar = require("../thumb-war");
const utils = require("../utils");
const winner = thumbWar("Ovidiu", "Mihai");
assert.strictEqual(winner, "Ovidiu");
assert.deepStrictEqual(utils.getWinner.mock.calls, [
["Ovidiu", "Mihai"],
["Ovidiu", "Mihai"],
]);
// Cleanup after tests
delete require.cache[utilsPath];
|
renemagrit/PP_MJCompiler
|
MJCompiler/src/rs/ac/bg/etf/pp1/ast/MethodDeclaration.java
|
// generated with ast extension for cup
// version 0.8
// 29/5/2021 18:50:59
package rs.ac.bg.etf.pp1.ast;
public class MethodDeclaration extends MethodDecl {
private MethodHeader MethodHeader;
private FormParamsBegin FormParamsBegin;
private FromParams FromParams;
private FormParamsEnd FormParamsEnd;
private MethodDelVarList MethodDelVarList;
private MethBodyStart MethBodyStart;
private ListStatementOpt ListStatementOpt;
public MethodDeclaration (MethodHeader MethodHeader, FormParamsBegin FormParamsBegin, FromParams FromParams, FormParamsEnd FormParamsEnd, MethodDelVarList MethodDelVarList, MethBodyStart MethBodyStart, ListStatementOpt ListStatementOpt) {
this.MethodHeader=MethodHeader;
if(MethodHeader!=null) MethodHeader.setParent(this);
this.FormParamsBegin=FormParamsBegin;
if(FormParamsBegin!=null) FormParamsBegin.setParent(this);
this.FromParams=FromParams;
if(FromParams!=null) FromParams.setParent(this);
this.FormParamsEnd=FormParamsEnd;
if(FormParamsEnd!=null) FormParamsEnd.setParent(this);
this.MethodDelVarList=MethodDelVarList;
if(MethodDelVarList!=null) MethodDelVarList.setParent(this);
this.MethBodyStart=MethBodyStart;
if(MethBodyStart!=null) MethBodyStart.setParent(this);
this.ListStatementOpt=ListStatementOpt;
if(ListStatementOpt!=null) ListStatementOpt.setParent(this);
}
public MethodHeader getMethodHeader() {
return MethodHeader;
}
public void setMethodHeader(MethodHeader MethodHeader) {
this.MethodHeader=MethodHeader;
}
public FormParamsBegin getFormParamsBegin() {
return FormParamsBegin;
}
public void setFormParamsBegin(FormParamsBegin FormParamsBegin) {
this.FormParamsBegin=FormParamsBegin;
}
public FromParams getFromParams() {
return FromParams;
}
public void setFromParams(FromParams FromParams) {
this.FromParams=FromParams;
}
public FormParamsEnd getFormParamsEnd() {
return FormParamsEnd;
}
public void setFormParamsEnd(FormParamsEnd FormParamsEnd) {
this.FormParamsEnd=FormParamsEnd;
}
public MethodDelVarList getMethodDelVarList() {
return MethodDelVarList;
}
public void setMethodDelVarList(MethodDelVarList MethodDelVarList) {
this.MethodDelVarList=MethodDelVarList;
}
public MethBodyStart getMethBodyStart() {
return MethBodyStart;
}
public void setMethBodyStart(MethBodyStart MethBodyStart) {
this.MethBodyStart=MethBodyStart;
}
public ListStatementOpt getListStatementOpt() {
return ListStatementOpt;
}
public void setListStatementOpt(ListStatementOpt ListStatementOpt) {
this.ListStatementOpt=ListStatementOpt;
}
public void accept(Visitor visitor) {
visitor.visit(this);
}
public void childrenAccept(Visitor visitor) {
if(MethodHeader!=null) MethodHeader.accept(visitor);
if(FormParamsBegin!=null) FormParamsBegin.accept(visitor);
if(FromParams!=null) FromParams.accept(visitor);
if(FormParamsEnd!=null) FormParamsEnd.accept(visitor);
if(MethodDelVarList!=null) MethodDelVarList.accept(visitor);
if(MethBodyStart!=null) MethBodyStart.accept(visitor);
if(ListStatementOpt!=null) ListStatementOpt.accept(visitor);
}
public void traverseTopDown(Visitor visitor) {
accept(visitor);
if(MethodHeader!=null) MethodHeader.traverseTopDown(visitor);
if(FormParamsBegin!=null) FormParamsBegin.traverseTopDown(visitor);
if(FromParams!=null) FromParams.traverseTopDown(visitor);
if(FormParamsEnd!=null) FormParamsEnd.traverseTopDown(visitor);
if(MethodDelVarList!=null) MethodDelVarList.traverseTopDown(visitor);
if(MethBodyStart!=null) MethBodyStart.traverseTopDown(visitor);
if(ListStatementOpt!=null) ListStatementOpt.traverseTopDown(visitor);
}
public void traverseBottomUp(Visitor visitor) {
if(MethodHeader!=null) MethodHeader.traverseBottomUp(visitor);
if(FormParamsBegin!=null) FormParamsBegin.traverseBottomUp(visitor);
if(FromParams!=null) FromParams.traverseBottomUp(visitor);
if(FormParamsEnd!=null) FormParamsEnd.traverseBottomUp(visitor);
if(MethodDelVarList!=null) MethodDelVarList.traverseBottomUp(visitor);
if(MethBodyStart!=null) MethBodyStart.traverseBottomUp(visitor);
if(ListStatementOpt!=null) ListStatementOpt.traverseBottomUp(visitor);
accept(visitor);
}
public String toString(String tab) {
StringBuffer buffer=new StringBuffer();
buffer.append(tab);
buffer.append("MethodDeclaration(\n");
if(MethodHeader!=null)
buffer.append(MethodHeader.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
if(FormParamsBegin!=null)
buffer.append(FormParamsBegin.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
if(FromParams!=null)
buffer.append(FromParams.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
if(FormParamsEnd!=null)
buffer.append(FormParamsEnd.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
if(MethodDelVarList!=null)
buffer.append(MethodDelVarList.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
if(MethBodyStart!=null)
buffer.append(MethBodyStart.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
if(ListStatementOpt!=null)
buffer.append(ListStatementOpt.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
buffer.append(tab);
buffer.append(") [MethodDeclaration]");
return buffer.toString();
}
}
|
Neoplatonist/axialrp-node
|
src/pages/generator/components/spells/components/spellList/index.js
|
import React, { Component } from 'react';
import SpellItem from './components/spellItem';
import { connect } from 'react-redux';
import {
selectClassObj,
selectSpellsLock
} from '../../../../../../actions';
class SpellList extends Component {
renderList = () => {
const list = this.props.list.filter(v => v !== undefined)
return list.map((v, k) => {
return <SpellItem
key={k}
spell={v}
level={this.props.name}
choose={this.props.choose}
/>;
});
}
renderTitle = () => {
const level = this.props.name;
switch(level) {
case 0: return 'Cantrips';
case 1: return '1st Level Spells';
case 2: return '2nd Level Spells';
case 3: return '3rd Level Spells';
default: return `${level}th Level Spells`;
}
}
render() {
return (
<div>
<br />
{ this.props.list.length
? <h5>{ this.renderTitle() } ({this.props.choose})</h5>
: '' }
{ this.props.list.length
? this.renderList()
: '' }
</div>
);
}
}
const mapStateToProps = state => ({
classObj: selectClassObj(state),
spellLock: selectSpellsLock(state),
});
const boundActions = {
};
export default connect(mapStateToProps, boundActions)(SpellList);
|
ORNL-CEES/kokkos
|
example/fixture/BoxElemFixture.hpp
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact <NAME> (<EMAIL>)
//
// ************************************************************************
//@HEADER
*/
#ifndef KOKKOS_EXAMPLE_BOXELEMFIXTURE_HPP
#define KOKKOS_EXAMPLE_BOXELEMFIXTURE_HPP
#include <cstdio>
#include <utility>
#include <Kokkos_Core.hpp>
#include <HexElement.hpp>
#include <BoxElemPart.hpp>
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Example {
/** \brief Map a grid onto a unit cube with smooth nonlinear grading
* of the map.
*/
struct MapGridUnitCube {
const float m_a;
const float m_b;
const float m_c;
const size_t m_max_x;
const size_t m_max_y;
const size_t m_max_z;
MapGridUnitCube(const size_t grid_max_x, const size_t grid_max_y,
const size_t grid_max_z, const float bubble_x,
const float bubble_y, const float bubble_z)
: m_a(bubble_x),
m_b(bubble_y),
m_c(bubble_z),
m_max_x(grid_max_x),
m_max_y(grid_max_y),
m_max_z(grid_max_z) {}
template <typename Scalar>
KOKKOS_INLINE_FUNCTION void operator()(int grid_x, int grid_y, int grid_z,
Scalar& coord_x, Scalar& coord_y,
Scalar& coord_z) const {
// Map to a unit cube [0,1]^3
const double x = double(grid_x) / double(m_max_x);
const double y = double(grid_y) / double(m_max_y);
const double z = double(grid_z) / double(m_max_z);
coord_x = x + x * x * (x - 1) * (x - 1) * m_a;
coord_y = y + y * y * (y - 1) * (y - 1) * m_b;
coord_z = z + z * z * (z - 1) * (z - 1) * m_c;
}
};
} // namespace Example
} // namespace Kokkos
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Example {
/** \brief Generate a distributed unstructured finite element mesh
* from a partitioned NX*NY*NZ box of elements.
*
* Order owned nodes first followed by off-process nodes
* grouped by owning process.
*/
template <class Device, BoxElemPart::ElemOrder Order,
class CoordinateMap = MapGridUnitCube>
class BoxElemFixture {
public:
typedef Device execution_space;
enum { SpaceDim = 3 };
enum {
ElemNode = Order == BoxElemPart::ElemLinear
? 8
: Order == BoxElemPart::ElemQuadratic ? 27 : 0
};
private:
typedef Kokkos::Example::HexElement_TensorData<ElemNode> hex_data;
Kokkos::Example::BoxElemPart m_box_part;
CoordinateMap m_coord_map;
Kokkos::View<double * [SpaceDim], Device> m_node_coord;
Kokkos::View<size_t * [SpaceDim], Device> m_node_grid;
Kokkos::View<size_t * [ElemNode], Device> m_elem_node;
Kokkos::View<size_t * [2], Device> m_recv_node;
Kokkos::View<size_t * [2], Device> m_send_node;
Kokkos::View<size_t*, Device> m_send_node_id;
unsigned char m_elem_node_local[ElemNode][4];
public:
typedef Kokkos::View<const size_t * [ElemNode], Device> elem_node_type;
typedef Kokkos::View<const double * [SpaceDim], Device> node_coord_type;
typedef Kokkos::View<const size_t * [SpaceDim], Device> node_grid_type;
typedef Kokkos::View<const size_t * [2], Device> comm_list_type;
typedef Kokkos::View<const size_t*, Device> send_nodeid_type;
inline bool ok() const { return m_box_part.ok(); }
KOKKOS_INLINE_FUNCTION
size_t node_count() const { return m_node_grid.extent(0); }
KOKKOS_INLINE_FUNCTION
size_t node_count_owned() const { return m_box_part.owns_node_count(); }
KOKKOS_INLINE_FUNCTION
size_t node_count_global() const { return m_box_part.global_node_count(); }
KOKKOS_INLINE_FUNCTION
size_t elem_count() const { return m_elem_node.extent(0); }
KOKKOS_INLINE_FUNCTION
size_t elem_count_global() const { return m_box_part.global_elem_count(); }
KOKKOS_INLINE_FUNCTION
size_t elem_node_local(size_t inode, int k) const {
return m_elem_node_local[inode][k];
}
KOKKOS_INLINE_FUNCTION
size_t node_grid(size_t inode, int iaxis) const {
return m_node_grid(inode, iaxis);
}
KOKKOS_INLINE_FUNCTION
size_t node_global_index(size_t local) const {
const size_t tmp_node_grid[SpaceDim] = {
m_node_grid(local, 0), m_node_grid(local, 1), m_node_grid(local, 2)};
return m_box_part.global_node_id(tmp_node_grid);
}
KOKKOS_INLINE_FUNCTION
double node_coord(size_t inode, int iaxis) const {
return m_node_coord(inode, iaxis);
}
KOKKOS_INLINE_FUNCTION
size_t node_grid_max(int iaxis) const {
return m_box_part.global_coord_max(iaxis);
}
KOKKOS_INLINE_FUNCTION
size_t elem_node(size_t ielem, size_t inode) const {
return m_elem_node(ielem, inode);
}
elem_node_type elem_node() const { return m_elem_node; }
node_coord_type node_coord() const { return m_node_coord; }
node_grid_type node_grid() const { return m_node_grid; }
comm_list_type recv_node() const { return m_recv_node; }
comm_list_type send_node() const { return m_send_node; }
send_nodeid_type send_nodeid() const { return m_send_node_id; }
KOKKOS_INLINE_FUNCTION
BoxElemFixture(const BoxElemFixture& rhs)
: m_box_part(rhs.m_box_part),
m_coord_map(rhs.m_coord_map),
m_node_coord(rhs.m_node_coord),
m_node_grid(rhs.m_node_grid),
m_elem_node(rhs.m_elem_node),
m_recv_node(rhs.m_recv_node),
m_send_node(rhs.m_send_node),
m_send_node_id(rhs.m_send_node_id) {
for (int i = 0; i < ElemNode; ++i) {
m_elem_node_local[i][0] = rhs.m_elem_node_local[i][0];
m_elem_node_local[i][1] = rhs.m_elem_node_local[i][1];
m_elem_node_local[i][2] = rhs.m_elem_node_local[i][2];
m_elem_node_local[i][3] = 0;
}
}
BoxElemFixture& operator=(const BoxElemFixture& rhs) {
m_box_part = rhs.m_box_part;
m_coord_map = rhs.m_coord_map;
m_node_coord = rhs.m_node_coord;
m_node_grid = rhs.m_node_grid;
m_elem_node = rhs.m_elem_node;
m_recv_node = rhs.m_recv_node;
m_send_node = rhs.m_send_node;
m_send_node_id = rhs.m_send_node_id;
for (int i = 0; i < ElemNode; ++i) {
m_elem_node_local[i][0] = rhs.m_elem_node_local[i][0];
m_elem_node_local[i][1] = rhs.m_elem_node_local[i][1];
m_elem_node_local[i][2] = rhs.m_elem_node_local[i][2];
m_elem_node_local[i][3] = 0;
}
return *this;
}
BoxElemFixture(const BoxElemPart::Decompose decompose,
const size_t global_size, const size_t global_rank,
const size_t elem_nx, const size_t elem_ny,
const size_t elem_nz, const float bubble_x = 1.1f,
const float bubble_y = 1.2f, const float bubble_z = 1.3f)
: m_box_part(Order, decompose, global_size, global_rank, elem_nx, elem_ny,
elem_nz),
m_coord_map(
m_box_part.global_coord_max(0), m_box_part.global_coord_max(1),
m_box_part.global_coord_max(2), bubble_x, bubble_y, bubble_z),
m_node_coord("fixture_node_coord", m_box_part.uses_node_count()),
m_node_grid("fixture_node_grid", m_box_part.uses_node_count()),
m_elem_node("fixture_elem_node", m_box_part.uses_elem_count()),
m_recv_node("fixture_recv_node", m_box_part.recv_node_msg_count()),
m_send_node("fixture_send_node", m_box_part.send_node_msg_count()),
m_send_node_id("fixture_send_node_id",
m_box_part.send_node_id_count()) {
{
const hex_data elem_data;
for (int i = 0; i < ElemNode; ++i) {
m_elem_node_local[i][0] = elem_data.eval_map[i][0];
m_elem_node_local[i][1] = elem_data.eval_map[i][1];
m_elem_node_local[i][2] = elem_data.eval_map[i][2];
m_elem_node_local[i][3] = 0;
}
}
const size_t nwork = std::max(
m_recv_node.extent(0),
std::max(
m_send_node.extent(0),
std::max(m_send_node_id.extent(0),
std::max(m_node_grid.extent(0),
m_elem_node.extent(0) * m_elem_node.extent(1)))));
Kokkos::parallel_for(nwork, *this);
}
// Initialization:
KOKKOS_INLINE_FUNCTION
void operator()(size_t i) const {
if (i < m_elem_node.extent(0) * m_elem_node.extent(1)) {
const size_t ielem = i / ElemNode;
const size_t inode = i % ElemNode;
size_t elem_grid[SpaceDim];
size_t tmp_node_grid[SpaceDim];
m_box_part.uses_elem_coord(ielem, elem_grid);
enum {
elem_node_scale = Order == BoxElemPart::ElemLinear
? 1
: Order == BoxElemPart::ElemQuadratic ? 2 : 0
};
tmp_node_grid[0] =
elem_node_scale * elem_grid[0] + m_elem_node_local[inode][0];
tmp_node_grid[1] =
elem_node_scale * elem_grid[1] + m_elem_node_local[inode][1];
tmp_node_grid[2] =
elem_node_scale * elem_grid[2] + m_elem_node_local[inode][2];
m_elem_node(ielem, inode) = m_box_part.local_node_id(tmp_node_grid);
}
if (i < m_node_grid.extent(0)) {
size_t tmp_node_grid[SpaceDim];
m_box_part.local_node_coord(i, tmp_node_grid);
m_node_grid(i, 0) = tmp_node_grid[0];
m_node_grid(i, 1) = tmp_node_grid[1];
m_node_grid(i, 2) = tmp_node_grid[2];
m_coord_map(tmp_node_grid[0], tmp_node_grid[1], tmp_node_grid[2],
m_node_coord(i, 0), m_node_coord(i, 1), m_node_coord(i, 2));
}
if (i < m_recv_node.extent(0)) {
m_recv_node(i, 0) = m_box_part.recv_node_rank(i);
m_recv_node(i, 1) = m_box_part.recv_node_count(i);
}
if (i < m_send_node.extent(0)) {
m_send_node(i, 0) = m_box_part.send_node_rank(i);
m_send_node(i, 1) = m_box_part.send_node_count(i);
}
if (i < m_send_node_id.extent(0)) {
m_send_node_id(i) = m_box_part.send_node_id(i);
}
}
};
} // namespace Example
} // namespace Kokkos
//----------------------------------------------------------------------------
#endif /* #ifndef KOKKOS_EXAMPLE_BOXELEMFIXTURE_HPP */
|
abbshr/Kedi
|
lib/kedi.rb
|
<filename>lib/kedi.rb
require "kedi/rest"
require "kedi/config"
require "kedi/version"
require "kedi/container"
# require "kedi/translate"
require "kedi/eventloop"
require "active_support/all"
module Kedi
extend self
attr_reader :config
attr_accessor :container
# 作为独立的 server 启动
def standalone(&p)
meow &p
start_httpserver
start_eventloop
end
# restful http server
def start_httpserver
@httpserver = RestServer.new
end
# 主线程接收消息、调度任务的事件循环
def start_eventloop
@eventloop = EventLoop.new
end
# 作为 gem 调用的入口 API
def meow(&p)
@config = Config.new
Thread.abort_on_exception = true if @config.debug
# 创建容纳 pipelines 的 container
@container = Container.new
# 执行 DSL
instance_eval &p if block_given?
# 激活 pipelines
@container.run
# generate_dag_container.run
end
## 创建 pipeline DSL
def pipeline(rule = nil, name: nil, &p)
pipe = Pipeline.new(rule, name, &p)
@container.add(pipe)
pipe
# pipe.streaming
end
## 配置文件 DSL
# 启动/设置选项
def enable(sym_option_name, option_value = true)
if option_value.is_a? FalseClass
option_value = true
end
@config.merge sym_option_name, option_value
end
# 禁用选项
def disable(sym_option_name)
@config.set sym_option_name, false
end
# 获取选项值
def get(sym_option_name)
@config.get sym_option_name
end
# 覆盖选项值
def set(sym_option_name, value)
@config.set sym_option_name, value
end
# 加载 DSL 文件
private
def unsafe_load(path, ctx)
eval File.read(path, encoding: "UTF-8"), ctx, path
end
# 加载 pipeline 描述文件(rule 文件)
def pipeline_loader(path)
pipeline { unsafe_load path, binding }
end
# 加载配置文件
def config_loader(path)
unsafe_load path, binding
end
# 加载规则创建 pipeline
def load_rules(from: :fs)
case from
when :fs then create_pipeline_from_fs
when :persist then create_pipeline_from_persist
end
end
# private def prepare
# @container = generate_dag_container
# end
private def get_raw_rules
# flatten nested dirs & get rule file
# TODO
@config.rules_dir
end
private def generate_container
pipelines = load_rules
@container = Container.new pipelines
end
# 从 pipeline 描述文件中创建 pipes
private def create_pipelines_from_fs
get_raw_rules.map do |raw_rule|
rule_skeleton = Translator.new raw_rule
pipeline(rule_skeleton)
end
end
# 从存储系统中创建 pipes
private def create_pipelines_from_persist
Rule.all.map { |rule| pipeline(rule) }
end
end
|
al4/vaultsmith
|
vaultsmith.go
|
package main
import (
"fmt"
log "github.com/sirupsen/logrus"
flag "github.com/spf13/pflag"
"os"
"strings"
"github.com/starlingbank/vaultsmith/config"
"github.com/starlingbank/vaultsmith/document"
"github.com/starlingbank/vaultsmith/internal"
"github.com/starlingbank/vaultsmith/vault"
"io/ioutil"
"path/filepath"
)
var flags = flag.NewFlagSet("Vaultsmith", flag.ExitOnError)
var documentPath string
var dry bool
var templateFile string
var vaultRole string
var logLevel string
var templateParams []string
var httpAuthToken string
var tarDir string
var noCleanUp bool
func init() {
flags.StringVar(
// TODO: remove default value of "./example", could do bad things in production
&documentPath, "document-path", "",
"The root directory of the configuration. Can be a local directory, local gz "+
"tarball or http url to a gz tarball.",
)
flags.StringVar(
&vaultRole, "role", "root", "The Vault role to authenticate as",
)
flags.StringVar(
&templateFile, "template-file", "", "JSON file containing template "+
"mappings. If not specified, vaultsmith will look for \"_vaultsmith.json\" in the "+
"base of the document path.",
)
flags.BoolVar(
&dry, "dry", false, "Dry run; will read from but not write to vault",
)
flags.StringVar(
&logLevel, "log-level", "info", fmt.Sprintf("Log level, valid "+
"values are %+v", log.AllLevels),
)
flags.StringSliceVar(
&templateParams, "template-params", []string{}, "Template parameters. "+
"Applies globally, but values in template-file take precedence. E.G.: service=foo,account=bar",
)
flags.StringVar(
&httpAuthToken, "http-auth-token", "", "Auth token to pass as "+
"'Authorization' header. Useful for passing user tokens to private github repos.",
)
flags.StringVar(
&tarDir, "tar-dir", "", "Directory within the tarball to use as the "+
"document-path. If not specified, and there is only one directory within the archive, "+
"that one will be used. If there is more than one diretory, the root directory of the "+
"archive will be used.",
)
flags.BoolVar(
&noCleanUp, "no-cleanup", false, "Don't clean up temp directory on exit",
)
flags.Usage = func() {
fmt.Printf("Usage of vaultsmith:\n")
flags.PrintDefaults()
fmt.Print("\nNotes:\n" +
"• BE CAREFUL with this tool, it will faithfully apply whatever config you give it " +
"without confirmation or warning! Use --dry until you are confident.\n" +
"• Vault authentication is handled by environment variables (the same " +
"ones as the Vault client, as vaultsmith uses the same code). So ensure VAULT_ADDR " +
"and VAULT_TOKEN are set.\n" +
"• Files that start with an underscore (e.g. _vaultsmith.json) are not published to " +
"vault.\n" +
"• If template-file is not specified, it is not mandatory for _vaultsmith.json to be " +
"present.\n" +
"• Specifying a parameter with --template-params allows only a single value. If you " +
"need multiple values, please use a template-file." +
"\n\n")
}
// Avoid parsing flags passed on running `go test`
var args []string
for _, s := range os.Args[1:] {
if !strings.HasPrefix(s, "-test.") {
args = append(args, s)
}
}
err := flags.Parse(args)
if err != nil {
log.Fatal(err)
}
}
func main() {
log.SetOutput(os.Stderr)
ll, err := log.ParseLevel(logLevel)
if err != nil {
log.Fatalln(err)
}
log.SetLevel(ll)
if dry {
log.Info("Dry mode enabled, no changes will be made")
}
if documentPath == "" {
log.Fatalln("Please specify --document-path")
}
// Only check if specified, otherwise no template file is OK
if templateFile != "" {
if _, err := os.Stat(templateFile); os.IsNotExist(err) {
log.Fatalf("Specified template-file does not exist: %s", err)
}
}
conf := config.VaultsmithConfig{
DocumentPath: documentPath,
VaultRole: vaultRole,
TemplateFile: templateFile,
Dry: dry,
TemplateParams: templateParams,
HttpAuthToken: httpAuthToken,
TarDir: tarDir,
}
var client vault.Vault
client, err = vault.NewVaultClient(conf.Dry)
if err != nil {
log.Fatal(err)
}
err = Run(client, conf)
if err != nil {
log.Fatalf("Error: %s", err)
}
log.Debugf("Success")
}
func whichFileExists(filePath ...string) (file string) {
for _, f := range filePath {
if _, err := os.Stat(f); !os.IsNotExist(err) {
log.WithFields(log.Fields{"file": f}).Debug("file exists")
return f
} else {
log.WithFields(log.Fields{"file": f}).Debug("file does not exist")
}
}
return ""
}
func Run(c vault.Vault, config config.VaultsmithConfig) error {
err := c.Authenticate(config.VaultRole)
if err != nil {
return fmt.Errorf("failed authenticating with Vault: %s", err)
}
workDir, err := ioutil.TempDir(os.TempDir(), "vaultsmith-")
if err != nil {
return fmt.Errorf("could not create temp directory: %s", err)
}
defer os.Remove(workDir)
docSet, err := document.GetSet(workDir, config)
if err != nil {
return err
}
err = docSet.Get()
if err != nil {
return err
}
if !noCleanUp {
defer docSet.CleanUp()
}
docPath, err := docSet.Path()
if err != nil {
return err
}
// Determine if we have a template file
config.TemplateFile = whichFileExists(
templateFile,
filepath.Join(docPath, "_vaultsmith.json"),
)
cw, err := internal.NewConfigWalker(c, config, docPath)
if err != nil {
return err
}
return cw.Run()
}
|
askmiso/miso-client-js-sdk
|
packages/client-sdk-algolia/src/filter/index.test.js
|
<gh_stars>0
import { buildFilters } from './index';
const mockAlgoliaClient = {};
const build = filters => buildFilters(mockAlgoliaClient, filters);
describe('filters', () => {
run('empty', {});
run('facet', { filters: '[a:x]' }, 'a:x');
run('numeric: range', { filters: 'a:0.5 TO 2' }, 'a:[0.5 TO 2]');
run('numeric: =', { filters: 'a = 1.5' }, 'a:1.5');
run('numeric: !=', { filters: 'a != 1.5' }, '(NOT a:1.5)');
run('numeric: <', { filters: 'a < 1.5' }, 'a:[* TO 1.5}');
run('numeric: <=', { filters: 'a <= 1.5' }, 'a:[* TO 1.5]');
run('numeric: >', { filters: 'a > 1.5' }, 'a:{1.5 TO *]');
run('numeric: >=', { filters: 'a >= 1.5' }, 'a:[1.5 TO *]');
run('tag: implicit', { filters: 'a' }, 'tags:a');
run('tag: explicit', { filters: '_tags:a' }, 'tags:a');
run('disjunction', { filters: 'a:x OR b:y' }, 'a:x OR b:y');
run('conjunction', { filters: 'a:x AND b:y' }, 'a:x AND b:y');
run('quote', { filters: '"[_tags:a]":"x > y"' }, '"[_tags:a]":"x > y"');
run('quote', { filters: '"x > y"' }, 'tags:"x > y"');
run('bare NOT', { filters: 'a:x OR NOT b:y' }, 'a:x OR (NOT b:y)');
run('bare NOT', { filters: 'a:x AND NOT b:y' }, 'a:x AND (NOT b:y)');
});
describe('facetFilters', () => {
run('simple', { facetFilters: ['a:x'] }, 'a:x');
run('disjunction', { facetFilters: [['a:x']] }, 'a:x');
run('disjunction', { facetFilters: [['a:x', 'b:y']] }, '(a:x OR b:y)');
run('disjunction', { facetFilters: [['a:x', 'b:y', 'c:z']] }, '(a:x OR b:y OR c:z)');
run('conjunction', { facetFilters: ['a:x', 'b:y'] }, 'a:x AND b:y');
run('conjunction', { facetFilters: ['a:x', 'b:y', 'c:z'] }, 'a:x AND b:y AND c:z');
run('negation', { facetFilters: ['a:-x'] }, '(NOT a:x)');
run('negation escaped', { facetFilters: ['a:\\-x'] }, 'a:"-x"');
});
describe('numericFilters', () => {
run('basic: range', { numericFilters: ['a:0.5 TO 2'] }, 'a:[0.5 TO 2]');
run('basic: =', { numericFilters: ['a = 1.5'] }, 'a:1.5');
run('basic: !=', { numericFilters: ['a != 1.5'] }, '(NOT a:1.5)');
run('basic: <', { numericFilters: ['a < 1.5'] }, 'a:[* TO 1.5}');
run('basic: <=', { numericFilters: ['a <= 1.5'] }, 'a:[* TO 1.5]');
run('basic: >', { numericFilters: ['a > 1.5'] }, 'a:{1.5 TO *]');
run('basic: >=', { numericFilters: ['a >= 1.5'] }, 'a:[1.5 TO *]');
});
describe('tagFilters', () => {
run('simple', { tagFilters: ['a'] }, 'tags:a');
run('disjunction', { tagFilters: [['a']] }, 'tags:a');
run('disjunction', { tagFilters: [['a', 'b']] }, '(tags:a OR tags:b)');
run('disjunction', { tagFilters: [['a', 'b', 'c']] }, '(tags:a OR tags:b OR tags:c)');
run('conjunction', { tagFilters: ['a', 'b'] }, 'tags:a AND tags:b');
run('conjunction', { tagFilters: ['a', 'b', 'c'] }, 'tags:a AND tags:b AND tags:c');
run('mixed', { tagFilters: ['a', ['b', 'c'], 'd'] }, 'tags:a AND (tags:b OR tags:c) AND tags:d');
});
function run(name, parameters, fq) {
it(name, () => {
expect(build(parameters)).toStrictEqual(fq === undefined ? {} : { fq });
});
}
|
DogJun/vue-boilerplate
|
src/components/messagebox/Confirm/index.js
|
import Vue from 'vue'
import ConfirmContainer from './tpl'
import iOSConfirm from '../iOS/Confirm'
import merge from 'lodash/merge'
let instance
let globalConfig = {}
let ConfirmConstructor = Vue.extend(ConfirmContainer)
let q = []
let isShowing = false
let Confirm = (options) => {
if (!isShowing) {
instance = new ConfirmConstructor({
el: document.createElement('div')
})
document.body.appendChild(instance.$el)
isShowing = true
} else {
q.push(options)
return
}
/* 支持 this.$Confirm(string) 的调用方式 */
if (typeof options === 'string') {
options = {
content: options
}
}
merge(instance.$data.w, globalConfig)
merge(instance.$data.w, options)
return new Promise((resolve, reject) => {
instance.show = true
if (instance.$data.w.component) {
instance.$options.components['userConfig'] = instance.$data.w.component
/* 设置当前的 activeView */
instance.activeView = 'userConfig'
} else {
instance.$options.components['iOS'] = iOSConfirm
instance.activeView = 'iOS'
}
/* fix 弹窗出来之后依旧键盘没有回收 */
let inputs = Array.prototype.slice.call(document.querySelectorAll('input'))
inputs.forEach((input) => {
input.blur()
})
/* 对 success 函数包裹一层 */
let success = instance.success
let fail = instance.fail
instance.success = () => {
success()
resolve('success')
isShowing = false
if (q.length > 0) {
Confirm(q.shift())
}
}
instance.fail = () => {
fail()
// eslint-disable-next-line
reject('fail')
isShowing = false
if (q.length > 0) {
Confirm(q.shift())
}
}
})
}
export default {
install (Vue, options = {}) {
globalConfig = options
Vue.prototype.$confirm = Confirm
}
}
|
ksteensig/stm32-libopencm3-platooning
|
PSoC/Platooning/PeakDetector_V2.cydsn/codegentemp/Comp_A_PM.c
|
/*******************************************************************************
* File Name: Comp_A.c
* Version 2.0
*
* Description:
* This file provides the power management source code APIs for the
* Comparator.
*
* Note:
* None
*
********************************************************************************
* Copyright 2008-2012, Cypress Semiconductor Corporation. All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
*******************************************************************************/
#include "Comp_A.h"
static Comp_A_backupStruct Comp_A_backup;
/*******************************************************************************
* Function Name: Comp_A_SaveConfig
********************************************************************************
*
* Summary:
* Save the current user configuration
*
* Parameters:
* void:
*
* Return:
* void
*
*******************************************************************************/
void Comp_A_SaveConfig(void)
{
/* Empty since all are system reset for retention flops */
}
/*******************************************************************************
* Function Name: Comp_A_RestoreConfig
********************************************************************************
*
* Summary:
* Restores the current user configuration.
*
* Parameters:
* void
*
* Return:
* void
*
********************************************************************************/
void Comp_A_RestoreConfig(void)
{
/* Empty since all are system reset for retention flops */
}
/*******************************************************************************
* Function Name: Comp_A_Sleep
********************************************************************************
*
* Summary:
* Stop and Save the user configuration
*
* Parameters:
* void:
*
* Return:
* void
*
* Global variables:
* Comp_A_backup.enableState: Is modified depending on the enable
* state of the block before entering sleep mode.
*
*******************************************************************************/
void Comp_A_Sleep(void)
{
/* Save Comp's enable state */
if(Comp_A_ACT_PWR_EN == (Comp_A_PWRMGR & Comp_A_ACT_PWR_EN))
{
/* Comp is enabled */
Comp_A_backup.enableState = 1u;
}
else
{
/* Comp is disabled */
Comp_A_backup.enableState = 0u;
}
Comp_A_Stop();
Comp_A_SaveConfig();
}
/*******************************************************************************
* Function Name: Comp_A_Wakeup
********************************************************************************
*
* Summary:
* Restores and enables the user configuration
*
* Parameters:
* void
*
* Return:
* void
*
* Global variables:
* Comp_A_backup.enableState: Is used to restore the enable state of
* block on wakeup from sleep mode.
*
*******************************************************************************/
void Comp_A_Wakeup(void)
{
Comp_A_RestoreConfig();
if(Comp_A_backup.enableState == 1u)
{
/* Enable Comp's operation */
Comp_A_Enable();
} /* Do nothing if Comp was disabled before */
}
/* [] END OF FILE */
|
timkittel/PyViability
|
pyviability/libviability.py
|
<gh_stars>0
"""
Basic module that contains most of the relevant routines.
"""
from __future__ import print_function, division, generators
from .tsm_style import tsm_colors
from . import periodic_kdtree as periodkdt
import numpy as np
import numpy.linalg as la
import math
import numba as nb
import scipy.integrate as integ
import scipy.spatial as spat
import matplotlib as mpl
import matplotlib.pyplot as plt
import warnings as warn
import itertools as it
import functools as ft
import datetime as dt
#################################################################
# Disclaimer:
# Most of the Code is written in functions so numba speed-up can
# be used easily. Everything will be wrapped in classes as soon
# as numba.jitclass has stabilized.
#################################################################
#################################################################
# Some doc strings are as comments, because the functions should
# not appear in the actual documentation. Usually, that is
# because they are still experimental.
#################################################################
# flush the output of print by default
print = ft.partial(print, flush=True)
# raise the odeing warning as an error because it indicates that we are at a
# fixed point (or the grid is not fine enough)
warn.filterwarnings("error", category=integ.odepack.ODEintWarning)
# these are automatically set during grid generation but need to be manually set
# when using own grid
BOUNDS_EPSILON = None # should be set during grid Generation
STEPSIZE = None
INDEX_TYPE = np.int64
INDEX_TYPE_NB = nb.int64
# some constants so the calculation does end
MAX_ITERATION_EDDIES = 10
DEBUGGING = 0
VERBOSITY = 0
# the stuff for remembering the status
STATUS = ""
STATUS_PREFIX = None
TOPOLOGY_STEP_LIST = ["GENERAL", "SHELTER", "GLADE", "REMUP", "MANAGEABLE", "REMDOWN", "REST", "GENERAL", ""] # the empty one is so that can be given, too
STATUS_TOPOLOGY = "TOPOLOGY"
STATUS_INFIX = " "
STATUS_PREPARATION = "PREPARATION"
STATUS_COMPUTATION = "COMPUTATION"
STATUS_POSTPROCESSING = "POSTPROCESSING"
STATUS_DONE = "DONE"
STATUS_EDDIES_DARK = "EDDIES_DARK"
STATUS_EDDIES_SUNNY = "EDDIES_SUNNY"
# verbose printing stuff
PRINT_PREFIX = ""
PRINT_INFIX = " :"
PRINT_INFIX_BEHIND = "( "
PRINT_POSTFIX_BEHIND = " )"
# The ones below are just used by the default pre-calculation hook and the
# default state evaluation. They are just here so they are not used for
# something else.
KDTREE = None
STATES = None
BOUNDS = None
BASIS_VECTORS = None
BASIS_VECTORS_INV = None
OUT_OF_BOUNDS = None
COORDINATES = None
ALL_NEIGHBORS_DISTANCE = None
# ---- stuff for remembering the paths ----
PATHS = {}
PATHS_LAKE = {}
PATHS_INDEX_TYPE = INDEX_TYPE
PATHS_INDEX_DEFAULT = np.iinfo(PATHS_INDEX_TYPE).min
PATHS_MANAGEMENT_TYPE = np.int16
PATHS_MANAGEMENT_DEFAULT = np.iinfo(PATHS_MANAGEMENT_TYPE).min
# ---- states ----
# encode the different states as integers, so arrays of integers can be used
# later in numpy arrays (which are very fast on integers)
# None state should never be used as it is used to indicate out of bounds
REGIONS = ["UNSET", "SHELTER", "GLADE", "LAKE", "SUNNY_UP", "DARK_UP", "BACKWATERS", "SUNNY_DOWN", "DARK_DOWN", "SUNNY_EDDIES", "DARK_EDDIES", "SUNNY_ABYSS", "DARK_ABYSS", "TRENCH"]
UNSET = 0
SHELTER = 1
GLADE = 2
LAKE = 3
SUNNY_UP = 4
DARK_UP = 5
BACKWATERS = 6
SUNNY_DOWN = 7
DARK_DOWN = 8
SUNNY_EDDIES = 9
DARK_EDDIES = 10
SUNNY_ABYSS = 11
DARK_ABYSS = 12
TRENCH = 13
assert set(REGIONS).issubset(globals())
OTHER_STATE = 14 # used for computation reasons only
OUT_OF_BOUNDS_STATE = 15
# ---- Colors ----
# identify the states with the corresponding colors in order to be consistent
# with the color definitions from the original paper
COLORS = {
UNSET: "blue",
-SHELTER: "blue",
-GLADE: "blue",
SHELTER: tsm_colors["cShelter"],
GLADE: tsm_colors["cGlade"],
LAKE: tsm_colors["cLake"],
SUNNY_UP: tsm_colors["cSunnyUp"],
DARK_UP: tsm_colors["cDarkUp"],
BACKWATERS: tsm_colors["cBackwaters"],
SUNNY_DOWN: tsm_colors["cSunnyDown"],
DARK_DOWN: tsm_colors["cDarkDown"],
SUNNY_EDDIES: tsm_colors["cSunnyEddie"],
DARK_EDDIES: tsm_colors["cDarkEddie"],
SUNNY_ABYSS: tsm_colors["cSunnyAbyss"],
DARK_ABYSS: tsm_colors["cDarkAbyss"],
TRENCH: tsm_colors["cTrench"],
}
def printv(*args, verbosity=1, date_behind = False, **kwargs):
"""Print the output depending on the given verbosity."""
if "flush" not in kwargs:
kwargs["flush"] = True
if verbosity <= VERBOSITY:
date = dt.datetime.now().ctime()
print_args = list(args)
if date_behind:
print_args.append(PRINT_INFIX_BEHIND + date + PRINT_POSTFIX_BEHIND)
else:
print_args.insert(0, PRINT_PREFIX + date + PRINT_INFIX)
print(*print_args, **kwargs)
def printd(*args, **kwargs):
# Print the output depending on the global variable `DEDBUGGING`.
if "flush" not in kwargs:
kwargs["flush"] = True
if DEBUGGING:
print(*args, **kwargs)
def Delta_series(Delta_0, dim):
# create the detla series for a simplex-based grid
q = Delta_0 ** 2
return [np.sqrt(q * (n+2) / (2*n + 2)) for n in range(dim)]
def p_series(Delta_0, dim):
# returns the p vectors as an array p[i, j] where j enumerates the \
# vector (and thus dimension) and i the component
p_all = np.zeros((dim, dim))
for n, Delta_n in enumerate(Delta_series(Delta_0, dim)):
p_all[:n, n] = np.sum(p_all[:n, :n], axis=1) / (n+1)
p_all[n, n] = Delta_n
return p_all
def generate_grid(boundaries, n0, grid_type = "orthogonal", periodicity=[], verbosity=True):
"""Generate a grid, that is already normalized to [0, 1]^dimension.
**Note:** This function also sets globally MAX_NEIGHBOR_DISTANCE, BOUNDS_EPSILON, STEPSIZE, ALL_NEIGHBORS_DISTANCE.
So if you don't use this function, you need to set it yourself by hand.
Later, this will be circumvented by using proper OO-programming.
Parameters
----------
boundaries : array-like
shape (dim, 2), give the boundaries (min and max) for each dimension of the mode system
n0 : non-negative int
total number of points that the grid should have
grid_type : str, default: "orthogonal"
specify the grid_type to be created. experimental, only use if your know what you do
periodicity : array-like, default: []
specify if there is an peridicity given (to avoid overlapping points)
verbosity : bool, default: True
specify the verbosity
Returns
-------
tuple
(grid, scaling_vectors, offset, x_step) with
`grid`: the actual rescaled grid
`scaling_vectors`, `offset` : parameters to scale the grid back to the original size
`x_step` : stepsize of the grid
"""
global MAX_NEIGHBOR_DISTANCE, BOUNDS_EPSILON, STEPSIZE, ALL_NEIGHBORS_DISTANCE
# These are set globally afterwards.
assert grid_type in ["simplex-based", "orthogonal"], "unkown grid type '{!s}'".format(grid_type)
boundaries = np.asarray(boundaries)
periodicity = np.asarray(periodicity)
dim = boundaries.shape[0]
offset = boundaries[:, 0].astype(float)
scaling_factor = boundaries[:, 1] - boundaries[:, 0]
if not periodicity.size:
periodicity = - np.ones((dim,))
assert periodicity.shape == (dim,), "given boundaries do not match periodicity input"
periodicity_bool = (periodicity > 0)
#############################
# generate the basic grid
#############################
grid_prep_aperiodic = np.linspace(0, 1, n0)
grid_prep_periodic = np.linspace(0, 1, n0-1, endpoint=False)
# the last point is not set as it would be the same as the first one in
# a periodic grid
grid_args = [grid_prep_periodic if periodicity_bool[d] else grid_prep_aperiodic for d in range(dim)]
# create the grid
grid = np.asarray(np.meshgrid(*grid_args))
# move the axis with the dimenion to the back
grid = np.rollaxis(grid, 0, dim + 1)
# flattening the array
grid = np.reshape(grid, (-1, dim))
x_step = grid_prep_periodic[1]
if grid_type in ["orthogonal"]:
scaling_vectors = np.diag(1 / scaling_factor)
assert x_step == grid_prep_aperiodic[1], "bug?"
MAX_NEIGHBOR_DISTANCE = 1.5 * x_step
BOUNDS_EPSILON = 0.1 * x_step
ALL_NEIGHBORS_DISTANCE = 2 * np.sqrt(dim) * x_step + BOUNDS_EPSILON
# print("x_step", x_step)
# print("ALL_NEIGHBORS_DISTANCE", ALL_NEIGHBORS_DISTANCE)
# assert False
# ALL_NEIGHBORS_DISTANCE = np.sqrt(dim) * x_step + BOUNDS_EPSILON
# STEPSIZE = ALL_NEIGHBORS_DISTANCE
# STEPSIZE = 1.5 * x_step
# STEPSIZE = 2.5 * x_step
STEPSIZE = 2. * x_step
elif grid_type in ["simplex-based"]:
if np.any(periodicity_bool[1:]):
# the periodic binary tree can handle orthogonal periodicity only
# because the first basis vector for the simplex based grid is
# parallel to the x-axis, orthogonality in the first dimension is
# okai and the if statement above tests only periodicity_bool[1:]
raise NotImplementedError("The generation of the simplex-based grid is not yet compatible with periodic state spaces (except in the first dimension).")
basis_vectors = p_series(1., dim)
scaling_vectors = basis_vectors / scaling_factor[None, :]
grid = np.tensordot(grid, basis_vectors, axes=[(1,), (1,)])
# when recursively going through, then add the direct neighbors only
MAX_NEIGHBOR_DISTANCE = 1.01 * x_step
# x_step = Delta_0 # Delta_0 is side length of the simplices
BOUNDS_EPSILON = 0.1 * x_step
STEPSIZE = 2.5 * x_step # seems to be correct
ALL_NEIGHBORS_DISTANCE = la.norm(np.sum(basis_vectors, axis=1)) * x_step + BOUNDS_EPSILON
if verbosity:
print("created {:d} points".format(grid.shape[0]))
return grid, scaling_vectors, offset, x_step
def _generate_viability_single_point(evolutions, state_evaluation, use_numba=False, nb_nopython=False):
if use_numba:
raise NotImplementedError("numba usage doesn't really make sense here, because KDTREE cannot be numba jitted")
else:
def _viability_single_point(coordinate_index, coordinates, states,
stop_states, succesful_state, else_state):
"""Calculate whether a coordinate with value 'stop_value' can be reached from 'coordinates[coordinate_index]'."""
start = coordinates[coordinate_index]
start_state = states[coordinate_index]
global DEBUGGING, PATHS
# Keep the below statements as they are rather useful for the debugging.
# Will be removed for the 1.0 release (one day ^^).
# DEBUGGING = True
# DEBUGGING = DEBUGGING and STATUS == "TOPOLOGY MANAGEABLE COMPUTATION"
# DEBUGGING = DEBUGGING and (start_state == 1)
# DEBUGGING = (coordinate_index == (10 * 80 - 64,))
# DEBUGGING = DEBUGGING and la.norm(start - np.array([0.0777, 0.947, 1.])) < 0.05
# DEBUGGING = DEBUGGING and la.norm(start - np.array([0.008, 0.747])) < 0.001
# DEBUGGING = DEBUGGING and start[0] < 0.01
# DEBUGGING = DEBUGGING and start_state == 1
# DEBUGGING = DEBUGGING or la.norm(start - np.array([0.1, 0.606])) < 0.02
# DEBUGGING = True
# print("DEBUGGING", DEBUGGING)
# if DEBUGGING:
# print()
for evol_num, evol in enumerate(evolutions):
traj = evol(start, STEPSIZE)
final_index, final_state = state_evaluation(traj)
if final_state in stop_states: # and constraint(point) and final_distance < MAX_FINAL_DISTANCE:
if PATHS:
PATHS["reached point"][coordinate_index][:] = traj[-1]
PATHS["next point index"][coordinate_index] = final_index
PATHS["choice"][coordinate_index] = evol_num
if DEBUGGING:
print( "%i:" % evol_num, coordinate_index, start, start_state, "-->", final_state )
return succesful_state
# run the other evolutions to check whether they can reach a point with 'stop_state'
if DEBUGGING:
print("%i:"%evol_num, coordinate_index, start, start_state, "## break")
# didn't find an option leading to a point with 'stop_state'
if DEBUGGING:
print("all:", coordinate_index, start, start_state, "-->", else_state)
return else_state
return _viability_single_point
def _state_evaluation_kdtree_line(traj):
# deprecated (for now ^^)
start_point = traj[0]
final_point = traj[-1]
# print("start_point", start_point)
# print("final_point", final_point)
if OUT_OF_BOUNDS:
# check whether out-of-bounds
projected_values = np.tensordot(BASIS_VECTORS_INV, final_point, axes=[(1,), (0,)])
if np.any( BOUNDS[:, 0] > projected_values) or np.any( BOUNDS[:, 1] < projected_values ): # is the point out-of-bounds?
if DEBUGGING:
print("out-of-bounds")
return -1, OUT_OF_BOUNDS_STATE
# assert False, "out of bounds doesn't seem to work?"
# if not out-of-bounds, determine where it went to
# print("ALL_NEIGHBORS_DISTANCE", ALL_NEIGHBORS_DISTANCE)
# print("start_point", start_point)
neighbor_indices = KDTREE.query_ball_point(start_point, ALL_NEIGHBORS_DISTANCE)
# print("neighbor_indices", neighbor_indices)
neighbors = KDTREE.data[neighbor_indices]
# print("neighbors", neighbors)
# print("KDTREE.data[2]", KDTREE.data[2])
# print("diff", neighbors - KDTREE.data[2])
# print("norm(diff)", la.norm(neighbors - KDTREE.data[2], axis=-1))
if hasattr(KDTREE, "bounds"):
if DEBUGGING:
print("bounds", KDTREE.bounds)
bool_bounds = (KDTREE.bounds > 0)
newbounds = KDTREE.bounds[bool_bounds]
_start_point = np.copy(start_point)
_start_point[bool_bounds] = start_point[bool_bounds] % newbounds
else:
_start_point = start_point
_start_point_local_index = np.argmax(np.logical_and.reduce(np.isclose(neighbors, _start_point[None, :]), axis=1))
_start_point_global_index = neighbor_indices.pop(_start_point_local_index)
neighbors = np.delete(neighbors, _start_point_local_index, axis=0)
del _start_point_local_index
if DEBUGGING:
# print("start_point", start_point)
# print(neighbors.shape)
# print("neighbors")
# print(neighbors)
plt.plot(start_point[0], start_point[1], color="black",
linestyle="", marker=".", markersize=40, zorder=0)
plt.plot(_start_point[0], _start_point[1], color="black",
linestyle="", marker=".", markersize=40, zorder=0)
plt.plot(neighbors[:, 0], neighbors[:, 1], color="blue",
linestyle="", marker=".", markersize=50, zorder=0)
a = final_point - start_point
if np.allclose(a, 0):
closest_index = _start_point_global_index
else:
# print("neighbors", neighbors)
b = neighbors - start_point[None, :]
# take care of the periodic boundaries
if hasattr(KDTREE, "bounds"):
newbounds = np.ones_like(KDTREE.bounds)
# newbounds = np.array(KDTREE.bounds)
# newbounds[newbounds <= 0] = np.infty
shiftbounds = 0.5 * np.ones_like(newbounds)
warn.warn("using cheap fix for periodic boundary here")
# if DEBUGGING:
# print("a", a)
# print("b", b)
a = (a + shiftbounds) % newbounds - shiftbounds
b = (b + shiftbounds[None, :]) % newbounds[None, :] - shiftbounds[None, :]
# if DEBUGGING:
# print("a", a)
# print("b", b)
_p = np.tensordot(a, b, axes=[(0,), (1,)])
distances_to_line_squared = np.sum(b * b, axis=1) - \
_p * np.abs(_p) / np.dot(a, a) # the signum of _p is used to find the correct side
_n_index = np.argmin(distances_to_line_squared)
closest_index = neighbor_indices[_n_index]
final_state = STATES[closest_index]
if DEBUGGING:
print("evaluation:", start_point, "via", final_point, "to", KDTREE.data[closest_index], "with state", final_state)
return closest_index, final_state
def state_evaluation_kdtree(traj):
"""Get the closest point to the end of the trajectory in the grid using KDTREE.
**Note:** Used internally during the viability computations.
"""
# global DEBUGGING
point = traj[-1]
if OUT_OF_BOUNDS:
projected_values = np.zeros_like(point)
dim = point.shape[0]
for i in range(dim):
projected_values += BASIS_VECTORS_INV[:, i] * point[i]
out = False
for i in range(dim):
if (BOUNDS[i, 0] > projected_values[i]) or (BOUNDS[i, 1] < projected_values[i]):
out = True
break
if out:
# DEBUGGING = False
# if DEBUGGING:
# print("out-of-bounds")
return -1, OUT_OF_BOUNDS_STATE
_, tree_index = KDTREE.query(point, 1)
# DEBUGGING = DEBUGGING and (STATES[tree_index] in [-1, 1, -2, 2])
# if DEBUGGING:
# print("evaluation:", traj[0], "via", traj[1], "to", KDTREE.data[tree_index], "with state", STATES[tree_index])
return tree_index, STATES[tree_index]
# def state_evaluation_kdtree(traj):
# point = traj[-1]
# if OUT_OF_BOUNDS:
# projected_values = np.tensordot(BASIS_VECTORS_INV, point, axes=[(1,), (0,)])
# if np.any( BOUNDS[:, 0] > projected_values) or np.any( BOUNDS[:, 1] < projected_values ): # is the point out-of-bounds?
# if DEBUGGING:
# print("out-of-bounds")
# return OUT_OF_BOUNDS_STATE
# _, tree_index = KDTREE.query(point, 1)
# return tree_index, STATES[tree_index]
def pre_calculation_hook_kdtree(coordinates, states,
is_sunny=None,
periodicity=None,
grid_type=None,
out_of_bounds=True):
"""Do all prepratory stuff for a viability computation.
**Note:** Usually used internally only.
This function creates the KDTREE, makes a variety of variables globally accessible.
"""
global KDTREE, STATES, BASIS_VECTORS, BASIS_VECTORS_INV, BOUNDS, OUT_OF_BOUNDS
STATES = states
dim = np.shape(coordinates)[-1]
periodicity_bool = (periodicity > 0)
printv("creating k-d tree ...", end=" ", flush=True)
# check, if there are periodic boundaries and if so, use different tree form
if np.any(periodicity_bool):
assert dim == len(periodicity_bool), "Given boundaries don't match with " \
"dimensions of coordinates. " \
"Write '-1' if boundary is not periodic!"
assert (grid_type in ["orthogonal"]) or ((grid_type in ["simplex-based"]) and not np.any(periodicity_bool[1:])),\
"does PeriodicCKDTREE support the periodicity for your grid?"
KDTREE = periodkdt.PeriodicCKDTree(periodicity, coordinates)
else:
KDTREE = spat.cKDTree(coordinates)
printv("done", date_behind=True)
OUT_OF_BOUNDS = not (out_of_bounds is False)
if OUT_OF_BOUNDS:
if out_of_bounds is True:
out_of_bounds = [[True, True]] * dim
out_of_bounds = np.asarray(out_of_bounds)
if out_of_bounds.shape == (dim,):
out_of_bounds = np.repeat(out_of_bounds[:, None], 2, axis=1)
assert out_of_bounds.shape == (dim, 2)
dim = coordinates.shape[-1]
BOUNDS = np.zeros((dim, 2))
if grid_type == "orthogonal":
basis_vectors = np.eye(dim)
elif grid_type == "simplex-based":
basis_vectors = p_series(1, dim)
BASIS_VECTORS = basis_vectors
BASIS_VECTORS_INV = la.inv(BASIS_VECTORS)
for d in range(dim):
if periodicity_bool[d]:
BOUNDS[d, :] = -np.inf, np.inf
# this basically means, because of periodicity, the trajectories
# cannot run out-of-bounds
else:
# project the values on the basis vector with a scalar product
# for that reason, basis vectors need to be normalized
# projected_values = np.tensordot(coordinates, basis_vectors[:,d], axes=[(1,), (0,)])
# actually the idea above is correct and this is simply the result
# combined with the checking whether out-of-bounds should be
# applied
BOUNDS[d, :] = np.where(out_of_bounds[d], (-BOUNDS_EPSILON, 1 + BOUNDS_EPSILON), (-np.infty, np.infty))
# BOUNDS[d,:] = np.min(projected_values) - BOUNDS_EPSILON, np.max(projected_values) + BOUNDS_EPSILON
# BOUNDS[d,:] = np.min(coordinates[:,d]) - BOUNDS_EPSILON, np.max(coordinates[:,d]) + BOUNDS_EPSILON
projected_values = np.tensordot(coordinates, BASIS_VECTORS_INV, axes=[(1,), (1,)])
assert np.all( BOUNDS[None, :, 0] < projected_values) \
and np.all( BOUNDS[None, :, 1] > projected_values ),\
"BOUNDS and coordinates do not fit together, did you set the correct grid_type argument?"
class RemovingSetWrapper(set):
"""RemovingSetWrapper removes elements on iteration.
**Note:** Usually used internally only.
When iterating over RemovingSetWrapper, the iterated element is removed.
This manages basically which points are still needed to iterate over in the viability
algorithm.
"""
def __iter__(self):
return self
def __next__(self):
if len(self):
return self.pop()
else:
raise StopIteration
def _viability_kernel_step(coordinates, states, *,
good_states, bad_states, succesful_states, work_states,
evolutions, state_evaluation,
use_numba=False,
nb_nopython=False):
"""do a single step of the viability calculation algorithm by checking which points stay immediately within the good_states"""
changed = False
assert len(coordinates.shape) == 2, "use flattened grid, plz"
max_index = coordinates.shape[0]
viability_single_point = _generate_viability_single_point(evolutions, state_evaluation,
use_numba=use_numba, nb_nopython=nb_nopython)
COUNTER = 0
neighbors = RemovingSetWrapper(range(max_index))
for index in neighbors: # iterate over all indices and, if one is change, add the neighbors again (if necessary)
COUNTER += 1
old_state = states[index]
if old_state in work_states:
state_index = work_states.index(old_state)
succesful_state = succesful_states[state_index]
bad_state = bad_states[state_index]
new_state = viability_single_point(index, coordinates, states, good_states,
succesful_state, bad_state)
if new_state != old_state:
changed = True
states[index] = new_state
# get_neighbor_indices(index, shape, neighbor_list = neighbors)
get_neighbor_indices_via_cKD(index, neighbor_list=neighbors)
print("FINAL COUNTER", COUNTER)
return changed
def get_neighbor_indices_via_cKD(index, neighbor_list=[]):
"""extend 'neighbor_list' by all neighbors that are closer than STEPSIZE + BOUNDS_EPSILON
"""
index = np.asarray(index).astype(int)
tree_neighbors = KDTREE.query_ball_point(KDTREE.data[index].flatten(), STEPSIZE + BOUNDS_EPSILON)
neighbor_list.update(tree_neighbors)
# neighbor_list.extend(tree_neighbors)
return neighbor_list
# def get_neighbor_indices(index, shape, neighbor_list=[]):
# """append all neighboring indices of 'index' to 'neighbor_list' if they are within 'shape'"""
#
# index = np.asarray(index)
# shape = np.asarray(shape)
#
# for diff_index in it.product([-1, 0, 1], repeat=len(index)):
# diff_index = np.asarray(diff_index)
# new_index = index + diff_index
#
# if np.count_nonzero(diff_index) and np.all( new_index >= 0 ) and np.all( new_index < shape ):
# neighbor_list.append(tuple(new_index))
#
# return neighbor_list
def _viability_kernel(coordinates, states, *,
good_states, bad_state, succesful_state, work_state, evolutions,
state_evaluation,
periodic_boundaries=[]
):
"""calculate the viability kernel by iterating through the viability kernel steps
until convergence (no further change)"""
# assert coordinates.shape[:-1] == states.shape[:-1], "'coordinates' and 'states' don't match in shape"
# assert "x_step" in globals() # needs to be set by the user for now ... will be changed later
assert "BOUNDS_EPSILON" in globals() # needs to be set by the user for now ... will be changed later
# assert "MAX_FINAL_DISTANCE" in globals() # needs to be set by the user for now ... will be changed later
assert "MAX_NEIGHBOR_DISTANCE" in globals() # needs to be set by the user for now ... will be changed later
assert "STEPSIZE" in globals() # as the above comments
# global x_half_step
# x_half_step = x_step/2
try:
work_states = list(work_state)
except TypeError:
work_states = [work_state]
try:
succesful_states = list(succesful_state)
except TypeError:
succesful_states = [succesful_state]
try:
bad_states = list(bad_state)
except TypeError:
bad_states = [bad_state]
# actually only one step is needed due to the recursive checks (i.e. first
# checking all neighbors of a point that changed state)
return _viability_kernel_step(coordinates, states,
good_states=good_states,
bad_states=bad_states,
succesful_states=succesful_states,
work_states=work_states,
evolutions=evolutions,
state_evaluation=state_evaluation)
def _viability_capture_basin(coordinates, states, *,
target_states, reached_state, bad_state, work_state, evolutions,
state_evaluation=state_evaluation_kdtree
):
"""reuse the viability kernel algorithm to calculate the capture basin"""
if work_state in states and any( ( target_state in states for target_state in target_states) ):
# num_work = np.count_nonzero(work_state == states)
_viability_kernel(coordinates, states,
good_states=target_states + [reached_state],
bad_state=work_state,
succesful_state=reached_state,
work_state=work_state,
evolutions=evolutions,
state_evaluation=state_evaluation
)
# changed = (num_work == np.count_nonzero(reached_state == states))
else:
printv("capture basin: empty work or target set", verbosity=2)
# changed = False
# all the points that still have the state work_state are not part of the capture basin and are set to be bad_states
changed = (work_state in states)
states[ states == work_state ] = bad_state
return changed
# below are just helper functions
def print_evaluation(states, print_empty_regions=True, print_unknown=True):
"""Print an Evaluation of the results of an TSM-Computation."""
total = states.size
total_length = str(len(str(total)))
num_sum = 0
current_globals = globals()
print("Evaluation (relative normalized Volume):")
for region in REGIONS:
num = np.count_nonzero(states == current_globals[region])
if print_empty_regions or num > 0:
num_sum += num
print(("{:<13} ({:>2}): {:>6.2f}% ( {:>"+total_length+"} )").format(region, globals()[region], num / total * 100, num))
print()
if print_unknown and num_sum != total:
print(("{:<15}: {:>6.2f}% ( {:>"+total_length+"} )").format("UNKNOWN", (total - num_sum) / total * 100, total - num_sum))
print()
def plot_points(coords, states, markersize=15, plot_unset=False):
"""plot the current states in the viability calculation as points"""
assert set(states.flatten()).issubset(COLORS)
plot_colors = list(COLORS)
if not plot_unset:
plot_colors.pop(UNSET)
for color_state in plot_colors:
plt.plot(coords[ states == color_state, 0], coords[ states == color_state, 1], color=COLORS[color_state],
linestyle="", marker=".", markersize=markersize, zorder=0)
def plot_areas(coords, states):
"""plot the current states in the viability calculation as areas"""
states = states.flatten()
assert set(states).issubset(COLORS)
coords = np.reshape(coords, states.shape + (-1,))
x, y = coords[:, 0], coords[:, 1]
color_states = sorted(COLORS)
cmap = mpl.colors.ListedColormap([ COLORS[state] for state in color_states ])
bounds = color_states[:1] + [ state + 0.5 for state in color_states[:-1]] + color_states[-1:]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
plt.tripcolor(x, y, states, cmap=cmap, norm=norm, shading="gouraud")
def make_run_function(rhs,
ordered_params,
offset,
scaling_vector,
returning="linear",
use_numba=True,
nb_nopython=True,
rescaling_epsilon=1e-6,
):
"""Create a *run-function* from a right-hand side of an ordinary differential equation.
The *run-function* takes a starting point and a time and returns a trajectory that
follows the corresponding ODE. It basically provides the step from a generic ODE to
a map that gives the next point. The reason the return value is actually a trajectory
and not just the next point is simply future compatibility.
**Note:** This function automatically rescales the RHS to work on [0, 1]^dim and homogenizes
the time (see https://arxiv.org/abs/1706.04542).
Parameters
----------
rhs : callable
Function that representes the RHS of the ODE. The first two arguments should be
the point `x` in state space and the time `t`. The following arguments should be
parameters that are need to be given, if necessary.
ordered_params : tuple
The parameters needed for rhs.
offset : array-like
output from grid rescaling, see `generate_grid`
scaling_vector : array-like
output from grid rescaling, see `generate_grid`
returning : str, default : "linear"
only change of you know what you do
use_numa : bool, default : True
Should numba be used?
nb_nb_nopython : bool, default : True,
If numba is used, force nopython-mode?
rescaling_rescaling_epsilon : float, default : 1e-6
When homogenizing the time, which \epsilong value should be used. see https://arxiv.org/abs/1706.04542
Returns
-------
callable
The corresponding run-function.
"""
S = np.array(scaling_vector, order="C", copy=True)
Sinv = np.array(la.inv(S), order="C", copy=True)
# ----------------------------------------
def rhs_scaled_to_one_PS(y, t):
"""\
for 2D plotting of the whole phase space plot
rescales space only, because that should be enough for the phase space plot
"""
x = offset[:, None, None] + np.tensordot(Sinv, y, axes=[(1,), (0,)])
val = rhs(x, t, *ordered_params) # calculate the rhs
val = np.tensordot(S, val, axes=[(1,), (0,)])
return val
# ----------------------------------------
if use_numba:
@nb.jit(nopython=nb_nopython)
def rhs_rescaled(y, t, *args):
dim = len(y)
# because of the rescaling to 1 in every dimension
# transforming y -> x
x = np.copy(offset)
for i in range(dim):
x += Sinv[:, i] * y[i]
# x += Sinv[:, i] * y[i]
dx = rhs(x, t, *args)
# transforming dx -> dy
dy = np.zeros_like(y)
for i in range(dim):
dy += S[:, i] * dx[i]
# dy += S[:, i] * dx[i]
# normalization of dy
dy_norm = 0.
for i in range(dim):
dy_norm += dy[i]*dy[i]
dy_norm = math.sqrt(dy_norm)
# check whether it's a fixed point
if dy_norm == 0.:
return np.zeros_like(dy)
return dy / (dy_norm + rescaling_epsilon)
else:
def rhs_rescaled(y, t, *args):
# because of the rescaling to 1 in every dimension
# transforming y -> x
x = offset + np.dot(Sinv, y)
# transforming dx -> dy
dy = np.dot(S, rhs(x, t, *args)) # calculate the rhs
# normalization of dy
dy_norm = np.sqrt(np.sum(dy ** 2, axis=-1))
if dy_norm == 0.:
return np.zeros_like(dy)
return dy / (dy_norm + rescaling_epsilon)
if use_numba:
@nb.jit(nopython=nb_nopython)
def normalized_linear_approximation(x, dt):
xdot = rhs_rescaled(x, dt, *ordered_params)
traj = np.empty((2, x.shape[0]))
traj[0] = x
if np.any(np.isinf(xdot)): # raise artifiially the warning if inf turns up
# warn.warn("got a inf in the RHS function; assume {!s} to be a stable fixed point and returning the starting point".format(x),
# category=RuntimeWarning)
traj[1] = traj[0]
else:
traj[1] = x + xdot*dt
return traj
else:
def normalized_linear_approximation(x, dt):
xdot = rhs_rescaled(x, dt, *ordered_params)
traj = np.array([x, x + xdot*dt])
if np.any(np.isinf(xdot)): # raise artifiially the warning if inf turns up
warn.warn("got a inf in the RHS function; assume {!s} to be a stable fixed point and returning the starting point".format(x),
category=RuntimeWarning)
traj[1] = traj[0]
if DEBUGGING:
p = traj[1]
# plot the point, but a bit larger than the color one later
plt.plot(p[0], p[1], color="red",
linestyle="", marker=".", markersize=45, zorder=0)
elif DEBUGGING:
plt.plot(traj[:, 0], traj[:, 1], color="red", linewidth=1)
return traj
# @nb.jit
# def distance_normalized_rhs(x, lam, x0, *args):
# val = rhs_scaled_to_one(x, lam, *args) # calculate the rhs
# if lam == 0:
# return val / np.sqrt(np.sum( val ** 2, axis=-1) )
# return val * lam / np.sum( (x-x0) * val, axis=-1)
# @helper.remembering(remember=remember)
# def integration(p, stepsize):
# if DEBUGGING:
# integ_time = np.linspace(0, stepsize, 100)
# else:
# integ_time = [0, stepsize]
# try:
# with helper.stdout_redirected():
# traj = integ.odeint(distance_normalized_rhs, p, integ_time,
# args=(p,) + ordered_params,
# printmessg = False
# )
# if np.any(np.isnan(traj[-1])): # raise artifiially the warning if nan turns up
# raise integ.odepack.ODEintWarning("got a nan")
# except integ.odepack.ODEintWarning:
# warn.warn("got an integration warning; assume {!s} to be a stable fixed point and returning the starting point".format(p),
# category=RuntimeWarning)
# if DEBUGGING:
# # plot the point, but a bit larger than the color one later
# plt.plot(p[0], p[1], color = "red",
# linestyle = "", marker = ".", markersize = 45 ,zorder=0)
# return np.asarray([p, p])
#
# if DEBUGGING:
# plt.plot(traj[:, 0], traj[:, 1], color="red", linewidth=3)
# return np.asarray([traj[0], traj[-1]])
# else:
# return traj
if returning == "linear":
return normalized_linear_approximation
elif returning == "PS":
return rhs_scaled_to_one_PS
else:
raise NameError("I don't know what to do with returning={!r}".format(returning))
def scaled_to_one_sunny(is_sunny, offset, scaling_vector):
"""Scale the is_sunny function so it operates on [0, 1]^dim."""
S = scaling_vector
Sinv = la.inv(S)
def scaled_sunny(grid):
new_grid = np.tensordot(grid, Sinv, axes=[(1,), (1,)]) + offset[None, :]
# new_grid = backscaling_grid(grid, scaling_vector, offset)
# new_grid = np.dot(Sinv, grid) + offset
val = is_sunny(new_grid) # calculate the rhs
return val # normalize it
return scaled_sunny
# def trajectory_length(traj):
# return np.sum( la.norm( traj[1:] - traj[:-1], axis=-1) )
# def trajectory_length_index(traj, target_length):
# lengths = np.cumsum( la.norm( traj[1:] - traj[:-1], axis=-1) )
#
# if target_length < lengths[-1]:
# return traj.shape[0] # incl. last element
# index_0, index_1 = 0, traj.shape[0] - 1
#
# while index_0 not in [index_1, index_1 - 1]:
# middle_index = int( (index_0 + index_1)/2 )
#
# if lengths[middle_index] <= target_length:
# index_0 = middle_index
# else:
# index_1 = middle_index
#
# return index_1
def backscaling_grid(grid, scaling_vector, offset):
"""Scale a grid back( after computation) from [0, 1]^dim to the original state space."""
S = scaling_vector
Sinv = la.inv(S)
new_grid = np.tensordot(grid, Sinv, axes=[(1,), (1,)]) + offset[None, :]
return new_grid
def reset_initial_states(coordinates, states):
# All initially given states are set to positive counterparts
# coordinates is given because this is the standard for a post_computation_hook of topology_classification (see there)
states[(states < UNSET)] *= -1
def set_global_status(*args, print_verbosity=None):
"""Setting the global Status of a Computation so it can be read out in case of Errors."""
assert not STATUS_PREFIX is None, "STATUS_PREFIX has to be set, maybe you found a bug?"
global STATUS
STATUS = STATUS_INFIX.join((STATUS_PREFIX,) + args)
if print_verbosity is None:
print_verbosity = 2
if STATUS_PREFIX == STATUS_TOPOLOGY:
if args[1] == STATUS_PREPARATION:
print_verbosity = 1
printv(STATUS, verbosity=print_verbosity)
def get_global_status():
"""Return the current Status of a computation."""
return STATUS
def topology_classification(coordinates, states, default_evols, management_evols, is_sunny,
periodic_boundaries=[],
compute_eddies=False,
pre_calculation_hook=pre_calculation_hook_kdtree, # None means nothing to be done
state_evaluation=state_evaluation_kdtree,
post_computation_hook=reset_initial_states,
grid_type="orthogonal",
out_of_bounds=True, # either bool or bool array with shape (dim, ) or shape (dim, 2) with values for each boundary
remember_paths=False,
verbosity=0,
stop_when_finished=TOPOLOGY_STEP_LIST[-1], # means everything goes
):
"""Estimate different regions of the state space using viability theory algorithms.
This function computes the Topology of Sustainable Management (TSM) classification of the state space (see [1] for mathematical details).
The first application can be found in [2].
[1] http://www.earth-syst-dynam.net/7/21/2016/esd-7-21-2016.html
[2] https://arxiv.org/abs/1706.04542
*Note:* A `state` is an integer referring to a certain region (in the sense of TSM), corresponding as to how they are defined in the header of this file
Parameters
----------
coordinates : array-like
Grid used for the computation, shape (n0, dim) where n0 is the total number of points and dim the dimension of the system
states : array-like
associates to each grid point the corresponding state. negative values correspond to preset values given by the user. **The results will be saved in here.**
compute_eddies : bool, default : True
Should the Eddies be computed as well. As indicated in [2], this may take quite a bit of computational power and is hence switched of generally.
pre_pre_calculation_hook : callable, default : pre_pre_calculation_hook_kdtree
ignore if you don't know what to do
state_evaluation : callable, default : state_evaluation_kdtree
ignore if you don't know what to do
post_computation_hook : callable, default : reset_initial_states
ignore if you don't know what to do
grid_type : str, default : "orthogonal"
out_of_bounds : bool, default : True
Is outside of the grid a undesirable region (in the sense of TSM)?
remember_paths : bool, default : False
Remember the paths that have been used. This is actually more of a hack and should not really be used.
verbosity : int, default : 0
stop_when_finished : str, default : ''
For Debugging only: stop when a certain operation has finished. See TOPOLOGY_STEP_LIST for the list of possible values.
"""
global VERBOSITY
VERBOSITY = verbosity
global STATUS_PREFIX
STATUS_PREFIX = STATUS_TOPOLOGY
current_step = 0
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_PREPARATION)
if isinstance(stop_when_finished, str):
stop_when_finished = TOPOLOGY_STEP_LIST.index(stop_when_finished)
assert isinstance(stop_when_finished, int) and stop_when_finished >= 0
coordinates = np.asarray(coordinates)
states = np.asarray(states)
grid_size, dim = coordinates.shape
assert states.shape == (grid_size,), "coordinates and states input doesn't match"
if remember_paths:
printv("generating PATHS and PATHS_LAKE arrays")
global PATHS, PATHS_LAKE
PATHS = {}
PATHS["reached point"] = np.copy(coordinates) # for the target point
PATHS["next point index"] = np.ones((grid_size,), dtype=PATHS_INDEX_TYPE) * PATHS_INDEX_DEFAULT # the coordinate where the target point get's associated to
PATHS["choice"] = np.ones((grid_size,), dtype=PATHS_MANAGEMENT_TYPE) * PATHS_MANAGEMENT_DEFAULT # for the number of the management option
PATHS_LAKE = {}
PATHS_LAKE["reached point"] = np.copy(PATHS["reached point"])
PATHS_LAKE["next point index"] = np.copy(PATHS["next point index"])
PATHS_LAKE["choice"] = np.copy(PATHS["choice"])
# PATHS = (np.copy(coordinates), # for the target point
# -np.ones((grid_size,), dtype=int), # the coordinate where the target point get's associated to
# -np.ones((grid_size,), dtype=np.int16) ) # for the number of the management option
if periodic_boundaries == []:
periodic_boundaries = - np.ones(dim)
periodic_boundaries = np.asarray(periodic_boundaries)
if pre_calculation_hook is not None:
# run the pre-calculation hook (defaults to creation of the KD-Tree)
pre_calculation_hook(coordinates, states,
is_sunny=is_sunny,
periodicity=periodic_boundaries,
grid_type=grid_type,
out_of_bounds=out_of_bounds)
# make sure, evols can be treated as lists
default_evols = list(default_evols)
management_evols = list(management_evols)
all_evols = default_evols + management_evols
# better remove this and use directly the lower level stuff, see issue #13
viability_kwargs = dict(
state_evaluation=state_evaluation,
)
# shelter_empty = False
# backwater_empty = False
if all_evols:
if not default_evols:
printv('no default dynamics given, skipping upstream')
current_step += 3
else:
# shelter computation
current_step += 1
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_PREPARATION)
states[(states == UNSET) & is_sunny(coordinates)] = SHELTER # initial state for shelter calculation
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION)
_viability_kernel(coordinates, states,
good_states=[SHELTER, -SHELTER],
bad_state=UNSET,
succesful_state=SHELTER,
work_state=SHELTER,
evolutions=default_evols,
**viability_kwargs)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_DONE)
if stop_when_finished == "shelter":
# do the post computation hook (default, setting negative states positive)
# and then exit
post_computation_hook(coordinates, states)
return
if not np.any(states == SHELTER): # shelter is empty?
printv('shelter empty, skip rest of upstream')
current_step += 2
else:
current_step += 1
if not management_evols:
printv('no management dynamics given, skipping glade')
else:
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_PREPARATION)
states[(states == UNSET) & is_sunny(coordinates)] = SUNNY_UP
# glade computation
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION)
_viability_capture_basin(coordinates, states,
target_states=[SHELTER, -SHELTER],
reached_state=GLADE,
bad_state=UNSET,
work_state=SUNNY_UP,
evolutions=all_evols, **viability_kwargs)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_DONE)
if stop_when_finished <= current_step:
# do the post computation hook (default, setting negative states positive)
# and then exit
post_computation_hook(coordinates, states)
return
current_step += 1
# computation remaining upstream dark and sunny (containing possible lake)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_PREPARATION)
states[(states == UNSET)] = DARK_UP
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION)
_viability_capture_basin(coordinates, states,
target_states=[SHELTER, -SHELTER, GLADE, -GLADE, -SUNNY_UP, -DARK_UP, -LAKE],
reached_state=SUNNY_UP,
bad_state=UNSET,
work_state=DARK_UP,
evolutions=all_evols,
**viability_kwargs)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_POSTPROCESSING)
states[~is_sunny(coordinates) & (states == SUNNY_UP)] = DARK_UP
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_DONE)
assert current_step == TOPOLOGY_STEP_LIST.index("REMUP"), "consistency check failed, bug? ({} != {})".format(current_step, TOPOLOGY_STEP_LIST.index("REMUP"))
if stop_when_finished <= current_step:
# do the post computation hook (default, setting negative states positive)
# and then exit
post_computation_hook(coordinates, states)
return
if not management_evols:
printv('no management dynamics given, skipping lake and downstream')
current_step += 2
else:
current_step += 1
assert current_step == TOPOLOGY_STEP_LIST.index("MANAGEABLE"), "consistency check failed, bug? ({} != {})".format(current_step, TOPOLOGY_STEP_LIST.index("MANAGEABLE"))
if remember_paths:
_PATHS = PATHS
PATHS = PATHS_LAKE
# compute rest of manageable region (lake + backwaters)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_PREPARATION)
states[is_sunny(coordinates) & (states == SUNNY_UP)] = LAKE
states[is_sunny(coordinates) & (states == UNSET)] = BACKWATERS
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION)
_viability_kernel(coordinates, states,
good_states=[
SHELTER, -SHELTER, # these should not be possible to be reached
GLADE, -GLADE, # these should not be possible to be reached
LAKE, -LAKE,
BACKWATERS, -BACKWATERS
],
bad_state=[SUNNY_UP, UNSET],
succesful_state=[LAKE, BACKWATERS],
work_state=[LAKE, BACKWATERS],
evolutions=all_evols,
**viability_kwargs)
if remember_paths:
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_POSTPROCESSING)
PATHS = _PATHS
# don't need to set back PATHS_LAKE as these are just references to the dictionaries anyway
del _PATHS # just for keeping the code clean, not really necessary
# write the backwaters part to the normal mask
mask = (states == BACKWATERS)
PATHS["reached point"][mask] = PATHS_LAKE["reached point"][mask]
PATHS["next point index"][mask] = PATHS_LAKE["next point index"][mask]
PATHS["choice"][mask] = PATHS_LAKE["choice"][mask]
PATHS_LAKE["next point index"][mask] = PATHS_INDEX_DEFAULT
PATHS_LAKE["choice"][mask] = PATHS_MANAGEMENT_DEFAULT
del mask
if not np.any(states == LAKE):
printv("no lake found, removing PATHS_LAKE arrays")
PATHS_LAKE = {}
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_DONE)
if stop_when_finished <= current_step:
# do the post computation hook (default, setting negative states positive)
# and then exit
post_computation_hook(coordinates, states)
return
current_step += 1
if not np.any(states == BACKWATERS):
printv('backwater empty, skip remaining downstream')
else:
# calculate remaining downstream dark and sunny
assert current_step == TOPOLOGY_STEP_LIST.index("REMDOWN"), "consistency check failed, bug? ({} != {})".format(current_step, TOPOLOGY_STEP_LIST.index("REMDOWN"))
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_PREPARATION)
states[(states == UNSET)] = DARK_DOWN
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION)
_viability_capture_basin(coordinates, states,
target_states=[BACKWATERS, -SUNNY_DOWN, -DARK_DOWN],
reached_state=SUNNY_DOWN,
bad_state=UNSET,
work_state=DARK_DOWN,
evolutions=all_evols,
**viability_kwargs)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_POSTPROCESSING)
states[~is_sunny(coordinates) & (states == SUNNY_DOWN)] = DARK_DOWN
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_DONE)
if stop_when_finished <= current_step:
# do the post computation hook (default, setting negative states positive)
# and then exit
post_computation_hook(coordinates, states)
return
current_step += 1
# calculate trench and set the rest as preliminary estimation for the eddies
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_PREPARATION)
states[is_sunny(coordinates) & (states == UNSET)] = SUNNY_EDDIES
# look only at the coordinates with state == UNSET
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION)
_viability_capture_basin(coordinates, states,
target_states=[
SUNNY_EDDIES, -SUNNY_EDDIES,
SUNNY_ABYSS, -SUNNY_ABYSS # a tad imprecise that both negative states are in here
],
reached_state=DARK_EDDIES,
bad_state=TRENCH,
work_state=UNSET,
evolutions=all_evols,
**viability_kwargs)
if not compute_eddies:
# assume all eddies are abysses
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_POSTPROCESSING)
states[(states == SUNNY_EDDIES)] = SUNNY_ABYSS
states[(states == UNSET)] = DARK_ABYSS
states[(states == DARK_EDDIES)] = DARK_ABYSS
else:
# the preliminary estimations for sunny and dark eddie are set
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION, STATUS_EDDIES_SUNNY, STATUS_PREPARATION)
states[(states == SUNNY_EDDIES)] = UNSET
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION, STATUS_EDDIES_SUNNY, STATUS_COMPUTATION)
_viability_capture_basin(coordinates, states,
target_states=[DARK_EDDIES, -DARK_EDDIES],
reached_state=SUNNY_EDDIES,
bad_state=SUNNY_ABYSS,
work_state=UNSET,
evolutions=all_evols,
**viability_kwargs)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION, STATUS_EDDIES_SUNNY, STATUS_DONE)
for num in range(MAX_ITERATION_EDDIES):
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION, STATUS_EDDIES_DARK, STATUS_PREPARATION)
states[(states == DARK_EDDIES)] = UNSET
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION, STATUS_EDDIES_DARK, STATUS_COMPUTATION)
changed = _viability_capture_basin(coordinates, states,
target_states=[SUNNY_EDDIES, -SUNNY_EDDIES],
reached_state=DARK_EDDIES,
bad_state=DARK_ABYSS,
work_state=UNSET,
evolutions=all_evols,
**viability_kwargs)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION, STATUS_EDDIES_DARK, STATUS_DONE)
if not changed:
break
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION, STATUS_EDDIES_SUNNY, STATUS_PREPARATION)
states[(states == SUNNY_EDDIES)] = UNSET
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION, STATUS_EDDIES_SUNNY, STATUS_COMPUTATION)
changed = _viability_capture_basin(coordinates, states,
target_states=[DARK_EDDIES, -DARK_EDDIES],
reached_state=SUNNY_EDDIES,
bad_state=SUNNY_ABYSS,
work_state=UNSET,
evolutions=all_evols,
**viability_kwargs)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_COMPUTATION, STATUS_EDDIES_SUNNY, STATUS_DONE)
if not changed:
break
else:
warn.warn("reached MAX_ITERATION_EDDIES = %i during the Eddies calculation"%MAX_ITERATION_EDDIES)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_DONE)
current_step += 1
assert current_step == len(TOPOLOGY_STEP_LIST) - 2, "consistency check failed, bug? ({} != {})".format(current_step, len(TOPOLOGY_STEP_LIST) - 2)
# there is a -2 in the assert statement because a trailing '""' is added to 'TOPOLOGY_STEP_LIST' in order to have '""' as the default for 'stop_when_finished'
# computation is done,
# do the post computation hook (default, setting negative states positive)
# and then exit
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_POSTPROCESSING)
post_computation_hook(coordinates, states)
set_global_status(TOPOLOGY_STEP_LIST[current_step], STATUS_DONE)
# clean up
global STATUS
STATUS = ""
STATUS_PREFIX = None
return
|
limvi-licef/NATAssistanceAR
|
Documentation/hololens/search/classes_5.js
|
var searchData=
[
['holoobjectdetectionapp',['HoloObjectDetectionApp',['../class_application_1_1_holo_object_detection_app.html',1,'Application']]]
];
|
matslindh/codingchallenges
|
knowit2020/01.py
|
<filename>knowit2020/01.py
vals = sorted([int(x) for x in open("input/01").read().split(',')])
for idx, val in enumerate(vals):
if val != (idx+1):
print(idx+1)
break
|
tiglabs-workspace/jmq
|
jmq-common/toolkit/src/main/java/com/ipd/jmq/toolkit/config/BooleanBinder.java
|
package com.ipd.jmq.toolkit.config;
import com.ipd.jmq.toolkit.config.annotation.BooleanBinding;
import com.ipd.jmq.toolkit.reflect.Reflect;
import com.ipd.jmq.toolkit.reflect.ReflectException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* 布尔值绑定
* Created by hexiaofeng on 16-8-29.
*/
public class BooleanBinder implements Binder {
public static final BooleanBinder INSTANCE = new BooleanBinder();
@Override
public void bind(final Field field, final Annotation annotation, final Object target, final Context context) throws
ReflectException {
if (field == null || annotation == null || target == null || context == null || !(annotation instanceof
BooleanBinding)) {
return;
}
BooleanBinding binding = (BooleanBinding) annotation;
Class<?> type = field.getType();
if (type.isAssignableFrom(boolean.class) || type.isAssignableFrom(Boolean.class)) {
boolean value = context.getBoolean(binding.key(), binding.defaultValue());
Reflect.set(field, target, value);
}
}
}
|
ChrisSmith/BuildMonitor
|
buildmonitor2/src/main/java/org/collegelabs/buildmonitor/buildmonitor2/tc/ServiceHelper.java
|
package org.collegelabs.buildmonitor.buildmonitor2.tc;
import android.util.Base64;
import com.facebook.stetho.okhttp.StethoInterceptor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.OkUrlFactory;
import org.collegelabs.buildmonitor.buildmonitor2.BuildConfig;
import org.collegelabs.buildmonitor.buildmonitor2.storage.Database;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;
import rx.Observable;
import java.util.concurrent.TimeUnit;
public class ServiceHelper {
public static TeamCityService getService(Credentials credentials){
return getCommonBuilder(credentials)
.build()
.create(TeamCityService.class);
}
private static RestAdapter.Builder getCommonBuilder(Credentials credentials) {
Gson gson = new GsonBuilder()
.setDateFormat("yyyyMMdd'T'HHmmssZ")
.create();
final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s
final int READ_TIMEOUT_MILLIS = 60 * 1000; // 60s
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
if(BuildConfig.DEBUG){
client.networkInterceptors().add(new StethoInterceptor());
}
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(getEndpoint(credentials))
.setClient(new OkClient(client))
.setLogLevel(RestAdapter.LogLevel.BASIC)
.setRequestInterceptor(new JsonHeaderInterceptor())
.setConverter(new GsonConverter(gson));
if(!credentials.isGuest){
String userAndPassword = credentials.username + ":" + credentials.password;
final String authHeader = "Basic " + Base64.encodeToString(userAndPassword.getBytes(), Base64.NO_WRAP);
builder.setRequestInterceptor(new BasicAuthInterceptor(authHeader));
}
return builder;
}
public static String getEndpoint(Credentials credentials){
HttpUrl.Builder endpoint = HttpUrl.parse(credentials.server).newBuilder();
if(credentials.isGuest){
endpoint.addPathSegment("guestAuth");
}
return endpoint
.build()
.toString();
}
}
|
waltechel/AlgorithmJava
|
src/MainJAEHASAFE_SongTaeheon.java
|
<reponame>waltechel/AlgorithmJava<gh_stars>1-10
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class MainJAEHASAFE_SongTaeheon {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int moveCount = 0;
static String[] inputs = new String[51];
public static void main(String[] args) throws IOException {
int testCount = readTestCount();
for (int i = 0; i < testCount; i++) {
input();
solve();
}
}
private static void solve() {
int result = 0;
boolean isClockwise = true;
for (int i = 0; i < moveCount; i++) {
int ticks = findTicks(inputs[i], inputs[i + 1], isClockwise);
result += ticks;
isClockwise = !isClockwise;
}
System.out.println(result);
}
private static int findTicks(String prev, String next, boolean isClockwise) {
int result = 0;
String doubledNext = next + next;
int[] pi = createPartialTable(prev);
int begin = 0;
int matched = 0;
while (begin + matched < doubledNext.length()) {
if (doubledNext.charAt(begin + matched) == prev.charAt(matched)) {
matched += 1;
if (matched == prev.length()) {
result = begin;
if (isClockwise) { // clockWise면 제일 먼저 걸린게 최단
break;
} else { // counterClockwise면 제일 나중에 걸린게 최단
begin = begin + matched - pi[matched - 1];
matched = pi[matched - 1];
}
}
} else {
if (matched == 0) {
begin += 1;
} else {
begin = begin + matched - pi[matched - 1];
matched = pi[matched - 1];
}
}
}
if (!isClockwise) {
result = prev.length() - result;
}
if (result == 0) {
result = prev.length();
}
return result;
}
private static int[] createPartialTable(String str) {
int[] pi = new int[str.length()];
int begin = 1;
int matched = 0;
while (begin + matched < str.length()) {
if (str.charAt(begin + matched) == str.charAt(matched)) {
pi[begin + matched] = matched + 1;
matched += 1;
} else {
if (matched == 0) {
begin += 1;
} else {
begin = begin + matched - pi[matched - 1];
matched = pi[matched - 1];
}
}
}
return pi;
}
private static int readTestCount() throws IOException {
StringTokenizer stTestCount = new StringTokenizer(br.readLine());
return Integer.parseInt(stTestCount.nextToken()); // C
}
private static void input() throws IOException {
StringTokenizer st = new StringTokenizer(br.readLine());
moveCount = Integer.parseInt(st.nextToken());
for (int i = 0; i < moveCount + 1; i++) {
StringTokenizer stStr = new StringTokenizer(br.readLine());
inputs[i] = stStr.nextToken();
}
}
}
|
jingetiema2100/MicroCommunity
|
java110-utils/src/main/java/com/java110/utils/constant/ServiceCodeStoreAttrConstant.java
|
package com.java110.utils.constant;
/**
* 商户属性常量类
* Created by wuxw on 2017/5/20.
*/
public class ServiceCodeStoreAttrConstant {
/**
* 添加 商户属性
*/
public static final String ADD_STOREATTR = "storeAttr.saveStoreAttr";
/**
* 修改 商户属性
*/
public static final String UPDATE_STOREATTR = "storeAttr.updateStoreAttr";
/**
* 删除 商户属性
*/
public static final String DELETE_STOREATTR = "storeAttr.deleteStoreAttr";
/**
* 查询 商户属性
*/
public static final String LIST_STOREATTRS = "storeAttr.listStoreAttrs";
}
|
Matko95/dvf-client-js
|
src/lib/validators/symbol.js
|
const DVFError = require('../dvf/DVFError')
module.exports = (dvf, symbol) => {
if (!symbol) {
throw new DVFError('ERR_INVALID_SYMBOL')
}
const from = symbol.toString().split(':')[0]
const to = symbol.toString().split(':')[1]
if (!dvf.token.getTokenInfo(from) || !dvf.token.getTokenInfo(to)) {
throw new DVFError('ERR_INVALID_SYMBOL')
}
}
|
AuditBox/api
|
spec/views/controls/show.html.erb_spec.rb
|
<reponame>AuditBox/api
require 'rails_helper'
RSpec.describe 'controls/show', type: :view do
let(:organization) { Fabricate(:organization) }
let(:control) { Fabricate(:control, organization: organization) }
before(:each) { @control = assign(:control, control) }
it 'renders attributes in <p>' do
render
end
end
|
sphairas/sphairas-desktop
|
sphairas-libs/journal/src/org/thespheres/betula/journal/notes/JournalNotesEditor2.java
|
<gh_stars>1-10
/*
* 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.
*/
package org.thespheres.betula.journal.notes;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Properties;
import javax.swing.text.BadLocationException;
import javax.swing.text.EditorKit;
import javax.swing.text.StyledDocument;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.NbBundle;
import org.openide.util.io.NullInputStream;
import org.openide.windows.TopComponent;
/**
*
* @author boris.heithecker
*/
@NbBundle.Messages({"JournalNotesEditor2.openAction=Bemerkungen (Berichtshefte)",
"JournalNotesEditor2.displayName=Berichtsheft-Bemerkungen",
"JournalNotesEditor2.current.displayName=Berichtsheft-Bemerkungen ({0})"})
@ActionID(category = "Window", id = "org.thespheres.betula.journal.notes.JournalNotesEditor2")
@ActionReference(path = "Menu/Window/betula-project-local-windows", position = 210)
@ConvertAsProperties(dtd = "-//org.thespheres.betula.journal.notes//JournalNotesEditor2//EN",
autostore = false)
@TopComponent.OpenActionRegistration(displayName = "#JournalNotesEditor2.openAction",
preferredID = "JournalNotesEditor2")
@TopComponent.Description(preferredID = "JournalNotesEditor2",
//iconBase="SET/PATH/TO/ICON/HERE",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "properties", openAtStartup = false)
public class JournalNotesEditor2 extends AbstractJournalNotesEditor {
public JournalNotesEditor2() {
super();
}
@Override
protected synchronized void reload(EditorKit kit, StyledDocument doc) throws IOException {
final NotesSectionsProvider2 nsp = new NotesSectionsProvider2(this, doc, current);
try (Reader reader = nsp.createGuardedReader(new NullInputStream(), Charset.defaultCharset())) {
kit.read(reader, doc, 0);
} catch (BadLocationException ex) {
throw new IOException(ex);
}
}
void writeProperties(Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
// TODO store your settings
}
void readProperties(Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
}
}
|
lizeidsness/minimalist
|
app/@esri/calcite-ui-icons/js/bookmark24F.js
|
<reponame>lizeidsness/minimalist
export const bookmark24F = "M19 23l-7-4-7 4V2h14v21z";
|
robotman2412/fabric_litemod
|
src/main/java/com/robotman2412/litemod/util/CountedIngredient.java
|
<filename>src/main/java/com/robotman2412/litemod/util/CountedIngredient.java
package com.robotman2412.litemod.util;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.recipe.Ingredient;
import net.minecraft.tag.Tag;
import net.minecraft.util.PacketByteBuf;
public class CountedIngredient {
public final Ingredient ingredient;
public final int count;
public CountedIngredient(Ingredient ingredient) {
this.ingredient = ingredient;
this.count = 1;
}
public CountedIngredient(Ingredient ingredient, int count) {
this.ingredient = ingredient;
this.count = count;
}
public void write(PacketByteBuf buf) {
ingredient.write(buf);
buf.writeInt(count);
}
public boolean isApplicable(ItemStack stack) {
return ingredient.test(stack);
}
public boolean containsEnough(Inventory inventory) {
return getNumberApplicable(inventory) >= count;
}
public boolean containsEnough(Inventory inventory, int... usableSlots) {
return getNumberApplicable(inventory, usableSlots) >= count;
}
public int getNumberApplicable(Inventory inventory) {
int[] slotas = new int[inventory.getInvSize()];
for (int i = 0; i < slotas.length; i++) {
slotas[i] = i;
}
return getNumberApplicable(inventory, slotas);
}
public int getNumberApplicable(Inventory inventory, int... usableSlots) {
int found = 0;
for (int slot : usableSlots) {
ItemStack stack = inventory.getInvStack(slot);
if (ingredient.test(stack)) {
found += stack.getCount();
}
}
return found;
}
public static CountedIngredient fromJson(JsonElement jsonElement) {
return fromJSON((JsonObject) jsonElement);
}
public static CountedIngredient fromJSON(JsonObject json) {
int count = 1;
if (json.has("count")) {
count = json.get("count").getAsInt();
}
return new CountedIngredient(Ingredient.fromJson(json), count);
}
public static CountedIngredient fromTag(Tag<Item> tag, int count) {
return new CountedIngredient(Ingredient.fromTag(tag), count);
}
public static CountedIngredient fromPacket(PacketByteBuf buf) {
return new CountedIngredient(Ingredient.fromPacket(buf), buf.readInt());
}
public void consume(Inventory inventory) {
int[] slotas = new int[inventory.getInvSize()];
for (int i = 0; i < slotas.length; i++) {
slotas[i] = i;
}
consume(inventory, slotas);
}
public void consume(Inventory inventory, int... usableSlots) {
int countLeft = count;
for (int slot : usableSlots) {
ItemStack stack = inventory.getInvStack(slot);
if (ingredient.test(stack)) {
if (stack.getItem().hasRecipeRemainder()) {
countLeft --;
inventory.setInvStack(slot, new ItemStack(stack.getItem().getRecipeRemainder()));
if (countLeft <= 0) {
return;
}
}
else
{
int taken = Math.min(stack.getCount(), countLeft);
countLeft -= taken;
stack.decrement(taken);
if (countLeft <= 0) {
return;
}
}
}
}
}
}
|
evercyan/brick
|
xhttp/options.go
|
package xhttp
import (
"crypto/tls"
"time"
)
// Option ...
type Option struct {
SSLEnabled bool
TLSConfig *tls.Config
Compressed bool
HandshakeTimeout time.Duration
ResponseHeaderTimeout time.Duration
RequestTimeout time.Duration
ConnsPerHost int
RetryTimes int
}
// ----------------------------------------------------------------
// defaultOption ...
var defaultOption = &Option{
Compressed: true,
HandshakeTimeout: 30 * time.Second,
ResponseHeaderTimeout: 30 * time.Second,
RequestTimeout: 30 * time.Second,
ConnsPerHost: 5,
RetryTimes: 3,
}
// setOptionDefaultValue ...
func setOptionDefaultValue(option *Option) *Option {
if option == nil {
return defaultOption
}
if option.RequestTimeout <= 0 {
option.RequestTimeout = defaultOption.RequestTimeout
}
if option.HandshakeTimeout <= 0 {
option.HandshakeTimeout = defaultOption.HandshakeTimeout
}
if option.ResponseHeaderTimeout <= 0 {
option.ResponseHeaderTimeout = defaultOption.ResponseHeaderTimeout
}
if option.ConnsPerHost <= 0 {
option.ConnsPerHost = defaultOption.ConnsPerHost
}
if option.RetryTimes <= 0 {
option.RetryTimes = defaultOption.RetryTimes
}
return option
}
|
AndreasFagschlunger/o2xfs-xfs3-api-it
|
src/main/java/at/o2xfs/xfs/v3_30/Base330IT.java
|
<filename>src/main/java/at/o2xfs/xfs/v3_30/Base330IT.java
package at.o2xfs.xfs.v3_30;
import at.o2xfs.common.Library;
import at.o2xfs.xfs.BaseIT;
public class Base330IT extends BaseIT {
static {
Library.loadLibrary("o2xfs-xfs330-api-it-bin");
}
}
|
ulisesten/xalanc
|
src/xalanc/XPath/XNodeSet.hpp
|
<reponame>ulisesten/xalanc<filename>src/xalanc/XPath/XNodeSet.hpp
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*/
#if !defined(XNODESET_HEADER_GUARD_1357924680)
#define XNODESET_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/XPath/XPathDefinitions.hpp>
// Base class header file.
#include <xalanc/XPath/XNodeSetBase.hpp>
#include <xalanc/XPath/XPathExecutionContext.hpp>
namespace XALAN_CPP_NAMESPACE {
/**
* Class to hold XPath return types.
*/
class XALAN_XPATH_EXPORT XNodeSet : public XNodeSetBase
{
public:
typedef XPathExecutionContext::BorrowReturnMutableNodeRefList BorrowReturnMutableNodeRefList;
/**
* Create an XNodeSet from a node list.
*
* @param value Pointer to source node list. The XNodeSet will adopt the pointer.
* @param theMemoryManager The MemoryManager for the instance.
*/
XNodeSet(
BorrowReturnMutableNodeRefList& value,
MemoryManager& theMemoryManager);
/**
* Create an XNodeSet from another.
*
* @param source object to copy
* @param theMemoryManager The MemoryManager for the instance.
*/
XNodeSet(
const XNodeSet& source,
MemoryManager& theMemoryManager);
virtual
~XNodeSet();
// These methods are inherited from XNodeSetBase...
virtual const NodeRefListBase&
nodeset() const;
virtual XalanNode*
item(size_type index) const;
virtual size_type
getLength() const;
/**
* Release the node set held by the instance.
*/
void
release();
/**
* Change the value of an XNodeSet
*
* @param theValue The new value.
*/
void
set(BorrowReturnMutableNodeRefList& value);
private:
// Not implemented...
XNodeSet&
operator=(const XNodeSet&);
// Data members...
BorrowReturnMutableNodeRefList m_value;
};
}
#endif // XNODESET_HEADER_GUARD_1357924680
|
gabrielmellooliveira/fastfeet
|
frontend/src/pages/Deliveries/LookDelivery/styles.js
|
import styled, { keyframes } from 'styled-components';
import PerfectScrollbar from 'react-perfect-scrollbar';
const containerAppear = keyframes`
from {
opacity: 0;
} to {
opacity: 1;
}
`;
const divAppear = keyframes`
0% {
transform: scale(0.8);
}
50% {
transform: scale(1.1);
}
100% {
transform: scale(1);
}
`;
export const Container = styled.div`
background: rgba(0, 0, 0, 0.3);
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
animation: ${containerAppear} 100ms linear backwards;
hr {
color: #00000033;
margin: 10px 0;
opacity: 0.3;
border: 1px solid #00000033;
}
> div {
background: #fff;
padding: 5px 0;
width: 100%;
max-width: 450px;
border-radius: 4px;
animation: ${divAppear} 200ms linear backwards;
strong {
margin-bottom: 10px;
font-size: 14px;
}
p {
color: #444444;
font-size: 16px;
margin: 5px 0;
}
span {
font-weight: bold;
color: #666666;
}
img {
display: block;
max-width: 100%;
height: auto;
margin: 0 auto;
margin-top: 20px;
}
}
`;
export const Scroll = styled(PerfectScrollbar)`
max-height: 90vh;
padding: 25px;
`;
|
jingetiema2100/MicroCommunity
|
service-user/src/main/java/com/java110/user/smo/impl/OwnerAppUserInnerServiceSMOImpl.java
|
package com.java110.user.smo.impl;
import com.java110.core.base.smo.BaseServiceSMO;
import com.java110.intf.user.IOwnerAppUserInnerServiceSMO;
import com.java110.intf.user.IUserInnerServiceSMO;
import com.java110.dto.PageDto;
import com.java110.dto.owner.OwnerAppUserDto;
import com.java110.po.owner.OwnerAppUserPo;
import com.java110.user.dao.IOwnerAppUserServiceDao;
import com.java110.utils.util.BeanConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* @ClassName FloorInnerServiceSMOImpl
* @Description 绑定业主内部服务实现类
* @Author wuxw
* @Date 2019/4/24 9:20
* @Version 1.0
* add by wuxw 2019/4/24
**/
@RestController
public class OwnerAppUserInnerServiceSMOImpl extends BaseServiceSMO implements IOwnerAppUserInnerServiceSMO {
@Autowired
private IOwnerAppUserServiceDao ownerAppUserServiceDaoImpl;
@Autowired
private IUserInnerServiceSMO userInnerServiceSMOImpl;
@Override
public List<OwnerAppUserDto> queryOwnerAppUsers(@RequestBody OwnerAppUserDto ownerAppUserDto) {
//校验是否传了 分页信息
int page = ownerAppUserDto.getPage();
if (page != PageDto.DEFAULT_PAGE) {
ownerAppUserDto.setPage((page - 1) * ownerAppUserDto.getRow());
}
List<OwnerAppUserDto> ownerAppUsers = BeanConvertUtil.covertBeanList(ownerAppUserServiceDaoImpl.getOwnerAppUserInfo(BeanConvertUtil.beanCovertMap(ownerAppUserDto)), OwnerAppUserDto.class);
return ownerAppUsers;
}
@Override
public int queryOwnerAppUsersCount(@RequestBody OwnerAppUserDto ownerAppUserDto) {
return ownerAppUserServiceDaoImpl.queryOwnerAppUsersCount(BeanConvertUtil.beanCovertMap(ownerAppUserDto));
}
@Override
public int updateOwnerAppUser(@RequestBody OwnerAppUserPo ownerAppUserPo) {
Map info = BeanConvertUtil.beanCovertMap(ownerAppUserPo);
info.put("statusCd","0");
ownerAppUserServiceDaoImpl.updateOwnerAppUserInfoInstance(info);
return 0;
}
public IOwnerAppUserServiceDao getOwnerAppUserServiceDaoImpl() {
return ownerAppUserServiceDaoImpl;
}
public void setOwnerAppUserServiceDaoImpl(IOwnerAppUserServiceDao ownerAppUserServiceDaoImpl) {
this.ownerAppUserServiceDaoImpl = ownerAppUserServiceDaoImpl;
}
public IUserInnerServiceSMO getUserInnerServiceSMOImpl() {
return userInnerServiceSMOImpl;
}
public void setUserInnerServiceSMOImpl(IUserInnerServiceSMO userInnerServiceSMOImpl) {
this.userInnerServiceSMOImpl = userInnerServiceSMOImpl;
}
}
|
Prifiz/scenario
|
src/test/java/org/prifizapps/menuentities/MenuFrameTest.java
|
<filename>src/test/java/org/prifizapps/menuentities/MenuFrameTest.java
package org.prifizapps.menuentities;
import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;
import mockit.Tested;
import org.junit.Assert;
import org.junit.Test;
import org.prifizapps.walkers.graphbuilders.GotoLevel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class MenuFrameTest {
@Tested MenuFrame menuFrame;
@Tested MenuItem menuItem;
@Test
public void isItemLevelGotoDefinedFrameWithNoItemsTest() {
menuFrame.setItems(null);
Assert.assertFalse(menuFrame.isItemLevelGotoDefined());
}
@Test
public void isItemLevelGotoDefinedFrameWithEmptyItemsTest() {
menuFrame.setItems(new ArrayList<>());
Assert.assertFalse(menuFrame.isItemLevelGotoDefined());
}
@Test
public void isItemLevelGotoDefinedItemsWithoutGoToTest() {
menuItem.setGotoMenu("");
menuFrame.setItems(Collections.singletonList(menuItem));
Assert.assertFalse(menuFrame.isItemLevelGotoDefined());
}
@Test
public void isItemLevelGotoDefinedPositiveTest() {
menuItem.setGotoMenu("firstMenu");
menuFrame.setItems(Collections.singletonList(menuItem));
Assert.assertTrue(menuFrame.isItemLevelGotoDefined());
}
@Test
public void getItemLevelGotoTest() throws IOException {
new Expectations(menuFrame) {{
menuFrame.isItemLevelGotoDefined();
result = true;
}};
/* new MockUp<MenuFrame>() {
@Mock
boolean isItemLevelGotoDefined() {
return true;
}
};*/
GotoLevel actual = menuFrame.getGotoLevel();
Assert.assertEquals(actual, GotoLevel.ITEM);
}
@Test
public void getMenuLevelGotoTest() throws IOException {
new Expectations(menuFrame) {{
menuFrame.isItemLevelGotoDefined();
result = false;
}};
menuFrame.setGotoMenu("firstMenu");
GotoLevel actual = menuFrame.getGotoLevel();
Assert.assertEquals(actual, GotoLevel.MENU);
}
@Test(expected = IOException.class)
public void gotoNotDefineTest() throws IOException {
new Expectations(menuFrame) {{
menuFrame.isItemLevelGotoDefined();
result = false;
}};
menuFrame.setGotoMenu("");
menuFrame.getGotoLevel();
}
@Test
public void positiveFindDuplicatesTest() {
MenuItem defaultItem = new MenuItem();
new MockUp<MenuItem>() {
@Mock
String getName() {
return "NotUniqueName";
}
};
menuFrame.setItems(new ArrayList<>(Arrays.asList(defaultItem, defaultItem)));
Assert.assertFalse(menuFrame.findDuplicates().isEmpty());
}
@Test
public void negativeFindDuplicatesTest() {
MenuItem firstMenuItem = new MenuItem();
firstMenuItem.setName("firstUniqName");
MenuItem secondMenuItem = new MenuItem();
secondMenuItem.setName("secondUniqName");
menuFrame.setItems(new ArrayList<>(Arrays.asList(firstMenuItem, secondMenuItem)));
Assert.assertTrue(menuFrame.findDuplicates().isEmpty());
}
}
|
johntom/trails3-helloworld
|
node_modules/trails/lib/errors/ConfigValueError.js
|
module.exports = class ConfigValueError extends RangeError {
constructor(msg) {
super(msg)
}
get name () {
return 'ConfigValueError'
}
}
|
BaiduFE/Tangram-component
|
test/baidu/data/Validator/tangram_validator_base.js
|
<filename>test/baidu/data/Validator/tangram_validator_base.js
// Copyright (c) 2009, Baidu Inc. All rights reserved.
//
// Licensed under the BSD License
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http:// tangram.baidu.com/license.html
//
// 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.
/**
* @namespace T Tangram七巧板
* @name T
* @version 1.3.9
*/
/**
* 声明baidu包
* @author: allstar, erik, meizz, berg
*/
var T,
baidu = T = baidu || {version: "1.3.9"};
//提出guid,防止在与老版本Tangram混用时
//在下一行错误的修改window[undefined]
baidu.guid = "$BAIDU$";
//Tangram可能被放在闭包中
//一些页面级别唯一的属性,需要挂载在window[baidu.guid]上
window[baidu.guid] = window[baidu.guid] || {};
/**
* @namespace baidu.lang 对语言层面的封装,包括类型判断、模块扩展、继承基类以及对象自定义事件的支持。
*/
baidu.lang = baidu.lang || {};
/**
* 返回一个当前页面的唯一标识字符串。
* @name baidu.lang.guid
* @function
* @grammar baidu.lang.guid()
* @version 1.1.1
* @meta standard
*
* @returns {String} 当前页面的唯一标识字符串
*/
(function(){
//不直接使用window,可以提高3倍左右性能
var guid = window[baidu.guid];
baidu.lang.guid = function() {
return "TANGRAM__" + (guid._counter ++).toString(36);
};
guid._counter = guid._counter || 1;
})();
/**
* 所有类的实例的容器
* key为每个实例的guid
* @meta standard
*/
window[baidu.guid]._instances = window[baidu.guid]._instances || {};
/**
* 判断目标参数是否为function或Function实例
* @name baidu.lang.isFunction
* @function
* @grammar baidu.lang.isFunction(source)
* @param {Any} source 目标参数
* @version 1.2
* @see baidu.lang.isString,baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isArray,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate
* @meta standard
* @returns {boolean} 类型判断结果
*/
baidu.lang.isFunction = function (source) {
// chrome下,'function' == typeof /a/ 为true.
return '[object Function]' == Object.prototype.toString.call(source);
};
/**
* Tangram继承机制提供的一个基类,用户可以通过继承baidu.lang.Class来获取它的属性及方法。
* @class
* @name baidu.lang.Class
* @grammar baidu.lang.Class(guid)
* @param {string} guid 对象的唯一标识
* @meta standard
* @remark baidu.lang.Class和它的子类的实例均包含一个全局唯一的标识guid。guid是在构造函数中生成的,因此,继承自baidu.lang.Class的类应该直接或者间接调用它的构造函数。<br>baidu.lang.Class的构造函数中产生guid的方式可以保证guid的唯一性,及每个实例都有一个全局唯一的guid。
* @meta standard
* @see baidu.lang.inherits,baidu.lang.Event
*/
baidu.lang.Class = function(guid) {
this.guid = guid || baidu.lang.guid();
window[baidu.guid]._instances[this.guid] = this;
};
window[baidu.guid]._instances = window[baidu.guid]._instances || {};
/**
* 释放对象所持有的资源,主要是自定义事件。
* @name dispose
* @grammar obj.dispose()
* TODO: 将_listeners中绑定的事件剔除掉
*/
baidu.lang.Class.prototype.dispose = function(){
delete window[baidu.guid]._instances[this.guid];
for(var property in this){
if (!baidu.lang.isFunction(this[property])) {
delete this[property];
}
}
this.disposed = true; // 20100716
};
/**
* 重载了默认的toString方法,使得返回信息更加准确一些。
* @return {string} 对象的String表示形式
*/
baidu.lang.Class.prototype.toString = function(){
return "[object " + (this._className || "Object" ) + "]";
};
/**
* 判断目标参数是否string类型或String对象
* @name baidu.lang.isString
* @function
* @grammar baidu.lang.isString(source)
* @param {Any} source 目标参数
* @shortcut isString
* @meta standard
* @see baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isArray,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate
*
* @returns {boolean} 类型判断结果
*/
baidu.lang.isString = function (source) {
return '[object String]' == Object.prototype.toString.call(source);
};
// 声明快捷方法
baidu.isString = baidu.lang.isString;
/**
* 自定义的事件对象。
* @class
* @name baidu.lang.Event
* @grammar baidu.lang.Event(type[, target])
* @param {string} type 事件类型名称。为了方便区分事件和一个普通的方法,事件类型名称必须以"on"(小写)开头。
* @param {Object} [target]触发事件的对象
* @meta standard
* @remark 引入该模块,会自动为Class引入3个事件扩展方法:addEventListener、removeEventListener和dispatchEvent。
* @meta standard
* @see baidu.lang.Class
*/
baidu.lang.Event = function (type, target) {
this.type = type;
this.returnValue = true;
this.target = target || null;
this.currentTarget = null;
};
/**
* 注册对象的事件监听器。引入baidu.lang.Event后,Class的子类实例才会获得该方法。
* @grammar obj.addEventListener(type, handler[, key])
* @param {string} type 自定义事件的名称
* @param {Function} handler 自定义事件被触发时应该调用的回调函数
* @param {string} [key] 为事件监听函数指定的名称,可在移除时使用。如果不提供,方法会默认为它生成一个全局唯一的key。
* @remark 事件类型区分大小写。如果自定义事件名称不是以小写"on"开头,该方法会给它加上"on"再进行判断,即"click"和"onclick"会被认为是同一种事件。
*/
baidu.lang.Class.prototype.addEventListener = function (type, handler, key) {
if (!baidu.lang.isFunction(handler)) {
return;
}
!this.__listeners && (this.__listeners = {});
var t = this.__listeners, id;
if (typeof key == "string" && key) {
if (/[^\w\-]/.test(key)) {
throw("nonstandard key:" + key);
} else {
handler.hashCode = key;
id = key;
}
}
type.indexOf("on") != 0 && (type = "on" + type);
typeof t[type] != "object" && (t[type] = {});
id = id || baidu.lang.guid();
handler.hashCode = id;
t[type][id] = handler;
};
/**
* 移除对象的事件监听器。引入baidu.lang.Event后,Class的子类实例才会获得该方法。
* @grammar obj.removeEventListener(type, handler)
* @param {string} type 事件类型
* @param {Function|string} handler 要移除的事件监听函数或者监听函数的key
* @remark 如果第二个参数handler没有被绑定到对应的自定义事件中,什么也不做。
*/
baidu.lang.Class.prototype.removeEventListener = function (type, handler) {
if (typeof handler != "undefined") {
if ( (baidu.lang.isFunction(handler) && ! (handler = handler.hashCode))
|| (! baidu.lang.isString(handler))
){
return;
}
}
!this.__listeners && (this.__listeners = {});
type.indexOf("on") != 0 && (type = "on" + type);
var t = this.__listeners;
if (!t[type]) {
return;
}
if (typeof handler != "undefined") {
t[type][handler] && delete t[type][handler];
} else {
for(var guid in t[type]){
delete t[type][guid];
}
}
};
/**
* 派发自定义事件,使得绑定到自定义事件上面的函数都会被执行。引入baidu.lang.Event后,Class的子类实例才会获得该方法。
* @grammar obj.dispatchEvent(event, options)
* @param {baidu.lang.Event|String} event Event对象,或事件名称(1.1.1起支持)
* @param {Object} options 扩展参数,所含属性键值会扩展到Event对象上(1.2起支持)
* @remark 处理会调用通过addEventListenr绑定的自定义事件回调函数之外,还会调用直接绑定到对象上面的自定义事件。例如:<br>
myobj.onMyEvent = function(){}<br>
myobj.addEventListener("onMyEvent", function(){});
*/
baidu.lang.Class.prototype.dispatchEvent = function (event, options) {
if (baidu.lang.isString(event)) {
event = new baidu.lang.Event(event);
}
!this.__listeners && (this.__listeners = {});
// 20100603 添加本方法的第二个参数,将 options extend到event中去传递
options = options || {};
for (var i in options) {
event[i] = options[i];
}
var i, t = this.__listeners, p = event.type;
event.target = event.target || this;
event.currentTarget = this;
p.indexOf("on") != 0 && (p = "on" + p);
baidu.lang.isFunction(this[p]) && this[p].apply(this, arguments);
if (typeof t[p] == "object") {
for (i in t[p]) {
t[p][i].apply(this, arguments);
}
}
return event.returnValue;
};
/**
* 创建一个类,包括创造类的构造器、继承基类Class
* @name baidu.lang.createClass
* @function
* @grammar baidu.lang.createClass(constructor[, options])
* @param {Function} constructor 类的构造器函数
* @param {Object} [options]
* @config {string} [className] 类名
* @config {Function} [superClass] 父类,默认为baidu.lang.Class
* @version 1.2
* @remark
*
使用createClass能方便的创建一个带有继承关系的类。同时会为返回的类对象添加extend方法,使用obj.extend({});可以方便的扩展原型链上的方法和属性
* @see baidu.lang.Class,baidu.lang.inherits
*
* @returns {Object} 一个类对象
*/
baidu.lang.createClass = /**@function*/function(constructor, options) {
options = options || {};
var superClass = options.superClass || baidu.lang.Class;
// 创建新类的真构造器函数
var fn = function(){
// 继承父类的构造器
if(superClass != baidu.lang.Class){
superClass.apply(this, arguments);
}else{
superClass.call(this);
}
constructor.apply(this, arguments);
};
fn.options = options.options || {};
var C = function(){},
cp = constructor.prototype;
C.prototype = superClass.prototype;
// 继承父类的原型(prototype)链
var fp = fn.prototype = new C();
// 继承传参进来的构造器的 prototype 不会丢
for (var i in cp) fp[i] = cp[i];
typeof options.className == "string" && (fp._className = options.className);
// 修正这种继承方式带来的 constructor 混乱的问题
fp.constructor = cp.constructor;
// 给类扩展出一个静态方法,以代替 baidu.object.extend()
fn.extend = function(json){
for (var i in json) {
fn.prototype[i] = json[i];
}
return fn; // 这个静态方法也返回类对象本身
};
return fn;
};
/**
* 判断目标参数是否Array对象
* @name baidu.lang.isArray
* @function
* @grammar baidu.lang.isArray(source)
* @param {Any} source 目标参数
* @meta standard
* @see baidu.lang.isString,baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate
*
* @returns {boolean} 类型判断结果
*/
baidu.lang.isArray = function (source) {
return '[object Array]' == Object.prototype.toString.call(source);
};
/**
* 判断目标参数是否Boolean对象
* @name baidu.lang.isBoolean
* @function
* @grammar baidu.lang.isBoolean(source)
* @param {Any} source 目标参数
* @version 1.3
* @see baidu.lang.isString,baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isElement,baidu.lang.isArray,baidu.lang.isDate
*
* @returns {boolean} 类型判断结果
*/
baidu.lang.isBoolean = function(o) {
return typeof o === 'boolean';
};
/**
* 判断目标参数是否为Date对象
* @name baidu.lang.isDate
* @function
* @grammar baidu.lang.isDate(source)
* @param {Any} source 目标参数
* @version 1.3
* @see baidu.lang.isString,baidu.lang.isObject,baidu.lang.isNumber,baidu.lang.isArray,baidu.lang.isBoolean,baidu.lang.isElement
*
* @returns {boolean} 类型判断结果
*/
baidu.lang.isDate = function(o) {
// return o instanceof Date;
return {}.toString.call(o) === "[object Date]" && o.toString() !== 'Invalid Date' && !isNaN(o);
};
/**
* 判断目标参数是否number类型或Number对象
* @name baidu.lang.isNumber
* @function
* @grammar baidu.lang.isNumber(source)
* @param {Any} source 目标参数
* @meta standard
* @see baidu.lang.isString,baidu.lang.isObject,baidu.lang.isArray,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate
*
* @returns {boolean} 类型判断结果
* @remark 用本函数判断NaN会返回false,尽管在Javascript中是Number类型。
*/
baidu.lang.isNumber = function (source) {
return '[object Number]' == Object.prototype.toString.call(source) && isFinite(source);
};
/**
* 判断目标参数是否为Object对象
* @name baidu.lang.isObject
* @function
* @grammar baidu.lang.isObject(source)
* @param {Any} source 目标参数
* @shortcut isObject
* @meta standard
* @see baidu.lang.isString,baidu.lang.isNumber,baidu.lang.isArray,baidu.lang.isElement,baidu.lang.isBoolean,baidu.lang.isDate
*
* @returns {boolean} 类型判断结果
*/
baidu.lang.isObject = function (source) {
return 'function' == typeof source || !!(source && 'object' == typeof source);
};
// 声明快捷方法
baidu.isObject = baidu.lang.isObject;
/**
* @namespace baidu.ajax 对XMLHttpRequest请求的封装。
*/
baidu.ajax = baidu.ajax || {};
/**
* @namespace baidu.fn 对方法的操作,解决内存泄露问题。
*/
baidu.fn = baidu.fn || {};
/**
* 这是一个空函数,用于需要排除函数作用域链干扰的情况.
* @author rocy
* @name baidu.fn.blank
* @function
* @grammar baidu.fn.blank()
* @meta standard
* @return {Function} 一个空函数
* @version 1.3.3
*/
baidu.fn.blank = function () {};
/**
* 发送一个ajax请求
* @author: allstar, erik, berg
* @name baidu.ajax.request
* @function
* @grammar baidu.ajax.request(url[, options])
* @param {string} url 发送请求的url
* @param {Object} options 发送请求的选项参数
* @config {String} [method] 请求发送的类型。默认为GET
* @config {Boolean} [async] 是否异步请求。默认为true(异步)
* @config {String} [data] 需要发送的数据。如果是GET请求的话,不需要这个属性
* @config {Object} [headers] 要设置的http request header
* @config {number} [timeout] 超时时间,单位ms
* @config {String} [username] 用户名
* @config {String} [password] 密码
* @config {Function} [onsuccess] 请求成功时触发,function(XMLHttpRequest xhr, string responseText)。
* @config {Function} [onfailure] 请求失败时触发,function(XMLHttpRequest xhr)。
* @config {Function} [onbeforerequest] 发送请求之前触发,function(XMLHttpRequest xhr)。
* @config {Function} [on{STATUS_CODE}] 当请求为相应状态码时触发的事件,如on302、on404、on500,function(XMLHttpRequest xhr)。3XX的状态码浏览器无法获取,4xx的,可能因为未知问题导致获取失败。
* @config {Boolean} [noCache] 是否需要缓存,默认为false(缓存),1.1.1起支持。
*
* @meta standard
* @see baidu.ajax.get,baidu.ajax.post,baidu.ajax.form
*
* @returns {XMLHttpRequest} 发送请求的XMLHttpRequest对象
*/
baidu.ajax.request = function (url, opt_options) {
var options = opt_options || {},
data = options.data || "",
async = !(options.async === false),
username = options.username || "",
password = options.password || "",
method = (options.method || "GET").toUpperCase(),
headers = options.headers || {},
// 基本的逻辑来自lili同学提供的patch
timeout = options.timeout || 0,
eventHandlers = {},
tick, key, xhr;
/**
* readyState发生变更时调用
*
* @ignore
*/
function stateChangeHandler() {
if (xhr.readyState == 4) {
try {
var stat = xhr.status;
} catch (ex) {
// 在请求时,如果网络中断,Firefox会无法取得status
fire('failure');
return;
}
fire(stat);
// http://www.never-online.net/blog/article.asp?id=261
// case 12002: // Server timeout
// case 12029: // dropped connections
// case 12030: // dropped connections
// case 12031: // dropped connections
// case 12152: // closed by server
// case 13030: // status and statusText are unavailable
// IE error sometimes returns 1223 when it
// should be 204, so treat it as success
if ((stat >= 200 && stat < 300)
|| stat == 304
|| stat == 1223) {
fire('success');
} else {
fire('failure');
}
/*
* NOTE: Testing discovered that for some bizarre reason, on Mozilla, the
* JavaScript <code>XmlHttpRequest.onreadystatechange</code> handler
* function maybe still be called after it is deleted. The theory is that the
* callback is cached somewhere. Setting it to null or an empty function does
* seem to work properly, though.
*
* On IE, there are two problems: Setting onreadystatechange to null (as
* opposed to an empty function) sometimes throws an exception. With
* particular (rare) versions of jscript.dll, setting onreadystatechange from
* within onreadystatechange causes a crash. Setting it from within a timeout
* fixes this bug (see issue 1610).
*
* End result: *always* set onreadystatechange to an empty function (never to
* null). Never set onreadystatechange from within onreadystatechange (always
* in a setTimeout()).
*/
window.setTimeout(
function() {
// 避免内存泄露.
// 由new Function改成不含此作用域链的 baidu.fn.blank 函数,
// 以避免作用域链带来的隐性循环引用导致的IE下内存泄露. By rocy 2011-01-05 .
xhr.onreadystatechange = baidu.fn.blank;
if (async) {
xhr = null;
}
}, 0);
}
}
/**
* 获取XMLHttpRequest对象
*
* @ignore
* @return {XMLHttpRequest} XMLHttpRequest对象
*/
function getXHR() {
if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
}
/**
* 触发事件
*
* @ignore
* @param {String} type 事件类型
*/
function fire(type) {
type = 'on' + type;
var handler = eventHandlers[type],
globelHandler = baidu.ajax[type];
// 不对事件类型进行验证
if (handler) {
if (tick) {
clearTimeout(tick);
}
if (type != 'onsuccess') {
handler(xhr);
} else {
//处理获取xhr.responseText导致出错的情况,比如请求图片地址.
try {
xhr.responseText;
} catch(error) {
return handler(xhr);
}
handler(xhr, xhr.responseText);
}
} else if (globelHandler) {
//onsuccess不支持全局事件
if (type == 'onsuccess') {
return;
}
globelHandler(xhr);
}
}
for (key in options) {
// 将options参数中的事件参数复制到eventHandlers对象中
// 这里复制所有options的成员,eventHandlers有冗余
// 但是不会产生任何影响,并且代码紧凑
eventHandlers[key] = options[key];
}
headers['X-Requested-With'] = 'XMLHttpRequest';
try {
xhr = getXHR();
if (method == 'GET') {
if (data) {
url += (url.indexOf('?') >= 0 ? '&' : '?') + data;
data = null;
}
if(options['noCache'])
url += (url.indexOf('?') >= 0 ? '&' : '?') + 'b' + (+ new Date) + '=1';
}
if (username) {
xhr.open(method, url, async, username, password);
} else {
xhr.open(method, url, async);
}
if (async) {
xhr.onreadystatechange = stateChangeHandler;
}
// 在open之后再进行http请求头设定
// FIXME 是否需要添加; charset=UTF-8呢
if (method == 'POST') {
xhr.setRequestHeader("Content-Type",
(headers['Content-Type'] || "application/x-www-form-urlencoded"));
}
for (key in headers) {
if (headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, headers[key]);
}
}
fire('beforerequest');
if (timeout) {
tick = setTimeout(function(){
xhr.onreadystatechange = baidu.fn.blank;
xhr.abort();
fire("timeout");
}, timeout);
}
xhr.send(data);
if (!async) {
stateChangeHandler();
}
} catch (ex) {
fire('failure');
}
return xhr;
};
/**
* @namespace baidu.array 操作数组的方法。
*/
baidu.array = baidu.array || {};
/**
* 遍历数组中所有元素
* @name baidu.array.each
* @function
* @grammar baidu.array.each(source, iterator[, thisObject])
* @param {Array} source 需要遍历的数组
* @param {Function} iterator 对每个数组元素进行调用的函数,该函数有两个参数,第一个为数组元素,第二个为数组索引值,function (item, index)。
* @param {Object} [thisObject] 函数调用时的this指针,如果没有此参数,默认是当前遍历的数组
* @remark
* each方法不支持对Object的遍历,对Object的遍历使用baidu.object.each 。
* @shortcut each
* @meta standard
*
* @returns {Array} 遍历的数组
*/
baidu.each = baidu.array.forEach = baidu.array.each = function (source, iterator, thisObject) {
var returnValue, item, i, len = source.length;
if ('function' == typeof iterator) {
for (i = 0; i < len; i++) {
item = source[i];
//TODO
//此处实现和标准不符合,标准中是这样说的:
//If a thisObject parameter is provided to forEach, it will be used as the this for each invocation of the callback. If it is not provided, or is null, the global object associated with callback is used instead.
returnValue = iterator.call(thisObject || source, item, i);
if (returnValue === false) {
break;
}
}
}
return source;
};
/**
* 查询数组中指定元素的索引位置
* @name baidu.array.indexOf
* @function
* @grammar baidu.array.indexOf(source, match[, fromIndex])
* @param {Array} source 需要查询的数组
* @param {Any} match 查询项
* @param {number} [fromIndex] 查询的起始位索引位置,如果为负数,则从source.length+fromIndex往后开始查找
* @see baidu.array.find,baidu.array.lastIndexOf
*
* @returns {number} 指定元素的索引位置,查询不到时返回-1
*/
baidu.array.indexOf = function (source, match, fromIndex) {
var len = source.length,
iterator = match;
fromIndex = fromIndex | 0;
if(fromIndex < 0){//小于0
fromIndex = Math.max(0, len + fromIndex)
}
for ( ; fromIndex < len; fromIndex++) {
if(fromIndex in source && source[fromIndex] === match) {
return fromIndex;
}
}
return -1;
};
/**
* 判断一个数组中是否包含给定元素
* @name baidu.array.contains
* @function
* @grammar baidu.array.contains(source, obj)
* @param {Array} source 需要判断的数组.
* @param {Any} obj 要查找的元素.
* @return {boolean} 判断结果.
* @author berg
*/
baidu.array.contains = function(source, obj) {
return (baidu.array.indexOf(source, obj) >= 0);
};
/**
* @namespace baidu.string 操作字符串的方法。
*/
baidu.string = baidu.string || {};
/**
* 删除目标字符串两端的空白字符
* @name baidu.string.trim
* @function
* @grammar baidu.string.trim(source)
* @param {string} source 目标字符串
* @remark
* 不支持删除单侧空白字符
* @shortcut trim
* @meta standard
*
* @returns {string} 删除两端空白字符后的字符串
*/
(function () {
var trimer = new RegExp("(^[\\s\\t\\xa0\\u3000]+)|([\\u3000\\xa0\\s\\t]+\x24)", "g");
baidu.string.trim = function (source) {
return String(source)
.replace(trimer, "");
};
})();
// 声明快捷方法
baidu.trim = baidu.string.trim;
/**
* @namespace baidu.object 操作原生对象的方法。
*/
baidu.object = baidu.object || {};
/**
* 遍历Object中所有元素,1.1.1增加
* @name baidu.object.each
* @function
* @grammar baidu.object.each(source, iterator)
* @param {Object} source 需要遍历的Object
* @param {Function} iterator 对每个Object元素进行调用的函数,function (item, key)
* @version 1.1.1
*
* @returns {Object} 遍历的Object
*/
baidu.object.each = function (source, iterator) {
var returnValue, key, item;
if ('function' == typeof iterator) {
for (key in source) {
if (source.hasOwnProperty(key)) {
item = source[key];
returnValue = iterator.call(source, item, key);
if (returnValue === false) {
break;
}
}
}
}
return source;
};
/** @namespace */
baidu.data = baidu.data || {};
/**
* @namespace baidu.dom 操作dom的方法。
*/
baidu.dom = baidu.dom || {};
/**
* 从文档中获取指定的DOM元素
* @name baidu.dom.g
* @function
* @grammar baidu.dom.g(id)
* @param {string|HTMLElement} id 元素的id或DOM元素
* @shortcut g,T.G
* @meta standard
* @see baidu.dom.q
*
* @returns {HTMLElement|null} 获取的元素,查找不到时返回null,如果参数不合法,直接返回参数
*/
baidu.dom.g = function (id) {
if ('string' == typeof id || id instanceof String) {
return document.getElementById(id);
} else if (id && id.nodeName && (id.nodeType == 1 || id.nodeType == 9)) {
return id;
}
return null;
};
// 声明快捷方法
baidu.g = baidu.G = baidu.dom.g;
/**
* 提供给setStyle与getStyle使用
*/
baidu.dom._styleFixer = baidu.dom._styleFixer || {};
/**
* 提供给setStyle与getStyle使用
*/
baidu.dom._styleFilter = baidu.dom._styleFilter || [];
/**
* 为获取和设置样式的过滤器
* @private
* @meta standard
*/
baidu.dom._styleFilter.filter = function (key, value, method) {
for (var i = 0, filters = baidu.dom._styleFilter, filter; filter = filters[i]; i++) {
if (filter = filter[method]) {
value = filter(key, value);
}
}
return value;
};
/**
* 将目标字符串进行驼峰化处理
* @name baidu.string.toCamelCase
* @function
* @grammar baidu.string.toCamelCase(source)
* @param {string} source 目标字符串
* @remark
* 支持单词以“-_”分隔
* @meta standard
*
* @returns {string} 驼峰化处理后的字符串
*/
//todo:考虑以后去掉下划线支持?
baidu.string.toCamelCase = function (source) {
//提前判断,提高getStyle等的效率 thanks xianwei
if (source.indexOf('-') < 0 && source.indexOf('_') < 0) {
return source;
}
return source.replace(/[-_][^-_]/g, function (match) {
return match.charAt(1).toUpperCase();
});
};
/**
* 设置目标元素的style样式值
* @name baidu.dom.setStyle
* @function
* @grammar baidu.dom.setStyle(element, key, value)
* @param {HTMLElement|string} element 目标元素或目标元素的id
* @param {string} key 要设置的样式名
* @param {string} value 要设置的样式值
* @remark
*
为了精简代码,本模块默认不对任何浏览器返回值进行归一化处理(如使用getStyle时,不同浏览器下可能返回rgb颜色或hex颜色),也不会修复浏览器的bug和差异性(如设置IE的float属性叫styleFloat,firefox则是cssFloat)。<br />
baidu.dom._styleFixer和baidu.dom._styleFilter可以为本模块提供支持。<br />
其中_styleFilter能对颜色和px进行归一化处理,_styleFixer能对display,float,opacity,textOverflow的浏览器兼容性bug进行处理。
* @shortcut setStyle
* @meta standard
* @see baidu.dom.getStyle,baidu.dom.setStyles
*
* @returns {HTMLElement} 目标元素
*/
baidu.dom.setStyle = function (element, key, value) {
var dom = baidu.dom, fixer;
// 放弃了对firefox 0.9的opacity的支持
element = dom.g(element);
key = baidu.string.toCamelCase(key);
if (fixer = dom._styleFilter) {
value = fixer.filter(key, value, 'set');
}
fixer = dom._styleFixer[key];
(fixer && fixer.set) ? fixer.set(element, value) : (element.style[fixer || key] = value);
return element;
};
// 声明快捷方法
baidu.setStyle = baidu.dom.setStyle;
/**
* 批量设置目标元素的style样式值
* @name baidu.dom.setStyles
* @function
* @grammar baidu.dom.setStyles(element, styles)
* @param {HTMLElement|string} element 目标元素或目标元素的id
* @param {Object} styles 要设置的样式集合
* @shortcut setStyles
* @meta standard
* @see baidu.dom.setStyle,baidu.dom.getStyle
*
* @returns {HTMLElement} 目标元素
*/
baidu.dom.setStyles = function (element, styles) {
element = baidu.dom.g(element);
for (var key in styles) {
baidu.dom.setStyle(element, key, styles[key]);
}
return element;
};
// 声明快捷方法
baidu.setStyles = baidu.dom.setStyles;
/**
* @namespace baidu.event 屏蔽浏览器差异性的事件封装。
* @property target 事件的触发元素
* @property pageX 鼠标事件的鼠标x坐标
* @property pageY 鼠标事件的鼠标y坐标
* @property keyCode 键盘事件的键值
*/
baidu.event = baidu.event || {};
/**
* 事件监听器的存储表
* @private
* @meta standard
*/
baidu.event._listeners = baidu.event._listeners || [];
/**
* 从文档中获取指定的DOM元素
* **内部方法**
*
* @param {string|HTMLElement} id 元素的id或DOM元素
* @meta standard
* @return {HTMLElement} DOM元素,如果不存在,返回null,如果参数不合法,直接返回参数
*/
baidu.dom._g = function (id) {
if (baidu.lang.isString(id)) {
return document.getElementById(id);
}
return id;
};
// 声明快捷方法
baidu._g = baidu.dom._g;
/**
* 为目标元素添加事件监听器
* @name baidu.event.on
* @function
* @grammar baidu.event.on(element, type, listener)
* @param {HTMLElement|string|window} element 目标元素或目标元素id
* @param {string} type 事件类型
* @param {Function} listener 需要添加的监听器
* @remark
*
1. 不支持跨浏览器的鼠标滚轮事件监听器添加<br>
2. 改方法不为监听器灌入事件对象,以防止跨iframe事件挂载的事件对象获取失败
* @shortcut on
* @meta standard
* @see baidu.event.un
* @returns {HTMLElement|window} 目标元素
*/
baidu.event.on = /**@function*/function (element, type, listener) {
type = type.replace(/^on/i, '');
element = baidu.dom._g(element);
var realListener = function (ev) {
// 1. 这里不支持EventArgument, 原因是跨frame的事件挂载
// 2. element是为了修正this
listener.call(element, ev);
},
lis = baidu.event._listeners,
filter = baidu.event._eventFilter,
afterFilter,
realType = type;
type = type.toLowerCase();
// filter过滤
if(filter && filter[type]){
afterFilter = filter[type](element, type, realListener);
realType = afterFilter.type;
realListener = afterFilter.listener;
}
// 事件监听器挂载
if (element.addEventListener) {
element.addEventListener(realType, realListener, false);
} else if (element.attachEvent) {
element.attachEvent('on' + realType, realListener);
}
// 将监听器存储到数组中
lis[lis.length] = [element, type, listener, realListener, realType];
return element;
};
// 声明快捷方法
baidu.on = baidu.event.on;
/**
* 为目标元素移除事件监听器
* @name baidu.event.un
* @function
* @grammar baidu.event.un(element, type, listener)
* @param {HTMLElement|string|window} element 目标元素或目标元素id
* @param {string} type 事件类型
* @param {Function} listener 需要移除的监听器
* @shortcut un
* @meta standard
* @see baidu.event.on
*
* @returns {HTMLElement|window} 目标元素
*/
baidu.event.un = function (element, type, listener) {
element = baidu.dom._g(element);
type = type.replace(/^on/i, '').toLowerCase();
var lis = baidu.event._listeners,
len = lis.length,
isRemoveAll = !listener,
item,
realType, realListener;
//如果将listener的结构改成json
//可以节省掉这个循环,优化性能
//但是由于un的使用频率并不高,同时在listener不多的时候
//遍历数组的性能消耗不会对代码产生影响
//暂不考虑此优化
while (len--) {
item = lis[len];
// listener存在时,移除element的所有以listener监听的type类型事件
// listener不存在时,移除element的所有type类型事件
if (item[1] === type
&& item[0] === element
&& (isRemoveAll || item[2] === listener)) {
realType = item[4];
realListener = item[3];
if (element.removeEventListener) {
element.removeEventListener(realType, realListener, false);
} else if (element.detachEvent) {
element.detachEvent('on' + realType, realListener);
}
lis.splice(len, 1);
}
}
return element;
};
// 声明快捷方法
baidu.un = baidu.event.un;
/**
* 为对象绑定方法和作用域
* @name baidu.fn.bind
* @function
* @grammar baidu.fn.bind(handler[, obj, args])
* @param {Function|String} handler 要绑定的函数,或者一个在作用域下可用的函数名
* @param {Object} obj 执行运行时this,如果不传入则运行时this为函数本身
* @param {args* 0..n} args 函数执行时附加到执行时函数前面的参数
* @version 1.3
*
* @returns {Function} 封装后的函数
*/
baidu.fn.bind = function(func, scope) {
var xargs = arguments.length > 2 ? [].slice.call(arguments, 2) : null;
return function () {
var fn = baidu.lang.isString(func) ? scope[func] : func,
args = (xargs) ? xargs.concat([].slice.call(arguments, 0)) : arguments;
return fn.apply(scope || fn, args);
};
};
/**
* XPC(cross page channel) 跨域通信模块
* @name baidu.data.XPC
* @function
* @grammar new baidu.data.XPC(true, url[, {timeout:1000}])
* @param {boolean} isParent 确定当前页面角色,如果是父页面,则为true,跨域的子页面为false,默认值为false.
* @param {string} url 在对方域下部署的子页面,如果isParent为true,则此参数为必须,否则可以省略.
* @param {number} timeout 设置超时时间(ms),超过这个时间视为初始化失败,默认值是3000.
* @author zhangyunlong
*/
baidu.data.XPC = baidu.lang.createClass(function(isParent, url, options) {
options = options || {};
//浏览器特性检查,判断是否支持postMessage,一次运行得到结果
this._canUsePostMessage = (typeof window.postMessage === 'function' || typeof window.postMessage === 'object');
//确定角色,父页面为true,子页面为false或undefined
this._isParent = isParent;
//初始化完毕标志位
this.ready = false;
//当前页面domain,形如(http://www.example.com)
this.currentDomain = this._getDomainByUrl(location.href);
//父页面的初始化过程
if (isParent && url) {
//创建iframe
this._channel = this._createIframe(url);
//设置对方域
this.targetDomain = this._getDomainByUrl(url);
this.source = (this._channel.contentWindow || this._channel);
//页面载入完毕后,由父页面先发送初始化消息
baidu.on(this._channel, 'load', baidu.fn.bind(function() {this.send('init');}, this));
//设置超时时间,默认为30秒
timeout = parseInt(options.timeout) || 30000;
this._timer = setTimeout(baidu.fn.bind(function() {
this.dispatchEvent(this._createEvent('error', 'Tiemout.'));
}, this), timeout);
} else if (!isParent) {
//子页面初始化过程
this.targetDomain = null;
this.source = window.parent;
//子页面允许与之通信的父页面domain列表
this.allowDomains = options.allowDomains || ['*'];
} else {
//初始化失败,派发错误消息
this.dispatchEvent(this._createEvent('error', 'need url.'));
}
var handler = baidu.fn.bind('_onMessage', this);
if (this._canUsePostMessage) {
baidu.on(window, 'message', handler);
} else {
try {
//IE6-7通过opener对象挂载父子页面互调方法进行通信,这里不排除身份伪造漏洞,使用时请注意,目前没有很好的方法fix
var win = isParent ? this.source : window,
opener = win.opener || {},
handlerNames = ['parentReceiveHandler', 'childReceiveHandler'],
receiveHandlerName = handlerNames[isParent ? 0 : 1],
sendHandlerName = handlerNames[isParent ? 1 : 0];
opener.xpc = opener.xpc || {};
opener.xpc[receiveHandlerName] = handler;
this._sendHandlerName = sendHandlerName;
this._xpc = opener.xpc;
win.opener = opener;
} catch (e) {
this.dispatchEvent(this._createEvent('error', e.message));
}
}
}).extend(
/**@lends baidu.data.XPC.prototype*/
{
//创建iframe,并返回DOM引用
_createIframe: function(url) {
var ifrm = document.createElement('IFRAME');
//firefox下,动态创建的iframe会从缓存中读取页面,通过将空白页指定给iframe的src属性来修正该问题
ifrm.src = 'about:blank';
ifrm.frameBorder = 0;
baidu.dom.setStyles(ifrm, {
position: 'absolute',
left: '-10000px',
top: '-10000px',
width: '10px',
height: '10px'
});
document.body.appendChild(ifrm);
ifrm.src = url;
return ifrm;
},
_createEvent: function(type, data) {
return {
type: type,
data: data
};
},
_checkDomain: function(domain) {
if (this._isParent) {
return domain === this.targetDomain;
} else {
var arr = this.allowDomains,
len = arr.length;
while (len--) {
var tmp = arr[len];
if (tmp === '*' || tmp === domain) {
return true;
}
}
return false;
}
},
//根据url获取domain信息
_getDomainByUrl: function(url) {
var a = document.createElement('A');
a.href = url;
//IE8将www.a.com:80和www.a.com认为是不同domain
return a.protocol + '\/\/' + a.hostname + ((parseInt(a.port) || 80) === 80 ? '' : ':' + a.port);
},
_onMessage: function(evt) {
evt = evt || window.event;
if (this._checkDomain(evt.origin)) {
this.source = evt.source;
this.targetDomain = evt.origin;
if (this.ready) {
this.dispatchEvent(this._createEvent('message', evt.data));
} else {
//初始化进行一次握手
if (this._isParent) {
//清除超时计时器
clearTimeout(this._timer);
delete this._timer;
} else {
this.send('init');
}
//派发初始化事件
this.ready = true;
this.dispatchEvent(this._createEvent('ready'));
}
}
},
/**
* 发送消息方法。
* @function
* @param {string} msg 要发送的消息.
*/
send: function(msg) {
if (this._canUsePostMessage) {
this.source.postMessage(msg, this.targetDomain);
} else {
var e = {
type: 'message',
data: msg,
origin: this.currentDomain,
source: window
};
this._xpc[this._sendHandlerName](e);
}
}
});
/**
* Tangram
* Copyright 2010 Baidu Inc. All rights reserved.
* @path:data/dataSource/DataSource.js
* @author:Walter
* @version:1.0.0
* @date:2010-11-30
*/
/**
* Tangram
* Copyright 2010 Baidu Inc. All rights reserved.
* @path:data/dataSource.js
* @author:walter
* @version:1.0.0
* @date:2010-11-30
*/
/**
* @namespace 定义命名空间
*/
baidu.data.dataSource = baidu.dataSource = baidu.data.dataSource || {};
/**
* 将源对象的所有属性拷贝到目标对象中
* @author erik
* @name baidu.object.extend
* @function
* @grammar baidu.object.extend(target, source)
* @param {Object} target 目标对象
* @param {Object} source 源对象
* @see baidu.array.merge
* @remark
*
1.目标对象中,与源对象key相同的成员将会被覆盖。<br>
2.源对象的prototype成员不会拷贝。
* @shortcut extend
* @meta standard
*
* @returns {Object} 目标对象
*/
baidu.extend =
baidu.object.extend = function (target, source) {
for (var p in source) {
if (source.hasOwnProperty(p)) {
target[p] = source[p];
}
}
return target;
};
/**
* 获取目标对象的键名列表
* @name baidu.object.keys
* @function
* @grammar baidu.object.keys(source)
* @param {Object} source 目标对象
* @see baidu.object.values
*
* @returns {Array} 键名列表
*/
baidu.object.keys = function (source) {
var result = [], resultLen = 0, k;
for (k in source) {
if (source.hasOwnProperty(k)) {
result[resultLen++] = k;
}
}
return result;
};
/**
* 数据源类
* @class
* @grammar new baidu.data.dataSource.DataSource(options)
* @param {Object} [options] config参数
* @config {Number} [maxCache = 10] 缓存数据的最大个数
* @config {Boolean} [cache = true] 是否使用缓存
* @config {Function} [transition] 转换数据算法
* @return {baidu.data.dataSource.DataSource} 数据源类
* @private
*/
baidu.data.dataSource.DataSource = baidu.lang.createClass(function(options){
this._cacheData = {};
baidu.object.extend(this, options);
this.addEventListener("onbeforeget", function(evt){
var me = this,
data;
if (me.cache && (data = me._cacheData[evt.key]) && evt.onsuccess) {
evt.onsuccess.call(me, data);
}
evt.returnValue = !!data;
});
}, {
className: "baidu.data.dataSource.DataSource"
}).extend(
/**
* @lends baidu.data.dataSource.DataSource.prototype
*/
{
maxCache: 100,
cache: true,
/**
* 更新配置
* @param {Object} options
*/
update: function(options){
var me = this;
baidu.object.extend(me, options);
},
/**
*
* 获取数据
* @interface
* @param {Object} options 配置信息
*/
get: function(options){
},
/**
* 转换数据格式并调用回调函数
* @private
* @param {Object} options
* @return {Object} 返回数据
*/
_get: function(options){
var me = this,
data;
data = me.transition.call(me, me.source);
me.cache && options.key && data && me._addCacheData(options.key, data);
options.onsuccess && options.onsuccess.call(me, data);
return data;
},
/**
* 转换数据格式
* @function
* @param {Object} source 数据源
* @return {Object} source 转换格式后的数据源
*/
transition: function(source){
return source;
},
/**
* 增加缓存数据
* @privite
* @param {Object} key 数据键值对Key值
* @param {Object} value 数据键值对value值
*/
_addCacheData: function(key, value){
var me = this,
keySet = baidu.object.keys(me._cacheData);
while (me.maxCache > 0 && keySet.length >= me.maxCache) {
delete me._cacheData[keySet.shift()];
}
if (me.maxCache > 0) {
me._cacheData[key] = value;
}
}
});
/**
* Tangram
* Copyright 2010 Baidu Inc. All rights reserved.
* @path:data/dataSource/ajax.js
* @author:Walter
* @version:1.0.0
* @date:2010-11-30
*/
/**
* @namespace baidu.json 操作json对象的方法。
*/
baidu.json = baidu.json || {};
/**
* 将json对象序列化
* @name baidu.json.stringify
* @function
* @grammar baidu.json.stringify(value)
* @param {JSON} value 需要序列化的json对象
* @remark
* 该方法的实现与ecma-262第五版中规定的JSON.stringify不同,暂时只支持传入一个参数。后续会进行功能丰富。
* @meta standard
* @see baidu.json.parse,baidu.json.encode
*
* @returns {string} 序列化后的字符串
*/
baidu.json.stringify = (function () {
/**
* 字符串处理时需要转义的字符表
* @private
*/
var escapeMap = {
"\b": '\\b',
"\t": '\\t',
"\n": '\\n',
"\f": '\\f',
"\r": '\\r',
'"' : '\\"',
"\\": '\\\\'
};
/**
* 字符串序列化
* @private
*/
function encodeString(source) {
if (/["\\\x00-\x1f]/.test(source)) {
source = source.replace(
/["\\\x00-\x1f]/g,
function (match) {
var c = escapeMap[match];
if (c) {
return c;
}
c = match.charCodeAt();
return "\\u00"
+ Math.floor(c / 16).toString(16)
+ (c % 16).toString(16);
});
}
return '"' + source + '"';
}
/**
* 数组序列化
* @private
*/
function encodeArray(source) {
var result = ["["],
l = source.length,
preComma, i, item;
for (i = 0; i < l; i++) {
item = source[i];
switch (typeof item) {
case "undefined":
case "function":
case "unknown":
break;
default:
if(preComma) {
result.push(',');
}
result.push(baidu.json.stringify(item));
preComma = 1;
}
}
result.push("]");
return result.join("");
}
/**
* 处理日期序列化时的补零
* @private
*/
function pad(source) {
return source < 10 ? '0' + source : source;
}
/**
* 日期序列化
* @private
*/
function encodeDate(source){
return '"' + source.getFullYear() + "-"
+ pad(source.getMonth() + 1) + "-"
+ pad(source.getDate()) + "T"
+ pad(source.getHours()) + ":"
+ pad(source.getMinutes()) + ":"
+ pad(source.getSeconds()) + '"';
}
return function (value) {
switch (typeof value) {
case 'undefined':
return 'undefined';
case 'number':
return isFinite(value) ? String(value) : "null";
case 'string':
return encodeString(value);
case 'boolean':
return String(value);
default:
if (value === null) {
return 'null';
} else if (value instanceof Array) {
return encodeArray(value);
} else if (value instanceof Date) {
return encodeDate(value);
} else {
var result = ['{'],
encode = baidu.json.stringify,
preComma,
item;
for (var key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
item = value[key];
switch (typeof item) {
case 'undefined':
case 'unknown':
case 'function':
break;
default:
if (preComma) {
result.push(',');
}
preComma = 1;
result.push(encode(key) + ':' + encode(item));
}
}
}
result.push('}');
return result.join('');
}
}
};
})();
/**
* 异步调用数据源类
* @function
* @grammar baidu.data.dataSource.ajax(url, options)
* @param {String} url 数据源地址
* @param {Object} [options] 配置
* @config {Number} maxCache 缓存数据的最大个数,默认10
* @config {Boolean} cache 是否使用缓存,默认开启
* @config {Function} transition 转换数据算法
* @config {Function} onbeforeget beforeget事件
*/
baidu.data.dataSource.ajax = function(url, options){
options = baidu.object.extend({
url: url
}, options || {});
var dataSource = new baidu.data.dataSource.DataSource(options);
/**
* 获取数据
* @param {Object} options 配置
* @param {String} [options.key = url + param] 用于存取缓存
* @param {String} [options.method = 'GET'] 请求的类型
* @param {Object} [options.param] 需要发送的数据
* @param {Function} [options.onsuccess] 加载成功回调函数
* @param {Function} [options.onfailure] 加载失败回调函数
* @param {Object} [options.ajaxOption] request参数
*/
dataSource.get = function(options){
var me = this;
options = options || {};
options.key = options.key || (me.url + (options.param ? "?" + baidu.json.stringify(options.param) : ""));
if (!me.dispatchEvent("onbeforeget", options)) {
baidu.ajax.request(me.url, me.ajaxOption ||
{
method: options.method || 'get',
data: options.param,
onsuccess: function(xhr, responseText){
me.source = responseText;
me._get(options);
},
onfailure: function(xhr){
options.onfailure && options.onfailure.call(me, xhr);
}
});
}
};
return dataSource;
};
/**
* Tangram
* Copyright 2010 Baidu Inc. All rights reserved.
* @path:data/dataSource/local.js
* @author:Walter
* @version:1.0.0
* @date:2010-11-30
*/
/**
* 本地数据源类
* @function
* @grammar baidu.data.dataSource.local(source, options)
* @param {Object} source 数据源
* @param {Object} [options] 配置
* @config {Number} maxCache 缓存数据的最大个数,默认10
* @config {Boolean} cache 是否使用缓存,默认开启
* @config {Function} transition 转换数据算法
* @config {Function} onbeforeget beforeget事件
*/
baidu.data.dataSource.local = function(source, options){
options = baidu.object.extend({
source: source
}, options || {});
var dataSource = new baidu.data.dataSource.DataSource(options);
/**
* 获取数据
* @param {Object} options 配置
* @param {String} [options.key = 'local'] 用于存取缓存
* @param {Function} [options.onsuccess] 加载成功回调函数
*/
dataSource.get = function(options){
var me = this,
data;
options = baidu.object.extend({
'key': 'local'
}, options || {});
if (!me.dispatchEvent("onbeforeget", options)) {
data = me._get(options);
}
return data;
};
return dataSource;
};
/**
* Tangram
* Copyright 2010 Baidu Inc. All rights reserved.
* @path:data/dataSource/sio.js
* @author:Walter
* @version:1.0.0
* @date:2010-11-30
*/
/**
* @namespace baidu.sio 使用动态script标签请求服务器资源,包括由服务器端的回调和浏览器端的回调。
*/
baidu.sio = baidu.sio || {};
/**
*
* @param {HTMLElement} src script节点
* @param {String} url script节点的地址
* @param {String} [charset] 编码
*/
baidu.sio._createScriptTag = function(scr, url, charset){
scr.setAttribute('type', 'text/javascript');
charset && scr.setAttribute('charset', charset);
scr.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(scr);
};
/**
* 删除script的属性,再删除script标签,以解决修复内存泄漏的问题
*
* @param {HTMLElement} src script节点
*/
baidu.sio._removeScriptTag = function(scr){
if (scr.clearAttributes) {
scr.clearAttributes();
} else {
for (var attr in scr) {
if (scr.hasOwnProperty(attr)) {
delete scr[attr];
}
}
}
if(scr && scr.parentNode){
scr.parentNode.removeChild(scr);
}
scr = null;
};
/**
* 通过script标签加载数据,加载完成由浏览器端触发回调
* @name baidu.sio.callByBrowser
* @function
* @grammar baidu.sio.callByBrowser(url, opt_callback, opt_options)
* @param {string} url 加载数据的url
* @param {Function|string} opt_callback 数据加载结束时调用的函数或函数名
* @param {Object} opt_options 其他可选项
* @config {String} [charset] script的字符集
* @config {Integer} [timeOut] 超时时间,超过这个时间将不再响应本请求,并触发onfailure函数
* @config {Function} [onfailure] timeOut设定后才生效,到达超时时间时触发本函数
* @remark
* 1、与callByServer不同,callback参数只支持Function类型,不支持string。
* 2、如果请求了一个不存在的页面,callback函数在IE/opera下也会被调用,因此使用者需要在onsuccess函数中判断数据是否正确加载。
* @meta standard
* @see baidu.sio.callByServer
*/
baidu.sio.callByBrowser = function (url, opt_callback, opt_options) {
var scr = document.createElement("SCRIPT"),
scriptLoaded = 0,
options = opt_options || {},
charset = options['charset'],
callback = opt_callback || function(){},
timeOut = options['timeOut'] || 0,
timer;
// IE和opera支持onreadystatechange
// safari、chrome、opera支持onload
scr.onload = scr.onreadystatechange = function () {
// 避免opera下的多次调用
if (scriptLoaded) {
return;
}
var readyState = scr.readyState;
if ('undefined' == typeof readyState
|| readyState == "loaded"
|| readyState == "complete") {
scriptLoaded = 1;
try {
callback();
clearTimeout(timer);
} finally {
scr.onload = scr.onreadystatechange = null;
baidu.sio._removeScriptTag(scr);
}
}
};
if( timeOut ){
timer = setTimeout(function(){
scr.onload = scr.onreadystatechange = null;
baidu.sio._removeScriptTag(scr);
options.onfailure && options.onfailure();
}, timeOut);
}
baidu.sio._createScriptTag(scr, url, charset);
};
/**
* 通过script标签加载数据,加载完成由服务器端触发回调
* @name baidu.sio.callByServer
* @function
* @grammar baidu.sio.callByServer(url, callback[, opt_options])
* @param {string} url 加载数据的url.
* @param {Function|string} callback 服务器端调用的函数或函数名。如果没有指定本参数,将在URL中寻找options['queryField']做为callback的方法名.
* @param {Object} opt_options 加载数据时的选项.
* @config {string} [charset] script的字符集
* @config {string} [queryField] 服务器端callback请求字段名,默认为callback
* @config {Integer} [timeOut] 超时时间(单位:ms),超过这个时间将不再响应本请求,并触发onfailure函数
* @config {Function} [onfailure] timeOut设定后才生效,到达超时时间时触发本函数
* @remark
* 如果url中已经包含key为“options['queryField']”的query项,将会被替换成callback中参数传递或自动生成的函数名。
* @meta standard
* @see baidu.sio.callByBrowser
*/
baidu.sio.callByServer = /**@function*/function(url, callback, opt_options) {
var scr = document.createElement('SCRIPT'),
prefix = 'bd__cbs__',
callbackName,
callbackImpl,
options = opt_options || {},
charset = options['charset'],
queryField = options['queryField'] || 'callback',
timeOut = options['timeOut'] || 0,
timer,
reg = new RegExp('(\\?|&)' + queryField + '=([^&]*)'),
matches;
if (baidu.lang.isFunction(callback)) {
callbackName = prefix + Math.floor(Math.random() * 2147483648).toString(36);
window[callbackName] = getCallBack(0);
} else if(baidu.lang.isString(callback)){
// 如果callback是一个字符串的话,就需要保证url是唯一的,不要去改变它
// TODO 当调用了callback之后,无法删除动态创建的script标签
callbackName = callback;
} else {
if (matches = reg.exec(url)) {
callbackName = matches[2];
}
}
if( timeOut ){
timer = setTimeout(getCallBack(1), timeOut);
}
//如果用户在URL中已有callback,用参数传入的callback替换之
url = url.replace(reg, '\x241' + queryField + '=' + callbackName);
if (url.search(reg) < 0) {
url += (url.indexOf('?') < 0 ? '?' : '&') + queryField + '=' + callbackName;
}
baidu.sio._createScriptTag(scr, url, charset);
/*
* 返回一个函数,用于立即(挂在window上)或者超时(挂在setTimeout中)时执行
*/
function getCallBack(onTimeOut){
/*global callbackName, callback, scr, options;*/
return function(){
try {
if( onTimeOut ){
options.onfailure && options.onfailure();
}else{
callback.apply(window, arguments);
clearTimeout(timer);
}
window[callbackName] = null;
delete window[callbackName];
} catch (exception) {
// ignore the exception
} finally {
baidu.sio._removeScriptTag(scr);
}
}
}
};
/**
* 跨域数据源类
* @function
* @grammar baidu.data.dataSource.sio(url, options)
* @param {String} url 数据源地址
* @param {Object} [options] 配置
* @config {Number} maxCache 缓存数据的最大个数,默认10
* @config {Boolean} cache 是否使用缓存,默认开启
* @config {Function} transition 转换数据算法
* @config {Function} onbeforeget beforeget事件
*/
baidu.data.dataSource.sio = function(url, options){
options = baidu.object.extend({
url: url
}, options || {});
var dataSource = new baidu.data.dataSource.DataSource(options);
/**
* 获取数据
* @param {Object} options 配置
* @param {String} [options.key = url + param] 用于存取缓存
* @param {String} [options.callByType = 'server'] 请求的类型
* @param {Object} [options.param] 需要发送的数据
* @param {Function} [options.onsuccess] 加载成功回调函数
*/
dataSource.get = function(options){
var me = this;
options = options || {};
options.key = options.key || (me.url + (options.param ? "?" + baidu.json.stringify(options.param) : ""));
if (options.callByType && options.callByType.toLowerCase() == "browser") {
options.callByType = "callByBrowser";
}
else {
options.callByType = "callByServer";
}
if (!me.dispatchEvent("onbeforeget", options)) {
baidu.sio[options.callByType](options.key, function(){
me._get(options);
});
}
};
return dataSource;
};
/**
* 判断一个对象是不是字面量对象,即判断这个对象是不是由{}或者new Object类似方式创建
*
* @name baidu.object.isPlain
* @function
* @grammar baidu.object.isPlain(source)
* @param {Object} source 需要检查的对象
* @remark
* 事实上来说,在Javascript语言中,任何判断都一定会有漏洞,因此本方法只针对一些最常用的情况进行了判断
*
* @returns {Boolean} 检查结果
*/
baidu.object.isPlain = function(obj){
var hasOwnProperty = Object.prototype.hasOwnProperty,
key;
if ( !obj ||
//一般的情况,直接用toString判断
Object.prototype.toString.call(obj) !== "[object Object]" ||
//IE下,window/document/document.body/HTMLElement/HTMLCollection/NodeList等DOM对象上一个语句为true
//isPrototypeOf挂在Object.prototype上的,因此所有的字面量都应该会有这个属性
//对于在window上挂了isPrototypeOf属性的情况,直接忽略不考虑
!('isPrototypeOf' in obj)
) {
return false;
}
//判断new fun()自定义对象的情况
//constructor不是继承自原型链的
//并且原型中有isPrototypeOf方法才是Object
if ( obj.constructor &&
!hasOwnProperty.call(obj, "constructor") &&
!hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
//判断有继承的情况
//如果有一项是继承过来的,那么一定不是字面量Object
//OwnProperty会首先被遍历,为了加速遍历过程,直接看最后一项
for ( key in obj ) {}
return key === undefined || hasOwnProperty.call( obj, key );
};
/**
* 对一个object进行深度拷贝
*
* @author berg
* @name baidu.object.clone
* @function
* @grammar baidu.object.clone(source)
* @param {Object} source 需要进行拷贝的对象
* @remark
* 对于Object来说,只拷贝自身成员,不拷贝prototype成员
* @meta standard
*
* @returns {Object} 拷贝后的新对象
*/
baidu.object.clone = function (source) {
var result = source, i, len;
if (!source
|| source instanceof Number
|| source instanceof String
|| source instanceof Boolean) {
return result;
} else if (baidu.lang.isArray(source)) {
result = [];
var resultLen = 0;
for (i = 0, len = source.length; i < len; i++) {
result[resultLen++] = baidu.object.clone(source[i]);
}
} else if (baidu.object.isPlain(source)) {
result = {};
for (i in source) {
if (source.hasOwnProperty(i)) {
result[i] = baidu.object.clone(source[i]);
}
}
}
return result;
};
/**
* 对方法的操作,解决内存泄露问题
* @namespace baidu.fn
*/
baidu.fn = baidu.fn || {};
/**
* 这是一个空函数,用于需要排除函数作用域链干扰的情况.
* @author rocy
* @name baidu.fn.blank
* @function
* @grammar baidu.fn.blank()
* @meta standard
* @return {Function} 一个空函数
* @version 1.3.3
*/
baidu.fn.blank = function () {};
|
ForrestSu/go_learn
|
advance/fastid/fastid_test.go
|
package fastid
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestLSB(t *testing.T) {
assert.Equal(t, byte(0xfe), LSB(0x123456fe))
}
func TestFastID_GenID(t *testing.T) {
var operatorID uint = 10
var userID uint = 123
sn := StdFastID.GenID(operatorID, userID)
// 202105171838043898712414209
t.Log(sn)
}
func TestFastID(t *testing.T) {
var lastID int64 = 1415918331035375617
var expectSeq int64 = 1
var expectTime int64 = 41208647 // 11:26:48.647
var expectMachineID byte = 12
assert.Equal(t, expectSeq, GetSeqFromID(lastID))
assert.Equal(t, expectTime, GetTimeFromID(lastID))
assert.Equal(t, expectMachineID, GetMachineFromID(lastID))
}
func BenchmarkFastID_GenID(b *testing.B) {
var operatorID uint = 10
var userID uint = 123
for i := 0; i < b.N; i++ {
_ = StdFastID.GenID(operatorID, userID)
}
}
|
Bycob/world
|
projects/world/core/GridStorage.h
|
<gh_stars>10-100
#ifndef WORLD_GRID_STORAGE_H
#define WORLD_GRID_STORAGE_H
#include "world/core/WorldConfig.h"
#include <type_traits>
#include <map>
#include "world/core/TileSystem.h"
#include "NodeCache.h"
#include "world/terrain/Terrain.h"
#include "GridStorageReducer.h"
namespace world {
class WORLDAPI_EXPORT GridStorageBase {
public:
virtual ~GridStorageBase() = default;
virtual bool has(const TileCoordinates &coords) const = 0;
/** Removes the tile from the GridStorageBase. If `keepCache` is set to
* true, all the cached tile information are kept, if they exist. */
virtual void remove(const TileCoordinates &coords, bool keepCache) = 0;
virtual NodeCache &getCache() = 0;
virtual void setReducer(GridStorageReducer *reducer);
protected:
GridStorageReducer *_reducer = nullptr;
};
class WORLDAPI_EXPORT IGridElement {
public:
virtual ~IGridElement() = default;
virtual void saveTo(NodeCache &cache) const {}
/** Read cached information about this element. Returns false
* if either the element does not exist in cache or if its related data
* are corrupted. */
// It is required that we create a minimum, ungenerated version of the
// tile before reading the cache
virtual bool tryLoadFrom(const NodeCache &cache) { return false; }
};
class WORLDAPI_EXPORT TerrainElement : public IGridElement {
public:
Terrain _terrain;
TerrainElement(int size) : _terrain(size) {}
TerrainElement(Terrain terrain) : _terrain(std::move(terrain)) {}
TerrainElement(Terrain &&terrain) : _terrain(terrain) {}
void saveTo(NodeCache &cache) const override {
cache.saveTerrain("terrain", _terrain);
}
bool tryLoadFrom(const NodeCache &cache) {
return cache.readTerrainInplace("terrain", _terrain);
}
};
template <
typename TElement,
std::enable_if_t<std::is_base_of<IGridElement, TElement>::value, int> = 0>
class GridStorage : public GridStorageBase {
public:
NodeCache _cache;
GridStorage() = default;
~GridStorage() override {
// Cache every remaining tile in storage
cacheAll();
}
GridStorage(const GridStorage &other) = delete;
GridStorage(GridStorage &&other) noexcept = default;
GridStorage &operator=(const GridStorage &other) = delete;
GridStorage &operator=(GridStorage &&other) noexcept = default;
template <typename... Args>
TElement &set(const TileCoordinates &coords, Args &&... args) {
if (_reducer != nullptr)
_reducer->registerAccess(coords);
return *(_storage[coords] = std::make_unique<TElement>(args...));
}
/** Get the element at the given coordinates. If this element does
* not exist, it is created with the arguments passed in parameters.
* If the element is cached, it is retrieved from the cache. */
template <typename... Args>
TElement &getOrCreate(const TileCoordinates &coords, Args &&... args) {
if (_reducer != nullptr)
_reducer->registerAccess(coords);
auto it = _storage.insert({coords, nullptr});
if (it.second) {
it.first->second = std::make_unique<TElement>(args...);
}
return *it.first->second;
}
/** Get the element at the given coordinates. If this element does
* not exist, it is created with the arguments passed in parameters,
* and the callback is called on this element.
* If the element was cached, it is retrieved from the cache and the
* callback is not called. */
template <typename... Args>
TElement &getOrCreateCallback(const TileCoordinates &coords,
std::function<void(TElement &)> callback,
Args &&... args) {
if (_reducer != nullptr)
_reducer->registerAccess(coords);
auto it = _storage.insert({coords, nullptr});
if (it.second) {
it.first->second = std::make_unique<TElement>(args...);
callback(*it.first->second);
}
return *it.first->second;
}
bool tryGet(const TileCoordinates &coords, TElement **elemPtr) const {
auto it = _storage.find(coords);
if (it != _storage.end()) {
if (_reducer != nullptr)
_reducer->registerAccess(coords);
*elemPtr = it->second.get();
return true;
} else {
return false;
}
}
TElement &get(const TileCoordinates &coords) const {
TElement *elemPtr;
if (tryGet(coords, &elemPtr)) {
return *elemPtr;
} else {
std::stringstream sstream;
sstream << "Tile not found: " << coords._pos << ", " << coords._lod;
throw std::runtime_error(sstream.str());
}
}
optional<TElement &> getopt(const TileCoordinates &coords) const {
TElement *elemPtr;
if (tryGet(coords, &elemPtr)) {
return *elemPtr;
} else {
return nullopt;
}
}
// Tiles are created externally
// but when they are cached, they still need be created by the caller
// So for example when doing a getopt:
// - if the tile is not cached nor created, return nullopt
// - if the tile is created in memory, return the tile
// - if the tile is cached: it should be created but initialized with the
// cache
// TODO function tryGetOrUncache, and getoptFromCache can do what described
// above?
bool has(const TileCoordinates &coords) const override {
return _storage.find(coords) != _storage.end();
}
bool isCached(const TileCoordinates &coords) const {
return _cache.hasChild(coords.toKey());
}
/** Try to get cached tile. Update elem and returns true if
* success, return false otherwise. */
bool readTileFromCache(const TileCoordinates &coords, TElement &elem) {
if (!_cache.isAvailable()) {
return false;
} else {
NodeCache tileCache(_cache, coords.toKey());
return elem.tryLoadFrom(tileCache);
}
}
void writeTileToCache(const TileCoordinates &coords, TElement &elem) {
if (_cache.isAvailable()) {
NodeCache tileCache(_cache, coords.toKey());
dynamic_cast<IGridElement *>(&elem)->saveTo(tileCache);
}
}
/** \param keepCache If true, the tile is only removed from memory
* but is saved to cache beforehand. If false, the tile is completely
* removed, from memory and from cache if needed. */
void remove(const TileCoordinates &coords, bool keepCache) override {
auto it = _storage.find(coords);
if (it == _storage.end()) {
return;
}
if (keepCache) {
writeTileToCache(it->first, *it->second);
} else {
NodeCache tileCache(_cache, coords.toKey());
tileCache.clear();
}
_storage.erase(it);
}
size_t size() const { return _storage.size(); }
/** Save all the tiles to the cache. */
void cacheAll() {
if (_cache.isAvailable()) {
for (auto &e : _storage) {
writeTileToCache(e.first, *e.second);
}
}
}
NodeCache &getCache() override { return _cache; }
private:
std::map<TileCoordinates, std::unique_ptr<TElement>> _storage;
};
typedef GridStorage<TerrainElement> TerrainGrid;
} // namespace world
#endif // WORLD_GRID_STORAGE_H
|
work-design/work.design
|
test/controllers/task_templates_controller_test.rb
|
<reponame>work-design/work.design<gh_stars>10-100
require 'test_helper'
class TaskTemplatesControllerTest < ActionDispatch::IntegrationTest
setup do
@task_template = task_templates(:one)
end
test "should get index" do
get task_templates_url
assert_response :success
end
test "should get new" do
get new_task_template_url
assert_response :success
end
test "should create task_template" do
assert_difference('TaskTemplate.count') do
post task_templates_url, params: { task_template: { } }
end
assert_redirected_to task_template_url(TaskTemplate.last)
end
test "should show task_template" do
get task_template_url(@task_template)
assert_response :success
end
test "should get edit" do
get edit_task_template_url(@task_template)
assert_response :success
end
test "should update task_template" do
patch task_template_url(@task_template), params: { task_template: { } }
assert_redirected_to task_template_url(@task_template)
end
test "should destroy task_template" do
assert_difference('TaskTemplate.count', -1) do
delete task_template_url(@task_template)
end
assert_redirected_to task_templates_url
end
end
|
jjuliano/brutal
|
sources/utils/test/brutal/codec/inflate.c
|
#include <brutal/alloc/global.h>
#include <brutal/codec/deflate/inflate.h>
#include "test/test.h"
TEST(inflate_uncompressed)
{
uint8_t out_storage[512];
const uint8_t in_storage[] = {1, 11, 0, 244, 255, 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
size_t size = UNWRAP(deflate_decompress_data(in_storage, sizeof(in_storage), out_storage, sizeof(out_storage)));
// A single uncompressed block has 5 extra bytes
assert_equal(size, sizeof(in_storage) - 5);
}
TEST(inflate_empty)
{
uint8_t out_storage[512];
/* Empty buffer, fixed, 6 bits of padding in the second byte set to 1 */
const uint8_t in_storage[] = {
0x03, 0xFC};
size_t size = UNWRAP(deflate_decompress_data(in_storage, sizeof(in_storage), out_storage, sizeof(out_storage)));
assert_equal(size, 0u);
}
TEST(inflate_empty_no_literals)
{
uint8_t out_storage[512];
/* Empty buffer, dynamic with 256 as only literal/length code
*
* You could argue that since the RFC only has an exception allowing
* one symbol for the distance tree, the literal/length tree should
* be complete. However gzip allows this.
*
* See also: https://github.com/madler/zlib/issues/75
*/
static const uint8_t in_storage[] = {
0x05, 0xCA, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0xFF,
0x6B, 0x01, 0x00};
size_t size = UNWRAP(deflate_decompress_data(in_storage, sizeof(in_storage), out_storage, sizeof(out_storage)));
assert_equal(size, 0u);
}
TEST(inflate_rle)
{
uint8_t out_storage[512];
/* 256 zero bytes compressed using RLE (only one distance code) */
const uint8_t in_storage[] = {
0xE5, 0xC0, 0x81, 0x00, 0x00, 0x00, 0x00, 0x80, 0xA0, 0xFC,
0xA9, 0x07, 0x39, 0x73, 0x01};
size_t size = UNWRAP(deflate_decompress_data(in_storage, sizeof(in_storage), out_storage, sizeof(out_storage)));
// Should be 256
assert_equal(size, 256u);
}
TEST(inflate_huffman)
{
uint8_t out_storage[512];
/* 256 zero bytes compressed using Huffman only (no match or distance codes) */
const uint8_t in_storage[] = {
0x05, 0xCA, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xFF,
0xD5, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02};
size_t size = UNWRAP(deflate_decompress_data(in_storage, sizeof(in_storage), out_storage, sizeof(out_storage)));
// Should be 256
assert_equal(size, 256u);
}
TEST(inflate_max_matchlen)
{
uint8_t out_storage[512];
/* 259 zero bytes compressed using literal/length code 285 (len 258) */
static const uint8_t in_storage[] = {
0xED, 0xCC, 0x81, 0x00, 0x00, 0x00, 0x00, 0x80, 0xA0, 0xFC,
0xA9, 0x17, 0xB9, 0x00, 0x2C};
size_t size = UNWRAP(deflate_decompress_data(in_storage, sizeof(in_storage), out_storage, sizeof(out_storage)));
// Should be 259
assert_equal(size, 259u);
}
|
ChristianSkov123/Authentication_Example
|
node_modules/@loopback/boot/dist/boot.component.js
|
<filename>node_modules/@loopback/boot/dist/boot.component.js
"use strict";
// Copyright IBM Corp. 2018,2020. All Rights Reserved.
// Node module: @loopback/boot
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
Object.defineProperty(exports, "__esModule", { value: true });
exports.BootComponent = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@loopback/core");
const booters_1 = require("./booters");
const bootstrapper_1 = require("./bootstrapper");
const keys_1 = require("./keys");
/**
* BootComponent is used to export the default list of Booter's made
* available by this module as well as bind the BootStrapper to the app so it
* can be used to run the Booters.
*/
let BootComponent = class BootComponent {
/**
*
* @param app - Application instance
*/
constructor(app) {
// Export a list of default booters in the component so they get bound
// automatically when this component is mounted.
this.booters = [
booters_1.ApplicationMetadataBooter,
booters_1.ControllerBooter,
booters_1.RepositoryBooter,
booters_1.ServiceBooter,
booters_1.DataSourceBooter,
booters_1.LifeCycleObserverBooter,
booters_1.InterceptorProviderBooter,
booters_1.ModelApiBooter,
booters_1.ModelBooter,
];
// Bound as a SINGLETON so it can be cached as it has no state
app
.bind(keys_1.BootBindings.BOOTSTRAPPER_KEY)
.toClass(bootstrapper_1.Bootstrapper)
.inScope(core_1.BindingScope.SINGLETON);
}
};
BootComponent = (0, tslib_1.__decorate)([
(0, tslib_1.__param)(0, (0, core_1.inject)(core_1.CoreBindings.APPLICATION_INSTANCE)),
(0, tslib_1.__metadata)("design:paramtypes", [core_1.Application])
], BootComponent);
exports.BootComponent = BootComponent;
//# sourceMappingURL=boot.component.js.map
|
iceignatius/genutil
|
gen/intutil.h
|
<filename>gen/intutil.h<gh_stars>0
/**
* @file
* @brief Integer utility.
* @details Some small and simple utility of integer calculation.
* @author 王文佑
* @date 2016.03.19
* @copyright ZLib Licence
* @see http://www.openfoundry.org/of/projects/2419
*/
#ifndef _GEN_INTUTIL_H_
#define _GEN_INTUTIL_H_
#include <stdbool.h>
#include <stdint.h>
#include <limits.h>
#ifdef __cplusplus
extern "C" {
#endif
static inline
bool intutil_is_pow2(unsigned long value)
{
/// Test is the input one of the power series of 2.
return !( value & ( value - 1 ) );
}
static inline
bool intutil_is_pow2_ull(unsigned long long value)
{
/// Test is the input one of the power series of 2.
return !( value & ( value - 1 ) );
}
static inline
unsigned long intutil_ceil_pow2(unsigned long value)
{
/// Calculate the smallest value of power series of 2 that
/// is great equal than the specific input @a value.
--value;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
#if ULONG_MAX >= UINT32_MAX
value |= value >> 16;
#endif
#if ULONG_MAX >= UINT64_MAX
value |= value >> 32;
#endif
#if ULONG_MAX > UINT64_MAX
#error Not support this kind of range.
#endif
return ++value;
}
static inline
unsigned long long intutil_ceil_pow2_ull(unsigned long long value)
{
/// Unsigned long long version of ::intutil_ceil_pow2.
--value;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
#if ULLONG_MAX >= UINT32_MAX
value |= value >> 16;
#endif
#if ULLONG_MAX >= UINT64_MAX
value |= value >> 32;
#endif
#if ULLONG_MAX > UINT64_MAX
#error Not support this kind of range.
#endif
return ++value;
}
static inline
unsigned long intutil_ceil_mul_n(unsigned long value, unsigned long n)
{
/// Calculate the smallest value of multiple of @a n that
/// is great equal than the specific input @a value.
return ( value + ( n - 1 ) ) / n * n;
}
static inline
unsigned long long intutil_ceil_mul_n_ull(unsigned long long value, unsigned long long n)
{
/// Unsigned long long version of ::intutil_ceil_mul_n.
return ( value + ( n - 1 ) ) / n * n;
}
static inline
unsigned long intutil_ceil_mul_pow2(unsigned long value, unsigned long n)
{
/// Similarly to ::intutil_ceil_mul_n, but optimised for the multiple of series of power 2.
/// @warning The input @a n must be one of the power series of 2,
/// or the behaviour bill be undefined.
--n;
return ( value + n ) & ~n;
}
static inline
unsigned long long intutil_ceil_mul_pow2_ull(unsigned long long value, unsigned long long n)
{
/// Unsigned long long version of ::intutil_ceil_mul_pow2.
--n;
return ( value + n ) & ~n;
}
static inline
unsigned long intutil_ceil_mul_4(unsigned long value)
{
/// Similarly to ::intutil_ceil_mul_n, but optimised for multiple of 4.
return ( value + ( 4 - 1 ) ) & ~( 4 - 1 );
}
static inline
unsigned long long intutil_ceil_mul_4_ull(unsigned long long value)
{
/// Unsigned long long version of ::intutil_ceil_mul_4.
return ( value + ( 4 - 1 ) ) & ~( 4 - 1 );
}
static inline
unsigned long intutil_ceil_mul_8(unsigned long value)
{
/// Similarly to ::intutil_ceil_mul_n, but optimised for multiple of 8.
return ( value + ( 8 - 1 ) ) & ~( 8 - 1 );
}
static inline
unsigned long long intutil_ceil_mul_8_ull(unsigned long long value)
{
/// Unsigned long long version of ::intutil_ceil_mul_8.
return ( value + ( 8 - 1 ) ) & ~( 8 - 1 );
}
static inline
unsigned long intutil_ceil_mul_16(unsigned long value)
{
/// Similarly to ::intutil_ceil_mul_n, but optimised for multiple of 16.
return ( value + ( 16 - 1 ) ) & ~( 16 - 1 );
}
static inline
unsigned long long intutil_ceil_mul_16_ull(unsigned long long value)
{
/// Unsigned long long version of ::intutil_ceil_mul_4.
return ( value + ( 16 - 1 ) ) & ~( 16 - 1 );
}
static inline
unsigned long intutil_ceil_mul_32(unsigned long value)
{
/// Similarly to ::intutil_ceil_mul_n, but optimised for multiple of 32.
return ( value + ( 32 - 1 ) ) & ~( 32 - 1 );
}
static inline
unsigned long long intutil_ceil_mul_32_ull(unsigned long long value)
{
/// Unsigned long long version of ::intutil_ceil_mul_4.
return ( value + ( 32 - 1 ) ) & ~( 32 - 1 );
}
static inline
unsigned long intutil_ceil_mul_64(unsigned long value)
{
/// Similarly to ::intutil_ceil_mul_n, but optimised for multiple of 64.
return ( value + ( 64 - 1 ) ) & ~( 64 - 1 );
}
static inline
unsigned long long intutil_ceil_mul_64_ull(unsigned long long value)
{
/// Unsigned long long version of ::intutil_ceil_mul_4.
return ( value + ( 64 - 1 ) ) & ~( 64 - 1 );
}
#ifdef __cplusplus
} // extern "C"
#endif
#endif
|
ulrichwi/ros-tinkerforge_sensors
|
src/tinkerforge/bricklet_rotary_encoder.c
|
<reponame>ulrichwi/ros-tinkerforge_sensors
/* ***********************************************************
* This file was automatically generated on 2018-11-28. *
* *
* C/C++ Bindings Version 2.1.23 *
* *
* If you have a bugfix for this file and want to commit it, *
* please fix the bug in the generator. You can find a link *
* to the generators git repository on tinkerforge.com *
*************************************************************/
#define IPCON_EXPOSE_INTERNALS
#include "bricklet_rotary_encoder.h"
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*Count_CallbackFunction)(int32_t count, void *user_data);
typedef void (*CountReached_CallbackFunction)(int32_t count, void *user_data);
typedef void (*Pressed_CallbackFunction)(void *user_data);
typedef void (*Released_CallbackFunction)(void *user_data);
#if defined _MSC_VER || defined __BORLANDC__
#pragma pack(push)
#pragma pack(1)
#define ATTRIBUTE_PACKED
#elif defined __GNUC__
#ifdef _WIN32
// workaround struct packing bug in GCC 4.7 on Windows
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52991
#define ATTRIBUTE_PACKED __attribute__((gcc_struct, packed))
#else
#define ATTRIBUTE_PACKED __attribute__((packed))
#endif
#else
#error unknown compiler, do not know how to enable struct packing
#endif
typedef struct {
PacketHeader header;
uint8_t reset;
} ATTRIBUTE_PACKED GetCount_Request;
typedef struct {
PacketHeader header;
int32_t count;
} ATTRIBUTE_PACKED GetCount_Response;
typedef struct {
PacketHeader header;
uint32_t period;
} ATTRIBUTE_PACKED SetCountCallbackPeriod_Request;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetCountCallbackPeriod_Request;
typedef struct {
PacketHeader header;
uint32_t period;
} ATTRIBUTE_PACKED GetCountCallbackPeriod_Response;
typedef struct {
PacketHeader header;
char option;
int32_t min;
int32_t max;
} ATTRIBUTE_PACKED SetCountCallbackThreshold_Request;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetCountCallbackThreshold_Request;
typedef struct {
PacketHeader header;
char option;
int32_t min;
int32_t max;
} ATTRIBUTE_PACKED GetCountCallbackThreshold_Response;
typedef struct {
PacketHeader header;
uint32_t debounce;
} ATTRIBUTE_PACKED SetDebouncePeriod_Request;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetDebouncePeriod_Request;
typedef struct {
PacketHeader header;
uint32_t debounce;
} ATTRIBUTE_PACKED GetDebouncePeriod_Response;
typedef struct {
PacketHeader header;
int32_t count;
} ATTRIBUTE_PACKED Count_Callback;
typedef struct {
PacketHeader header;
int32_t count;
} ATTRIBUTE_PACKED CountReached_Callback;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED IsPressed_Request;
typedef struct {
PacketHeader header;
uint8_t pressed;
} ATTRIBUTE_PACKED IsPressed_Response;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED Pressed_Callback;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED Released_Callback;
typedef struct {
PacketHeader header;
} ATTRIBUTE_PACKED GetIdentity_Request;
typedef struct {
PacketHeader header;
char uid[8];
char connected_uid[8];
char position;
uint8_t hardware_version[3];
uint8_t firmware_version[3];
uint16_t device_identifier;
} ATTRIBUTE_PACKED GetIdentity_Response;
#if defined _MSC_VER || defined __BORLANDC__
#pragma pack(pop)
#endif
#undef ATTRIBUTE_PACKED
static void rotary_encoder_callback_wrapper_count(DevicePrivate *device_p, Packet *packet) {
Count_CallbackFunction callback_function;
void *user_data = device_p->registered_callback_user_data[DEVICE_NUM_FUNCTION_IDS + ROTARY_ENCODER_CALLBACK_COUNT];
Count_Callback *callback = (Count_Callback *)packet;
*(void **)(&callback_function) = device_p->registered_callbacks[DEVICE_NUM_FUNCTION_IDS + ROTARY_ENCODER_CALLBACK_COUNT];
if (callback_function == NULL) {
return;
}
callback->count = leconvert_int32_from(callback->count);
callback_function(callback->count, user_data);
}
static void rotary_encoder_callback_wrapper_count_reached(DevicePrivate *device_p, Packet *packet) {
CountReached_CallbackFunction callback_function;
void *user_data = device_p->registered_callback_user_data[DEVICE_NUM_FUNCTION_IDS + ROTARY_ENCODER_CALLBACK_COUNT_REACHED];
CountReached_Callback *callback = (CountReached_Callback *)packet;
*(void **)(&callback_function) = device_p->registered_callbacks[DEVICE_NUM_FUNCTION_IDS + ROTARY_ENCODER_CALLBACK_COUNT_REACHED];
if (callback_function == NULL) {
return;
}
callback->count = leconvert_int32_from(callback->count);
callback_function(callback->count, user_data);
}
static void rotary_encoder_callback_wrapper_pressed(DevicePrivate *device_p, Packet *packet) {
Pressed_CallbackFunction callback_function;
void *user_data = device_p->registered_callback_user_data[DEVICE_NUM_FUNCTION_IDS + ROTARY_ENCODER_CALLBACK_PRESSED];
(void)packet;
*(void **)(&callback_function) = device_p->registered_callbacks[DEVICE_NUM_FUNCTION_IDS + ROTARY_ENCODER_CALLBACK_PRESSED];
if (callback_function == NULL) {
return;
}
callback_function(user_data);
}
static void rotary_encoder_callback_wrapper_released(DevicePrivate *device_p, Packet *packet) {
Released_CallbackFunction callback_function;
void *user_data = device_p->registered_callback_user_data[DEVICE_NUM_FUNCTION_IDS + ROTARY_ENCODER_CALLBACK_RELEASED];
(void)packet;
*(void **)(&callback_function) = device_p->registered_callbacks[DEVICE_NUM_FUNCTION_IDS + ROTARY_ENCODER_CALLBACK_RELEASED];
if (callback_function == NULL) {
return;
}
callback_function(user_data);
}
void rotary_encoder_create(RotaryEncoder *rotary_encoder, const char *uid, IPConnection *ipcon) {
DevicePrivate *device_p;
device_create(rotary_encoder, uid, ipcon->p, 2, 0, 0);
device_p = rotary_encoder->p;
device_p->response_expected[ROTARY_ENCODER_FUNCTION_GET_COUNT] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[ROTARY_ENCODER_FUNCTION_SET_COUNT_CALLBACK_PERIOD] = DEVICE_RESPONSE_EXPECTED_TRUE;
device_p->response_expected[ROTARY_ENCODER_FUNCTION_GET_COUNT_CALLBACK_PERIOD] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[ROTARY_ENCODER_FUNCTION_SET_COUNT_CALLBACK_THRESHOLD] = DEVICE_RESPONSE_EXPECTED_TRUE;
device_p->response_expected[ROTARY_ENCODER_FUNCTION_GET_COUNT_CALLBACK_THRESHOLD] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[ROTARY_ENCODER_FUNCTION_SET_DEBOUNCE_PERIOD] = DEVICE_RESPONSE_EXPECTED_TRUE;
device_p->response_expected[ROTARY_ENCODER_FUNCTION_GET_DEBOUNCE_PERIOD] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[ROTARY_ENCODER_FUNCTION_IS_PRESSED] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->response_expected[ROTARY_ENCODER_FUNCTION_GET_IDENTITY] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE;
device_p->callback_wrappers[ROTARY_ENCODER_CALLBACK_COUNT] = rotary_encoder_callback_wrapper_count;
device_p->callback_wrappers[ROTARY_ENCODER_CALLBACK_COUNT_REACHED] = rotary_encoder_callback_wrapper_count_reached;
device_p->callback_wrappers[ROTARY_ENCODER_CALLBACK_PRESSED] = rotary_encoder_callback_wrapper_pressed;
device_p->callback_wrappers[ROTARY_ENCODER_CALLBACK_RELEASED] = rotary_encoder_callback_wrapper_released;
}
void rotary_encoder_destroy(RotaryEncoder *rotary_encoder) {
device_release(rotary_encoder->p);
}
int rotary_encoder_get_response_expected(RotaryEncoder *rotary_encoder, uint8_t function_id, bool *ret_response_expected) {
return device_get_response_expected(rotary_encoder->p, function_id, ret_response_expected);
}
int rotary_encoder_set_response_expected(RotaryEncoder *rotary_encoder, uint8_t function_id, bool response_expected) {
return device_set_response_expected(rotary_encoder->p, function_id, response_expected);
}
int rotary_encoder_set_response_expected_all(RotaryEncoder *rotary_encoder, bool response_expected) {
return device_set_response_expected_all(rotary_encoder->p, response_expected);
}
void rotary_encoder_register_callback(RotaryEncoder *rotary_encoder, int16_t callback_id, void *function, void *user_data) {
device_register_callback(rotary_encoder->p, callback_id, function, user_data);
}
int rotary_encoder_get_api_version(RotaryEncoder *rotary_encoder, uint8_t ret_api_version[3]) {
return device_get_api_version(rotary_encoder->p, ret_api_version);
}
int rotary_encoder_get_count(RotaryEncoder *rotary_encoder, bool reset, int32_t *ret_count) {
DevicePrivate *device_p = rotary_encoder->p;
GetCount_Request request;
GetCount_Response response;
int ret;
ret = packet_header_create(&request.header, sizeof(request), ROTARY_ENCODER_FUNCTION_GET_COUNT, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.reset = reset ? 1 : 0;
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response);
if (ret < 0) {
return ret;
}
*ret_count = leconvert_int32_from(response.count);
return ret;
}
int rotary_encoder_set_count_callback_period(RotaryEncoder *rotary_encoder, uint32_t period) {
DevicePrivate *device_p = rotary_encoder->p;
SetCountCallbackPeriod_Request request;
int ret;
ret = packet_header_create(&request.header, sizeof(request), ROTARY_ENCODER_FUNCTION_SET_COUNT_CALLBACK_PERIOD, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.period = leconvert_uint32_to(period);
ret = device_send_request(device_p, (Packet *)&request, NULL);
return ret;
}
int rotary_encoder_get_count_callback_period(RotaryEncoder *rotary_encoder, uint32_t *ret_period) {
DevicePrivate *device_p = rotary_encoder->p;
GetCountCallbackPeriod_Request request;
GetCountCallbackPeriod_Response response;
int ret;
ret = packet_header_create(&request.header, sizeof(request), ROTARY_ENCODER_FUNCTION_GET_COUNT_CALLBACK_PERIOD, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response);
if (ret < 0) {
return ret;
}
*ret_period = leconvert_uint32_from(response.period);
return ret;
}
int rotary_encoder_set_count_callback_threshold(RotaryEncoder *rotary_encoder, char option, int32_t min, int32_t max) {
DevicePrivate *device_p = rotary_encoder->p;
SetCountCallbackThreshold_Request request;
int ret;
ret = packet_header_create(&request.header, sizeof(request), ROTARY_ENCODER_FUNCTION_SET_COUNT_CALLBACK_THRESHOLD, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.option = option;
request.min = leconvert_int32_to(min);
request.max = leconvert_int32_to(max);
ret = device_send_request(device_p, (Packet *)&request, NULL);
return ret;
}
int rotary_encoder_get_count_callback_threshold(RotaryEncoder *rotary_encoder, char *ret_option, int32_t *ret_min, int32_t *ret_max) {
DevicePrivate *device_p = rotary_encoder->p;
GetCountCallbackThreshold_Request request;
GetCountCallbackThreshold_Response response;
int ret;
ret = packet_header_create(&request.header, sizeof(request), ROTARY_ENCODER_FUNCTION_GET_COUNT_CALLBACK_THRESHOLD, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response);
if (ret < 0) {
return ret;
}
*ret_option = response.option;
*ret_min = leconvert_int32_from(response.min);
*ret_max = leconvert_int32_from(response.max);
return ret;
}
int rotary_encoder_set_debounce_period(RotaryEncoder *rotary_encoder, uint32_t debounce) {
DevicePrivate *device_p = rotary_encoder->p;
SetDebouncePeriod_Request request;
int ret;
ret = packet_header_create(&request.header, sizeof(request), ROTARY_ENCODER_FUNCTION_SET_DEBOUNCE_PERIOD, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
request.debounce = leconvert_uint32_to(debounce);
ret = device_send_request(device_p, (Packet *)&request, NULL);
return ret;
}
int rotary_encoder_get_debounce_period(RotaryEncoder *rotary_encoder, uint32_t *ret_debounce) {
DevicePrivate *device_p = rotary_encoder->p;
GetDebouncePeriod_Request request;
GetDebouncePeriod_Response response;
int ret;
ret = packet_header_create(&request.header, sizeof(request), ROTARY_ENCODER_FUNCTION_GET_DEBOUNCE_PERIOD, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response);
if (ret < 0) {
return ret;
}
*ret_debounce = leconvert_uint32_from(response.debounce);
return ret;
}
int rotary_encoder_is_pressed(RotaryEncoder *rotary_encoder, bool *ret_pressed) {
DevicePrivate *device_p = rotary_encoder->p;
IsPressed_Request request;
IsPressed_Response response;
int ret;
ret = packet_header_create(&request.header, sizeof(request), ROTARY_ENCODER_FUNCTION_IS_PRESSED, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response);
if (ret < 0) {
return ret;
}
*ret_pressed = response.pressed != 0;
return ret;
}
int rotary_encoder_get_identity(RotaryEncoder *rotary_encoder, char ret_uid[8], char ret_connected_uid[8], char *ret_position, uint8_t ret_hardware_version[3], uint8_t ret_firmware_version[3], uint16_t *ret_device_identifier) {
DevicePrivate *device_p = rotary_encoder->p;
GetIdentity_Request request;
GetIdentity_Response response;
int ret;
ret = packet_header_create(&request.header, sizeof(request), ROTARY_ENCODER_FUNCTION_GET_IDENTITY, device_p->ipcon_p, device_p);
if (ret < 0) {
return ret;
}
ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response);
if (ret < 0) {
return ret;
}
memcpy(ret_uid, response.uid, 8);
memcpy(ret_connected_uid, response.connected_uid, 8);
*ret_position = response.position;
memcpy(ret_hardware_version, response.hardware_version, 3 * sizeof(uint8_t));
memcpy(ret_firmware_version, response.firmware_version, 3 * sizeof(uint8_t));
*ret_device_identifier = leconvert_uint16_from(response.device_identifier);
return ret;
}
#ifdef __cplusplus
}
#endif
|
juanfelipe82193/opensap
|
sapui5-sdk-1.74.0/test-resources/sap/gantt/qunit/shape/ResizeShadowShape.qunit.js
|
<gh_stars>0
/*global QUnit*/
sap.ui.define([
"sap/gantt/config/Shape",
"sap/gantt/config/TimeHorizon",
"sap/gantt/GanttChart",
"sap/gantt/shape/ResizeShadowShape",
"sap/gantt/shape/Path",
"sap/gantt/shape/Group",
"sap/gantt/shape/Rectangle",
"sap/gantt/shape/Line",
"sap/gantt/shape/Image",
"sap/gantt/shape/Polygon",
"sap/gantt/shape/Polyline",
"sap/gantt/shape/Circle"
], function (ShapeConfig, TimeHorizon, GanttChart) {
"use strict";
QUnit.module("Test Resize Shadow Shape.", {
beforeEach: function () {
// shape configuration
this.oPathConfig = new ShapeConfig({
key: "path",
shapeClassName: "sap.gantt.shape.Path",
shapeProperties: {
time: "{startTime}",
endTime: "{endTime}"
},
resizeShadowClassName: "sap.gantt.shape.ResizeShadowShape"
});
this.oGroupConfig = new ShapeConfig({
key: "group",
shapeClassName: "sap.gantt.shape.Group",
shapeProperties: {
time: "{startTime}",
endTime: "{endTime}",
isDuration: true
},
resizeShadowClassName: "sap.gantt.shape.ResizeShadowShape",
groupAggregation: [
new ShapeConfig({
key: "gPath",
shapeClassName: "sap.gantt.shape.Path",
shapeProperties: {
time: "{startTime}",
endTime: "{endTime}"
}
})
]
});
this.oRectConfig = new ShapeConfig({
key: "rect",
shapeClassName: "sap.gantt.shape.Rectangle",
shapeProperties: {
time: "{startTime}",
endTime: "{endTime}",
isDuration: true
},
resizeShadowClassName: "sap.gantt.shape.ResizeShadowShape"
});
this.oLineConfig = new ShapeConfig({
key: "line",
shapeClassName: "sap.gantt.shape.Line",
shapeProperties: {
time: "{startTime}",
endTime: "{endTime}"
},
resizeShadowClassName: "sap.gantt.shape.ResizeShadowShape"
});
this.oImageConfig = new ShapeConfig({
key: "image",
shapeClassName: "sap.gantt.shape.Image",
shapeProperties: {
time: "{startTime}",
endTime: "{endTime}"
},
resizeShadowClassName: "sap.gantt.shape.ResizeShadowShape"
});
this.oPolygonConfig = new ShapeConfig({
key: "polygon",
shapeClassName: "sap.gantt.shape.Polygon",
shapeProperties: {
time: "{startTime}"
},
resizeShadowClassName: "sap.gantt.shape.ResizeShadowShape"
});
this.oPolylineConfig = new ShapeConfig({
key: "polyline",
shapeClassName: "sap.gantt.shape.Polyline",
shapeProperties: {
time: "{startTime}"
},
resizeShadowClassName: "sap.gantt.shape.ResizeShadowShape"
});
this.oCircleConfig = new ShapeConfig({
key: "circle",
shapeClassName: "sap.gantt.shape.Circle",
shapeProperties: {
time: "{startTime}"
},
resizeShadowClassName: "sap.gantt.shape.ResizeShadowShape"
});
// GanttChart object which creates shape instance
var oTimeAxisConfig = new sap.gantt.config.TimeAxis({
planHorizon: new TimeHorizon({
startTime: "20140901000000",
endTime: "20141031000000"
})
});
this.oGanttChart = new GanttChart({
timeAxis: oTimeAxisConfig,
shapes: [this.oPathConfig, this.oGroupConfig, this.oRectConfig, this.oLineConfig, this.oImageConfig,
this.oPolygonConfig, this.oPolylineConfig, this.oCircleConfig]
});
this.oResizeShadowShapePath = this.oGanttChart.getShapeInstance("path").getAggregation("resizeShadowShape");
this.oResizeShadowShapeGroup = this.oGanttChart.getShapeInstance("group").getAggregation("resizeShadowShape");
this.oResizeShadowShapeRect = this.oGanttChart.getShapeInstance("rect").getAggregation("resizeShadowShape");
this.oResizeShadowShapeLine = this.oGanttChart.getShapeInstance("line").getAggregation("resizeShadowShape");
this.oResizeShadowShapeImage = this.oGanttChart.getShapeInstance("image").getAggregation("resizeShadowShape");
this.oResizeShadowShapePolygon = this.oGanttChart.getShapeInstance("polygon").getAggregation("resizeShadowShape");
this.oResizeShadowShapePolyline = this.oGanttChart.getShapeInstance("polyline").getAggregation("resizeShadowShape");
this.oResizeShadowShapeCircle = this.oGanttChart.getShapeInstance("circle").getAggregation("resizeShadowShape");
// call back parameter
this.oData = {
startTime: "20140919000000",
endTime: "20141012000000"
};
// call back parameter
this.oRowInfo = {
rowHeight: 32,
y: 0,
uid: "PATH:0000|SCHEME:ac_main[0]",
data: {
ut: [this.oData]
}
};
},
afterEach: function () {
this.oResizeShadowShapePath = undefined;
this.oResizeShadowShapeGroup = undefined;
this.oResizeShadowShapeRect = undefined;
this.oResizeShadowShapeLine = undefined;
this.oResizeShadowShapeImage = undefined;
this.oResizeShadowShapePolygon = undefined;
this.oResizeShadowShapePolyline = undefined;
this.oResizeShadowShapeCircle = undefined;
this.oData = undefined;
this.oRowInfo = undefined;
this.oGanttChart.destroy();
}
});
QUnit.test("Resize shadow shape under different shapes", function (assert) {
//path
assert.strictEqual(this.oResizeShadowShapePath.getD(this.oData, this.oRowInfo), "M 405.0187369882027 16 c 0,-7.5 7.5,-7.5 7.5,0 c 0,7.5 7.5,7.5 7.5,0", "Resize shadow shape for <Path> works fine.");
assert.strictEqual(this.oResizeShadowShapePath.getEnableSelection(this.oData, this.oRowInfo), false, "Resize shadow shape enableSelection works fine.");
assert.strictEqual(this.oResizeShadowShapePath.getFill(this.oData, this.oRowInfo), "none", "Resize shadow shape getFill works fine.");
assert.strictEqual(this.oResizeShadowShapePath.getStroke(this.oData, this.oRowInfo), "red", "Resize shadow shape getStroke works fine.");
assert.strictEqual(this.oResizeShadowShapePath.getIsDuration(this.oData, this.oRowInfo), false, "Resize shadow shape getIsDuration works fine.");
//group
assert.strictEqual(this.oResizeShadowShapeGroup.getD(this.oData, this.oRowInfo), "M 405.0187369882027 7.5 L 923.5426786953506 7.5 L 923.5426786953506 22.5 L 405.0187369882027 22.5 z", "Resize shadow shape for <Group> works fine.");
//rectangle
assert.strictEqual(this.oResizeShadowShapeRect.getD(this.oData, this.oRowInfo), "M 404.0187369882027 7.5 L 923.5426786953506 7.5 L 923.5426786953506 24.5 L 404.0187369882027 24.5 z", "Resize shadow shape for <Rectangle> works fine.");
//line
assert.strictEqual(this.oResizeShadowShapeLine.getD(this.oData, this.oRowInfo), "M 404.0187369882027 15 L 924.5426786953506 15 L 924.5426786953506 18 L 404.0187369882027 18 z", "Resize shadow shape for <Line> works fine.");
//image
assert.strictEqual(this.oResizeShadowShapeImage.getD(this.oData, this.oRowInfo), "M 394.0187369882027 5 L 416.0187369882027 5 L 416.0187369882027 27 L 394.0187369882027 27 z", "Resize shadow shape for <Image> works fine.");
//polygon
assert.strictEqual(this.oResizeShadowShapePolygon.getD(this.oData, this.oRowInfo), "M 398.0905337579272 12 L 405.0187369882027 8 L 411.94694021847823 12 L 411.94694021847823 20 L 405.0187369882027 24 L 398.0905337579272 20 z", "Resize shadow shape for <Polygon> works fine.");
//polyline
assert.strictEqual(this.oResizeShadowShapePolyline.getD(this.oData, this.oRowInfo), "M 390.0187369882027 16 L 395.0187369882027 16 L 400.0187369882027 8.5 L 410.0187369882027 23.5 L 415.0187369882027 16 L 420.0187369882027 16", "Resize shadow shape for <Polyline> works fine.");
//circle
assert.strictEqual(this.oResizeShadowShapeCircle.getD(this.oData, this.oRowInfo), "M 405.0187369882027 16 A 5 5, 0, 1, 1, 405.0187369882027 16", "Resize shadow shape for <Circle> Cx works fine.");
});
});
|
dlario/PyFlow
|
PyFlow/Packages/PyflowBase/__init__.py
|
<filename>PyFlow/Packages/PyflowBase/__init__.py
PACKAGE_NAME = 'PyflowBase'
from collections import OrderedDict
from PyFlow.UI.UIInterfaces import IPackage
# Pins
from PyFlow.Packages.PyflowBase.Pins.AnyPin import AnyPin
from PyFlow.Packages.PyflowBase.Pins.BoolPin import BoolPin
from PyFlow.Packages.PyflowBase.Pins.ExecPin import ExecPin
from PyFlow.Packages.PyflowBase.Pins.FloatPin import FloatPin
from PyFlow.Packages.PyflowBase.Pins.IntPin import IntPin
from PyFlow.Packages.PyflowBase.Pins.StringPin import StringPin
from PyFlow.Packages.PyflowBase.Pins.ListPin import ListPin
# Function based nodes
from PyFlow.Packages.PyflowBase.FunctionLibraries.ArrayLib import ArrayLib
from PyFlow.Packages.PyflowBase.FunctionLibraries.BoolLib import BoolLib
from PyFlow.Packages.PyflowBase.FunctionLibraries.DefaultLib import DefaultLib
from PyFlow.Packages.PyflowBase.FunctionLibraries.FloatLib import FloatLib
from PyFlow.Packages.PyflowBase.FunctionLibraries.IntLib import IntLib
from PyFlow.Packages.PyflowBase.FunctionLibraries.MathLib import MathLib
from PyFlow.Packages.PyflowBase.FunctionLibraries.MathAbstractLib import MathAbstractLib
from PyFlow.Packages.PyflowBase.FunctionLibraries.RandomLib import RandomLib
# Class based nodes
from PyFlow.Packages.PyflowBase.Nodes.branch import branch
from PyFlow.Packages.PyflowBase.Nodes.tick import tick
from PyFlow.Packages.PyflowBase.Nodes.charge import charge
from PyFlow.Packages.PyflowBase.Nodes.delay import delay
from PyFlow.Packages.PyflowBase.Nodes.deltaTime import deltaTime
from PyFlow.Packages.PyflowBase.Nodes.doN import doN
from PyFlow.Packages.PyflowBase.Nodes.doOnce import doOnce
from PyFlow.Packages.PyflowBase.Nodes.flipFlop import flipFlop
from PyFlow.Packages.PyflowBase.Nodes.forLoop import forLoop
from PyFlow.Packages.PyflowBase.Nodes.forEachLoop import forEachLoop
from PyFlow.Packages.PyflowBase.Nodes.forLoopWithBreak import forLoopWithBreak
from PyFlow.Packages.PyflowBase.Nodes.retriggerableDelay import retriggerableDelay
from PyFlow.Packages.PyflowBase.Nodes.sequence import sequence
from PyFlow.Packages.PyflowBase.Nodes.switchOnString import switchOnString
from PyFlow.Packages.PyflowBase.Nodes.timer import timer
from PyFlow.Packages.PyflowBase.Nodes.whileLoop import whileLoop
from PyFlow.Packages.PyflowBase.Nodes.commentNode import commentNode
from PyFlow.Packages.PyflowBase.Nodes.getVar import getVar
from PyFlow.Packages.PyflowBase.Nodes.setVar import setVar
from PyFlow.Packages.PyflowBase.Nodes.reroute import reroute
from PyFlow.Packages.PyflowBase.Nodes.rerouteExecs import rerouteExecs
from PyFlow.Packages.PyflowBase.Nodes.makeArray import makeArray
from PyFlow.Packages.PyflowBase.Nodes.makeList import makeList
from PyFlow.Packages.PyflowBase.Nodes.consoleOutput import consoleOutput
from PyFlow.Packages.PyflowBase.Nodes.address import address
from PyFlow.Packages.PyflowBase.Nodes.graphNodes import (
graphInputs,
graphOutputs
)
from PyFlow.Packages.PyflowBase.Nodes.pythonNode import pythonNode
from PyFlow.Packages.PyflowBase.Nodes.compound import compound
from PyFlow.Packages.PyflowBase.Nodes.constant import constant
from PyFlow.Packages.PyflowBase.Tools.ScreenshotTool import ScreenshotTool
from PyFlow.Packages.PyflowBase.Tools.AlignLeftTool import AlignLeftTool
from PyFlow.Packages.PyflowBase.Tools.AlignRightTool import AlignRightTool
from PyFlow.Packages.PyflowBase.Tools.AlignTopTool import AlignTopTool
from PyFlow.Packages.PyflowBase.Tools.AlignBottomTool import AlignBottomTool
from PyFlow.Packages.PyflowBase.Tools.HistoryTool import HistoryTool
from PyFlow.Packages.PyflowBase.Tools.PropertiesTool import PropertiesTool
from PyFlow.Packages.PyflowBase.Tools.VariablesTool import VariablesTool
# Factories
from PyFlow.Packages.PyflowBase.Factories.UIPinFactory import createUIPin
from PyFlow.Packages.PyflowBase.Factories.PinInputWidgetFactory import getInputWidget
from PyFlow.Packages.PyflowBase.Factories.UINodeFactory import createUINode
_FOO_LIBS = {
ArrayLib.__name__: ArrayLib(PACKAGE_NAME),
BoolLib.__name__: BoolLib(PACKAGE_NAME),
DefaultLib.__name__: DefaultLib(PACKAGE_NAME),
FloatLib.__name__: FloatLib(PACKAGE_NAME),
IntLib.__name__: IntLib(PACKAGE_NAME),
MathLib.__name__: MathLib(PACKAGE_NAME),
MathAbstractLib.__name__: MathAbstractLib(PACKAGE_NAME),
RandomLib.__name__: RandomLib(PACKAGE_NAME),
}
_NODES = {
branch.__name__: branch,
charge.__name__: charge,
delay.__name__: delay,
deltaTime.__name__: deltaTime,
doN.__name__: doN,
doOnce.__name__: doOnce,
flipFlop.__name__: flipFlop,
forLoop.__name__: forLoop,
forLoopWithBreak.__name__: forLoopWithBreak,
retriggerableDelay.__name__: retriggerableDelay,
sequence.__name__: sequence,
switchOnString.__name__: switchOnString,
timer.__name__: timer,
whileLoop.__name__: whileLoop,
commentNode.__name__: commentNode,
getVar.__name__: getVar,
setVar.__name__: setVar,
reroute.__name__: reroute,
rerouteExecs.__name__: rerouteExecs,
graphInputs.__name__: graphInputs,
graphOutputs.__name__: graphOutputs,
compound.__name__: compound,
pythonNode.__name__: pythonNode,
makeArray.__name__: makeArray,
makeList.__name__: makeList,
consoleOutput.__name__: consoleOutput,
forEachLoop.__name__: forEachLoop,
address.__name__: address,
constant.__name__: constant,
tick.__name__: tick
}
_PINS = {
AnyPin.__name__: AnyPin,
BoolPin.__name__: BoolPin,
ExecPin.__name__: ExecPin,
FloatPin.__name__: FloatPin,
IntPin.__name__: IntPin,
StringPin.__name__: StringPin,
ListPin.__name__: ListPin
}
# Toolbar will be created in following order
_TOOLS = OrderedDict()
_TOOLS[ScreenshotTool.__name__] = ScreenshotTool
_TOOLS[AlignLeftTool.__name__] = AlignLeftTool
_TOOLS[AlignRightTool.__name__] = AlignRightTool
_TOOLS[AlignTopTool.__name__] = AlignTopTool
_TOOLS[AlignBottomTool.__name__] = AlignBottomTool
_TOOLS[HistoryTool.__name__] = HistoryTool
_TOOLS[PropertiesTool.__name__] = PropertiesTool
_TOOLS[VariablesTool.__name__] = VariablesTool
class PyflowBase(IPackage):
def __init__(self):
super(PyflowBase, self).__init__()
@staticmethod
def GetFunctionLibraries():
return _FOO_LIBS
@staticmethod
def GetNodeClasses():
return _NODES
@staticmethod
def GetPinClasses():
return _PINS
@staticmethod
def GetToolClasses():
return _TOOLS
@staticmethod
def UIPinsFactory():
return createUIPin
@staticmethod
def UINodesFactory():
return createUINode
@staticmethod
def PinsInputWidgetFactory():
return getInputWidget
|
rudyzulemie/onos-1
|
core/net/src/main/java/org/onosproject/cluster/impl/ConfigFileBasedClusterMetadataProvider.java
|
<gh_stars>1-10
/*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cluster.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.onosproject.cluster.ClusterMetadata;
import org.onosproject.cluster.ClusterMetadataProvider;
import org.onosproject.cluster.ClusterMetadataProviderRegistry;
import org.onosproject.cluster.ClusterMetadataProviderService;
import org.onosproject.cluster.DefaultControllerNode;
import org.onosproject.cluster.Node;
import org.onosproject.cluster.NodeId;
import org.onosproject.cluster.PartitionId;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.store.service.Versioned;
import org.slf4j.Logger;
import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static org.onlab.util.Tools.groupedThreads;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provider of {@link ClusterMetadata cluster metadata} sourced from a local config file.
*/
@Component(immediate = true)
public class ConfigFileBasedClusterMetadataProvider implements ClusterMetadataProvider {
private final Logger log = getLogger(getClass());
private static final String CONFIG_DIR = "../config";
private static final String CONFIG_FILE_NAME = "cluster.json";
private static final File CONFIG_FILE = new File(CONFIG_DIR, CONFIG_FILE_NAME);
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected ClusterMetadataProviderRegistry providerRegistry;
private static final ProviderId PROVIDER_ID = new ProviderId("file", "none");
private final AtomicReference<Versioned<ClusterMetadata>> cachedMetadata = new AtomicReference<>();
private final ScheduledExecutorService configFileChangeDetector =
newSingleThreadScheduledExecutor(groupedThreads("onos/cluster/metadata/config-watcher", "", log));
private String metadataUrl;
private ObjectMapper mapper;
private ClusterMetadataProviderService providerService;
@Activate
public void activate() {
mapper = new ObjectMapper();
providerService = providerRegistry.register(this);
metadataUrl = System.getProperty("onos.cluster.metadata.uri", "file://" + CONFIG_DIR + "/" + CONFIG_FILE);
configFileChangeDetector.scheduleWithFixedDelay(() -> watchUrl(metadataUrl), 100, 500, TimeUnit.MILLISECONDS);
log.info("Started");
}
@Deactivate
public void deactivate() {
configFileChangeDetector.shutdown();
providerRegistry.unregister(this);
log.info("Stopped");
}
@Override
public ProviderId id() {
return PROVIDER_ID;
}
@Override
public Versioned<ClusterMetadata> getClusterMetadata() {
checkState(isAvailable());
synchronized (this) {
if (cachedMetadata.get() == null) {
cachedMetadata.set(blockForMetadata(metadataUrl));
}
return cachedMetadata.get();
}
}
private ClusterMetadataPrototype toPrototype(ClusterMetadata metadata) {
ClusterMetadataPrototype prototype = new ClusterMetadataPrototype();
prototype.setName(metadata.getName());
prototype.setController(metadata.getNodes()
.stream()
.map(this::toPrototype)
.collect(Collectors.toSet()));
prototype.setStorage(metadata.getStorageNodes()
.stream()
.map(this::toPrototype)
.collect(Collectors.toSet()));
prototype.setClusterSecret(metadata.getClusterSecret());
return prototype;
}
private NodePrototype toPrototype(Node node) {
NodePrototype prototype = new NodePrototype();
prototype.setId(node.id().id());
prototype.setHost(node.host());
prototype.setPort(node.tcpPort());
return prototype;
}
@Override
public void setClusterMetadata(ClusterMetadata metadata) {
try {
File configFile = new File(metadataUrl.replaceFirst("file://", ""));
Files.createParentDirs(configFile);
ClusterMetadataPrototype metadataPrototype = toPrototype(metadata);
mapper.writeValue(configFile, metadataPrototype);
cachedMetadata.set(fetchMetadata(metadataUrl));
providerService.clusterMetadataChanged(new Versioned<>(metadata, configFile.lastModified()));
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public void addActivePartitionMember(PartitionId partitionId, NodeId nodeId) {
throw new UnsupportedOperationException();
}
@Override
public void removeActivePartitionMember(PartitionId partitionId, NodeId nodeId) {
throw new UnsupportedOperationException();
}
@Override
public Set<NodeId> getActivePartitionMembers(PartitionId partitionId) {
throw new UnsupportedOperationException();
}
@Override
public boolean isAvailable() {
try {
URL url = new URL(metadataUrl);
if ("file".equals(url.getProtocol())) {
File file = new File(metadataUrl.replaceFirst("file://", ""));
return file.exists();
} else {
// Return true for HTTP URLs since we allow blocking until HTTP servers come up
return "http".equals(url.getProtocol());
}
} catch (Exception e) {
log.warn("Exception accessing metadata file at {}:", metadataUrl, e);
return false;
}
}
private Versioned<ClusterMetadata> blockForMetadata(String metadataUrl) {
long iterations = 0;
for (;;) {
try {
Versioned<ClusterMetadata> metadata = fetchMetadata(metadataUrl);
if (metadata != null) {
return metadata;
}
} catch (Exception e) {
log.warn("Exception attempting to access metadata file at {}: {}", metadataUrl, e);
}
try {
Thread.sleep((int) Math.pow(2, iterations < 7 ? ++iterations : iterations) * 10L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
}
private static NodeId getNodeId(NodePrototype node) {
if (node.getId() != null) {
return NodeId.nodeId(node.getId());
} else if (node.getHost() != null) {
return NodeId.nodeId(node.getHost());
} else if (node.getIp() != null) {
return NodeId.nodeId(node.getIp());
} else {
return NodeId.nodeId(UUID.randomUUID().toString());
}
}
private static String getNodeHost(NodePrototype node) {
if (node.getHost() != null) {
return node.getHost();
} else if (node.getIp() != null) {
return node.getIp();
} else {
throw new IllegalArgumentException(
"Malformed cluster configuration: No host specified for node " + node.getId());
}
}
private static int getNodePort(NodePrototype node) {
if (node.getPort() != null) {
return node.getPort();
}
return DefaultControllerNode.DEFAULT_PORT;
}
private Versioned<ClusterMetadata> fetchMetadata(String metadataUrl) {
try {
URL url = new URL(metadataUrl);
ClusterMetadataPrototype metadata = null;
long version = 0;
if ("file".equals(url.getProtocol())) {
File file = new File(metadataUrl.replaceFirst("file://", ""));
version = file.lastModified();
metadata = mapper.readValue(new FileInputStream(file), ClusterMetadataPrototype.class);
} else if ("http".equals(url.getProtocol())) {
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
log.warn("Could not reach metadata URL {}. Retrying...", url);
return null;
}
if (conn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
return null;
}
version = conn.getLastModified();
metadata = mapper.readValue(conn.getInputStream(), ClusterMetadataPrototype.class);
} catch (IOException e) {
log.warn("Could not reach metadata URL {}. Retrying...", url);
return null;
}
}
if (null == metadata) {
log.warn("Metadata is null in the function fetchMetadata");
throw new NullPointerException();
}
return new Versioned<>(new ClusterMetadata(
PROVIDER_ID,
metadata.getName(),
metadata.getNode() != null ?
new DefaultControllerNode(
getNodeId(metadata.getNode()),
getNodeHost(metadata.getNode()),
getNodePort(metadata.getNode())) : null,
metadata.getController()
.stream()
.map(node -> new DefaultControllerNode(getNodeId(node), getNodeHost(node), getNodePort(node)))
.collect(Collectors.toSet()),
metadata.getStorage()
.stream()
.map(node -> new DefaultControllerNode(getNodeId(node), getNodeHost(node), getNodePort(node)))
.collect(Collectors.toSet()),
metadata.getClusterSecret()),
version);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Monitors the metadata url for any updates and notifies providerService accordingly.
*/
private void watchUrl(String metadataUrl) {
if (!isAvailable()) {
return;
}
// TODO: We are merely polling the url.
// This can be easily addressed for files. For http urls we need to move to a push style protocol.
try {
Versioned<ClusterMetadata> latestMetadata = fetchMetadata(metadataUrl);
if (cachedMetadata.get() != null && latestMetadata != null
&& cachedMetadata.get().version() < latestMetadata.version()) {
cachedMetadata.set(latestMetadata);
providerService.clusterMetadataChanged(latestMetadata);
}
} catch (Exception e) {
log.error("Unable to parse metadata : ", e);
}
}
private static class ClusterMetadataPrototype {
private String name;
private NodePrototype node;
private Set<NodePrototype> controller = Sets.newHashSet();
private Set<NodePrototype> storage = Sets.newHashSet();
private String clusterSecret;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public NodePrototype getNode() {
return node;
}
public void setNode(NodePrototype node) {
this.node = node;
}
public Set<NodePrototype> getController() {
return controller;
}
public void setController(Set<NodePrototype> controller) {
this.controller = controller;
}
public Set<NodePrototype> getStorage() {
return storage;
}
public void setStorage(Set<NodePrototype> storage) {
this.storage = storage;
}
public void setClusterSecret(String clusterSecret) {
this.clusterSecret = clusterSecret;
}
public String getClusterSecret() {
return clusterSecret;
}
}
private static class NodePrototype {
private String id;
private String ip;
private String host;
private Integer port;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
}
}
|
elyndon/ecolect-js
|
src/language/en/number.js
|
import GraphBuilder from '../../graph/builder';
import { float, combine, negative, map } from '../numbers';
function number(o) {
return typeof o.value !== 'undefined';
}
export default function(language) {
const integer = language.integer;
return new GraphBuilder(language)
.name('number')
.add(integer, v => v[0])
.add([ GraphBuilder.result(number), integer ], v => combine(v[0], v[1]))
.add([ integer, '.', GraphBuilder.result(integer, v => ! v.suffix && ! v.suffixed) ], v => float(v[0], v[1]))
.add([ GraphBuilder.result(number), 'e', /^[0-9]$/], v => combine(v[0], {
value: Math.pow(10, parseInt(v[1])),
suffix: true
}))
.add([ GraphBuilder.result(number), 'e', '-', /^[0-9]$/], v => combine(v[0], {
value: Math.pow(10, -parseInt(v[1])),
suffix: true
}))
.add([ '-', GraphBuilder.result(number) ], v => negative(v[0]))
.add([ 'minus', GraphBuilder.result(number) ], v => negative(v[0]))
.add([ 'negative', GraphBuilder.result(number) ], v => negative(v[0]))
.mapResults(map)
.onlyBest()
.toMatcher();
}
|
itachi46/constellation
|
CoreVisualGraph/src/au/gov/asd/tac/constellation/graph/visual/drawflags/DrawFlagsIOProvider.java
|
<filename>CoreVisualGraph/src/au/gov/asd/tac/constellation/graph/visual/drawflags/DrawFlagsIOProvider.java
/*
* Copyright 2010-2019 Australian Signals Directorate
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package au.gov.asd.tac.constellation.graph.visual.drawflags;
import au.gov.asd.tac.constellation.graph.Attribute;
import au.gov.asd.tac.constellation.graph.GraphReadMethods;
import au.gov.asd.tac.constellation.graph.GraphWriteMethods;
import au.gov.asd.tac.constellation.graph.io.providers.AbstractGraphIOProvider;
import au.gov.asd.tac.constellation.graph.io.providers.GraphByteReader;
import au.gov.asd.tac.constellation.graph.io.providers.GraphByteWriter;
import au.gov.asd.tac.constellation.graph.utilities.ImmutableObjectCache;
import au.gov.asd.tac.constellation.visual.drawflags.DrawFlags;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.Map;
import org.openide.util.lookup.ServiceProvider;
/**
* IOProvider for attributes described by
* {@link au.gov.asd.tac.constellation.graph.visual.connectionmode.ConnectionModeAttributeDescription}
*
* @author twilight_sparkle
*/
@ServiceProvider(service = AbstractGraphIOProvider.class)
public class DrawFlagsIOProvider extends AbstractGraphIOProvider {
@Override
public String getName() {
return DrawFlagsAttributeDescription.ATTRIBUTE_NAME;
}
@Override
public void readObject(final int attributeId, final int elementId, final JsonNode jnode, final GraphWriteMethods graph, final Map<Integer, Integer> vertexMap, final Map<Integer, Integer> transactionMap, final GraphByteReader byteReader, ImmutableObjectCache cache) throws IOException {
final int attrVal = jnode.isNull() ? ((DrawFlags) graph.getAttributeDefaultValue(attributeId)).getFlags() : jnode.intValue();
graph.setIntValue(attributeId, elementId, attrVal);
}
@Override
public void writeObject(final Attribute attr, final int elementId, final JsonGenerator jsonGenerator, final GraphReadMethods graph, final GraphByteWriter byteWriter, final boolean verbose) throws IOException {
if (verbose || !graph.isDefaultValue(attr.getId(), elementId)) {
final int attrVal = graph.getIntValue(attr.getId(), elementId);
jsonGenerator.writeNumberField(attr.getName(), attrVal);
}
}
}
|
mpejcoch/aviso
|
aviso-server/monitoring/tests/test_aviso_rest_reporter.py
|
# (C) Copyright 1996- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
import os
from aviso_monitoring import logger
from aviso_monitoring.config import Config
from aviso_monitoring.receiver import AVISO_REST_APP_NAME, Receiver
from aviso_monitoring.reporter.aviso_rest_reporter import (
AvisoRestMetricType,
AvisoRestReporter,
)
config = {
"aviso_rest_reporter": {
"enabled": True,
"frequency": 2, # in minutes
},
# this are the setting for sending the telemetry to a monitoring server like Opsview
"monitor_servers": [
{"url": "https://monitoring-dev.ecmwf.int/rest", "username": "TBD", "password": "<PASSWORD>", "service_host": "aviso"}
],
"udp_server": {"host": "127.0.0.1", "port": 1112},
}
tlm_type = AvisoRestMetricType.rest_resp_time.name
def receiver():
tlms = [
{
"telemetry_type": tlm_type,
"component_name": "aviso-rest",
"hostname": "aviso-rest-blue-55f6dd8876-6kg5k",
"time": 1615206256.11515,
"telemetry": {tlm_type + "_counter": 2, tlm_type + "_avg": 2, tlm_type + "_max": 3, tlm_type + "_min": 1},
},
{
"telemetry_type": tlm_type,
"component_name": "aviso-rest",
"hostname": "aviso-rest-blue-55f6dd8876-6kg5k",
"time": 1615206256.889785,
"telemetry": {tlm_type + "_counter": 2, tlm_type + "_avg": 3, tlm_type + "_max": 4, tlm_type + "_min": 2},
},
]
err_rest_log = '<191>1 2021-04-12T09:19:12.252093+00:00 aviso-rest-green-9c975dc86-mvplw aviso-rest 58 -\
[origin software="aviso"] {"asctime": "2021-04-12 09:19:12,252", "hostname":\
"aviso-rest-green-9c975dc86-mvplw", "process": 58, "thread": 139943263611624, "name":\
"aviso-monitoring", "filename": "transmitter.py", "lineno": 74, "levelname":\
"ERROR", "message": "Telemetry transmitter cycle completed"}'
receiver = Receiver()
receiver._incoming_tlms[tlm_type] = tlms
receiver._incoming_errors[AVISO_REST_APP_NAME] = [err_rest_log]
return receiver
# you need to set the connection to opsview to run this test and select a tml_type associated to a passive check
def test_run_reporter():
logger.debug(os.environ.get("PYTEST_CURRENT_TEST").split(":")[-1].split(" ")[0])
reporter = AvisoRestReporter(Config(**config), receiver())
reporter.run()
def test_process_tlms():
logger.debug(os.environ.get("PYTEST_CURRENT_TEST").split(":")[-1].split(" ")[0])
reporter = AvisoRestReporter(Config(**config), receiver())
metrics = reporter.process_messages()
assert len(metrics) == 3
assert len(metrics[0].get("metrics")) == 3
assert len(list(filter(lambda m: m["m_value"] == 4, metrics[0].get("metrics")))) == 1
errors = list(filter(lambda m: m["name"] == "rest_error_log", metrics))[0]
assert errors["status"] == 2
|
orange-cloudfoundry/spring-cloud-dataflow
|
spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/config/security/package-info.java
|
/**
* Contains security related configuration classes.
*/
package org.springframework.cloud.dataflow.server.config.security;
|
antonkanin/potatoengine
|
engine/include/key_code.hpp
|
#pragma once
namespace pt
{
enum class key_code
{
unsupported = 0,
up = 1,
right = 2,
down = 3,
left = 4,
button_a = 5,
button_b = 6,
select = 7,
start = 8,
jump = 9,
crouch = 10,
mouse_left = 11,
mouse_right = 12,
F12 = 13
};
enum class key_state
{
pressed = 0,
released = 1
};
} // namespace pt
|
setvik/codsen
|
packages/object-boolean-combinations/dist/object-boolean-combinations.cjs.js
|
/**
* @name object-boolean-combinations
* @fileoverview Consumes a defaults object with booleans, generates all possible variations of it
* @version 4.0.16
* @author <NAME>, Codsen Ltd
* @license MIT
* {@link https://codsen.com/os/object-boolean-combinations/}
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var intersection = require('lodash.intersection');
var pull = require('lodash.pull');
var isObj = require('lodash.isplainobject');
var clone = require('lodash.clonedeep');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var intersection__default = /*#__PURE__*/_interopDefaultLegacy(intersection);
var pull__default = /*#__PURE__*/_interopDefaultLegacy(pull);
var isObj__default = /*#__PURE__*/_interopDefaultLegacy(isObj);
var clone__default = /*#__PURE__*/_interopDefaultLegacy(clone);
var version$1 = "4.0.16";
var version = version$1;
function combinations(originalIncomingObject) {
var originalOverrideObject = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
function combi(n) {
var r = [];
for (var i = 0; i < 1 << n; i++) {
var c = [];
for (var j = 0; j < n; j++) {
c.push(i & 1 << j ? 1 : 0);
}
r.push(c);
}
return r;
}
if (!originalIncomingObject) {
throw new Error("[THROW_ID_01] missing input object");
}
if (!isObj__default['default'](originalIncomingObject)) {
throw new Error("[THROW_ID_02] the first input object must be a true object");
}
if (originalOverrideObject && !isObj__default['default'](originalOverrideObject)) {
throw new Error("[THROW_ID_03] the second override object must be a true object");
}
var incomingObject = clone__default['default'](originalIncomingObject);
var overrideObject = clone__default['default'](originalOverrideObject);
var propertiesToMix = Object.keys(incomingObject);
var outcomingObjectsArray = [];
var propertiesToBeOverridden = [];
if (isObj__default['default'](overrideObject) && Object.keys(overrideObject).length) {
propertiesToBeOverridden = intersection__default['default'](Object.keys(overrideObject), Object.keys(incomingObject));
propertiesToBeOverridden.forEach(function (elem) {
return pull__default['default'](propertiesToMix, elem);
});
}
var boolCombinations = combi(Object.keys(propertiesToMix).length);
var tempObject;
boolCombinations.forEach(function (_elem1, index1) {
tempObject = {};
propertiesToMix.forEach(function (elem2, index2) {
tempObject[elem2] = boolCombinations[index1][index2] === 1;
});
outcomingObjectsArray.push(tempObject);
});
if (isObj__default['default'](overrideObject) && Object.keys(overrideObject).length) {
outcomingObjectsArray.forEach(function (elem3) {
return propertiesToBeOverridden.forEach(function (elem4) {
elem3[elem4] = overrideObject[elem4];
});
});
}
return outcomingObjectsArray;
}
exports.combinations = combinations;
exports.version = version;
|
CabezasGonzalezJavier/Unit-Converter-Pro-Evolution
|
app/src/main/java/com/thedeveloperworldisyours/unitconverterpro/area/AreaPresenterImpl.java
|
package com.thedeveloperworldisyours.unitconverterpro.area;
import android.content.Context;
import com.thedeveloperworldisyours.unitconverterpro.sqlite.area.Area;
import com.thedeveloperworldisyours.unitconverterpro.sqlite.area.AreaDataSource;
import java.util.ArrayList;
import java.util.List;
/**
* Created by javierg on 17/10/2016.
*/
public class AreaPresenterImpl implements AreaPresenter {
AreaDataSource mAreaDataSource;
AreaView mAreaView;
int mTotal;
@Override
public void refresh(Context context, AreaView areaView) {
mAreaDataSource = new AreaDataSource(context);
mAreaView = areaView;
create();
mAreaView.showInfo(sortList());
mAreaDataSource.close();
}
public void create() {
mAreaDataSource.open();
mTotal = mAreaDataSource.getAllAreas().size();
if (mTotal <= 0) {
mAreaDataSource.createArea("kilometre", 1L, 6);
mAreaDataSource.createArea("hectare", 100L, 1);
mAreaDataSource.createArea("metre", 1000000L, 2);
mAreaDataSource.createArea("centimetre", 10000000000L, 3);
mAreaDataSource.createArea("millimetre", 1000000000000L, 4);
mAreaDataSource.createArea("mile", (long) Double.parseDouble("0.3861022"), 5);
mAreaDataSource.createArea("acre", (long) Double.parseDouble("247.1054"), 0);
}
}
public List<Area> sortList() {
List<Area> areasDelete = mAreaDataSource.getAllAreas();
mTotal = mAreaDataSource.getAllAreas().size();
List<Area> areas = new ArrayList<>();
for (int i=0; i<mTotal; i++){
areas.add(i, mAreaDataSource.getAreaWhenPosition(i));
}
return areas;
}
}
|
ChenMJ068/fund
|
fund-service/fund-service-account/src/main/java/com/fund/account/service/impl/FundAccountTransactionServiceImpl.java
|
<filename>fund-service/fund-service-account/src/main/java/com/fund/account/service/impl/FundAccountTransactionServiceImpl.java<gh_stars>0
package com.fund.account.service.impl;
import java.util.List;
import com.fund.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fund.account.mapper.FundAccountTransactionMapper;
import com.fund.account.domain.FundAccountTransaction;
import com.fund.account.service.IFundAccountTransactionService;
/**
* 【请填写功能名称】Service业务层处理
*
* @author ChenMJ
* @date 2021-11-30
*/
@Service
public class FundAccountTransactionServiceImpl implements IFundAccountTransactionService
{
@Autowired
private FundAccountTransactionMapper fundAccountTransactionMapper;
/**
* 查询【请填写功能名称】
*
* @param id 【请填写功能名称】主键
* @return 【请填写功能名称】
*/
@Override
public FundAccountTransaction selectFundAccountTransactionById(Integer id)
{
return fundAccountTransactionMapper.selectFundAccountTransactionById(id);
}
/**
* 查询【请填写功能名称】列表
*
* @param fundAccountTransaction 【请填写功能名称】
* @return 【请填写功能名称】
*/
@Override
public List<FundAccountTransaction> selectFundAccountTransactionList(FundAccountTransaction fundAccountTransaction)
{
return fundAccountTransactionMapper.selectFundAccountTransactionList(fundAccountTransaction);
}
/**
* 新增【请填写功能名称】
*
* @param fundAccountTransaction 【请填写功能名称】
* @return 结果
*/
@Override
public int insertFundAccountTransaction(FundAccountTransaction fundAccountTransaction)
{
fundAccountTransaction.setCreateTime(DateUtils.getNowDate());
return fundAccountTransactionMapper.insertFundAccountTransaction(fundAccountTransaction);
}
/**
* 修改【请填写功能名称】
*
* @param fundAccountTransaction 【请填写功能名称】
* @return 结果
*/
@Override
public int updateFundAccountTransaction(FundAccountTransaction fundAccountTransaction)
{
fundAccountTransaction.setUpdateTime(DateUtils.getNowDate());
return fundAccountTransactionMapper.updateFundAccountTransaction(fundAccountTransaction);
}
/**
* 批量删除【请填写功能名称】
*
* @param ids 需要删除的【请填写功能名称】主键
* @return 结果
*/
@Override
public int deleteFundAccountTransactionByIds(Integer[] ids)
{
return fundAccountTransactionMapper.deleteFundAccountTransactionByIds(ids);
}
/**
* 删除【请填写功能名称】信息
*
* @param id 【请填写功能名称】主键
* @return 结果
*/
@Override
public int deleteFundAccountTransactionById(Integer id)
{
return fundAccountTransactionMapper.deleteFundAccountTransactionById(id);
}
}
|
shuangwei-Ye/WeChat_tweak
|
Resources/WC_7_0_5_Headers/APCheckConfig.h
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "MMObject.h"
#import "WCTTableCoding.h"
@class NSString;
@interface APCheckConfig : MMObject <WCTTableCoding>
{
int _configVersion;
unsigned int _httpConnectTimeoutMillis;
unsigned int _httpReadTimeoutMillis;
NSString *_pingUrl;
NSString *_threeTwoBlackUrl;
NSString *_pingEnabled;
NSString *_echoStr;
}
+ (void)__wcdb_column_constraint_7:(struct WCTBinding *)arg1;
+ (const struct WCTProperty *)__wcdb_synthesize_0:(struct WCTBinding *)arg1;
+ (const struct WCTProperty *)__wcdb_synthesize_1:(struct WCTBinding *)arg1;
+ (const struct WCTProperty *)__wcdb_synthesize_2:(struct WCTBinding *)arg1;
+ (const struct WCTProperty *)__wcdb_synthesize_3:(struct WCTBinding *)arg1;
+ (const struct WCTProperty *)__wcdb_synthesize_4:(struct WCTBinding *)arg1;
+ (const struct WCTProperty *)__wcdb_synthesize_5:(struct WCTBinding *)arg1;
+ (const struct WCTProperty *)__wcdb_synthesize_6:(struct WCTBinding *)arg1;
+ (id)__wcdbtyper;
+ (const SyntaxList_7f15fe8c *)allProperties;
+ (const struct WCTProperty *)configVersion;
+ (const struct WCTProperty *)echoStr;
+ (const struct WCTProperty *)httpConnectTimeoutMillis;
+ (const struct WCTProperty *)httpReadTimeoutMillis;
+ (const struct WCTBinding *)objectRelationalMapping;
+ (const struct WCTProperty *)pingEnabled;
+ (const struct WCTProperty *)pingUrl;
+ (const struct WCTProperty *)threeTwoBlackUrl;
- (void).cxx_destruct;
@property(nonatomic) int configVersion; // @synthesize configVersion=_configVersion;
@property(retain, nonatomic) NSString *echoStr; // @synthesize echoStr=_echoStr;
@property(nonatomic) unsigned int httpConnectTimeoutMillis; // @synthesize httpConnectTimeoutMillis=_httpConnectTimeoutMillis;
@property(nonatomic) unsigned int httpReadTimeoutMillis; // @synthesize httpReadTimeoutMillis=_httpReadTimeoutMillis;
@property(retain, nonatomic) NSString *pingEnabled; // @synthesize pingEnabled=_pingEnabled;
@property(retain, nonatomic) NSString *pingUrl; // @synthesize pingUrl=_pingUrl;
@property(retain, nonatomic) NSString *threeTwoBlackUrl; // @synthesize threeTwoBlackUrl=_threeTwoBlackUrl;
// Remaining properties
@property(nonatomic) _Bool isAutoIncrement;
@property(nonatomic) long long lastInsertedRowID;
@end
|
Ranmal-Dewage/Prasara-Washing-Plant-Project
|
src/production/process.java
|
<reponame>Ranmal-Dewage/Prasara-Washing-Plant-Project
/*
* 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.
*/
package production;
import java.awt.Color;
import ITP.Home;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import static production.dbCon.con;
/**
*
* @author Axio
*/
public class process extends javax.swing.JPanel {
int tot;
int maxPages;
int pg = 1;
int lim = 15;
int offset = 0;
production pro = new production();
/**
* Creates new form process
*
* @throws java.sql.SQLException
*/
public process() throws SQLException {
initComponents();
jButton1.setVisible(false);
Production.setBackground(new Color(0, 0, 0, 0));
Production.setVisible(false);
BWQC.setVisible(false);
Chem.setVisible(false);
Wash.setVisible(false);
Hyd.setVisible(false);
WetQC.setVisible(false);
Dry.setVisible(false);
AWQC.setVisible(false);
Finish.setVisible(false);
BWQC1.setVisible(false);
Chem1.setVisible(false);
Wash1.setVisible(false);
Hyd1.setVisible(false);
WetQC1.setVisible(false);
Dry1.setVisible(false);
AWQC1.setVisible(false);
Finish1.setVisible(false);
dbCon d = new dbCon();
d.connect();
// when initizalised valus add the table when system is start
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addDryProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
}
// making format to selected format
void updateMax(String q, javax.swing.JLabel tox, javax.swing.JTextField pad) throws SQLException {
ResultSet rs = con.createStatement().executeQuery(q);
rs.next();
tot = rs.getInt("count");
int i = tot % lim;
if (i > 0) {
maxPages = tot / lim + 1;
} else {
maxPages = tot / lim;
}
tox.setText(Integer.toString(maxPages));
if (pg > maxPages) {
pg = maxPages;
pad.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
}
if (maxPages == 1) {
pg = 1;
pad.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
}
}
void addProcessTable(String q, javax.swing.JTable jb) throws SQLException {
try {
ResultSet rs1 = con.createStatement().executeQuery(q);
DefaultTableModel model = new DefaultTableModel(new Object[]{"Tag Number", "Date", "Time", "Employee"}, 0);
while (rs1.next()) {
String tag = rs1.getString("Tag_No");
String date = rs1.getString("Date");
String time = rs1.getString("Time");
String emp = rs1.getString("Emp_No");
Object[] row = {tag, date, time, emp};
model.addRow(row);
}
jb.setModel(model);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
void addDryProcessTable(String q, javax.swing.JTable jb) throws SQLException {
try {
ResultSet rs1 = con.createStatement().executeQuery(q);
DefaultTableModel model = new DefaultTableModel(new Object[]{"Tag Number", "Machine Number", "Date", "Time", "Employee"}, 0);
while (rs1.next()) {
String tag = rs1.getString("Tag_No");
String mah = rs1.getString("Machine_No");
String date = rs1.getString("Date");
String time = rs1.getString("Time");
String emp = rs1.getString("Emp_No");
Object[] row = {tag, mah, date, time, emp};
model.addRow(row);
}
jb.setModel(model);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
boolean DryValidate() throws SQLException {
if ((Dry_tag.getSelectedIndex()) != -1) {
if ((Dry_mah.getSelectedIndex()) != -1) {
if ((Dry_emp.getSelectedIndex()) == -1) {
//JOptionPane.showMessageDialog(null, "Employee not Selected", "Error", JOptionPane.ERROR_MESSAGE);
Dry_emp.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
Dry_err.setText("Employee not Selected");
return false;
}
} else {
// JOptionPane.showMessageDialog(null, "Machine Number not Selected", "Error", JOptionPane.ERROR_MESSAGE);
Dry_mah.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
Dry_err.setText("Machine Number not Selected");
return false;
}
} else {
// JOptionPane.showMessageDialog(null, "Tag Not Selected", "Error", JOptionPane.ERROR_MESSAGE);
Dry_tag.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
Dry_err.setText("Tag Not Selected");
return false;
}
return true;
}
// null validate
boolean TableValidate(javax.swing.JComboBox tb, javax.swing.JComboBox tb1, javax.swing.JLabel lb) throws SQLException {
if ((tb.getSelectedIndex()) != -1) {
if ((tb1.getSelectedIndex()) != -1) {
} else {
//JOptionPane.showMessageDialog(null, "Employee not Selected", "Error", JOptionPane.ERROR_MESSAGE);
tb1.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
lb.setText("Employee not Selected");
return false;
}
} else {
//JOptionPane.showMessageDialog(null, "Tag Not Selected", "Error", JOptionPane.ERROR_MESSAGE);
tb.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
lb.setText("Tag Not Selected");
return false;
}
return true;
}
// scaning part null validate
boolean AutoValidate(javax.swing.JTextField tx, javax.swing.JTextField tx1, javax.swing.JLabel lb) throws SQLException {
String rh = tx.getText();
String rh1 = tx1.getText();
if (rh.equals("")) {
//JOptionPane.showMessageDialog(null, "Tag Not Scaned", "Error", JOptionPane.ERROR_MESSAGE);
tx.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
lb.setText("Tag Not Scaned");
return false;
} else {
if ((rh1.equals(""))) {
//JOptionPane.showMessageDialog(null, "Employee not Scaned", "Error", JOptionPane.ERROR_MESSAGE);
tx1.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
lb.setText("Employee not Scaned");
return false;
}
}
return true;
}
boolean AutoDryValidate(javax.swing.JTextField tx, javax.swing.JTextField tx1, javax.swing.JComboBox tc) throws SQLException {
String rh = tx.getText();
String rh1 = tx1.getText();
if (rh.equals("")) {
//JOptionPane.showMessageDialog(null, "Tag Not Scaned", "Error", JOptionPane.ERROR_MESSAGE);
tx.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
Dry_err.setText("Tag Not Scaned ");
return false;
} else {
if ((rh1.equals(""))) {
//JOptionPane.showMessageDialog(null, "Employee not Scaned", "Error", JOptionPane.ERROR_MESSAGE);
tx1.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
Dry_err.setText("Employee not Scaned ");
return false;
} else {
if ((tc.getSelectedIndex()) == -1) {
//JOptionPane.showMessageDialog(null, "Machine Number not Selected", "Error", JOptionPane.ERROR_MESSAGE);
tc.setBorder(BorderFactory.createLineBorder(Color.decode("#ff0000")));
Dry_err.setText("Machine Number not Selected");
return false;
}
}
}
return true;
}
//compare rows of tag and proccess chek table and add rows witch are not in proccess chk table from tag table
void addtoProcesschkTable() throws SQLException {
String bat;
String cus;
String col;
String style;
int tag;
/*int bwqc;
int chem;
int wash;
int hydro;
int wetqc;
int dry;
int awqc;*/
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No, t.BLP_No, t.Customer, t.Color, t.Style_No FROM tag t LEFT JOIN processchk p ON t.BLP_No = p.BLP_No WHERE t.Tag_Status = 'Printed' AND p.Tag_No IS NULL");
while (rs.next()) {
tag = rs.getInt("Tag_No");
bat = rs.getString("BLP_No");
cus = rs.getString("Customer");
style = rs.getString("Style_No");
col = rs.getString("Color");
con.prepareStatement("INSERT INTO processchk (Tag_No,BLP_No,Customer,Style_No,Color) VALUES('" + tag + "','" + bat + "','" + cus + "','" + style + "','" + col + "')").execute();
/*ResultSet rs1 = con.createStatement().executeQuery("SELECT bwqc,chemicals,wash,hydro,wetqc,dry,awqc FROM recipe WHERE customer = '"+cus+" AND styleNo = '"+style+"' AND color = '"+col+"' ");
rs1.next();
bwqc = rs.getInt("bwqc");
chem = rs.getInt("chemicals");
wash = rs.getInt("wash");
hydro = rs.getInt("hydro");
wetqc = rs.getInt("wetqc");
dry = rs.getInt("dry");
awqc = rs.getInt("awqc");
con.prepareStatement("INSERT INTO processchk (Tag_No,BLP_No,Customer,Style_No,Color,bwqc,chemicals,wash,hydro,wetqc,dry,awqc) VALUES('"+tag+"','"+bat+"','"+cus+"','"+style+"','"+col+"',"+bwqc+","+chem+","+wash+","+hydro+","+wetqc+","+dry+","+awqc+")").execute();*/
}
}
// this methode chek whether the a packing list follows tha recipy given
boolean processchk(int tg, String colname, String Deptname) throws SQLException {
int tag = tg; //get parameters and asign to the variable
String cus;
String style;
int count;
int bwqc, chem, wash, hydro, wetqc, dry, awqc;
int bwqcck, chemck, washck, hydrock, wetqcck, dryck, awqcck;
//get customer and style and asign to the two variable
ResultSet rs = con.createStatement().executeQuery("SELECT Customer, Style_No FROM tag WHERE Tag_No = " + tag + "");
rs.next();
cus = rs.getString("Customer");
style = rs.getString("Style_No");
//get recipy from the recipy table using CUSTOMER AND STYLE a
try {
ResultSet rs1 = con.createStatement().executeQuery("SELECT bwqc,chemicals,w1,h1,wetqc,d1,awqc FROM recipe WHERE customer = '" + cus + "' AND styleNo = '" + style + "'");
rs1.next();
bwqc = rs1.getInt("bwqc");
chem = rs1.getInt("chemicals");
wash = rs1.getInt("w1");
hydro = rs1.getInt("h1");
wetqc = rs1.getInt("wetqc");
dry = rs1.getInt("d1");
awqc = rs1.getInt("awqc");
ResultSet rs2 = con.createStatement().executeQuery("SELECT COUNT(*) AS 'count' FROM " + Deptname + " WHERE Tag_No = " + tag + "");
rs2.next();
count = rs2.getInt("count");//check the tag is printed befor and get raw count
if (count == 0) {
con.prepareStatement("UPDATE processchk set " + colname + " = 1 WHERE Tag_No = " + tag + "").execute();//using that tag number and col name is going to 1
ResultSet rs3 = con.createStatement().executeQuery("SELECT bwqc, chemicals, wash, hydro, wetqc, dry, awqc FROM processchk WHERE Tag_No = " + tag + "");//get all values from da procces table
rs3.next();
bwqcck = rs3.getInt("bwqc");
chemck = rs3.getInt("chemicals");
washck = rs3.getInt("wash");
hydrock = rs3.getInt("hydro");
wetqcck = rs3.getInt("wetqc");
dryck = rs3.getInt("dry");
awqcck = rs3.getInt("awqc");
if (bwqcck == bwqc) {
if (chemck == chem && !Deptname.equals("bwqc")) {
if (washck == wash && !Deptname.equals("chemicals")) {
if (hydrock == hydro && !Deptname.equals("wash")) {
if (wetqcck == wetqc && !Deptname.equals("hydro")) {
if (dryck == dry && !Deptname.equals("wetqc")) {
if (awqcck == awqc && !Deptname.equals("dry")) {
if (colname.equals("finish")) {
return true;
}
} else if (awqcck < awqc && !Deptname.equals("dry")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Tag was NOT SCANNED in after wash quality check department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
} else if (awqcck > awqc && !Deptname.equals("dry")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Item is NOT SUPPOSE to go into after wash quality check department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
} else if (dryck < dry && !Deptname.equals("wetqc")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Tag was NOT SCANNED in dry department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
} else if (dryck > dry && !Deptname.equals("wetqc")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Item is NOT SUPPOSE to go into dry department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
} else if (wetqcck < wetqc && !Deptname.equals("hydro")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Tag was NOT SCANNED in wet quality check department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
} else if (wetqcck > wetqc && !Deptname.equals("hydro")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Item is NOT SUPPOSE to go into wet quality check department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
} else if (hydrock < hydro && !Deptname.equals("wash")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Tag was NOT SCANNED in hydro department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
} else if (hydrock > hydro && !Deptname.equals("wash")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Item is NOT SUPPOSE to go into hydro department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
} else if (washck < wash && !Deptname.equals("chemicals")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Tag was NOT SCANNED in washing department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
} else if (washck > wash && !Deptname.equals("chemicals")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Item is NOT SUPPOSE to go into washing department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
} else if (chemck < chem && !Deptname.equals("bwqc")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Tag was NOT SCANNED in chemicals department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
} else if (chemck > chem && !Deptname.equals("bwqc")) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Item is NOT SUPPOSE to go into chemicals department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
} else if (bwqcck < bwqc) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Tag was NOT SCANNED in bwqc department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
} else if (bwqcck > bwqc) {
con.prepareStatement("UPDATE processchk set " + colname + " = 0 WHERE Tag_No = " + tag + "").execute();
JOptionPane.showMessageDialog(null, "Item is NOT SUPPOSE to go into bwqc department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
} else {
JOptionPane.showMessageDialog(null, "Tag was ALREADY SCANNED in this department", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "please add a recipe", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLayeredPane1 = new javax.swing.JLayeredPane();
Production = new javax.swing.JPanel();
BWQCButton = new javax.swing.JButton();
ChemicalsButton = new javax.swing.JButton();
WashingButton = new javax.swing.JButton();
HydroButton = new javax.swing.JButton();
WetQCButton = new javax.swing.JButton();
DryingButton = new javax.swing.JButton();
AWQCButton = new javax.swing.JButton();
FinishingButton = new javax.swing.JButton();
BWQC = new javax.swing.JPanel();
jLabel94 = new javax.swing.JLabel();
jSeparator13 = new javax.swing.JSeparator();
jScrollPane5 = new javax.swing.JScrollPane();
jTable5 = new javax.swing.JTable();
jLabel96 = new javax.swing.JLabel();
jComboBox25 = new javax.swing.JComboBox<>();
jLabel97 = new javax.swing.JLabel();
search2 = new javax.swing.JTextField();
BWQCBack = new javax.swing.JButton();
BWQCchk = new javax.swing.JButton();
jButton23 = new javax.swing.JButton();
jButton24 = new javax.swing.JButton();
total4 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
page4 = new javax.swing.JTextField();
jButton29 = new javax.swing.JButton();
jButton30 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jLabel9 = new javax.swing.JLabel();
Chem = new javax.swing.JPanel();
jLabel99 = new javax.swing.JLabel();
jSeparator14 = new javax.swing.JSeparator();
jScrollPane6 = new javax.swing.JScrollPane();
jTable6 = new javax.swing.JTable();
jLabel101 = new javax.swing.JLabel();
jComboBox26 = new javax.swing.JComboBox<>();
jLabel102 = new javax.swing.JLabel();
search3 = new javax.swing.JTextField();
ChemBack = new javax.swing.JButton();
chem_check = new javax.swing.JButton();
jButton31 = new javax.swing.JButton();
jButton33 = new javax.swing.JButton();
page5 = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
total5 = new javax.swing.JLabel();
jButton34 = new javax.swing.JButton();
jButton35 = new javax.swing.JButton();
search4 = new javax.swing.JTextField();
jButton13 = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
Wash = new javax.swing.JPanel();
jLabel104 = new javax.swing.JLabel();
jSeparator15 = new javax.swing.JSeparator();
jScrollPane7 = new javax.swing.JScrollPane();
jTable13 = new javax.swing.JTable();
jLabel106 = new javax.swing.JLabel();
jComboBox27 = new javax.swing.JComboBox<>();
jLabel107 = new javax.swing.JLabel();
WashBack = new javax.swing.JButton();
Washchk = new javax.swing.JButton();
jButton36 = new javax.swing.JButton();
jButton37 = new javax.swing.JButton();
page6 = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
total6 = new javax.swing.JLabel();
jButton38 = new javax.swing.JButton();
jButton39 = new javax.swing.JButton();
search5 = new javax.swing.JTextField();
jButton14 = new javax.swing.JButton();
jLabel11 = new javax.swing.JLabel();
Hyd = new javax.swing.JPanel();
jLabel109 = new javax.swing.JLabel();
jSeparator16 = new javax.swing.JSeparator();
jScrollPane8 = new javax.swing.JScrollPane();
jTable14 = new javax.swing.JTable();
jLabel111 = new javax.swing.JLabel();
jComboBox28 = new javax.swing.JComboBox<>();
jLabel112 = new javax.swing.JLabel();
HydBack = new javax.swing.JButton();
Hydrochk = new javax.swing.JButton();
jButton40 = new javax.swing.JButton();
jButton41 = new javax.swing.JButton();
page7 = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
total7 = new javax.swing.JLabel();
jButton42 = new javax.swing.JButton();
jButton43 = new javax.swing.JButton();
search6 = new javax.swing.JTextField();
jButton15 = new javax.swing.JButton();
jLabel12 = new javax.swing.JLabel();
WetQC = new javax.swing.JPanel();
jLabel114 = new javax.swing.JLabel();
jSeparator17 = new javax.swing.JSeparator();
jScrollPane9 = new javax.swing.JScrollPane();
jTable15 = new javax.swing.JTable();
jLabel116 = new javax.swing.JLabel();
jComboBox29 = new javax.swing.JComboBox<>();
jLabel117 = new javax.swing.JLabel();
WetQCBack = new javax.swing.JButton();
WetQCchk = new javax.swing.JButton();
jButton44 = new javax.swing.JButton();
jButton45 = new javax.swing.JButton();
page8 = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
total8 = new javax.swing.JLabel();
jButton46 = new javax.swing.JButton();
jButton47 = new javax.swing.JButton();
search10 = new javax.swing.JTextField();
jButton16 = new javax.swing.JButton();
jLabel31 = new javax.swing.JLabel();
Dry = new javax.swing.JPanel();
jLabel119 = new javax.swing.JLabel();
jSeparator18 = new javax.swing.JSeparator();
jScrollPane10 = new javax.swing.JScrollPane();
jTable16 = new javax.swing.JTable();
jLabel121 = new javax.swing.JLabel();
jComboBox30 = new javax.swing.JComboBox<>();
jLabel122 = new javax.swing.JLabel();
search7 = new javax.swing.JTextField();
DryBack = new javax.swing.JButton();
Drychk = new javax.swing.JButton();
jButton48 = new javax.swing.JButton();
jButton49 = new javax.swing.JButton();
page9 = new javax.swing.JTextField();
jLabel18 = new javax.swing.JLabel();
total9 = new javax.swing.JLabel();
jButton50 = new javax.swing.JButton();
jButton51 = new javax.swing.JButton();
search11 = new javax.swing.JTextField();
jButton17 = new javax.swing.JButton();
jLabel32 = new javax.swing.JLabel();
AWQC = new javax.swing.JPanel();
jLabel124 = new javax.swing.JLabel();
jSeparator19 = new javax.swing.JSeparator();
jScrollPane11 = new javax.swing.JScrollPane();
jTable17 = new javax.swing.JTable();
jLabel126 = new javax.swing.JLabel();
jComboBox31 = new javax.swing.JComboBox<>();
jLabel127 = new javax.swing.JLabel();
search8 = new javax.swing.JTextField();
AWQCBack = new javax.swing.JButton();
AWQCchk = new javax.swing.JButton();
jButton52 = new javax.swing.JButton();
jButton53 = new javax.swing.JButton();
page10 = new javax.swing.JTextField();
jLabel19 = new javax.swing.JLabel();
total10 = new javax.swing.JLabel();
jButton54 = new javax.swing.JButton();
jButton55 = new javax.swing.JButton();
search12 = new javax.swing.JTextField();
jButton18 = new javax.swing.JButton();
jLabel33 = new javax.swing.JLabel();
Finish = new javax.swing.JPanel();
jLabel130 = new javax.swing.JLabel();
jSeparator20 = new javax.swing.JSeparator();
jScrollPane12 = new javax.swing.JScrollPane();
jTable18 = new javax.swing.JTable();
jLabel140 = new javax.swing.JLabel();
jComboBox32 = new javax.swing.JComboBox<>();
jLabel153 = new javax.swing.JLabel();
search9 = new javax.swing.JTextField();
FinBack = new javax.swing.JButton();
Finchk = new javax.swing.JButton();
jButton56 = new javax.swing.JButton();
jButton57 = new javax.swing.JButton();
page11 = new javax.swing.JTextField();
jLabel30 = new javax.swing.JLabel();
total11 = new javax.swing.JLabel();
jButton58 = new javax.swing.JButton();
jButton59 = new javax.swing.JButton();
search13 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton19 = new javax.swing.JButton();
jLabel34 = new javax.swing.JLabel();
BWQC1 = new javax.swing.JPanel();
BWQCBack1 = new javax.swing.JButton();
jSeparator21 = new javax.swing.JSeparator();
jLabel103 = new javax.swing.JLabel();
BWQCchk3add = new javax.swing.JButton();
jSeparator23 = new javax.swing.JSeparator();
BWQCchk4addmanually = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
BW_ctag = new javax.swing.JTextField();
BW_cemp = new javax.swing.JTextField();
BW_time = new javax.swing.JTextField();
BW_tag = new javax.swing.JComboBox<>();
BW_emp = new javax.swing.JComboBox<>();
BW_err = new javax.swing.JLabel();
BW_date = new javax.swing.JTextField();
Chem1 = new javax.swing.JPanel();
addchemback = new javax.swing.JButton();
jSeparator25 = new javax.swing.JSeparator();
add_chem_man_add = new javax.swing.JButton();
add_che_add = new javax.swing.JButton();
jLabel24 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
jLabel27 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
jLabel29 = new javax.swing.JLabel();
jLabel37 = new javax.swing.JLabel();
Chem_ctag = new javax.swing.JTextField();
Chem_cemp = new javax.swing.JTextField();
Chem_time = new javax.swing.JTextField();
jLabel105 = new javax.swing.JLabel();
Chem_emp = new javax.swing.JComboBox<>();
Chem_tag = new javax.swing.JComboBox<>();
Chem_err = new javax.swing.JLabel();
Chem_date = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
Wash1 = new javax.swing.JPanel();
add_wash_back = new javax.swing.JButton();
jSeparator29 = new javax.swing.JSeparator();
Add_wash_manu_add = new javax.swing.JButton();
add_wash_add = new javax.swing.JButton();
jLabel20 = new javax.swing.JLabel();
jLabel39 = new javax.swing.JLabel();
jLabel43 = new javax.swing.JLabel();
jLabel45 = new javax.swing.JLabel();
jLabel46 = new javax.swing.JLabel();
jLabel48 = new javax.swing.JLabel();
jLabel49 = new javax.swing.JLabel();
jLabel52 = new javax.swing.JLabel();
Wash_ctag = new javax.swing.JTextField();
Wash_cemp = new javax.swing.JTextField();
Wash_time = new javax.swing.JTextField();
jLabel98 = new javax.swing.JLabel();
Wash_emp = new javax.swing.JComboBox<>();
Wash_tag = new javax.swing.JComboBox<>();
Wash_err = new javax.swing.JLabel();
Wash_date = new javax.swing.JTextField();
Hyd1 = new javax.swing.JPanel();
add_hydro_back = new javax.swing.JButton();
jSeparator33 = new javax.swing.JSeparator();
jLabel100 = new javax.swing.JLabel();
Hydro_time = new javax.swing.JTextField();
Hydro_cemp = new javax.swing.JTextField();
Hydro_ctag = new javax.swing.JTextField();
jLabel76 = new javax.swing.JLabel();
jLabel75 = new javax.swing.JLabel();
jLabel74 = new javax.swing.JLabel();
jLabel73 = new javax.swing.JLabel();
jLabel72 = new javax.swing.JLabel();
jLabel71 = new javax.swing.JLabel();
jLabel68 = new javax.swing.JLabel();
jLabel56 = new javax.swing.JLabel();
add_hydro_add = new javax.swing.JButton();
add_hydro_manu_add = new javax.swing.JButton();
Hydro_emp = new javax.swing.JComboBox<>();
Hydro_tag = new javax.swing.JComboBox<>();
Hydro_err = new javax.swing.JLabel();
Hydro_date = new javax.swing.JTextField();
WetQC1 = new javax.swing.JPanel();
cheak_wet_qc_back = new javax.swing.JButton();
jSeparator37 = new javax.swing.JSeparator();
Wet_addMan = new javax.swing.JButton();
Wet_cAdd = new javax.swing.JButton();
jLabel77 = new javax.swing.JLabel();
jLabel87 = new javax.swing.JLabel();
jLabel88 = new javax.swing.JLabel();
jLabel93 = new javax.swing.JLabel();
jLabel120 = new javax.swing.JLabel();
jLabel123 = new javax.swing.JLabel();
jLabel125 = new javax.swing.JLabel();
jLabel128 = new javax.swing.JLabel();
Wet_ctag = new javax.swing.JTextField();
Wet_cemp = new javax.swing.JTextField();
Wet_time = new javax.swing.JTextField();
jLabel115 = new javax.swing.JLabel();
Wet_emp = new javax.swing.JComboBox<>();
Wet_tag = new javax.swing.JComboBox<>();
Wet_err = new javax.swing.JLabel();
Wet_date = new javax.swing.JTextField();
Dry1 = new javax.swing.JPanel();
add_dry_back = new javax.swing.JButton();
jSeparator41 = new javax.swing.JSeparator();
add_dry_manu_add = new javax.swing.JButton();
add_dry_add = new javax.swing.JButton();
jLabel132 = new javax.swing.JLabel();
jLabel134 = new javax.swing.JLabel();
jLabel135 = new javax.swing.JLabel();
jLabel136 = new javax.swing.JLabel();
jLabel137 = new javax.swing.JLabel();
jLabel138 = new javax.swing.JLabel();
jLabel129 = new javax.swing.JLabel();
jLabel149 = new javax.swing.JLabel();
jLabel150 = new javax.swing.JLabel();
Dry_time = new javax.swing.JTextField();
Dry_ctag = new javax.swing.JTextField();
Dry_cemp = new javax.swing.JTextField();
jLabel151 = new javax.swing.JLabel();
jLabel152 = new javax.swing.JLabel();
Dry_mah = new javax.swing.JComboBox<>();
Dry_tag = new javax.swing.JComboBox<>();
Dry_emp = new javax.swing.JComboBox<>();
Dry_err = new javax.swing.JLabel();
Dry_date = new javax.swing.JTextField();
Dry_cmah = new javax.swing.JComboBox<>();
AWQC1 = new javax.swing.JPanel();
jLabel139 = new javax.swing.JLabel();
AWQC1Back = new javax.swing.JButton();
jSeparator45 = new javax.swing.JSeparator();
AWQC1chk = new javax.swing.JButton();
jSeparator47 = new javax.swing.JSeparator();
AWQCchk15 = new javax.swing.JButton();
jLabel154 = new javax.swing.JLabel();
jLabel155 = new javax.swing.JLabel();
AW_ctag = new javax.swing.JTextField();
jLabel156 = new javax.swing.JLabel();
AW_cemp = new javax.swing.JTextField();
jLabel157 = new javax.swing.JLabel();
jLabel158 = new javax.swing.JLabel();
jLabel159 = new javax.swing.JLabel();
jLabel160 = new javax.swing.JLabel();
jLabel161 = new javax.swing.JLabel();
AW_time = new javax.swing.JTextField();
AW_emp = new javax.swing.JComboBox<>();
AW_tag = new javax.swing.JComboBox<>();
AW_err = new javax.swing.JLabel();
AW_date = new javax.swing.JTextField();
Finish1 = new javax.swing.JPanel();
Finish1back = new javax.swing.JButton();
jSeparator38 = new javax.swing.JSeparator();
Finish1add = new javax.swing.JButton();
Finish1add1 = new javax.swing.JButton();
jLabel95 = new javax.swing.JLabel();
jLabel108 = new javax.swing.JLabel();
jLabel110 = new javax.swing.JLabel();
jLabel113 = new javax.swing.JLabel();
jLabel167 = new javax.swing.JLabel();
jLabel168 = new javax.swing.JLabel();
jLabel169 = new javax.swing.JLabel();
jLabel170 = new javax.swing.JLabel();
Fin_ctag = new javax.swing.JTextField();
Fin_cemp = new javax.swing.JTextField();
Fin_time = new javax.swing.JTextField();
jLabel118 = new javax.swing.JLabel();
Fin_emp = new javax.swing.JComboBox<>();
Fin_tag = new javax.swing.JComboBox<>();
Fin_err = new javax.swing.JLabel();
Fin_date = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel141 = new javax.swing.JLabel();
jSeparator3 = new javax.swing.JSeparator();
jLabel142 = new javax.swing.JLabel();
Background = new javax.swing.JLabel();
setMaximumSize(new java.awt.Dimension(940, 480));
setMinimumSize(new java.awt.Dimension(940, 480));
setPreferredSize(new java.awt.Dimension(940, 480));
jPanel1.setMinimumSize(new java.awt.Dimension(940, 480));
jPanel1.setPreferredSize(new java.awt.Dimension(940, 480));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLayeredPane1.setLayout(new java.awt.CardLayout());
Production.setMinimumSize(new java.awt.Dimension(940, 480));
Production.setPreferredSize(new java.awt.Dimension(940, 480));
Production.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
BWQCButton.setBackground(new java.awt.Color(48, 48, 240));
BWQCButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
BWQCButton.setForeground(new java.awt.Color(255, 255, 255));
BWQCButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-services-48.png"))); // NOI18N
BWQCButton.setText("B/W QC");
BWQCButton.setToolTipText("");
BWQCButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
BWQCButton.setMaximumSize(new java.awt.Dimension(120, 120));
BWQCButton.setMinimumSize(new java.awt.Dimension(120, 120));
BWQCButton.setPreferredSize(new java.awt.Dimension(120, 120));
BWQCButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
BWQCButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BWQCButtonActionPerformed(evt);
}
});
Production.add(BWQCButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 190, 120, 120));
ChemicalsButton.setBackground(new java.awt.Color(48, 48, 240));
ChemicalsButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
ChemicalsButton.setForeground(new java.awt.Color(255, 255, 255));
ChemicalsButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-experiment-48.png"))); // NOI18N
ChemicalsButton.setText("Chemicals");
ChemicalsButton.setToolTipText("");
ChemicalsButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
ChemicalsButton.setMaximumSize(new java.awt.Dimension(120, 120));
ChemicalsButton.setMinimumSize(new java.awt.Dimension(120, 120));
ChemicalsButton.setPreferredSize(new java.awt.Dimension(120, 120));
ChemicalsButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
ChemicalsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ChemicalsButtonActionPerformed(evt);
}
});
Production.add(ChemicalsButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 190, 120, 120));
WashingButton.setBackground(new java.awt.Color(48, 48, 240));
WashingButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
WashingButton.setForeground(new java.awt.Color(255, 255, 255));
WashingButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-washing-machine-50.png"))); // NOI18N
WashingButton.setText("Washing");
WashingButton.setToolTipText("");
WashingButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
WashingButton.setMaximumSize(new java.awt.Dimension(120, 120));
WashingButton.setMinimumSize(new java.awt.Dimension(120, 120));
WashingButton.setPreferredSize(new java.awt.Dimension(120, 120));
WashingButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
WashingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WashingButtonActionPerformed(evt);
}
});
Production.add(WashingButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 190, 120, 120));
HydroButton.setBackground(new java.awt.Color(48, 48, 240));
HydroButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
HydroButton.setForeground(new java.awt.Color(255, 255, 255));
HydroButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-geothermal-50.png"))); // NOI18N
HydroButton.setText("Hydro");
HydroButton.setToolTipText("");
HydroButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
HydroButton.setMaximumSize(new java.awt.Dimension(120, 120));
HydroButton.setMinimumSize(new java.awt.Dimension(120, 120));
HydroButton.setPreferredSize(new java.awt.Dimension(120, 120));
HydroButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
HydroButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
HydroButtonActionPerformed(evt);
}
});
Production.add(HydroButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 190, 120, 120));
WetQCButton.setBackground(new java.awt.Color(48, 48, 240));
WetQCButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
WetQCButton.setForeground(new java.awt.Color(255, 255, 255));
WetQCButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-wet-50.png"))); // NOI18N
WetQCButton.setText("Wet QC");
WetQCButton.setToolTipText("");
WetQCButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
WetQCButton.setMaximumSize(new java.awt.Dimension(120, 120));
WetQCButton.setMinimumSize(new java.awt.Dimension(120, 120));
WetQCButton.setPreferredSize(new java.awt.Dimension(120, 120));
WetQCButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
WetQCButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WetQCButtonActionPerformed(evt);
}
});
Production.add(WetQCButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 190, 120, 120));
DryingButton.setBackground(new java.awt.Color(48, 48, 240));
DryingButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
DryingButton.setForeground(new java.awt.Color(255, 255, 255));
DryingButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-hair-dryer-50.png"))); // NOI18N
DryingButton.setText("Drying");
DryingButton.setToolTipText("");
DryingButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
DryingButton.setMaximumSize(new java.awt.Dimension(120, 120));
DryingButton.setMinimumSize(new java.awt.Dimension(120, 120));
DryingButton.setPreferredSize(new java.awt.Dimension(120, 120));
DryingButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
DryingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DryingButtonActionPerformed(evt);
}
});
Production.add(DryingButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 320, 120, 120));
AWQCButton.setBackground(new java.awt.Color(48, 48, 240));
AWQCButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
AWQCButton.setForeground(new java.awt.Color(255, 255, 255));
AWQCButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-idea-50.png"))); // NOI18N
AWQCButton.setText("A/W QC");
AWQCButton.setToolTipText("");
AWQCButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
AWQCButton.setMaximumSize(new java.awt.Dimension(120, 120));
AWQCButton.setMinimumSize(new java.awt.Dimension(120, 120));
AWQCButton.setPreferredSize(new java.awt.Dimension(120, 120));
AWQCButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
AWQCButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AWQCButtonActionPerformed(evt);
}
});
Production.add(AWQCButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 320, 120, 120));
FinishingButton.setBackground(new java.awt.Color(48, 48, 240));
FinishingButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
FinishingButton.setForeground(new java.awt.Color(255, 255, 255));
FinishingButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-finish-flag-filled-50.png"))); // NOI18N
FinishingButton.setText("Finishing");
FinishingButton.setToolTipText("");
FinishingButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
FinishingButton.setMaximumSize(new java.awt.Dimension(120, 120));
FinishingButton.setMinimumSize(new java.awt.Dimension(120, 120));
FinishingButton.setPreferredSize(new java.awt.Dimension(120, 120));
FinishingButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
FinishingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FinishingButtonActionPerformed(evt);
}
});
Production.add(FinishingButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 320, 120, 120));
jLayeredPane1.add(Production, "card18");
BWQC.setBackground(new java.awt.Color(255, 255, 255));
BWQC.setMinimumSize(new java.awt.Dimension(940, 480));
BWQC.setPreferredSize(new java.awt.Dimension(940, 480));
BWQC.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel94.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel94.setForeground(new java.awt.Color(255, 255, 255));
jLabel94.setText("B/W QC");
BWQC.add(jLabel94, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
BWQC.add(jSeparator13, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jTable5.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Date & Time", "Tag No", "Start Time", "End Time", "Emp No"
}
));
jTable5.setRowHeight(35);
jScrollPane5.setViewportView(jTable5);
BWQC.add(jScrollPane5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 910, 260));
jLabel96.setForeground(new java.awt.Color(255, 255, 255));
jLabel96.setText("Show :");
BWQC.add(jLabel96, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
jComboBox25.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "5", "10", "15" }));
jComboBox25.setSelectedIndex(2);
jComboBox25.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox25ActionPerformed(evt);
}
});
BWQC.add(jComboBox25, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 110, 70, 30));
jLabel97.setForeground(new java.awt.Color(255, 255, 255));
jLabel97.setText("entries");
BWQC.add(jLabel97, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, -1, -1));
search2.setText("Search..");
search2.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
search2CaretUpdate(evt);
}
});
search2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
search2MouseClicked(evt);
}
});
BWQC.add(search2, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
BWQCBack.setBackground(new java.awt.Color(255, 51, 0));
BWQCBack.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
BWQCBack.setForeground(new java.awt.Color(255, 255, 255));
BWQCBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Back.png"))); // NOI18N
BWQCBack.setText("Go Back");
BWQCBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BWQCBackActionPerformed(evt);
}
});
BWQC.add(BWQCBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
BWQCchk.setBackground(new java.awt.Color(0, 2, 240));
BWQCchk.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
BWQCchk.setForeground(new java.awt.Color(255, 255, 255));
BWQCchk.setText("Check B/W QC Tags");
BWQCchk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BWQCchkActionPerformed(evt);
}
});
BWQC.add(BWQCchk, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 60, 190, 30));
jButton23.setBackground(new java.awt.Color(0, 0, 255));
jButton23.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-14 (2).png"))); // NOI18N
jButton23.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton23ActionPerformed(evt);
}
});
BWQC.add(jButton23, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 420, 30, 30));
jButton24.setBackground(new java.awt.Color(0, 0, 255));
jButton24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-filled-14.png"))); // NOI18N
jButton24.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton24ActionPerformed(evt);
}
});
BWQC.add(jButton24, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 420, 30, 30));
total4.setForeground(new java.awt.Color(255, 255, 255));
total4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
BWQC.add(total4, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 30, 30));
jLabel13.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jLabel13.setForeground(new java.awt.Color(255, 255, 255));
jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel13.setText("/");
BWQC.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 420, 30, 30));
page4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
page4ActionPerformed(evt);
}
});
BWQC.add(page4, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, 30, 30));
jButton29.setBackground(new java.awt.Color(0, 0, 255));
jButton29.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14.png"))); // NOI18N
jButton29.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton29ActionPerformed(evt);
}
});
BWQC.add(jButton29, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 420, 30, 30));
jButton30.setBackground(new java.awt.Color(0, 0, 255));
jButton30.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14 (1).png"))); // NOI18N
jButton30.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton30ActionPerformed(evt);
}
});
BWQC.add(jButton30, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 420, 30, 30));
jButton12.setBackground(new java.awt.Color(71, 71, 116));
jButton12.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jButton12.setForeground(new java.awt.Color(255, 255, 255));
jButton12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Print.png"))); // NOI18N
jButton12.setText("Print");
jButton12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton12ActionPerformed(evt);
}
});
BWQC.add(jButton12, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 60, 100, 30));
jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/IMG-20180315-WA0017.jpg"))); // NOI18N
BWQC.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 940, 480));
jLayeredPane1.add(BWQC, "card9");
Chem.setBackground(new java.awt.Color(255, 255, 255));
Chem.setMinimumSize(new java.awt.Dimension(940, 480));
Chem.setPreferredSize(new java.awt.Dimension(940, 480));
Chem.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel99.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel99.setForeground(new java.awt.Color(255, 255, 255));
jLabel99.setText("Chemicals");
Chem.add(jLabel99, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
Chem.add(jSeparator14, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jTable6.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Date & Time", "Tag No", "Start Time", "End Time", "Emp No"
}
));
jTable6.setRowHeight(35);
jScrollPane6.setViewportView(jTable6);
Chem.add(jScrollPane6, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 910, 260));
jLabel101.setForeground(new java.awt.Color(255, 255, 255));
jLabel101.setText("Show :");
Chem.add(jLabel101, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
jComboBox26.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "5", "10", "15" }));
jComboBox26.setSelectedIndex(2);
jComboBox26.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox26ActionPerformed(evt);
}
});
Chem.add(jComboBox26, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 110, 70, 30));
jLabel102.setForeground(new java.awt.Color(255, 255, 255));
jLabel102.setText("entries");
Chem.add(jLabel102, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, -1, -1));
search3.setText("Search..");
search3.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
search3CaretUpdate(evt);
}
});
search3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
search3MouseClicked(evt);
}
});
Chem.add(search3, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
ChemBack.setBackground(new java.awt.Color(255, 51, 0));
ChemBack.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
ChemBack.setForeground(new java.awt.Color(255, 255, 255));
ChemBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Back.png"))); // NOI18N
ChemBack.setText("Go Back");
ChemBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ChemBackActionPerformed(evt);
}
});
Chem.add(ChemBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
chem_check.setBackground(new java.awt.Color(0, 2, 240));
chem_check.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
chem_check.setForeground(new java.awt.Color(255, 255, 255));
chem_check.setText("Check Chemicals Tag");
chem_check.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chem_checkActionPerformed(evt);
}
});
Chem.add(chem_check, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 60, 190, 30));
jButton31.setBackground(new java.awt.Color(0, 0, 255));
jButton31.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14 (1).png"))); // NOI18N
jButton31.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton31ActionPerformed(evt);
}
});
Chem.add(jButton31, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 420, 30, 30));
jButton33.setBackground(new java.awt.Color(0, 0, 255));
jButton33.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14.png"))); // NOI18N
jButton33.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton33ActionPerformed(evt);
}
});
Chem.add(jButton33, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 420, 30, 30));
page5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
page5ActionPerformed(evt);
}
});
Chem.add(page5, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, 30, 30));
jLabel14.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jLabel14.setForeground(new java.awt.Color(255, 255, 255));
jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel14.setText("/");
Chem.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 420, 30, 30));
total5.setForeground(new java.awt.Color(255, 255, 255));
total5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
Chem.add(total5, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 30, 30));
jButton34.setBackground(new java.awt.Color(0, 0, 255));
jButton34.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-filled-14.png"))); // NOI18N
jButton34.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton34ActionPerformed(evt);
}
});
Chem.add(jButton34, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 420, 30, 30));
jButton35.setBackground(new java.awt.Color(0, 0, 255));
jButton35.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-14 (2).png"))); // NOI18N
jButton35.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton35ActionPerformed(evt);
}
});
Chem.add(jButton35, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 420, 30, 30));
search4.setText("Search");
Chem.add(search4, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
jButton13.setBackground(new java.awt.Color(71, 71, 116));
jButton13.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jButton13.setForeground(new java.awt.Color(255, 255, 255));
jButton13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Print.png"))); // NOI18N
jButton13.setText("Print");
jButton13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton13ActionPerformed(evt);
}
});
Chem.add(jButton13, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 60, 100, 30));
jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/IMG-20180315-WA0017.jpg"))); // NOI18N
Chem.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 940, 480));
jLayeredPane1.add(Chem, "card9");
Wash.setBackground(new java.awt.Color(255, 255, 255));
Wash.setMinimumSize(new java.awt.Dimension(940, 480));
Wash.setPreferredSize(new java.awt.Dimension(940, 480));
Wash.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel104.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel104.setForeground(new java.awt.Color(255, 255, 255));
jLabel104.setText("Washing");
Wash.add(jLabel104, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
Wash.add(jSeparator15, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jTable13.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Date & Time", "Tag No", "Start Time", "End Time", "Emp No"
}
));
jTable13.setRowHeight(35);
jScrollPane7.setViewportView(jTable13);
Wash.add(jScrollPane7, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 910, 260));
jLabel106.setForeground(new java.awt.Color(255, 255, 255));
jLabel106.setText("Show :");
Wash.add(jLabel106, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
jComboBox27.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "5", "10", "15" }));
jComboBox27.setSelectedIndex(2);
jComboBox27.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox27ActionPerformed(evt);
}
});
Wash.add(jComboBox27, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 110, 70, 30));
jLabel107.setForeground(new java.awt.Color(255, 255, 255));
jLabel107.setText("entries");
Wash.add(jLabel107, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, -1, -1));
WashBack.setBackground(new java.awt.Color(255, 51, 0));
WashBack.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
WashBack.setForeground(new java.awt.Color(255, 255, 255));
WashBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Back.png"))); // NOI18N
WashBack.setText("Go Back");
WashBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WashBackActionPerformed(evt);
}
});
Wash.add(WashBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
Washchk.setBackground(new java.awt.Color(0, 2, 240));
Washchk.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
Washchk.setForeground(new java.awt.Color(255, 255, 255));
Washchk.setText("Check Washing Tag");
Washchk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WashchkActionPerformed(evt);
}
});
Wash.add(Washchk, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 60, 190, 30));
jButton36.setBackground(new java.awt.Color(0, 0, 255));
jButton36.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14 (1).png"))); // NOI18N
jButton36.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton36ActionPerformed(evt);
}
});
Wash.add(jButton36, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 420, 30, 30));
jButton37.setBackground(new java.awt.Color(0, 0, 255));
jButton37.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14.png"))); // NOI18N
jButton37.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton37ActionPerformed(evt);
}
});
Wash.add(jButton37, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 420, 30, 30));
page6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
page6ActionPerformed(evt);
}
});
Wash.add(page6, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, 30, 30));
jLabel15.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jLabel15.setForeground(new java.awt.Color(255, 255, 255));
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel15.setText("/");
Wash.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 420, 30, 30));
total6.setForeground(new java.awt.Color(255, 255, 255));
total6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
Wash.add(total6, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 30, 30));
jButton38.setBackground(new java.awt.Color(0, 0, 255));
jButton38.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-filled-14.png"))); // NOI18N
jButton38.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton38ActionPerformed(evt);
}
});
Wash.add(jButton38, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 420, 30, 30));
jButton39.setBackground(new java.awt.Color(0, 0, 255));
jButton39.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-14 (2).png"))); // NOI18N
jButton39.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton39ActionPerformed(evt);
}
});
Wash.add(jButton39, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 420, 30, 30));
search5.setText("Search..");
search5.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
search5CaretUpdate(evt);
}
});
search5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
search5MouseClicked(evt);
}
});
Wash.add(search5, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
jButton14.setBackground(new java.awt.Color(71, 71, 116));
jButton14.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jButton14.setForeground(new java.awt.Color(255, 255, 255));
jButton14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Print.png"))); // NOI18N
jButton14.setText("Print");
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14ActionPerformed(evt);
}
});
Wash.add(jButton14, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 60, 100, 30));
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/IMG-20180315-WA0017.jpg"))); // NOI18N
Wash.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 940, 480));
jLayeredPane1.add(Wash, "card9");
Hyd.setBackground(new java.awt.Color(255, 255, 255));
Hyd.setMinimumSize(new java.awt.Dimension(940, 480));
Hyd.setPreferredSize(new java.awt.Dimension(940, 480));
Hyd.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel109.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel109.setForeground(new java.awt.Color(255, 255, 255));
jLabel109.setText("Hydro");
Hyd.add(jLabel109, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
Hyd.add(jSeparator16, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jTable14.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Date & Time", "Tag No", "Start Time", "End Time", "Emp No"
}
));
jTable14.setRowHeight(35);
jScrollPane8.setViewportView(jTable14);
Hyd.add(jScrollPane8, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 910, 260));
jLabel111.setForeground(new java.awt.Color(255, 255, 255));
jLabel111.setText("Show :");
Hyd.add(jLabel111, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
jComboBox28.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "5", "10", "15" }));
jComboBox28.setSelectedIndex(2);
jComboBox28.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox28ActionPerformed(evt);
}
});
Hyd.add(jComboBox28, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 110, 70, 30));
jLabel112.setForeground(new java.awt.Color(255, 255, 255));
jLabel112.setText("entries");
Hyd.add(jLabel112, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, -1, -1));
HydBack.setBackground(new java.awt.Color(255, 51, 0));
HydBack.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
HydBack.setForeground(new java.awt.Color(255, 255, 255));
HydBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Back.png"))); // NOI18N
HydBack.setText("Go Back");
HydBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
HydBackActionPerformed(evt);
}
});
Hyd.add(HydBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
Hydrochk.setBackground(new java.awt.Color(0, 2, 240));
Hydrochk.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
Hydrochk.setForeground(new java.awt.Color(255, 255, 255));
Hydrochk.setText("Check Hydro Tag");
Hydrochk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
HydrochkActionPerformed(evt);
}
});
Hyd.add(Hydrochk, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 60, 190, 30));
jButton40.setBackground(new java.awt.Color(0, 0, 255));
jButton40.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14 (1).png"))); // NOI18N
jButton40.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton40ActionPerformed(evt);
}
});
Hyd.add(jButton40, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 420, 30, 30));
jButton41.setBackground(new java.awt.Color(0, 0, 255));
jButton41.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14.png"))); // NOI18N
jButton41.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton41ActionPerformed(evt);
}
});
Hyd.add(jButton41, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 420, 30, 30));
page7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
page7ActionPerformed(evt);
}
});
Hyd.add(page7, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, 30, 30));
jLabel16.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jLabel16.setForeground(new java.awt.Color(255, 255, 255));
jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel16.setText("/");
Hyd.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 420, 30, 30));
total7.setForeground(new java.awt.Color(255, 255, 255));
total7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
Hyd.add(total7, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 30, 30));
jButton42.setBackground(new java.awt.Color(0, 0, 255));
jButton42.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-filled-14.png"))); // NOI18N
jButton42.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton42ActionPerformed(evt);
}
});
Hyd.add(jButton42, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 420, 30, 30));
jButton43.setBackground(new java.awt.Color(0, 0, 255));
jButton43.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-14 (2).png"))); // NOI18N
jButton43.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton43ActionPerformed(evt);
}
});
Hyd.add(jButton43, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 420, 30, 30));
search6.setText("Search..");
search6.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
search6CaretUpdate(evt);
}
});
search6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
search6MouseClicked(evt);
}
});
Hyd.add(search6, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
jButton15.setBackground(new java.awt.Color(71, 71, 116));
jButton15.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jButton15.setForeground(new java.awt.Color(255, 255, 255));
jButton15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Print.png"))); // NOI18N
jButton15.setText("Print");
jButton15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton15ActionPerformed(evt);
}
});
Hyd.add(jButton15, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 60, 100, 30));
jLabel12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/IMG-20180315-WA0017.jpg"))); // NOI18N
Hyd.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 940, 480));
jLayeredPane1.add(Hyd, "card9");
WetQC.setBackground(new java.awt.Color(255, 255, 255));
WetQC.setMinimumSize(new java.awt.Dimension(940, 480));
WetQC.setPreferredSize(new java.awt.Dimension(940, 480));
WetQC.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel114.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel114.setForeground(new java.awt.Color(255, 255, 255));
jLabel114.setText("Wet QC");
WetQC.add(jLabel114, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
WetQC.add(jSeparator17, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jTable15.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Date & Time", "Tag No", "Start Time", "End Time", "Emp No"
}
));
jTable15.setRowHeight(35);
jScrollPane9.setViewportView(jTable15);
WetQC.add(jScrollPane9, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 910, 260));
jLabel116.setForeground(new java.awt.Color(255, 255, 255));
jLabel116.setText("Show :");
WetQC.add(jLabel116, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
jComboBox29.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "5", "10", "15" }));
jComboBox29.setSelectedIndex(2);
jComboBox29.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox29ActionPerformed(evt);
}
});
WetQC.add(jComboBox29, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 110, 70, 30));
jLabel117.setForeground(new java.awt.Color(255, 255, 255));
jLabel117.setText("entries");
WetQC.add(jLabel117, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, -1, -1));
WetQCBack.setBackground(new java.awt.Color(255, 51, 0));
WetQCBack.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
WetQCBack.setForeground(new java.awt.Color(255, 255, 255));
WetQCBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Back.png"))); // NOI18N
WetQCBack.setText("Go Back");
WetQCBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WetQCBackActionPerformed(evt);
}
});
WetQC.add(WetQCBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
WetQCchk.setBackground(new java.awt.Color(0, 2, 240));
WetQCchk.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
WetQCchk.setForeground(new java.awt.Color(255, 255, 255));
WetQCchk.setText("Check Wet QC Tag");
WetQCchk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
WetQCchkActionPerformed(evt);
}
});
WetQC.add(WetQCchk, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 60, 190, 30));
jButton44.setBackground(new java.awt.Color(0, 0, 255));
jButton44.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14 (1).png"))); // NOI18N
jButton44.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton44ActionPerformed(evt);
}
});
WetQC.add(jButton44, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 420, 30, 30));
jButton45.setBackground(new java.awt.Color(0, 0, 255));
jButton45.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14.png"))); // NOI18N
jButton45.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton45ActionPerformed(evt);
}
});
WetQC.add(jButton45, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 420, 30, 30));
page8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
page8ActionPerformed(evt);
}
});
WetQC.add(page8, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, 30, 30));
jLabel17.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jLabel17.setForeground(new java.awt.Color(255, 255, 255));
jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel17.setText("/");
WetQC.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 420, 30, 30));
total8.setForeground(new java.awt.Color(255, 255, 255));
total8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
WetQC.add(total8, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 30, 30));
jButton46.setBackground(new java.awt.Color(0, 0, 255));
jButton46.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-filled-14.png"))); // NOI18N
jButton46.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton46ActionPerformed(evt);
}
});
WetQC.add(jButton46, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 420, 30, 30));
jButton47.setBackground(new java.awt.Color(0, 0, 255));
jButton47.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-14 (2).png"))); // NOI18N
jButton47.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton47ActionPerformed(evt);
}
});
WetQC.add(jButton47, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 420, 30, 30));
search10.setText("Search..");
search10.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
search10CaretUpdate(evt);
}
});
search10.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
search10MouseClicked(evt);
}
});
WetQC.add(search10, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
jButton16.setBackground(new java.awt.Color(71, 71, 116));
jButton16.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jButton16.setForeground(new java.awt.Color(255, 255, 255));
jButton16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Print.png"))); // NOI18N
jButton16.setText("Print");
jButton16.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton16ActionPerformed(evt);
}
});
WetQC.add(jButton16, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 60, 100, 30));
jLabel31.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/IMG-20180315-WA0017.jpg"))); // NOI18N
WetQC.add(jLabel31, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 940, 480));
jLayeredPane1.add(WetQC, "card9");
Dry.setBackground(new java.awt.Color(255, 255, 255));
Dry.setMinimumSize(new java.awt.Dimension(940, 480));
Dry.setPreferredSize(new java.awt.Dimension(940, 480));
Dry.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel119.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel119.setForeground(new java.awt.Color(255, 255, 255));
jLabel119.setText("Drying");
Dry.add(jLabel119, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
Dry.add(jSeparator18, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jTable16.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Date & Time", "Tag No", "Start Time", "End Time", "Emp No"
}
));
jTable16.setRowHeight(35);
jScrollPane10.setViewportView(jTable16);
Dry.add(jScrollPane10, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 910, 260));
jLabel121.setForeground(new java.awt.Color(255, 255, 255));
jLabel121.setText("Show :");
Dry.add(jLabel121, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
jComboBox30.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "5", "10", "15" }));
jComboBox30.setSelectedIndex(2);
jComboBox30.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox30ActionPerformed(evt);
}
});
Dry.add(jComboBox30, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 110, 70, 30));
jLabel122.setForeground(new java.awt.Color(255, 255, 255));
jLabel122.setText("entries");
Dry.add(jLabel122, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, -1, -1));
search7.setText("Search..");
search7.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
search7CaretUpdate(evt);
}
});
search7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
search7MouseClicked(evt);
}
});
Dry.add(search7, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
DryBack.setBackground(new java.awt.Color(255, 51, 0));
DryBack.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
DryBack.setForeground(new java.awt.Color(255, 255, 255));
DryBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
DryBack.setText("Go Back");
DryBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DryBackActionPerformed(evt);
}
});
Dry.add(DryBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
Drychk.setBackground(new java.awt.Color(0, 2, 240));
Drychk.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
Drychk.setForeground(new java.awt.Color(255, 255, 255));
Drychk.setText("Check Drying Tag");
Drychk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DrychkActionPerformed(evt);
}
});
Dry.add(Drychk, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 60, 190, 30));
jButton48.setBackground(new java.awt.Color(0, 0, 255));
jButton48.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14 (1).png"))); // NOI18N
jButton48.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton48ActionPerformed(evt);
}
});
Dry.add(jButton48, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 420, 30, 30));
jButton49.setBackground(new java.awt.Color(0, 0, 255));
jButton49.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14.png"))); // NOI18N
jButton49.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton49ActionPerformed(evt);
}
});
Dry.add(jButton49, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 420, 30, 30));
page9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
page9ActionPerformed(evt);
}
});
Dry.add(page9, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, 30, 30));
jLabel18.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jLabel18.setForeground(new java.awt.Color(255, 255, 255));
jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel18.setText("/");
Dry.add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 420, 30, 30));
total9.setForeground(new java.awt.Color(255, 255, 255));
total9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
Dry.add(total9, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 30, 30));
jButton50.setBackground(new java.awt.Color(0, 0, 255));
jButton50.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-filled-14.png"))); // NOI18N
jButton50.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton50ActionPerformed(evt);
}
});
Dry.add(jButton50, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 420, 30, 30));
jButton51.setBackground(new java.awt.Color(0, 0, 255));
jButton51.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-14 (2).png"))); // NOI18N
jButton51.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton51ActionPerformed(evt);
}
});
Dry.add(jButton51, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 420, 30, 30));
search11.setText("Search");
Dry.add(search11, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
jButton17.setBackground(new java.awt.Color(71, 71, 116));
jButton17.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jButton17.setForeground(new java.awt.Color(255, 255, 255));
jButton17.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Print.png"))); // NOI18N
jButton17.setText("Print");
jButton17.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton17ActionPerformed(evt);
}
});
Dry.add(jButton17, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 60, 100, 30));
jLabel32.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/IMG-20180315-WA0017.jpg"))); // NOI18N
Dry.add(jLabel32, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 940, 480));
jLayeredPane1.add(Dry, "card9");
AWQC.setBackground(new java.awt.Color(255, 255, 255));
AWQC.setMinimumSize(new java.awt.Dimension(940, 480));
AWQC.setPreferredSize(new java.awt.Dimension(940, 480));
AWQC.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel124.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel124.setForeground(new java.awt.Color(255, 255, 255));
jLabel124.setText("A/W QC");
AWQC.add(jLabel124, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
AWQC.add(jSeparator19, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jTable17.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Date & Time", "Tag No", "Start Time", "End Time", "Emp No"
}
));
jTable17.setRowHeight(35);
jScrollPane11.setViewportView(jTable17);
AWQC.add(jScrollPane11, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 910, 260));
jLabel126.setForeground(new java.awt.Color(255, 255, 255));
jLabel126.setText("Show :");
AWQC.add(jLabel126, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
jComboBox31.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "5", "10", "15" }));
jComboBox31.setSelectedIndex(2);
jComboBox31.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox31ActionPerformed(evt);
}
});
AWQC.add(jComboBox31, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 110, 70, 30));
jLabel127.setForeground(new java.awt.Color(255, 255, 255));
jLabel127.setText("entries");
AWQC.add(jLabel127, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, -1, -1));
search8.setText("Search..");
search8.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
search8CaretUpdate(evt);
}
});
search8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
search8MouseClicked(evt);
}
});
AWQC.add(search8, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
AWQCBack.setBackground(new java.awt.Color(255, 51, 0));
AWQCBack.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
AWQCBack.setForeground(new java.awt.Color(255, 255, 255));
AWQCBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
AWQCBack.setText("Go Back");
AWQCBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AWQCBackActionPerformed(evt);
}
});
AWQC.add(AWQCBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
AWQCchk.setBackground(new java.awt.Color(0, 2, 240));
AWQCchk.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
AWQCchk.setForeground(new java.awt.Color(255, 255, 255));
AWQCchk.setText("Check A/W QC Tag");
AWQCchk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AWQCchkActionPerformed(evt);
}
});
AWQC.add(AWQCchk, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 60, 190, 30));
jButton52.setBackground(new java.awt.Color(0, 0, 255));
jButton52.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14 (1).png"))); // NOI18N
jButton52.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton52ActionPerformed(evt);
}
});
AWQC.add(jButton52, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 420, 30, 30));
jButton53.setBackground(new java.awt.Color(0, 0, 255));
jButton53.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14.png"))); // NOI18N
jButton53.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton53ActionPerformed(evt);
}
});
AWQC.add(jButton53, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 420, 30, 30));
page10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
page10ActionPerformed(evt);
}
});
AWQC.add(page10, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, 30, 30));
jLabel19.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jLabel19.setForeground(new java.awt.Color(255, 255, 255));
jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel19.setText("/");
AWQC.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 420, 30, 30));
total10.setForeground(new java.awt.Color(255, 255, 255));
total10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
AWQC.add(total10, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 30, 30));
jButton54.setBackground(new java.awt.Color(0, 0, 255));
jButton54.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-filled-14.png"))); // NOI18N
jButton54.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton54ActionPerformed(evt);
}
});
AWQC.add(jButton54, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 420, 30, 30));
jButton55.setBackground(new java.awt.Color(0, 0, 255));
jButton55.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-14 (2).png"))); // NOI18N
jButton55.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton55ActionPerformed(evt);
}
});
AWQC.add(jButton55, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 420, 30, 30));
search12.setText("Search");
AWQC.add(search12, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
jButton18.setBackground(new java.awt.Color(71, 71, 116));
jButton18.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jButton18.setForeground(new java.awt.Color(255, 255, 255));
jButton18.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Print.png"))); // NOI18N
jButton18.setText("Print");
jButton18.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton18ActionPerformed(evt);
}
});
AWQC.add(jButton18, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 60, 100, 30));
jLabel33.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/IMG-20180315-WA0017.jpg"))); // NOI18N
AWQC.add(jLabel33, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 940, 480));
jLayeredPane1.add(AWQC, "card9");
Finish.setBackground(new java.awt.Color(255, 255, 255));
Finish.setMinimumSize(new java.awt.Dimension(940, 480));
Finish.setPreferredSize(new java.awt.Dimension(940, 480));
Finish.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
FinishMouseClicked(evt);
}
});
Finish.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel130.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel130.setForeground(new java.awt.Color(255, 255, 255));
jLabel130.setText("Finishing");
Finish.add(jLabel130, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
Finish.add(jSeparator20, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jScrollPane12.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jScrollPane12MouseClicked(evt);
}
});
jTable18.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Date & Time", "Tag No", "Start Time", "End Time", "Emp No"
}
));
jTable18.setRowHeight(35);
jTable18.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable18MouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jTable18MouseEntered(evt);
}
});
jScrollPane12.setViewportView(jTable18);
Finish.add(jScrollPane12, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 910, 260));
jLabel140.setForeground(new java.awt.Color(255, 255, 255));
jLabel140.setText("Show :");
Finish.add(jLabel140, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
jComboBox32.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "5", "10", "15" }));
jComboBox32.setSelectedIndex(2);
jComboBox32.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox32ActionPerformed(evt);
}
});
Finish.add(jComboBox32, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 110, 70, 30));
jLabel153.setForeground(new java.awt.Color(255, 255, 255));
jLabel153.setText("entries");
Finish.add(jLabel153, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, -1, -1));
search9.setText("Search..");
search9.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
search9CaretUpdate(evt);
}
});
search9.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
search9MouseClicked(evt);
}
});
Finish.add(search9, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
FinBack.setBackground(new java.awt.Color(255, 51, 0));
FinBack.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
FinBack.setForeground(new java.awt.Color(255, 255, 255));
FinBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
FinBack.setText("Go Back");
FinBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FinBackActionPerformed(evt);
}
});
Finish.add(FinBack, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
Finchk.setBackground(new java.awt.Color(0, 2, 240));
Finchk.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
Finchk.setForeground(new java.awt.Color(255, 255, 255));
Finchk.setText("Check Finishing Tag");
Finchk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FinchkActionPerformed(evt);
}
});
Finish.add(Finchk, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 60, 190, 30));
jButton56.setBackground(new java.awt.Color(0, 0, 255));
jButton56.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14 (1).png"))); // NOI18N
jButton56.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton56ActionPerformed(evt);
}
});
Finish.add(jButton56, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 420, 30, 30));
jButton57.setBackground(new java.awt.Color(0, 0, 255));
jButton57.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-skip-to-start-14.png"))); // NOI18N
jButton57.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton57ActionPerformed(evt);
}
});
Finish.add(jButton57, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 420, 30, 30));
page11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
page11ActionPerformed(evt);
}
});
Finish.add(page11, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, 30, 30));
jLabel30.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jLabel30.setForeground(new java.awt.Color(255, 255, 255));
jLabel30.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel30.setText("/");
Finish.add(jLabel30, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 420, 30, 30));
total11.setForeground(new java.awt.Color(255, 255, 255));
total11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
Finish.add(total11, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 30, 30));
jButton58.setBackground(new java.awt.Color(0, 0, 255));
jButton58.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-filled-14.png"))); // NOI18N
jButton58.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton58ActionPerformed(evt);
}
});
Finish.add(jButton58, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 420, 30, 30));
jButton59.setBackground(new java.awt.Color(0, 0, 255));
jButton59.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/icons8-end-14 (2).png"))); // NOI18N
jButton59.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton59ActionPerformed(evt);
}
});
Finish.add(jButton59, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 420, 30, 30));
search13.setText("Search");
Finish.add(search13, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 110, 140, 30));
jButton1.setBackground(new java.awt.Color(71, 71, 116));
jButton1.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 255, 255));
jButton1.setText("Send Email");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
Finish.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 430, 180, 30));
jButton19.setBackground(new java.awt.Color(71, 71, 116));
jButton19.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jButton19.setForeground(new java.awt.Color(255, 255, 255));
jButton19.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Print.png"))); // NOI18N
jButton19.setText("Print");
jButton19.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton19ActionPerformed(evt);
}
});
Finish.add(jButton19, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 60, 100, 30));
jLabel34.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/IMG-20180315-WA0017.jpg"))); // NOI18N
Finish.add(jLabel34, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 940, 480));
jLayeredPane1.add(Finish, "card9");
BWQC1.setBackground(new java.awt.Color(255, 255, 255));
BWQC1.setMinimumSize(new java.awt.Dimension(940, 480));
BWQC1.setPreferredSize(new java.awt.Dimension(940, 480));
BWQC1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
BWQCBack1.setBackground(new java.awt.Color(255, 51, 0));
BWQCBack1.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
BWQCBack1.setForeground(new java.awt.Color(255, 255, 255));
BWQCBack1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
BWQCBack1.setText("Go Back");
BWQCBack1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BWQCBack1ActionPerformed(evt);
}
});
BWQC1.add(BWQCBack1, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
BWQC1.add(jSeparator21, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jLabel103.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel103.setText("Add before wash quality check tag ");
BWQC1.add(jLabel103, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
BWQCchk3add.setBackground(new java.awt.Color(0, 2, 240));
BWQCchk3add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
BWQCchk3add.setForeground(new java.awt.Color(255, 255, 255));
BWQCchk3add.setText("Add");
BWQCchk3add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BWQCchk3addActionPerformed(evt);
}
});
BWQC1.add(BWQCchk3add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 190, 190, 30));
BWQC1.add(jSeparator23, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
BWQCchk4addmanually.setBackground(new java.awt.Color(0, 2, 240));
BWQCchk4addmanually.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
BWQCchk4addmanually.setForeground(new java.awt.Color(255, 255, 255));
BWQCchk4addmanually.setText("Add Manually");
BWQCchk4addmanually.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BWQCchk4addmanuallyActionPerformed(evt);
}
});
BWQC1.add(BWQCchk4addmanually, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 440, 190, 30));
jLabel8.setText("Tag Number");
BWQC1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 310, -1, -1));
jLabel21.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel21.setText("Enter B/W Qc Information");
BWQC1.add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 270, -1, -1));
jLabel22.setText("Tag Number");
BWQC1.add(jLabel22, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 140, -1, -1));
jLabel23.setText("Employee No");
BWQC1.add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 180, -1, -1));
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel4.setText("Barcode Read");
BWQC1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, 130, 50));
jLabel7.setText("Time");
BWQC1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 390, -1, -1));
jLabel6.setText("Employee No");
BWQC1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 430, -1, -1));
jLabel5.setText("Date");
BWQC1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 350, -1, -1));
BW_ctag.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
BW_ctagFocusGained(evt);
}
});
BWQC1.add(BW_ctag, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 130, 390, 30));
BW_cemp.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
BW_cempFocusGained(evt);
}
});
BWQC1.add(BW_cemp, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 170, 390, 30));
BWQC1.add(BW_time, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 380, 340, 30));
BW_tag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BW_tagActionPerformed(evt);
}
});
BWQC1.add(BW_tag, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 300, 340, 30));
BW_emp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BW_empActionPerformed(evt);
}
});
BWQC1.add(BW_emp, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 420, 340, 30));
BW_err.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
BW_err.setForeground(new java.awt.Color(255, 0, 0));
BW_err.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
BWQC1.add(BW_err, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 400, 190, -1));
BWQC1.add(BW_date, new org.netbeans.lib.awtextra.AbsoluteConstraints(149, 340, 340, 30));
jLayeredPane1.add(BWQC1, "card9");
Chem1.setBackground(new java.awt.Color(255, 255, 255));
Chem1.setMinimumSize(new java.awt.Dimension(940, 480));
Chem1.setPreferredSize(new java.awt.Dimension(940, 480));
Chem1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
addchemback.setBackground(new java.awt.Color(255, 51, 0));
addchemback.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
addchemback.setForeground(new java.awt.Color(255, 255, 255));
addchemback.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
addchemback.setText("Go Back");
addchemback.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addchembackActionPerformed(evt);
}
});
Chem1.add(addchemback, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
Chem1.add(jSeparator25, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
add_chem_man_add.setBackground(new java.awt.Color(0, 2, 240));
add_chem_man_add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
add_chem_man_add.setForeground(new java.awt.Color(255, 255, 255));
add_chem_man_add.setText("Add manually");
add_chem_man_add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_chem_man_addActionPerformed(evt);
}
});
Chem1.add(add_chem_man_add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 440, 190, 30));
add_che_add.setBackground(new java.awt.Color(0, 2, 240));
add_che_add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
add_che_add.setForeground(new java.awt.Color(255, 255, 255));
add_che_add.setText("Add");
add_che_add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_che_addActionPerformed(evt);
}
});
Chem1.add(add_che_add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 190, 190, 30));
jLabel24.setText(" Tag Number");
Chem1.add(jLabel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 140, -1, -1));
jLabel25.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel25.setText("Barcode Reader");
Chem1.add(jLabel25, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, -1));
jLabel26.setText("Time");
Chem1.add(jLabel26, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 390, -1, -1));
jLabel27.setText("Tag Number");
Chem1.add(jLabel27, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 310, -1, -1));
jLabel28.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel28.setText("Enter deptChemicals Information");
Chem1.add(jLabel28, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, -1, -1));
jLabel29.setText(" Employee No");
Chem1.add(jLabel29, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 430, -1, -1));
jLabel37.setText("Employee No");
Chem1.add(jLabel37, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 180, -1, -1));
Chem_ctag.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Chem_ctagFocusGained(evt);
}
});
Chem1.add(Chem_ctag, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 130, 390, 30));
Chem_cemp.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Chem_cempFocusGained(evt);
}
});
Chem1.add(Chem_cemp, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 170, 390, 30));
Chem1.add(Chem_time, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 380, 220, 30));
jLabel105.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel105.setText("Add chemicals tag");
Chem1.add(jLabel105, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, -1, -1));
Chem_emp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Chem_empActionPerformed(evt);
}
});
Chem1.add(Chem_emp, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 420, 220, 30));
Chem_tag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Chem_tagActionPerformed(evt);
}
});
Chem1.add(Chem_tag, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 300, 220, 30));
Chem_err.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
Chem_err.setForeground(new java.awt.Color(255, 0, 0));
Chem1.add(Chem_err, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 400, 190, -1));
Chem1.add(Chem_date, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 340, 220, 30));
jLabel1.setText("Date");
Chem1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 350, -1, -1));
jLayeredPane1.add(Chem1, "card9");
Wash1.setBackground(new java.awt.Color(255, 255, 255));
Wash1.setMinimumSize(new java.awt.Dimension(940, 480));
Wash1.setPreferredSize(new java.awt.Dimension(940, 480));
Wash1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
add_wash_back.setBackground(new java.awt.Color(255, 51, 0));
add_wash_back.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
add_wash_back.setForeground(new java.awt.Color(255, 255, 255));
add_wash_back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
add_wash_back.setText("Go Back");
add_wash_back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_wash_backActionPerformed(evt);
}
});
Wash1.add(add_wash_back, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
Wash1.add(jSeparator29, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
Add_wash_manu_add.setBackground(new java.awt.Color(0, 2, 240));
Add_wash_manu_add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
Add_wash_manu_add.setForeground(new java.awt.Color(255, 255, 255));
Add_wash_manu_add.setText("Add Manually");
Add_wash_manu_add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Add_wash_manu_addActionPerformed(evt);
}
});
Wash1.add(Add_wash_manu_add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 440, 190, 30));
add_wash_add.setBackground(new java.awt.Color(0, 2, 240));
add_wash_add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
add_wash_add.setForeground(new java.awt.Color(255, 255, 255));
add_wash_add.setText("Add");
add_wash_add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_wash_addActionPerformed(evt);
}
});
Wash1.add(add_wash_add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 190, 190, 30));
jLabel20.setText(" Tag Number");
Wash1.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 140, -1, -1));
jLabel39.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel39.setText("Barcode Reader");
Wash1.add(jLabel39, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, -1));
jLabel43.setText("Date");
Wash1.add(jLabel43, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 350, -1, -1));
jLabel45.setText("Tag Number");
Wash1.add(jLabel45, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 310, -1, -1));
jLabel46.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel46.setText("Enter Washing Information");
Wash1.add(jLabel46, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, -1, -1));
jLabel48.setText("Time");
Wash1.add(jLabel48, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 390, -1, -1));
jLabel49.setText("Employee No");
Wash1.add(jLabel49, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 430, -1, -1));
jLabel52.setText("Employee No");
Wash1.add(jLabel52, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 180, -1, -1));
Wash_ctag.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Wash_ctagFocusGained(evt);
}
});
Wash1.add(Wash_ctag, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 130, 390, 30));
Wash_cemp.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Wash_cempFocusGained(evt);
}
});
Wash1.add(Wash_cemp, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 170, 390, 30));
Wash1.add(Wash_time, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 380, 230, 30));
jLabel98.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel98.setText("Add washing tag");
Wash1.add(jLabel98, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
Wash_emp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Wash_empActionPerformed(evt);
}
});
Wash1.add(Wash_emp, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 420, 230, 30));
Wash_tag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Wash_tagActionPerformed(evt);
}
});
Wash1.add(Wash_tag, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 300, 230, 30));
Wash_err.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
Wash_err.setForeground(new java.awt.Color(255, 0, 0));
Wash1.add(Wash_err, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 400, 190, -1));
Wash1.add(Wash_date, new org.netbeans.lib.awtextra.AbsoluteConstraints(149, 340, 230, 30));
jLayeredPane1.add(Wash1, "card9");
Hyd1.setBackground(new java.awt.Color(255, 255, 255));
Hyd1.setMinimumSize(new java.awt.Dimension(940, 480));
Hyd1.setPreferredSize(new java.awt.Dimension(940, 480));
Hyd1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
add_hydro_back.setBackground(new java.awt.Color(255, 51, 0));
add_hydro_back.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
add_hydro_back.setForeground(new java.awt.Color(255, 255, 255));
add_hydro_back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
add_hydro_back.setText("Go Back");
add_hydro_back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_hydro_backActionPerformed(evt);
}
});
Hyd1.add(add_hydro_back, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
Hyd1.add(jSeparator33, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
jLabel100.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel100.setText("Add hydro tag");
Hyd1.add(jLabel100, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, -1, -1));
Hyd1.add(Hydro_time, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 380, 240, 30));
Hydro_cemp.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Hydro_cempFocusGained(evt);
}
});
Hyd1.add(Hydro_cemp, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 170, 390, 30));
Hydro_ctag.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Hydro_ctagFocusGained(evt);
}
});
Hyd1.add(Hydro_ctag, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 130, 390, 30));
jLabel76.setText("Employee No");
Hyd1.add(jLabel76, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 180, -1, -1));
jLabel75.setText("Employee No ");
Hyd1.add(jLabel75, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 430, -1, -1));
jLabel74.setText("Time");
Hyd1.add(jLabel74, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 390, -1, -1));
jLabel73.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel73.setText("Enter Hydro Information");
Hyd1.add(jLabel73, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, -1, -1));
jLabel72.setText("Tag Number");
Hyd1.add(jLabel72, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 310, -1, -1));
jLabel71.setText("Date");
Hyd1.add(jLabel71, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 350, -1, -1));
jLabel68.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel68.setText("Barcode reader");
Hyd1.add(jLabel68, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, -1));
jLabel56.setText(" Tag Number");
Hyd1.add(jLabel56, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 140, -1, -1));
add_hydro_add.setBackground(new java.awt.Color(0, 2, 240));
add_hydro_add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
add_hydro_add.setForeground(new java.awt.Color(255, 255, 255));
add_hydro_add.setText("Add");
add_hydro_add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_hydro_addActionPerformed(evt);
}
});
Hyd1.add(add_hydro_add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 190, 190, 30));
add_hydro_manu_add.setBackground(new java.awt.Color(0, 2, 240));
add_hydro_manu_add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
add_hydro_manu_add.setForeground(new java.awt.Color(255, 255, 255));
add_hydro_manu_add.setText("Add Manually");
add_hydro_manu_add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_hydro_manu_addActionPerformed(evt);
}
});
Hyd1.add(add_hydro_manu_add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 440, 190, 30));
Hydro_emp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Hydro_empActionPerformed(evt);
}
});
Hyd1.add(Hydro_emp, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 420, 240, 30));
Hydro_tag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Hydro_tagActionPerformed(evt);
}
});
Hyd1.add(Hydro_tag, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 300, 240, 30));
Hydro_err.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
Hydro_err.setForeground(new java.awt.Color(255, 0, 0));
Hyd1.add(Hydro_err, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 400, 190, -1));
Hyd1.add(Hydro_date, new org.netbeans.lib.awtextra.AbsoluteConstraints(169, 340, 240, 30));
jLayeredPane1.add(Hyd1, "card9");
WetQC1.setBackground(new java.awt.Color(255, 255, 255));
WetQC1.setMinimumSize(new java.awt.Dimension(940, 480));
WetQC1.setPreferredSize(new java.awt.Dimension(940, 480));
WetQC1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
cheak_wet_qc_back.setBackground(new java.awt.Color(255, 51, 0));
cheak_wet_qc_back.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
cheak_wet_qc_back.setForeground(new java.awt.Color(255, 255, 255));
cheak_wet_qc_back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
cheak_wet_qc_back.setText("Go Back");
cheak_wet_qc_back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cheak_wet_qc_backActionPerformed(evt);
}
});
WetQC1.add(cheak_wet_qc_back, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
WetQC1.add(jSeparator37, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
Wet_addMan.setBackground(new java.awt.Color(0, 2, 240));
Wet_addMan.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
Wet_addMan.setForeground(new java.awt.Color(255, 255, 255));
Wet_addMan.setText("Add Manually");
Wet_addMan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Wet_addManActionPerformed(evt);
}
});
WetQC1.add(Wet_addMan, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 440, 190, 30));
Wet_cAdd.setBackground(new java.awt.Color(0, 2, 240));
Wet_cAdd.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
Wet_cAdd.setForeground(new java.awt.Color(255, 255, 255));
Wet_cAdd.setText("Add");
Wet_cAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Wet_cAddActionPerformed(evt);
}
});
WetQC1.add(Wet_cAdd, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 190, 190, 30));
jLabel77.setText("Tag Number");
WetQC1.add(jLabel77, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 140, -1, 10));
jLabel87.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel87.setText("Barcode Reader");
WetQC1.add(jLabel87, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, -1));
jLabel88.setText("Date");
WetQC1.add(jLabel88, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 350, -1, -1));
jLabel93.setText("Tag Number");
WetQC1.add(jLabel93, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 310, -1, -1));
jLabel120.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel120.setText("Enter wet Qc Information");
WetQC1.add(jLabel120, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, -1, -1));
jLabel123.setText("Time");
WetQC1.add(jLabel123, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 390, -1, -1));
jLabel125.setText("Employee No");
WetQC1.add(jLabel125, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 430, -1, -1));
jLabel128.setText("Employee No");
WetQC1.add(jLabel128, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 180, -1, -1));
Wet_ctag.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Wet_ctagFocusGained(evt);
}
});
WetQC1.add(Wet_ctag, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 130, 390, 30));
Wet_cemp.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Wet_cempFocusGained(evt);
}
});
WetQC1.add(Wet_cemp, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 170, 390, 30));
WetQC1.add(Wet_time, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 380, 220, 30));
jLabel115.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel115.setText("Add wet quality check tag");
WetQC1.add(jLabel115, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
Wet_emp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Wet_empActionPerformed(evt);
}
});
WetQC1.add(Wet_emp, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 220, 30));
Wet_tag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Wet_tagActionPerformed(evt);
}
});
WetQC1.add(Wet_tag, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 300, 220, 30));
Wet_err.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
Wet_err.setForeground(new java.awt.Color(255, 0, 0));
WetQC1.add(Wet_err, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 400, 190, -1));
WetQC1.add(Wet_date, new org.netbeans.lib.awtextra.AbsoluteConstraints(159, 340, 220, 30));
jLayeredPane1.add(WetQC1, "card9");
Dry1.setBackground(new java.awt.Color(255, 255, 255));
Dry1.setMinimumSize(new java.awt.Dimension(940, 480));
Dry1.setPreferredSize(new java.awt.Dimension(940, 480));
Dry1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
add_dry_back.setBackground(new java.awt.Color(255, 51, 0));
add_dry_back.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
add_dry_back.setForeground(new java.awt.Color(255, 255, 255));
add_dry_back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
add_dry_back.setText("Go Back");
add_dry_back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_dry_backActionPerformed(evt);
}
});
Dry1.add(add_dry_back, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
Dry1.add(jSeparator41, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
add_dry_manu_add.setBackground(new java.awt.Color(0, 2, 240));
add_dry_manu_add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
add_dry_manu_add.setForeground(new java.awt.Color(255, 255, 255));
add_dry_manu_add.setText("Add Manually");
add_dry_manu_add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_dry_manu_addActionPerformed(evt);
}
});
Dry1.add(add_dry_manu_add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 440, 190, 30));
add_dry_add.setBackground(new java.awt.Color(0, 2, 240));
add_dry_add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
add_dry_add.setForeground(new java.awt.Color(255, 255, 255));
add_dry_add.setText("Add");
add_dry_add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_dry_addActionPerformed(evt);
}
});
Dry1.add(add_dry_add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 200, 190, 30));
jLabel132.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel132.setText("Barcode Reader");
Dry1.add(jLabel132, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, -1));
jLabel134.setText(" Tag Number");
Dry1.add(jLabel134, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 300, -1, -1));
jLabel135.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel135.setText("Enter Drying Information");
Dry1.add(jLabel135, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 230, -1, -1));
jLabel136.setText(" Drying Maching No");
Dry1.add(jLabel136, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 300, -1, -1));
jLabel137.setText("Date");
Dry1.add(jLabel137, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 340, -1, -1));
jLabel138.setText("Drying Machine No");
Dry1.add(jLabel138, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 110, -1, -1));
jLabel129.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel129.setText("Add drying tag");
Dry1.add(jLabel129, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, -1, -1));
jLabel149.setText("Employee No");
Dry1.add(jLabel149, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 420, -1, -1));
jLabel150.setText("Time");
Dry1.add(jLabel150, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 380, -1, -1));
Dry1.add(Dry_time, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 370, 220, 30));
Dry_ctag.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Dry_ctagFocusGained(evt);
}
});
Dry1.add(Dry_ctag, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 100, 260, 30));
Dry_cemp.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Dry_cempFocusGained(evt);
}
});
Dry1.add(Dry_cemp, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 140, 260, 30));
jLabel151.setText("Employee No");
Dry1.add(jLabel151, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 150, -1, -1));
jLabel152.setText("Tag number");
Dry1.add(jLabel152, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 110, -1, -1));
Dry_mah.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "M001", "M002" }));
Dry_mah.setSelectedIndex(-1);
Dry_mah.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Dry_mahActionPerformed(evt);
}
});
Dry1.add(Dry_mah, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 290, 220, 30));
Dry_tag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Dry_tagActionPerformed(evt);
}
});
Dry1.add(Dry_tag, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 290, 220, 30));
Dry_emp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Dry_empActionPerformed(evt);
}
});
Dry1.add(Dry_emp, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 410, 220, 30));
Dry_err.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
Dry_err.setForeground(new java.awt.Color(255, 0, 0));
Dry_err.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
Dry1.add(Dry_err, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 370, 190, 40));
Dry1.add(Dry_date, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 330, 220, 30));
Dry_cmah.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "M001", "M002" }));
Dry_cmah.setSelectedIndex(-1);
Dry_cmah.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Dry_cmahActionPerformed(evt);
}
});
Dry1.add(Dry_cmah, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 100, 220, 30));
jLayeredPane1.add(Dry1, "card9");
AWQC1.setBackground(new java.awt.Color(255, 255, 255));
AWQC1.setMinimumSize(new java.awt.Dimension(940, 480));
AWQC1.setPreferredSize(new java.awt.Dimension(940, 480));
AWQC1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel139.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel139.setText("Add after wash quality check tag");
AWQC1.add(jLabel139, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
AWQC1Back.setBackground(new java.awt.Color(255, 51, 0));
AWQC1Back.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
AWQC1Back.setForeground(new java.awt.Color(255, 255, 255));
AWQC1Back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
AWQC1Back.setText("Go Back");
AWQC1Back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AWQC1BackActionPerformed(evt);
}
});
AWQC1.add(AWQC1Back, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
AWQC1.add(jSeparator45, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
AWQC1chk.setBackground(new java.awt.Color(0, 2, 240));
AWQC1chk.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
AWQC1chk.setForeground(new java.awt.Color(255, 255, 255));
AWQC1chk.setText("Add");
AWQC1chk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AWQC1chkActionPerformed(evt);
}
});
AWQC1.add(AWQC1chk, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 190, 190, 30));
AWQC1.add(jSeparator47, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
AWQCchk15.setBackground(new java.awt.Color(0, 2, 240));
AWQCchk15.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
AWQCchk15.setForeground(new java.awt.Color(255, 255, 255));
AWQCchk15.setText("Add Manualy");
AWQCchk15.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AWQCchk15ActionPerformed(evt);
}
});
AWQC1.add(AWQCchk15, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 410, 190, 30));
jLabel154.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel154.setText("Barcode Reader");
AWQC1.add(jLabel154, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, -1));
jLabel155.setText("Tag Number");
AWQC1.add(jLabel155, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 140, -1, 10));
AW_ctag.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
AW_ctagFocusGained(evt);
}
});
AWQC1.add(AW_ctag, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 130, 390, 30));
jLabel156.setText("Employee No");
AWQC1.add(jLabel156, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 180, -1, -1));
AW_cemp.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
AW_cempFocusGained(evt);
}
});
AWQC1.add(AW_cemp, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 170, 390, 30));
jLabel157.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel157.setText("Enter AW QC Information");
AWQC1.add(jLabel157, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, -1, -1));
jLabel158.setText("Tag Number");
AWQC1.add(jLabel158, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 310, -1, -1));
jLabel159.setText("Date");
AWQC1.add(jLabel159, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 350, -1, -1));
jLabel160.setText("Time");
AWQC1.add(jLabel160, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 390, -1, -1));
jLabel161.setText("Employee No");
AWQC1.add(jLabel161, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 430, -1, -1));
AWQC1.add(AW_time, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 380, 220, 30));
AW_emp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AW_empActionPerformed(evt);
}
});
AWQC1.add(AW_emp, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 220, 30));
AW_tag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AW_tagActionPerformed(evt);
}
});
AWQC1.add(AW_tag, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 300, 220, 30));
AW_err.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
AW_err.setForeground(new java.awt.Color(255, 0, 0));
AWQC1.add(AW_err, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 380, 190, -1));
AWQC1.add(AW_date, new org.netbeans.lib.awtextra.AbsoluteConstraints(159, 340, 220, 30));
jLayeredPane1.add(AWQC1, "card9");
Finish1.setBackground(new java.awt.Color(255, 255, 255));
Finish1.setMinimumSize(new java.awt.Dimension(940, 480));
Finish1.setPreferredSize(new java.awt.Dimension(940, 480));
Finish1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Finish1back.setBackground(new java.awt.Color(255, 51, 0));
Finish1back.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
Finish1back.setForeground(new java.awt.Color(255, 255, 255));
Finish1back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/production/Images/Back.png"))); // NOI18N
Finish1back.setText("Go Back");
Finish1back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Finish1backActionPerformed(evt);
}
});
Finish1.add(Finish1back, new org.netbeans.lib.awtextra.AbsoluteConstraints(830, 10, 100, -1));
Finish1.add(jSeparator38, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 940, 10));
Finish1add.setBackground(new java.awt.Color(0, 2, 240));
Finish1add.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
Finish1add.setForeground(new java.awt.Color(255, 255, 255));
Finish1add.setText("Add");
Finish1add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Finish1addActionPerformed(evt);
}
});
Finish1.add(Finish1add, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 190, 190, 30));
Finish1add1.setBackground(new java.awt.Color(0, 2, 240));
Finish1add1.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
Finish1add1.setForeground(new java.awt.Color(255, 255, 255));
Finish1add1.setText("Add Manually");
Finish1add1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Finish1add1ActionPerformed(evt);
}
});
Finish1.add(Finish1add1, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 440, 190, 30));
jLabel95.setText("Tag Number");
Finish1.add(jLabel95, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 130, -1, 20));
jLabel108.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel108.setText("Barcode Reader");
Finish1.add(jLabel108, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, -1));
jLabel110.setText("Date");
Finish1.add(jLabel110, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 350, -1, -1));
jLabel113.setText("Tag Number");
Finish1.add(jLabel113, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 310, -1, -1));
jLabel167.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel167.setText("Enter Finishing Information");
Finish1.add(jLabel167, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, -1, -1));
jLabel168.setText("Time");
Finish1.add(jLabel168, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 390, -1, -1));
jLabel169.setText("Employee No");
Finish1.add(jLabel169, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 430, -1, -1));
jLabel170.setText("Employee No");
Finish1.add(jLabel170, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 180, -1, -1));
Fin_ctag.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Fin_ctagFocusGained(evt);
}
});
Finish1.add(Fin_ctag, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 130, 390, 30));
Fin_cemp.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
Fin_cempFocusGained(evt);
}
});
Finish1.add(Fin_cemp, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 170, 390, 30));
Finish1.add(Fin_time, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 380, 220, 30));
jLabel118.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel118.setText("Add finishing tag");
Finish1.add(jLabel118, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
Fin_emp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Fin_empActionPerformed(evt);
}
});
Finish1.add(Fin_emp, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 420, 220, 30));
Fin_tag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Fin_tagActionPerformed(evt);
}
});
Finish1.add(Fin_tag, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 300, 220, 30));
Fin_err.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
Fin_err.setForeground(new java.awt.Color(255, 0, 0));
Finish1.add(Fin_err, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 400, 190, -1));
Finish1.add(Fin_date, new org.netbeans.lib.awtextra.AbsoluteConstraints(159, 340, 220, 30));
jLayeredPane1.add(Finish1, "card9");
jPanel1.add(jLayeredPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(-6, -5, 950, 490));
jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Production Process");
jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel2MouseClicked(evt);
}
});
jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 120, -1, -1));
jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Pre-Production Process");
jLabel3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel3MouseClicked(evt);
}
});
jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 120, -1, -1));
jSeparator1.setForeground(new java.awt.Color(255, 255, 255));
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 120, 10, 30));
jLabel141.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jLabel141.setForeground(new java.awt.Color(255, 255, 255));
jLabel141.setText("PROCESS");
jPanel1.add(jLabel141, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 30, 390, 40));
jSeparator3.setForeground(new java.awt.Color(255, 255, 255));
jPanel1.add(jSeparator3, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 82, 690, 10));
jLabel142.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/Production.png"))); // NOI18N
jLabel142.setText("jLabel3");
jPanel1.add(jLabel142, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 30, 50, 40));
Background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ITP/Images/IMG-20180315-WA0017.jpg"))); // NOI18N
jPanel1.add(Background, new org.netbeans.lib.awtextra.AbsoluteConstraints(-6, -6, 950, 490));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 940, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 480, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
private void BWQCButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BWQCButtonActionPerformed
// TODO add your handling code here:
BWQC.setVisible(true);
Production.setVisible(false);
Home.pro.setVisible(false);
jLabel2.hide();
jLabel3.hide();
Background.hide();
try {
addtoProcesschkTable();
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_BWQCButtonActionPerformed
private void ChemicalsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ChemicalsButtonActionPerformed
// TODO add your handling code here:
Chem.setVisible(true);
Production.setVisible(false);
Home.pro.setVisible(false);
jLabel2.hide();
jLabel3.hide();
Background.hide();
try {
addtoProcesschkTable();
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_ChemicalsButtonActionPerformed
private void WashingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_WashingButtonActionPerformed
// TODO add your handling code here:
Wash.setVisible(true);
Production.setVisible(false);
Home.pro.setVisible(false);
jLabel2.hide();
jLabel3.hide();
Background.hide();
try {
addtoProcesschkTable();
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_WashingButtonActionPerformed
private void HydroButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HydroButtonActionPerformed
// TODO add your handling code here:
Hyd.setVisible(true);
Production.setVisible(false);
Home.pro.setVisible(false);
jLabel2.hide();
jLabel3.hide();
Background.hide();
try {
addtoProcesschkTable();
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_HydroButtonActionPerformed
private void WetQCButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_WetQCButtonActionPerformed
// TODO add your handling code here:
WetQC.setVisible(true);
Production.setVisible(false);
Home.pro.setVisible(false);
jLabel2.hide();
jLabel3.hide();
Background.hide();
try {
addtoProcesschkTable();
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_WetQCButtonActionPerformed
private void DryingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DryingButtonActionPerformed
// TODO add your handling code here:
Dry.setVisible(true);
Production.setVisible(false);
Home.pro.setVisible(false);
jLabel2.hide();
jLabel3.hide();
Background.hide();
try {
addtoProcesschkTable();
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_DryingButtonActionPerformed
private void AWQCButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AWQCButtonActionPerformed
// TODO add your handling code here:
AWQC.setVisible(true);
Production.setVisible(false);
Home.pro.setVisible(false);
jLabel2.hide();
jLabel3.hide();
Background.hide();
try {
addtoProcesschkTable();
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_AWQCButtonActionPerformed
private void FinishingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FinishingButtonActionPerformed
// TODO add your handling code here:
Finish.setVisible(true);
Production.setVisible(false);
Home.pro.setVisible(false);
jLabel2.hide();
jLabel3.hide();
Background.hide();
try {
addtoProcesschkTable();
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_FinishingButtonActionPerformed
private void BWQCBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BWQCBackActionPerformed
// TODO add your handling code here:
Home.pro.setVisible(false);
Production.setVisible(true);
BWQC.setVisible(false);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
Background.setVisible(true);
}//GEN-LAST:event_BWQCBackActionPerformed
private void BWQCchkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BWQCchkActionPerformed
BWQC1.setVisible(true);
BWQC.setVisible(false);
try {
BW_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN bwqc b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
BW_tag.addItem(rs.getString("Tag_No"));
}
BW_tag.setSelectedIndex(-1);
BW_emp.removeAllItems();
ResultSet rs1 = con.createStatement().executeQuery("SELECT empNo FROM employee");
while (rs1.next()) {
BW_emp.addItem(rs1.getString("empNo"));
}
BW_emp.setSelectedIndex(-1);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
BW_date.setText(String.valueOf(java.time.LocalDate.now()));
BW_date.setEnabled(false);
BW_time.setText(String.valueOf(java.time.LocalTime.now()));
BW_time.setEnabled(false);
}//GEN-LAST:event_BWQCchkActionPerformed
private void ChemBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ChemBackActionPerformed
// TODO add your handling code here:
Home.pro.setVisible(false);
Production.setVisible(true);
Chem.setVisible(false);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
Background.setVisible(true);
}//GEN-LAST:event_ChemBackActionPerformed
private void chem_checkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chem_checkActionPerformed
// TODO add your handling code here:
Chem1.setVisible(true);
Chem.setVisible(false);
try {
Chem_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN chemicals b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Chem_tag.addItem(rs.getString("Tag_No"));
}
Chem_tag.setSelectedIndex(-1);
Chem_emp.removeAllItems();
ResultSet rs1 = con.createStatement().executeQuery("SELECT empNo FROM employee");
while (rs1.next()) {
Chem_emp.addItem(rs1.getString("empNo"));
}
Chem_emp.setSelectedIndex(-1);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Chem_date.setText(String.valueOf(java.time.LocalDate.now()));
Chem_date.setEnabled(false);
Chem_time.setText(String.valueOf(java.time.LocalTime.now()));
Chem_time.setEnabled(false);
}//GEN-LAST:event_chem_checkActionPerformed
private void WashBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_WashBackActionPerformed
// TODO add your handling code here:
Home.pro.setVisible(false);
Production.setVisible(true);
Wash.setVisible(false);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
Background.setVisible(true);
}//GEN-LAST:event_WashBackActionPerformed
private void WashchkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_WashchkActionPerformed
// TODO add your handling code here:
Wash1.setVisible(true);
Wash.setVisible(false);
try {
Wash_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN wash b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Wash_tag.addItem(rs.getString("Tag_No"));
}
Wash_tag.setSelectedIndex(-1);
Wash_emp.removeAllItems();
ResultSet rs1 = con.createStatement().executeQuery("SELECT empNo FROM employee");
while (rs1.next()) {
Wash_emp.addItem(rs1.getString("empNo"));
}
Wash_emp.setSelectedIndex(-1);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Wash_date.setText(String.valueOf(java.time.LocalDate.now()));
Wash_date.setEnabled(false);
Wash_time.setText(String.valueOf(java.time.LocalTime.now()));
Wash_time.setEnabled(false);
}//GEN-LAST:event_WashchkActionPerformed
private void HydBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HydBackActionPerformed
// TODO add your handling code here:
Home.pro.setVisible(false);
Production.setVisible(true);
Hyd.setVisible(false);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
Background.setVisible(true);
}//GEN-LAST:event_HydBackActionPerformed
private void HydrochkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HydrochkActionPerformed
// TODO add your handling code here:
Hyd1.setVisible(true);
Hyd.setVisible(false);
try {
Hydro_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN hydro b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Hydro_tag.addItem(rs.getString("Tag_No"));
}
Hydro_tag.setSelectedIndex(-1);
Hydro_emp.removeAllItems();
ResultSet rs1 = con.createStatement().executeQuery("SELECT empNo FROM employee");
while (rs1.next()) {
Hydro_emp.addItem(rs1.getString("empNo"));
}
Hydro_emp.setSelectedIndex(-1);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Hydro_date.setText(String.valueOf(java.time.LocalDate.now()));
Hydro_date.setEnabled(false);
Hydro_time.setText(String.valueOf(java.time.LocalTime.now()));
Hydro_time.setEnabled(false);
}//GEN-LAST:event_HydrochkActionPerformed
private void WetQCBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_WetQCBackActionPerformed
// TODO add your handling code here:
Home.pro.setVisible(false);
Production.setVisible(true);
WetQC.setVisible(false);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
Background.setVisible(true);
}//GEN-LAST:event_WetQCBackActionPerformed
private void WetQCchkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_WetQCchkActionPerformed
// TODO add your handling code here:
WetQC1.setVisible(true);
WetQC.setVisible(false);
try {
Wet_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN wetqc b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Wet_tag.addItem(rs.getString("Tag_No"));
}
Wet_tag.setSelectedIndex(-1);
Wet_emp.removeAllItems();
ResultSet rs1 = con.createStatement().executeQuery("SELECT empNo FROM employee");
while (rs1.next()) {
Wet_emp.addItem(rs1.getString("empNo"));
}
Wet_emp.setSelectedIndex(-1);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Wet_date.setText(String.valueOf(java.time.LocalDate.now()));
Wet_date.setEnabled(false);
Wet_time.setText(String.valueOf(java.time.LocalTime.now()));
Wet_time.setEnabled(false);
}//GEN-LAST:event_WetQCchkActionPerformed
private void DryBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DryBackActionPerformed
// TODO add your handling code here:
Home.pro.setVisible(false);
Production.setVisible(true);
Dry.setVisible(false);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
Background.setVisible(true);
}//GEN-LAST:event_DryBackActionPerformed
private void DrychkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DrychkActionPerformed
// TODO add your handling code here:
Dry1.setVisible(true);
Dry.setVisible(false);
try {
Dry_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN dry b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Dry_tag.addItem(rs.getString("Tag_No"));
}
Dry_tag.setSelectedIndex(-1);
Dry_emp.removeAllItems();
ResultSet rs1 = con.createStatement().executeQuery("SELECT empNo FROM employee");
while (rs1.next()) {
Dry_emp.addItem(rs1.getString("empNo"));
}
Dry_emp.setSelectedIndex(-1);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Dry_date.setText(String.valueOf(java.time.LocalDate.now()));
Dry_date.setEnabled(false);
Dry_time.setText(String.valueOf(java.time.LocalTime.now()));
Dry_time.setEnabled(false);
}//GEN-LAST:event_DrychkActionPerformed
private void AWQCBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AWQCBackActionPerformed
// TODO add your handling code here:
Home.pro.setVisible(false);
Production.setVisible(true);
AWQC.setVisible(false);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
Background.setVisible(true);
}//GEN-LAST:event_AWQCBackActionPerformed
private void AWQCchkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AWQCchkActionPerformed
// TODO add your handling code here:
AWQC1.setVisible(true);
AWQC.setVisible(false);
try {
AW_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN awqc b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
AW_tag.addItem(rs.getString("Tag_No"));
}
AW_tag.setSelectedIndex(-1);
AW_emp.removeAllItems();
ResultSet rs1 = con.createStatement().executeQuery("SELECT empNo FROM employee");
while (rs1.next()) {
AW_emp.addItem(rs1.getString("empNo"));
}
AW_emp.setSelectedIndex(-1);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
AW_date.setText(String.valueOf(java.time.LocalDate.now()));
AW_date.setEnabled(false);
AW_time.setText(String.valueOf(java.time.LocalTime.now()));
AW_time.setEnabled(false);
}//GEN-LAST:event_AWQCchkActionPerformed
private void FinBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FinBackActionPerformed
// TODO add your handling code here:
Home.pro.setVisible(false);
Production.setVisible(true);
Finish.setVisible(false);
jLabel2.setVisible(true);
jLabel3.setVisible(true);
Background.setVisible(true);
}//GEN-LAST:event_FinBackActionPerformed
private void FinchkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FinchkActionPerformed
// TODO add your handling code here:
Finish.setVisible(false);
Finish1.setVisible(true);
try {
Fin_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN finish b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Fin_tag.addItem(rs.getString("Tag_No"));
}
Fin_tag.setSelectedIndex(-1);
Fin_emp.removeAllItems();
ResultSet rs1 = con.createStatement().executeQuery("SELECT empNo FROM employee");
while (rs1.next()) {
Fin_emp.addItem(rs1.getString("empNo"));
}
Fin_emp.setSelectedIndex(-1);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Fin_date.setText(String.valueOf(java.time.LocalDate.now()));
Fin_date.setEnabled(false);
Fin_time.setText(String.valueOf(java.time.LocalTime.now()));
Fin_time.setEnabled(false);
}//GEN-LAST:event_FinchkActionPerformed
private void BWQCBack1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BWQCBack1ActionPerformed
// TODO add your handling code here:
BWQC1.setVisible(false);
BWQC.setVisible(true);
}//GEN-LAST:event_BWQCBack1ActionPerformed
private void addchembackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addchembackActionPerformed
// TODO add your handling code here:
Chem1.setVisible(false);
Chem.setVisible(true);
}//GEN-LAST:event_addchembackActionPerformed
private void add_wash_backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_wash_backActionPerformed
// TODO add your handling code here:
Wash1.setVisible(false);
Wash.setVisible(true);
}//GEN-LAST:event_add_wash_backActionPerformed
private void add_hydro_backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_hydro_backActionPerformed
Hyd1.setVisible(false);
Hyd.setVisible(true);
// TODO add your handling code here:
}//GEN-LAST:event_add_hydro_backActionPerformed
private void cheak_wet_qc_backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cheak_wet_qc_backActionPerformed
WetQC1.setVisible(false);
WetQC.setVisible(true); // TODO add your handling code here:
}//GEN-LAST:event_cheak_wet_qc_backActionPerformed
private void add_dry_backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_dry_backActionPerformed
Dry1.setVisible(false);
Dry.setVisible(true); // TODO add your handling code here:
}//GEN-LAST:event_add_dry_backActionPerformed
private void AWQC1BackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AWQC1BackActionPerformed
// TODO add your handling code here:
AWQC.setVisible(true);
AWQC1.setVisible(false);
}//GEN-LAST:event_AWQC1BackActionPerformed
private void Finish1backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Finish1backActionPerformed
try {
// TODO add your handling code here:
Finish.setVisible(true);
Finish1.setVisible(false);
updateMax("SELECT COUNT(*) AS count FROM finish", total4, page4);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_Finish1backActionPerformed
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MouseClicked
// TODO add your handling code here:
Home.process.setVisible(true);
Home.pro.setVisible(false);
}//GEN-LAST:event_jLabel2MouseClicked
private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked
// TODO add your handling code here:
Home.pro.setVisible(true);
Home.process.setVisible(false);
}//GEN-LAST:event_jLabel3MouseClicked
private void jButton30ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton30ActionPerformed
pg = 1;
page4.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton30ActionPerformed
private void jButton29ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton29ActionPerformed
if (pg > 1) {
pg--;
page4.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton29ActionPerformed
private void page4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_page4ActionPerformed
int p = Integer.parseInt((String) page4.getText());
if (p > maxPages || p < 1) {
} else {
try {
pg = p;
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_page4ActionPerformed
private void jButton24ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton24ActionPerformed
if (pg < maxPages) {
pg++;
page4.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton24ActionPerformed
private void jButton23ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton23ActionPerformed
pg = maxPages;
page4.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton23ActionPerformed
private void jComboBox25ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox25ActionPerformed
if (jComboBox25.getSelectedItem().equals("")) {
lim = 15;
jComboBox25.setSelectedItem("15");
pg = 1;
page4.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
lim = Integer.parseInt((String) jComboBox25.getSelectedItem());
pg = 1;
page4.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jComboBox25ActionPerformed
private void search2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_search2MouseClicked
search2.setText(null);
}//GEN-LAST:event_search2MouseClicked
private void search2CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_search2CaretUpdate
String sh = search2.getText();
if (sh.equals("")) {
try {
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
addProcessTable("SELECT * FROM bwqc WHERE Tag_No like '%" + sh + "%' or Date like '%" + sh + "%' or Time like '%" + sh + "%' or Emp_No like '%" + sh + "%'", jTable5);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_search2CaretUpdate
private void jButton31ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton31ActionPerformed
pg = 1;
page5.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton31ActionPerformed
private void jButton33ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton33ActionPerformed
if (pg > 1) {
pg--;
page5.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton33ActionPerformed
private void page5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_page5ActionPerformed
int p = Integer.parseInt((String) page5.getText());
if (p > maxPages || p < 1) {
} else {
try {
pg = p;
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_page5ActionPerformed
private void jButton34ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton34ActionPerformed
if (pg < maxPages) {
pg++;
page5.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton34ActionPerformed
private void jButton35ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton35ActionPerformed
pg = maxPages;
page5.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton35ActionPerformed
private void jComboBox26ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox26ActionPerformed
if (jComboBox26.getSelectedItem().equals("")) {
lim = 15;
jComboBox26.setSelectedItem("15");
pg = 1;
page5.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
lim = Integer.parseInt((String) jComboBox26.getSelectedItem());
pg = 1;
page5.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jComboBox26ActionPerformed
private void search3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_search3MouseClicked
search3.setText(null);
}//GEN-LAST:event_search3MouseClicked
private void search3CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_search3CaretUpdate
String sh = search2.getText();
if (sh.equals("")) {
try {
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
addProcessTable("SELECT * FROM chemicals WHERE Tag_No like '%" + sh + "%' or Date like '%" + sh + "%' or Time like '%" + sh + "%' or Emp_No like '%" + sh + "%'", jTable6);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_search3CaretUpdate
private void jButton36ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton36ActionPerformed
pg = 1;
page6.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton36ActionPerformed
private void jButton37ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton37ActionPerformed
if (pg > 1) {
pg--;
page6.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton37ActionPerformed
private void page6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_page6ActionPerformed
int p = Integer.parseInt((String) page6.getText());
if (p > maxPages || p < 1) {
} else {
try {
pg = p;
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_page6ActionPerformed
private void jButton38ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton38ActionPerformed
if (pg < maxPages) {
pg++;
page6.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton38ActionPerformed
private void jButton39ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton39ActionPerformed
pg = maxPages;
page6.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton39ActionPerformed
private void jComboBox27ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox27ActionPerformed
if (jComboBox27.getSelectedItem().equals("")) {
lim = 15;
jComboBox27.setSelectedItem("15");
pg = 1;
page6.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
lim = Integer.parseInt((String) jComboBox27.getSelectedItem());
pg = 1;
page6.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jComboBox27ActionPerformed
private void search5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_search5MouseClicked
search5.setText(null);
}//GEN-LAST:event_search5MouseClicked
private void search5CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_search5CaretUpdate
String sh = search5.getText();
if (sh.equals("")) {
try {
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
addProcessTable("SELECT * FROM wash WHERE Tag_No like '%" + sh + "%' or Date like '%" + sh + "%' or Time like '%" + sh + "%' or Emp_No like '%" + sh + "%'", jTable13);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_search5CaretUpdate
private void jButton40ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton40ActionPerformed
pg = 1;
page7.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton40ActionPerformed
private void jButton41ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton41ActionPerformed
if (pg > 1) {
pg--;
page7.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton41ActionPerformed
private void page7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_page7ActionPerformed
int p = Integer.parseInt((String) page7.getText());
if (p > maxPages || p < 1) {
} else {
try {
pg = p;
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_page7ActionPerformed
private void jButton42ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton42ActionPerformed
if (pg < maxPages) {
pg++;
page7.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton42ActionPerformed
private void jButton43ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton43ActionPerformed
pg = maxPages;
page7.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton43ActionPerformed
private void jComboBox28ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox28ActionPerformed
if (jComboBox28.getSelectedItem().equals("")) {
lim = 15;
jComboBox28.setSelectedItem("15");
pg = 1;
page7.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
lim = Integer.parseInt((String) jComboBox28.getSelectedItem());
pg = 1;
page7.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jComboBox28ActionPerformed
private void search6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_search6MouseClicked
search6.setText(null);
}//GEN-LAST:event_search6MouseClicked
private void search6CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_search6CaretUpdate
String sh = search6.getText();
if (sh.equals("")) {
try {
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
addProcessTable("SELECT * FROM hydro WHERE Tag_No like '%" + sh + "%' or Date like '%" + sh + "%' or Time like '%" + sh + "%' or Emp_No like '%" + sh + "%'", jTable14);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_search6CaretUpdate
private void jButton44ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton44ActionPerformed
pg = 1;
page8.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton44ActionPerformed
private void jButton45ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton45ActionPerformed
if (pg > 1) {
pg--;
page8.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton45ActionPerformed
private void page8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_page8ActionPerformed
int p = Integer.parseInt((String) page8.getText());
if (p > maxPages || p < 1) {
} else {
try {
pg = p;
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_page8ActionPerformed
private void jButton46ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton46ActionPerformed
if (pg < maxPages) {
pg++;
page8.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton46ActionPerformed
private void jButton47ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton47ActionPerformed
pg = maxPages;
page8.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton47ActionPerformed
private void jComboBox29ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox29ActionPerformed
if (jComboBox29.getSelectedItem().equals("")) {
lim = 15;
jComboBox29.setSelectedItem("15");
pg = 1;
page8.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
lim = Integer.parseInt((String) jComboBox29.getSelectedItem());
pg = 1;
page8.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jComboBox29ActionPerformed
private void search10MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_search10MouseClicked
search10.setText(null);
}//GEN-LAST:event_search10MouseClicked
private void search10CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_search10CaretUpdate
String sh = search10.getText();
if (sh.equals("")) {
try {
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
addProcessTable("SELECT * FROM wetqc WHERE Tag_No like '%" + sh + "%' or Date like '%" + sh + "%' or Time like '%" + sh + "%' or Emp_No like '%" + sh + "%'", jTable15);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_search10CaretUpdate
private void jButton48ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton48ActionPerformed
pg = 1;
page9.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addDryProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton48ActionPerformed
private void jButton49ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton49ActionPerformed
if (pg > 1) {
pg--;
page9.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addDryProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton49ActionPerformed
private void page9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_page9ActionPerformed
int p = Integer.parseInt((String) page9.getText());
if (p > maxPages || p < 1) {
} else {
try {
pg = p;
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addDryProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_page9ActionPerformed
private void jButton50ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton50ActionPerformed
if (pg < maxPages) {
pg++;
page9.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addDryProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton50ActionPerformed
private void jButton51ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton51ActionPerformed
pg = maxPages;
page9.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addDryProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton51ActionPerformed
private void jComboBox30ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox30ActionPerformed
if (jComboBox30.getSelectedItem().equals("")) {
lim = 15;
jComboBox30.setSelectedItem("15");
pg = 1;
page9.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addDryProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
lim = Integer.parseInt((String) jComboBox30.getSelectedItem());
pg = 1;
page9.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addDryProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jComboBox30ActionPerformed
private void search7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_search7MouseClicked
search7.setText(null);
}//GEN-LAST:event_search7MouseClicked
private void search7CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_search7CaretUpdate
String sh = search7.getText();
if (sh.equals("")) {
try {
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addDryProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
addDryProcessTable("SELECT * FROM dry WHERE Tag_No like '%" + sh + "%' or Machine_No like '%" + sh + "%' or Date like '%" + sh + "%' or Time like '%" + sh + "%' or Emp_No like '%" + sh + "%'", jTable16);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_search7CaretUpdate
private void jButton52ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton52ActionPerformed
pg = 1;
page10.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton52ActionPerformed
private void jButton53ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton53ActionPerformed
if (pg > 1) {
pg--;
page10.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton53ActionPerformed
private void page10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_page10ActionPerformed
int p = Integer.parseInt((String) page10.getText());
if (p > maxPages || p < 1) {
} else {
try {
pg = p;
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_page10ActionPerformed
private void jButton54ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton54ActionPerformed
if (pg < maxPages) {
pg++;
page10.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton54ActionPerformed
private void jButton55ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton55ActionPerformed
pg = maxPages;
page10.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton55ActionPerformed
private void jComboBox31ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox31ActionPerformed
if (jComboBox31.getSelectedItem().equals("")) {
lim = 15;
jComboBox31.setSelectedItem("15");
pg = 1;
page10.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
lim = Integer.parseInt((String) jComboBox31.getSelectedItem());
pg = 1;
page10.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jComboBox31ActionPerformed
private void search8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_search8MouseClicked
search8.setText(null);
}//GEN-LAST:event_search8MouseClicked
private void search8CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_search8CaretUpdate
String sh = search8.getText();
if (sh.equals("")) {
try {
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
addProcessTable("SELECT * FROM awqc WHERE Tag_No like '%" + sh + "%' or Date like '%" + sh + "%' or Time like '%" + sh + "%' or Emp_No like '%" + sh + "%'", jTable17);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_search8CaretUpdate
private void jButton56ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton56ActionPerformed
pg = 1;
page11.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton56ActionPerformed
private void jButton57ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton57ActionPerformed
if (pg > 1) {
pg--;
page11.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton57ActionPerformed
private void page11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_page11ActionPerformed
int p = Integer.parseInt((String) page11.getText());
if (p > maxPages || p < 1) {
} else {
try {
pg = p;
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_page11ActionPerformed
private void jButton58ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton58ActionPerformed
if (pg < maxPages) {
pg++;
page11.setText(Integer.toString(pg));
}
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton58ActionPerformed
private void jButton59ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton59ActionPerformed
pg = maxPages;
page11.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton59ActionPerformed
private void jComboBox32ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox32ActionPerformed
if (jComboBox32.getSelectedItem().equals("")) {
lim = 15;
jComboBox32.setSelectedItem("15");
pg = 1;
page11.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
lim = Integer.parseInt((String) jComboBox32.getSelectedItem());
pg = 1;
page11.setText(Integer.toString(pg));
if (pg == 0) {
offset = (pg) * lim;
} else {
offset = (pg - 1) * lim;
}
try {
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jComboBox32ActionPerformed
private void search9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_search9MouseClicked
search9.setText(null);
}//GEN-LAST:event_search9MouseClicked
private void search9CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_search9CaretUpdate
String sh = search9.getText();
if (sh.equals("")) {
try {
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try {
addProcessTable("SELECT * FROM finish WHERE Tag_No like '%" + sh + "%' or Date like '%" + sh + "%' or Time like '%" + sh + "%' or Emp_No like '%" + sh + "%'", jTable18);
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_search9CaretUpdate
private void BW_tagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BW_tagActionPerformed
BW_tag.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
BW_err.setText(null);
}//GEN-LAST:event_BW_tagActionPerformed
private void Fin_tagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Fin_tagActionPerformed
Fin_tag.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Fin_err.setText(null);
}//GEN-LAST:event_Fin_tagActionPerformed
private void BWQCchk4addmanuallyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BWQCchk4addmanuallyActionPerformed
try {
if (TableValidate(BW_tag, BW_emp, BW_err)) {
int tag = Integer.parseInt(String.valueOf(BW_tag.getSelectedItem()));
String emp = String.valueOf(BW_emp.getSelectedItem());
String date = BW_date.getText();
String time = BW_time.getText();
String col = "bwqc";
String dep = "bwqc";
try {
if (processchk(tag, col, dep)) {
con.prepareStatement("INSERT INTO bwqc (Tag_No,Date,Time,Emp_No) VALUES(" + tag + ",'" + date + "','" + time + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "BWQC Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
BW_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN bwqc b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
BW_tag.addItem(rs.getString("Tag_No"));
}
BW_tag.setSelectedIndex(-1);
BW_emp.setSelectedIndex(-1);
updateMax("SELECT COUNT(*) AS count FROM bwqc", total4, page4);
addProcessTable("SELECT * FROM bwqc LIMIT " + lim + " OFFSET " + offset + "", jTable5);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_BWQCchk4addmanuallyActionPerformed
private void add_chem_man_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_chem_man_addActionPerformed
try {
if (TableValidate(Chem_tag, Chem_emp, Chem_err)) {
int tag = Integer.parseInt(String.valueOf(Chem_tag.getSelectedItem()));
String emp = String.valueOf(Chem_emp.getSelectedItem());
String date = Chem_date.getText();
String time = Chem_time.getText();
String col = "chemicals";
String dep = "chemicals";
try {
if (processchk(tag, col, dep)) {
con.prepareStatement("INSERT INTO chemicals (Tag_No,Date,Time,Emp_No) VALUES(" + tag + ",'" + date + "','" + time + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "chemicals Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
Chem_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN chemicals b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Chem_tag.addItem(rs.getString("Tag_No"));
}
Chem_tag.setSelectedIndex(-1);
Chem_emp.setSelectedIndex(-1);
updateMax("SELECT COUNT(*) AS count FROM chemicals", total5, page5);
addProcessTable("SELECT * FROM chemicals LIMIT " + lim + " OFFSET " + offset + "", jTable6);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_add_chem_man_addActionPerformed
private void Add_wash_manu_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Add_wash_manu_addActionPerformed
try {
if (TableValidate(Wash_tag, Wash_emp, Wash_err)) {
int tag = Integer.parseInt(String.valueOf(Wash_tag.getSelectedItem()));
String emp = String.valueOf(Wash_emp.getSelectedItem());
String date = Wash_date.getText();
String time = Wash_time.getText();
String col = "wash";
String dep = "wash";
try {
if (processchk(tag, col, dep)) {
con.prepareStatement("INSERT INTO wash (Tag_No,Date,Time,Emp_No) VALUES(" + tag + ",'" + date + "','" + time + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "wash Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
Wash_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN wash b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Wash_tag.addItem(rs.getString("Tag_No"));
}
Wash_tag.setSelectedIndex(-1);
Wash_emp.setSelectedIndex(-1);
updateMax("SELECT COUNT(*) AS count FROM wash", total6, page6);
addProcessTable("SELECT * FROM wash LIMIT " + lim + " OFFSET " + offset + "", jTable13);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_Add_wash_manu_addActionPerformed
private void add_hydro_manu_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_hydro_manu_addActionPerformed
try {
if (TableValidate(Hydro_tag, Hydro_emp, Hydro_err)) {
int tag = Integer.parseInt(String.valueOf(Hydro_tag.getSelectedItem()));
String emp = String.valueOf(Hydro_emp.getSelectedItem());
String date = Hydro_date.getText();
String time = Hydro_time.getText();
String col = "hydro";
String dep = "hydro";
try {
if (processchk(tag, col, dep)) {
con.prepareStatement("INSERT INTO hydro (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + date + "','" + time + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "hydro Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
Hydro_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN hydro b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Hydro_tag.addItem(rs.getString("Tag_No"));
}
Hydro_tag.setSelectedIndex(-1);
Hydro_emp.setSelectedIndex(-1);
updateMax("SELECT COUNT(*) AS count FROM hydro", total7, page7);
addProcessTable("SELECT * FROM hydro LIMIT " + lim + " OFFSET " + offset + "", jTable14);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_add_hydro_manu_addActionPerformed
private void Wet_addManActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Wet_addManActionPerformed
try {
if (TableValidate(Wet_tag, Wet_emp, Wet_err)) {
int tag = Integer.parseInt(String.valueOf(Wet_tag.getSelectedItem()));
String emp = String.valueOf(Wet_emp.getSelectedItem());
String date = Wet_date.getText();
String time = Wet_time.getText();
String col = "wetqc";
String dep = "wetqc";
try {
if (processchk(tag, col, dep)) {
con.prepareStatement("INSERT INTO wetqc (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + date + "','" + time + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "wetQC Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
Wet_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN wetqc b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Wet_tag.addItem(rs.getString("Tag_No"));
}
Wet_tag.setSelectedIndex(-1);
Wet_emp.setSelectedIndex(-1);
updateMax("SELECT COUNT(*) AS count FROM wetqc", total8, page8);
addProcessTable("SELECT * FROM wetqc LIMIT " + lim + " OFFSET " + offset + "", jTable15);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_Wet_addManActionPerformed
private void add_dry_manu_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_dry_manu_addActionPerformed
try {
if (DryValidate()) {
int tag = Integer.parseInt(String.valueOf(Dry_tag.getSelectedItem()));
String emp = String.valueOf(Dry_emp.getSelectedItem());
String mah = String.valueOf(Dry_mah.getSelectedItem());
String date = Dry_date.getText();
String time = Dry_time.getText();
String col = "dry";
String dep = "dry";
try {
if (processchk(tag, col, dep)) {
con.prepareStatement("INSERT INTO dry (Tag_No,Machine_No,Date,Time,Emp_No) VALUES('" + tag + "','" + mah + "','" + date + "','" + time + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "dry Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
Dry_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN dry b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Dry_tag.addItem(rs.getString("Tag_No"));
}
Dry_tag.setSelectedIndex(-1);
Dry_emp.setSelectedIndex(-1);
updateMax("SELECT COUNT(*) AS count FROM dry", total9, page9);
addProcessTable("SELECT * FROM dry LIMIT " + lim + " OFFSET " + offset + "", jTable16);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_add_dry_manu_addActionPerformed
private void AWQCchk15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AWQCchk15ActionPerformed
try {
if (TableValidate(AW_tag, AW_emp, AW_err)) {
int tag = Integer.parseInt(String.valueOf(AW_tag.getSelectedItem()));
String emp = String.valueOf(AW_emp.getSelectedItem());
String date = AW_date.getText();
String time = AW_time.getText();
String col = "awqc";
String dep = "awqc";
try {
if (processchk(tag, col, dep)) {
con.prepareStatement("INSERT INTO awqc (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + date + "','" + time + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "AWQC Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
AW_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN awqc b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
AW_tag.addItem(rs.getString("Tag_No"));
}
AW_tag.setSelectedIndex(-1);
AW_emp.setSelectedIndex(-1);
updateMax("SELECT COUNT(*) AS count FROM awqc", total10, page10);
addProcessTable("SELECT * FROM awqc LIMIT " + lim + " OFFSET " + offset + "", jTable17);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_AWQCchk15ActionPerformed
private void Finish1add1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Finish1add1ActionPerformed
try {
if (TableValidate(Fin_tag, Fin_emp, Fin_err)) {
int tag = Integer.parseInt(String.valueOf(Fin_tag.getSelectedItem()));
String blp;
String emp = String.valueOf(Fin_emp.getSelectedItem());
String date = Fin_date.getText();
String time = Fin_time.getText();
String col = "finish";
String dep = "finish";
try {
if (processchk(tag, col, dep)) {
con.prepareStatement("INSERT INTO finish (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + date + "','" + time + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "Finish Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
Fin_tag.removeAllItems();
ResultSet rs = con.createStatement().executeQuery("SELECT t.Tag_No FROM tag t LEFT JOIN finish b ON t.Tag_No = b.Tag_No WHERE t.Tag_Status ='Printed' AND b.Tag_No IS NULL");
while (rs.next()) {
Fin_tag.addItem(rs.getString("Tag_No"));
}
Fin_tag.setSelectedIndex(-1);
Fin_emp.setSelectedIndex(-1);
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
ResultSet rs1 = con.createStatement().executeQuery("SELECT BLP_No FROM tag WHERE Tag_No = " + tag + "");
rs1.next();
blp = rs1.getString("BLP_No");
con.prepareStatement("UPDATE processplan SET Finished = 1 WHERE BLP_No = '" + blp + "'");
pro.updateMax("SELECT COUNT(*) AS count FROM processplan", pro.total1, pro.page1);
pro.addPProTable("SELECT * FROM processplan LIMIT " + lim + " OFFSET " + offset + "");
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_Finish1add1ActionPerformed
private void BWQCchk3addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BWQCchk3addActionPerformed
String tag = BW_ctag.getText();
String emp = BW_cemp.getText();
try {
if (AutoValidate(BW_ctag, BW_cemp, BW_err)) {
con.prepareStatement("INSERT INTO bwqc (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + java.time.LocalDate.now() + "','" + java.time.LocalTime.now() + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "BWQC Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
updateMax("SELECT COUNT(*) AS count FROM finish", total4, page4);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable5);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
BW_ctag.setText(null);
BW_cemp.setText(null);
}//GEN-LAST:event_BWQCchk3addActionPerformed
private void add_che_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_che_addActionPerformed
String tag = Chem_ctag.getText();
String emp = Chem_cemp.getText();
try {
if (AutoValidate(Chem_ctag, Chem_cemp, Chem_err)) {
con.prepareStatement("INSERT INTO chemicals (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + java.time.LocalDate.now() + "','" + java.time.LocalTime.now() + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "CHEMICALS Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
updateMax("SELECT COUNT(*) AS count FROM finish", total5, page5);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable6);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Chem_ctag.setText(null);
Chem_cemp.setText(null);
}//GEN-LAST:event_add_che_addActionPerformed
private void add_wash_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_wash_addActionPerformed
String tag = Wash_ctag.getText();
String emp = Wash_cemp.getText();
try {
if (AutoValidate(Wash_ctag, Wash_cemp, Wash_err)) {
con.prepareStatement("INSERT INTO wash (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + java.time.LocalDate.now() + "','" + java.time.LocalTime.now() + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "WASH Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
updateMax("SELECT COUNT(*) AS count FROM finish", total6, page6);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable13);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Wash_ctag.setText(null);
Wash_cemp.setText(null);
}//GEN-LAST:event_add_wash_addActionPerformed
private void add_hydro_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_hydro_addActionPerformed
String tag = Hydro_ctag.getText();
String emp = Hydro_cemp.getText();
try {
if (AutoValidate(Hydro_ctag, Hydro_cemp, Hydro_err)) {
con.prepareStatement("INSERT INTO hydro (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + java.time.LocalDate.now() + "','" + java.time.LocalTime.now() + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "HYDRO Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
updateMax("SELECT COUNT(*) AS count FROM finish", total7, page7);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable14);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Hydro_ctag.setText(null);
Hydro_cemp.setText(null);
}//GEN-LAST:event_add_hydro_addActionPerformed
private void Wet_cAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Wet_cAddActionPerformed
String tag = Wet_ctag.getText();
String emp = Wet_cemp.getText();
try {
if (AutoValidate(Wet_ctag, Wet_cemp, Wet_err)) {
con.prepareStatement("INSERT INTO wetqc (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + java.time.LocalDate.now() + "','" + java.time.LocalTime.now() + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "WETQC Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
updateMax("SELECT COUNT(*) AS count FROM finish", total8, page8);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable15);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Wet_ctag.setText(null);
Wet_cemp.setText(null);
}//GEN-LAST:event_Wet_cAddActionPerformed
private void add_dry_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_dry_addActionPerformed
String tag = Dry_ctag.getText();
String emp = Dry_cemp.getText();
String mah = String.valueOf(Dry_cmah.getSelectedItem());
try {
if (AutoDryValidate(Dry_ctag, Dry_cemp, Dry_cmah)) {
con.prepareStatement("INSERT INTO dry (Tag_No,Machine_No,Date,Time,Emp_No) VALUES('" + tag + "','" + mah + "','" + java.time.LocalDate.now() + "','" + java.time.LocalTime.now() + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "DRY Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
updateMax("SELECT COUNT(*) AS count FROM finish", total9, page9);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable16);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Dry_ctag.setText(null);
Dry_cemp.setText(null);
}//GEN-LAST:event_add_dry_addActionPerformed
private void AWQC1chkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AWQC1chkActionPerformed
String tag = AW_ctag.getText();
String emp = AW_cemp.getText();
try {
if (AutoValidate(AW_ctag, AW_cemp, AW_err)) {
con.prepareStatement("INSERT INTO awqc (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + java.time.LocalDate.now() + "','" + java.time.LocalTime.now() + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "AWQC Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
updateMax("SELECT COUNT(*) AS count FROM finish", total10, page10);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable17);
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
AW_ctag.setText(null);
AW_cemp.setText(null);
}//GEN-LAST:event_AWQC1chkActionPerformed
private void Finish1addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Finish1addActionPerformed
String tag = Fin_ctag.getText();
String emp = Fin_cemp.getText();
try {
if (AutoValidate(Fin_ctag, Fin_cemp, Fin_err)) {
con.prepareStatement("INSERT INTO finish (Tag_No,Date,Time,Emp_No) VALUES('" + tag + "','" + java.time.LocalDate.now() + "','" + java.time.LocalTime.now() + "','" + emp + "')").execute();
JOptionPane.showMessageDialog(null, "FINISH Updated", "Done", JOptionPane.INFORMATION_MESSAGE);
updateMax("SELECT COUNT(*) AS count FROM finish", total11, page11);
addProcessTable("SELECT * FROM finish LIMIT " + lim + " OFFSET " + offset + "", jTable18);
con.prepareStatement("UPDATE processplan SET Finished = 1 WHERE BLP_No = '" + tag + "'");
pro.updateMax("SELECT COUNT(*) AS count FROM processplan", pro.total1, pro.page1);
pro.addPProTable("SELECT * FROM processplan LIMIT " + lim + " OFFSET " + offset + "");
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
Fin_ctag.setText(null);
Fin_cemp.setText(null);
}//GEN-LAST:event_Finish1addActionPerformed
private void Dry_cmahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Dry_cmahActionPerformed
Dry_cmah.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Dry_err.setText(null);
}//GEN-LAST:event_Dry_cmahActionPerformed
private void BW_empActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BW_empActionPerformed
BW_emp.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
BW_err.setText(null);
}//GEN-LAST:event_BW_empActionPerformed
private void Chem_tagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Chem_tagActionPerformed
Chem_tag.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Chem_err.setText(null);
}//GEN-LAST:event_Chem_tagActionPerformed
private void Chem_empActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Chem_empActionPerformed
Chem_emp.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Chem_err.setText(null);
}//GEN-LAST:event_Chem_empActionPerformed
private void Wash_tagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Wash_tagActionPerformed
Wash_tag.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Wash_err.setText(null);
}//GEN-LAST:event_Wash_tagActionPerformed
private void Wash_empActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Wash_empActionPerformed
Wash_emp.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Wash_err.setText(null);
}//GEN-LAST:event_Wash_empActionPerformed
private void Hydro_tagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Hydro_tagActionPerformed
Hydro_tag.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Hydro_err.setText(null);
}//GEN-LAST:event_Hydro_tagActionPerformed
private void Hydro_empActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Hydro_empActionPerformed
Hydro_emp.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Hydro_err.setText(null);
}//GEN-LAST:event_Hydro_empActionPerformed
private void Wet_tagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Wet_tagActionPerformed
Wet_tag.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Wet_err.setText(null);
}//GEN-LAST:event_Wet_tagActionPerformed
private void Wet_empActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Wet_empActionPerformed
Wet_emp.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Wet_err.setText(null);
}//GEN-LAST:event_Wet_empActionPerformed
private void Dry_tagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Dry_tagActionPerformed
Dry_tag.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Dry_err.setText(null);
}//GEN-LAST:event_Dry_tagActionPerformed
private void Dry_empActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Dry_empActionPerformed
Dry_emp.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Dry_err.setText(null);
}//GEN-LAST:event_Dry_empActionPerformed
private void Dry_mahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Dry_mahActionPerformed
Dry_mah.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Dry_err.setText(null);
}//GEN-LAST:event_Dry_mahActionPerformed
private void AW_tagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AW_tagActionPerformed
AW_tag.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
AW_err.setText(null);
}//GEN-LAST:event_AW_tagActionPerformed
private void AW_empActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AW_empActionPerformed
AW_emp.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
AW_err.setText(null);
}//GEN-LAST:event_AW_empActionPerformed
private void Fin_empActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Fin_empActionPerformed
Fin_emp.setBorder(BorderFactory.createLineBorder(Color.decode("#ffffff")));
Fin_err.setText(null);
}//GEN-LAST:event_Fin_empActionPerformed
private void BW_ctagFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_BW_ctagFocusGained
BW_ctag.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
BW_err.setText(null);
}//GEN-LAST:event_BW_ctagFocusGained
private void BW_cempFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_BW_cempFocusGained
BW_cemp.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
BW_err.setText(null);
}//GEN-LAST:event_BW_cempFocusGained
private void Chem_ctagFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Chem_ctagFocusGained
Chem_ctag.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Chem_err.setText(null);
}//GEN-LAST:event_Chem_ctagFocusGained
private void Chem_cempFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Chem_cempFocusGained
Chem_cemp.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Chem_err.setText(null);
}//GEN-LAST:event_Chem_cempFocusGained
private void Wash_ctagFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Wash_ctagFocusGained
Wash_ctag.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Wash_err.setText(null);
}//GEN-LAST:event_Wash_ctagFocusGained
private void Wash_cempFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Wash_cempFocusGained
Wash_cemp.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Wash_err.setText(null);
}//GEN-LAST:event_Wash_cempFocusGained
private void Hydro_ctagFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Hydro_ctagFocusGained
Hydro_ctag.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Hydro_err.setText(null);
}//GEN-LAST:event_Hydro_ctagFocusGained
private void Hydro_cempFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Hydro_cempFocusGained
Hydro_cemp.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Hydro_err.setText(null);
}//GEN-LAST:event_Hydro_cempFocusGained
private void Wet_ctagFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Wet_ctagFocusGained
Wet_ctag.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Wet_err.setText(null);
}//GEN-LAST:event_Wet_ctagFocusGained
private void Wet_cempFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Wet_cempFocusGained
Wet_cemp.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Wet_err.setText(null);
}//GEN-LAST:event_Wet_cempFocusGained
private void Dry_ctagFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Dry_ctagFocusGained
Dry_ctag.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Dry_err.setText(null);
}//GEN-LAST:event_Dry_ctagFocusGained
private void Dry_cempFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Dry_cempFocusGained
Dry_cemp.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Dry_err.setText(null);
}//GEN-LAST:event_Dry_cempFocusGained
private void AW_ctagFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_AW_ctagFocusGained
AW_ctag.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
AW_err.setText(null);
}//GEN-LAST:event_AW_ctagFocusGained
private void AW_cempFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_AW_cempFocusGained
AW_cemp.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
AW_err.setText(null);
}//GEN-LAST:event_AW_cempFocusGained
private void Fin_ctagFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Fin_ctagFocusGained
Fin_ctag.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Fin_err.setText(null);
}//GEN-LAST:event_Fin_ctagFocusGained
private void Fin_cempFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_Fin_cempFocusGained
Fin_cemp.setBorder(BorderFactory.createLineBorder(Color.decode("#a0a0a0")));
Fin_err.setText(null);
}//GEN-LAST:event_Fin_cempFocusGained
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
int po = 0;
String compname = null;
double up = 0;
String style = null;
double tc = 0;
String pk = null;
String email = null;
int r = jTable18.getSelectedRow();
int tag = Integer.parseInt(jTable18.getValueAt(r, 0).toString());
try {
ResultSet r50 = con.createStatement().executeQuery("SELECT BLP_No FROM tag WHERE Tag_No = " + tag);
while (r50.next()) {
pk = r50.getString("BLP_No");
ResultSet r51 = con.createStatement().executeQuery("SELECT * FROM splglove s,poglove p WHERE s.lotNo=p.lotNo AND p.lotNo ='" + pk + "'");
while (r51.next()) {
po = r51.getInt("poNo");
compname = r51.getString("customer");
up = r51.getDouble("unitCost");
style = r51.getString("style");
tc = r51.getDouble("totCost");
}
ResultSet rs = con.createStatement().executeQuery("select email from customer where name='" + compname + "'");
if (rs.next()) {
email = rs.getString(1);
}
}
} catch (SQLException ex) {
Logger.getLogger(process.class.getName()).log(Level.SEVERE, null, ex);
}
/*System.out.println(po);
System.out.println(compname);
System.out.println(up);
System.out.println(style);
System.out.println(tc);
System.out.println(email);*/
int x = JOptionPane.showConfirmDialog(null, "Do you want Send the mail?");
if (x == 0) {
try {
final String username = "<EMAIL>";
final String password = "<PASSWORD>";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = null;
session = session.getInstance(props, new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
try {
javax.mail.Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(email));
message.setSubject("Regarding Request Completion");
message.setContent("<body style=\"background-color:whitesmoke;\"><center><div align='center' style=\"background-color:white; max-width: 600px; padding: 10px\"><center><img src=http://www.prasarawashing.com/images/logo.png alt='Prasara LOGO'></center>"
+ "<br><br>"
+ ""
+ "<center><h1>" + compname.toUpperCase() + "</h1></center>"
+ "<br><font color=\"black\"><center><l>Thank you for trusting us in ensuring to make your life much simpler & easier.</l></center>"
+ "<br><br> <h4 align='left'><u>ORDER DETAILS :- Tag Number=" + pk + "</u><h4>"
+ "<br> <div align='center' padding><table align='center' cellpadding='25'>"
+ "<tr>"
+ " <th><b>Reference</b></th>"
+ " <th><b>Product</b></th>"
+ " <th><b>Unit Price</b></th>"
+ " <th><b>Quantity</b></th>"
+ " <th><b>Total Price</b></th>"
+ "</tr>"
+ "<tr>"
+ " <td>" + po + "</td>"
+ " <td>" + style + "</td>"
+ " <td>" + up + "</td>"
+ " <td>" + tc / up + "</td>"
+ " <td>" + tc + "</td>"
+ "</tr>"
+ "</table></div>"
+ "<br><div align='right' style=\"line-height: 2;\"> <b>Total Amount(Rs):</b> " + tc
+ "<br><b>Discounts(Rs):</b> " + "0.00"
+ "<br><b>Total Tax(Rs):</b> " + "0%"
+ "<br><b>Total Paid(Rs):</b> " + "0.00</div>"
+ "<br><br>"
+ "<div align='center'>If any details with regards to the above report is concerning, please contact us.</div><br><br>"
+ "<br><br>"
+ "<div align='left' style=\"line-height: 1.5;\">Thank you! <br>Product Management Division<br>PRASARA WASHING PLANT</font></div>"
+ "<br><footer><font color=\"black\">+94 31 4927863 / 0714 904 740 <br> <EMAIL>, <EMAIL><br>Prasara Washing Plant Dankotuwa (Pvt) Ltd. Negombo Road, Thabarawila, Waikkala.</font></footer></body></center></div>", "text/html");
Transport.send(message);
//System.out.println("Email sent");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
JOptionPane.showMessageDialog(null, " Email has ben sent!");
} catch (Exception e) {
e.printStackTrace();
}
} else if (x == 1) {
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jScrollPane12MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane12MouseClicked
// TODO add your handling code here:
/*String s = (String) jTable18.getValueAt(jTable18.getSelectedRow(), 0);
if (s != null && !s.trim().equals("")) {
jButton1.setVisible(true);
}*/
}//GEN-LAST:event_jScrollPane12MouseClicked
private void FinishMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_FinishMouseClicked
// TODO add your handling code here:
jButton1.setVisible(false);
}//GEN-LAST:event_FinishMouseClicked
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
Home.Report(jTable5, "Before Wash Quality Check Details", "E:\\Reports\\BWQC.pdf");
}//GEN-LAST:event_jButton12ActionPerformed
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
Home.Report(jTable6, "Chemical Wash Details", "E:\\Reports\\chem.pdf");
}//GEN-LAST:event_jButton13ActionPerformed
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed
Home.Report(jTable13, "Washing Details", "E:\\Reports\\wash.pdf");
}//GEN-LAST:event_jButton14ActionPerformed
private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15ActionPerformed
Home.Report(jTable14, "Hydro Washing Details", "E:\\Reports\\hydro.pdf");
}//GEN-LAST:event_jButton15ActionPerformed
private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton16ActionPerformed
Home.Report(jTable15, "Wet Quality Check Details", "E:\\Reports\\WetQC.pdf");
}//GEN-LAST:event_jButton16ActionPerformed
private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton17ActionPerformed
Home.Report(jTable16, "Drying Details", "E:\\Reports\\dry.pdf");
}//GEN-LAST:event_jButton17ActionPerformed
private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton18ActionPerformed
Home.Report(jTable17, "After Wash quality Check Details", "E:\\Reports\\AWQC.pdf");
}//GEN-LAST:event_jButton18ActionPerformed
private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton19ActionPerformed
Home.Report(jTable18, "Finished Washing Details", "E:\\Reports\\finish.pdf");
}//GEN-LAST:event_jButton19ActionPerformed
private void jTable18MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable18MouseClicked
// TODO add your handling code here:
String s = (String) jTable18.getValueAt(jTable18.getSelectedRow(), 0);
if (s != null && !s.trim().equals("")) {
jButton1.setVisible(true);
}
}//GEN-LAST:event_jTable18MouseClicked
private void jTable18MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable18MouseEntered
// TODO add your handling code here:
}//GEN-LAST:event_jTable18MouseEntered
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel AWQC;
private javax.swing.JPanel AWQC1;
private javax.swing.JButton AWQC1Back;
private javax.swing.JButton AWQC1chk;
private javax.swing.JButton AWQCBack;
private javax.swing.JButton AWQCButton;
private javax.swing.JButton AWQCchk;
private javax.swing.JButton AWQCchk15;
private javax.swing.JTextField AW_cemp;
private javax.swing.JTextField AW_ctag;
private javax.swing.JTextField AW_date;
private javax.swing.JComboBox<String> AW_emp;
private javax.swing.JLabel AW_err;
private javax.swing.JComboBox<String> AW_tag;
private javax.swing.JTextField AW_time;
private javax.swing.JButton Add_wash_manu_add;
private javax.swing.JPanel BWQC;
private javax.swing.JPanel BWQC1;
private javax.swing.JButton BWQCBack;
private javax.swing.JButton BWQCBack1;
private javax.swing.JButton BWQCButton;
private javax.swing.JButton BWQCchk;
private javax.swing.JButton BWQCchk3add;
private javax.swing.JButton BWQCchk4addmanually;
private javax.swing.JTextField BW_cemp;
private javax.swing.JTextField BW_ctag;
private javax.swing.JTextField BW_date;
private javax.swing.JComboBox<String> BW_emp;
private javax.swing.JLabel BW_err;
private javax.swing.JComboBox<String> BW_tag;
private javax.swing.JTextField BW_time;
private javax.swing.JLabel Background;
private javax.swing.JPanel Chem;
private javax.swing.JPanel Chem1;
private javax.swing.JButton ChemBack;
private javax.swing.JTextField Chem_cemp;
private javax.swing.JTextField Chem_ctag;
private javax.swing.JTextField Chem_date;
private javax.swing.JComboBox<String> Chem_emp;
private javax.swing.JLabel Chem_err;
private javax.swing.JComboBox<String> Chem_tag;
private javax.swing.JTextField Chem_time;
private javax.swing.JButton ChemicalsButton;
private javax.swing.JPanel Dry;
private javax.swing.JPanel Dry1;
private javax.swing.JButton DryBack;
private javax.swing.JTextField Dry_cemp;
private javax.swing.JComboBox<String> Dry_cmah;
private javax.swing.JTextField Dry_ctag;
private javax.swing.JTextField Dry_date;
private javax.swing.JComboBox<String> Dry_emp;
private javax.swing.JLabel Dry_err;
private javax.swing.JComboBox<String> Dry_mah;
private javax.swing.JComboBox<String> Dry_tag;
private javax.swing.JTextField Dry_time;
private javax.swing.JButton Drychk;
private javax.swing.JButton DryingButton;
private javax.swing.JButton FinBack;
private javax.swing.JTextField Fin_cemp;
private javax.swing.JTextField Fin_ctag;
private javax.swing.JTextField Fin_date;
private javax.swing.JComboBox<String> Fin_emp;
private javax.swing.JLabel Fin_err;
private javax.swing.JComboBox<String> Fin_tag;
private javax.swing.JTextField Fin_time;
private javax.swing.JButton Finchk;
private javax.swing.JPanel Finish;
private javax.swing.JPanel Finish1;
private javax.swing.JButton Finish1add;
private javax.swing.JButton Finish1add1;
private javax.swing.JButton Finish1back;
private javax.swing.JButton FinishingButton;
private javax.swing.JPanel Hyd;
private javax.swing.JPanel Hyd1;
private javax.swing.JButton HydBack;
private javax.swing.JButton HydroButton;
private javax.swing.JTextField Hydro_cemp;
private javax.swing.JTextField Hydro_ctag;
private javax.swing.JTextField Hydro_date;
private javax.swing.JComboBox<String> Hydro_emp;
private javax.swing.JLabel Hydro_err;
private javax.swing.JComboBox<String> Hydro_tag;
private javax.swing.JTextField Hydro_time;
private javax.swing.JButton Hydrochk;
private javax.swing.JPanel Production;
private javax.swing.JPanel Wash;
private javax.swing.JPanel Wash1;
private javax.swing.JButton WashBack;
private javax.swing.JTextField Wash_cemp;
private javax.swing.JTextField Wash_ctag;
private javax.swing.JTextField Wash_date;
private javax.swing.JComboBox<String> Wash_emp;
private javax.swing.JLabel Wash_err;
private javax.swing.JComboBox<String> Wash_tag;
private javax.swing.JTextField Wash_time;
private javax.swing.JButton Washchk;
private javax.swing.JButton WashingButton;
private javax.swing.JPanel WetQC;
private javax.swing.JPanel WetQC1;
private javax.swing.JButton WetQCBack;
private javax.swing.JButton WetQCButton;
private javax.swing.JButton WetQCchk;
private javax.swing.JButton Wet_addMan;
private javax.swing.JButton Wet_cAdd;
private javax.swing.JTextField Wet_cemp;
private javax.swing.JTextField Wet_ctag;
private javax.swing.JTextField Wet_date;
private javax.swing.JComboBox<String> Wet_emp;
private javax.swing.JLabel Wet_err;
private javax.swing.JComboBox<String> Wet_tag;
private javax.swing.JTextField Wet_time;
private javax.swing.JButton add_che_add;
private javax.swing.JButton add_chem_man_add;
private javax.swing.JButton add_dry_add;
private javax.swing.JButton add_dry_back;
private javax.swing.JButton add_dry_manu_add;
private javax.swing.JButton add_hydro_add;
private javax.swing.JButton add_hydro_back;
private javax.swing.JButton add_hydro_manu_add;
private javax.swing.JButton add_wash_add;
private javax.swing.JButton add_wash_back;
private javax.swing.JButton addchemback;
private javax.swing.JButton cheak_wet_qc_back;
private javax.swing.JButton chem_check;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton18;
private javax.swing.JButton jButton19;
private javax.swing.JButton jButton23;
private javax.swing.JButton jButton24;
private javax.swing.JButton jButton29;
private javax.swing.JButton jButton30;
private javax.swing.JButton jButton31;
private javax.swing.JButton jButton33;
private javax.swing.JButton jButton34;
private javax.swing.JButton jButton35;
private javax.swing.JButton jButton36;
private javax.swing.JButton jButton37;
private javax.swing.JButton jButton38;
private javax.swing.JButton jButton39;
private javax.swing.JButton jButton40;
private javax.swing.JButton jButton41;
private javax.swing.JButton jButton42;
private javax.swing.JButton jButton43;
private javax.swing.JButton jButton44;
private javax.swing.JButton jButton45;
private javax.swing.JButton jButton46;
private javax.swing.JButton jButton47;
private javax.swing.JButton jButton48;
private javax.swing.JButton jButton49;
private javax.swing.JButton jButton50;
private javax.swing.JButton jButton51;
private javax.swing.JButton jButton52;
private javax.swing.JButton jButton53;
private javax.swing.JButton jButton54;
private javax.swing.JButton jButton55;
private javax.swing.JButton jButton56;
private javax.swing.JButton jButton57;
private javax.swing.JButton jButton58;
private javax.swing.JButton jButton59;
private javax.swing.JComboBox<String> jComboBox25;
private javax.swing.JComboBox<String> jComboBox26;
private javax.swing.JComboBox<String> jComboBox27;
private javax.swing.JComboBox<String> jComboBox28;
private javax.swing.JComboBox<String> jComboBox29;
private javax.swing.JComboBox<String> jComboBox30;
private javax.swing.JComboBox<String> jComboBox31;
private javax.swing.JComboBox<String> jComboBox32;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel100;
private javax.swing.JLabel jLabel101;
private javax.swing.JLabel jLabel102;
private javax.swing.JLabel jLabel103;
private javax.swing.JLabel jLabel104;
private javax.swing.JLabel jLabel105;
private javax.swing.JLabel jLabel106;
private javax.swing.JLabel jLabel107;
private javax.swing.JLabel jLabel108;
private javax.swing.JLabel jLabel109;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel110;
private javax.swing.JLabel jLabel111;
private javax.swing.JLabel jLabel112;
private javax.swing.JLabel jLabel113;
private javax.swing.JLabel jLabel114;
private javax.swing.JLabel jLabel115;
private javax.swing.JLabel jLabel116;
private javax.swing.JLabel jLabel117;
private javax.swing.JLabel jLabel118;
private javax.swing.JLabel jLabel119;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel120;
private javax.swing.JLabel jLabel121;
private javax.swing.JLabel jLabel122;
private javax.swing.JLabel jLabel123;
private javax.swing.JLabel jLabel124;
private javax.swing.JLabel jLabel125;
private javax.swing.JLabel jLabel126;
private javax.swing.JLabel jLabel127;
private javax.swing.JLabel jLabel128;
private javax.swing.JLabel jLabel129;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel130;
private javax.swing.JLabel jLabel132;
private javax.swing.JLabel jLabel134;
private javax.swing.JLabel jLabel135;
private javax.swing.JLabel jLabel136;
private javax.swing.JLabel jLabel137;
private javax.swing.JLabel jLabel138;
private javax.swing.JLabel jLabel139;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel140;
private javax.swing.JLabel jLabel141;
private javax.swing.JLabel jLabel142;
private javax.swing.JLabel jLabel149;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel150;
private javax.swing.JLabel jLabel151;
private javax.swing.JLabel jLabel152;
private javax.swing.JLabel jLabel153;
private javax.swing.JLabel jLabel154;
private javax.swing.JLabel jLabel155;
private javax.swing.JLabel jLabel156;
private javax.swing.JLabel jLabel157;
private javax.swing.JLabel jLabel158;
private javax.swing.JLabel jLabel159;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel160;
private javax.swing.JLabel jLabel161;
private javax.swing.JLabel jLabel167;
private javax.swing.JLabel jLabel168;
private javax.swing.JLabel jLabel169;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel170;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel37;
private javax.swing.JLabel jLabel39;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel43;
private javax.swing.JLabel jLabel45;
private javax.swing.JLabel jLabel46;
private javax.swing.JLabel jLabel48;
private javax.swing.JLabel jLabel49;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel52;
private javax.swing.JLabel jLabel56;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel68;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel71;
private javax.swing.JLabel jLabel72;
private javax.swing.JLabel jLabel73;
private javax.swing.JLabel jLabel74;
private javax.swing.JLabel jLabel75;
private javax.swing.JLabel jLabel76;
private javax.swing.JLabel jLabel77;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel87;
private javax.swing.JLabel jLabel88;
private javax.swing.JLabel jLabel9;
private javax.swing.JLabel jLabel93;
private javax.swing.JLabel jLabel94;
private javax.swing.JLabel jLabel95;
private javax.swing.JLabel jLabel96;
private javax.swing.JLabel jLabel97;
private javax.swing.JLabel jLabel98;
private javax.swing.JLabel jLabel99;
private javax.swing.JLayeredPane jLayeredPane1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane10;
private javax.swing.JScrollPane jScrollPane11;
private javax.swing.JScrollPane jScrollPane12;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JScrollPane jScrollPane9;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator13;
private javax.swing.JSeparator jSeparator14;
private javax.swing.JSeparator jSeparator15;
private javax.swing.JSeparator jSeparator16;
private javax.swing.JSeparator jSeparator17;
private javax.swing.JSeparator jSeparator18;
private javax.swing.JSeparator jSeparator19;
private javax.swing.JSeparator jSeparator20;
private javax.swing.JSeparator jSeparator21;
private javax.swing.JSeparator jSeparator23;
private javax.swing.JSeparator jSeparator25;
private javax.swing.JSeparator jSeparator29;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator33;
private javax.swing.JSeparator jSeparator37;
private javax.swing.JSeparator jSeparator38;
private javax.swing.JSeparator jSeparator41;
private javax.swing.JSeparator jSeparator45;
private javax.swing.JSeparator jSeparator47;
private javax.swing.JTable jTable13;
private javax.swing.JTable jTable14;
private javax.swing.JTable jTable15;
private javax.swing.JTable jTable16;
private javax.swing.JTable jTable17;
private javax.swing.JTable jTable18;
private javax.swing.JTable jTable5;
private javax.swing.JTable jTable6;
private javax.swing.JTextField page10;
private javax.swing.JTextField page11;
private javax.swing.JTextField page4;
private javax.swing.JTextField page5;
private javax.swing.JTextField page6;
private javax.swing.JTextField page7;
private javax.swing.JTextField page8;
private javax.swing.JTextField page9;
private javax.swing.JTextField search10;
private javax.swing.JTextField search11;
private javax.swing.JTextField search12;
private javax.swing.JTextField search13;
private javax.swing.JTextField search2;
private javax.swing.JTextField search3;
private javax.swing.JTextField search4;
private javax.swing.JTextField search5;
private javax.swing.JTextField search6;
private javax.swing.JTextField search7;
private javax.swing.JTextField search8;
private javax.swing.JTextField search9;
private javax.swing.JLabel total10;
private javax.swing.JLabel total11;
private javax.swing.JLabel total4;
private javax.swing.JLabel total5;
private javax.swing.JLabel total6;
private javax.swing.JLabel total7;
private javax.swing.JLabel total8;
private javax.swing.JLabel total9;
// End of variables declaration//GEN-END:variables
}
|
afterloe/opencv-practice
|
deep_learning/handwritten_digits/office.py
|
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml
from sklearn.neural_network import MLPClassifier
print(__doc__)
# Load data from https://www.openml.org/d/554
X, y = fetch_openml('mnist_784', version=1, return_X_y=True)
X = X / 255.
# rescale the data, use the traditional train/test split
X_train, X_test = X[:60000], X[60000:]
y_train, y_test = y[:60000], y[60000:]
mlp = MLPClassifier(hidden_layer_sizes=(50,), max_iter=10, alpha=1e-4,
solver='sgd', verbose=10, random_state=1,
learning_rate_init=.1)
mlp.fit(X_train, y_train)
print("Training set score: %f" % mlp.score(X_train, y_train))
print("Test set score: %f" % mlp.score(X_test, y_test))
fig, axes = plt.subplots(4, 4)
# use global min / max to ensure all weights are shown on the same scale
vmin, vmax = mlp.coefs_[0].min(), mlp.coefs_[0].max()
for coef, ax in zip(mlp.coefs_[0].T, axes.ravel()):
ax.matshow(coef.reshape(28, 28), cmap=plt.cm.gray, vmin=.5 * vmin,
vmax=.5 * vmax)
ax.set_xticks(())
ax.set_yticks(())
plt.show()
|
cartolab-gis/elements
|
src/components/Measure/Measure.test.js
|
import React from 'react';
import {
render,
fireEvent,
wait,
waitForElement
} from '@testing-library/react';
import Measure from './Measure';
import ElementsProvider from '../_common/ElementsProvider';
import mockMapContext from '../../util/mockMapContext';
jest.mock('@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw', () =>
jest.fn(() => ({
changeMode: () => jest.fn(),
getAll: () => jest.fn(),
deleteAll: () => jest.fn()
}))
);
describe('Measure component', () => {
it('renders without error', () => {
const { container, getByText, getByTitle } = render(
<ElementsProvider mapOverride={mockMapContext}>
<Measure />
</ElementsProvider>
);
expect(container.firstChild).toBeInTheDocument();
expect(getByText('Measure')).toBeInTheDocument();
expect(getByTitle('Measure Line')).toBeInTheDocument();
expect(getByTitle('Measure Area')).toBeInTheDocument();
});
it('displays measurement options when active (line)', async () => {
const { getByTitle, getByRole } = render(
<ElementsProvider mapOverride={mockMapContext}>
<Measure />
</ElementsProvider>
);
const lineBtn = getByTitle('Measure Line');
fireEvent.click(lineBtn);
const listbox = await waitForElement(() => getByRole('combobox'));
const deleteBtn = await waitForElement(() =>
getByTitle('Delete Measurement')
);
expect(listbox).toBeInTheDocument();
expect(deleteBtn).toBeInTheDocument();
});
it('displays measurement options when active (area)', async () => {
const { getByTitle, getByRole } = render(
<ElementsProvider mapOverride={mockMapContext}>
<Measure />
</ElementsProvider>
);
const areaBtn = getByTitle('Measure Area');
fireEvent.click(areaBtn);
const listbox = await waitForElement(() => getByRole('combobox'));
const deleteBtn = await waitForElement(() =>
getByTitle('Delete Measurement')
);
expect(listbox).toBeInTheDocument();
expect(deleteBtn).toBeInTheDocument();
// expect(getByTitle('Delete Measurement')).toBeVisible();
});
it('hides measurement options when reset is clicked', async () => {
const { getByTitle, queryByRole } = render(
<ElementsProvider mapOverride={mockMapContext}>
<Measure />
</ElementsProvider>
);
const areaBtn = getByTitle('Measure Area');
fireEvent.click(areaBtn);
const resetBtn = await waitForElement(() =>
getByTitle('Delete Measurement')
);
fireEvent.click(resetBtn);
await wait(() => expect(queryByRole('listbox')).toBeNull());
});
});
|
tommyettinger/SquidLib-Demos
|
FormicDemo/core/src/main/java/com/github/tommyettinger/demos/FormicDemo.java
|
package com.github.tommyettinger.demos;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import squidpony.FakeLanguageGen;
import squidpony.squidgrid.gui.gdx.DefaultResources;
import squidpony.squidgrid.gui.gdx.FilterBatch;
import squidpony.squidgrid.gui.gdx.SColor;
import squidpony.squidgrid.gui.gdx.SparseLayers;
import squidpony.squidgrid.gui.gdx.SquidInput;
import squidpony.squidmath.GWTRNG;
import text.formic.Stringf;
import java.util.Date;
/**
* This is a tiny demo that tests various features of Formic ( https://github.com/tommyettinger/formic ),
* a String formatting library for GWT.
*/
public class FormicDemo extends ApplicationAdapter {
// FilterBatch is almost the same as SpriteBatch, but is a bit faster with SquidLib and allows color filtering
private FilterBatch batch;
// a type of random number generator, see below
private GWTRNG rng;
// rendering classes that show only the chars and backgrounds that they've been told to render, unlike some earlier
// classes in SquidLib.
private SparseLayers languageDisplay;
//Here, gridHeight refers to the total number of rows to be displayed on the screen.
//We're displaying 25 rows of dungeon, then 7 more rows of text generation to show some tricks with language.
//gridHeight is 25 because that variable will be used for generating the dungeon (the actual size of the dungeon
//will be triple gridWidth and triple gridHeight), and determines how much off the dungeon is visible at any time.
//The bonusHeight is the number of additional rows that aren't handled like the dungeon rows and are shown in a
//separate area; here we use them for translations. The gridWidth is 90, which means we show 90 grid spaces
//across the whole screen, but the actual dungeon is larger. The cellWidth and cellHeight are 10 and 20, which will
//match the starting dimensions of a cell in pixels, but won't be stuck at that value because we use a "Stretchable"
//font, and so the cells can change size (they don't need to be scaled by equal amounts, either). While gridWidth
//and gridHeight are measured in spaces on the grid, cellWidth and cellHeight are the initial pixel dimensions of
//one cell; resizing the window can make the units cellWidth and cellHeight use smaller or larger than a pixel.
/** In number of cells */
public static final int gridWidth = 120;
/** In number of cells */
public static final int gridHeight = 25;
/** The pixel width of a cell */
public static final int cellWidth = 8;
/** The pixel height of a cell */
public static final int cellHeight = 20;
private SquidInput input;
private Color bgColor;
private Stage languageStage;
private static final float FLOAT_LIGHTING = -0x1.cff1fep126F, // same result as SColor.COSMIC_LATTE.toFloatBits()
GRAY_FLOAT = -0x1.7e7e7ep125F; // same result as SColor.CW_GRAY_BLACK.toFloatBits()
@Override
public void create () {
// gotta have a random number generator. We can seed an RNG with any long we want, or even a String.
// if the seed is identical between two runs, any random factors will also be identical (until user input may
// cause the usage of an RNG to change). You can randomize the dungeon and several other initial settings by
// just removing the String seed, making the line "rng = new GWTRNG();" . Keeping the seed as a default allows
// changes to be more easily reproducible, and using a fixed seed is strongly recommended for tests.
// SquidLib has many methods that expect an IRNG instance, and there's several classes to choose from.
// In this program we'll use GWTRNG, which will behave better on the HTML target than other generators.
rng = new GWTRNG(123456789);
// FilterBatch is exactly like libGDX' SpriteBatch, except it is a fair bit faster when the Batch color is set
// often (which is always true for SquidLib's text-based display), and it allows a FloatFilter to be optionally
// set that can adjust colors in various ways. The FloatFilter here, a YCwCmFilter, can have its adjustments to
// brightness (Y, also called luma), warmth (blue/green vs. red/yellow) and mildness (blue/red vs. green/yellow)
// changed at runtime, and the putMap() method does this. This can be very powerful; you might increase the
// warmth of all colors (additively) if the player is on fire, for instance.
batch = new FilterBatch();
StretchViewport languageViewport = new StretchViewport(gridWidth * cellWidth, gridHeight * cellHeight);
languageViewport.setScreenBounds(0, 0, gridWidth * cellWidth, gridHeight * cellHeight);
languageStage = new Stage(languageViewport, batch);
languageDisplay = new SparseLayers(gridWidth, gridHeight, cellWidth, cellHeight, DefaultResources.getCrispSlabFont());
languageDisplay.defaultPackedBackground = SColor.FLOAT_WHITE;
languageDisplay.setPosition(0f, 0f);
bgColor = SColor.WHITE;
input = new SquidInput(new SquidInput.KeyHandler() {
@Override
public void handle(char key, boolean alt, boolean ctrl, boolean shift) {
switch (key)
{
case 'Q':
case 'q':
case SquidInput.ESCAPE:
{
Gdx.app.exit();
break;
}
default:
{
putMap();
break;
}
}
}
});
//Setting the InputProcessor is ABSOLUTELY NEEDED TO HANDLE INPUT
Gdx.input.setInputProcessor(new InputMultiplexer(languageStage, input));
languageStage.addActor(languageDisplay);
putMap();
}
/**
* Draws the map, applies any highlighting for the path to the cursor, and then draws the player.
*/
public void putMap()
{
languageDisplay.clear(0);
languageDisplay.fillBackground(languageDisplay.defaultPackedBackground);
for (int i = 0; i < gridHeight - 1; i += 2) {
//////////////////////////(dec hex) str (float decsci sci hexfloat)
String s = Stringf.format("%11d %<08X %12s %10.10f %<10.10g %<10.10E %<10.10a",
rng.nextInt(),
FakeLanguageGen.CELESTIAL.word(rng, true, 3),
rng.nextDouble() / (1.0 - rng.nextDouble()));
languageDisplay.put(1, i, s,
rng.getRandomElement(SColor.COLOR_WHEEL_PALETTE_RICH));
s = Stringf.format("%tD %<tT", new Date()); // date and time
languageDisplay.put(1, i+1, s,
rng.getRandomElement(SColor.COLOR_WHEEL_PALETTE_RICH));
}
}
@Override
public void render () {
// standard clear the background routine for libGDX
Gdx.gl.glClearColor(bgColor.r / 255.0f, bgColor.g / 255.0f, bgColor.b / 255.0f, 1.0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if(input.hasNext()) {
input.next();
}
// we need to do some work with viewports here so the language display (or game info messages in a real game)
// will display in the same place even though the map view will move around. We have the language stuff set up
// its viewport so it is in place and won't be altered by the map. Then we just tell the Stage for the language
// texts to draw.
languageStage.getViewport().apply(false);
languageStage.draw();
Gdx.graphics.setTitle("Formic Demo running at FPS: " + Gdx.graphics.getFramesPerSecond());
}
@Override
public void resize(int width, int height) {
super.resize(width, height);
// message box won't respond to clicks on the far right if the stage hasn't been updated with a larger size
float currentZoomX = (float)width / gridWidth;
// total new screen height in pixels divided by total number of rows on the screen
float currentZoomY = (float)height / (gridHeight);
// message box should be given updated bounds since I don't think it will do this automatically
languageDisplay.setBounds(0, 0, width, currentZoomY * gridHeight);
// the viewports are updated separately so each doesn't interfere with the other's drawn area.
languageStage.getViewport().update(width, height, false);
// we also set the bounds of that drawn area here for each viewport.
languageStage.getViewport().setScreenBounds(0, 0, width, height);
}
}
|
yiyenene/yori
|
lib/yori/schema/v3/root.rb
|
# frozen_string_literal: true
module Yori
module Schema
module V3
# Root
module Root
def self.included(klass)
klass.class_eval do
class << self
def api_docs_factory
@_api_docs_factory
end
def api_docs
return unless api_docs_factory
openapi = api_docs_factory.call
openapi.to_json
end
def root(id = '', &block)
@_api_docs_factory = proc do
Yori::Schema::V3::OpenAPI.new.tap do |openapi|
openapi.id = id
openapi.instance_eval(&block)
end
end
end
end
end
end
def api_docs
self.class.api_docs
end
end
end
end
end
|
zarathustra323/omeda
|
packages/api-client/src/entities/deployment/split.js
|
<reponame>zarathustra323/omeda
const build = require('../../schema/utils/build');
const schema = require('../../schema/deployment/split-elements');
class EmailDeploymentSplitEntity {
constructor(obj) {
Object.assign(this, build({ schema, obj }));
}
}
module.exports = EmailDeploymentSplitEntity;
|
RatanMasanta/DataStructure-StudyPlan-Leetcode
|
src/com/masanta/ratan/leetcode/study/plan/data/structure/two/ConvertSortedArrayToBinarySearch.java
|
<filename>src/com/masanta/ratan/leetcode/study/plan/data/structure/two/ConvertSortedArrayToBinarySearch.java
package com.masanta.ratan.leetcode.study.plan.data.structure.two;
public class ConvertSortedArrayToBinarySearch {
/*
* Given an integer array nums where the elements are sorted in ascending order,
* convert it to a height-balanced binary search tree.
*
* A height-balanced binary tree is a binary tree in which the depth of the two
* subtrees of every node never differs by more than one.
*/
public static void main(String[] args) {
int[] nums = new int[] {1,2,3,4,5,6,7,8,9};
TreeNode resultantTree = sortedArrayToBST(nums);
System.out.println("Done");
}
public static TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0) {
return null;
}
return helper(nums,0,nums.length-1);
}
public static TreeNode helper(int[] nums, int start, int end) {
// base case
if(start > end)
return null;
if(start == end)
return new TreeNode(nums[start]);
// Recursive case
int mid = start + (end-start)/2;
TreeNode rootNode = new TreeNode(nums[mid]);
rootNode.left = helper(nums,start,mid-1);
rootNode.right = helper(nums,mid+1,end);
return rootNode;
}
}
|
qwo/6to5
|
test/fixtures/transformation/es6-modules-common/.disallow-import-remapping-9/actual.js
|
import { foo as bar } from "foo";
import { foo as bar } from "bar";
|
stangelandcl/hardhat
|
hardhat/recipes/pcre.py
|
<gh_stars>0
from .base import GnuRecipe
class PcreRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(PcreRecipe, self).__init__(*args, **kwargs)
self.sha256 = '69acbc2fbdefb955d42a4c606dfde800' \
'c2885711d2979e356c0636efde9ec3b5'
self.name = 'pcre'
self.version = '8.42'
self.url = 'https://ftp.pcre.org/pub/pcre/pcre-$version.tar.gz'
self.depends = ['bzip2', 'readline', 'zlib']
self.configure_args += ['--enable-jit',
'--enable-utf8',
'--enable-pcre16',
'--enable-pcre32',
'--enable-pcregrep-libz',
'--enable-pcregrep-libbz2',
'--enable-pcretest-libreadline',
'--enable-unicode-properties']
|
14ms/Minecraft-Disclosed-Source-Modifications
|
UwUWare/src/minecraft/net/minecraft/client/renderer/entity/layers/LayerHeldItemWitch.java
|
<gh_stars>1-10
package net.minecraft.client.renderer.entity.layers;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelWitch;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.entity.RenderWitch;
import net.minecraft.entity.monster.EntityWitch;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class LayerHeldItemWitch implements LayerRenderer<EntityWitch> {
private final RenderWitch witchRenderer;
public LayerHeldItemWitch(RenderWitch witchRendererIn) {
this.witchRenderer = witchRendererIn;
}
public void doRenderLayer(EntityWitch entitylivingbaseIn, float p_177141_2_, float p_177141_3_, float partialTicks,
float p_177141_5_, float p_177141_6_, float p_177141_7_, float scale) {
ItemStack itemstack = entitylivingbaseIn.getHeldItem();
if (itemstack != null) {
GlStateManager.color(1.0F, 1.0F, 1.0F);
GlStateManager.pushMatrix();
if (this.witchRenderer.getMainModel().isChild) {
GlStateManager.translate(0.0F, 0.625F, 0.0F);
GlStateManager.rotate(-20.0F, -1.0F, 0.0F, 0.0F);
float f = 0.5F;
GlStateManager.scale(f, f, f);
}
((ModelWitch) this.witchRenderer.getMainModel()).villagerNose.postRender(0.0625F);
GlStateManager.translate(-0.0625F, 0.53125F, 0.21875F);
Item item = itemstack.getItem();
Minecraft minecraft = Minecraft.getMinecraft();
if (item instanceof ItemBlock && minecraft.getBlockRendererDispatcher()
.isRenderTypeChest(Block.getBlockFromItem(item), itemstack.getMetadata())) {
GlStateManager.translate(0.0F, 0.0625F, -0.25F);
GlStateManager.rotate(30.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(-5.0F, 0.0F, 1.0F, 0.0F);
float f4 = 0.375F;
GlStateManager.scale(f4, -f4, f4);
} else if (item == Items.bow) {
GlStateManager.translate(0.0F, 0.125F, -0.125F);
GlStateManager.rotate(-45.0F, 0.0F, 1.0F, 0.0F);
float f1 = 0.625F;
GlStateManager.scale(f1, -f1, f1);
GlStateManager.rotate(-100.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(-20.0F, 0.0F, 1.0F, 0.0F);
} else if (item.isFull3D()) {
if (item.shouldRotateAroundWhenRendering()) {
GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F);
GlStateManager.translate(0.0F, -0.0625F, 0.0F);
}
this.witchRenderer.transformHeldFull3DItemLayer();
GlStateManager.translate(0.0625F, -0.125F, 0.0F);
float f2 = 0.625F;
GlStateManager.scale(f2, -f2, f2);
GlStateManager.rotate(0.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(0.0F, 0.0F, 1.0F, 0.0F);
} else {
GlStateManager.translate(0.1875F, 0.1875F, 0.0F);
float f3 = 0.875F;
GlStateManager.scale(f3, f3, f3);
GlStateManager.rotate(-20.0F, 0.0F, 0.0F, 1.0F);
GlStateManager.rotate(-60.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(-30.0F, 0.0F, 0.0F, 1.0F);
}
GlStateManager.rotate(-15.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(40.0F, 0.0F, 0.0F, 1.0F);
minecraft.getItemRenderer().renderItem(entitylivingbaseIn, itemstack,
ItemCameraTransforms.TransformType.THIRD_PERSON);
GlStateManager.popMatrix();
}
}
public boolean shouldCombineTextures() {
return false;
}
}
|
ScalablyTyped/SlinkyTyped
|
m/maxim_mazurok__gapi_dot_client_dot_toolresults/src/main/scala/typingsSlinky/maximMazurokGapiClientToolresults/gapi/client/toolresults/ListEnvironmentsResponse.scala
|
<gh_stars>10-100
package typingsSlinky.maximMazurokGapiClientToolresults.gapi.client.toolresults
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ListEnvironmentsResponse extends StObject {
/** Environments. Always set. */
var environments: js.UndefOr[js.Array[Environment]] = js.native
/** A Execution id Always set. */
var executionId: js.UndefOr[String] = js.native
/** A History id. Always set. */
var historyId: js.UndefOr[String] = js.native
/** A continuation token to resume the query at the next item. Will only be set if there are more Environments to fetch. */
var nextPageToken: js.UndefOr[String] = js.native
/** A Project id. Always set. */
var projectId: js.UndefOr[String] = js.native
}
object ListEnvironmentsResponse {
@scala.inline
def apply(): ListEnvironmentsResponse = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[ListEnvironmentsResponse]
}
@scala.inline
implicit class ListEnvironmentsResponseMutableBuilder[Self <: ListEnvironmentsResponse] (val x: Self) extends AnyVal {
@scala.inline
def setEnvironments(value: js.Array[Environment]): Self = StObject.set(x, "environments", value.asInstanceOf[js.Any])
@scala.inline
def setEnvironmentsUndefined: Self = StObject.set(x, "environments", js.undefined)
@scala.inline
def setEnvironmentsVarargs(value: Environment*): Self = StObject.set(x, "environments", js.Array(value :_*))
@scala.inline
def setExecutionId(value: String): Self = StObject.set(x, "executionId", value.asInstanceOf[js.Any])
@scala.inline
def setExecutionIdUndefined: Self = StObject.set(x, "executionId", js.undefined)
@scala.inline
def setHistoryId(value: String): Self = StObject.set(x, "historyId", value.asInstanceOf[js.Any])
@scala.inline
def setHistoryIdUndefined: Self = StObject.set(x, "historyId", js.undefined)
@scala.inline
def setNextPageToken(value: String): Self = StObject.set(x, "nextPageToken", value.asInstanceOf[js.Any])
@scala.inline
def setNextPageTokenUndefined: Self = StObject.set(x, "nextPageToken", js.undefined)
@scala.inline
def setProjectId(value: String): Self = StObject.set(x, "projectId", value.asInstanceOf[js.Any])
@scala.inline
def setProjectIdUndefined: Self = StObject.set(x, "projectId", js.undefined)
}
}
|
X1nto/AliucordPlugins-1
|
Themer/src/main/java/com/aliucord/plugins/themer/ThemerSettings.java
|
<reponame>X1nto/AliucordPlugins-1
/*
* Ven's Aliucord Plugins
* Copyright (C) 2021 Vendicated
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.aliucord.plugins.themer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.EditText;
import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.res.ResourcesCompat;
import com.aliucord.*;
import com.aliucord.fragments.SettingsPage;
import com.aliucord.plugins.Themer;
import com.aliucord.views.Button;
import com.aliucord.views.Divider;
import com.discord.views.CheckedSetting;
import com.discord.views.RadioManager;
import com.lytefast.flexinput.R$h;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.File;
import java.io.FileOutputStream;
public class ThemerSettings extends SettingsPage {
private ActivityResultLauncher<Intent> launcher;
public void importTheme(Uri uri, String name) throws Throwable {
if (!name.endsWith(".json")) name += ".json";
try (var is = requireActivity().getContentResolver().openInputStream(uri)) {
try (var os = new FileOutputStream(new File(Constants.BASE_PATH, "themes/" + name))) {
int n;
byte[] buf = new byte[16384]; // 16 KB
while ((n = is.read(buf)) > -1) {
os.write(buf, 0, n);
}
os.flush();
}
var ctx = requireContext();
Utils.showToast(ctx, "Successfully imported theme " + name);
ThemeManager.themes.clear();
ThemeManager.loadThemes(ctx, false, false);
reRender();
}
}
@SuppressLint("SetTextI18n")
@Override
public void onViewBound(View view) {
super.onViewBound(view);
var ctx = requireContext();
var act = requireActivity();
if (launcher == null)
launcher = act.registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
res -> {
if (res.getResultCode() == Activity.RESULT_OK) {
var data = res.getData();
if (data == null) return;
var contentUri = data.getData();
try (var is = act.getContentResolver().openInputStream(contentUri)) {
var json = new JSONObject(new JSONTokener(new String(Utils.readBytes(is))));
if (json.has("name")) importTheme(contentUri, json.getString("name"));
else if (contentUri.toString().endsWith(".json")) importTheme(contentUri, contentUri.getLastPathSegment());
else {
var input = new EditText(ctx);
var db = new AlertDialog.Builder(ctx)
.setTitle("Please specify a name for this theme")
.setView(input)
.setPositiveButton("OK", (dialog, which) -> {
var text = input.getText().toString();
if (text.length() > 0) {
try {
importTheme(contentUri, text);
} catch (Throwable ex) {
Themer.logger.error(requireContext(), "Failed to import theme.", ex);
}
}
}).setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());
db.show();
}
} catch (Throwable ex) {
Themer.logger.error(requireContext(), "Failed to import theme.", ex);
}
}
}
);
setActionBarTitle("Themer");
var importBtn = new Button(ctx);
importBtn.setText("Import theme");
importBtn.setOnClickListener(e -> {
var type = MimeTypeMap.getSingleton().getMimeTypeFromExtension("json");
var intent = new Intent(Intent.ACTION_GET_CONTENT).setType(type);
intent = Intent.createChooser(intent, "Choose a json file");
launcher.launch(intent);
});
var refreshBtn = new Button(ctx);
refreshBtn.setText("Load missing themes");
refreshBtn.setOnClickListener(e -> {
ThemeManager.themes.clear();
ThemeManager.loadThemes(e.getContext(), false, false);
reRender();
});
addView(importBtn);
addView(refreshBtn);
addView(new Divider(ctx));
var header = new TextView(ctx, null, 0, R$h.UiKit_Settings_Item_Header);
header.setText("Active Theme");
header.setTypeface(ResourcesCompat.getFont(ctx, Constants.Fonts.whitney_semibold));
addView(header);
if (ThemeManager.themes.size() == 0) {
var text = new TextView(ctx, null, 0, R$h.UiKit_TextView);
text.setText("Hmm... No themes found.");
addView(text);
} else {
var items = CollectionUtils.map(ThemeManager.themes, t -> Utils.createCheckedSetting(ctx, CheckedSetting.ViewType.RADIO, t.name, null));
var noTheme = Utils.createCheckedSetting(ctx, CheckedSetting.ViewType.RADIO, "None", null);
items.add(0, noTheme);
var manager = new RadioManager(items);
manager.a(noTheme);
noTheme.e(e -> {
ThemeManager.activeTheme = null;
int idx = manager.b();
if (idx != 0) {
ThemeManager.themes.get(idx - 1).disable();
manager.a(noTheme);
Utils.appActivity.recreate();
requireActivity().onBackPressed();
Utils.openPageWithProxy(ctx, new ThemerSettings());
}
});
addView(noTheme);
for (int i = 1; i < items.size(); i++) {
var theme = ThemeManager.themes.get(i - 1);
var item = items.get(i);
final int idx = i;
item.e(e -> {
if (manager.b() != idx) {
if (theme.load()) {
theme.enable();
manager.a(item);
requireActivity().onBackPressed();
Utils.openPageWithProxy(ctx, new ThemerSettings());
} else {
Utils.showToast(ctx, "Something went wrong while loading that theme :(");
}
}
});
addView(item);
if (theme.isEnabled()) manager.a(item);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.