code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/* JOrbis
* Copyright (C) 2000 ymnk, JCraft,Inc.
*
* Written by: 2000 ymnk<ymnk@jcraft.com>
*
* Many thanks to
* Monty <monty@xiph.org> and
* The XIPHOPHORUS Company http://www.xiph.org/ .
* JOrbis has been based on their awesome works, Vorbis codec.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License
* as published by the Free Software Foundation; either version 2 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package com.jcraft.jorbis;
// psychoacoustic setup
class PsyInfo{
int athp;
int decayp;
int smoothp;
int noisefitp;
int noisefit_subblock;
float noisefit_threshdB;
float ath_att;
int tonemaskp;
float[] toneatt_125Hz=new float[5];
float[] toneatt_250Hz=new float[5];
float[] toneatt_500Hz=new float[5];
float[] toneatt_1000Hz=new float[5];
float[] toneatt_2000Hz=new float[5];
float[] toneatt_4000Hz=new float[5];
float[] toneatt_8000Hz=new float[5];
int peakattp;
float[] peakatt_125Hz=new float[5];
float[] peakatt_250Hz=new float[5];
float[] peakatt_500Hz=new float[5];
float[] peakatt_1000Hz=new float[5];
float[] peakatt_2000Hz=new float[5];
float[] peakatt_4000Hz=new float[5];
float[] peakatt_8000Hz=new float[5];
int noisemaskp;
float[] noiseatt_125Hz=new float[5];
float[] noiseatt_250Hz=new float[5];
float[] noiseatt_500Hz=new float[5];
float[] noiseatt_1000Hz=new float[5];
float[] noiseatt_2000Hz=new float[5];
float[] noiseatt_4000Hz=new float[5];
float[] noiseatt_8000Hz=new float[5];
float max_curve_dB;
float attack_coeff;
float decay_coeff;
void free(){
}
}
| XtremeMP-Project/xtrememp-fx | xtrememp-audio-spi-vorbis/src/com/jcraft/jorbis/PsyInfo.java | Java | bsd-3-clause | 2,222 |
// Copyright 2014 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.
package org.chromium.base;
import android.os.Looper;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.util.Log;
import android.util.Printer;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* Java mirror of Chrome trace event API. See base/trace_event/trace_event.h. Unlike the native
* version, Java does not have stack objects, so a TRACE_EVENT() which does both TRACE_EVENT_BEGIN()
* and TRACE_EVENT_END() in ctor/dtor is not possible.
* It is OK to use tracing before the native library has loaded, but such traces will
* be ignored. (Perhaps we could devise to buffer them up in future?).
*/
@JNINamespace("base::android")
public class TraceEvent {
private static volatile boolean sEnabled = false;
private static volatile boolean sATraceEnabled = false; // True when taking an Android systrace.
private static class BasicLooperMonitor implements Printer {
@Override
public void println(final String line) {
if (line.startsWith(">")) {
beginHandling(line);
} else {
assert line.startsWith("<");
endHandling(line);
}
}
void beginHandling(final String line) {
if (sEnabled) nativeBeginToplevel();
}
void endHandling(final String line) {
if (sEnabled) nativeEndToplevel();
}
}
/**
* A class that records, traces and logs statistics about the UI thead's Looper.
* The output of this class can be used in a number of interesting ways:
* <p>
* <ol><li>
* When using chrometrace, there will be a near-continuous line of
* measurements showing both event dispatches as well as idles;
* </li><li>
* Logging messages are output for events that run too long on the
* event dispatcher, making it easy to identify problematic areas;
* </li><li>
* Statistics are output whenever there is an idle after a non-trivial
* amount of activity, allowing information to be gathered about task
* density and execution cadence on the Looper;
* </li></ol>
* <p>
* The class attaches itself as an idle handler to the main Looper, and
* monitors the execution of events and idle notifications. Task counters
* accumulate between idle notifications and get reset when a new idle
* notification is received.
*/
private static final class IdleTracingLooperMonitor extends BasicLooperMonitor
implements MessageQueue.IdleHandler {
// Tags for dumping to logcat or TraceEvent
private static final String TAG = "TraceEvent.LooperMonitor";
private static final String IDLE_EVENT_NAME = "Looper.queueIdle";
// Calculation constants
private static final long FRAME_DURATION_MILLIS = 1000L / 60L; // 60 FPS
// A reasonable threshold for defining a Looper event as "long running"
private static final long MIN_INTERESTING_DURATION_MILLIS =
FRAME_DURATION_MILLIS;
// A reasonable threshold for a "burst" of tasks on the Looper
private static final long MIN_INTERESTING_BURST_DURATION_MILLIS =
MIN_INTERESTING_DURATION_MILLIS * 3;
// Stats tracking
private long mLastIdleStartedAt = 0L;
private long mLastWorkStartedAt = 0L;
private int mNumTasksSeen = 0;
private int mNumIdlesSeen = 0;
private int mNumTasksSinceLastIdle = 0;
// State
private boolean mIdleMonitorAttached = false;
// Called from within the begin/end methods only.
// This method can only execute on the looper thread, because that is
// the only thread that is permitted to call Looper.myqueue().
private final void syncIdleMonitoring() {
if (sEnabled && !mIdleMonitorAttached) {
// approximate start time for computational purposes
mLastIdleStartedAt = SystemClock.elapsedRealtime();
Looper.myQueue().addIdleHandler(this);
mIdleMonitorAttached = true;
Log.v(TAG, "attached idle handler");
} else if (mIdleMonitorAttached && !sEnabled) {
Looper.myQueue().removeIdleHandler(this);
mIdleMonitorAttached = false;
Log.v(TAG, "detached idle handler");
}
}
@Override
final void beginHandling(final String line) {
// Close-out any prior 'idle' period before starting new task.
if (mNumTasksSinceLastIdle == 0) {
TraceEvent.end(IDLE_EVENT_NAME);
}
mLastWorkStartedAt = SystemClock.elapsedRealtime();
syncIdleMonitoring();
super.beginHandling(line);
}
@Override
final void endHandling(final String line) {
final long elapsed = SystemClock.elapsedRealtime()
- mLastWorkStartedAt;
if (elapsed > MIN_INTERESTING_DURATION_MILLIS) {
traceAndLog(Log.WARN, "observed a task that took "
+ elapsed + "ms: " + line);
}
super.endHandling(line);
syncIdleMonitoring();
mNumTasksSeen++;
mNumTasksSinceLastIdle++;
}
private static void traceAndLog(int level, String message) {
TraceEvent.instant("TraceEvent.LooperMonitor:IdleStats", message);
Log.println(level, TAG, message);
}
@Override
public final boolean queueIdle() {
final long now = SystemClock.elapsedRealtime();
if (mLastIdleStartedAt == 0) mLastIdleStartedAt = now;
final long elapsed = now - mLastIdleStartedAt;
mNumIdlesSeen++;
TraceEvent.begin(IDLE_EVENT_NAME, mNumTasksSinceLastIdle + " tasks since last idle.");
if (elapsed > MIN_INTERESTING_BURST_DURATION_MILLIS) {
// Dump stats
String statsString = mNumTasksSeen + " tasks and "
+ mNumIdlesSeen + " idles processed so far, "
+ mNumTasksSinceLastIdle + " tasks bursted and "
+ elapsed + "ms elapsed since last idle";
traceAndLog(Log.DEBUG, statsString);
}
mLastIdleStartedAt = now;
mNumTasksSinceLastIdle = 0;
return true; // stay installed
}
}
// Holder for monitor avoids unnecessary construction on non-debug runs
private static final class LooperMonitorHolder {
private static final BasicLooperMonitor sInstance =
CommandLine.getInstance().hasSwitch(BaseSwitches.ENABLE_IDLE_TRACING)
? new IdleTracingLooperMonitor() : new BasicLooperMonitor();
}
/**
* Register an enabled observer, such that java traces are always enabled with native.
*/
public static void registerNativeEnabledObserver() {
nativeRegisterEnabledObserver();
}
/**
* Notification from native that tracing is enabled/disabled.
*/
@CalledByNative
public static void setEnabled(boolean enabled) {
sEnabled = enabled;
// Android M+ systrace logs this on its own. Only log it if not writing to Android systrace.
if (sATraceEnabled) return;
ThreadUtils.getUiThreadLooper().setMessageLogging(
enabled ? LooperMonitorHolder.sInstance : null);
}
/**
* Enables or disabled Android systrace path of Chrome tracing. If enabled, all Chrome
* traces will be also output to Android systrace. Because of the overhead of Android
* systrace, this is for WebView only.
*/
public static void setATraceEnabled(boolean enabled) {
if (sATraceEnabled == enabled) return;
sATraceEnabled = enabled;
if (enabled) {
// Calls TraceEvent.setEnabled(true) via
// TraceLog::EnabledStateObserver::OnTraceLogEnabled
nativeStartATrace();
} else {
// Calls TraceEvent.setEnabled(false) via
// TraceLog::EnabledStateObserver::OnTraceLogDisabled
nativeStopATrace();
}
}
/**
* @return True if tracing is enabled, false otherwise.
* It is safe to call trace methods without checking if TraceEvent
* is enabled.
*/
public static boolean enabled() {
return sEnabled;
}
/**
* Triggers the 'instant' native trace event with no arguments.
* @param name The name of the event.
*/
public static void instant(String name) {
if (sEnabled) nativeInstant(name, null);
}
/**
* Triggers the 'instant' native trace event.
* @param name The name of the event.
* @param arg The arguments of the event.
*/
public static void instant(String name, String arg) {
if (sEnabled) nativeInstant(name, arg);
}
/**
* Triggers the 'start' native trace event with no arguments.
* @param name The name of the event.
* @param id The id of the asynchronous event.
*/
public static void startAsync(String name, long id) {
if (sEnabled) nativeStartAsync(name, id);
}
/**
* Triggers the 'finish' native trace event with no arguments.
* @param name The name of the event.
* @param id The id of the asynchronous event.
*/
public static void finishAsync(String name, long id) {
if (sEnabled) nativeFinishAsync(name, id);
}
/**
* Triggers the 'begin' native trace event with no arguments.
* @param name The name of the event.
*/
public static void begin(String name) {
if (sEnabled) nativeBegin(name, null);
}
/**
* Triggers the 'begin' native trace event.
* @param name The name of the event.
* @param arg The arguments of the event.
*/
public static void begin(String name, String arg) {
if (sEnabled) nativeBegin(name, arg);
}
/**
* Triggers the 'end' native trace event with no arguments.
* @param name The name of the event.
*/
public static void end(String name) {
if (sEnabled) nativeEnd(name, null);
}
/**
* Triggers the 'end' native trace event.
* @param name The name of the event.
* @param arg The arguments of the event.
*/
public static void end(String name, String arg) {
if (sEnabled) nativeEnd(name, arg);
}
private static native void nativeRegisterEnabledObserver();
private static native void nativeStartATrace();
private static native void nativeStopATrace();
private static native void nativeInstant(String name, String arg);
private static native void nativeBegin(String name, String arg);
private static native void nativeEnd(String name, String arg);
private static native void nativeBeginToplevel();
private static native void nativeEndToplevel();
private static native void nativeStartAsync(String name, long id);
private static native void nativeFinishAsync(String name, long id);
}
| Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/base/android/java/src/org/chromium/base/TraceEvent.java | Java | mit | 11,372 |
/*
* Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package build.tools.jdwpgen;
import java.util.*;
import java.io.*;
class AltNode extends AbstractGroupNode implements TypeNode {
SelectNode select = null;
void constrain(Context ctx) {
super.constrain(ctx);
if (!(nameNode instanceof NameValueNode)) {
error("Alt name must have value: " + nameNode);
}
if (parent instanceof SelectNode) {
select = (SelectNode)parent;
} else {
error("Alt must be in Select");
}
}
void document(PrintWriter writer) {
docRowStart(writer);
writer.println("<td colspan=" +
(maxStructIndent - structIndent + 1) + ">");
writer.println("Case " + nameNode.name + " - if <i>" +
((SelectNode)parent).typeNode.name +
"</i> is " + nameNode.value() + ":");
writer.println("<td>" + comment() + " ");
++structIndent;
super.document(writer);
--structIndent;
}
String javaClassImplements() {
return " extends " + select.commonBaseClass();
}
void genJavaClassSpecifics(PrintWriter writer, int depth) {
indent(writer, depth);
writer.print("static final " + select.typeNode.javaType());
writer.println(" ALT_ID = " + nameNode.value() + ";");
if (context.isWritingCommand()) {
genJavaCreateMethod(writer, depth);
} else {
indent(writer, depth);
writer.println(select.typeNode.javaParam() + "() {");
indent(writer, depth+1);
writer.println("return ALT_ID;");
indent(writer, depth);
writer.println("}");
}
super.genJavaClassSpecifics(writer, depth);
}
void genJavaWriteMethod(PrintWriter writer, int depth) {
genJavaWriteMethod(writer, depth, "");
}
void genJavaReadsSelectCase(PrintWriter writer, int depth, String common) {
indent(writer, depth);
writer.println("case " + nameNode.value() + ":");
indent(writer, depth+1);
writer.println(common + " = new " + name + "(vm, ps);");
indent(writer, depth+1);
writer.println("break;");
}
void genJavaCreateMethod(PrintWriter writer, int depth) {
indent(writer, depth);
writer.print("static " + select.name() + " create(");
writer.print(javaParams());
writer.println(") {");
indent(writer, depth+1);
writer.print("return new " + select.name() + "(");
writer.print("ALT_ID, new " + javaClassName() + "(");
for (Iterator it = components.iterator(); it.hasNext();) {
TypeNode tn = (TypeNode)it.next();
writer.print(tn.name());
if (it.hasNext()) {
writer.print(", ");
}
}
writer.println("));");
indent(writer, depth);
writer.println("}");
}
}
| rokn/Count_Words_2015 | testing/openjdk/jdk/make/tools/src/build/tools/jdwpgen/AltNode.java | Java | mit | 4,156 |
/*
* Copyright (c) 2015, 张涛.
*
* 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.kymjs.blog.ui.widget;
import java.io.File;
import java.io.IOException;
import org.kymjs.blog.AppConfig;
import org.kymjs.blog.R;
import org.kymjs.kjframe.ui.KJActivityStack;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.FileUtils;
import org.kymjs.kjframe.utils.StringUtils;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.widget.TextView;
/**
*
* {@link #RecordButton}需要的工具类
*
* @author kymjs (http://www.kymjs.com/)
*
*/
public class RecordButtonUtil {
private final static String TAG = "AudioUtil";
public static final String AUDOI_DIR = FileUtils.getSDCardPath()
+ File.separator + AppConfig.audioPath; // 录音音频保存根路径
private String mAudioPath; // 要播放的声音的路径
private boolean mIsRecording;// 是否正在录音
private boolean mIsPlaying;// 是否正在播放
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private OnPlayListener listener;
public boolean isPlaying() {
return mIsPlaying;
}
/**
* 设置要播放的声音的路径
*
* @param path
*/
public void setAudioPath(String path) {
this.mAudioPath = path;
}
/**
* 播放声音结束时调用
*
* @param l
*/
public void setOnPlayListener(OnPlayListener l) {
this.listener = l;
}
// 初始化 录音器
private void initRecorder() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(mAudioPath);
mIsRecording = true;
}
/**
* 开始录音,并保存到文件中
*/
public void recordAudio() {
initRecorder();
try {
mRecorder.prepare();
mRecorder.start();
} catch (IOException e) {
ViewInject.toast("小屁孩不听你说话了,请返回重试");
}
}
/**
* 获取音量值,只是针对录音音量
*
* @return
*/
public int getVolumn() {
int volumn = 0;
// 录音
if (mRecorder != null && mIsRecording) {
volumn = mRecorder.getMaxAmplitude();
if (volumn != 0)
volumn = (int) (10 * Math.log(volumn) / Math.log(10)) / 5;
}
return volumn;
}
/**
* 停止录音
*/
public void stopRecord() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
mIsRecording = false;
}
}
public void stopPlay() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
mIsPlaying = false;
if (listener != null) {
listener.stopPlay();
}
}
}
public void startPlay(String audioPath, TextView timeView) {
if (!mIsPlaying) {
if (!StringUtils.isEmpty(audioPath)) {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(audioPath);
mPlayer.prepare();
if (timeView != null) {
int len = (mPlayer.getDuration() + 500) / 1000;
timeView.setText(len + "s");
}
mPlayer.start();
if (listener != null) {
listener.starPlay();
}
mIsPlaying = true;
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
ViewInject.toast(KJActivityStack.create().topActivity()
.getString(R.string.record_sound_notfound));
}
} else {
stopPlay();
} // end playing
}
/**
* 开始播放
*/
public void startPlay() {
startPlay(mAudioPath, null);
}
public interface OnPlayListener {
/**
* 播放声音结束时调用
*/
void stopPlay();
/**
* 播放声音开始时调用
*/
void starPlay();
}
}
| supercwn/KJFrameForAndroid | KJFrame/app/src/main/java/org/kymjs/blog/ui/widget/RecordButtonUtil.java | Java | apache-2.0 | 5,318 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.trans.steps.salesforce;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.Mockito;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.mock.StepMockHelper;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class SalesforceStepTest {
@ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment();
private StepMockHelper<SalesforceStepMeta, SalesforceStepData> smh;
@BeforeClass
public static void setUpBeforeClass() throws KettleException {
KettleEnvironment.init( false );
}
@Before
public void setUp() throws KettleException {
smh =
new StepMockHelper<SalesforceStepMeta, SalesforceStepData>( "Salesforce", SalesforceStepMeta.class,
SalesforceStepData.class );
when( smh.logChannelInterfaceFactory.create( any(), any( LoggingObjectInterface.class ) ) ).thenReturn(
smh.logChannelInterface );
when( smh.trans.isRunning() ).thenReturn( true );
}
@After
public void cleanUp() {
smh.cleanUp();
}
@Test
public void testErrorHandling() {
SalesforceStepMeta meta = mock( SalesforceStepMeta.class, Mockito.CALLS_REAL_METHODS );
assertFalse( meta.supportsErrorHandling() );
}
@Test
public void testInitDispose() {
SalesforceStepMeta meta = mock( SalesforceStepMeta.class, Mockito.CALLS_REAL_METHODS );
SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) );
/*
* Salesforce Step should fail if username and password are not set
* We should not set a default account for all users
*/
meta.setDefault();
assertFalse( step.init( meta, smh.stepDataInterface ) );
meta.setDefault();
meta.setTargetURL( null );
assertFalse( step.init( meta, smh.stepDataInterface ) );
meta.setDefault();
meta.setUsername( "anonymous" );
assertFalse( step.init( meta, smh.stepDataInterface ) );
meta.setDefault();
meta.setUsername( "anonymous" );
meta.setPassword( "myPwd" );
meta.setModule( null );
assertFalse( step.init( meta, smh.stepDataInterface ) );
/*
* After setting username and password, we should have enough defaults to properly init
*/
meta.setDefault();
meta.setUsername( "anonymous" );
meta.setPassword( "myPwd" );
assertTrue( step.init( meta, smh.stepDataInterface ) );
// Dispose check
assertNotNull( smh.stepDataInterface.connection );
step.dispose( meta, smh.stepDataInterface );
assertNull( smh.stepDataInterface.connection );
}
class MockSalesforceStep extends SalesforceStep {
public MockSalesforceStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr,
TransMeta transMeta, Trans trans ) {
super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
}
}
@Test
public void createIntObjectTest() throws KettleValueException {
SalesforceStep step =
spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) );
ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class );
Mockito.when( valueMeta.getType() ).thenReturn( ValueMetaInterface.TYPE_INTEGER );
Object value = step.normalizeValue( valueMeta, 100L );
Assert.assertTrue( value instanceof Integer );
}
@Test
public void createDateObjectTest() throws KettleValueException, ParseException {
SalesforceStep step =
spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) );
ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class );
DateFormat dateFormat = new SimpleDateFormat( "dd-MM-yyyy hh:mm:ss" );
Date date = dateFormat.parse( "12-10-2017 15:10:25" );
Mockito.when( valueMeta.isDate() ).thenReturn( true );
Mockito.when( valueMeta.getDateFormatTimeZone() ).thenReturn( TimeZone.getTimeZone( "UTC" ) );
Mockito.when( valueMeta.getDate( Mockito.eq( date ) ) ).thenReturn( date );
Object value = step.normalizeValue( valueMeta, date );
Assert.assertTrue( value instanceof Calendar );
DateFormat minutesDateFormat = new SimpleDateFormat( "mm:ss" );
//check not missing minutes and seconds
Assert.assertEquals( minutesDateFormat.format( date ), minutesDateFormat.format( ( (Calendar) value ).getTime() ) );
}
}
| tkafalas/pentaho-kettle | plugins/salesforce/core/src/test/java/org/pentaho/di/trans/steps/salesforce/SalesforceStepTest.java | Java | apache-2.0 | 6,334 |
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.services.glacier.model.transform;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.transform.GlacierErrorUnmarshaller;
import com.amazonaws.util.json.JSONObject;
import com.amazonaws.services.glacier.model.InvalidParameterValueException;
public class InvalidParameterValueExceptionUnmarshaller extends GlacierErrorUnmarshaller {
public InvalidParameterValueExceptionUnmarshaller() {
super(InvalidParameterValueException.class);
}
@Override
public boolean match(String errorTypeFromHeader, JSONObject json) throws Exception {
if (errorTypeFromHeader == null) {
// Parse error type from the JSON content if it's not available in the response headers
String errorCodeFromContent = parseErrorCode(json);
return (errorCodeFromContent != null && errorCodeFromContent.equals("InvalidParameterValueException"));
} else {
return errorTypeFromHeader.equals("InvalidParameterValueException");
}
}
@Override
public AmazonServiceException unmarshall(JSONObject json) throws Exception {
InvalidParameterValueException e = (InvalidParameterValueException)super.unmarshall(json);
e.setErrorCode("InvalidParameterValueException");
e.setType(parseMember("Type", json));
e.setCode(parseMember("Code", json));
return e;
}
}
| mahaliachante/aws-sdk-java | aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/model/transform/InvalidParameterValueExceptionUnmarshaller.java | Java | apache-2.0 | 2,012 |
/*
* Copyright (C) 2010-2013 The SINA WEIBO Open Source Project
*
* 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 com.sina.weibo.sdk.openapi.models;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* 微博结构体。
*
* @author SINA
* @since 2013-11-22
*/
public class Status {
/** 微博创建时间 */
public String created_at;
/** 微博ID */
public String id;
/** 微博MID */
public String mid;
/** 字符串型的微博ID */
public String idstr;
/** 微博信息内容 */
public String text;
/** 微博来源 */
public String source;
/** 是否已收藏,true:是,false:否 */
public boolean favorited;
/** 是否被截断,true:是,false:否 */
public boolean truncated;
/**(暂未支持)回复ID */
public String in_reply_to_status_id;
/**(暂未支持)回复人UID */
public String in_reply_to_user_id;
/**(暂未支持)回复人昵称 */
public String in_reply_to_screen_name;
/** 缩略图片地址(小图),没有时不返回此字段 */
public String thumbnail_pic;
/** 中等尺寸图片地址(中图),没有时不返回此字段 */
public String bmiddle_pic;
/** 原始图片地址(原图),没有时不返回此字段 */
public String original_pic;
/** 地理信息字段 */
public Geo geo;
/** 微博作者的用户信息字段 */
public User user;
/** 被转发的原微博信息字段,当该微博为转发微博时返回 */
public Status retweeted_status;
/** 转发数 */
public int reposts_count;
/** 评论数 */
public int comments_count;
/** 表态数 */
public int attitudes_count;
/** 暂未支持 */
public int mlevel;
/**
* 微博的可见性及指定可见分组信息。该 object 中 type 取值,
* 0:普通微博,1:私密微博,3:指定分组微博,4:密友微博;
* list_id为分组的组号
*/
public Visible visible;
/** 微博配图地址。多图时返回多图链接。无配图返回"[]" */
public ArrayList<String> pic_urls;
/** 微博流内的推广微博ID */
//public Ad ad;
public static Status parse(String jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
return Status.parse(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public static Status parse(JSONObject jsonObject) {
if (null == jsonObject) {
return null;
}
Status status = new Status();
status.created_at = jsonObject.optString("created_at");
status.id = jsonObject.optString("id");
status.mid = jsonObject.optString("mid");
status.idstr = jsonObject.optString("idstr");
status.text = jsonObject.optString("text");
status.source = jsonObject.optString("source");
status.favorited = jsonObject.optBoolean("favorited", false);
status.truncated = jsonObject.optBoolean("truncated", false);
// Have NOT supported
status.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");
status.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");
status.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");
status.thumbnail_pic = jsonObject.optString("thumbnail_pic");
status.bmiddle_pic = jsonObject.optString("bmiddle_pic");
status.original_pic = jsonObject.optString("original_pic");
status.geo = Geo.parse(jsonObject.optJSONObject("geo"));
status.user = User.parse(jsonObject.optJSONObject("user"));
status.retweeted_status = Status.parse(jsonObject.optJSONObject("retweeted_status"));
status.reposts_count = jsonObject.optInt("reposts_count");
status.comments_count = jsonObject.optInt("comments_count");
status.attitudes_count = jsonObject.optInt("attitudes_count");
status.mlevel = jsonObject.optInt("mlevel", -1); // Have NOT supported
status.visible = Visible.parse(jsonObject.optJSONObject("visible"));
JSONArray picUrlsArray = jsonObject.optJSONArray("pic_urls");
if (picUrlsArray != null && picUrlsArray.length() > 0) {
int length = picUrlsArray.length();
status.pic_urls = new ArrayList<String>(length);
JSONObject tmpObject = null;
for (int ix = 0; ix < length; ix++) {
tmpObject = picUrlsArray.optJSONObject(ix);
if (tmpObject != null) {
status.pic_urls.add(tmpObject.optString("thumbnail_pic"));
}
}
}
//status.ad = jsonObject.optString("ad", "");
return status;
}
}
| zjupure/SneezeReader | weibosdk/src/main/java/com/sina/weibo/sdk/openapi/models/Status.java | Java | apache-2.0 | 5,659 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.filter;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.search.aggregations.AggregationStreams;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.bucket.InternalSingleBucketAggregation;
import java.io.IOException;
/**
*
*/
public class InternalFilter extends InternalSingleBucketAggregation implements Filter {
public final static Type TYPE = new Type("filter");
public final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public InternalFilter readResult(StreamInput in) throws IOException {
InternalFilter result = new InternalFilter();
result.readFrom(in);
return result;
}
};
public static void registerStreams() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
InternalFilter() {} // for serialization
InternalFilter(String name, long docCount, InternalAggregations subAggregations) {
super(name, docCount, subAggregations);
}
@Override
public Type type() {
return TYPE;
}
@Override
protected InternalSingleBucketAggregation newAggregation(String name, long docCount, InternalAggregations subAggregations) {
return new InternalFilter(name, docCount, subAggregations);
}
} | corochoone/elasticsearch | src/main/java/org/elasticsearch/search/aggregations/bucket/filter/InternalFilter.java | Java | apache-2.0 | 2,222 |
/*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.xsom.impl.parser;
import com.sun.xml.internal.xsom.XSSchemaSet;
import com.sun.xml.internal.xsom.impl.ElementDecl;
import com.sun.xml.internal.xsom.impl.SchemaImpl;
import com.sun.xml.internal.xsom.impl.SchemaSetImpl;
import com.sun.xml.internal.xsom.parser.AnnotationParserFactory;
import com.sun.xml.internal.xsom.parser.XMLParser;
import com.sun.xml.internal.xsom.parser.XSOMParser;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
/**
* Provides context information to be used by {@link NGCCRuntimeEx}s.
*
* <p>
* This class does the actual processing for {@link XSOMParser},
* but to hide the details from the public API, this class in
* a different package.
*
* @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class ParserContext {
/** SchemaSet to which a newly parsed schema is put in. */
public final SchemaSetImpl schemaSet = new SchemaSetImpl();
private final XSOMParser owner;
final XMLParser parser;
private final Vector<Patch> patchers = new Vector<Patch>();
private final Vector<Patch> errorCheckers = new Vector<Patch>();
/**
* Documents that are parsed already. Used to avoid cyclic inclusion/double
* inclusion of schemas. Set of {@link SchemaDocumentImpl}s.
*
* The actual data structure is map from {@link SchemaDocumentImpl} to itself,
* so that we can access the {@link SchemaDocumentImpl} itself.
*/
public final Map<SchemaDocumentImpl, SchemaDocumentImpl> parsedDocuments = new HashMap<SchemaDocumentImpl, SchemaDocumentImpl>();
public ParserContext( XSOMParser owner, XMLParser parser ) {
this.owner = owner;
this.parser = parser;
try {
parse(new InputSource(ParserContext.class.getResource("datatypes.xsd").toExternalForm()));
SchemaImpl xs = (SchemaImpl)
schemaSet.getSchema("http://www.w3.org/2001/XMLSchema");
xs.addSimpleType(schemaSet.anySimpleType,true);
xs.addComplexType(schemaSet.anyType,true);
} catch( SAXException e ) {
// this must be a bug of XSOM
if(e.getException()!=null)
e.getException().printStackTrace();
else
e.printStackTrace();
throw new InternalError();
}
}
public EntityResolver getEntityResolver() {
return owner.getEntityResolver();
}
public AnnotationParserFactory getAnnotationParserFactory() {
return owner.getAnnotationParserFactory();
}
/**
* Parses a new XML Schema document.
*/
public void parse( InputSource source ) throws SAXException {
newNGCCRuntime().parseEntity(source,false,null,null);
}
public XSSchemaSet getResult() throws SAXException {
// run all the patchers
for (Patch patcher : patchers)
patcher.run();
patchers.clear();
// build the element substitutability map
Iterator itr = schemaSet.iterateElementDecls();
while(itr.hasNext())
((ElementDecl)itr.next()).updateSubstitutabilityMap();
// run all the error checkers
for (Patch patcher : errorCheckers)
patcher.run();
errorCheckers.clear();
if(hadError) return null;
else return schemaSet;
}
public NGCCRuntimeEx newNGCCRuntime() {
return new NGCCRuntimeEx(this);
}
/** Once an error is detected, this flag is set to true. */
private boolean hadError = false;
/** Turns on the error flag. */
void setErrorFlag() { hadError=true; }
/**
* PatchManager implementation, which is accessible only from
* NGCCRuntimEx.
*/
final PatcherManager patcherManager = new PatcherManager() {
public void addPatcher( Patch patch ) {
patchers.add(patch);
}
public void addErrorChecker( Patch patch ) {
errorCheckers.add(patch);
}
public void reportError( String msg, Locator src ) throws SAXException {
// set a flag to true to avoid returning a corrupted object.
setErrorFlag();
SAXParseException e = new SAXParseException(msg,src);
if(errorHandler==null)
throw e;
else
errorHandler.error(e);
}
};
/**
* ErrorHandler proxy to turn on the hadError flag when an error
* is found.
*/
final ErrorHandler errorHandler = new ErrorHandler() {
private ErrorHandler getErrorHandler() {
if( owner.getErrorHandler()==null )
return noopHandler;
else
return owner.getErrorHandler();
}
public void warning(SAXParseException e) throws SAXException {
getErrorHandler().warning(e);
}
public void error(SAXParseException e) throws SAXException {
setErrorFlag();
getErrorHandler().error(e);
}
public void fatalError(SAXParseException e) throws SAXException {
setErrorFlag();
getErrorHandler().fatalError(e);
}
};
/**
* {@link ErrorHandler} that does nothing.
*/
final ErrorHandler noopHandler = new ErrorHandler() {
public void warning(SAXParseException e) {
}
public void error(SAXParseException e) {
}
public void fatalError(SAXParseException e) {
setErrorFlag();
}
};
}
| rokn/Count_Words_2015 | testing/openjdk2/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/impl/parser/ParserContext.java | Java | mit | 6,989 |
/*
* 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.kafka.connect.runtime.standalone;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.connect.runtime.WorkerConfig;
import java.util.Map;
public class StandaloneConfig extends WorkerConfig {
private static final ConfigDef CONFIG;
/**
* <code>offset.storage.file.filename</code>
*/
public static final String OFFSET_STORAGE_FILE_FILENAME_CONFIG = "offset.storage.file.filename";
private static final String OFFSET_STORAGE_FILE_FILENAME_DOC = "File to store offset data in";
static {
CONFIG = baseConfigDef()
.define(OFFSET_STORAGE_FILE_FILENAME_CONFIG,
ConfigDef.Type.STRING,
ConfigDef.Importance.HIGH,
OFFSET_STORAGE_FILE_FILENAME_DOC);
}
public StandaloneConfig(Map<String, String> props) {
super(CONFIG, props);
}
}
| wangcy6/storm_app | frame/kafka-0.11.0/kafka-0.11.0.1-src/connect/runtime/src/main/java/org/apache/kafka/connect/runtime/standalone/StandaloneConfig.java | Java | apache-2.0 | 1,709 |
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright (C) 1991-2007 Unicode, Inc. All rights reserved.
* Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of the Unicode data files and any associated documentation (the "Data
* Files") or Unicode software and any associated documentation (the
* "Software") to deal in the Data Files or Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Data Files or Software, and
* to permit persons to whom the Data Files or Software are furnished to do
* so, provided that (a) the above copyright notice(s) and this permission
* notice appear with all copies of the Data Files or Software, (b) both the
* above copyright notice(s) and this permission notice appear in associated
* documentation, and (c) there is clear notice in each modified Data File or
* in the Software as well as in the documentation associated with the Data
* File(s) or Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR
* CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in these Data Files or Software without prior written
* authorization of the copyright holder.
*/
package sun.text.resources.sr;
import sun.util.resources.ParallelListResourceBundle;
public class FormatData_sr_ME extends ParallelListResourceBundle {
protected final Object[][] getContents() {
return new Object[][] {
};
}
}
| rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/sun/text/resources/sr/FormatData_sr_ME.java | Java | mit | 3,546 |
/*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@summary Test SoftAudioSynthesizer getFormat method */
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Patch;
import javax.sound.sampled.*;
import com.sun.media.sound.*;
public class GetFormat {
private static void assertEquals(Object a, Object b) throws Exception
{
if(!a.equals(b))
throw new RuntimeException("assertEquals fails!");
}
private static void assertTrue(boolean value) throws Exception
{
if(!value)
throw new RuntimeException("assertTrue fails!");
}
public static void main(String[] args) throws Exception {
AudioSynthesizer synth = new SoftSynthesizer();
AudioFormat defformat = synth.getFormat();
assertTrue(defformat != null);
synth.openStream(null, null);
assertTrue(synth.getFormat().toString().equals(defformat.toString()));
synth.close();
AudioFormat custformat = new AudioFormat(8000, 16, 1, true, false);
synth.openStream(custformat, null);
assertTrue(synth.getFormat().toString().equals(custformat.toString()));
synth.close();
}
}
| rokn/Count_Words_2015 | testing/openjdk/jdk/test/javax/sound/midi/Gervill/SoftAudioSynthesizer/GetFormat.java | Java | mit | 2,359 |
/*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import java.io.DataInputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.Arrays;
import java.util.zip.InflaterInputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
class CharacterName {
private static SoftReference<byte[]> refStrPool;
private static int[][] lookup;
private static synchronized byte[] initNamePool() {
byte[] strPool = null;
if (refStrPool != null && (strPool = refStrPool.get()) != null)
return strPool;
DataInputStream dis = null;
try {
dis = new DataInputStream(new InflaterInputStream(
AccessController.doPrivileged(new PrivilegedAction<InputStream>()
{
public InputStream run() {
return getClass().getResourceAsStream("uniName.dat");
}
})));
lookup = new int[(Character.MAX_CODE_POINT + 1) >> 8][];
int total = dis.readInt();
int cpEnd = dis.readInt();
byte ba[] = new byte[cpEnd];
dis.readFully(ba);
int nameOff = 0;
int cpOff = 0;
int cp = 0;
do {
int len = ba[cpOff++] & 0xff;
if (len == 0) {
len = ba[cpOff++] & 0xff;
// always big-endian
cp = ((ba[cpOff++] & 0xff) << 16) |
((ba[cpOff++] & 0xff) << 8) |
((ba[cpOff++] & 0xff));
} else {
cp++;
}
int hi = cp >> 8;
if (lookup[hi] == null) {
lookup[hi] = new int[0x100];
}
lookup[hi][cp&0xff] = (nameOff << 8) | len;
nameOff += len;
} while (cpOff < cpEnd);
strPool = new byte[total - cpEnd];
dis.readFully(strPool);
refStrPool = new SoftReference<>(strPool);
} catch (Exception x) {
throw new InternalError(x.getMessage(), x);
} finally {
try {
if (dis != null)
dis.close();
} catch (Exception xx) {}
}
return strPool;
}
public static String get(int cp) {
byte[] strPool = null;
if (refStrPool == null || (strPool = refStrPool.get()) == null)
strPool = initNamePool();
int off = 0;
if (lookup[cp>>8] == null ||
(off = lookup[cp>>8][cp&0xff]) == 0)
return null;
@SuppressWarnings("deprecation")
String result = new String(strPool, 0, off >>> 8, off & 0xff); // ASCII
return result;
}
}
| rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/java/lang/CharacterName.java | Java | mit | 4,017 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.discovery.zen.fd;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ProcessedClusterStateNonMasterUpdateTask;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.discovery.zen.NotMasterException;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.elasticsearch.transport.TransportRequestOptions.options;
/**
* A fault detection that pings the master periodically to see if its alive.
*/
public class MasterFaultDetection extends FaultDetection {
public static final String MASTER_PING_ACTION_NAME = "internal:discovery/zen/fd/master_ping";
public static interface Listener {
/** called when pinging the master failed, like a timeout, transport disconnects etc */
void onMasterFailure(DiscoveryNode masterNode, String reason);
}
private final ClusterService clusterService;
private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
private volatile MasterPinger masterPinger;
private final Object masterNodeMutex = new Object();
private volatile DiscoveryNode masterNode;
private volatile int retryCount;
private final AtomicBoolean notifiedMasterFailure = new AtomicBoolean();
public MasterFaultDetection(Settings settings, ThreadPool threadPool, TransportService transportService,
ClusterName clusterName, ClusterService clusterService) {
super(settings, threadPool, transportService, clusterName);
this.clusterService = clusterService;
logger.debug("[master] uses ping_interval [{}], ping_timeout [{}], ping_retries [{}]", pingInterval, pingRetryTimeout, pingRetryCount);
transportService.registerRequestHandler(MASTER_PING_ACTION_NAME, MasterPingRequest::new, ThreadPool.Names.SAME, new MasterPingRequestHandler());
}
public DiscoveryNode masterNode() {
return this.masterNode;
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public void restart(DiscoveryNode masterNode, String reason) {
synchronized (masterNodeMutex) {
if (logger.isDebugEnabled()) {
logger.debug("[master] restarting fault detection against master [{}], reason [{}]", masterNode, reason);
}
innerStop();
innerStart(masterNode);
}
}
public void start(final DiscoveryNode masterNode, String reason) {
synchronized (masterNodeMutex) {
if (logger.isDebugEnabled()) {
logger.debug("[master] starting fault detection against master [{}], reason [{}]", masterNode, reason);
}
innerStart(masterNode);
}
}
private void innerStart(final DiscoveryNode masterNode) {
this.masterNode = masterNode;
this.retryCount = 0;
this.notifiedMasterFailure.set(false);
// try and connect to make sure we are connected
try {
transportService.connectToNode(masterNode);
} catch (final Exception e) {
// notify master failure (which stops also) and bail..
notifyMasterFailure(masterNode, "failed to perform initial connect [" + e.getMessage() + "]");
return;
}
if (masterPinger != null) {
masterPinger.stop();
}
this.masterPinger = new MasterPinger();
// we start pinging slightly later to allow the chosen master to complete it's own master election
threadPool.schedule(pingInterval, ThreadPool.Names.SAME, masterPinger);
}
public void stop(String reason) {
synchronized (masterNodeMutex) {
if (masterNode != null) {
if (logger.isDebugEnabled()) {
logger.debug("[master] stopping fault detection against master [{}], reason [{}]", masterNode, reason);
}
}
innerStop();
}
}
private void innerStop() {
// also will stop the next ping schedule
this.retryCount = 0;
if (masterPinger != null) {
masterPinger.stop();
masterPinger = null;
}
this.masterNode = null;
}
@Override
public void close() {
super.close();
stop("closing");
this.listeners.clear();
transportService.removeHandler(MASTER_PING_ACTION_NAME);
}
@Override
protected void handleTransportDisconnect(DiscoveryNode node) {
synchronized (masterNodeMutex) {
if (!node.equals(this.masterNode)) {
return;
}
if (connectOnNetworkDisconnect) {
try {
transportService.connectToNode(node);
// if all is well, make sure we restart the pinger
if (masterPinger != null) {
masterPinger.stop();
}
this.masterPinger = new MasterPinger();
// we use schedule with a 0 time value to run the pinger on the pool as it will run on later
threadPool.schedule(TimeValue.timeValueMillis(0), ThreadPool.Names.SAME, masterPinger);
} catch (Exception e) {
logger.trace("[master] [{}] transport disconnected (with verified connect)", masterNode);
notifyMasterFailure(masterNode, "transport disconnected (with verified connect)");
}
} else {
logger.trace("[master] [{}] transport disconnected", node);
notifyMasterFailure(node, "transport disconnected");
}
}
}
private void notifyMasterFailure(final DiscoveryNode masterNode, final String reason) {
if (notifiedMasterFailure.compareAndSet(false, true)) {
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
for (Listener listener : listeners) {
listener.onMasterFailure(masterNode, reason);
}
}
});
stop("master failure, " + reason);
}
}
private class MasterPinger implements Runnable {
private volatile boolean running = true;
public void stop() {
this.running = false;
}
@Override
public void run() {
if (!running) {
// return and don't spawn...
return;
}
final DiscoveryNode masterToPing = masterNode;
if (masterToPing == null) {
// master is null, should not happen, but we are still running, so reschedule
threadPool.schedule(pingInterval, ThreadPool.Names.SAME, MasterPinger.this);
return;
}
final MasterPingRequest request = new MasterPingRequest(clusterService.localNode().id(), masterToPing.id(), clusterName);
final TransportRequestOptions options = options().withType(TransportRequestOptions.Type.PING).withTimeout(pingRetryTimeout);
transportService.sendRequest(masterToPing, MASTER_PING_ACTION_NAME, request, options, new BaseTransportResponseHandler<MasterPingResponseResponse>() {
@Override
public MasterPingResponseResponse newInstance() {
return new MasterPingResponseResponse();
}
@Override
public void handleResponse(MasterPingResponseResponse response) {
if (!running) {
return;
}
// reset the counter, we got a good result
MasterFaultDetection.this.retryCount = 0;
// check if the master node did not get switched on us..., if it did, we simply return with no reschedule
if (masterToPing.equals(MasterFaultDetection.this.masterNode())) {
// we don't stop on disconnection from master, we keep pinging it
threadPool.schedule(pingInterval, ThreadPool.Names.SAME, MasterPinger.this);
}
}
@Override
public void handleException(TransportException exp) {
if (!running) {
return;
}
synchronized (masterNodeMutex) {
// check if the master node did not get switched on us...
if (masterToPing.equals(MasterFaultDetection.this.masterNode())) {
if (exp instanceof ConnectTransportException || exp.getCause() instanceof ConnectTransportException) {
handleTransportDisconnect(masterToPing);
return;
} else if (exp.getCause() instanceof NotMasterException) {
logger.debug("[master] pinging a master {} that is no longer a master", masterNode);
notifyMasterFailure(masterToPing, "no longer master");
return;
} else if (exp.getCause() instanceof ThisIsNotTheMasterYouAreLookingForException) {
logger.debug("[master] pinging a master {} that is not the master", masterNode);
notifyMasterFailure(masterToPing, "not master");
return;
} else if (exp.getCause() instanceof NodeDoesNotExistOnMasterException) {
logger.debug("[master] pinging a master {} but we do not exists on it, act as if its master failure", masterNode);
notifyMasterFailure(masterToPing, "do not exists on master, act as master failure");
return;
}
int retryCount = ++MasterFaultDetection.this.retryCount;
logger.trace("[master] failed to ping [{}], retry [{}] out of [{}]", exp, masterNode, retryCount, pingRetryCount);
if (retryCount >= pingRetryCount) {
logger.debug("[master] failed to ping [{}], tried [{}] times, each with maximum [{}] timeout", masterNode, pingRetryCount, pingRetryTimeout);
// not good, failure
notifyMasterFailure(masterToPing, "failed to ping, tried [" + pingRetryCount + "] times, each with maximum [" + pingRetryTimeout + "] timeout");
} else {
// resend the request, not reschedule, rely on send timeout
transportService.sendRequest(masterToPing, MASTER_PING_ACTION_NAME, request, options, this);
}
}
}
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
);
}
}
/** Thrown when a ping reaches the wrong node */
static class ThisIsNotTheMasterYouAreLookingForException extends IllegalStateException {
ThisIsNotTheMasterYouAreLookingForException(String msg) {
super(msg);
}
ThisIsNotTheMasterYouAreLookingForException() {
}
@Override
public Throwable fillInStackTrace() {
return null;
}
}
static class NodeDoesNotExistOnMasterException extends IllegalStateException {
@Override
public Throwable fillInStackTrace() {
return null;
}
}
private class MasterPingRequestHandler implements TransportRequestHandler<MasterPingRequest> {
@Override
public void messageReceived(final MasterPingRequest request, final TransportChannel channel) throws Exception {
final DiscoveryNodes nodes = clusterService.state().nodes();
// check if we are really the same master as the one we seemed to be think we are
// this can happen if the master got "kill -9" and then another node started using the same port
if (!request.masterNodeId.equals(nodes.localNodeId())) {
throw new ThisIsNotTheMasterYouAreLookingForException();
}
// ping from nodes of version < 1.4.0 will have the clustername set to null
if (request.clusterName != null && !request.clusterName.equals(clusterName)) {
logger.trace("master fault detection ping request is targeted for a different [{}] cluster then us [{}]", request.clusterName, clusterName);
throw new ThisIsNotTheMasterYouAreLookingForException("master fault detection ping request is targeted for a different [" + request.clusterName + "] cluster then us [" + clusterName + "]");
}
// when we are elected as master or when a node joins, we use a cluster state update thread
// to incorporate that information in the cluster state. That cluster state is published
// before we make it available locally. This means that a master ping can come from a node
// that has already processed the new CS but it is not known locally.
// Therefore, if we fail we have to check again under a cluster state thread to make sure
// all processing is finished.
//
if (!nodes.localNodeMaster() || !nodes.nodeExists(request.nodeId)) {
logger.trace("checking ping from [{}] under a cluster state thread", request.nodeId);
clusterService.submitStateUpdateTask("master ping (from: [" + request.nodeId + "])", new ProcessedClusterStateNonMasterUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
// if we are no longer master, fail...
DiscoveryNodes nodes = currentState.nodes();
if (!nodes.localNodeMaster()) {
throw new NotMasterException("local node is not master");
}
if (!nodes.nodeExists(request.nodeId)) {
throw new NodeDoesNotExistOnMasterException();
}
return currentState;
}
@Override
public void onFailure(String source, @Nullable Throwable t) {
if (t == null) {
t = new ElasticsearchException("unknown error while processing ping");
}
try {
channel.sendResponse(t);
} catch (IOException e) {
logger.warn("error while sending ping response", e);
}
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
try {
channel.sendResponse(new MasterPingResponseResponse());
} catch (IOException e) {
logger.warn("error while sending ping response", e);
}
}
});
} else {
// send a response, and note if we are connected to the master or not
channel.sendResponse(new MasterPingResponseResponse());
}
}
}
public static class MasterPingRequest extends TransportRequest {
private String nodeId;
private String masterNodeId;
private ClusterName clusterName;
public MasterPingRequest() {
}
private MasterPingRequest(String nodeId, String masterNodeId, ClusterName clusterName) {
this.nodeId = nodeId;
this.masterNodeId = masterNodeId;
this.clusterName = clusterName;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
nodeId = in.readString();
masterNodeId = in.readString();
clusterName = ClusterName.readClusterName(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(nodeId);
out.writeString(masterNodeId);
clusterName.writeTo(out);
}
}
private static class MasterPingResponseResponse extends TransportResponse {
private MasterPingResponseResponse() {
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
}
}
| himanshuag/elasticsearch | core/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java | Java | apache-2.0 | 19,229 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.client.ml;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractXContentTestCase;
import java.io.IOException;
public class StopDatafeedResponseTests extends AbstractXContentTestCase<StopDatafeedResponse> {
@Override
protected StopDatafeedResponse createTestInstance() {
return new StopDatafeedResponse(randomBoolean());
}
@Override
protected StopDatafeedResponse doParseInstance(XContentParser parser) throws IOException {
return StopDatafeedResponse.fromXContent(parser);
}
@Override
protected boolean supportsUnknownFields() {
return true;
}
}
| nknize/elasticsearch | client/rest-high-level/src/test/java/org/elasticsearch/client/ml/StopDatafeedResponseTests.java | Java | apache-2.0 | 1,469 |
/**
* 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.activemq.filter;
import junit.framework.TestCase;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
public class DestinationFilterTest extends TestCase {
public void testPrefixFilter() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue(">"));
assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof PrefixDestinationFilter);
System.out.println(filter);
assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic(">")));
}
public void testWildcardFilter() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*"));
assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof WildcardDestinationFilter);
assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B")));
}
public void testCompositeFilter() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.B,B.C"));
assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof CompositeDestinationFilter);
assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B")));
}
public void testMatchesChild() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*.C"));
assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B")));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C")));
filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*"));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B")));
assertFalse("Filter did match", filter.matches(new ActiveMQQueue("A")));
}
public void testMatchesAny() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.>.>"));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.C")));
assertFalse("Filter did match", filter.matches(new ActiveMQQueue("B")));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B")));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C.D.E.F")));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A")));
}
}
| cshannon/activemq-artemis | tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.java | Java | apache-2.0 | 3,298 |
package org.jsoup.parser;
import org.jsoup.helper.Validate;
import java.util.Arrays;
import java.util.Locale;
/**
CharacterReader consumes tokens off a string. To replace the old TokenQueue.
*/
final class CharacterReader {
static final char EOF = (char) -1;
private static final int maxCacheLen = 12;
private final char[] input;
private final int length;
private int pos = 0;
private int mark = 0;
private final String[] stringCache = new String[512]; // holds reused strings in this doc, to lessen garbage
CharacterReader(String input) {
Validate.notNull(input);
this.input = input.toCharArray();
this.length = this.input.length;
}
int pos() {
return pos;
}
boolean isEmpty() {
return pos >= length;
}
char current() {
return pos >= length ? EOF : input[pos];
}
char consume() {
char val = pos >= length ? EOF : input[pos];
pos++;
return val;
}
void unconsume() {
pos--;
}
void advance() {
pos++;
}
void mark() {
mark = pos;
}
void rewindToMark() {
pos = mark;
}
String consumeAsString() {
return new String(input, pos++, 1);
}
/**
* Returns the number of characters between the current position and the next instance of the input char
* @param c scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
int nextIndexOf(char c) {
// doesn't handle scanning for surrogates
for (int i = pos; i < length; i++) {
if (c == input[i])
return i - pos;
}
return -1;
}
/**
* Returns the number of characters between the current position and the next instance of the input sequence
*
* @param seq scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
int nextIndexOf(CharSequence seq) {
// doesn't handle scanning for surrogates
char startChar = seq.charAt(0);
for (int offset = pos; offset < length; offset++) {
// scan to first instance of startchar:
if (startChar != input[offset])
while(++offset < length && startChar != input[offset]) { /* empty */ }
int i = offset + 1;
int last = i + seq.length()-1;
if (offset < length && last <= length) {
for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++) { /* empty */ }
if (i == last) // found full sequence
return offset - pos;
}
}
return -1;
}
String consumeTo(char c) {
int offset = nextIndexOf(c);
if (offset != -1) {
String consumed = cacheString(pos, offset);
pos += offset;
return consumed;
} else {
return consumeToEnd();
}
}
String consumeTo(String seq) {
int offset = nextIndexOf(seq);
if (offset != -1) {
String consumed = cacheString(pos, offset);
pos += offset;
return consumed;
} else {
return consumeToEnd();
}
}
String consumeToAny(final char... chars) {
final int start = pos;
final int remaining = length;
OUTER: while (pos < remaining) {
for (char c : chars) {
if (input[pos] == c)
break OUTER;
}
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeToAnySorted(final char... chars) {
final int start = pos;
final int remaining = length;
final char[] val = input;
while (pos < remaining) {
if (Arrays.binarySearch(chars, val[pos]) >= 0)
break;
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeData() {
// &, <, null
final int start = pos;
final int remaining = length;
final char[] val = input;
while (pos < remaining) {
final char c = val[pos];
if (c == '&'|| c == '<' || c == TokeniserState.nullChar)
break;
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeTagName() {
// '\t', '\n', '\r', '\f', ' ', '/', '>', nullChar
final int start = pos;
final int remaining = length;
final char[] val = input;
while (pos < remaining) {
final char c = val[pos];
if (c == '\t'|| c == '\n'|| c == '\r'|| c == '\f'|| c == ' '|| c == '/'|| c == '>'|| c == TokeniserState.nullChar)
break;
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeToEnd() {
String data = cacheString(pos, length-pos);
pos = length;
return data;
}
String consumeLetterSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
pos++;
else
break;
}
return cacheString(start, pos - start);
}
String consumeLetterThenDigitSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
pos++;
else
break;
}
while (!isEmpty()) {
char c = input[pos];
if (c >= '0' && c <= '9')
pos++;
else
break;
}
return cacheString(start, pos - start);
}
String consumeHexSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))
pos++;
else
break;
}
return cacheString(start, pos - start);
}
String consumeDigitSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if (c >= '0' && c <= '9')
pos++;
else
break;
}
return cacheString(start, pos - start);
}
boolean matches(char c) {
return !isEmpty() && input[pos] == c;
}
boolean matches(String seq) {
int scanLength = seq.length();
if (scanLength > length - pos)
return false;
for (int offset = 0; offset < scanLength; offset++)
if (seq.charAt(offset) != input[pos+offset])
return false;
return true;
}
boolean matchesIgnoreCase(String seq) {
int scanLength = seq.length();
if (scanLength > length - pos)
return false;
for (int offset = 0; offset < scanLength; offset++) {
char upScan = Character.toUpperCase(seq.charAt(offset));
char upTarget = Character.toUpperCase(input[pos + offset]);
if (upScan != upTarget)
return false;
}
return true;
}
boolean matchesAny(char... seq) {
if (isEmpty())
return false;
char c = input[pos];
for (char seek : seq) {
if (seek == c)
return true;
}
return false;
}
boolean matchesAnySorted(char[] seq) {
return !isEmpty() && Arrays.binarySearch(seq, input[pos]) >= 0;
}
boolean matchesLetter() {
if (isEmpty())
return false;
char c = input[pos];
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
boolean matchesDigit() {
if (isEmpty())
return false;
char c = input[pos];
return (c >= '0' && c <= '9');
}
boolean matchConsume(String seq) {
if (matches(seq)) {
pos += seq.length();
return true;
} else {
return false;
}
}
boolean matchConsumeIgnoreCase(String seq) {
if (matchesIgnoreCase(seq)) {
pos += seq.length();
return true;
} else {
return false;
}
}
boolean containsIgnoreCase(String seq) {
// used to check presence of </title>, </style>. only finds consistent case.
String loScan = seq.toLowerCase(Locale.ENGLISH);
String hiScan = seq.toUpperCase(Locale.ENGLISH);
return (nextIndexOf(loScan) > -1) || (nextIndexOf(hiScan) > -1);
}
@Override
public String toString() {
return new String(input, pos, length - pos);
}
/**
* Caches short strings, as a flywheel pattern, to reduce GC load. Just for this doc, to prevent leaks.
* <p />
* Simplistic, and on hash collisions just falls back to creating a new string, vs a full HashMap with Entry list.
* That saves both having to create objects as hash keys, and running through the entry list, at the expense of
* some more duplicates.
*/
private String cacheString(final int start, final int count) {
final char[] val = input;
final String[] cache = stringCache;
// limit (no cache):
if (count > maxCacheLen)
return new String(val, start, count);
// calculate hash:
int hash = 0;
int offset = start;
for (int i = 0; i < count; i++) {
hash = 31 * hash + val[offset++];
}
// get from cache
final int index = hash & cache.length - 1;
String cached = cache[index];
if (cached == null) { // miss, add
cached = new String(val, start, count);
cache[index] = cached;
} else { // hashcode hit, check equality
if (rangeEquals(start, count, cached)) {
// hit
return cached;
} else { // hashcode conflict
cached = new String(val, start, count);
}
}
return cached;
}
/**
* Check if the value of the provided range equals the string.
*/
boolean rangeEquals(final int start, int count, final String cached) {
if (count == cached.length()) {
char one[] = input;
int i = start;
int j = 0;
while (count-- != 0) {
if (one[i++] != cached.charAt(j++))
return false;
}
return true;
}
return false;
}
}
| rogerxaic/gestock | src/org/jsoup/parser/CharacterReader.java | Java | unlicense | 10,826 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.job.entries.evaluatetablecontent;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import org.mockito.stubbing.Answer;
public class MockDriver implements Driver {
private static final List<MockDriver> drivers = new ArrayList<MockDriver>();
public static synchronized void registerInstance() throws SQLException {
MockDriver driver = new MockDriver();
DriverManager.registerDriver( driver );
drivers.add( driver );
}
public static synchronized void deregeisterInstances() throws SQLException {
for ( Driver driver : drivers ) {
DriverManager.deregisterDriver( driver );
}
drivers.clear();
}
public MockDriver() {
}
@Override
public boolean acceptsURL( String url ) throws SQLException {
return true;
}
@Override
public Connection connect( String url, Properties info ) throws SQLException {
Connection conn = mock( Connection.class );
Statement stmt = mock( Statement.class );
ResultSet rs = mock( ResultSet.class );
ResultSetMetaData md = mock( ResultSetMetaData.class );
when( stmt.getMaxRows() ).thenReturn( 5 );
when( stmt.getResultSet() ).thenReturn( rs );
when( stmt.executeQuery( anyString() ) ).thenReturn( rs );
when( rs.getMetaData() ).thenReturn( md );
when( rs.getLong( anyInt() ) ).thenReturn( 5L );
when( rs.next() ).thenAnswer( new Answer<Boolean>() {
private int count = 0;
public Boolean answer( org.mockito.invocation.InvocationOnMock invocation ) throws Throwable {
return count++ == 0;
}
} );
when( md.getColumnCount() ).thenReturn( 1 );
when( md.getColumnName( anyInt() ) ).thenReturn( "count" );
when( md.getColumnType( anyInt() ) ).thenReturn( java.sql.Types.INTEGER );
when( conn.createStatement() ).thenReturn( stmt );
return conn;
}
@Override
public int getMajorVersion() {
return 0;
}
@Override
public int getMinorVersion() {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
@Override
public DriverPropertyInfo[] getPropertyInfo( String url, Properties info ) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean jdbcCompliant() {
// TODO Auto-generated method stub
return false;
}
}
| tkafalas/pentaho-kettle | engine/src/test/java/org/pentaho/di/job/entries/evaluatetablecontent/MockDriver.java | Java | apache-2.0 | 3,801 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.core;
public interface KettleAttributeInterface {
/**
* @return the key for this attribute, usually the repository code.
*/
public String getKey();
/**
* @return the xmlCode
*/
public String getXmlCode();
/**
* @return the repCode
*/
public String getRepCode();
/**
* @return the description
*/
public String getDescription();
/**
* @return the tooltip
*/
public String getTooltip();
/**
* @return the type
*/
public int getType();
/**
* @return The parent interface.
*/
public KettleAttributeInterface getParent();
}
| wseyler/pentaho-kettle | core/src/main/java/org/pentaho/di/core/KettleAttributeInterface.java | Java | apache-2.0 | 1,533 |
/*
* Copyright 2016 The Netty Project
*
* The Netty Project 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 io.netty.channel;
import io.netty.util.IntSupplier;
/**
* Default select strategy.
*/
final class DefaultSelectStrategy implements SelectStrategy {
static final SelectStrategy INSTANCE = new DefaultSelectStrategy();
private DefaultSelectStrategy() { }
@Override
public int calculateStrategy(IntSupplier selectSupplier, boolean hasTasks) throws Exception {
return hasTasks ? selectSupplier.get() : SelectStrategy.SELECT;
}
}
| bryce-anderson/netty | transport/src/main/java/io/netty/channel/DefaultSelectStrategy.java | Java | apache-2.0 | 1,101 |
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.kroll;
public class KrollPropertyChange {
protected String name;
protected Object oldValue, newValue;
public KrollPropertyChange(String name, Object oldValue, Object newValue) {
this.name = name;
this.oldValue = oldValue;
this.newValue = newValue;
}
public void fireEvent(KrollProxy proxy, KrollProxyListener listener) {
if (listener != null) {
listener.propertyChanged(name, oldValue, newValue, proxy);
}
}
public String getName() {
return name;
}
public Object getOldValue() {
return oldValue;
}
public Object getNewValue() {
return newValue;
}
}
| arnaudsj/titanium_mobile | android/titanium/src/org/appcelerator/kroll/KrollPropertyChange.java | Java | apache-2.0 | 846 |
class Foo {
public void foo() {
int i;
}
} | asedunov/intellij-community | java/java-tests/testData/inspection/defUse/UnusedVariable.java | Java | apache-2.0 | 50 |
/*
* 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 com.facebook.presto.metadata;
import com.facebook.presto.spi.type.Type;
import java.util.Map;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
public class SpecializedFunctionKey
{
private final ParametricFunction function;
private final Map<String, Type> boundTypeParameters;
private final int arity;
public SpecializedFunctionKey(ParametricFunction function, Map<String, Type> boundTypeParameters, int arity)
{
this.function = checkNotNull(function, "function is null");
this.boundTypeParameters = checkNotNull(boundTypeParameters, "boundTypeParameters is null");
this.arity = arity;
}
public ParametricFunction getFunction()
{
return function;
}
public Map<String, Type> getBoundTypeParameters()
{
return boundTypeParameters;
}
public int getArity()
{
return arity;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SpecializedFunctionKey that = (SpecializedFunctionKey) o;
return Objects.equals(arity, that.arity) &&
Objects.equals(boundTypeParameters, that.boundTypeParameters) &&
Objects.equals(function.getSignature(), that.function.getSignature());
}
@Override
public int hashCode()
{
return Objects.hash(function.getSignature(), boundTypeParameters, arity);
}
}
| kuzemchik/presto | presto-main/src/main/java/com/facebook/presto/metadata/SpecializedFunctionKey.java | Java | apache-2.0 | 2,138 |
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package com.skia;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.opengl.EGL14;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;
public class SkiaSampleView extends GLSurfaceView {
private final SkiaSampleRenderer mSampleRenderer;
private boolean mRequestedOpenGLAPI; // true == use (desktop) OpenGL. false == use OpenGL ES.
private int mRequestedMSAASampleCount;
public SkiaSampleView(Context ctx, String cmdLineFlags, boolean useOpenGL, int msaaSampleCount) {
super(ctx);
mSampleRenderer = new SkiaSampleRenderer(this, cmdLineFlags);
mRequestedMSAASampleCount = msaaSampleCount;
setEGLContextClientVersion(2);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
setEGLConfigChooser(8, 8, 8, 8, 0, 8);
} else {
mRequestedOpenGLAPI = useOpenGL;
setEGLConfigChooser(new SampleViewEGLConfigChooser());
}
setRenderer(mSampleRenderer);
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int count = event.getPointerCount();
for (int i = 0; i < count; i++) {
final float x = event.getX(i);
final float y = event.getY(i);
final int owner = event.getPointerId(i);
int action = event.getAction() & MotionEvent.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_POINTER_UP:
action = MotionEvent.ACTION_UP;
break;
case MotionEvent.ACTION_POINTER_DOWN:
action = MotionEvent.ACTION_DOWN;
break;
default:
break;
}
final int finalAction = action;
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.handleClick(owner, x, y, finalAction);
}
});
}
return true;
}
public void inval() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.postInval();
}
});
}
public void terminate() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.term();
}
});
}
public void showOverview() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.showOverview();
}
});
}
public void nextSample() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.nextSample();
}
});
}
public void previousSample() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.previousSample();
}
});
}
public void goToSample(final int position) {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.goToSample(position);
}
});
}
public void toggleRenderingMode() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleRenderingMode();
}
});
}
public void toggleSlideshow() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleSlideshow();
}
});
}
public void toggleFPS() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleFPS();
}
});
}
public void toggleTiling() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleTiling();
}
});
}
public void toggleBBox() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleBBox();
}
});
}
public void saveToPDF() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.saveToPDF();
}
});
}
public boolean getUsesOpenGLAPI() {
return mRequestedOpenGLAPI;
}
public int getMSAASampleCount() {
return mSampleRenderer.getMSAASampleCount();
}
private class SampleViewEGLConfigChooser implements GLSurfaceView.EGLConfigChooser {
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
int numConfigs = 0;
int[] configSpec = null;
int[] value = new int[1];
int[] validAPIs = new int[] {
EGL14.EGL_OPENGL_API,
EGL14.EGL_OPENGL_ES_API
};
int initialAPI = mRequestedOpenGLAPI ? 0 : 1;
for (int i = initialAPI; i < validAPIs.length && numConfigs == 0; i++) {
int currentAPI = validAPIs[i];
EGL14.eglBindAPI(currentAPI);
// setup the renderableType which will only be included in the
// spec if we are attempting to get access to the OpenGL APIs.
int renderableType = EGL14.EGL_OPENGL_BIT;
if (currentAPI == EGL14.EGL_OPENGL_API) {
renderableType = EGL14.EGL_OPENGL_ES2_BIT;
}
if (mRequestedMSAASampleCount > 0) {
configSpec = new int[] {
EGL10.EGL_RED_SIZE, 8,
EGL10.EGL_GREEN_SIZE, 8,
EGL10.EGL_BLUE_SIZE, 8,
EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_SAMPLE_BUFFERS, 1,
EGL10.EGL_SAMPLES, mRequestedMSAASampleCount,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
// EGL_RENDERABLE_TYPE is only needed when attempting to use
// the OpenGL API (not ES) and causes many EGL drivers to fail
// with a BAD_ATTRIBUTE error.
if (!mRequestedOpenGLAPI) {
configSpec[16] = EGL10.EGL_NONE;
Log.i("Skia", "spec: " + configSpec);
}
if (!egl.eglChooseConfig(display, configSpec, null, 0, value)) {
Log.i("Skia", "Could not get MSAA context count: " + mRequestedMSAASampleCount);
}
numConfigs = value[0];
}
if (numConfigs <= 0) {
// Try without multisampling.
configSpec = new int[] {
EGL10.EGL_RED_SIZE, 8,
EGL10.EGL_GREEN_SIZE, 8,
EGL10.EGL_BLUE_SIZE, 8,
EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
// EGL_RENDERABLE_TYPE is only needed when attempting to use
// the OpenGL API (not ES) and causes many EGL drivers to fail
// with a BAD_ATTRIBUTE error.
if (!mRequestedOpenGLAPI) {
configSpec[12] = EGL10.EGL_NONE;
Log.i("Skia", "spec: " + configSpec);
}
if (!egl.eglChooseConfig(display, configSpec, null, 0, value)) {
Log.i("Skia", "Could not get non-MSAA context count");
}
numConfigs = value[0];
}
}
if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec");
}
// Get all matching configurations.
EGLConfig[] configs = new EGLConfig[numConfigs];
if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, value)) {
throw new IllegalArgumentException("Could not get config data");
}
for (int i = 0; i < configs.length; ++i) {
EGLConfig config = configs[i];
if (findConfigAttrib(egl, display, config , EGL10.EGL_RED_SIZE, 0) == 8 &&
findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0) == 8 &&
findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0) == 8 &&
findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0) == 8 &&
findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0) == 8) {
return config;
}
}
throw new IllegalArgumentException("Could not find suitable EGL config");
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display,
EGLConfig config, int attribute, int defaultValue) {
int[] value = new int[1];
if (egl.eglGetConfigAttrib(display, config, attribute, value)) {
return value[0];
}
return defaultValue;
}
}
}
| zero-rp/miniblink49 | third_party/skia/platform_tools/android/app/src/com/skia/SkiaSampleView.java | Java | apache-2.0 | 10,208 |
package org.apache.maven.repository.metadata;
/*
* 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.
*/
import org.apache.maven.artifact.ArtifactScopeEnum;
/**
* Resolves conflicts in the supplied dependency graph.
* Different implementations will implement different conflict resolution policies.
*
* @author <a href="mailto:oleg@codehaus.org">Oleg Gusakov</a>
*/
public interface GraphConflictResolver
{
String ROLE = GraphConflictResolver.class.getName();
/**
* Cleanses the supplied graph by leaving only one directed versioned edge\
* between any two nodes, if multiple exists. Uses scope relationships, defined
* in <code>ArtifactScopeEnum</code>
*
* @param graph the "dirty" graph to be simplified via conflict resolution
* @param scope scope for which the graph should be resolved
*
* @return resulting "clean" graph for the specified scope
*
* @since 3.0
*/
MetadataGraph resolveConflicts( MetadataGraph graph, ArtifactScopeEnum scope )
throws GraphConflictResolutionException;
}
| apache/maven | maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolver.java | Java | apache-2.0 | 1,822 |
/*
* 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.nifi.cluster.coordination.flow;
import org.apache.nifi.cluster.protocol.DataFlow;
import org.apache.nifi.cluster.protocol.NodeIdentifier;
/**
* <p>
* A FlowElection is responsible for examining multiple versions of a dataflow and determining which of
* the versions is the "correct" version of the flow.
* </p>
*/
public interface FlowElection {
/**
* Checks if the election has completed or not.
*
* @return <code>true</code> if the election has completed, <code>false</code> otherwise.
*/
boolean isElectionComplete();
/**
* Returns <code>true</code> if a vote has already been counted for the given Node Identifier, <code>false</code> otherwise.
*
* @param nodeIdentifier the identifier of the node
* @return <code>true</code> if a vote has already been counted for the given Node Identifier, <code>false</code> otherwise.
*/
boolean isVoteCounted(NodeIdentifier nodeIdentifier);
/**
* If the election has not yet completed, adds the given DataFlow to the list of candidates
* (if it is not already in the running) and increments the number of votes for this DataFlow by 1.
* If the election has completed, the given candidate is ignored, and the already-elected DataFlow
* will be returned. If the election has not yet completed, a vote will be cast for the given
* candidate and <code>null</code> will be returned, signifying that no candidate has yet been chosen.
*
* @param candidate the DataFlow to vote for and add to the pool of candidates if not already present
* @param nodeIdentifier the identifier of the node casting the vote
*
* @return the elected {@link DataFlow}, or <code>null</code> if no DataFlow has yet been elected
*/
DataFlow castVote(DataFlow candidate, NodeIdentifier nodeIdentifier);
/**
* Returns the DataFlow that has been elected as the "correct" version of the flow, or <code>null</code>
* if the election has not yet completed.
*
* @return the DataFlow that has been elected as the "correct" version of the flow, or <code>null</code>
* if the election has not yet completed.
*/
DataFlow getElectedDataFlow();
/**
* Returns a human-readable description of the status of the election
*
* @return a human-readable description of the status of the election
*/
String getStatusDescription();
}
| WilliamNouet/nifi | nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/FlowElection.java | Java | apache-2.0 | 3,255 |
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* 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.jetbrains.jps.model.serialization;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.testFramework.PlatformTestUtil;
import org.jdom.Element;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsEncodingConfigurationService;
import org.jetbrains.jps.model.JpsEncodingProjectConfiguration;
import org.jetbrains.jps.model.artifact.JpsArtifactService;
import org.jetbrains.jps.model.java.*;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.library.JpsOrderRootType;
import org.jetbrains.jps.model.library.sdk.JpsSdkReference;
import org.jetbrains.jps.model.module.*;
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* @author nik
*/
public class JpsProjectSerializationTest extends JpsSerializationTestCase {
public static final String SAMPLE_PROJECT_PATH = "/jps/model-serialization/testData/sampleProject";
public void testLoadProject() {
loadProject(SAMPLE_PROJECT_PATH);
String baseDirPath = getTestDataFileAbsolutePath(SAMPLE_PROJECT_PATH);
assertTrue(FileUtil.filesEqual(new File(baseDirPath), JpsModelSerializationDataService.getBaseDirectory(myProject)));
assertEquals("sampleProjectName", myProject.getName());
List<JpsModule> modules = myProject.getModules();
assertEquals(3, modules.size());
JpsModule main = modules.get(0);
assertEquals("main", main.getName());
JpsModule util = modules.get(1);
assertEquals("util", util.getName());
JpsModule xxx = modules.get(2);
assertEquals("xxx", xxx.getName());
assertTrue(FileUtil.filesEqual(new File(baseDirPath, "util"), JpsModelSerializationDataService.getBaseDirectory(util)));
List<JpsLibrary> libraries = myProject.getLibraryCollection().getLibraries();
assertEquals(3, libraries.size());
List<JpsDependencyElement> dependencies = util.getDependenciesList().getDependencies();
assertEquals(4, dependencies.size());
JpsSdkDependency sdkDependency = assertInstanceOf(dependencies.get(0), JpsSdkDependency.class);
assertSame(JpsJavaSdkType.INSTANCE, sdkDependency.getSdkType());
JpsSdkReference<?> reference = sdkDependency.getSdkReference();
assertNotNull(reference);
assertEquals("1.5", reference.getSdkName());
assertInstanceOf(dependencies.get(1), JpsModuleSourceDependency.class);
assertInstanceOf(dependencies.get(2), JpsLibraryDependency.class);
assertInstanceOf(dependencies.get(3), JpsLibraryDependency.class);
JpsSdkDependency inheritedSdkDependency = assertInstanceOf(main.getDependenciesList().getDependencies().get(0), JpsSdkDependency.class);
JpsSdkReference<?> projectSdkReference = inheritedSdkDependency.getSdkReference();
assertNotNull(projectSdkReference);
assertEquals("1.6", projectSdkReference.getSdkName());
assertEquals(getUrl("xxx/output"), JpsJavaExtensionService.getInstance().getOutputUrl(xxx, true));
assertEquals(getUrl("xxx/output"), JpsJavaExtensionService.getInstance().getOutputUrl(xxx, false));
}
public void testFileBasedProjectNameAndBaseDir() {
String relativePath = "/jps/model-serialization/testData/run-configurations/run-configurations.ipr";
String absolutePath = getTestDataFileAbsolutePath(relativePath);
loadProject(relativePath);
assertEquals("run-configurations", myProject.getName());
assertTrue(FileUtil.filesEqual(new File(absolutePath).getParentFile(), JpsModelSerializationDataService.getBaseDirectory(myProject)));
}
public void testDirectoryBasedProjectName() {
loadProject("/jps/model-serialization/testData/run-configurations-dir");
assertEquals("run-configurations-dir", myProject.getName());
}
public void testImlUnderDotIdea() {
loadProject("/jps/model-serialization/testData/imlUnderDotIdea");
JpsModule module = assertOneElement(myProject.getModules());
JpsModuleSourceRoot root = assertOneElement(module.getSourceRoots());
assertEquals(getUrl("src"), root.getUrl());
}
public void testProjectSdkWithoutType() {
loadProject("/jps/model-serialization/testData/projectSdkWithoutType/projectSdkWithoutType.ipr");
JpsSdkReference<JpsDummyElement> reference = myProject.getSdkReferencesTable().getSdkReference(JpsJavaSdkType.INSTANCE);
assertNotNull(reference);
assertEquals("1.6", reference.getSdkName());
}
public void testInvalidDependencyScope() {
loadProject("/jps/model-serialization/testData/invalidDependencyScope/invalidDependencyScope.ipr");
JpsModule module = assertOneElement(myProject.getModules());
List<JpsDependencyElement> dependencies = module.getDependenciesList().getDependencies();
assertEquals(3, dependencies.size());
JpsJavaDependencyExtension extension = JpsJavaExtensionService.getInstance().getDependencyExtension(dependencies.get(2));
assertNotNull(extension);
assertEquals(JpsJavaDependencyScope.COMPILE, extension.getScope());
}
public void testDuplicatedModuleLibrary() {
loadProject("/jps/model-serialization/testData/duplicatedModuleLibrary/duplicatedModuleLibrary.ipr");
JpsModule module = assertOneElement(myProject.getModules());
List<JpsDependencyElement> dependencies = module.getDependenciesList().getDependencies();
assertEquals(4, dependencies.size());
JpsLibrary lib1 = assertInstanceOf(dependencies.get(2), JpsLibraryDependency.class).getLibrary();
assertNotNull(lib1);
assertSameElements(lib1.getRootUrls(JpsOrderRootType.COMPILED), getUrl("data/lib1"));
JpsLibrary lib2 = assertInstanceOf(dependencies.get(3), JpsLibraryDependency.class).getLibrary();
assertNotSame(lib1, lib2);
assertNotNull(lib2);
assertSameElements(lib2.getRootUrls(JpsOrderRootType.COMPILED), getUrl("data/lib2"));
}
public void testDotIdeaUnderDotIdea() {
loadProject("/jps/model-serialization/testData/matryoshka/.idea");
JpsJavaProjectExtension extension = JpsJavaExtensionService.getInstance().getProjectExtension(myProject);
assertNotNull(extension);
assertEquals(getUrl("out"), extension.getOutputUrl());
}
public void testLoadEncoding() {
loadProject(SAMPLE_PROJECT_PATH);
JpsEncodingConfigurationService service = JpsEncodingConfigurationService.getInstance();
assertEquals("UTF-8", service.getProjectEncoding(myModel));
JpsEncodingProjectConfiguration configuration = service.getEncodingConfiguration(myProject);
assertNotNull(configuration);
assertEquals("UTF-8", configuration.getProjectEncoding());
assertEquals("windows-1251", configuration.getEncoding(new File(getAbsolutePath("util"))));
assertEquals("windows-1251", configuration.getEncoding(new File(getAbsolutePath("util/foo/bar/file.txt"))));
assertEquals("UTF-8", configuration.getEncoding(new File(getAbsolutePath("other"))));
}
public void testResourceRoots() {
String projectPath = "/jps/model-serialization/testData/resourceRoots/";
loadProject(projectPath + "resourceRoots.ipr");
JpsModule module = assertOneElement(myProject.getModules());
List<JpsModuleSourceRoot> roots = module.getSourceRoots();
assertSame(JavaSourceRootType.SOURCE, roots.get(0).getRootType());
checkResourceRoot(roots.get(1), false, "");
checkResourceRoot(roots.get(2), true, "");
checkResourceRoot(roots.get(3), true, "foo");
doTestSaveModule(module, projectPath + "resourceRoots.iml");
}
private static void checkResourceRoot(JpsModuleSourceRoot root, boolean forGenerated, String relativeOutput) {
assertSame(JavaResourceRootType.RESOURCE, root.getRootType());
JavaResourceRootProperties properties = root.getProperties(JavaResourceRootType.RESOURCE);
assertNotNull(properties);
assertEquals(forGenerated, properties.isForGeneratedSources());
assertEquals(relativeOutput, properties.getRelativeOutputPath());
}
public void testSaveProject() {
loadProject(SAMPLE_PROJECT_PATH);
List<JpsModule> modules = myProject.getModules();
doTestSaveModule(modules.get(0), SAMPLE_PROJECT_PATH + "/main.iml");
doTestSaveModule(modules.get(1), SAMPLE_PROJECT_PATH + "/util/util.iml");
//tod[nik] remember that test output root wasn't specified and doesn't save it to avoid unnecessary modifications of iml files
//doTestSaveModule(modules.get(2), "xxx/xxx.iml");
File[] libs = getFileInSampleProject(".idea/libraries").listFiles();
assertNotNull(libs);
for (File libFile : libs) {
String libName = FileUtil.getNameWithoutExtension(libFile);
JpsLibrary library = myProject.getLibraryCollection().findLibrary(libName);
assertNotNull(libName, library);
doTestSaveLibrary(libFile, libName, library);
}
}
private void doTestSaveLibrary(File libFile, String libName, JpsLibrary library) {
try {
Element actual = new Element("library");
JpsLibraryTableSerializer.saveLibrary(library, actual, libName);
JpsMacroExpander
macroExpander = JpsProjectLoader.createProjectMacroExpander(Collections.<String, String>emptyMap(), getFileInSampleProject(""));
Element rootElement = JpsLoaderBase.loadRootElement(libFile, macroExpander);
Element expected = rootElement.getChild("library");
PlatformTestUtil.assertElementsEqual(expected, actual);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private void doTestSaveModule(JpsModule module, final String moduleFilePath) {
try {
Element actual = JDomSerializationUtil.createComponentElement("NewModuleRootManager");
JpsModuleRootModelSerializer.saveRootModel(module, actual);
File imlFile = new File(getTestDataFileAbsolutePath(moduleFilePath));
Element rootElement = loadModuleRootTag(imlFile);
Element expected = JDomSerializationUtil.findComponent(rootElement, "NewModuleRootManager");
PlatformTestUtil.assertElementsEqual(expected, actual);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public File getFileInSampleProject(String relativePath) {
return new File(getTestDataFileAbsolutePath(SAMPLE_PROJECT_PATH + "/" + relativePath));
}
public void testLoadIdeaProject() {
long start = System.currentTimeMillis();
loadProjectByAbsolutePath(PathManager.getHomePath());
assertTrue(myProject.getModules().size() > 0);
System.out.println("JpsProjectSerializationTest: " + myProject.getModules().size() + " modules, " + myProject.getLibraryCollection().getLibraries().size() + " libraries and " +
JpsArtifactService.getInstance().getArtifacts(myProject).size() + " artifacts loaded in " + (System.currentTimeMillis() - start) + "ms");
}
}
| akosyakov/intellij-community | jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsProjectSerializationTest.java | Java | apache-2.0 | 11,503 |
/**********************************************************************************
*
* $Id$
*
***********************************************************************************
*
* Copyright (c) 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.service.gradebook.shared;
import java.util.Date;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* This service is designed for use by external assessment engines. These use
* the Gradebook as a passive mirror of their own assignments and scores,
* letting Gradebook users see those assignments alongside Gradebook-managed
* assignments, and combine them when calculating a course grade. The Gradebook
* application itself will not modify externally-managed assignments and scores.
*
* <b>WARNING</b>: Because the Gradebook project team is not responsible for
* defining the external clients' requirements, the Gradebook service does not
* attempt to guess at their authorization needs. Our administrative and
* external-assessment methods simply follow orders and assume that the caller
* has taken the responsibility of "doing the right thing." DO NOT wrap these
* methods in an open web service!
*/
public interface GradebookExternalAssessmentService {
/**
* @deprecated Replaced by
* {@link addExternalAssessment(String, String, String, String, Double, Date, String, Boolean)}
*/
public void addExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, double points, Date dueDate, String externalServiceDescription)
throws GradebookNotFoundException, ConflictingAssignmentNameException,
ConflictingExternalIdException, AssignmentHasIllegalPointsException;
/**
* Add an externally-managed assessment to a gradebook to be treated as a
* read-only assignment. The gradebook application will not modify the
* assessment properties or create any scores for the assessment.
* Since each assignment in a given gradebook must have a unique name,
* conflicts are possible.
*
* @param gradebookUid
* @param externalId
* some unique identifier which Samigo uses for the assessment.
* The externalId is globally namespaced within the gradebook, so
* if other apps decide to put assessments into the gradebook,
* they should prefix their externalIds with a well known (and
* unique within sakai) string.
* @param externalUrl
* a link to go to if the instructor or student wants to look at the assessment
* in Samigo; if null, no direct link will be provided in the
* gradebook, and the user will have to navigate to the assessment
* within the other application
* @param title
* @param points
* this is the total amount of points available and must be greater than zero.
* it could be null if it's an ungraded item.
* @param dueDate
* @param externalServiceDescription
* @param ungraded
*
* @param externalServiceDescription
* what to display as the source of the assignment (e.g., "from Samigo")
*
*/
public void addExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, Double points, Date dueDate, String externalServiceDescription, Boolean ungraded)
throws GradebookNotFoundException, ConflictingAssignmentNameException,
ConflictingExternalIdException, AssignmentHasIllegalPointsException;
/**
* This method is identical to {@link #addExternalAssessment(String, String, String, String, Double, Date, String, Boolean)} but
* allows you to also specify the associated Category for this assignment. If the gradebook is set up for categories and
* categoryId is null, assignment category will be unassigned
* @param gradebookUid
* @param externalId
* @param externalUrl
* @param title
* @param points
* @param dueDate
* @param externalServiceDescription
* @param ungraded
* @param categoryId
* @throws GradebookNotFoundException
* @throws ConflictingAssignmentNameException
* @throws ConflictingExternalIdException
* @throws AssignmentHasIllegalPointsException
* @throws InvalidCategoryException
*/
public void addExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, Double points, Date dueDate, String externalServiceDescription, Boolean ungraded, Long categoryId)
throws GradebookNotFoundException, ConflictingAssignmentNameException,
ConflictingExternalIdException, AssignmentHasIllegalPointsException, InvalidCategoryException;
/**
* @deprecated Replaced by
* {@link updateExternalAssessment(String, String, String, String, Double, Date, Boolean)}
*/
public void updateExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, double points, Date dueDate)
throws GradebookNotFoundException, AssessmentNotFoundException,
ConflictingAssignmentNameException, AssignmentHasIllegalPointsException;
/**
* Update an external assessment
* @param gradebookUid
* @param externalId
* @param externalUrl
* @param title
* @param points
* @param dueDate
* @param ungraded
* @throws GradebookNotFoundException
* @throws AssessmentNotFoundException
* @throws ConflictingAssignmentNameException
* @throws AssignmentHasIllegalPointsException
*/
public void updateExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, Double points, Date dueDate, Boolean ungraded)
throws GradebookNotFoundException, AssessmentNotFoundException,
ConflictingAssignmentNameException, AssignmentHasIllegalPointsException;
/**
* Remove the assessment reference from the gradebook. Although Samigo
* doesn't currently delete assessments, an instructor can retract an
* assessment to keep it from students. Since such an assessment would
* presumably no longer be used to calculate final grades, Samigo should
* also remove that assessment from the gradebook.
*
* @param externalId
* the UID of the assessment
*/
public void removeExternalAssessment(String gradebookUid, String externalId)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Updates an external score for an external assignment in the gradebook.
*
* @param gradebookUid
* The Uid of the gradebook
* @param externalId
* The external ID of the assignment/assessment
* @param studentUid
* The unique id of the student
* @param points
* The number of points earned on this assessment, or null if a score
* should be removed
*/
public void updateExternalAssessmentScore(String gradebookUid, String externalId,
String studentUid, String points)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
*
* @param gradebookUid
* @param externalId
* @param studentUidsToScores
* @throws GradebookNotFoundException
* @throws AssessmentNotFoundException
*
* @deprecated Replaced by
* {@link updateExternalAssessmentScoresString(String, String, Map<String, String)}
*/
public void updateExternalAssessmentScores(String gradebookUid,
String externalId, Map<String, Double> studentUidsToScores)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Updates a set of external scores for an external assignment in the gradebook.
*
* @param gradebookUid
* The Uid of the gradebook
* @param externalId
* The external ID of the assignment/assessment
* @param studentUidsToScores
* A map whose String keys are the unique ID strings of the students and whose
* String values are points earned on this assessment or null if the score
* should be removed.
*/
public void updateExternalAssessmentScoresString(String gradebookUid,
String externalId, Map<String, String> studentUidsToScores)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Updates an external comment for an external assignment in the gradebook.
*
* @param gradebookUid
* The Uid of the gradebook
* @param externalId
* The external ID of the assignment/assessment
* @param studentUid
* The unique id of the student
* @param comment
* The comment to be added to this grade, or null if a comment
* should be removed
*/
public void updateExternalAssessmentComment(String gradebookUid,
String externalId, String studentUid, String comment )
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Updates a set of external comments for an external assignment in the gradebook.
*
* @param gradebookUid
* The Uid of the gradebook
* @param externalId
* The external ID of the assignment/assessment
* @param studentUidsToScores
* A map whose String keys are the unique ID strings of the students and whose
* String values are comments or null if the comments
* should be removed.
*/
public void updateExternalAssessmentComments(String gradebookUid,
String externalId, Map<String, String> studentUidsToComments)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Check to see if an assignment with the given name already exists
* in the given gradebook. This will give external assessment systems
* a chance to avoid the ConflictingAssignmentNameException.
*/
public boolean isAssignmentDefined(String gradebookUid, String assignmentTitle)
throws GradebookNotFoundException;
/**
* Check to see if an assignment with the given external id already exists
* in the given gradebook. This will give external assessment systems
* a chance to avoid the ConflictingExternalIdException.
*
* @param gradebookUid The gradebook's unique identifier
* @param externalId The external assessment's external identifier
*/
public boolean isExternalAssignmentDefined(String gradebookUid, String externalId)
throws GradebookNotFoundException;
/**
* Check with the appropriate external service if a specific assignment is
* available only to groups.
*
* @param gradebookUid The gradebook's unique identifier
* @param externalId The external assessment's external identifier
*/
public boolean isExternalAssignmentGrouped(String gradebookUid, String externalId)
throws GradebookNotFoundException;
/**
* Check with the appropriate external service if a specific assignment is
* available to a specific user (i.e., the user is in an appropriate group).
* Note that this method will return true if the assignment exists in the
* gradebook and is marked as externally maintained while no provider
* recognizes it; this is to maintain a safer default (no change from the
* 2.8 release) for tools that have not implemented a provider.
*
* @param gradebookUid The gradebook's unique identifier
* @param externalId The external assessment's external identifier
* @param userId The user ID to check
*/
public boolean isExternalAssignmentVisible(String gradebookUid, String externalId, String userId)
throws GradebookNotFoundException;
/**
* Retrieve all assignments for a gradebook that are marked as externally
* maintained and are visible to the current user. Assignments may be included
* with a null providerAppKey, indicating that the gradebook references the
* assignment, but no provider claims responsibility for it.
*
* @param gradebookUid The gradebook's unique identifier
* @return A map from the externalId of each activity to the providerAppKey
*/
public Map<String, String> getExternalAssignmentsForCurrentUser(String gradebookUid)
throws GradebookNotFoundException;
/**
* Retrieve a list of all visible, external assignments for a set of users.
*
* @param gradebookUid The gradebook's unique identifier
* @param studentIds The collection of student IDs for which to retrieve assignments
* @return A map from the student ID to all visible, external activity IDs
*/
public Map<String, List<String>> getVisibleExternalAssignments(String gradebookUid, Collection<String> studentIds)
throws GradebookNotFoundException;
/**
* Register a new ExternalAssignmentProvider for handling the integration of external
* assessment sources with the sakai gradebook
* Registering more than once will overwrite the current with the new one
*
* @param provider the provider implementation object
*/
public void registerExternalAssignmentProvider(ExternalAssignmentProvider provider);
/**
* Remove/unregister any ExternalAssignmentProvider which is currently registered,
* does nothing if they provider does not exist
*
* @param providerAppKey the unique app key for a provider
*/
public void unregisterExternalAssignmentProvider(String providerAppKey);
/**
* Checks to see whether a gradebook with the given uid exists.
*
* @param gradebookUid
* The gradebook UID to check
* @return Whether the gradebook exists
*/
public boolean isGradebookDefined(String gradebookUid);
/**
* Break the connection between an external assessment engine and an assessment which
* it created, giving it up to the Gradebook application to control from now on.
*
* @param gradebookUid
* @param externalId
*/
public void setExternalAssessmentToGradebookAssignment(String gradebookUid, String externalId);
/**
* Get the category of a gradebook with the externalId given
*
* @param gradebookUId
* @param externalId
* @return
*/
public Long getExternalAssessmentCategoryId(String gradebookUId, String externalId);
}
| rodriguezdevera/sakai | edu-services/gradebook-service/api/src/java/org/sakaiproject/service/gradebook/shared/GradebookExternalAssessmentService.java | Java | apache-2.0 | 14,476 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.core.vfs.configuration;
import java.io.IOException;
import java.lang.reflect.Method;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
/**
* This class supports overriding of config builders by supplying a VariableSpace containing a variable in the format of
* vfs.[scheme].config.parser where [scheme] is one of the VFS schemes (file, http, sftp, etc...)
*
* @author cboyden
*/
public class KettleFileSystemConfigBuilderFactory {
private static Class<?> PKG = KettleVFS.class; // for i18n purposes, needed by Translator2!!
/**
* This factory returns a FileSystemConfigBuilder. Custom FileSystemConfigBuilders can be created by implementing the
* {@link IKettleFileSystemConfigBuilder} or overriding the {@link KettleGenericFileSystemConfigBuilder}
*
* @see org.apache.commons.vfs.FileSystemConfigBuilder
*
* @param varSpace
* A Kettle variable space for resolving VFS config parameters
* @param scheme
* The VFS scheme (FILE, HTTP, SFTP, etc...)
* @return A FileSystemConfigBuilder that can translate Kettle variables into VFS config parameters
* @throws IOException
*/
public static IKettleFileSystemConfigBuilder getConfigBuilder( VariableSpace varSpace, String scheme ) throws IOException {
IKettleFileSystemConfigBuilder result = null;
// Attempt to load the Config Builder from a variable: vfs.config.parser = class
String parserClass = varSpace.getVariable( "vfs." + scheme + ".config.parser" );
if ( parserClass != null ) {
try {
Class<?> configBuilderClass =
KettleFileSystemConfigBuilderFactory.class.getClassLoader().loadClass( parserClass );
Method mGetInstance = configBuilderClass.getMethod( "getInstance" );
if ( ( mGetInstance != null )
&& ( IKettleFileSystemConfigBuilder.class.isAssignableFrom( mGetInstance.getReturnType() ) ) ) {
result = (IKettleFileSystemConfigBuilder) mGetInstance.invoke( null );
} else {
result = (IKettleFileSystemConfigBuilder) configBuilderClass.newInstance();
}
} catch ( Exception e ) {
// Failed to load custom parser. Throw exception.
throw new IOException( BaseMessages.getString( PKG, "CustomVfsSettingsParser.Log.FailedToLoad" ) );
}
} else {
// No custom parser requested, load default
if ( scheme.equalsIgnoreCase( "sftp" ) ) {
result = KettleSftpFileSystemConfigBuilder.getInstance();
} else {
result = KettleGenericFileSystemConfigBuilder.getInstance();
}
}
return result;
}
}
| apratkin/pentaho-kettle | core/src/org/pentaho/di/core/vfs/configuration/KettleFileSystemConfigBuilderFactory.java | Java | apache-2.0 | 3,605 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.action;
import com.google.common.collect.Lists;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope;
import org.junit.Test;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.Matchers.equalTo;
/**
*/
@ClusterScope(scope = ElasticsearchIntegrationTest.Scope.SUITE, numDataNodes = 2)
public class RejectionActionTests extends ElasticsearchIntegrationTest {
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return ImmutableSettings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put("threadpool.search.size", 1)
.put("threadpool.search.queue_size", 1)
.put("threadpool.index.size", 1)
.put("threadpool.index.queue_size", 1)
.put("threadpool.get.size", 1)
.put("threadpool.get.queue_size", 1)
.build();
}
@Test
public void simulateSearchRejectionLoad() throws Throwable {
for (int i = 0; i < 10; i++) {
client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "1").get();
}
int numberOfAsyncOps = randomIntBetween(200, 700);
final CountDownLatch latch = new CountDownLatch(numberOfAsyncOps);
final CopyOnWriteArrayList<Object> responses = Lists.newCopyOnWriteArrayList();
for (int i = 0; i < numberOfAsyncOps; i++) {
client().prepareSearch("test")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(QueryBuilders.matchQuery("field", "1"))
.execute(new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse searchResponse) {
responses.add(searchResponse);
latch.countDown();
}
@Override
public void onFailure(Throwable e) {
responses.add(e);
latch.countDown();
}
});
}
latch.await();
assertThat(responses.size(), equalTo(numberOfAsyncOps));
// validate all responses
for (Object response : responses) {
if (response instanceof SearchResponse) {
SearchResponse searchResponse = (SearchResponse) response;
for (ShardSearchFailure failure : searchResponse.getShardFailures()) {
assertTrue("got unexpected reason..." + failure.reason(), failure.reason().toLowerCase(Locale.ENGLISH).contains("rejected"));
}
} else {
Throwable t = (Throwable) response;
Throwable unwrap = ExceptionsHelper.unwrapCause(t);
if (unwrap instanceof SearchPhaseExecutionException) {
SearchPhaseExecutionException e = (SearchPhaseExecutionException) unwrap;
for (ShardSearchFailure failure : e.shardFailures()) {
assertTrue("got unexpected reason..." + failure.reason(), failure.reason().toLowerCase(Locale.ENGLISH).contains("rejected"));
}
} else if ((unwrap instanceof EsRejectedExecutionException) == false) {
throw new AssertionError("unexpected failure", (Throwable) response);
}
}
}
}
}
| dantuffery/elasticsearch | src/test/java/org/elasticsearch/action/RejectionActionTests.java | Java | apache-2.0 | 4,951 |
/*
* 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 com.facebook.presto.sql.tree;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
public class NotExpression
extends Expression
{
private final Expression value;
public NotExpression(Expression value)
{
this(Optional.empty(), value);
}
public NotExpression(NodeLocation location, Expression value)
{
this(Optional.of(location), value);
}
private NotExpression(Optional<NodeLocation> location, Expression value)
{
super(location);
requireNonNull(value, "value is null");
this.value = value;
}
public Expression getValue()
{
return value;
}
@Override
public <R, C> R accept(AstVisitor<R, C> visitor, C context)
{
return visitor.visitNotExpression(this, context);
}
@Override
public List<Node> getChildren()
{
return ImmutableList.of(value);
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NotExpression that = (NotExpression) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode()
{
return value.hashCode();
}
}
| marsorp/blog | presto166/presto-parser/src/main/java/com/facebook/presto/sql/tree/NotExpression.java | Java | apache-2.0 | 1,998 |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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 com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.intention.impl.TypeExpression;
import com.intellij.codeInsight.template.TemplateBuilder;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author ven
*/
public class GuessTypeParameters {
private final JVMElementFactory myFactory;
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters");
public GuessTypeParameters(JVMElementFactory factory) {
myFactory = factory;
}
private List<PsiType> matchingTypeParameters (PsiType[] paramVals, PsiTypeParameter[] params, ExpectedTypeInfo info) {
PsiType type = info.getType();
int kind = info.getKind();
List<PsiType> result = new ArrayList<PsiType>();
for (int i = 0; i < paramVals.length; i++) {
PsiType val = paramVals[i];
if (val != null) {
switch (kind) {
case ExpectedTypeInfo.TYPE_STRICTLY:
if (val.equals(type)) result.add(myFactory.createType(params[i]));
break;
case ExpectedTypeInfo.TYPE_OR_SUBTYPE:
if (type.isAssignableFrom(val)) result.add(myFactory.createType(params[i]));
break;
case ExpectedTypeInfo.TYPE_OR_SUPERTYPE:
if (val.isAssignableFrom(type)) result.add(myFactory.createType(params[i]));
break;
}
}
}
return result;
}
public void setupTypeElement (PsiTypeElement typeElement, ExpectedTypeInfo[] infos, PsiSubstitutor substitutor,
TemplateBuilder builder, @Nullable PsiElement context, PsiClass targetClass) {
LOG.assertTrue(typeElement.isValid());
ApplicationManager.getApplication().assertWriteAccessAllowed();
PsiManager manager = typeElement.getManager();
GlobalSearchScope scope = typeElement.getResolveScope();
Project project = manager.getProject();
if (infos.length == 1 && substitutor != null && substitutor != PsiSubstitutor.EMPTY) {
ExpectedTypeInfo info = infos[0];
Map<PsiTypeParameter, PsiType> map = substitutor.getSubstitutionMap();
PsiType[] vals = map.values().toArray(PsiType.createArray(map.size()));
PsiTypeParameter[] params = map.keySet().toArray(new PsiTypeParameter[map.size()]);
List<PsiType> types = matchingTypeParameters(vals, params, info);
if (!types.isEmpty()) {
ContainerUtil.addAll(types, ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project));
builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
return;
}
else {
PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
PsiType type = info.getType();
PsiType defaultType = info.getDefaultType();
try {
PsiTypeElement inplaceTypeElement = ((PsiVariable)factory.createVariableDeclarationStatement("foo", type, null).getDeclaredElements()[0]).getTypeElement();
PsiSubstitutor rawingSubstitutor = getRawingSubstitutor (context, targetClass);
int substitionResult = substituteToTypeParameters(typeElement, inplaceTypeElement, vals, params, builder, rawingSubstitutor, true);
if (substitionResult != SUBSTITUTED_NONE) {
if (substitionResult == SUBSTITUTED_IN_PARAMETERS) {
PsiJavaCodeReferenceElement refElement = typeElement.getInnermostComponentReferenceElement();
LOG.assertTrue(refElement != null && refElement.getReferenceNameElement() != null);
type = getComponentType(type);
LOG.assertTrue(type != null);
defaultType = getComponentType(defaultType);
LOG.assertTrue(defaultType != null);
ExpectedTypeInfo info1 = ExpectedTypesProvider.createInfo(((PsiClassType)defaultType).rawType(),
ExpectedTypeInfo.TYPE_STRICTLY,
((PsiClassType)defaultType).rawType(),
info.getTailType());
MyTypeVisitor visitor = new MyTypeVisitor(manager, scope);
builder.replaceElement(refElement.getReferenceNameElement(),
new TypeExpression(project, ExpectedTypesProvider.processExpectedTypes(new ExpectedTypeInfo[]{info1}, visitor, project)));
}
return;
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
PsiType[] types = infos.length == 0 ? new PsiType[] {typeElement.getType()} : ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project);
builder.replaceElement(typeElement,
new TypeExpression(project, types));
}
private static PsiSubstitutor getRawingSubstitutor(PsiElement context, PsiClass targetClass) {
if (context == null || targetClass == null) return PsiSubstitutor.EMPTY;
PsiTypeParameterListOwner currContext = PsiTreeUtil.getParentOfType(context, PsiTypeParameterListOwner.class);
PsiManager manager = context.getManager();
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
while (currContext != null && !manager.areElementsEquivalent(currContext, targetClass)) {
PsiTypeParameter[] typeParameters = currContext.getTypeParameters();
substitutor = JavaPsiFacade.getInstance(context.getProject()).getElementFactory().createRawSubstitutor(substitutor, typeParameters);
currContext = currContext.getContainingClass();
}
return substitutor;
}
@Nullable
private static PsiClassType getComponentType (PsiType type) {
type = type.getDeepComponentType();
if (type instanceof PsiClassType) return (PsiClassType)type;
return null;
}
private static final int SUBSTITUTED_NONE = 0;
private static final int SUBSTITUTED_IN_REF = 1;
private static final int SUBSTITUTED_IN_PARAMETERS = 2;
private int substituteToTypeParameters (PsiTypeElement typeElement,
PsiTypeElement inplaceTypeElement,
PsiType[] paramVals,
PsiTypeParameter[] params,
TemplateBuilder builder,
PsiSubstitutor rawingSubstitutor,
boolean toplevel) {
PsiType type = inplaceTypeElement.getType();
List<PsiType> types = new ArrayList<PsiType>();
for (int i = 0; i < paramVals.length; i++) {
PsiType val = paramVals[i];
if (val == null) return SUBSTITUTED_NONE;
if (type.equals(val)) {
types.add(myFactory.createType(params[i]));
}
}
if (!types.isEmpty()) {
Project project = typeElement.getProject();
PsiType substituted = rawingSubstitutor.substitute(type);
if (!CommonClassNames.JAVA_LANG_OBJECT.equals(substituted.getCanonicalText()) && (toplevel || substituted.equals(type))) {
types.add(substituted);
}
builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
return toplevel ? SUBSTITUTED_IN_REF : SUBSTITUTED_IN_PARAMETERS;
}
boolean substituted = false;
PsiJavaCodeReferenceElement ref = typeElement.getInnermostComponentReferenceElement();
PsiJavaCodeReferenceElement inplaceRef = inplaceTypeElement.getInnermostComponentReferenceElement();
if (ref != null) {
LOG.assertTrue(inplaceRef != null);
PsiTypeElement[] innerTypeElements = ref.getParameterList().getTypeParameterElements();
PsiTypeElement[] inplaceInnerTypeElements = inplaceRef.getParameterList().getTypeParameterElements();
for (int i = 0; i < innerTypeElements.length; i++) {
substituted |= substituteToTypeParameters(innerTypeElements[i], inplaceInnerTypeElements[i], paramVals, params, builder,
rawingSubstitutor, false) != SUBSTITUTED_NONE;
}
}
return substituted ? SUBSTITUTED_IN_PARAMETERS : SUBSTITUTED_NONE;
}
public static class MyTypeVisitor extends PsiTypeVisitor<PsiType> {
private final GlobalSearchScope myResolveScope;
private final PsiManager myManager;
public MyTypeVisitor(PsiManager manager, GlobalSearchScope resolveScope) {
myManager = manager;
myResolveScope = resolveScope;
}
@Override
public PsiType visitType(PsiType type) {
if (type.equals(PsiType.NULL)) return PsiType.getJavaLangObject(myManager, myResolveScope);
return type;
}
@Override
public PsiType visitCapturedWildcardType(PsiCapturedWildcardType capturedWildcardType) {
return capturedWildcardType.getUpperBound().accept(this);
}
}
}
| kdwink/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/GuessTypeParameters.java | Java | apache-2.0 | 10,162 |
/*
* 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.cassandra.repair.consistent;
import java.net.UnknownHostException;
import java.util.Set;
import java.util.UUID;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.junit.Ignore;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.streaming.PreviewKind;
import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.UUIDGen;
@Ignore
public abstract class AbstractConsistentSessionTest
{
protected static final InetAddressAndPort COORDINATOR;
protected static final InetAddressAndPort PARTICIPANT1;
protected static final InetAddressAndPort PARTICIPANT2;
protected static final InetAddressAndPort PARTICIPANT3;
static
{
try
{
COORDINATOR = InetAddressAndPort.getByName("10.0.0.1");
PARTICIPANT1 = InetAddressAndPort.getByName("10.0.0.1");
PARTICIPANT2 = InetAddressAndPort.getByName("10.0.0.2");
PARTICIPANT3 = InetAddressAndPort.getByName("10.0.0.3");
}
catch (UnknownHostException e)
{
throw new AssertionError(e);
}
DatabaseDescriptor.daemonInitialization();
}
protected static final Set<InetAddressAndPort> PARTICIPANTS = ImmutableSet.of(PARTICIPANT1, PARTICIPANT2, PARTICIPANT3);
protected static Token t(int v)
{
return DatabaseDescriptor.getPartitioner().getToken(ByteBufferUtil.bytes(v));
}
protected static final Range<Token> RANGE1 = new Range<>(t(1), t(2));
protected static final Range<Token> RANGE2 = new Range<>(t(2), t(3));
protected static final Range<Token> RANGE3 = new Range<>(t(4), t(5));
protected static UUID registerSession(ColumnFamilyStore cfs)
{
UUID sessionId = UUIDGen.getTimeUUID();
ActiveRepairService.instance.registerParentRepairSession(sessionId,
COORDINATOR,
Lists.newArrayList(cfs),
Sets.newHashSet(RANGE1, RANGE2, RANGE3),
true,
System.currentTimeMillis(),
true,
PreviewKind.NONE);
return sessionId;
}
}
| pauloricardomg/cassandra | test/unit/org/apache/cassandra/repair/consistent/AbstractConsistentSessionTest.java | Java | apache-2.0 | 3,628 |
/*
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.parse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* An operation that removes every instance of an element from an array field.
*/
/** package */ class ParseRemoveOperation implements ParseFieldOperation {
protected final HashSet<Object> objects = new HashSet<>();
public ParseRemoveOperation(Collection<?> coll) {
objects.addAll(coll);
}
@Override
public JSONObject encode(ParseEncoder objectEncoder) throws JSONException {
JSONObject output = new JSONObject();
output.put("__op", "Remove");
output.put("objects", objectEncoder.encode(new ArrayList<>(objects)));
return output;
}
@Override
public ParseFieldOperation mergeWithPrevious(ParseFieldOperation previous) {
if (previous == null) {
return this;
} else if (previous instanceof ParseDeleteOperation) {
return new ParseSetOperation(objects);
} else if (previous instanceof ParseSetOperation) {
Object value = ((ParseSetOperation) previous).getValue();
if (value instanceof JSONArray || value instanceof List) {
return new ParseSetOperation(this.apply(value, null));
} else {
throw new IllegalArgumentException("You can only add an item to a List or JSONArray.");
}
} else if (previous instanceof ParseRemoveOperation) {
HashSet<Object> result = new HashSet<>(((ParseRemoveOperation) previous).objects);
result.addAll(objects);
return new ParseRemoveOperation(result);
} else {
throw new IllegalArgumentException("Operation is invalid after previous operation.");
}
}
@Override
public Object apply(Object oldValue, String key) {
if (oldValue == null) {
return new ArrayList<>();
} else if (oldValue instanceof JSONArray) {
ArrayList<Object> old = ParseFieldOperations.jsonArrayAsArrayList((JSONArray) oldValue);
@SuppressWarnings("unchecked")
ArrayList<Object> newValue = (ArrayList<Object>) this.apply(old, key);
return new JSONArray(newValue);
} else if (oldValue instanceof List) {
ArrayList<Object> result = new ArrayList<>((List<?>) oldValue);
result.removeAll(objects);
// Remove the removed objects from "objects" -- the items remaining
// should be ones that weren't removed by object equality.
ArrayList<Object> objectsToBeRemoved = new ArrayList<>(objects);
objectsToBeRemoved.removeAll(result);
// Build up set of object IDs for any ParseObjects in the remaining objects-to-be-removed
HashSet<String> objectIds = new HashSet<>();
for (Object obj : objectsToBeRemoved) {
if (obj instanceof ParseObject) {
objectIds.add(((ParseObject) obj).getObjectId());
}
}
// And iterate over "result" to see if any other ParseObjects need to be removed
Iterator<Object> resultIterator = result.iterator();
while (resultIterator.hasNext()) {
Object obj = resultIterator.next();
if (obj instanceof ParseObject && objectIds.contains(((ParseObject) obj).getObjectId())) {
resultIterator.remove();
}
}
return result;
} else {
throw new IllegalArgumentException("Operation is invalid after previous operation.");
}
}
}
| MSchantz/Parse-SDK-Android | Parse/src/main/java/com/parse/ParseRemoveOperation.java | Java | bsd-3-clause | 3,725 |
/*
* 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.ignite.internal.processors.cache.binary;
import org.apache.ignite.cache.CacheAtomicityMode;
/**
* Cache EntryProcessor + Deployment for transactional cache.
*/
public class GridCacheBinaryTransactionalEntryProcessorDeploymentSelfTest extends
GridCacheBinaryAtomicEntryProcessorDeploymentSelfTest {
/** {@inheritDoc} */
@Override protected CacheAtomicityMode atomicityMode() {
return CacheAtomicityMode.TRANSACTIONAL;
}
}
| irudyak/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/GridCacheBinaryTransactionalEntryProcessorDeploymentSelfTest.java | Java | apache-2.0 | 1,284 |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.message.api;
import java.util.Collection;
import java.util.Stack;
import org.sakaiproject.entity.api.AttachmentContainer;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.user.api.User;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* <p>
* MessageHeader is the base Interface for a Sakai Message headers. Header fields common to all message service message headers are defined here.
* </p>
*/
public interface MessageHeader extends AttachmentContainer
{
/**
* <p>
* MessageAccess enumerates different access modes for the message: channel-wide or grouped.
* </p>
*/
public class MessageAccess
{
private final String m_id;
private MessageAccess(String id)
{
m_id = id;
}
public String toString()
{
return m_id;
}
static public MessageAccess fromString(String access)
{
// if (PUBLIC.m_id.equals(access)) return PUBLIC;
if (CHANNEL.m_id.equals(access)) return CHANNEL;
if (GROUPED.m_id.equals(access)) return GROUPED;
return null;
}
/** public access to the message: pubview */
// public static final MessageAccess PUBLIC = new MessageAccess("public");
/** channel (site) level access to the message */
public static final MessageAccess CHANNEL = new MessageAccess("channel");
/** grouped access; only members of the getGroup() groups (authorization groups) have access */
public static final MessageAccess GROUPED = new MessageAccess("grouped");
}
/**
* Access the unique (within the channel) message id.
*
* @return The unique (within the channel) message id.
*/
String getId();
/**
* Access the date/time the message was sent to the channel.
*
* @return The date/time the message was sent to the channel.
*/
Time getDate();
/**
* Access the message order of the message was sent to the channel.
*
* @return The message order of the message was sent to the channel.
*/
Integer getMessage_order();
/**
* Access the User who sent the message to the channel.
*
* @return The User who sent the message to the channel.
*/
User getFrom();
/**
* Access the draft status of the message.
*
* @return True if the message is a draft, false if not.
*/
boolean getDraft();
/**
* Access the groups defined for this message.
*
* @return A Collection (String) of group refs (authorization group ids) defined for this message; empty if none are defined.
*/
Collection<String> getGroups();
/**
* Access the groups, as Group objects, defined for this message.
*
* @return A Collection (Group) of group objects defined for this message; empty if none are defined.
*/
Collection<Group> getGroupObjects();
/**
* Access the access mode for the message - how we compute who has access to the message.
*
* @return The MessageAccess access mode for the message.
*/
MessageAccess getAccess();
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
Element toXml(Document doc, Stack stack);
}
| conder/sakai | message/message-api/api/src/java/org/sakaiproject/message/api/MessageHeader.java | Java | apache-2.0 | 4,259 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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.tensorflow.op.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used by classes to make TensorFlow operations conveniently accessible via {@code
* org.tensorflow.op.Ops}.
*
* <p>An annotation processor (TODO: not yet implemented) builds the {@code Ops} class by
* aggregating all classes annotated as {@code @Operator}s. Each annotated class <b>must</b> have at
* least one public static factory method named {@code create} that accepts a {@link
* org.tensorflow.op.Scope} as its first argument. The processor then adds a convenience method in
* the {@code Ops} class. For example:
*
* <pre>{@code
* @Operator
* public final class MyOp implements Op {
* public static MyOp create(Scope scope, Operand operand) {
* ...
* }
* }
* }</pre>
*
* <p>results in a method in the {@code Ops} class
*
* <pre>{@code
* import org.tensorflow.op.Ops;
* ...
* Ops ops = new Ops(graph);
* ...
* ops.myOp(operand);
* // and has exactly the same effect as calling
* // MyOp.create(ops.getScope(), operand);
* }</pre>
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Operator {
/**
* Specify an optional group within the {@code Ops} class.
*
* <p>By default, an annotation processor will create convenience methods directly in the {@code
* Ops} class. An annotated operator may optionally choose to place the method within a group. For
* example:
*
* <pre>{@code
* @Operator(group="math")
* public final class Add extends PrimitiveOp implements Operand {
* ...
* }
* }</pre>
*
* <p>results in the {@code add} method placed within a {@code math} group within the {@code Ops}
* class.
*
* <pre>{@code
* ops.math().add(...);
* }</pre>
*
* <p>The group name must be a <a
* href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java
* identifier</a>.
*/
String group() default "";
/**
* Name for the wrapper method used in the {@code Ops} class.
*
* <p>By default, a processor derives the method name in the {@code Ops} class from the class name
* of the operator. This attribute allow you to provide a different name instead. For example:
*
* <pre>{@code
* @Operator(name="myOperation")
* public final class MyRealOperation implements Operand {
* public static MyRealOperation create(...)
* }
* }</pre>
*
* <p>results in this method added to the {@code Ops} class
*
* <pre>{@code
* ops.myOperation(...);
* // and is the same as calling
* // MyRealOperation.create(...)
* }</pre>
*
* <p>The name must be a <a
* href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java
* identifier</a>.
*/
String name() default "";
}
| nburn42/tensorflow | tensorflow/java/src/main/java/org/tensorflow/op/annotation/Operator.java | Java | apache-2.0 | 3,654 |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 edu.amc.sakai.user;
import com.novell.ldap.LDAPConnection;
/**
* Pluggable strategy for verifying {@link LDAPConnection}
* "liveness". Typically injected into a
* {@link PooledLDAPConnectionFactory}.
*
* @author dmccallum@unicon.net
*
*/
public interface LdapConnectionLivenessValidator {
public boolean isConnectionAlive(LDAPConnection connectionToTest);
}
| marktriggs/nyu-sakai-10.4 | providers/jldap/src/java/edu/amc/sakai/user/LdapConnectionLivenessValidator.java | Java | apache-2.0 | 1,307 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.stresstest.indexing;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import java.util.concurrent.ThreadLocalRandom;
/**
*/
public class BulkIndexingStressTest {
public static void main(String[] args) {
final int NUMBER_OF_NODES = 4;
final int NUMBER_OF_INDICES = 600;
final int BATCH = 300;
final Settings nodeSettings = ImmutableSettings.settingsBuilder().put("index.number_of_shards", 2).build();
// ESLogger logger = Loggers.getLogger("org.elasticsearch");
// logger.setLevel("DEBUG");
Node[] nodes = new Node[NUMBER_OF_NODES];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = NodeBuilder.nodeBuilder().settings(nodeSettings).node();
}
Client client = nodes.length == 1 ? nodes[0].client() : nodes[1].client();
while (true) {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (int i = 0; i < BATCH; i++) {
bulkRequest.add(Requests.indexRequest("test" + ThreadLocalRandom.current().nextInt(NUMBER_OF_INDICES)).type("type").source("field", "value"));
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
for (BulkItemResponse item : bulkResponse) {
if (item.isFailed()) {
System.out.println("failed response:" + item.getFailureMessage());
}
}
throw new RuntimeException("Failed responses");
}
;
}
}
}
| corochoone/elasticsearch | src/test/java/org/elasticsearch/stresstest/indexing/BulkIndexingStressTest.java | Java | apache-2.0 | 2,807 |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.maps.android;
import static java.lang.Math.*;
/**
* Utility functions that are used my both PolyUtil and SphericalUtil.
*/
class MathUtil {
/**
* The earth's radius, in meters.
* Mean radius as defined by IUGG.
*/
static final double EARTH_RADIUS = 6371009;
/**
* Restrict x to the range [low, high].
*/
static double clamp(double x, double low, double high) {
return x < low ? low : (x > high ? high : x);
}
/**
* Wraps the given value into the inclusive-exclusive interval between min and max.
* @param n The value to wrap.
* @param min The minimum.
* @param max The maximum.
*/
static double wrap(double n, double min, double max) {
return (n >= min && n < max) ? n : (mod(n - min, max - min) + min);
}
/**
* Returns the non-negative remainder of x / m.
* @param x The operand.
* @param m The modulus.
*/
static double mod(double x, double m) {
return ((x % m) + m) % m;
}
/**
* Returns mercator Y corresponding to latitude.
* See http://en.wikipedia.org/wiki/Mercator_projection .
*/
static double mercator(double lat) {
return log(tan(lat * 0.5 + PI/4));
}
/**
* Returns latitude from mercator Y.
*/
static double inverseMercator(double y) {
return 2 * atan(exp(y)) - PI / 2;
}
/**
* Returns haversine(angle-in-radians).
* hav(x) == (1 - cos(x)) / 2 == sin(x / 2)^2.
*/
static double hav(double x) {
double sinHalf = sin(x * 0.5);
return sinHalf * sinHalf;
}
/**
* Computes inverse haversine. Has good numerical stability around 0.
* arcHav(x) == acos(1 - 2 * x) == 2 * asin(sqrt(x)).
* The argument must be in [0, 1], and the result is positive.
*/
static double arcHav(double x) {
return 2 * asin(sqrt(x));
}
// Given h==hav(x), returns sin(abs(x)).
static double sinFromHav(double h) {
return 2 * sqrt(h * (1 - h));
}
// Returns hav(asin(x)).
static double havFromSin(double x) {
double x2 = x * x;
return x2 / (1 + sqrt(1 - x2)) * .5;
}
// Returns sin(arcHav(x) + arcHav(y)).
static double sinSumFromHav(double x, double y) {
double a = sqrt(x * (1 - x));
double b = sqrt(y * (1 - y));
return 2 * (a + b - 2 * (a * y + b * x));
}
/**
* Returns hav() of distance from (lat1, lng1) to (lat2, lng2) on the unit sphere.
*/
static double havDistance(double lat1, double lat2, double dLng) {
return hav(lat1 - lat2) + hav(dLng) * cos(lat1) * cos(lat2);
}
}
| davidmrtz/TrackingApp | myMapa/library/src/com/google/maps/android/MathUtil.java | Java | apache-2.0 | 3,305 |
/**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.maxcube.internal.exceptions;
/**
* Will be thrown when there is an attempt to put a new message line into the message processor,
* but the processor is currently processing an other message type.
*
* @author Christian Rockrohr <christian@rockrohr.de>
*/
public class IncorrectMultilineIndexException extends Exception {
private static final long serialVersionUID = -2261755876987011907L;
}
| cyclingengineer/UpnpHomeAutomationBridge | src/org/openhab/binding/maxcube/internal/exceptions/IncorrectMultilineIndexException.java | Java | epl-1.0 | 737 |
/**
* 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.hadoop.hdfs;
import java.io.IOException;
/**
* For sharing between the local and remote block reader implementations.
*/
class BlockReaderUtil {
/* See {@link BlockReader#readAll(byte[], int, int)} */
public static int readAll(BlockReader reader,
byte[] buf, int offset, int len) throws IOException {
int n = 0;
for (;;) {
int nread = reader.read(buf, offset + n, len - n);
if (nread <= 0)
return (n == 0) ? nread : n;
n += nread;
if (n >= len)
return n;
}
}
/* See {@link BlockReader#readFully(byte[], int, int)} */
public static void readFully(BlockReader reader,
byte[] buf, int off, int len) throws IOException {
int toRead = len;
while (toRead > 0) {
int ret = reader.read(buf, off, toRead);
if (ret < 0) {
throw new IOException("Premature EOF from inputStream");
}
toRead -= ret;
off += ret;
}
}
} | tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/BlockReaderUtil.java | Java | apache-2.0 | 1,761 |
/*
Copyright 2015 Google Inc. All Rights Reserved.
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 com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.CMain;
import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase;
import com.google.security.zynamics.binnavi.Gui.MainWindow.Implementations.CModuleFunctions;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractLazyComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractNodeComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CProjectTreeNode;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module.Component.CModuleNodeComponent;
import com.google.security.zynamics.binnavi.disassembly.CProjectContainer;
import com.google.security.zynamics.binnavi.disassembly.INaviAddressSpace;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleContainer;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleListenerAdapter;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.binnavi.disassembly.views.IViewContainer;
import com.google.security.zynamics.zylib.gui.SwingInvoker;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Represents module nodes in the project tree.
*/
public final class CModuleNode extends CProjectTreeNode<INaviModule> {
/**
* Used for serialization.
*/
private static final long serialVersionUID = -5643276356053733957L;
/**
* Icon used for loaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module.png"));
/**
* Icon used for unloaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_GRAY =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_gray.png"));
/**
* Icon used for incomplete modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_BROKEN =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_broken.png"));
/**
* Icon used for not yet converted modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_UNCONVERTED =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_light_gray.png"));
/**
* The module described by the node.
*/
private final INaviModule m_module;
/**
* Context in which views of the represented module are opened.
*/
private final IViewContainer m_contextContainer;
/**
* Updates the node on important changes in the represented module.
*/
private final InternalModuleListener m_listener;
/**
* Constructor for modules inside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param addressSpace The address space the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree,
final DefaultMutableTreeNode parentNode,
final IDatabase database,
final INaviAddressSpace addressSpace,
final INaviModule module,
final CProjectContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, addressSpace, module,
contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
addressSpace,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01972: Database argument can't be null");
Preconditions.checkNotNull(addressSpace, "IE01973: Address space can't be null");
m_module = Preconditions.checkNotNull(module, "IE01974: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Constructor for modules outside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree, final DefaultMutableTreeNode parentNode,
final IDatabase database, final INaviModule module, final CModuleContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, null, module, contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
null,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01970: Database can't be null");
m_module = Preconditions.checkNotNull(module, "IE01971: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Creates the child nodes of the module node. One node is added for the native Call graph of the
* module, another node is added that contains all native Flow graph views of the module.
*/
@Override
protected void createChildren() {}
@Override
public void dispose() {
super.dispose();
m_contextContainer.dispose();
m_module.removeListener(m_listener);
deleteChildren();
}
@Override
public void doubleClicked() {
if (m_module.getConfiguration().getRawModule().isComplete() && !m_module.isLoaded()) {
CModuleFunctions.loadModules(getProjectTree(), new INaviModule[] {m_module});
}
}
@Override
public CModuleNodeComponent getComponent() {
return (CModuleNodeComponent) super.getComponent();
}
@Override
public Icon getIcon() {
if (m_module.getConfiguration().getRawModule().isComplete() && m_module.isInitialized()) {
return m_module.isLoaded() ? ICON_MODULE : ICON_MODULE_GRAY;
} else if (m_module.getConfiguration().getRawModule().isComplete()
&& !m_module.isInitialized()) {
return ICON_MODULE_UNCONVERTED;
} else {
return ICON_MODULE_BROKEN;
}
}
@Override
public String toString() {
return m_module.getConfiguration().getName() + " (" + m_module.getFunctionCount() + "/"
+ m_module.getCustomViewCount() + ")";
}
/**
* Updates the node on important changes in the represented module.
*/
private class InternalModuleListener extends CModuleListenerAdapter {
@Override
public void addedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void changedName(final INaviModule module, final String name) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void deletedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
/**
* When the module is loaded, create the child nodes.
*/
@Override
public void loadedModule(final INaviModule module) {
new SwingInvoker() {
@Override
protected void operation() {
createChildren();
getTreeModel().nodeStructureChanged(CModuleNode.this);
}
}.invokeAndWait();
}
}
}
| dgrif/binnavi | src/main/java/com/google/security/zynamics/binnavi/Gui/MainWindow/ProjectTree/Nodes/Module/CModuleNode.java | Java | apache-2.0 | 8,652 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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 com.intellij.mock;
import com.intellij.lang.FileASTNode;
import com.intellij.lang.Language;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.FileContextUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.LocalTimeCounter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class MockPsiFile extends MockPsiElement implements PsiFile {
private final long myModStamp = LocalTimeCounter.currentTime();
private VirtualFile myVirtualFile = null;
public boolean valid = true;
public String text = "";
private final FileViewProvider myFileViewProvider;
private final PsiManager myPsiManager;
public MockPsiFile(@NotNull PsiManager psiManager) {
super(psiManager.getProject());
myPsiManager = psiManager;
myFileViewProvider = new SingleRootFileViewProvider(getManager(), new LightVirtualFile("noname", getFileType(), ""));
}
public MockPsiFile(@NotNull VirtualFile virtualFile, @NotNull PsiManager psiManager) {
super(psiManager.getProject());
myPsiManager = psiManager;
myVirtualFile = virtualFile;
myFileViewProvider = new SingleRootFileViewProvider(getManager(), virtualFile);
}
@Override
public VirtualFile getVirtualFile() {
return myVirtualFile;
}
@Override
public boolean processChildren(final PsiElementProcessor<PsiFileSystemItem> processor) {
return true;
}
@Override
@NotNull
public String getName() {
return "mock.file";
}
@Override
@Nullable
public ItemPresentation getPresentation() {
return null;
}
@Override
public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Not implemented");
}
@Override
public void checkSetName(String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Not implemented");
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public PsiDirectory getContainingDirectory() {
return null;
}
@Nullable
public PsiDirectory getParentDirectory() {
throw new UnsupportedOperationException("Method getParentDirectory is not yet implemented in " + getClass().getName());
}
@Override
public long getModificationStamp() {
return myModStamp;
}
@Override
@NotNull
public PsiFile getOriginalFile() {
return this;
}
@Override
@NotNull
public FileType getFileType() {
return StdFileTypes.JAVA;
}
@Override
@NotNull
public Language getLanguage() {
return StdFileTypes.JAVA.getLanguage();
}
@Override
@NotNull
public PsiFile[] getPsiRoots() {
return new PsiFile[]{this};
}
@Override
@NotNull
public FileViewProvider getViewProvider() {
return myFileViewProvider;
}
@Override
public PsiManager getManager() {
return myPsiManager;
}
@Override
@NotNull
public PsiElement[] getChildren() {
return PsiElement.EMPTY_ARRAY;
}
@Override
public PsiDirectory getParent() {
return null;
}
@Override
public PsiElement getFirstChild() {
return null;
}
@Override
public PsiElement getLastChild() {
return null;
}
@Override
public void acceptChildren(@NotNull PsiElementVisitor visitor) {
}
@Override
public PsiElement getNextSibling() {
return null;
}
@Override
public PsiElement getPrevSibling() {
return null;
}
@Override
public PsiFile getContainingFile() {
return null;
}
@Override
public TextRange getTextRange() {
return null;
}
@Override
public int getStartOffsetInParent() {
return 0;
}
@Override
public int getTextLength() {
return 0;
}
@Override
public PsiElement findElementAt(int offset) {
return null;
}
@Override
public PsiReference findReferenceAt(int offset) {
return null;
}
@Override
public int getTextOffset() {
return 0;
}
@Override
public String getText() {
return text;
}
@Override
@NotNull
public char[] textToCharArray() {
return ArrayUtil.EMPTY_CHAR_ARRAY;
}
@Override
public boolean textMatches(@NotNull CharSequence text) {
return false;
}
@Override
public boolean textMatches(@NotNull PsiElement element) {
return false;
}
@Override
public boolean textContains(char c) {
return false;
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
}
@Override
public PsiElement copy() {
return null;
}
@Override
public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
return null;
}
@Override
public void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException {
}
@Override
public PsiElement addRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addRangeBefore(@NotNull PsiElement first, @NotNull PsiElement last, PsiElement anchor)
throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addRangeAfter(PsiElement first, PsiElement last, PsiElement anchor)
throws IncorrectOperationException {
return null;
}
@Override
public void delete() throws IncorrectOperationException {
}
@Override
public void checkDelete() throws IncorrectOperationException {
}
@Override
public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
}
@Override
public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException {
return null;
}
@Override
public boolean isValid() {
return valid;
}
@Override
public boolean isWritable() {
return false;
}
@Override
public PsiReference getReference() {
return null;
}
@Override
@NotNull
public PsiReference[] getReferences() {
return PsiReference.EMPTY_ARRAY;
}
@Override
public <T> T getCopyableUserData(@NotNull Key<T> key) {
return null;
}
@Override
public <T> void putCopyableUserData(@NotNull Key<T> key, T value) {
}
@Override
@NotNull
public Project getProject() {
final PsiManager manager = getManager();
if (manager == null) throw new PsiInvalidElementAccessException(this);
return manager.getProject();
}
@Override
public boolean isPhysical() {
return true;
}
@Override
public PsiElement getNavigationElement() {
return this;
}
@Override
public PsiElement getOriginalElement() {
return this;
}
@Override
@NotNull
public GlobalSearchScope getResolveScope() {
return GlobalSearchScope.EMPTY_SCOPE;
}
@Override
@NotNull
public SearchScope getUseScope() {
return GlobalSearchScope.EMPTY_SCOPE;
}
@Override
public FileASTNode getNode() {
return null;
}
@Override
public void subtreeChanged() {
}
@Override
public void navigate(boolean requestFocus) {
}
@Override
public boolean canNavigate() {
return false;
}
@Override
public boolean canNavigateToSource() {
return false;
}
@Override
public PsiElement getContext() {
return FileContextUtil.getFileContext(this);
}
}
| idea4bsd/idea4bsd | platform/testFramework/src/com/intellij/mock/MockPsiFile.java | Java | apache-2.0 | 8,673 |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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 com.intellij.psi.impl.source.xml;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.xml.XmlElementType;
import com.intellij.psi.xml.XmlMarkupDecl;
/**
* @author Mike
*/
public class XmlMarkupDeclImpl extends XmlElementImpl implements XmlMarkupDecl {
public XmlMarkupDeclImpl() {
super(XmlElementType.XML_MARKUP_DECL);
}
@Override
public PsiMetaData getMetaData(){
return MetaRegistry.getMeta(this);
}
}
| asedunov/intellij-community | xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlMarkupDeclImpl.java | Java | apache-2.0 | 1,100 |
/**
* 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.camel.component.zookeeper.operations;
import java.util.List;
import static java.lang.String.format;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
/**
* <code>CreateOperation</code> is a basic Zookeeper operation used to create
* and set the data contained in a given node
*/
public class CreateOperation extends ZooKeeperOperation<String> {
private static final List<ACL> DEFAULT_PERMISSIONS = Ids.OPEN_ACL_UNSAFE;
private static final CreateMode DEFAULT_MODE = CreateMode.EPHEMERAL;
private byte[] data;
private List<ACL> permissions = DEFAULT_PERMISSIONS;
private CreateMode createMode = DEFAULT_MODE;
public CreateOperation(ZooKeeper connection, String node) {
super(connection, node);
}
@Override
public OperationResult<String> getResult() {
try {
String created = connection.create(node, data, permissions, createMode);
if (LOG.isDebugEnabled()) {
LOG.debug(format("Created node '%s' using mode '%s'", created, createMode));
}
// for consistency with other operations return an empty stats set.
return new OperationResult<String>(created, new Stat());
} catch (Exception e) {
return new OperationResult<String>(e);
}
}
public void setData(byte[] data) {
this.data = data;
}
public void setPermissions(List<ACL> permissions) {
this.permissions = permissions;
}
public void setCreateMode(CreateMode createMode) {
this.createMode = createMode;
}
}
| YMartsynkevych/camel | components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/operations/CreateOperation.java | Java | apache-2.0 | 2,550 |
/*
* Copyright 2005 Sascha Weinreuter
*
* 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.intellij.lang.xpath;
import com.intellij.lang.Commenter;
import com.intellij.lang.Language;
import com.intellij.openapi.fileTypes.SingleLazyInstanceSyntaxHighlighterFactory;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import org.jetbrains.annotations.NotNull;
public final class XPath2Language extends Language {
public static final String ID = "XPath2";
XPath2Language() {
super(Language.findLanguageByID(XPathLanguage.ID), ID);
}
@Override
public XPathFileType getAssociatedFileType() {
return XPathFileType.XPATH2;
}
public static class XPathSyntaxHighlighterFactory extends SingleLazyInstanceSyntaxHighlighterFactory {
@NotNull
protected SyntaxHighlighter createHighlighter() {
return new XPathHighlighter(true);
}
}
public static class XPath2Commenter implements Commenter {
@Override
public String getLineCommentPrefix() {
return null;
}
@Override
public String getBlockCommentPrefix() {
return "(:";
}
@Override
public String getBlockCommentSuffix() {
return ":)";
}
@Override
public String getCommentedBlockCommentPrefix() {
return getBlockCommentPrefix();
}
@Override
public String getCommentedBlockCommentSuffix() {
return getBlockCommentSuffix();
}
}
}
| clumsy/intellij-community | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/XPath2Language.java | Java | apache-2.0 | 1,943 |
/**
* 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.hadoop.mapred;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* This class tests reliability of the framework in the face of failures of
* both tasks and tasktrackers. Steps:
* 1) Get the cluster status
* 2) Get the number of slots in the cluster
* 3) Spawn a sleepjob that occupies the entire cluster (with two waves of maps)
* 4) Get the list of running attempts for the job
* 5) Fail a few of them
* 6) Now fail a few trackers (ssh)
* 7) Job should run to completion
* 8) The above is repeated for the Sort suite of job (randomwriter, sort,
* validator). All jobs must complete, and finally, the sort validation
* should succeed.
* To run the test:
* ./bin/hadoop --config <config> jar
* build/hadoop-<version>-test.jar MRReliabilityTest -libjars
* build/hadoop-<version>-examples.jar [-scratchdir <dir>]"
*
* The scratchdir is optional and by default the current directory on the client
* will be used as the scratch space. Note that password-less SSH must be set up
* between the client machine from where the test is submitted, and the cluster
* nodes where the test runs.
*
* The test should be run on a <b>free</b> cluster where there is no other parallel
* job submission going on. Submission of other jobs while the test runs can cause
* the tests/jobs submitted to fail.
*/
public class ReliabilityTest extends Configured implements Tool {
private String dir;
private static final Log LOG = LogFactory.getLog(ReliabilityTest.class);
private void displayUsage() {
LOG.info("This must be run in only the distributed mode " +
"(LocalJobRunner not supported).\n\tUsage: MRReliabilityTest " +
"-libjars <path to hadoop-examples.jar> [-scratchdir <dir>]" +
"\n[-scratchdir] points to a scratch space on this host where temp" +
" files for this test will be created. Defaults to current working" +
" dir. \nPasswordless SSH must be set up between this host and the" +
" nodes which the test is going to use.\n"+
"The test should be run on a free cluster with no parallel job submission" +
" going on, as the test requires to restart TaskTrackers and kill tasks" +
" any job submission while the tests are running can cause jobs/tests to fail");
System.exit(-1);
}
public int run(String[] args) throws Exception {
Configuration conf = getConf();
if ("local".equals(conf.get("mapred.job.tracker", "local"))) {
displayUsage();
}
String[] otherArgs =
new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length == 2) {
if (otherArgs[0].equals("-scratchdir")) {
dir = otherArgs[1];
} else {
displayUsage();
}
}
else if (otherArgs.length == 0) {
dir = System.getProperty("user.dir");
} else {
displayUsage();
}
//to protect against the case of jobs failing even when multiple attempts
//fail, set some high values for the max attempts
conf.setInt("mapred.map.max.attempts", 10);
conf.setInt("mapred.reduce.max.attempts", 10);
runSleepJobTest(new JobClient(new JobConf(conf)), conf);
runSortJobTests(new JobClient(new JobConf(conf)), conf);
return 0;
}
private void runSleepJobTest(final JobClient jc, final Configuration conf)
throws Exception {
ClusterStatus c = jc.getClusterStatus();
int maxMaps = c.getMaxMapTasks() * 2;
int maxReduces = maxMaps;
int mapSleepTime = (int)c.getTTExpiryInterval();
int reduceSleepTime = mapSleepTime;
String[] sleepJobArgs = new String[] {
"-m", Integer.toString(maxMaps),
"-r", Integer.toString(maxReduces),
"-mt", Integer.toString(mapSleepTime),
"-rt", Integer.toString(reduceSleepTime)};
runTest(jc, conf, "org.apache.hadoop.examples.SleepJob", sleepJobArgs,
new KillTaskThread(jc, 2, 0.2f, false, 2),
new KillTrackerThread(jc, 2, 0.4f, false, 1));
LOG.info("SleepJob done");
}
private void runSortJobTests(final JobClient jc, final Configuration conf)
throws Exception {
String inputPath = "my_reliability_test_input";
String outputPath = "my_reliability_test_output";
FileSystem fs = jc.getFs();
fs.delete(new Path(inputPath), true);
fs.delete(new Path(outputPath), true);
runRandomWriterTest(jc, conf, inputPath);
runSortTest(jc, conf, inputPath, outputPath);
runSortValidatorTest(jc, conf, inputPath, outputPath);
}
private void runRandomWriterTest(final JobClient jc,
final Configuration conf, final String inputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.examples.RandomWriter",
new String[]{inputPath},
null, new KillTrackerThread(jc, 0, 0.4f, false, 1));
LOG.info("RandomWriter job done");
}
private void runSortTest(final JobClient jc, final Configuration conf,
final String inputPath, final String outputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.examples.Sort",
new String[]{inputPath, outputPath},
new KillTaskThread(jc, 2, 0.2f, false, 2),
new KillTrackerThread(jc, 2, 0.8f, false, 1));
LOG.info("Sort job done");
}
private void runSortValidatorTest(final JobClient jc,
final Configuration conf, final String inputPath, final String outputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.mapred.SortValidator", new String[] {
"-sortInput", inputPath, "-sortOutput", outputPath},
new KillTaskThread(jc, 2, 0.2f, false, 1),
new KillTrackerThread(jc, 2, 0.8f, false, 1));
LOG.info("SortValidator job done");
}
private String normalizeCommandPath(String command) {
final String hadoopHome;
if ((hadoopHome = System.getenv("HADOOP_HOME")) != null) {
command = hadoopHome + "/" + command;
}
return command;
}
private void checkJobExitStatus(int status, String jobName) {
if (status != 0) {
LOG.info(jobName + " job failed with status: " + status);
System.exit(status);
} else {
LOG.info(jobName + " done.");
}
}
//Starts the job in a thread. It also starts the taskKill/tasktrackerKill
//threads.
private void runTest(final JobClient jc, final Configuration conf,
final String jobClass, final String[] args, KillTaskThread killTaskThread,
KillTrackerThread killTrackerThread) throws Exception {
Thread t = new Thread("Job Test") {
public void run() {
try {
Class<?> jobClassObj = conf.getClassByName(jobClass);
int status = ToolRunner.run(conf, (Tool)(jobClassObj.newInstance()),
args);
checkJobExitStatus(status, jobClass);
} catch (Exception e) {
LOG.fatal("JOB " + jobClass + " failed to run");
System.exit(-1);
}
}
};
t.setDaemon(true);
t.start();
JobStatus[] jobs;
//get the job ID. This is the job that we just submitted
while ((jobs = jc.jobsToComplete()).length == 0) {
LOG.info("Waiting for the job " + jobClass +" to start");
Thread.sleep(1000);
}
JobID jobId = jobs[jobs.length - 1].getJobID();
RunningJob rJob = jc.getJob(jobId);
if(rJob.isComplete()) {
LOG.error("The last job returned by the querying JobTracker is complete :" +
rJob.getJobID() + " .Exiting the test");
System.exit(-1);
}
while (rJob.getJobState() == JobStatus.PREP) {
LOG.info("JobID : " + jobId + " not started RUNNING yet");
Thread.sleep(1000);
rJob = jc.getJob(jobId);
}
if (killTaskThread != null) {
killTaskThread.setRunningJob(rJob);
killTaskThread.start();
killTaskThread.join();
LOG.info("DONE WITH THE TASK KILL/FAIL TESTS");
}
if (killTrackerThread != null) {
killTrackerThread.setRunningJob(rJob);
killTrackerThread.start();
killTrackerThread.join();
LOG.info("DONE WITH THE TESTS TO DO WITH LOST TASKTRACKERS");
}
t.join();
}
private class KillTrackerThread extends Thread {
private volatile boolean killed = false;
private JobClient jc;
private RunningJob rJob;
final private int thresholdMultiplier;
private float threshold = 0.2f;
private boolean onlyMapsProgress;
private int numIterations;
final private String slavesFile = dir + "/_reliability_test_slaves_file_";
final String shellCommand = normalizeCommandPath("bin/slaves.sh");
final private String STOP_COMMAND = "ps uwwx | grep java | grep " +
"org.apache.hadoop.mapred.TaskTracker"+ " |" +
" grep -v grep | tr -s ' ' | cut -d ' ' -f2 | xargs kill -s STOP";
final private String RESUME_COMMAND = "ps uwwx | grep java | grep " +
"org.apache.hadoop.mapred.TaskTracker"+ " |" +
" grep -v grep | tr -s ' ' | cut -d ' ' -f2 | xargs kill -s CONT";
//Only one instance must be active at any point
public KillTrackerThread(JobClient jc, int threshaldMultiplier,
float threshold, boolean onlyMapsProgress, int numIterations) {
this.jc = jc;
this.thresholdMultiplier = threshaldMultiplier;
this.threshold = threshold;
this.onlyMapsProgress = onlyMapsProgress;
this.numIterations = numIterations;
setDaemon(true);
}
public void setRunningJob(RunningJob rJob) {
this.rJob = rJob;
}
public void kill() {
killed = true;
}
public void run() {
stopStartTrackers(true);
if (!onlyMapsProgress) {
stopStartTrackers(false);
}
}
private void stopStartTrackers(boolean considerMaps) {
if (considerMaps) {
LOG.info("Will STOP/RESUME tasktrackers based on Maps'" +
" progress");
} else {
LOG.info("Will STOP/RESUME tasktrackers based on " +
"Reduces' progress");
}
LOG.info("Initial progress threshold: " + threshold +
". Threshold Multiplier: " + thresholdMultiplier +
". Number of iterations: " + numIterations);
float thresholdVal = threshold;
int numIterationsDone = 0;
while (!killed) {
try {
float progress;
if (jc.getJob(rJob.getID()).isComplete() ||
numIterationsDone == numIterations) {
break;
}
if (considerMaps) {
progress = jc.getJob(rJob.getID()).mapProgress();
} else {
progress = jc.getJob(rJob.getID()).reduceProgress();
}
if (progress >= thresholdVal) {
numIterationsDone++;
ClusterStatus c;
stopTaskTrackers((c = jc.getClusterStatus(true)));
Thread.sleep((int)Math.ceil(1.5 * c.getTTExpiryInterval()));
startTaskTrackers();
thresholdVal = thresholdVal * thresholdMultiplier;
}
Thread.sleep(5000);
} catch (InterruptedException ie) {
killed = true;
return;
} catch (Exception e) {
LOG.fatal(StringUtils.stringifyException(e));
}
}
}
private void stopTaskTrackers(ClusterStatus c) throws Exception {
Collection <String> trackerNames = c.getActiveTrackerNames();
ArrayList<String> trackerNamesList = new ArrayList<String>(trackerNames);
Collections.shuffle(trackerNamesList);
int count = 0;
FileOutputStream fos = new FileOutputStream(new File(slavesFile));
LOG.info(new Date() + " Stopping a few trackers");
for (String tracker : trackerNamesList) {
String host = convertTrackerNameToHostName(tracker);
LOG.info(new Date() + " Marking tracker on host: " + host);
fos.write((host + "\n").getBytes());
if (count++ >= trackerNamesList.size()/2) {
break;
}
}
fos.close();
runOperationOnTT("suspend");
}
private void startTaskTrackers() throws Exception {
LOG.info(new Date() + " Resuming the stopped trackers");
runOperationOnTT("resume");
new File(slavesFile).delete();
}
private void runOperationOnTT(String operation) throws IOException {
Map<String,String> hMap = new HashMap<String,String>();
hMap.put("HADOOP_SLAVES", slavesFile);
StringTokenizer strToken;
if (operation.equals("suspend")) {
strToken = new StringTokenizer(STOP_COMMAND, " ");
} else {
strToken = new StringTokenizer(RESUME_COMMAND, " ");
}
String commandArgs[] = new String[strToken.countTokens() + 1];
int i = 0;
commandArgs[i++] = shellCommand;
while (strToken.hasMoreTokens()) {
commandArgs[i++] = strToken.nextToken();
}
String output = Shell.execCommand(hMap, commandArgs);
if (output != null && !output.equals("")) {
LOG.info(output);
}
}
private String convertTrackerNameToHostName(String trackerName) {
// Convert the trackerName to it's host name
int indexOfColon = trackerName.indexOf(":");
String trackerHostName = (indexOfColon == -1) ?
trackerName :
trackerName.substring(0, indexOfColon);
return trackerHostName.substring("tracker_".length());
}
}
private class KillTaskThread extends Thread {
private volatile boolean killed = false;
private RunningJob rJob;
private JobClient jc;
final private int thresholdMultiplier;
private float threshold = 0.2f;
private boolean onlyMapsProgress;
private int numIterations;
public KillTaskThread(JobClient jc, int thresholdMultiplier,
float threshold, boolean onlyMapsProgress, int numIterations) {
this.jc = jc;
this.thresholdMultiplier = thresholdMultiplier;
this.threshold = threshold;
this.onlyMapsProgress = onlyMapsProgress;
this.numIterations = numIterations;
setDaemon(true);
}
public void setRunningJob(RunningJob rJob) {
this.rJob = rJob;
}
public void kill() {
killed = true;
}
public void run() {
killBasedOnProgress(true);
if (!onlyMapsProgress) {
killBasedOnProgress(false);
}
}
private void killBasedOnProgress(boolean considerMaps) {
boolean fail = false;
if (considerMaps) {
LOG.info("Will kill tasks based on Maps' progress");
} else {
LOG.info("Will kill tasks based on Reduces' progress");
}
LOG.info("Initial progress threshold: " + threshold +
". Threshold Multiplier: " + thresholdMultiplier +
". Number of iterations: " + numIterations);
float thresholdVal = threshold;
int numIterationsDone = 0;
while (!killed) {
try {
float progress;
if (jc.getJob(rJob.getID()).isComplete() ||
numIterationsDone == numIterations) {
break;
}
if (considerMaps) {
progress = jc.getJob(rJob.getID()).mapProgress();
} else {
progress = jc.getJob(rJob.getID()).reduceProgress();
}
if (progress >= thresholdVal) {
numIterationsDone++;
if (numIterationsDone > 0 && numIterationsDone % 2 == 0) {
fail = true; //fail tasks instead of kill
}
ClusterStatus c = jc.getClusterStatus();
LOG.info(new Date() + " Killing a few tasks");
Collection<TaskAttemptID> runningTasks =
new ArrayList<TaskAttemptID>();
TaskReport mapReports[] = jc.getMapTaskReports(rJob.getID());
for (TaskReport mapReport : mapReports) {
if (mapReport.getCurrentStatus() == TIPStatus.RUNNING) {
runningTasks.addAll(mapReport.getRunningTaskAttempts());
}
}
if (runningTasks.size() > c.getTaskTrackers()/2) {
int count = 0;
for (TaskAttemptID t : runningTasks) {
LOG.info(new Date() + " Killed task : " + t);
rJob.killTask(t, fail);
if (count++ > runningTasks.size()/2) { //kill 50%
break;
}
}
}
runningTasks.clear();
TaskReport reduceReports[] = jc.getReduceTaskReports(rJob.getID());
for (TaskReport reduceReport : reduceReports) {
if (reduceReport.getCurrentStatus() == TIPStatus.RUNNING) {
runningTasks.addAll(reduceReport.getRunningTaskAttempts());
}
}
if (runningTasks.size() > c.getTaskTrackers()/2) {
int count = 0;
for (TaskAttemptID t : runningTasks) {
LOG.info(new Date() + " Killed task : " + t);
rJob.killTask(t, fail);
if (count++ > runningTasks.size()/2) { //kill 50%
break;
}
}
}
thresholdVal = thresholdVal * thresholdMultiplier;
}
Thread.sleep(5000);
} catch (InterruptedException ie) {
killed = true;
} catch (Exception e) {
LOG.fatal(StringUtils.stringifyException(e));
}
}
}
}
public static void main(String args[]) throws Exception {
int res = ToolRunner.run(new Configuration(), new ReliabilityTest(), args);
System.exit(res);
}
} | shakamunyi/hadoop-20 | src/test/org/apache/hadoop/mapred/ReliabilityTest.java | Java | apache-2.0 | 18,910 |
package butterknife;
import android.view.View;
import butterknife.internal.ListenerClass;
import butterknife.internal.ListenerMethod;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static android.widget.AdapterView.OnItemSelectedListener;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
/**
* Bind a method to an {@link OnItemSelectedListener OnItemSelectedListener} on the view for each
* ID specified.
* <pre><code>
* {@literal @}OnItemSelected(R.id.example_list) void onItemSelected(int position) {
* Toast.makeText(this, "Selected position " + position + "!", Toast.LENGTH_SHORT).show();
* }
* </code></pre>
* Any number of parameters from
* {@link OnItemSelectedListener#onItemSelected(android.widget.AdapterView, android.view.View, int,
* long) onItemSelected} may be used on the method.
* <p>
* To bind to methods other than {@code onItemSelected}, specify a different {@code callback}.
* <pre><code>
* {@literal @}OnItemSelected(value = R.id.example_list, callback = NOTHING_SELECTED)
* void onNothingSelected() {
* Toast.makeText(this, "Nothing selected!", Toast.LENGTH_SHORT).show();
* }
* </code></pre>
*
* @see OnItemSelectedListener
*/
@Target(METHOD)
@Retention(CLASS)
@ListenerClass(
targetType = "android.widget.AdapterView<?>",
setter = "setOnItemSelectedListener",
type = "android.widget.AdapterView.OnItemSelectedListener",
callbacks = OnItemSelected.Callback.class
)
public @interface OnItemSelected {
/** View IDs to which the method will be bound. */
int[] value() default { View.NO_ID };
/** Listener callback to which the method will be bound. */
Callback callback() default Callback.ITEM_SELECTED;
/** {@link OnItemSelectedListener} callback methods. */
enum Callback {
/**
* {@link OnItemSelectedListener#onItemSelected(android.widget.AdapterView, android.view.View,
* int, long)}
*/
@ListenerMethod(
name = "onItemSelected",
parameters = {
"android.widget.AdapterView<?>",
"android.view.View",
"int",
"long"
}
)
ITEM_SELECTED,
/** {@link OnItemSelectedListener#onNothingSelected(android.widget.AdapterView)} */
@ListenerMethod(
name = "onNothingSelected",
parameters = "android.widget.AdapterView<?>"
)
NOTHING_SELECTED
}
}
| carollynn2253/butterknife | butterknife/src/main/java/butterknife/OnItemSelected.java | Java | apache-2.0 | 2,447 |
/*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
* @bug 4959409
* @author Naoto Sato
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class bug4959409 extends javax.swing.JApplet {
public void init() {
new TestFrame();
}
}
class TestFrame extends JFrame implements KeyListener {
JTextField text;
JLabel label;
TestFrame () {
text = new JTextField();
text.addKeyListener(this);
label = new JLabel(" ");
Container c = getContentPane();
BorderLayout borderLayout1 = new BorderLayout();
c.setLayout(borderLayout1);
c.add(text, BorderLayout.CENTER);
c.add(label, BorderLayout.SOUTH);
setSize(300, 200);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
int mods = e.getModifiers();
if (code == '1' && mods == KeyEvent.SHIFT_MASK) {
label.setText("KEYPRESS received for Shift+1");
} else {
label.setText(" ");
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
| rokn/Count_Words_2015 | testing/openjdk2/jdk/test/java/awt/im/4959409/bug4959409.java | Java | mit | 2,168 |
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
package de.appplant.cordova.plugin.localnotification;
import de.appplant.cordova.plugin.notification.Builder;
import de.appplant.cordova.plugin.notification.Notification;
import de.appplant.cordova.plugin.notification.TriggerReceiver;
/**
* The receiver activity is triggered when a notification is clicked by a user.
* The activity calls the background callback and brings the launch intent
* up to foreground.
*/
public class ClickActivity extends de.appplant.cordova.plugin.notification.ClickActivity {
/**
* Called when local notification was clicked by the user.
*
* @param notification
* Wrapper around the local notification
*/
@Override
public void onClick(Notification notification) {
LocalNotification.fireEvent("click", notification);
if (!notification.getOptions().isOngoing()) {
String event = notification.isRepeating() ? "clear" : "cancel";
LocalNotification.fireEvent(event, notification);
}
super.onClick(notification);
}
/**
* Build notification specified by options.
*
* @param builder
* Notification builder
*/
@Override
public Notification buildNotification (Builder builder) {
return builder
.setTriggerReceiver(TriggerReceiver.class)
.build();
}
}
| ElieSauveterre/cordova-plugin-local-notifications | src/android/ClickActivity.java | Java | apache-2.0 | 2,346 |
public enum A {
;
A(String s){}
} | asedunov/intellij-community | java/java-tests/testData/refactoring/moveMembers/enumConstant/before/A.java | Java | apache-2.0 | 37 |
class A {
public void f() {
Inner i = new Inner();
i.doStuff();
}
private class <caret>Inner {
public void doStuff() {
}
}
} | asedunov/intellij-community | java/java-tests/testData/refactoring/inlineToAnonymousClass/NoInlineMethodUsage.java | Java | apache-2.0 | 173 |
class MyException extends RuntimeException{}
class MyClass {
public void foo() throws MyException {
throw new MyException();<caret>
}
} | asedunov/intellij-community | java/java-tests/testData/codeInsight/completion/smartType/ExceptionTwice-out.java | Java | apache-2.0 | 139 |
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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 ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
public class ReadRecInd extends GenericPdu {
/**
* Constructor, used when composing a M-ReadRec.ind pdu.
*
* @param from the from value
* @param messageId the message ID value
* @param mmsVersion current viersion of mms
* @param readStatus the read status value
* @param to the to value
* @throws InvalidHeaderValueException if parameters are invalid.
* NullPointerException if messageId or to is null.
*/
public ReadRecInd(EncodedStringValue from,
byte[] messageId,
int mmsVersion,
int readStatus,
EncodedStringValue[] to) throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_READ_REC_IND);
setFrom(from);
setMessageId(messageId);
setMmsVersion(mmsVersion);
setTo(to);
setReadStatus(readStatus);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
ReadRecInd(PduHeaders headers) {
super(headers);
}
/**
* Get Date value.
*
* @return the value
*/
public long getDate() {
return mPduHeaders.getLongInteger(PduHeaders.DATE);
}
/**
* Set Date value.
*
* @param value the value
*/
public void setDate(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.DATE);
}
/**
* Get Message-ID value.
*
* @return the value
*/
public byte[] getMessageId() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID);
}
/**
* Set Message-ID value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setMessageId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID);
}
/**
* Get To value.
*
* @return the value
*/
public EncodedStringValue[] getTo() {
return mPduHeaders.getEncodedStringValues(PduHeaders.TO);
}
/**
* Set To value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTo(EncodedStringValue[] value) {
mPduHeaders.setEncodedStringValues(value, PduHeaders.TO);
}
/**
* Get X-MMS-Read-status value.
*
* @return the value
*/
public int getReadStatus() {
return mPduHeaders.getOctet(PduHeaders.READ_STATUS);
}
/**
* Set X-MMS-Read-status value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setReadStatus(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.READ_STATUS);
}
/*
* Optional, not supported header fields:
*
* public byte[] getApplicId() {return null;}
* public void setApplicId(byte[] value) {}
*
* public byte[] getAuxApplicId() {return null;}
* public void getAuxApplicId(byte[] value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*/
}
| jodson/TextSecure | src/ws/com/google/android/mms/pdu/ReadRecInd.java | Java | gpl-3.0 | 4,014 |
/**
* 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.camel.processor;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @version
*/
public class RedeliveryOnExceptionBlockedDelayTest extends ContextTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(RedeliveryOnExceptionBlockedDelayTest.class);
private static volatile int attempt;
public void testRedelivery() throws Exception {
MockEndpoint before = getMockEndpoint("mock:result");
before.expectedBodiesReceived("Hello World", "Hello Camel");
// we use blocked redelivery delay so the messages arrive in the same order
MockEndpoint result = getMockEndpoint("mock:result");
result.expectedBodiesReceived("Hello World", "Hello Camel");
template.sendBody("seda:start", "World");
template.sendBody("seda:start", "Camel");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// will by default block
onException(IllegalArgumentException.class)
.maximumRedeliveries(5).redeliveryDelay(2000);
from("seda:start")
.to("log:before")
.to("mock:before")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
LOG.info("Processing at attempt " + attempt + " " + exchange);
String body = exchange.getIn().getBody(String.class);
if (body.contains("World")) {
if (++attempt <= 2) {
LOG.info("Processing failed will thrown an exception");
throw new IllegalArgumentException("Damn");
}
}
exchange.getIn().setBody("Hello " + body);
LOG.info("Processing at attempt " + attempt + " complete " + exchange);
}
})
.to("log:after")
.to("mock:result");
}
};
}
}
| mohanaraosv/camel | camel-core/src/test/java/org/apache/camel/processor/RedeliveryOnExceptionBlockedDelayTest.java | Java | apache-2.0 | 3,369 |
/**
* 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.camel.processor;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
public class RemoveHeadersTest extends ContextTestSupport {
public void testRemoveHeadersWildcard() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:end");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("duck", "Donald");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("dudeCool", "cool");
headers.put("dudeWicket", "wicket");
headers.put("duck", "Donald");
headers.put("foo", "bar");
template.sendBodyAndHeaders("direct:start", "Hello World", headers);
assertMockEndpointsSatisfied();
// breadcrumb is a header added as well so we expect 2
assertEquals(2, mock.getReceivedExchanges().get(0).getIn().getHeaders().size());
}
public void testRemoveHeadersRegEx() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:end");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("duck", "Donald");
mock.expectedHeaderReceived("BeerHeineken", "Good");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("dudeCool", "cool");
headers.put("dudeWicket", "wicket");
headers.put("duck", "Donald");
headers.put("BeerCarlsberg", "Great");
headers.put("BeerTuborg", "Also Great");
headers.put("BeerHeineken", "Good");
template.sendBodyAndHeaders("direct:start", "Hello World", headers);
assertMockEndpointsSatisfied();
// breadcrumb is a header added as well so we expect 3
assertEquals(3, mock.getReceivedExchanges().get(0).getIn().getHeaders().size());
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start")
.removeHeaders("dude*")
.removeHeaders("Beer(Carlsberg|Tuborg)")
.removeHeaders("foo")
.to("mock:end");
}
};
}
} | coderczp/camel | camel-core/src/test/java/org/apache/camel/processor/RemoveHeadersTest.java | Java | apache-2.0 | 3,108 |
/**
* 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.camel.processor.aggregator;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.processor.aggregate.AggregateController;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.apache.camel.processor.aggregate.DefaultAggregateController;
import org.junit.Test;
/**
*
*/
public class AggregateControllerTest extends ContextTestSupport {
private AggregateController controller;
public AggregateController getAggregateController() {
if (controller == null) {
controller = new DefaultAggregateController();
}
return controller;
}
@Test
public void testForceCompletionOfAll() throws Exception {
getMockEndpoint("mock:aggregated").expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "test1", "id", "1");
template.sendBodyAndHeader("direct:start", "test2", "id", "2");
template.sendBodyAndHeader("direct:start", "test3", "id", "1");
template.sendBodyAndHeader("direct:start", "test4", "id", "2");
assertMockEndpointsSatisfied();
getMockEndpoint("mock:aggregated").expectedMessageCount(2);
getMockEndpoint("mock:aggregated").expectedBodiesReceivedInAnyOrder("test1test3", "test2test4");
getMockEndpoint("mock:aggregated").expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, "force");
int groups = getAggregateController().forceCompletionOfAllGroups();
assertEquals(2, groups);
assertMockEndpointsSatisfied();
}
@Test
public void testForceCompletionOfGroup() throws Exception {
getMockEndpoint("mock:aggregated").expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "test1", "id", "1");
template.sendBodyAndHeader("direct:start", "test2", "id", "2");
template.sendBodyAndHeader("direct:start", "test3", "id", "1");
template.sendBodyAndHeader("direct:start", "test4", "id", "2");
assertMockEndpointsSatisfied();
getMockEndpoint("mock:aggregated").expectedMessageCount(1);
getMockEndpoint("mock:aggregated").expectedBodiesReceivedInAnyOrder("test1test3");
getMockEndpoint("mock:aggregated").expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, "force");
int groups = getAggregateController().forceCompletionOfGroup("1");
assertEquals(1, groups);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.aggregate(header("id"), new MyAggregationStrategy()).aggregateController(getAggregateController())
.completionSize(10)
.to("mock:aggregated");
}
};
}
public static class MyAggregationStrategy implements AggregationStrategy {
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
String body1 = oldExchange.getIn().getBody(String.class);
String body2 = newExchange.getIn().getBody(String.class);
oldExchange.getIn().setBody(body1 + body2);
return oldExchange;
}
}
} | CandleCandle/camel | camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateControllerTest.java | Java | apache-2.0 | 4,309 |
/**
* 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.camel.dataformat.univocity;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* This class tests the options of {@link org.apache.camel.dataformat.univocity.UniVocityCsvDataFormat}.
*/
public final class UniVocityCsvDataFormatTest {
@Test
public void shouldConfigureNullValue() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setNullValue("N/A");
assertEquals("N/A", dataFormat.getNullValue());
assertEquals("N/A", dataFormat.createAndConfigureWriterSettings().getNullValue());
assertEquals("N/A", dataFormat.createAndConfigureParserSettings().getNullValue());
}
@Test
public void shouldConfigureSkipEmptyLines() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setSkipEmptyLines(true);
assertTrue(dataFormat.getSkipEmptyLines());
assertTrue(dataFormat.createAndConfigureWriterSettings().getSkipEmptyLines());
assertTrue(dataFormat.createAndConfigureParserSettings().getSkipEmptyLines());
}
@Test
public void shouldConfigureIgnoreTrailingWhitespaces() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setIgnoreTrailingWhitespaces(true);
assertTrue(dataFormat.getIgnoreTrailingWhitespaces());
assertTrue(dataFormat.createAndConfigureWriterSettings().getIgnoreTrailingWhitespaces());
assertTrue(dataFormat.createAndConfigureParserSettings().getIgnoreTrailingWhitespaces());
}
@Test
public void shouldConfigureIgnoreLeadingWhitespaces() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setIgnoreLeadingWhitespaces(true);
assertTrue(dataFormat.getIgnoreLeadingWhitespaces());
assertTrue(dataFormat.createAndConfigureWriterSettings().getIgnoreLeadingWhitespaces());
assertTrue(dataFormat.createAndConfigureParserSettings().getIgnoreLeadingWhitespaces());
}
@Test
public void shouldConfigureHeadersDisabled() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setHeadersDisabled(true);
assertTrue(dataFormat.isHeadersDisabled());
assertNull(dataFormat.createAndConfigureWriterSettings().getHeaders());
assertNull(dataFormat.createAndConfigureParserSettings().getHeaders());
}
@Test
public void shouldConfigureHeaders() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setHeaders(new String[]{"A", "B", "C"});
assertArrayEquals(new String[]{"A", "B", "C"}, dataFormat.getHeaders());
assertArrayEquals(new String[]{"A", "B", "C"}, dataFormat.createAndConfigureWriterSettings().getHeaders());
assertArrayEquals(new String[]{"A", "B", "C"}, dataFormat.createAndConfigureParserSettings().getHeaders());
}
@Test
public void shouldConfigureHeaderExtractionEnabled() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setHeaderExtractionEnabled(true);
assertTrue(dataFormat.getHeaderExtractionEnabled());
assertTrue(dataFormat.createAndConfigureParserSettings().isHeaderExtractionEnabled());
}
@Test
public void shouldConfigureNumberOfRecordsToRead() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setNumberOfRecordsToRead(42);
assertEquals(Integer.valueOf(42), dataFormat.getNumberOfRecordsToRead());
assertEquals(42, dataFormat.createAndConfigureParserSettings().getNumberOfRecordsToRead());
}
@Test
public void shouldConfigureEmptyValue() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setEmptyValue("empty");
assertEquals("empty", dataFormat.getEmptyValue());
assertEquals("empty", dataFormat.createAndConfigureWriterSettings().getEmptyValue());
assertEquals("empty", dataFormat.createAndConfigureParserSettings().getEmptyValue());
}
@Test
public void shouldConfigureLineSeparator() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setLineSeparator("ls");
assertEquals("ls", dataFormat.getLineSeparator());
assertEquals("ls", dataFormat.createAndConfigureWriterSettings().getFormat().getLineSeparatorString());
assertEquals("ls", dataFormat.createAndConfigureParserSettings().getFormat().getLineSeparatorString());
}
@Test
public void shouldConfigureNormalizedLineSeparator() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setNormalizedLineSeparator('n');
assertEquals(Character.valueOf('n'), dataFormat.getNormalizedLineSeparator());
assertEquals('n', dataFormat.createAndConfigureWriterSettings().getFormat().getNormalizedNewline());
assertEquals('n', dataFormat.createAndConfigureParserSettings().getFormat().getNormalizedNewline());
}
@Test
public void shouldConfigureComment() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setComment('c');
assertEquals(Character.valueOf('c'), dataFormat.getComment());
assertEquals('c', dataFormat.createAndConfigureWriterSettings().getFormat().getComment());
assertEquals('c', dataFormat.createAndConfigureParserSettings().getFormat().getComment());
}
@Test
public void shouldConfigureLazyLoad() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setLazyLoad(true);
assertTrue(dataFormat.isLazyLoad());
}
@Test
public void shouldConfigureAsMap() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setAsMap(true);
assertTrue(dataFormat.isAsMap());
}
@Test
public void shouldConfigureQuoteAllFields() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setQuoteAllFields(true);
assertTrue(dataFormat.getQuoteAllFields());
assertTrue(dataFormat.createAndConfigureWriterSettings().getQuoteAllFields());
}
@Test
public void shouldConfigureQuote() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setQuote('q');
assertEquals(Character.valueOf('q'), dataFormat.getQuote());
assertEquals('q', dataFormat.createAndConfigureWriterSettings().getFormat().getQuote());
assertEquals('q', dataFormat.createAndConfigureParserSettings().getFormat().getQuote());
}
@Test
public void shouldConfigureQuoteEscape() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setQuoteEscape('e');
assertEquals(Character.valueOf('e'), dataFormat.getQuoteEscape());
assertEquals('e', dataFormat.createAndConfigureWriterSettings().getFormat().getQuoteEscape());
assertEquals('e', dataFormat.createAndConfigureParserSettings().getFormat().getQuoteEscape());
}
@Test
public void shouldConfigureDelimiter() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setDelimiter('d');
assertEquals(Character.valueOf('d'), dataFormat.getDelimiter());
assertEquals('d', dataFormat.createAndConfigureWriterSettings().getFormat().getDelimiter());
assertEquals('d', dataFormat.createAndConfigureParserSettings().getFormat().getDelimiter());
}
}
| YMartsynkevych/camel | components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatTest.java | Java | apache-2.0 | 8,709 |
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.datasource;
/**
* Base implementation of {@link DataSubscriber} that ensures that the data source is closed when
* the subscriber has finished with it.
* <p>
* Sample usage:
* <pre>
* <code>
* dataSource.subscribe(
* new BaseDataSubscriber() {
* {@literal @}Override
* public void onNewResultImpl(DataSource dataSource) {
* // Store image ref to be released later.
* mCloseableImageRef = dataSource.getResult();
* // Use the image.
* updateImage(mCloseableImageRef);
* // No need to do any cleanup of the data source.
* }
*
* {@literal @}Override
* public void onFailureImpl(DataSource dataSource) {
* // No cleanup of the data source required here.
* }
* });
* </code>
* </pre>
*/
public abstract class BaseDataSubscriber<T> implements DataSubscriber<T> {
@Override
public void onNewResult(DataSource<T> dataSource) {
try {
onNewResultImpl(dataSource);
} finally {
if (dataSource.isFinished()) {
dataSource.close();
}
}
}
@Override
public void onFailure(DataSource<T> dataSource) {
try {
onFailureImpl(dataSource);
} finally {
dataSource.close();
}
}
@Override
public void onCancellation(DataSource<T> dataSource) {
}
@Override
public void onProgressUpdate(DataSource<T> dataSource) {
}
protected abstract void onNewResultImpl(DataSource<T> dataSource);
protected abstract void onFailureImpl(DataSource<T> dataSource);
}
| ppamorim/fresco | fbcore/src/main/java/com/facebook/datasource/BaseDataSubscriber.java | Java | bsd-3-clause | 1,838 |
/*
* Copyright (C) 2009,2010,2011,2012 Samuel Audet
*
* This file is part of JavaCV.
*
* JavaCV 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 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* JavaCV 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 JavaCV. If not, see <http://www.gnu.org/licenses/>.
*/
package com.googlecode.javacv;
import static com.googlecode.javacv.cpp.cvkernels.*;
import static com.googlecode.javacv.cpp.opencv_calib3d.*;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
/**
*
* @author Samuel Audet
*/
public class ProCamTransformer implements ImageTransformer {
public ProCamTransformer(double[] referencePoints,
CameraDevice camera, ProjectorDevice projector) {
this(referencePoints, camera, projector, null);
}
public ProCamTransformer(double[] referencePoints,
CameraDevice camera, ProjectorDevice projector, CvMat n) {
this.camera = camera;
this.projector = projector;
if (referencePoints != null) {
this.surfaceTransformer = new ProjectiveColorTransformer(
camera.cameraMatrix, camera.cameraMatrix, null, null, n,
referencePoints, null, null, 3, 0);
}
double[] referencePoints1 = { 0, 0, camera.imageWidth/2, camera.imageHeight, camera.imageWidth, 0 };
double[] referencePoints2 = { 0, 0, projector.imageWidth/2, projector.imageHeight, projector.imageWidth, 0 };
if (n != null) {
invCameraMatrix = CvMat.create(3, 3);
cvInvert(camera.cameraMatrix, invCameraMatrix);
JavaCV.perspectiveTransform(referencePoints2, referencePoints1,
invCameraMatrix, projector.cameraMatrix, projector.R, projector.T, n, true);
}
this.projectorTransformer = new ProjectiveColorTransformer(
camera.cameraMatrix, projector.cameraMatrix, projector.R, projector.T, null,
referencePoints1, referencePoints2, projector.colorMixingMatrix,
/*surfaceTransformer == null ? 3 : */1, 3);
// CvMat n2 = createParameters().getN();
if (referencePoints != null && n != null) {
frontoParallelH = camera.getFrontoParallelH(referencePoints, n, CvMat.create(3, 3));
invFrontoParallelH = frontoParallelH.clone();
cvInvert(frontoParallelH, invFrontoParallelH);
}
}
protected CameraDevice camera = null;
protected ProjectorDevice projector = null;
protected ProjectiveColorTransformer surfaceTransformer = null;
protected ProjectiveColorTransformer projectorTransformer = null;
protected IplImage[] projectorImage = null, surfaceImage = null;
protected CvScalar fillColor = cvScalar(0.0, 0.0, 0.0, 1.0);
protected CvRect roi = new CvRect();
protected CvMat frontoParallelH = null, invFrontoParallelH = null;
protected CvMat invCameraMatrix = null;
protected KernelData kernelData = null;
protected CvMat[] H1 = null;
protected CvMat[] H2 = null;
protected CvMat[] X = null;
public int getNumGains() {
return projectorTransformer.getNumGains();
}
public int getNumBiases() {
return projectorTransformer.getNumBiases();
}
public CvScalar getFillColor() {
return fillColor;
}
public void setFillColor(CvScalar fillColor) {
this.fillColor = fillColor;
}
public ProjectiveColorTransformer getSurfaceTransformer() {
return surfaceTransformer;
}
public ProjectiveColorTransformer getProjectorTransformer() {
return projectorTransformer;
}
public IplImage getProjectorImage(int pyramidLevel) {
return projectorImage[pyramidLevel];
}
public void setProjectorImage(IplImage projectorImage0, int minLevel, int maxLevel) {
setProjectorImage(projectorImage0, minLevel, maxLevel, true);
}
public void setProjectorImage(IplImage projectorImage0, int minLevel, int maxLevel, boolean convertToFloat) {
if (projectorImage == null || projectorImage.length != maxLevel+1) {
projectorImage = new IplImage[maxLevel+1];
}
if (projectorImage0.depth() == IPL_DEPTH_32F || !convertToFloat) {
projectorImage[minLevel] = projectorImage0;
} else {
if (projectorImage[minLevel] == null) {
projectorImage[minLevel] = IplImage.create(projectorImage0.width(), projectorImage0.height(),
IPL_DEPTH_32F, projectorImage0.nChannels(), projectorImage0.origin());
}
IplROI ir = projectorImage0.roi();
if (ir != null) {
int align = 1<<(maxLevel+1);
roi.x(Math.max(0, (int)Math.floor((double)ir.xOffset()/align)*align));
roi.y(Math.max(0, (int)Math.floor((double)ir.yOffset()/align)*align));
roi.width (Math.min(projectorImage0.width(), (int)Math.ceil((double)ir.width() /align)*align));
roi.height(Math.min(projectorImage0.height(), (int)Math.ceil((double)ir.height()/align)*align));
cvSetImageROI(projectorImage0, roi);
cvSetImageROI(projectorImage[minLevel], roi);
} else {
cvResetImageROI(projectorImage0);
cvResetImageROI(projectorImage[minLevel]);
}
cvConvertScale(projectorImage0, projectorImage[minLevel], 1.0/255.0, 0);
}
// CvScalar.ByValue average = cvAvg(projectorImage[0], null);
// cvSubS(projectorImage[0], average, projectorImage[0], null);
for (int i = minLevel+1; i <= maxLevel; i++) {
int w = projectorImage[i-1].width()/2;
int h = projectorImage[i-1].height()/2;
int d = projectorImage[i-1].depth();
int c = projectorImage[i-1].nChannels();
int o = projectorImage[i-1].origin();
if (projectorImage[i] == null) {
projectorImage[i] = IplImage.create(w, h, d, c, o);
}
IplROI ir = projectorImage[i-1].roi();
if (ir != null) {
roi.x(ir.xOffset()/2); roi.width (ir.width() /2);
roi.y(ir.yOffset()/2); roi.height(ir.height()/2);
cvSetImageROI(projectorImage[i], roi);
} else {
cvResetImageROI(projectorImage[i]);
}
cvPyrDown(projectorImage[i-1], projectorImage[i], CV_GAUSSIAN_5x5);
cvResetImageROI(projectorImage[i-1]);
}
}
public IplImage getSurfaceImage(int pyramidLevel) {
return surfaceImage[pyramidLevel];
}
public void setSurfaceImage(IplImage surfaceImage0, int pyramidLevels) {
if (surfaceImage == null || surfaceImage.length != pyramidLevels) {
surfaceImage = new IplImage[pyramidLevels];
}
surfaceImage[0] = surfaceImage0;
cvResetImageROI(surfaceImage0);
for (int i = 1; i < pyramidLevels; i++) {
int w = surfaceImage[i-1].width()/2;
int h = surfaceImage[i-1].height()/2;
int d = surfaceImage[i-1].depth();
int c = surfaceImage[i-1].nChannels();
int o = surfaceImage[i-1].origin();
if (surfaceImage[i] == null) {
surfaceImage[i] = IplImage.create(w, h, d, c, o);
} else {
cvResetImageROI(surfaceImage[i]);
}
cvPyrDown(surfaceImage[i-1], surfaceImage[i], CV_GAUSSIAN_5x5);
}
}
protected void prepareTransforms(CvMat H1, CvMat H2, CvMat X, int pyramidLevel, Parameters p) {
ProjectiveColorTransformer.Parameters cameraParameters = p.getSurfaceParameters();
ProjectiveColorTransformer.Parameters projectorParameters = p.getProjectorParameters();
if (surfaceTransformer != null) {
cvInvert(cameraParameters.getH(), H1);
}
cvInvert(projectorParameters.getH(), H2);
// adjust the scale of the transformation based on the pyramid level
if (pyramidLevel > 0) {
int scale = 1<<pyramidLevel;
if (surfaceTransformer != null) {
H1.put(2, H1.get(2)/scale);
H1.put(5, H1.get(5)/scale);
H1.put(6, H1.get(6)*scale);
H1.put(7, H1.get(7)*scale);
}
H2.put(2, H2.get(2)/scale);
H2.put(5, H2.get(5)/scale);
H2.put(6, H2.get(6)*scale);
H2.put(7, H2.get(7)*scale);
}
double[] x = projector.colorMixingMatrix.get();
double[] a = projectorParameters.getColorParameters();
double a2 = a[0];
X.put(a2*x[0], a2*x[1], a2*x[2], a[1],
a2*x[3], a2*x[4], a2*x[5], a[2],
a2*x[6], a2*x[7], a2*x[8], a[3],
0, 0, 0, 1);
}
public void transform(final IplImage srcImage, final IplImage dstImage, final CvRect roi,
final int pyramidLevel, final ImageTransformer.Parameters parameters, final boolean inverse) {
if (inverse) {
throw new UnsupportedOperationException("Inverse transform not supported.");
}
final Parameters p = ((Parameters)parameters);
final ProjectiveTransformer.Parameters cameraParameters = p.getSurfaceParameters();
final ProjectiveTransformer.Parameters projectorParameters = p.getProjectorParameters();
if (p.tempImage == null || p.tempImage.length <= pyramidLevel) {
p.tempImage = new IplImage[pyramidLevel+1];
}
p.tempImage[pyramidLevel] = IplImage.createIfNotCompatible(p.tempImage[pyramidLevel], dstImage);
if (roi == null) {
cvResetImageROI(p.tempImage[pyramidLevel]);
} else {
cvSetImageROI(p.tempImage[pyramidLevel], roi);
}
// Parallel.run(new Runnable() { public void run() {
// warp the template image
if (surfaceTransformer != null) {
surfaceTransformer.transform(srcImage, p.tempImage[pyramidLevel], roi, pyramidLevel, cameraParameters, false);
}
// }}, new Runnable() { public void run() {
// warp the projector image
projectorTransformer.transform(projectorImage[pyramidLevel], dstImage, roi, pyramidLevel, projectorParameters, false);
// }});
// multiply projector image with template image
if (surfaceTransformer != null) {
cvMul(dstImage, p.tempImage[pyramidLevel], dstImage, 1/dstImage.highValue());
} else {
cvCopy(p.tempImage[pyramidLevel], dstImage);
}
}
public void transform(CvMat srcPts, CvMat dstPts, ImageTransformer.Parameters parameters, boolean inverse) {
if (surfaceTransformer != null) {
surfaceTransformer.transform(srcPts, dstPts, ((Parameters)parameters).surfaceParameters, inverse);
} else if (dstPts != srcPts) {
dstPts.put(srcPts);
}
}
public void transform(Data[] data, CvRect roi, ImageTransformer.Parameters[] parameters, boolean[] inverses) {
assert data.length == parameters.length;
if (kernelData == null || kernelData.capacity() < data.length) {
kernelData = new KernelData(data.length);
}
if ((H1 == null || H1.length < data.length) && surfaceTransformer != null) {
H1 = new CvMat[data.length];
for (int i = 0; i < H1.length; i++) {
H1[i] = CvMat.create(3, 3);
}
}
if (H2 == null || H2.length < data.length) {
H2 = new CvMat[data.length];
for (int i = 0; i < H2.length; i++) {
H2[i] = CvMat.create(3, 3);
}
}
if (X == null || X.length < data.length) {
X = new CvMat[data.length];
for (int i = 0; i < X.length; i++) {
X[i] = CvMat.create(4, 4);
}
}
for (int i = 0; i < data.length; i++) {
kernelData.position(i);
kernelData.srcImg(projectorImage[data[i].pyramidLevel]);
kernelData.srcImg2(surfaceTransformer == null ? null : data[i].srcImg);
kernelData.subImg(data[i].subImg);
kernelData.srcDotImg(data[i].srcDotImg);
kernelData.mask(data[i].mask);
kernelData.zeroThreshold(data[i].zeroThreshold);
kernelData.outlierThreshold(data[i].outlierThreshold);
if (inverses != null && inverses[i]) {
throw new UnsupportedOperationException("Inverse transform not supported.");
}
prepareTransforms(surfaceTransformer == null ? null : H1[i],
H2[i], X[i], data[i].pyramidLevel, (Parameters)parameters[i]);
kernelData.H1(H2[i]);
kernelData.H2(surfaceTransformer == null ? null : H1[i]);
kernelData.X (X [i]);
kernelData.transImg(data[i].transImg);
kernelData.dstImg(data[i].dstImg);
kernelData.dstDstDot(data[i].dstDstDot);
}
int fullCapacity = kernelData.capacity();
kernelData.capacity(data.length);
multiWarpColorTransform(kernelData, roi, getFillColor());
kernelData.capacity(fullCapacity);
for (int i = 0; i < data.length; i++) {
kernelData.position(i);
data[i].dstCount = kernelData.dstCount();
data[i].dstCountZero = kernelData.dstCountZero();
data[i].dstCountOutlier = kernelData.dstCountOutlier();
data[i].srcDstDot = kernelData.srcDstDot();
}
// if (data[0].dstCountZero > 0) {
// System.err.println(data[0].dstCountZero + " out of " + data[0].dstCount
// + " are zero = " + 100*data[0].dstCountZero/data[0].dstCount + "%");
// }
}
public Parameters createParameters() {
return new Parameters();
}
public class Parameters implements ImageTransformer.Parameters {
protected Parameters() {
reset(false);
}
protected Parameters(ProjectiveColorTransformer.Parameters surfaceParameters,
ProjectiveColorTransformer.Parameters projectorParameters) {
reset(surfaceParameters, projectorParameters);
}
private ProjectiveColorTransformer.Parameters surfaceParameters = null;
private ProjectiveColorTransformer.Parameters projectorParameters = null;
private IplImage[] tempImage = null;
private CvMat H = CvMat.create(3, 3), R = CvMat.create(3, 3),
n = CvMat.create(3, 1), t = CvMat.create(3, 1);
public ProjectiveColorTransformer.Parameters getSurfaceParameters() {
return surfaceParameters;
}
public ProjectiveColorTransformer.Parameters getProjectorParameters() {
return projectorParameters;
}
private int getSizeForSurface() {
return surfaceTransformer == null ? 0 : surfaceParameters.size() -
surfaceTransformer.getNumGains() - surfaceTransformer.getNumBiases();
}
private int getSizeForProjector() {
return projectorParameters.size();
}
public int size() {
return getSizeForSurface() + getSizeForProjector();
}
public double[] get() {
double[] p = new double[size()];
for (int i = 0; i < p.length; i++) {
p[i] = get(i);
}
return p;
}
public double get(int i) {
if (i < getSizeForSurface()) {
return surfaceParameters.get(i);
} else {
return projectorParameters.get(i-getSizeForSurface());
}
}
public void set(double ... p) {
for (int i = 0; i < p.length; i++) {
set(i, p[i]);
}
}
public void set(int i, double p) {
if (i < getSizeForSurface()) {
surfaceParameters.set(i, p);
} else {
projectorParameters.set(i-getSizeForSurface(), p);
}
}
public void set(ImageTransformer.Parameters p) {
Parameters pcp = (Parameters)p;
if (surfaceTransformer != null) {
surfaceParameters.set(pcp.getSurfaceParameters());
surfaceParameters.resetColor(false);
}
projectorParameters.set(pcp.getProjectorParameters());
}
public void reset(boolean asIdentity) {
reset(null, null);
}
public void reset(ProjectiveColorTransformer.Parameters surfaceParameters,
ProjectiveColorTransformer.Parameters projectorParameters) {
if (surfaceParameters == null && surfaceTransformer != null) {
surfaceParameters = surfaceTransformer.createParameters();
}
if (projectorParameters == null) {
projectorParameters = projectorTransformer.createParameters();
}
this.surfaceParameters = surfaceParameters;
this.projectorParameters = projectorParameters;
setSubspace(getSubspace());
}
// public boolean addDelta(int i) {
// return addDelta(i, 1);
// }
// public boolean addDelta(int i, double scale) {
// // gradient varies linearly with intensity, so
// // the increment value is not very important, but
// // referenceCameraImage is good only for the value 1,
// // so let's use that
// if (i < getSizeForSurface()) {
// surfaceParameters.addDelta(i, scale);
// projectorParameters.setUpdateNeeded(true);
// } else {
// projectorParameters.addDelta(i-getSizeForSurface(), scale);
// }
//
// return false;
// }
public double getConstraintError() {
double error = surfaceTransformer == null ? 0 : surfaceParameters.getConstraintError();
projectorParameters.update();
return error;
}
public void compose(ImageTransformer.Parameters p1, boolean inverse1,
ImageTransformer.Parameters p2, boolean inverse2) {
throw new UnsupportedOperationException("Compose operation not supported.");
}
public boolean preoptimize() {
double[] p = setSubspaceInternal(getSubspaceInternal());
if (p != null) {
set(8, p[8]);
set(9, p[9]);
set(10, p[10]);
return true;
}
return false;
}
public void setSubspace(double ... p) {
double[] dst = setSubspaceInternal(p);
if (dst != null) {
set(dst);
}
}
public double[] getSubspace() {
return getSubspaceInternal();
}
private double[] setSubspaceInternal(double ... p) {
if (invFrontoParallelH == null) {
return null;
}
double[] dst = new double[8+3];
t.put(p[0], p[1], p[2]);
cvRodrigues2(t, R, null);
t.put(p[3], p[4], p[5]);
// compute new H
H.put(R.get(0), R.get(1), t.get(0),
R.get(3), R.get(4), t.get(1),
R.get(6), R.get(7), t.get(2));
cvMatMul(H, invFrontoParallelH, H);
cvMatMul(surfaceTransformer.getK2(), H, H);
cvMatMul(H, surfaceTransformer.getInvK1(), H);
// compute new n, rotation from the z-axis
cvGEMM(R, t, 1, null, 0, t, CV_GEMM_A_T);
double scale = 1/t.get(2);
n.put(0.0, 0.0, 1.0);
cvGEMM(R, n, scale, null, 0, n, 0);
// compute and set new three points
double[] src = projectorTransformer.getReferencePoints2();
JavaCV.perspectiveTransform(src, dst,
projectorTransformer.getInvK1(),projectorTransformer.getK2(),
projectorTransformer.getR(), projectorTransformer.getT(), n, true);
dst[8] = dst[0];
dst[9] = dst[2];
dst[10] = dst[4];
// compute and set new four points
JavaCV.perspectiveTransform(surfaceTransformer.getReferencePoints1(), dst, H);
return dst;
}
private double[] getSubspaceInternal() {
if (frontoParallelH == null) {
return null;
}
cvMatMul(surfaceTransformer.getK1(), frontoParallelH, H);
cvMatMul(surfaceParameters .getH(), H, H);
cvMatMul(surfaceTransformer.getInvK2(), H, H);
JavaCV.HtoRt(H, R, t);
cvRodrigues2(R, n, null);
double[] p = { n.get(0), n.get(1), n.get(2),
t.get(0), t.get(1), t.get(2) };
return p;
}
public CvMat getN() {
double[] src = projectorTransformer.getReferencePoints2();
double[] dst = projectorTransformer.getReferencePoints1().clone();
dst[0] = projectorParameters.get(0);
dst[2] = projectorParameters.get(1);
dst[4] = projectorParameters.get(2);
// get plane parameters n, but since we model the target to be
// the camera, we have to inverse everything before calling
// getPlaneParameters() and reframe the n it returns
cvTranspose(projectorTransformer.getR(), R);
cvGEMM(R, projectorTransformer.getT(), -1, null, 0, t, 0);
JavaCV.getPlaneParameters(src, dst, projectorTransformer.getInvK2(),
projectorTransformer.getK1(), R, t, n);
double d = 1 + cvDotProduct(n, projectorTransformer.getT());
cvGEMM(R, n, 1/d, null, 0, n, 0);
return n;
}
public CvMat getN0() {
n = getN();
if (surfaceTransformer == null) {
return n;
}
// remove projective effect of the current n,
// leaving only the effect of n0
camera.getFrontoParallelH(surfaceParameters.get(), n, R);
cvInvert(surfaceParameters.getH(), H);
cvMatMul(H, surfaceTransformer.getK2(), H);
cvMatMul(H, R, H);
cvMatMul(surfaceTransformer.getInvK1(), H, H);
JavaCV.HtoRt(H, R, t);
// compute n0, as a rotation from the z-axis
cvGEMM(R, t, 1, null, 0, t, CV_GEMM_A_T);
double scale = 1/t.get(2);
n.put(0.0, 0.0, 1.0);
cvGEMM(R, n, scale, null, 0, n, 0);
return n;
}
@Override public Parameters clone() {
Parameters p = new Parameters();
p.surfaceParameters = surfaceParameters == null ? null : surfaceParameters.clone();
p.projectorParameters = projectorParameters.clone();
return p;
}
@Override public String toString() {
if (surfaceParameters != null) {
return surfaceParameters.toString() + projectorParameters.toString();
} else {
return projectorParameters.toString();
}
}
}
}
| JanesR/javacv | src/main/java/com/googlecode/javacv/ProCamTransformer.java | Java | gpl-2.0 | 23,990 |
/**
* 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.camel.example;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Bar {
@XmlAttribute
private String name;
@XmlAttribute
private String value;
public Bar() {
}
public void setName(String name) {
this.name = name;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
| CandleCandle/camel | components/camel-jaxb/src/test/java/org/apache/camel/example/Bar.java | Java | apache-2.0 | 1,514 |
/* 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 java.nio;
import com.google.gwt.typedarrays.shared.ArrayBufferView;
import com.google.gwt.typedarrays.shared.Float32Array;
import com.google.gwt.typedarrays.shared.TypedArrays;
/** This class wraps a byte buffer to be a float buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the
* adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position
* and limit.</li>
* </ul>
* </p> */
final class DirectReadWriteFloatBufferAdapter extends FloatBuffer implements HasArrayBufferView {
// implements DirectBuffer {
static FloatBuffer wrap (DirectReadWriteByteBuffer byteBuffer) {
return new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice());
}
private final DirectReadWriteByteBuffer byteBuffer;
private final Float32Array floatArray;
DirectReadWriteFloatBufferAdapter (DirectReadWriteByteBuffer byteBuffer) {
super((byteBuffer.capacity() >> 2));
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
this.floatArray = TypedArrays.createFloat32Array(byteBuffer.byteArray.buffer(), byteBuffer.byteArray.byteOffset(), capacity);
}
// TODO(haustein) This will be slow
@Override
public FloatBuffer asReadOnlyBuffer () {
DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter(byteBuffer);
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public FloatBuffer compact () {
byteBuffer.limit(limit << 2);
byteBuffer.position(position << 2);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
@Override
public FloatBuffer duplicate () {
DirectReadWriteFloatBufferAdapter buf = new DirectReadWriteFloatBufferAdapter(
(DirectReadWriteByteBuffer)byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public float get () {
// if (position == limit) {
// throw new BufferUnderflowException();
// }
return floatArray.get(position++);
}
@Override
public float get (int index) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
return floatArray.get(index);
}
@Override
public boolean isDirect () {
return true;
}
@Override
public boolean isReadOnly () {
return false;
}
@Override
public ByteOrder order () {
return byteBuffer.order();
}
@Override
protected float[] protectedArray () {
throw new UnsupportedOperationException();
}
@Override
protected int protectedArrayOffset () {
throw new UnsupportedOperationException();
}
@Override
protected boolean protectedHasArray () {
return false;
}
@Override
public FloatBuffer put (float c) {
// if (position == limit) {
// throw new BufferOverflowException();
// }
floatArray.set(position++, c);
return this;
}
@Override
public FloatBuffer put (int index, float c) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
floatArray.set(index, c);
return this;
}
@Override
public FloatBuffer slice () {
byteBuffer.limit(limit << 2);
byteBuffer.position(position << 2);
FloatBuffer result = new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice());
byteBuffer.clear();
return result;
}
public ArrayBufferView getTypedArray () {
return floatArray;
}
public int getElementSize () {
return 4;
}
}
| nelsonsilva/libgdx | backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteFloatBufferAdapter.java | Java | apache-2.0 | 4,412 |
/*
* 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.
*/
/**
* Allows the execution of relational queries, including those expressed in SQL using Spark.
*/
package org.apache.spark.sql.api.java;
| esi-mineset/spark | sql/core/src/main/java/org/apache/spark/sql/api/java/package-info.java | Java | apache-2.0 | 942 |
/**
* 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.hadoop.oncrpc;
/**
* Represent an RPC message as defined in RFC 1831.
*/
public abstract class RpcMessage {
/** Message type */
public static enum Type {
// the order of the values below are significant.
RPC_CALL,
RPC_REPLY;
public int getValue() {
return ordinal();
}
public static Type fromValue(int value) {
if (value < 0 || value >= values().length) {
return null;
}
return values()[value];
}
}
protected final int xid;
protected final Type messageType;
RpcMessage(int xid, Type messageType) {
if (messageType != Type.RPC_CALL && messageType != Type.RPC_REPLY) {
throw new IllegalArgumentException("Invalid message type " + messageType);
}
this.xid = xid;
this.messageType = messageType;
}
public abstract XDR write(XDR xdr);
public int getXid() {
return xid;
}
public Type getMessageType() {
return messageType;
}
protected void validateMessageType(Type expected) {
if (expected != messageType) {
throw new IllegalArgumentException("Message type is expected to be "
+ expected + " but got " + messageType);
}
}
}
| tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/oncrpc/RpcMessage.java | Java | apache-2.0 | 2,009 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.analysis;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.payloads.*;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.assistedinject.Assisted;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.settings.IndexSettings;
/**
*
*/
public class DelimitedPayloadTokenFilterFactory extends AbstractTokenFilterFactory {
public static final char DEFAULT_DELIMITER = '|';
public static final PayloadEncoder DEFAULT_ENCODER = new FloatEncoder();
static final String ENCODING = "encoding";
static final String DELIMITER = "delimiter";
char delimiter;
PayloadEncoder encoder;
@Inject
public DelimitedPayloadTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name,
@Assisted Settings settings) {
super(index, indexSettings, name, settings);
String delimiterConf = settings.get(DELIMITER);
if (delimiterConf != null) {
delimiter = delimiterConf.charAt(0);
} else {
delimiter = DEFAULT_DELIMITER;
}
if (settings.get(ENCODING) != null) {
if (settings.get(ENCODING).equals("float")) {
encoder = new FloatEncoder();
} else if (settings.get(ENCODING).equals("int")) {
encoder = new IntegerEncoder();
} else if (settings.get(ENCODING).equals("identity")) {
encoder = new IdentityEncoder();
}
} else {
encoder = DEFAULT_ENCODER;
}
}
@Override
public TokenStream create(TokenStream tokenStream) {
DelimitedPayloadTokenFilter filter = new DelimitedPayloadTokenFilter(tokenStream, delimiter, encoder);
return filter;
}
}
| mkis-/elasticsearch | src/main/java/org/elasticsearch/index/analysis/DelimitedPayloadTokenFilterFactory.java | Java | apache-2.0 | 2,762 |
package info.faceland.loot.data;
public class PriceData {
private int price;
private boolean rare;
public PriceData (int price, boolean rare) {
this.price = price;
this.rare = rare;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public boolean isRare() {
return rare;
}
public void setRare(boolean rare) {
this.rare = rare;
}
}
| TealCube/loot | src/main/java/info/faceland/loot/data/PriceData.java | Java | isc | 435 |
package de.klimek.spacecurl.activities;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelSlideListener;
import java.util.ArrayList;
import java.util.List;
import de.klimek.spacecurl.Database;
import de.klimek.spacecurl.R;
import de.klimek.spacecurl.game.GameCallBackListener;
import de.klimek.spacecurl.game.GameDescription;
import de.klimek.spacecurl.game.GameFragment;
import de.klimek.spacecurl.util.ColorGradient;
import de.klimek.spacecurl.util.cards.StatusCard;
import de.klimek.spacecurl.util.collection.GameStatus;
import de.klimek.spacecurl.util.collection.Training;
import de.klimek.spacecurl.util.collection.TrainingStatus;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;
import it.gmariotti.cardslib.library.view.CardView;
/**
* This abstract class loads a training and provides functionality to
* subclasses, e. g. usage of the status panel, switching games, and showing a
* pause screen. <br/>
* A Training must be loaded with {@link #loadTraining(Training)}. In order to
* use the status-panel {@link #useStatusPanel()} has to be called.
*
* @author Mike Klimek
* @see <a href="http://developer.android.com/reference/packages.html">Android
* API</a>
*/
public abstract class BasicTrainingActivity extends FragmentActivity implements OnClickListener,
GameCallBackListener {
public static final String TAG = BasicTrainingActivity.class.getName();
// Status panel
private boolean mUsesStatus = false;
private TrainingStatus mTrainingStatus;
private GameStatus mCurGameStatus;
private int mStatusColor;
private ColorGradient mStatusGradient = new ColorGradient(Color.RED, Color.YELLOW, Color.GREEN);
private FrameLayout mStatusIndicator;
private ImageButton mSlidingToggleButton;
private boolean mButtonImageIsExpand = true;
private SlidingUpPanelLayout mSlidingUpPanel;
private CardListView mCardListView;
private CardArrayAdapter mCardArrayAdapter;
private List<Card> mCards = new ArrayList<Card>();
private GameFragment mGameFragment;
private FrameLayout mGameFrame;
private Training mTraining;
private Database mDatabase;
// Pause Frame
private FrameLayout mPauseFrame;
private LinearLayout mInstructionLayout;
private ImageView mResumeButton;
private TextView mInstructionsTextView;
private String mInstructions = "";
private int mShortAnimationDuration;
private State mState = State.Paused;
public static enum State {
Paused, Pausing, Running
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabase = Database.getInstance(this);
setContentView(R.layout.activity_base);
setupPauseView();
}
/**
* Dialog with instructions for the current game or pause/play icon. Shows
* when the user interacts with the App.
*/
private void setupPauseView() {
mGameFrame = (FrameLayout) findViewById(R.id.game_frame);
mGameFrame.setOnClickListener(this);
// hide initially
mPauseFrame = (FrameLayout) findViewById(R.id.pause_layout);
mPauseFrame.setAlpha(0.0f);
mPauseFrame.setVisibility(View.GONE);
mInstructionLayout = (LinearLayout) findViewById(R.id.instruction_layout);
mResumeButton = (ImageView) findViewById(R.id.resume_button);
mInstructionsTextView = (TextView) findViewById(R.id.instructions_textview);
mShortAnimationDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
@Override
protected void onResume() {
super.onResume();
if (mDatabase.isOrientationLandscape()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
/**
* Subclasses must load a Training with this method.
*
* @param training
*/
protected final void loadTraining(Training training) {
mTraining = training;
}
/**
* Subclasses can use this method to enable the status-panel.
*/
protected final void useStatusPanel() {
mTrainingStatus = mTraining.createTrainingStatus();
mUsesStatus = true;
mStatusIndicator = (FrameLayout) findViewById(R.id.status_indicator);
mSlidingToggleButton = (ImageButton) findViewById(R.id.panel_button);
mSlidingUpPanel = (SlidingUpPanelLayout) findViewById(R.id.content_frame);
mSlidingUpPanel.setPanelSlideListener(new PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
if (slideOffset > 0.5f && mButtonImageIsExpand) {
mSlidingToggleButton.setImageResource(R.drawable.ic_collapse);
mButtonImageIsExpand = false;
} else if (slideOffset < 0.5f && !mButtonImageIsExpand) {
mSlidingToggleButton.setImageResource(R.drawable.ic_expand);
mButtonImageIsExpand = true;
}
}
@Override
public void onPanelCollapsed(View panel) {
}
@Override
public void onPanelExpanded(View panel) {
}
@Override
public void onPanelAnchored(View panel) {
}
@Override
public void onPanelHidden(View panel) {
}
});
int statusIndicatorHeight = (int) (getResources()
.getDimension(R.dimen.status_indicator_height));
mSlidingUpPanel.setPanelHeight(statusIndicatorHeight);
// delegate clicks to underlying panel
mSlidingToggleButton.setClickable(false);
mSlidingUpPanel.setEnabled(true);
// setup cardlist
mCardArrayAdapter = new FixedCardArrayAdapter(this, mCards);
mCardListView = (CardListView) findViewById(R.id.card_list);
mCardListView.setAdapter(mCardArrayAdapter);
}
protected final void updateCurGameStatus(final float status) {
// graph
mCurGameStatus.addStatus(status);
// indicator color
mStatusColor = mStatusGradient.getColorForFraction(status);
mStatusIndicator.setBackgroundColor(mStatusColor);
}
protected final void expandSlidingPane() {
if (mState == State.Running) {
pause();
mState = State.Paused;
}
mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
}
protected final void collapseSlidingPane() {
mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
protected final void showStatusIndicator() {
mStatusIndicator.setVisibility(View.VISIBLE);
}
protected final void hideStatusIndicator() {
mStatusIndicator.setVisibility(View.GONE);
}
protected final void lockSlidingPane() {
mSlidingToggleButton.setVisibility(View.GONE);
}
protected final void unlockSlidingPane() {
mSlidingToggleButton.setVisibility(View.VISIBLE);
}
/**
* Creates a new GameFragment from a gameDescriptionIndex and displays it.
* Switches to the associated gameStatus from a previous game (overwriting
* it) or creates a new one.
*
* @param gameDescriptionIndex the game to start
* @param enterAnimation how the fragment should enter
* @param exitAnimation how the previous fragment should be removed
*/
protected final void switchToGame(int gameDescriptionIndex, int enterAnimation,
int exitAnimation) {
mState = State.Paused;
pause();
// get Fragment
GameDescription newGameDescription = mTraining.get(gameDescriptionIndex);
mGameFragment = newGameDescription.createFragment();
// Transaction
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(enterAnimation, exitAnimation)
.replace(R.id.game_frame, mGameFragment)
.commit();
// enable callback
mGameFragment.registerGameCallBackListener(this);
// update pause view
mInstructions = newGameDescription.getInstructions();
if (mInstructions == null || mInstructions.isEmpty()) {
// only show pause/play icon
mInstructionLayout.setVisibility(View.GONE);
mResumeButton.setVisibility(View.VISIBLE);
} else {
// only show instructions
mResumeButton.setVisibility(View.GONE);
mInstructionLayout.setVisibility(View.VISIBLE);
mInstructionsTextView.setText(mInstructions);
}
if (mUsesStatus) {
// switch to status associated with current game
mCurGameStatus = mTrainingStatus.get(gameDescriptionIndex);
if (mCurGameStatus == null) {
// create new
mCurGameStatus = new GameStatus(newGameDescription.getTitle());
mTrainingStatus.append(gameDescriptionIndex, mCurGameStatus);
mCards.add(gameDescriptionIndex, new StatusCard(this, mCurGameStatus));
mCardArrayAdapter.notifyDataSetChanged();
} else {
// reset existing
mCurGameStatus.reset();
mCardArrayAdapter.notifyDataSetChanged();
}
}
}
/**
* Convenience method. Same as
* {@link #switchToGame(int gameDescriptionIndex, int enterAnimation, int exitAnimation)}
* but uses standard fade_in/fade_out animations.
*
* @param gameDescriptionIndex the game to start
*/
protected final void switchToGame(int gameDescriptionIndex) {
switchToGame(gameDescriptionIndex, android.R.anim.fade_in, android.R.anim.fade_out);
}
@Override
protected void onPause() {
super.onPause();
if (mState == State.Running) {
pause();
}
mState = State.Paused;
}
@Override
public void onUserInteraction() {
// Pause on every user interaction
if (mState == State.Running) {
mState = State.Pausing;
pause();
} else if (mState == State.Pausing) {
// Previously clicked outside of gameframe and now possibly on
// gameframe again to resume
mState = State.Paused;
}
super.onUserInteraction();
}
/**
* Called when clicking inside the game frame (after onUserInteraction)
*/
@Override
public void onClick(View v) {
if (mState == State.Paused) {
// Resume when paused
resume();
mState = State.Running;
} else if (mState == State.Pausing) {
// We have just paused in onUserInteraction -> don't resume
mState = State.Paused;
}
}
private void pause() {
Log.v(TAG, "Paused");
// pause game
if (mGameFragment != null) {
mGameFragment.onPauseGame();
}
// Show pause view and grey out screen
mPauseFrame.setVisibility(View.VISIBLE);
mPauseFrame.animate()
.alpha(1f)
.setDuration(mShortAnimationDuration)
.setListener(null);
// Show navigation bar
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
private void resume() {
Log.v(TAG, "Resumed");
// hide pause view
mPauseFrame.animate()
.alpha(0f)
.setDuration(mShortAnimationDuration)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mPauseFrame.setVisibility(View.GONE);
}
});
// resume game
if (mGameFragment != null) {
mGameFragment.onResumeGame();
}
// Grey out navigation bar
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
/**
* Fixes bug in {@link CardArrayAdapter CardArrayAdapter's} Viewholder
* pattern. Otherwise the cards innerViewElements would not be replaced
* (Title and Graph from previous Graph is shown).
*
* @author Mike Klimek
*/
private class FixedCardArrayAdapter extends CardArrayAdapter {
public FixedCardArrayAdapter(Context context, List<Card> cards) {
super(context, cards);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Card card = (Card) getItem(position);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(R.layout.list_card_layout, parent, false);
}
CardView view = (CardView) convertView.findViewById(R.id.list_cardId);
view.setForceReplaceInnerLayout(true);
view.setCard(card);
return convertView;
}
}
}
| Tetr4/Spacecurl | app/src/main/java/de/klimek/spacecurl/activities/BasicTrainingActivity.java | Java | isc | 14,055 |
package com.evanbyrne.vending_machine_kata.ui;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.SortedMap;
import org.jooq.lambda.tuple.Tuple2;
import com.evanbyrne.vending_machine_kata.coin.Cents;
import com.evanbyrne.vending_machine_kata.coin.Coin;
import com.evanbyrne.vending_machine_kata.coin.CoinCollection;
import com.evanbyrne.vending_machine_kata.coin.CoinFactory;
import com.evanbyrne.vending_machine_kata.inventory.IInventoryService;
import com.evanbyrne.vending_machine_kata.inventory.InventoryProduct;
/**
* Manages console input and output.
*/
public class Console {
/**
* Get change display for terminal output.
*
* @param Change.
* @return Formatted message.
*/
public String getChangeDisplay(final CoinCollection change) {
final ArrayList<String> display = new ArrayList<String>();
final LinkedHashMap<Coin, Integer> coinMap = new LinkedHashMap<Coin, Integer>();
display.add("THANK YOU");
for(final Coin coin : change.getList()) {
if(coinMap.containsKey(coin)) {
coinMap.put(coin, coinMap.get(coin) + 1);
} else {
coinMap.put(coin, 1);
}
}
if(!coinMap.isEmpty()) {
final ArrayList<String> displayReturn = new ArrayList<String>();
for(final Map.Entry<Coin, Integer> entry : coinMap.entrySet()) {
final String name = entry.getKey().name().toLowerCase();
final int count = entry.getValue();
displayReturn.add(String.format("%s (x%d)", name, count));
}
display.add("RETURN: " + String.join(", ", displayReturn));
}
return String.join("\n", display);
}
/**
* Get product listing display for terminal output.
*
* @param Sorted map of all inventory.
* @return Formatted message.
*/
public String getProductDisplay(final SortedMap<String, InventoryProduct> inventory) {
if(!inventory.isEmpty()) {
final ArrayList<String> display = new ArrayList<String>();
for(final Map.Entry<String, InventoryProduct> entry : inventory.entrySet()) {
final String centsString = Cents.toString(entry.getValue().getCents());
final String name = entry.getValue().getName();
final String key = entry.getKey();
display.add(String.format("%s\t%s\t%s", key, centsString, name));
}
return String.join("\n", display);
}
return "No items in vending machine.";
}
/**
* Prompt user for payment.
*
* Loops until payment >= selected product cost.
*
* @param Scanner.
* @param A product representing their selection.
* @return Payment.
*/
public CoinCollection promptForPayment(final Scanner scanner, final InventoryProduct selection) {
final CoinCollection paid = new CoinCollection();
Coin insert;
String input;
do {
System.out.println("PRICE: " + Cents.toString(selection.getCents()));
do {
System.out.print(String.format("INSERT COIN (%s): ", Cents.toString(paid.getTotal())));
input = scanner.nextLine();
insert = CoinFactory.getByName(input);
if(insert == null) {
System.out.println("Invalid coin. This machine accepts: quarter, dime, nickel.");
}
} while(insert == null);
paid.addCoin(insert);
} while(paid.getTotal() < selection.getCents());
return paid;
}
/**
* Prompt for product selection.
*
* Loops until a valid product has been selected.
*
* @param Scanner
* @param An implementation of IInventoryService.
* @return A tuple with the product key and product.
*/
public Tuple2<String, InventoryProduct> promptForSelection(final Scanner scanner, final IInventoryService inventoryService) {
InventoryProduct selection;
String input;
do {
System.out.print("SELECT: ");
input = scanner.nextLine();
selection = inventoryService.getProduct(input);
if( selection == null ) {
System.out.println("Invalid selection.");
}
} while(selection == null);
return new Tuple2<String, InventoryProduct>(input, selection);
}
}
| evantbyrne/vending-machine-kata | src/main/java/com/evanbyrne/vending_machine_kata/ui/Console.java | Java | isc | 4,553 |
/*
* Copyright © 2016 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jcanephora.tests.lwjgl3;
import com.io7m.jcanephora.core.api.JCGLContextType;
import com.io7m.jcanephora.core.api.JCGLInterfaceGL33Type;
import com.io7m.jcanephora.tests.contracts.JCGLFramebuffersContract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class LWJGL3FramebuffersTestGL33 extends JCGLFramebuffersContract
{
private static final Logger LOG;
static {
LOG = LoggerFactory.getLogger(LWJGL3FramebuffersTestGL33.class);
}
@Override
public void onTestCompleted()
{
LWJGL3TestContexts.closeAllContexts();
}
@Override
protected Interfaces getInterfaces(final String name)
{
final JCGLContextType c = LWJGL3TestContexts.newGL33Context(name, 24, 8);
final JCGLInterfaceGL33Type cg = c.contextGetGL33();
return new Interfaces(c, cg.framebuffers(), cg.textures());
}
@Override
protected boolean hasRealBlitting()
{
return true;
}
}
| io7m/jcanephora | com.io7m.jcanephora.tests.lwjgl3/src/test/java/com/io7m/jcanephora/tests/lwjgl3/LWJGL3FramebuffersTestGL33.java | Java | isc | 1,726 |
package org.apollo.game.event.handler.impl;
import org.apollo.game.event.handler.EventHandler;
import org.apollo.game.event.handler.EventHandlerContext;
import org.apollo.game.event.impl.ItemOnItemEvent;
import org.apollo.game.model.Inventory;
import org.apollo.game.model.Item;
import org.apollo.game.model.Player;
/**
* An {@link EventHandler} which verifies the target item in {@link ItemOnItemEvent}s.
*
* @author Chris Fletcher
*/
public final class ItemOnItemVerificationHandler extends EventHandler<ItemOnItemEvent> {
@Override
public void handle(EventHandlerContext ctx, Player player, ItemOnItemEvent event) {
Inventory inventory = ItemVerificationHandler.interfaceToInventory(player, event.getTargetInterfaceId());
int slot = event.getTargetSlot();
if (slot < 0 || slot >= inventory.capacity()) {
ctx.breakHandlerChain();
return;
}
Item item = inventory.get(slot);
if (item == null || item.getId() != event.getTargetId()) {
ctx.breakHandlerChain();
}
}
} | DealerNextDoor/ApolloDev | src/org/apollo/game/event/handler/impl/ItemOnItemVerificationHandler.java | Java | isc | 1,001 |
package com.leychina.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.widget.ImageView;
import android.widget.TextView;
import com.leychina.R;
import com.leychina.model.Artist;
import com.leychina.value.Constant;
import com.leychina.widget.tabindicator.TouchyWebView;
import com.squareup.picasso.Picasso;
/**
* Created by yuandunlong on 11/21/15.
*/
public class ArtistDetailActivity extends AppCompatActivity {
TouchyWebView webview;
Artist artist;
ImageView imageView;
TextView weight, height, name, birthday;
public static void start(Context from, Artist artist) {
Intent intent = new Intent(from, ArtistDetailActivity.class);
intent.putExtra("artist", artist);
from.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
this.artist = (Artist) intent.getSerializableExtra("artist");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artist_detail);
webview = (TouchyWebView) findViewById(R.id.artist_webview);
imageView = (ImageView) findViewById(R.id.image_view_artist_cover);
Picasso.with(this).load(Constant.DOMAIN+"/static/upload/"+artist.getPhoto()).into(imageView);
name = (TextView) findViewById(R.id.text_view_name);
height = (TextView) findViewById(R.id.text_view_height);
weight = (TextView) findViewById(R.id.text_view_weight);
birthday= (TextView) findViewById(R.id.text_view_birthday);
// name.setText(artist.get);
weight.setText(artist.getWeight() + "");
height.setText(artist.getHeight() + "");
birthday.setText(artist.getBlood());
webview.setWebChromeClient(new WebChromeClient());
webview.getSettings().setDefaultTextEncodingName("utf-8");
webview.loadDataWithBaseURL(Constant.DOMAIN, artist.getDescription(), "text/html", "utf-8","");
}
}
| yuandunlong/leychina-android | app/src/main/java/com/leychina/activity/ArtistDetailActivity.java | Java | isc | 2,114 |
/*
* Copyright (c) 2014 Stephan D. Cote' - All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the MIT License which accompanies this distribution, and is
* available at http://creativecommons.org/licenses/MIT/
*
* Contributors:
* Stephan D. Cote
* - Initial concept and implementation
*/
package coyote.i13n;
//import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.AfterClass;
import org.junit.Test;
/**
*
*/
public class EventListTest {
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* Test method for {@link coyote.i13n.EventList#lastSequence()}.
*/
//@Test
public void testLastSequence() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#EventList()}.
*/
//@Test
public void testEventList() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getMaxEvents()}.
*/
@Test
public void testGetMaxEvents() {
EventList list = new EventList();
list.setMaxEvents( 5 );
AppEvent alert0 = list.createEvent( "Zero" );
AppEvent alert1 = list.createEvent( "One" );
AppEvent alert2 = list.createEvent( "Two" );
AppEvent alert3 = list.createEvent( "Three" );
AppEvent alert4 = list.createEvent( "Four" );
AppEvent alert5 = list.createEvent( "Five" );
AppEvent alert6 = list.createEvent( "Six" );
//System.out.println( "Max="+list.getMaxEvents()+" Size=" + list.getSize() );
assertTrue( list._list.size() == 5 );
// should result in the list being trimmed immediately
list.setMaxEvents( 2 );
assertTrue( list._list.size() == 2 );
list.add( alert0 );
list.add( alert1 );
list.add( alert2 );
list.add( alert3 );
list.add( alert4 );
list.add( alert5 );
list.add( alert6 );
// should still only contain 2 events
assertTrue( list._list.size() == 2 );
// Check the first and last event in the list
assertEquals( alert5, list.getFirst() );
assertEquals( alert6, list.getLast() );
}
/**
* Test method for {@link coyote.i13n.EventList#setMaxEvents(int)}.
*/
//@Test
public void testSetMaxEvents() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#add(coyote.i13n.AppEvent)}.
*/
//@Test
public void testAdd() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#remove(coyote.i13n.AppEvent)}.
*/
//@Test
public void testRemove() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#get(long)}.
*/
//@Test
public void testGet() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getFirst()}.
*/
//@Test
public void testGetFirst() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getLast()}.
*/
//@Test
public void testGetLast() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getSize()}.
*/
//@Test
public void testGetSize() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#createEvent(java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, int, int, java.lang.String)}.
*/
//@Test
public void testCreateEventStringStringStringStringIntIntIntString() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#createEvent(java.lang.String)}.
*/
//@Test
public void testCreateEventString() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#createEvent(java.lang.String, int, int)}.
*/
//@Test
public void testCreateEventStringIntInt() {
fail( "Not yet implemented" );
}
}
| sdcote/loader | src/test/java/coyote/i13n/EventListTest.java | Java | mit | 4,336 |
package com.isme.zteui.cache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
/**
* Title: Volley 的缓存类</br><br>
* Description: </br><br>
* Copyright: Copyright(c)2003</br><br>
* Company: ihalma </br><br>
* @author and</br><br>
* @version 1 </br><br>
* data: 2015-3-17</br>
*/
public class BitmapLruCache implements ImageCache {
private LruCache<String, Bitmap> mCache;
/**
* 最大缓存 10 M
*/
public BitmapLruCache() {
int maxSize = 1024 * 1024 * 10; //最大缓存10M
mCache = new LruCache<String, Bitmap>(maxSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
}
@Override
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
}
| heyugtan/zteUI | ZTEUI/src/com/isme/zteui/cache/BitmapLruCache.java | Java | mit | 944 |
package warhammerrpg.database.exception;
import warhammerrpg.core.exception.WarhammerRpgException;
public class DatabaseException extends WarhammerRpgException {
public DatabaseException(Exception originalExceptionObject) {
super(originalExceptionObject);
}
public DatabaseException() {
super();
}
}
| tomaszkowalczyk94/warhammer-rpg-helper | src/main/java/warhammerrpg/database/exception/DatabaseException.java | Java | mit | 335 |
package org.ethereum.android.service;
import android.os.Message;
public interface ConnectorHandler {
boolean handleMessage(Message message);
void onConnectorConnected();
void onConnectorDisconnected();
String getID();
}
| BlockchainSociety/ethereumj-android | ethereumj-core-android/src/main/java/org/ethereum/android/service/ConnectorHandler.java | Java | mit | 240 |
/*
* Copyright (c) 2003-2009 jMonkeyEngine
* 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 name of 'jMonkeyEngine' 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 OWNER 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.
*/
package com.jme.curve;
import java.io.IOException;
import com.jme.math.Vector3f;
import com.jme.scene.Controller;
import com.jme.scene.Spatial;
import com.jme.util.export.InputCapsule;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.OutputCapsule;
/**
* <code>CurveController</code> defines a controller that moves a supplied
* <code>Spatial</code> object along a curve. Attributes of the curve are set
* such as the up vector (if not set, the spacial object will roll along the
* curve), the orientation precision defines how accurate the orientation of the
* spatial will be.
* @author Mark Powell
* @version $Id: CurveController.java 4131 2009-03-19 20:15:28Z blaine.dev $
*/
public class CurveController extends Controller {
private static final long serialVersionUID = 1L;
private Spatial mover;
private Curve curve;
private Vector3f up;
private float orientationPrecision = 0.1f;
private float currentTime = 0.0f;
private float deltaTime = 0.0f;
private boolean cycleForward = true;
private boolean autoRotation = false;
/**
* Constructor instantiates a new <code>CurveController</code> object.
* The curve object that the controller operates on and the spatial object
* that is moved is specified during construction.
* @param curve the curve to operate on.
* @param mover the spatial to move.
*/
public CurveController(Curve curve, Spatial mover) {
this.curve = curve;
this.mover = mover;
setUpVector(new Vector3f(0,1,0));
setMinTime(0);
setMaxTime(Float.MAX_VALUE);
setRepeatType(Controller.RT_CLAMP);
setSpeed(1.0f);
}
/**
* Constructor instantiates a new <code>CurveController</code> object.
* The curve object that the controller operates on and the spatial object
* that is moved is specified during construction. The game time to
* start and the game time to finish is also supplied.
* @param curve the curve to operate on.
* @param mover the spatial to move.
* @param minTime the time to start the controller.
* @param maxTime the time to end the controller.
*/
public CurveController(
Curve curve,
Spatial mover,
float minTime,
float maxTime) {
this.curve = curve;
this.mover = mover;
setMinTime(minTime);
setMaxTime(maxTime);
setRepeatType(Controller.RT_CLAMP);
}
/**
*
* <code>setUpVector</code> sets the locking vector for the spatials up
* vector. This prevents rolling along the curve and allows for a better
* tracking.
* @param up the vector to lock as the spatials up vector.
*/
public void setUpVector(Vector3f up) {
this.up = up;
}
/**
*
* <code>setOrientationPrecision</code> sets a precision value for the
* spatials orientation. The smaller the number the higher the precision.
* By default 0.1 is used, and typically does not require changing.
* @param value the precision value of the spatial's orientation.
*/
public void setOrientationPrecision(float value) {
orientationPrecision = value;
}
/**
*
* <code>setAutoRotation</code> determines if the object assigned to
* the controller will rotate with the curve or just following the
* curve.
* @param value true if the object is to rotate with the curve, false
* otherwise.
*/
public void setAutoRotation(boolean value) {
autoRotation = value;
}
/**
*
* <code>isAutoRotating</code> returns true if the object is rotating with
* the curve and false if it is not.
* @return true if the object is following the curve, false otherwise.
*/
public boolean isAutoRotating() {
return autoRotation;
}
/**
* <code>update</code> moves a spatial along the given curve for along a
* time period.
* @see com.jme.scene.Controller#update(float)
*/
public void update(float time) {
if(mover == null || curve == null || up == null) {
return;
}
currentTime += time * getSpeed();
if (currentTime >= getMinTime() && currentTime <= getMaxTime()) {
if (getRepeatType() == RT_CLAMP) {
deltaTime = currentTime - getMinTime();
mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation()));
if(autoRotation) {
mover.setLocalRotation(
curve.getOrientation(
deltaTime,
orientationPrecision,
up));
}
} else if (getRepeatType() == RT_WRAP) {
deltaTime = (currentTime - getMinTime()) % 1.0f;
if (deltaTime > 1) {
currentTime = 0;
deltaTime = 0;
}
mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation()));
if(autoRotation) {
mover.setLocalRotation(
curve.getOrientation(
deltaTime,
orientationPrecision,
up));
}
} else if (getRepeatType() == RT_CYCLE) {
float prevTime = deltaTime;
deltaTime = (currentTime - getMinTime()) % 1.0f;
if (prevTime > deltaTime) {
cycleForward = !cycleForward;
}
if (cycleForward) {
mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation()));
if(autoRotation) {
mover.setLocalRotation(
curve.getOrientation(
deltaTime,
orientationPrecision,
up));
}
} else {
mover.setLocalTranslation(
curve.getPoint(1.0f - deltaTime,mover.getLocalTranslation()));
if(autoRotation) {
mover.setLocalRotation(
curve.getOrientation(
1.0f - deltaTime,
orientationPrecision,
up));
}
}
} else {
return;
}
}
}
public void reset() {
this.currentTime = 0;
}
public void write(JMEExporter e) throws IOException {
super.write(e);
OutputCapsule capsule = e.getCapsule(this);
capsule.write(mover, "mover", null);
capsule.write(curve, "Curve", null);
capsule.write(up, "up", null);
capsule.write(orientationPrecision, "orientationPrecision", 0.1f);
capsule.write(cycleForward, "cycleForward", true);
capsule.write(autoRotation, "autoRotation", false);
}
public void read(JMEImporter e) throws IOException {
super.read(e);
InputCapsule capsule = e.getCapsule(this);
mover = (Spatial)capsule.readSavable("mover", null);
curve = (Curve)capsule.readSavable("curve", null);
up = (Vector3f)capsule.readSavable("up", null);
orientationPrecision = capsule.readFloat("orientationPrecision", 0.1f);
cycleForward = capsule.readBoolean("cycleForward", true);
autoRotation = capsule.readBoolean("autoRotation", false);
}
}
| accelazh/ThreeBodyProblem | lib/jME2_0_1-Stable/src/com/jme/curve/CurveController.java | Java | mit | 9,311 |
/*
* Copyright (C) 2011 ZXing authors
*
* 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 com.longluo.demo.qrcode.zxing.client.android.encode;
/**
* Encapsulates some simple formatting logic, to aid refactoring in {@link ContactEncoder}.
*
* @author Sean Owen
*/
interface Formatter {
/**
* @param value value to format
* @param index index of value in a list of values to be formatted
* @return formatted value
*/
CharSequence format(CharSequence value, int index);
}
| longluo/AndroidDemo | app/src/main/java/com/longluo/demo/qrcode/zxing/client/android/encode/Formatter.java | Java | mit | 1,015 |
/**
*
*/
package com.kant.datastructure.queues;
import com.kant.sortingnsearching.MyUtil;
/**
* @author shaskant
*
*/
public class GenerateBinaryNumbers1toN {
/**
*
* @param n
* @return
* @throws OverFlowException
* @throws UnderFlowException
*/
public String[] solve(int n) throws OverFlowException, UnderFlowException {
String[] result = new String[n];
System.out.println("input # " + n);
Queue<String> dequeue = new QueueListImplementation<String>();
dequeue.enQueue("1");
for (int count = 0; count < n; count++) {
result[count] = dequeue.deQueue();
dequeue.enQueue(result[count]+"0");
dequeue.enQueue(result[count]+"1");
}
return result;
}
/**
*
* @param args
* @throws OverFlowException
* @throws UnderFlowException
*/
public static void main(String[] args) throws OverFlowException, UnderFlowException {
GenerateBinaryNumbers1toN prob = new GenerateBinaryNumbers1toN();
System.out.print("output # ");
MyUtil.printArrayType(prob.solve(10));
}
}
| thekant/myCodeRepo | src/com/kant/datastructure/queues/GenerateBinaryNumbers1toN.java | Java | mit | 1,022 |
package com.baomidou.hibernateplus.spring.vo;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.baomidou.hibernateplus.entity.Convert;
/**
* <p>
* Vdemo
* </p>
*
* @author Caratacus
* @date 2016-12-2
*/
public class Vdemo extends Convert implements Serializable {
protected Long id;
private String demo1;
private String demo2;
private String demo3;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDemo1() {
return demo1;
}
public void setDemo1(String demo1) {
this.demo1 = demo1;
}
public String getDemo2() {
return demo2;
}
public void setDemo2(String demo2) {
this.demo2 = demo2;
}
public String getDemo3() {
return demo3;
}
public void setDemo3(String demo3) {
this.demo3 = demo3;
}
} | baomidou/hibernate-plus | hibernate-plus/src/test/java/com/baomidou/hibernateplus/spring/vo/Vdemo.java | Java | mit | 1,066 |
package xsmeral.semnet.sink;
import java.util.Properties;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.sail.rdbms.RdbmsStore;
/**
* Factory of {@link RdbmsStore} repositories.
* <br />
* Takes parameters corresponding to RdbmsStore {@linkplain RdbmsStore#RdbmsStore(java.lang.String, java.lang.String, java.lang.String, java.lang.String) constructor}:
* <ul>
* <li><code>driver</code> - FQN of JDBC driver</li>
* <li><code>url</code> - JDBC URL</li>
* <li><code>user</code> - DB user name</li>
* <li><code>password</code> - DB password</li>
* </ul>
* @author Ron Šmeral (xsmeral@fi.muni.cz)
*/
public class RdbmsStoreFactory extends RepositoryFactory {
@Override
public void initialize() throws RepositoryException {
Properties props = getProperties();
String jdbcDriver = props.getProperty("driver");
String url = props.getProperty("url");
String user = props.getProperty("user");
String pwd = props.getProperty("password");
if (jdbcDriver == null || url == null || user == null || pwd == null) {
throw new RepositoryException("Invalid parameters for repository");
} else {
Repository repo = new SailRepository(new RdbmsStore(jdbcDriver, url, user, pwd));
repo.initialize();
setRepository(repo);
}
}
}
| rsmeral/semnet | SemNet/src/xsmeral/semnet/sink/RdbmsStoreFactory.java | Java | mit | 1,465 |
package com.test.SERVICE;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.DAO.IMercaderiaDAO;
import com.test.BEAN.Mercaderia;
@Service
public class MercaderiaService implements IMercaderiaService{
@Autowired
private IMercaderiaDAO mercaderiaDAO;
@Override
public List<Mercaderia> getAllMercaderia() {
return mercaderiaDAO.getAllMercaderia();
}
@Override
public Mercaderia getMercaderiaById(int mercaderiaId) {
Mercaderia merc = mercaderiaDAO.getMercaderiaById(mercaderiaId);
return merc;
}
@Override
public boolean createMercaderia(Mercaderia mercaderia) {
if (mercaderiaDAO.mercaderiaExists(mercaderia.getNombre())) {
return false;
} else {
mercaderiaDAO.createMercaderia(mercaderia);
return true;
}
}
@Override
public void updateMercaderia(Mercaderia mercaderia) {
// TODO Auto-generated method stub
mercaderiaDAO.updateMercaderia(mercaderia);
}
}
| renzopalmieri/demomercaderia | spring-boot-2/src/main/java/com/test/SERVICE/MercaderiaService.java | Java | mit | 1,116 |
package org.gw4e.eclipse.builder.exception;
/*-
* #%L
* gw4e
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2017 gw4e-project
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import org.gw4e.eclipse.builder.GW4EParser;
import org.gw4e.eclipse.builder.Location;
public class SeverityConfigurationException extends BuildPolicyConfigurationException {
/**
*
*/
private static final long serialVersionUID = 1L;
public SeverityConfigurationException(Location location, String message,ParserContextProperties p) {
super(location, message,p);
}
public int getProblemId () {
return GW4EParser.INVALID_SEVERITY;
}
}
| gw4e/gw4e.project | bundles/gw4e-eclipse-plugin/src/org/gw4e/eclipse/builder/exception/SeverityConfigurationException.java | Java | mit | 1,676 |
package org.jabref.gui.openoffice;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import org.jabref.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.logic.l10n.Localization;
import com.jgoodies.forms.builder.ButtonBarBuilder;
import com.jgoodies.forms.builder.FormBuilder;
import com.jgoodies.forms.layout.FormLayout;
/**
* Dialog for adding citation with page number info.
*/
class AdvancedCiteDialog {
private static boolean defaultInPar = true;
private boolean okPressed;
private final JDialog diag;
private final JTextField pageInfo = new JTextField(15);
public AdvancedCiteDialog(JabRefFrame parent) {
diag = new JDialog((JFrame) null, Localization.lang("Cite special"), true);
ButtonGroup bg = new ButtonGroup();
JRadioButton inPar = new JRadioButton(Localization.lang("Cite selected entries between parenthesis"));
JRadioButton inText = new JRadioButton(Localization.lang("Cite selected entries with in-text citation"));
bg.add(inPar);
bg.add(inText);
if (defaultInPar) {
inPar.setSelected(true);
} else {
inText.setSelected(true);
}
inPar.addChangeListener(changeEvent -> defaultInPar = inPar.isSelected());
FormBuilder builder = FormBuilder.create()
.layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref, 4dlu, pref"));
builder.add(inPar).xyw(1, 1, 3);
builder.add(inText).xyw(1, 3, 3);
builder.add(Localization.lang("Extra information (e.g. page number)") + ":").xy(1, 5);
builder.add(pageInfo).xy(3, 5);
builder.padding("10dlu, 10dlu, 10dlu, 10dlu");
diag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
JButton ok = new JButton(Localization.lang("OK"));
JButton cancel = new JButton(Localization.lang("Cancel"));
bb.addButton(ok);
bb.addButton(cancel);
bb.addGlue();
bb.padding("5dlu, 5dlu, 5dlu, 5dlu");
diag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
diag.pack();
ActionListener okAction = actionEvent -> {
okPressed = true;
diag.dispose();
};
ok.addActionListener(okAction);
pageInfo.addActionListener(okAction);
inPar.addActionListener(okAction);
inText.addActionListener(okAction);
Action cancelAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
okPressed = false;
diag.dispose();
}
};
cancel.addActionListener(cancelAction);
builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close");
builder.getPanel().getActionMap().put("close", cancelAction);
}
public void showDialog() {
diag.setLocationRelativeTo(diag.getParent());
diag.setVisible(true);
}
public boolean canceled() {
return !okPressed;
}
public String getPageInfo() {
return pageInfo.getText().trim();
}
public boolean isInParenthesisCite() {
return defaultInPar;
}
}
| tobiasdiez/jabref | src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.java | Java | mit | 3,726 |
package com.ricex.aft.android.request;
import org.springframework.http.HttpStatus;
public class AFTResponse<T> {
/** The successful response from the server */
private final T response;
/** The error response from the server */
private final String error;
/** The HttpStatus code of the response */
private final HttpStatus statusCode;
/** Whether or not this response is valid */
private final boolean valid;
/** Creates a new instance of AFTResponse, representing a successful response
*
* @param response The parsed response received from the server
* @param statusCode The status code of the response
*/
public AFTResponse(T response, HttpStatus statusCode) {
this.response = response;
this.statusCode = statusCode;
this.error = null;
valid = true;
}
/** Creates a new instance of AFTResponse, representing an invalid (error) response
*
* @param response The response (if any) received from the server
* @param error The error message received from the server
* @param statusCode The status code of the response
*/
public AFTResponse(T response, String error, HttpStatus statusCode) {
this.response = response;
this.error = error;
this.statusCode = statusCode;
valid = false;
}
/** Whether or not this response is valid
*
* @return True if the server returned Http OK (200), otherwise false
*/
public boolean isValid() {
return valid;
}
/** The response from the server if valid
*
* @return The response from the server
*/
public T getResponse() {
return response;
}
/** Returns the error received by the server, if invalid response
*
* @return The error the server returned
*/
public String getError() {
return error;
}
/** Return the status code received from the server
*
* @return the status code received from the server
*/
public HttpStatus getStatusCode() {
return statusCode;
}
}
| mwcaisse/AndroidFT | aft-android/src/main/java/com/ricex/aft/android/request/AFTResponse.java | Java | mit | 1,925 |
package cn.edu.ustc.appseed.clubseed.activity;
/*
* Show the detail content of the event which you select.
* Why to use a custom toolbar instead of the default toolbar in ActionBarActivity?
* Because the custom toolbar is very convenient to edit it and good to unify the GUI.
*/
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import cn.edu.ustc.appseed.clubseed.R;
import cn.edu.ustc.appseed.clubseed.data.Event;
import cn.edu.ustc.appseed.clubseed.data.ViewActivityPhp;
import cn.edu.ustc.appseed.clubseed.fragment.NoticeFragment;
import cn.edu.ustc.appseed.clubseed.fragment.StarFragment;
import cn.edu.ustc.appseed.clubseed.utils.AppUtils;
public class StarContentActivity extends ActionBarActivity {
private Toolbar toolbar;
private TextView mTextView;
private ImageView mImageView;
private TextView nullTextView;
private Event mEvent;
int ID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_content);
toolbar = (Toolbar) findViewById(R.id.toolbar);
mTextView = (TextView) findViewById(R.id.textViewEventContent);
mImageView = (ImageView) findViewById(R.id.imgContent);
if (toolbar != null) {
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back));
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
ID = getIntent().getIntExtra(StarFragment.EXTRA_ID, 0);
mEvent = AppUtils.savedEvents.get(ID);
setTitle(mEvent.getTitle());
mTextView.setText(mEvent.getContent());
mImageView.setImageBitmap(mEvent.getBitmap());
}
}
| leerduo/ClubSeed | app/src/main/java/cn/edu/ustc/appseed/clubseed/activity/StarContentActivity.java | Java | mit | 2,293 |
package com.smbc.droid;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.android.volley.toolbox.NetworkImageView;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ComicPagerAdapter adapter = new ComicPagerAdapter( getSupportFragmentManager());
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
// findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// viewPager.setCurrentItem(viewPager.getCurrentItem()+1, true);
// }
// });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| nindalf/smbc-droid | app/src/main/java/com/smbc/droid/MainActivity.java | Java | mit | 1,709 |
package lab;
public class IntArrayWorker
{
/** two dimensional matrix */
private int[][] matrix = null;
/** set the matrix to the passed one
* @param theMatrix the one to use
*/
public void setMatrix(int[][] theMatrix)
{
matrix = theMatrix;
}
/**
* Method to return the total
* @return the total of the values in the array
*/
public int getTotal()
{
int total = 0;
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
total = total + matrix[row][col];
}
}
return total;
}
/**
* Method to return the total using a nested for-each loop
* @return the total of the values in the array
*/
public int getTotalNested()
{
int total = 0;
for (int[] rowArray : matrix)
{
for (int item : rowArray)
{
total = total + item;
}
}
return total;
}
/**
* Method to fill with an increasing count
*/
public void fillCount()
{
int numCols = matrix[0].length;
int count = 1;
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < numCols; col++)
{
matrix[row][col] = count;
count++;
}
}
}
/**
* print the values in the array in rows and columns
*/
public void print()
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
System.out.print( matrix[row][col] + " " );
}
System.out.println();
}
System.out.println();
}
public int getCount(int num){
int count = 0;
for(int row = 0; row < matrix.length; row++)
for(int col = 0; col < matrix[0].length; col++)
if(matrix[row][col] == num)
count++;
return count;
}
public int getColTotal(int col){
int total = 0;
for(int row = 0; row < matrix.length; row++)
total += matrix[row][col];
return total;
}
public int getLargest(){
int largest = matrix[0][0];
for(int row = 0; row < matrix.length; row++)
for(int col = 0; col < matrix[0].length; col++)
if(matrix[row][col] > largest)
largest = matrix[row][col];
return largest;
}
/**
* fill the array with a pattern
*/
public void fillPattern1()
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length;
col++)
{
if (row < col)
matrix[row][col] = 1;
else if (row == col)
matrix[row][col] = 2;
else
matrix[row][col] = 3;
}
}
}
} | Zedai/APCOMSCI | ApComSci/pictures_lab/lab/IntArrayWorker.java | Java | mit | 2,755 |
package com.smartbit8.laravelstorm.run;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.ide.browsers.*;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter;
import com.intellij.util.xmlb.XmlSerializer;
import com.jetbrains.php.config.interpreters.PhpInterpreter;
import com.jetbrains.php.config.interpreters.PhpInterpretersManagerImpl;
import com.smartbit8.laravelstorm.ui.LaravelRunConfSettingsEditor;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
public class LaravelRunConf extends RunConfigurationBase {
private Project project;
private String host = "localhost";
private int port = 8000;
private String route = "/";
private WebBrowser browser;
private PhpInterpreter interpreter;
LaravelRunConf(@NotNull Project project, @NotNull ConfigurationFactory factory, String name) {
super(project, factory, name);
this.project = project;
}
@Override
public void createAdditionalTabComponents(AdditionalTabComponentManager manager, ProcessHandler startedProcess) {
LogTab logTab = new LogTab(getProject());
manager.addAdditionalTabComponent(logTab, "Laravel.log");
startedProcess.addProcessListener(new ProcessAdapter() {
@Override
public void startNotified(ProcessEvent event) {
logTab.start();
}
@Override
public void processTerminated(ProcessEvent event) {
startedProcess.removeProcessListener(this);
}
});
}
@Override
public void readExternal(Element element) throws InvalidDataException {
super.readExternal(element);
Settings settings = XmlSerializer.deserialize(element, Settings.class);
this.host = settings.host;
this.port = settings.port;
this.route = settings.route;
this.browser = WebBrowserManager.getInstance().findBrowserById(settings.browser);
this.interpreter = PhpInterpretersManagerImpl.getInstance(getProject()).findInterpreter(settings.interpreterName);
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
Settings settings = new Settings();
settings.host = this.host;
settings.port = this.port;
settings.route = this.route;
if (this.browser != null)
settings.browser = this.browser.getId().toString();
else
settings.browser = "";
if (this.interpreter != null)
settings.interpreterName = this.interpreter.getName();
else
settings.interpreterName = "";
XmlSerializer.serializeInto(settings, element, new SkipDefaultsSerializationFilter());
super.writeExternal(element);
}
@NotNull
@Override
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new LaravelRunConfSettingsEditor(getProject());
}
@Override
public void checkConfiguration() throws RuntimeConfigurationException {}
@Nullable
@Override
public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws ExecutionException {
return new CommandLineState(executionEnvironment) {
@NotNull
@Override
protected ProcessHandler startProcess() throws ExecutionException {
String phpExec = (interpreter != null? interpreter.getPathToPhpExecutable():"php");
GeneralCommandLine cmd = new GeneralCommandLine(phpExec, "artisan", "serve", "--host=" + host, "--port="+ port);
cmd.setWorkDirectory(project.getBasePath());
OSProcessHandler handler = new OSProcessHandler(cmd);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key outputType) {
String text = event.getText();
if (text != null){
if (text.startsWith("Laravel development server started:")){
BrowserLauncher.getInstance().browse("http://" + host + ":" + port +
(route.startsWith("/") ? route : "/" + route), browser);
handler.removeProcessListener(this);
}
}
}
});
// new LaravelRunMgr(handler, new File(getProject().getBasePath()+("/storage/logs/laravel.log")));
return handler;
}
};
}
public int getPort() {
return port;
}
public String getHost() {
return host;
}
public void setPort(int port) {
this.port = port;
}
public void setHost(String host) {
this.host = host;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public WebBrowser getBrowser() {
return browser;
}
public void setBrowser(WebBrowser browser) {
this.browser = browser;
}
public PhpInterpreter getInterpreter() {
return interpreter;
}
public void setInterpreter(PhpInterpreter interpreter) {
this.interpreter = interpreter;
}
public static class Settings {
public String host;
public int port;
public String route;
public String browser;
public String interpreterName;
}
}
| 3mmarg97/LaravelStorm | src/com/smartbit8/laravelstorm/run/LaravelRunConf.java | Java | mit | 6,140 |
package com.bitdubai.fermat_bnk_api.layer.bnk_wallet.bank_money.exceptions;
import com.bitdubai.fermat_api.FermatException;
/**
* Created by Yordin Alayn on 18.09.15.
*/
public class CantTransactionBankMoneyException extends FermatException {
public static final String DEFAULT_MESSAGE = "Falled To Get Bank Transaction Wallet Bank Money.";
public CantTransactionBankMoneyException(String message, Exception cause, String context, String possibleReason) {
super(message, cause, context, possibleReason);
}
}
| fvasquezjatar/fermat-unused | fermat-bnk-api/src/main/java/com/bitdubai/fermat_bnk_api/layer/bnk_wallet/bank_money/exceptions/CantTransactionBankMoneyException.java | Java | mit | 533 |
/*
* 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 modelo;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author Deivis
*/
public class Cotacao {
private int id;
private Date data;
private Double valor;
private TipoMoeda tipoMoeda;
public TipoMoeda getTipoMoeda() {
return tipoMoeda;
}
public void setTipoMoeda(TipoMoeda tipoMoeda) {
this.tipoMoeda = tipoMoeda;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getData() {
return data;
}
public String getDataString() {
if (this.data != null) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(this.data);
} else {
return null;
}
}
public String getDataStringBr() {
if (this.data != null) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
return df.format(this.data);
} else {
return null;
}
}
public void setData(String data) throws ParseException {
if (!"".equals(data)) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
this.data = df.parse(data);
} else {
this.data = null;
}
}
public void setDataBr(String data) throws ParseException {
if (!"".equals(data)) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
this.data = df.parse(data);
} else {
this.data = null;
}
}
public void setDataString(String data) throws ParseException {
if (!"".equals(data)) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
this.data = df.parse(data);
} else {
this.data = null;
}
}
public Double getValor() {
return valor;
}
public String getValorString() {
return valor.toString();
}
public void setValor(String valor) {
if (!"".equals(valor)) {
this.valor = Double.parseDouble(valor.replace(",", "."));
} else {
this.valor = null;
}
}
}
| deivisvieira/PosJava | src/java/modelo/Cotacao.java | Java | mit | 2,527 |
package br.com.dbsoft.rest.dados;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import br.com.dbsoft.rest.interfaces.IStatus;
@JsonInclude(value=Include.NON_NULL)
@JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class DadosStatus implements IStatus {
private static final long serialVersionUID = -6552296817145232368L;
@JsonProperty("status")
private Boolean wStatus;
@Override
public Boolean getStatus() {
return wStatus;
}
@Override
public void setStatus(Boolean pStatus) {
wStatus = pStatus;
}
}
| dbsoftcombr/dbssdk | src/main/java/br/com/dbsoft/rest/dados/DadosStatus.java | Java | mit | 1,014 |
package com.landenlabs.all_flipanimation;
/**
* Copyright (c) 2015 Dennis Lang (LanDen Labs) landenlabs@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @author Dennis Lang (3/21/2015)
* @see http://landenlabs.com
*
*/
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import android.widget.CheckBox;
import android.widget.TextView;
/**
* Demonstrate rotating View animation using two rotating animations.
*
* @author Dennis Lang (LanDen Labs)
* @see <a href="http://landenlabs.com/android/index-m.html"> author's web-site </a>
* // http://www.inter-fuser.com/2009/08/android-animations-3d-flip.html
*/
public class ActivityRotAnimation extends Activity {
// ---- Layout ----
View mView1;
View mView2;
View mClickView;
DrawView mDrawView;
TextView mAngle1;
TextView mAngle2;
// ---- Data ----
float mCameraZ = -25;
Flip3dAnimation mRotation1;
Flip3dAnimation mRotation2;
boolean mRotateYaxis = true;
boolean mIsForward = true;
boolean mAutoMode = false;
MediaPlayer mSoundClick;
MediaPlayer mSoundShut;
// ---- Timer ----
private Handler m_handler = new Handler();
private int mDurationMsec = 3000;
private Runnable m_updateElapsedTimeTask = new Runnable() {
public void run() {
animateIt();
m_handler.postDelayed(this, mDurationMsec); // Re-execute after msec
}
};
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rot_animation);
mView1 = Ui.viewById(this, R.id.view1);
mView2 = Ui.viewById(this, R.id.view2);
// Create a new 3D rotation with the supplied parameter
mRotation1 = new Flip3dAnimation();
mRotation2 = new Flip3dAnimation();
Ui.<TextView>viewById(this, R.id.side_title).setText("Rotating Animation");
setupUI();
}
/**
* Start animation.
*/
public void animateIt() {
ObjectAnimator.ofFloat(mClickView, View.ALPHA, mClickView.getAlpha(), 0).start();
final float end = 90.0f;
if (mIsForward) {
mRotation1.mFromDegrees = 0.0f;
mRotation1.mToDegrees = end;
mRotation2.mFromDegrees = -end;
mRotation2.mToDegrees = 0.0f;
} else {
mRotation1.mFromDegrees = end;
mRotation1.mToDegrees = 0.0f;
mRotation2.mFromDegrees = 0.0f;
mRotation2.mToDegrees = -end;
}
mIsForward = !mIsForward;
if (mRotateYaxis) {
mRotation1.mCenterX = mView1.getWidth();
mRotation1.mCenterY = mView1.getHeight() / 2.0f;
mRotation2.mCenterX = 0.0f;
mRotation2.mCenterY = mView2.getHeight() / 2.0f;
} else {
mRotation1.mCenterY = 0.0f; // mView1.getHeight();
mRotation1.mCenterX = mView1.getWidth() / 2.0f;
mRotation2.mCenterY = mView1.getHeight(); // 0.0f;
mRotation2.mCenterX = mView2.getWidth() / 2.0f;
}
mRotation1.reset(mView1, mDurationMsec, mCameraZ);
mRotation2.reset(mView2, mDurationMsec, mCameraZ);
mRotation2.setAnimationListener(new Animation.AnimationListener() {
@Override public void onAnimationStart(Animation animation) { }
@Override public void onAnimationEnd(Animation animation) {
mSoundShut.start();
}
@Override public void onAnimationRepeat(Animation animation) { }
});
// Run both animations in parallel.
AnimationSet animationSet = new AnimationSet(true);
animationSet.setInterpolator(new LinearInterpolator());
animationSet.addAnimation(mRotation1);
animationSet.addAnimation(mRotation2);
animationSet.start();
}
public class Flip3dAnimation extends Animation {
float mFromDegrees;
float mToDegrees;
float mCenterX = 0;
float mCenterY = 0;
float mCameraZ = -8;
Camera mCamera;
View mView;
public Flip3dAnimation() {
setFillEnabled(true);
setFillAfter(true);
setFillBefore(true);
}
public void reset(View view, int durationMsec, float cameraZ) {
mCameraZ = cameraZ;
setDuration(durationMsec);
view.clearAnimation(); // This is very important to get 2nd..nth run to work.
view.setAnimation(this);
mView = view;
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mCamera = new Camera();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation trans) {
final float fromDegrees = mFromDegrees;
float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);
final Camera camera = mCamera;
final Matrix matrix = trans.getMatrix();
camera.save();
camera.setLocation(0, 0, mCameraZ);
if (mRotateYaxis)
camera.rotateY(degrees);
else
camera.rotateX(degrees);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-mCenterX, -mCenterY);
matrix.postTranslate(mCenterX, mCenterY);
final float degree3 = degrees;
if (mView == mView1) {
mDrawView.setAngle1(degree3);
mAngle1.setText(String.format("%.0f°", degree3));
} else {
mDrawView.setAngle2(degree3);
mAngle2.setText(String.format("%.0f°", degree3));
}
}
}
/**
* Build User Interface - setup callbacks.
*/
private void setupUI() {
mSoundClick = MediaPlayer.create(this, R.raw.click);
// mSoundClick.setVolume(0.5f, 0.5f);
mSoundShut = MediaPlayer.create(this, R.raw.shut);
// mSoundShut.setVolume(0.3f, 0.3f);
final TextView title = (TextView) this.findViewById(R.id.title);
mClickView = this.findViewById(R.id.click_view);
mClickView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mSoundClick.start();
animateIt();
}
});
final SlideBar seekspeedSB = new SlideBar(this.findViewById(R.id.seekSpeed), "Delay:");
seekspeedSB.setValueChanged(new SlideBar.ValueChanged() {
@Override
public float onValueChanged(View v, float value) {
mDurationMsec = (int) (value = 100 + value * 100);
title.setText(String.format("Delay:%d CameraZ:%.0f", mDurationMsec, mCameraZ));
return value;
}
});
final SlideBar cameraZpos = new SlideBar(this.findViewById(R.id.cameraZpos), "CamZ:");
cameraZpos.setProgress((int) (mCameraZ / -2 + 50));
cameraZpos.setValueChanged(new SlideBar.ValueChanged() {
@Override
public float onValueChanged(View v, float value) {
mCameraZ = value = (50 - value) * 2.0f;
title.setText(String.format("Delay:%d CameraZ:%.0f", mDurationMsec, mCameraZ));
return value;
}
});
final CheckBox autoFlipCb = Ui.viewById(this, R.id.autoflip);
autoFlipCb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mAutoMode = ((CheckBox) v).isChecked();
if (mAutoMode) {
m_handler.postDelayed(m_updateElapsedTimeTask, 0);
} else {
m_handler.removeCallbacks(m_updateElapsedTimeTask);
}
}
});
final CheckBox yaxisCb = Ui.viewById(this, R.id.yaxis);
mRotateYaxis = yaxisCb.isChecked();
yaxisCb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean autoMode = mAutoMode;
if (autoMode)
autoFlipCb.performClick(); // Stop automatic animation.
mRotateYaxis = ((CheckBox) v).isChecked();
if (autoMode)
autoFlipCb.performClick(); // Restart automatic animation.
}
});
mDrawView = Ui.viewById(this, R.id.drawView);
mAngle1 = Ui.viewById(this, R.id.angle1);
mAngle2 = Ui.viewById(this, R.id.angle2);
}
} | landenlabs2/all_FlipAnimation | app/src/main/java/com/landenlabs/all_flipanimation/ActivityRotAnimation.java | Java | mit | 10,273 |
package com.example.apahlavan1.top10downloader;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | AriaPahlavan/Android-Apps | Top10Downloader/app/src/androidTest/java/com/example/apahlavan1/top10downloader/ApplicationTest.java | Java | mit | 369 |
package com.kkk.retrofitdemo;
import com.kkk.retrofitdemo.bean.Repo;
import com.kkk.retrofitdemo.bean.SearchRepoResult;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable;
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
@GET("search/repositories")
Observable<SearchRepoResult> searchRepos(@Query("q") String keyword,
@Query("sort") String sort,
@Query("order") String order);
} | kylm53/learn-android | RetrofitDemo/src/main/java/com/kkk/retrofitdemo/GitHubService.java | Java | mit | 655 |
package gui;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Toolkit;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.DefaultComboBoxModel;
import javax.swing.UIManager;
import app.Applikation;
import javax.swing.DropMode;
import parsers.*;
import java.io.IOException;
import java.util.Random;
public class GUI {
private JFrame frmImageDownloader;
private JTextField txtInsertTagHere;
private JTextArea textArea;
private JSpinner PageSpinner;
private JComboBox<Object> comboBox;
private ImageParser parser;
private JButton Parsebtn;
private JTextField DelayField;
private BufferedImage bgImage;
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JLabel lblTag;
private final String FOURCHAN_THREAD = "4chan-Thread - http://boards.4chan.org/x/res/123123";
private final String FOURCHAN_BOARD = "4chan-Board - http://boards.4chan.org/x/catalog";
private final String INFINITYCHAN_THREAD = "Infinity Chan Thread - https://8chan.co/BOARD/res/THREADNR.html";
private final String INFINITYCHAN_BOARD = "Infinity Chan Board - https://8chan.co/BOARDNR/";
private final String PAHEAL = "http://rule34.paheal.net/";
private final String XXX = "http://rule34.xxx/";
private final String GELBOORU = "http://gelbooru.com/";
private final String R34HENTAI = "http://rule34hentai.net/";
private final String TUMBLR = "Tumblr Artist - http://XxXxXxX.tumblr.com";
private final String IMGUR = "Imgur-Album - http://imgur.com/a/xXxXx";
private final String GE_HENTAI_SINGLE = "http://g.e-hentai.org/ - Single Album Page";
private final String GE_HENTAI_MORE = "http://g.e-hentai.org/ - >=1 Pages";
private final String ARCHIVE_MOE_THREAD = "archive.moe/fgts.jp (Thread) - https://archive.moe/BOARD/thread/THREADNR/";
private final String ARCHIVE_MOE_BOARD = "archive-moe (Board) - https://archive.moe/BOARD/";
private final String FGTS_JP_BOARD = "fgts.jp (Board) - http://fgts.jp/BOARD/";
private boolean parsing;
public GUI() {
System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
frmImageDownloader = new JFrame();
frmImageDownloader.setIconImage(Toolkit.getDefaultToolkit()
.getImage(this.getClass().getResource("/images/icon.png")));
frmImageDownloader.getContentPane().setBackground(
UIManager.getColor("Button.background"));
frmImageDownloader.setResizable(false);
frmImageDownloader.setTitle("Image Downloader v1.5.1");
frmImageDownloader.setBounds(100, 100, 761, 558);
frmImageDownloader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmImageDownloader.getContentPane().setLayout(null);
JLabel lblMadeByLars = new JLabel("@ berserkingyadis");
lblMadeByLars.setFont(new Font("Dialog", Font.PLAIN, 12));
lblMadeByLars.setBounds(14, 468, 157, 40);
frmImageDownloader.getContentPane().add(lblMadeByLars);
JScrollPane scrollPane = new JScrollPane();
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(205, 185, 542, 331);
scrollPane.setAutoscrolls(true);
frmImageDownloader.getContentPane().add(scrollPane);
try {
bgImage = ImageIO.read(Applikation.class.getResource("/images/bg" + (new Random().nextInt(4) + 1) + ".png"));
} catch (IOException e) {
appendLog("Could not get Background Image", true);
}
textArea = new BackgroundArea(bgImage);
textArea.setEditable(false);
textArea.setDropMode(DropMode.INSERT);
textArea.setColumns(2);
textArea.setFont(new Font("Monospaced", Font.PLAIN, 11));
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
txtInsertTagHere = new JTextField();
txtInsertTagHere.setText("insert tag here");
txtInsertTagHere.setFont(new Font("Dialog", Font.PLAIN, 14));
txtInsertTagHere.setBounds(14, 208, 181, 30);
frmImageDownloader.getContentPane().add(txtInsertTagHere);
txtInsertTagHere.setColumns(10);
lblTag = new JLabel("Tag:");
lblTag.setFont(new Font("Dialog", Font.BOLD, 12));
lblTag.setBounds(12, 183, 175, 24);
frmImageDownloader.getContentPane().add(lblTag);
Parsebtn = new JButton("start parsing");
Parsebtn.setBounds(12, 372, 181, 85);
frmImageDownloader.getContentPane().add(Parsebtn);
PageSpinner = new JSpinner();
PageSpinner.setModel(new SpinnerNumberModel(new Integer(1),
new Integer(1), null, new Integer(1)));
PageSpinner.setBounds(155, 249, 40, 30);
frmImageDownloader.getContentPane().add(PageSpinner);
lblNewLabel = new JLabel("Pages to parse:");
lblNewLabel.setFont(new Font("Dialog", Font.BOLD, 11));
lblNewLabel.setBounds(12, 249, 123, 30);
frmImageDownloader.getContentPane().add(lblNewLabel);
lblNewLabel_1 = new JLabel("1 Page = 50-60 Pictures");
lblNewLabel_1.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewLabel_1.setBounds(12, 290, 175, 30);
frmImageDownloader.getContentPane().add(lblNewLabel_1);
comboBox = new JComboBox<Object>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
switch (comboBox.getSelectedItem().toString()) {
case GE_HENTAI_SINGLE:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(false);
lblTag.setText("Page URL:");
txtInsertTagHere.setText("insert page URL here");
lblNewLabel.setEnabled(false);
break;
case GE_HENTAI_MORE:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Album URL:");
txtInsertTagHere.setText("insert album URL here");
break;
case PAHEAL:
case GELBOORU:
case R34HENTAI:
case XXX:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Tag:");
txtInsertTagHere.setText("insert tag here");
lblNewLabel.setText("Pages to parse:");
break;
case FOURCHAN_THREAD:
case INFINITYCHAN_THREAD:
case ARCHIVE_MOE_THREAD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setText("Pages to parse:");
lblNewLabel.setEnabled(false);
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(false);
lblTag.setText("Thread URL:");
txtInsertTagHere.setText("insert link here");
break;
case FOURCHAN_BOARD:
case INFINITYCHAN_BOARD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setEnabled(true);
lblNewLabel.setText("Threads to parse:");
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(true);
lblTag.setText("Board(eg: v or e):");
txtInsertTagHere.setText("insert Board Letter here");
break;
case ARCHIVE_MOE_BOARD:
case FGTS_JP_BOARD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setEnabled(true);
lblNewLabel.setText("Sites to parse(1 Site = 100 Threads):");
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(true);
lblTag.setText("Board(eg: v or e):");
txtInsertTagHere.setText("insert Board Letter here");
break;
case TUMBLR:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Artist name:");
txtInsertTagHere.setText("insert artist name here");
lblNewLabel.setText("Pages to parse:");
break;
case IMGUR:
lblNewLabel.setEnabled(false);
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(false);
DelayField.setText("100");
lblTag.setText("Album Letters: (eg: \"Bl1QP\")");
txtInsertTagHere.setText("insert the letters here");
Parsebtn.setText("start parsing");
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setEnabled(true);
break;
}
}
});
comboBox.setModel(new DefaultComboBoxModel<Object>(
new String[]{
PAHEAL,
XXX,
R34HENTAI,
GELBOORU,
GE_HENTAI_SINGLE,
GE_HENTAI_MORE,
FOURCHAN_THREAD,
FOURCHAN_BOARD,
//ARCHIVE_MOE_THREAD,
//ARCHIVE_MOE_BOARD,
//FGTS_JP_BOARD,
INFINITYCHAN_THREAD,
INFINITYCHAN_BOARD,
TUMBLR,
IMGUR
}));
comboBox.setBounds(434, 35, 313, 24);
comboBox.setFont(new Font("Dialog", Font.PLAIN, 11));
frmImageDownloader.getContentPane().add(comboBox);
JLabel lblNewLabel_2 = new JLabel("choose the Site to parse:");
lblNewLabel_2.setFont(new Font("Dialog", Font.BOLD, 12));
lblNewLabel_2.setBounds(434, 5, 268, 30);
frmImageDownloader.getContentPane().add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel(
"<html>\nWelcome to the Image Downloader. <br>\nYour can enter the Tag of the images you are looking for below. <br>\nImgur is not supported yet. <br>\nWhen you click parse a folder with the name of the tag will be <br>\ncreated and the images will be downloaded into it. <br><br>\nI strongly advise you to not set the delay under 100 ms, <br>\nif you abuse this you will get banned from the site <br><br>\n\nhave fun :)\n\n\n</html>");
lblNewLabel_3.setVerticalAlignment(SwingConstants.TOP);
lblNewLabel_3.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewLabel_3.setBounds(12, 12, 404, 195);
frmImageDownloader.getContentPane().add(lblNewLabel_3);
JLabel lblDelay = new JLabel("Delay(ms):");
lblDelay.setFont(new Font("Dialog", Font.BOLD, 12));
lblDelay.setBounds(12, 331, 85, 30);
frmImageDownloader.getContentPane().add(lblDelay);
DelayField = new JTextField();
DelayField.setText("100");
DelayField.setBounds(140, 331, 55, 30);
frmImageDownloader.getContentPane().add(DelayField);
DelayField.setColumns(10);
JLabel lblPahealSearchFor = new JLabel(
"<html>\r\npaheal: Search for Characters or Artists\r\n\t\t eg: Tifa Lockhart, Fugtrup<br>\r\nrule34.xxx: Search for things\r\n\t\teg: long hair, hand on hip<br>\r\ngelbooru: Search for what you want<br>\r\n4chan/8chan: paste the Thread URL/Boardletter in the\r\n\t\tTextfield <br>\r\ntumblr: enter the artist's name<br>imgur: enter the album id</html>");
lblPahealSearchFor.setVerticalAlignment(SwingConstants.TOP);
lblPahealSearchFor.setFont(new Font("Dialog", Font.PLAIN, 11));
lblPahealSearchFor.setBounds(434, 71, 313, 109);
frmImageDownloader.getContentPane().add(lblPahealSearchFor);
Parsebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (parsing) {
parser.diePlease();
parser = null;
} else {
GUI g = getGUI();
textArea.setText("");
frmImageDownloader
.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
String tag = txtInsertTagHere.getText().replace(' ', '_');
int pages = (int) PageSpinner.getValue();
String site = comboBox.getSelectedItem().toString();
int delay = Integer.parseInt(DelayField.getText());
switch (site) {
case PAHEAL:
parser = new PahealParser();
parser.setup(tag, pages, g, delay);
break;
case XXX:
parser = new XXXParser();
parser.setup(tag, pages, g, delay);
break;
case R34HENTAI:
parser = new R34HentaiParser();
parser.setup(tag, pages, g, delay);
break;
case GELBOORU:
parser = new GelBooruParser();
parser.setup(tag, pages, g, delay);
break;
case FOURCHAN_THREAD:
parser = new FourChanParser(tag, delay, g, 0);
break;
case FOURCHAN_BOARD:
parser = new FourChanParser(tag, delay, g, 1, pages);
break;
case INFINITYCHAN_THREAD:
parser = new InfinityChanParser(tag, delay, g, 0);
break;
case INFINITYCHAN_BOARD:
parser = new InfinityChanParser(tag, delay, g, 1, pages);
break;
case ARCHIVE_MOE_THREAD:
parser = new ArchiveMoeParser(tag, delay, g, 0);
break;
case ARCHIVE_MOE_BOARD:
parser = new ArchiveMoeParser(tag, delay, g, 1, pages);
break;
case FGTS_JP_BOARD:
parser = new ArchiveMoeParser(tag, delay, g, 2, pages);
break;
case TUMBLR:
parser = new TumblrParser();
parser.setup(tag, pages, g, delay);
break;
case IMGUR:
parser = new ImgurParser(tag, delay, g);
break;
case GE_HENTAI_SINGLE:
parser = new GEHentaiParser(tag, delay, g, false, pages);
break;
case GE_HENTAI_MORE:
parser = new GEHentaiParser(tag, delay, g, true, pages);
}
parser.start();
parsing = true;
Parsebtn.setText("stop parsing");
}
}
});
frmImageDownloader.setVisible(true);
parsing = false;
}
public void appendLog(String txt, boolean brk) {
textArea.append(txt);
if (brk)
textArea.append("\n");
}
private GUI getGUI() {
return this;
}
public void reportback() {
Parsebtn.setEnabled(true);
frmImageDownloader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Parsebtn.setText("start parsing");
parsing = false;
}
}
| berserkingyadis/ImageDownloader | src/main/java/gui/GUI.java | Java | mit | 18,735 |
/*
* 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 curveavg;
/**
* Small helper class for computing the circular arc between two points.
* @author Sebastian Weiss
*/
public class CircularArc {
private static final float EPSILON = 1e-5f;
private final Vector3f P;
private final Vector3f A;
private final Vector3f B;
private Vector3f C;
private float r;
private Vector3f N;
private Vector3f CA;
private float angle;
/**
* Computes the circular arc between the points A and B, with the point P on the
* medial axis (i.e. |A-N|==|B-N|).
* @param P the point on the medial axis, A and B are at the same distance from P
* @param A the closest point from P on the first control curve
* @param B the closest point from P on the second control curve
*/
public CircularArc(Vector3f P, Vector3f A, Vector3f B) {
this.P = P;
this.A = A;
this.B = B;
computeCenter();
}
private void computeCenter() {
Vector3f PA = A.subtract(P);
Vector3f PB = B.subtract(P);
N = PA.cross(PB);
//check for degenerated case
if (N.lengthSquared() <= EPSILON*EPSILON) {
// System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line");
r = 0;
return; //Degenerated to a line
}
//compute directions of A,B to the center C
N.normalizeLocal();
PA.normalizeLocal();
PB.normalizeLocal();
Vector3f U = N.cross(PA);
Vector3f V = N.cross(PB);
//C is now the intersection of A+aU and B+bV
Vector3f UxV = U.cross(V);
Vector3f rhs = (B.subtract(A)).cross(V);
float a1 = rhs.x / UxV.x;
float a2 = rhs.y / UxV.y;
float a3 = rhs.z / UxV.z; //all a1,a2,a3 have to be equal
C = A.addScaled(a1, U);
//compute radius and angle
r = C.distance(A);
CA = A.subtract(C);
angle = (CA.normalize()).angleBetween((B.subtract(C).normalizeLocal()));
}
private float computeCenter_old() {
//check for degenerated case
Vector3f PA = A.subtract(P);
Vector3f PB = B.subtract(P);
N = PA.cross(PB);
if (N.lengthSquared() <= EPSILON*EPSILON) {
// System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line");
return 0; //Degenerated to a line
}
//define orthonormal basis I,J,K
N.normalizeLocal();
Vector3f I = PA.normalize();
Vector3f J = N.cross(I);
Vector3f K = N;
Vector3f IxK = I.cross(K);
Vector3f JxK = J.cross(K);
//project points in the plane PAB
Vector3f PAxN = PA.cross(N);
Vector3f PBxN = PB.cross(N);
Vector2f P2 = new Vector2f(0, 0);
Vector2f A2 = new Vector2f(PA.dot(JxK)/I.dot(JxK), PA.dot(IxK)/J.dot(IxK));
Vector2f B2 = new Vector2f(PB.dot(JxK)/I.dot(JxK), PB.dot(IxK)/J.dot(IxK));
//compute time t of C=P+tPA°
float t;
if (B2.x == A2.x) {
t = (B2.y - A2.y) / (A2.x - B2.x);
} else {
t = (B2.x - A2.x) / (A2.y - B2.y);
}
//compute C
Vector2f PArot = new Vector2f(A.y-P.y, P.x-A.x);
Vector2f C2 = P2.addLocal(PArot.multLocal(t));
//project back
C = new Vector3f(P);
C.addScaledLocal(C2.x, I);
C.addScaledLocal(C2.y, J);
//Debug
// System.out.println("A="+A+", B="+B+" P="+P+" -> I="+I+", J="+J+", K="+K+", P'="+P2+", A'="+A2+", B'="+B2+", t="+t+", C'="+C2+", C="+C);
//set radius
return C.distance(A);
}
/**
* Computes a point on the actual circular arc from A to B.
* The vectors C and the float r are the result from
* {@link #computeCenter(curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f) }.
* It interpolates from A (alpha=0) to B (alpha=1) in a circular arc.
* @param alpha
* @return
*/
public Vector3f getPointOnArc(float alpha) {
if (isDegenerated()) {
Vector3f V = new Vector3f();
return V.interpolateLocal(A, B, alpha); //degenerated case
}
//normal case, rotate
Vector3f V = rotate(alpha*angle, CA, N);
return V.addLocal(C);
}
private static Vector3f rotate(float angle, Vector3f X, Vector3f N) {
Vector3f W = N.mult(N.dot(X));
Vector3f U = X.subtract(W);
return W.add(U.mult((float) Math.cos(angle)))
.subtract(N.cross(U).mult((float) Math.sin(angle)));
}
public boolean isDegenerated() {
return r==0;
}
public Vector3f getCenter() {
return C;
}
public float getRadius() {
return r;
}
public Vector3f getNormal() {
return N;
}
public float getAngle() {
return angle;
}
@Override
public String toString() {
return "CircularArc{" + "P=" + P + ", A=" + A + ", B=" + B + " -> C=" + C + ", r=" + r + ", N=" + N + ", angle=" + angle + '}';
}
}
| shamanDevel/CurveAverage | src/curveavg/CircularArc.java | Java | mit | 4,540 |
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import com.sendgrid.helpers.mail.objects.Personalization;
import java.io.IOException;
public class SingleEmailMultipleRecipients {
public static void main(String[] args) throws IOException {
final Mail mail = new Mail();
mail.setFrom(new Email("test@example.com", "Example User"));
mail.setSubject("Sending with Twilio SendGrid is Fun");
final Personalization personalization = new Personalization();
personalization.addTo(new Email("test1@example.com", "Example User1"));
personalization.addTo(new Email("test2@example.com", "Example User2"));
personalization.addTo(new Email("test3@example.com", "Example User3"));
mail.addPersonalization(personalization);
mail.addContent(new Content("text/plain", "and easy to do anywhere, even with Java"));
mail.addContent(new Content("text/html", "<strong>and easy to do anywhere, even with Java</strong>"));
send(mail);
}
private static void send(final Mail mail) throws IOException {
final SendGrid client = new SendGrid(System.getenv("SENDGRID_API_KEY"));
final Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
final Response response = client.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
}
}
| sendgrid/sendgrid-java | examples/helpers/mail/SingleEmailMultipleRecipients.java | Java | mit | 1,666 |
package org.workcraft.plugins.circuit;
import org.workcraft.annotations.DisplayName;
import org.workcraft.annotations.Hotkey;
import org.workcraft.annotations.SVGIcon;
import org.workcraft.dom.Node;
import org.workcraft.dom.visual.BoundingBoxHelper;
import org.workcraft.dom.visual.DrawRequest;
import org.workcraft.formula.BooleanFormula;
import org.workcraft.formula.visitors.FormulaRenderingResult;
import org.workcraft.formula.visitors.FormulaToGraphics;
import org.workcraft.gui.tools.Decoration;
import org.workcraft.observation.PropertyChangedEvent;
import org.workcraft.observation.StateEvent;
import org.workcraft.observation.StateObserver;
import org.workcraft.plugins.circuit.renderers.ComponentRenderingResult.RenderType;
import org.workcraft.serialisation.NoAutoSerialisation;
import org.workcraft.utils.ColorUtils;
import org.workcraft.utils.Hierarchy;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.font.FontRenderContext;
import java.awt.geom.*;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
@DisplayName("Input/output port")
@Hotkey(KeyEvent.VK_P)
@SVGIcon("images/circuit-node-port.svg")
public class VisualFunctionContact extends VisualContact implements StateObserver {
private static final double size = 0.3;
private static FontRenderContext context = new FontRenderContext(AffineTransform.getScaleInstance(1000.0, 1000.0), true, true);
private static Font functionFont;
private FormulaRenderingResult renderedSetFunction = null;
private FormulaRenderingResult renderedResetFunction = null;
private static double functionFontSize = CircuitSettings.getFunctionFontSize();
static {
try {
functionFont = Font.createFont(Font.TYPE1_FONT, ClassLoader.getSystemResourceAsStream("fonts/eurm10.pfb"));
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
}
public VisualFunctionContact(FunctionContact contact) {
super(contact);
}
@Override
public FunctionContact getReferencedComponent() {
return (FunctionContact) super.getReferencedComponent();
}
@NoAutoSerialisation
public BooleanFormula getSetFunction() {
return getReferencedComponent().getSetFunction();
}
@NoAutoSerialisation
public void setSetFunction(BooleanFormula setFunction) {
if (getParent() instanceof VisualFunctionComponent) {
VisualFunctionComponent p = (VisualFunctionComponent) getParent();
p.invalidateRenderingResult();
}
renderedSetFunction = null;
getReferencedComponent().setSetFunction(setFunction);
}
@NoAutoSerialisation
public BooleanFormula getResetFunction() {
return getReferencedComponent().getResetFunction();
}
@NoAutoSerialisation
public void setForcedInit(boolean value) {
getReferencedComponent().setForcedInit(value);
}
@NoAutoSerialisation
public boolean getForcedInit() {
return getReferencedComponent().getForcedInit();
}
@NoAutoSerialisation
public void setInitToOne(boolean value) {
getReferencedComponent().setInitToOne(value);
}
@NoAutoSerialisation
public boolean getInitToOne() {
return getReferencedComponent().getInitToOne();
}
@NoAutoSerialisation
public void setResetFunction(BooleanFormula resetFunction) {
if (getParent() instanceof VisualFunctionComponent) {
VisualFunctionComponent p = (VisualFunctionComponent) getParent();
p.invalidateRenderingResult();
}
renderedResetFunction = null;
getReferencedComponent().setResetFunction(resetFunction);
}
public void invalidateRenderedFormula() {
renderedSetFunction = null;
renderedResetFunction = null;
}
private Font getFunctionFont() {
return functionFont.deriveFont((float) CircuitSettings.getFunctionFontSize());
}
private FormulaRenderingResult getRenderedSetFunction() {
if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) {
functionFontSize = CircuitSettings.getContactFontSize();
renderedSetFunction = null;
}
BooleanFormula setFunction = getReferencedComponent().getSetFunction();
if (setFunction == null) {
renderedSetFunction = null;
} else if (renderedSetFunction == null) {
renderedSetFunction = FormulaToGraphics.render(setFunction, context, getFunctionFont());
}
return renderedSetFunction;
}
private Point2D getSetFormulaOffset() {
double xOffset = size;
double yOffset = -size / 2;
FormulaRenderingResult renderingResult = getRenderedSetFunction();
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
xOffset = -(size + renderingResult.boundingBox.getWidth());
}
}
return new Point2D.Double(xOffset, yOffset);
}
private Rectangle2D getSetBoundingBox() {
Rectangle2D bb = null;
FormulaRenderingResult setRenderingResult = getRenderedSetFunction();
if (setRenderingResult != null) {
bb = BoundingBoxHelper.move(setRenderingResult.boundingBox, getSetFormulaOffset());
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
bb = BoundingBoxHelper.transform(bb, rotateTransform);
}
}
return bb;
}
private FormulaRenderingResult getRenderedResetFunction() {
if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) {
functionFontSize = CircuitSettings.getContactFontSize();
renderedResetFunction = null;
}
BooleanFormula resetFunction = getReferencedComponent().getResetFunction();
if (resetFunction == null) {
renderedResetFunction = null;
} else if (renderedResetFunction == null) {
renderedResetFunction = FormulaToGraphics.render(resetFunction, context, getFunctionFont());
}
return renderedResetFunction;
}
private Point2D getResetFormulaOffset() {
double xOffset = size;
double yOffset = size / 2;
FormulaRenderingResult renderingResult = getRenderedResetFunction();
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
xOffset = -(size + renderingResult.boundingBox.getWidth());
}
yOffset = size / 2 + renderingResult.boundingBox.getHeight();
}
return new Point2D.Double(xOffset, yOffset);
}
private Rectangle2D getResetBoundingBox() {
Rectangle2D bb = null;
FormulaRenderingResult renderingResult = getRenderedResetFunction();
if (renderingResult != null) {
bb = BoundingBoxHelper.move(renderingResult.boundingBox, getResetFormulaOffset());
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
bb = BoundingBoxHelper.transform(bb, rotateTransform);
}
}
return bb;
}
private void drawArrow(Graphics2D g, int arrowType, double arrX, double arrY) {
double s = CircuitSettings.getFunctionFontSize();
g.setStroke(new BasicStroke((float) s / 25));
double s1 = 0.75 * s;
double s2 = 0.45 * s;
double s3 = 0.30 * s;
if (arrowType == 1) {
// arrow down
Line2D line = new Line2D.Double(arrX, arrY - s1, arrX, arrY - s3);
Path2D path = new Path2D.Double();
path.moveTo(arrX - 0.05, arrY - s3);
path.lineTo(arrX + 0.05, arrY - s3);
path.lineTo(arrX, arrY);
path.closePath();
g.fill(path);
g.draw(line);
} else if (arrowType == 2) {
// arrow up
Line2D line = new Line2D.Double(arrX, arrY, arrX, arrY - s2);
Path2D path = new Path2D.Double();
path.moveTo(arrX - 0.05, arrY - s2);
path.lineTo(arrX + 0.05, arrY - s2);
path.lineTo(arrX, arrY - s1);
path.closePath();
g.fill(path);
g.draw(line);
}
}
private void drawFormula(Graphics2D g, int arrowType, Point2D offset, FormulaRenderingResult renderingResult) {
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
AffineTransform savedTransform = g.getTransform();
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
g.transform(rotateTransform);
}
double dXArrow = -0.15;
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
dXArrow = renderingResult.boundingBox.getWidth() + 0.15;
}
drawArrow(g, arrowType, offset.getX() + dXArrow, offset.getY());
g.translate(offset.getX(), offset.getY());
renderingResult.draw(g);
g.setTransform(savedTransform);
}
}
@Override
public void draw(DrawRequest r) {
if (needsFormulas()) {
Graphics2D g = r.getGraphics();
Decoration d = r.getDecoration();
g.setColor(ColorUtils.colorise(getForegroundColor(), d.getColorisation()));
FormulaRenderingResult renderingResult;
renderingResult = getRenderedSetFunction();
if (renderingResult != null) {
Point2D offset = getSetFormulaOffset();
drawFormula(g, 2, offset, renderingResult);
}
renderingResult = getRenderedResetFunction();
if (renderingResult != null) {
Point2D offset = getResetFormulaOffset();
drawFormula(g, 1, offset, renderingResult);
}
}
super.draw(r);
}
private boolean needsFormulas() {
boolean result = false;
Node parent = getParent();
if (parent != null) {
// Primary input port
if (!(parent instanceof VisualCircuitComponent) && isInput()) {
result = true;
}
// Output port of a BOX-rendered component
if ((parent instanceof VisualFunctionComponent) && isOutput()) {
VisualFunctionComponent component = (VisualFunctionComponent) parent;
if (component.getRenderType() == RenderType.BOX) {
result = true;
}
}
}
return result;
}
@Override
public Rectangle2D getBoundingBoxInLocalSpace() {
Rectangle2D bb = super.getBoundingBoxInLocalSpace();
if (needsFormulas()) {
bb = BoundingBoxHelper.union(bb, getSetBoundingBox());
bb = BoundingBoxHelper.union(bb, getResetBoundingBox());
}
return bb;
}
private Collection<VisualFunctionContact> getAllContacts() {
HashSet<VisualFunctionContact> result = new HashSet<>();
Node root = Hierarchy.getRoot(this);
if (root != null) {
result.addAll(Hierarchy.getDescendantsOfType(root, VisualFunctionContact.class));
}
return result;
}
@Override
public void notify(StateEvent e) {
if (e instanceof PropertyChangedEvent) {
PropertyChangedEvent pc = (PropertyChangedEvent) e;
String propertyName = pc.getPropertyName();
if (propertyName.equals(FunctionContact.PROPERTY_SET_FUNCTION) || propertyName.equals(FunctionContact.PROPERTY_RESET_FUNCTION)) {
invalidateRenderedFormula();
}
if (propertyName.equals(Contact.PROPERTY_NAME)) {
for (VisualFunctionContact vc : getAllContacts()) {
vc.invalidateRenderedFormula();
}
}
}
super.notify(e);
}
}
| tuura/workcraft | workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualFunctionContact.java | Java | mit | 13,140 |
package net.dirtyfilthy.bouncycastle.asn1.nist;
import net.dirtyfilthy.bouncycastle.asn1.DERObjectIdentifier;
import net.dirtyfilthy.bouncycastle.asn1.sec.SECNamedCurves;
import net.dirtyfilthy.bouncycastle.asn1.sec.SECObjectIdentifiers;
import net.dirtyfilthy.bouncycastle.asn1.x9.X9ECParameters;
import net.dirtyfilthy.bouncycastle.util.Strings;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* Utility class for fetching curves using their NIST names as published in FIPS-PUB 186-2
*/
public class NISTNamedCurves
{
static final Hashtable objIds = new Hashtable();
static final Hashtable names = new Hashtable();
static void defineCurve(String name, DERObjectIdentifier oid)
{
objIds.put(name, oid);
names.put(oid, name);
}
static
{
// TODO Missing the "K-" curves
defineCurve("B-571", SECObjectIdentifiers.sect571r1);
defineCurve("B-409", SECObjectIdentifiers.sect409r1);
defineCurve("B-283", SECObjectIdentifiers.sect283r1);
defineCurve("B-233", SECObjectIdentifiers.sect233r1);
defineCurve("B-163", SECObjectIdentifiers.sect163r2);
defineCurve("P-521", SECObjectIdentifiers.secp521r1);
defineCurve("P-384", SECObjectIdentifiers.secp384r1);
defineCurve("P-256", SECObjectIdentifiers.secp256r1);
defineCurve("P-224", SECObjectIdentifiers.secp224r1);
defineCurve("P-192", SECObjectIdentifiers.secp192r1);
}
public static X9ECParameters getByName(
String name)
{
DERObjectIdentifier oid = (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name));
if (oid != null)
{
return getByOID(oid);
}
return null;
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters getByOID(
DERObjectIdentifier oid)
{
return SECNamedCurves.getByOID(oid);
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DERObjectIdentifier getOID(
String name)
{
return (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name));
}
/**
* return the named curve name represented by the given object identifier.
*/
public static String getName(
DERObjectIdentifier oid)
{
return (String)names.get(oid);
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static Enumeration getNames()
{
return objIds.keys();
}
}
| dirtyfilthy/dirtyfilthy-bouncycastle | net/dirtyfilthy/bouncycastle/asn1/nist/NISTNamedCurves.java | Java | mit | 2,937 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.