repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
nikhaldi/android-view-selector | src/robolectric2-test/test/com/nikhaldimann/viewselector/robolectric2/attributes/ViewAttributesTest.java | // Path: src/robolectric2-test/test/com/nikhaldimann/viewselector/robolectric2/testutil/Robolectric2ViewFactory.java
// public class Robolectric2ViewFactory extends ProvidedContextViewFactory {
//
// public Robolectric2ViewFactory() {
// super(Robolectric.application);
// }
//
// }
//
// Path: src/test-lib/src/com/nikhaldimann/viewselector/test/abstrakt/attributes/AbstractViewAttributesTest.java
// public abstract class AbstractViewAttributesTest extends ViewSelectorAndroidTestCase {
//
// @Test
// public void testGetGetterMethodName() {
// assertEquals("getText", ViewAttributes.getGetterMethodName("text"));
// assertEquals("getText", ViewAttributes.getGetterMethodName("Text"));
// assertEquals("getFooText", ViewAttributes.getGetterMethodName("fooText"));
// }
//
// @Test
// public void testGetGetterMethodNameBooleanAttribute() {
// assertEquals("isFoo", ViewAttributes.getGetterMethodName("isFoo"));
// assertEquals("hasFoo", ViewAttributes.getGetterMethodName("hasFoo"));
// assertEquals("getIs", ViewAttributes.getGetterMethodName("is"));
// assertEquals("getIsland", ViewAttributes.getGetterMethodName("island"));
// assertEquals("getHas", ViewAttributes.getGetterMethodName("has"));
// assertEquals("getHash", ViewAttributes.getGetterMethodName("hash"));
// }
//
// @Test
// public void testCallGetter() {
// TextView view = viewFactory.createTextView();
// view.setText("foo");
// view.setInputType(InputType.TYPE_CLASS_TEXT);
// view.setVisibility(View.INVISIBLE);
// assertEquals("foo", ViewAttributes.callGetter(view, "getText").toString());
// assertEquals(null, ViewAttributes.callGetter(view, "getTag"));
// assertEquals(InputType.TYPE_CLASS_TEXT, ViewAttributes.callGetter(view, "getInputType"));
// assertEquals(false, ViewAttributes.callGetter(view, "isShown"));
// // TODO need to figure out how to deal with base class methods in Robolectric
// }
//
// @Test
// public void testCallGetterNoSuchMethod() {
// try {
// ViewAttributes.callGetter(viewFactory.createTextView(), "getFoo");
// fail();
// } catch (AttributeAccessException ex) {
// // expected
// }
// }
//
// }
//
// Path: src/test-lib/src/com/nikhaldimann/viewselector/test/util/ViewFactory.java
// public interface ViewFactory {
//
// TextView createTextView();
//
// LinearLayout createLinearLayout();
//
// FrameLayout createFrameLayout();
//
// }
| import org.junit.runner.RunWith;
import com.nikhaldimann.viewselector.robolectric2.testutil.Robolectric2ViewFactory;
import com.nikhaldimann.viewselector.test.abstrakt.attributes.AbstractViewAttributesTest;
import com.nikhaldimann.viewselector.test.util.ViewFactory;
import org.robolectric.RobolectricTestRunner; | package com.nikhaldimann.viewselector.robolectric2.attributes;
@RunWith(RobolectricTestRunner.class)
public class ViewAttributesTest extends AbstractViewAttributesTest {
| // Path: src/robolectric2-test/test/com/nikhaldimann/viewselector/robolectric2/testutil/Robolectric2ViewFactory.java
// public class Robolectric2ViewFactory extends ProvidedContextViewFactory {
//
// public Robolectric2ViewFactory() {
// super(Robolectric.application);
// }
//
// }
//
// Path: src/test-lib/src/com/nikhaldimann/viewselector/test/abstrakt/attributes/AbstractViewAttributesTest.java
// public abstract class AbstractViewAttributesTest extends ViewSelectorAndroidTestCase {
//
// @Test
// public void testGetGetterMethodName() {
// assertEquals("getText", ViewAttributes.getGetterMethodName("text"));
// assertEquals("getText", ViewAttributes.getGetterMethodName("Text"));
// assertEquals("getFooText", ViewAttributes.getGetterMethodName("fooText"));
// }
//
// @Test
// public void testGetGetterMethodNameBooleanAttribute() {
// assertEquals("isFoo", ViewAttributes.getGetterMethodName("isFoo"));
// assertEquals("hasFoo", ViewAttributes.getGetterMethodName("hasFoo"));
// assertEquals("getIs", ViewAttributes.getGetterMethodName("is"));
// assertEquals("getIsland", ViewAttributes.getGetterMethodName("island"));
// assertEquals("getHas", ViewAttributes.getGetterMethodName("has"));
// assertEquals("getHash", ViewAttributes.getGetterMethodName("hash"));
// }
//
// @Test
// public void testCallGetter() {
// TextView view = viewFactory.createTextView();
// view.setText("foo");
// view.setInputType(InputType.TYPE_CLASS_TEXT);
// view.setVisibility(View.INVISIBLE);
// assertEquals("foo", ViewAttributes.callGetter(view, "getText").toString());
// assertEquals(null, ViewAttributes.callGetter(view, "getTag"));
// assertEquals(InputType.TYPE_CLASS_TEXT, ViewAttributes.callGetter(view, "getInputType"));
// assertEquals(false, ViewAttributes.callGetter(view, "isShown"));
// // TODO need to figure out how to deal with base class methods in Robolectric
// }
//
// @Test
// public void testCallGetterNoSuchMethod() {
// try {
// ViewAttributes.callGetter(viewFactory.createTextView(), "getFoo");
// fail();
// } catch (AttributeAccessException ex) {
// // expected
// }
// }
//
// }
//
// Path: src/test-lib/src/com/nikhaldimann/viewselector/test/util/ViewFactory.java
// public interface ViewFactory {
//
// TextView createTextView();
//
// LinearLayout createLinearLayout();
//
// FrameLayout createFrameLayout();
//
// }
// Path: src/robolectric2-test/test/com/nikhaldimann/viewselector/robolectric2/attributes/ViewAttributesTest.java
import org.junit.runner.RunWith;
import com.nikhaldimann.viewselector.robolectric2.testutil.Robolectric2ViewFactory;
import com.nikhaldimann.viewselector.test.abstrakt.attributes.AbstractViewAttributesTest;
import com.nikhaldimann.viewselector.test.util.ViewFactory;
import org.robolectric.RobolectricTestRunner;
package com.nikhaldimann.viewselector.robolectric2.attributes;
@RunWith(RobolectricTestRunner.class)
public class ViewAttributesTest extends AbstractViewAttributesTest {
| protected ViewFactory createViewFactory() { |
nikhaldi/android-view-selector | src/robolectric2-test/test/com/nikhaldimann/viewselector/robolectric2/attributes/ViewAttributesTest.java | // Path: src/robolectric2-test/test/com/nikhaldimann/viewselector/robolectric2/testutil/Robolectric2ViewFactory.java
// public class Robolectric2ViewFactory extends ProvidedContextViewFactory {
//
// public Robolectric2ViewFactory() {
// super(Robolectric.application);
// }
//
// }
//
// Path: src/test-lib/src/com/nikhaldimann/viewselector/test/abstrakt/attributes/AbstractViewAttributesTest.java
// public abstract class AbstractViewAttributesTest extends ViewSelectorAndroidTestCase {
//
// @Test
// public void testGetGetterMethodName() {
// assertEquals("getText", ViewAttributes.getGetterMethodName("text"));
// assertEquals("getText", ViewAttributes.getGetterMethodName("Text"));
// assertEquals("getFooText", ViewAttributes.getGetterMethodName("fooText"));
// }
//
// @Test
// public void testGetGetterMethodNameBooleanAttribute() {
// assertEquals("isFoo", ViewAttributes.getGetterMethodName("isFoo"));
// assertEquals("hasFoo", ViewAttributes.getGetterMethodName("hasFoo"));
// assertEquals("getIs", ViewAttributes.getGetterMethodName("is"));
// assertEquals("getIsland", ViewAttributes.getGetterMethodName("island"));
// assertEquals("getHas", ViewAttributes.getGetterMethodName("has"));
// assertEquals("getHash", ViewAttributes.getGetterMethodName("hash"));
// }
//
// @Test
// public void testCallGetter() {
// TextView view = viewFactory.createTextView();
// view.setText("foo");
// view.setInputType(InputType.TYPE_CLASS_TEXT);
// view.setVisibility(View.INVISIBLE);
// assertEquals("foo", ViewAttributes.callGetter(view, "getText").toString());
// assertEquals(null, ViewAttributes.callGetter(view, "getTag"));
// assertEquals(InputType.TYPE_CLASS_TEXT, ViewAttributes.callGetter(view, "getInputType"));
// assertEquals(false, ViewAttributes.callGetter(view, "isShown"));
// // TODO need to figure out how to deal with base class methods in Robolectric
// }
//
// @Test
// public void testCallGetterNoSuchMethod() {
// try {
// ViewAttributes.callGetter(viewFactory.createTextView(), "getFoo");
// fail();
// } catch (AttributeAccessException ex) {
// // expected
// }
// }
//
// }
//
// Path: src/test-lib/src/com/nikhaldimann/viewselector/test/util/ViewFactory.java
// public interface ViewFactory {
//
// TextView createTextView();
//
// LinearLayout createLinearLayout();
//
// FrameLayout createFrameLayout();
//
// }
| import org.junit.runner.RunWith;
import com.nikhaldimann.viewselector.robolectric2.testutil.Robolectric2ViewFactory;
import com.nikhaldimann.viewselector.test.abstrakt.attributes.AbstractViewAttributesTest;
import com.nikhaldimann.viewselector.test.util.ViewFactory;
import org.robolectric.RobolectricTestRunner; | package com.nikhaldimann.viewselector.robolectric2.attributes;
@RunWith(RobolectricTestRunner.class)
public class ViewAttributesTest extends AbstractViewAttributesTest {
protected ViewFactory createViewFactory() { | // Path: src/robolectric2-test/test/com/nikhaldimann/viewselector/robolectric2/testutil/Robolectric2ViewFactory.java
// public class Robolectric2ViewFactory extends ProvidedContextViewFactory {
//
// public Robolectric2ViewFactory() {
// super(Robolectric.application);
// }
//
// }
//
// Path: src/test-lib/src/com/nikhaldimann/viewselector/test/abstrakt/attributes/AbstractViewAttributesTest.java
// public abstract class AbstractViewAttributesTest extends ViewSelectorAndroidTestCase {
//
// @Test
// public void testGetGetterMethodName() {
// assertEquals("getText", ViewAttributes.getGetterMethodName("text"));
// assertEquals("getText", ViewAttributes.getGetterMethodName("Text"));
// assertEquals("getFooText", ViewAttributes.getGetterMethodName("fooText"));
// }
//
// @Test
// public void testGetGetterMethodNameBooleanAttribute() {
// assertEquals("isFoo", ViewAttributes.getGetterMethodName("isFoo"));
// assertEquals("hasFoo", ViewAttributes.getGetterMethodName("hasFoo"));
// assertEquals("getIs", ViewAttributes.getGetterMethodName("is"));
// assertEquals("getIsland", ViewAttributes.getGetterMethodName("island"));
// assertEquals("getHas", ViewAttributes.getGetterMethodName("has"));
// assertEquals("getHash", ViewAttributes.getGetterMethodName("hash"));
// }
//
// @Test
// public void testCallGetter() {
// TextView view = viewFactory.createTextView();
// view.setText("foo");
// view.setInputType(InputType.TYPE_CLASS_TEXT);
// view.setVisibility(View.INVISIBLE);
// assertEquals("foo", ViewAttributes.callGetter(view, "getText").toString());
// assertEquals(null, ViewAttributes.callGetter(view, "getTag"));
// assertEquals(InputType.TYPE_CLASS_TEXT, ViewAttributes.callGetter(view, "getInputType"));
// assertEquals(false, ViewAttributes.callGetter(view, "isShown"));
// // TODO need to figure out how to deal with base class methods in Robolectric
// }
//
// @Test
// public void testCallGetterNoSuchMethod() {
// try {
// ViewAttributes.callGetter(viewFactory.createTextView(), "getFoo");
// fail();
// } catch (AttributeAccessException ex) {
// // expected
// }
// }
//
// }
//
// Path: src/test-lib/src/com/nikhaldimann/viewselector/test/util/ViewFactory.java
// public interface ViewFactory {
//
// TextView createTextView();
//
// LinearLayout createLinearLayout();
//
// FrameLayout createFrameLayout();
//
// }
// Path: src/robolectric2-test/test/com/nikhaldimann/viewselector/robolectric2/attributes/ViewAttributesTest.java
import org.junit.runner.RunWith;
import com.nikhaldimann.viewselector.robolectric2.testutil.Robolectric2ViewFactory;
import com.nikhaldimann.viewselector.test.abstrakt.attributes.AbstractViewAttributesTest;
import com.nikhaldimann.viewselector.test.util.ViewFactory;
import org.robolectric.RobolectricTestRunner;
package com.nikhaldimann.viewselector.robolectric2.attributes;
@RunWith(RobolectricTestRunner.class)
public class ViewAttributesTest extends AbstractViewAttributesTest {
protected ViewFactory createViewFactory() { | return new Robolectric2ViewFactory(); |
urandom/gearshift | gearshift/src/main/java/org/sugr/gearshift/ui/util/colorpicker/ColorPickerPreference.java | // Path: gearshift/src/main/java/org/sugr/gearshift/ui/util/Colorizer.java
// public class Colorizer {
// public static void colorizeView(ImageView view, int color, int shape) {
// Resources res = view.getContext().getResources();
//
// Drawable currentDrawable = view.getDrawable();
// GradientDrawable colorChoiceDrawable;
// if (currentDrawable != null && currentDrawable instanceof GradientDrawable) {
// // Reuse drawable
// colorChoiceDrawable = (GradientDrawable) currentDrawable;
// } else {
// colorChoiceDrawable = new GradientDrawable();
// colorChoiceDrawable.setShape(shape);
// }
//
// int darkenedColor;
// if (color == defaultColor(view.getContext())) {
// darkenedColor = Color.rgb(95, 95, 95);
// } else {
// // Set stroke to dark version of color
// darkenedColor = Color.rgb(
// Color.red(color) * 192 / 256,
// Color.green(color) * 192 / 256,
// Color.blue(color) * 192 / 256);
// }
//
// colorChoiceDrawable.setColor(color);
// colorChoiceDrawable.setStroke((int) TypedValue.applyDimension(
// TypedValue.COMPLEX_UNIT_DIP, 1, res.getDisplayMetrics()), darkenedColor);
// view.setImageDrawable(colorChoiceDrawable);
//
// }
//
// public static void colorizeView(TextView view, int color) {
// view.setTextColor(color);
// }
//
// public static int defaultColor(Context context) {
//
// int[] colorArray = context.getResources().getIntArray(R.array.default_color_choice_values);
//
// if (colorArray != null && colorArray.length > 0) {
// return colorArray[0];
// } else {
// return context.getResources().getColor(R.color.primary);
// }
// }
//
// }
| import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.drawable.GradientDrawable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import org.sugr.gearshift.R;
import org.sugr.gearshift.ui.util.Colorizer; | }
public ColorPickerPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initAttrs(attrs, defStyle);
}
private void initAttrs(AttributeSet attrs, int defStyle) {
TypedArray a = getContext().getTheme().obtainStyledAttributes(
attrs, R.styleable.ColorPickerPreference, defStyle, defStyle);
try {
mItemLayoutId = a.getResourceId(R.styleable.ColorPickerPreference_cal_itemLayout, mItemLayoutId);
mNumColumns = a.getInteger(R.styleable.ColorPickerPreference_cal_numColumns, mNumColumns);
int choicesResId = a.getResourceId(R.styleable.ColorPickerPreference_cal_choices,
R.array.default_color_choice_values);
if (choicesResId > 0) {
mColorChoices = a.getResources().getIntArray(choicesResId);
}
} finally {
a.recycle();
}
setWidgetLayoutResource(mItemLayoutId);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
mPreviewView = view.findViewById(R.id.calendar_color_view); | // Path: gearshift/src/main/java/org/sugr/gearshift/ui/util/Colorizer.java
// public class Colorizer {
// public static void colorizeView(ImageView view, int color, int shape) {
// Resources res = view.getContext().getResources();
//
// Drawable currentDrawable = view.getDrawable();
// GradientDrawable colorChoiceDrawable;
// if (currentDrawable != null && currentDrawable instanceof GradientDrawable) {
// // Reuse drawable
// colorChoiceDrawable = (GradientDrawable) currentDrawable;
// } else {
// colorChoiceDrawable = new GradientDrawable();
// colorChoiceDrawable.setShape(shape);
// }
//
// int darkenedColor;
// if (color == defaultColor(view.getContext())) {
// darkenedColor = Color.rgb(95, 95, 95);
// } else {
// // Set stroke to dark version of color
// darkenedColor = Color.rgb(
// Color.red(color) * 192 / 256,
// Color.green(color) * 192 / 256,
// Color.blue(color) * 192 / 256);
// }
//
// colorChoiceDrawable.setColor(color);
// colorChoiceDrawable.setStroke((int) TypedValue.applyDimension(
// TypedValue.COMPLEX_UNIT_DIP, 1, res.getDisplayMetrics()), darkenedColor);
// view.setImageDrawable(colorChoiceDrawable);
//
// }
//
// public static void colorizeView(TextView view, int color) {
// view.setTextColor(color);
// }
//
// public static int defaultColor(Context context) {
//
// int[] colorArray = context.getResources().getIntArray(R.array.default_color_choice_values);
//
// if (colorArray != null && colorArray.length > 0) {
// return colorArray[0];
// } else {
// return context.getResources().getColor(R.color.primary);
// }
// }
//
// }
// Path: gearshift/src/main/java/org/sugr/gearshift/ui/util/colorpicker/ColorPickerPreference.java
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.drawable.GradientDrawable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import org.sugr.gearshift.R;
import org.sugr.gearshift.ui.util.Colorizer;
}
public ColorPickerPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initAttrs(attrs, defStyle);
}
private void initAttrs(AttributeSet attrs, int defStyle) {
TypedArray a = getContext().getTheme().obtainStyledAttributes(
attrs, R.styleable.ColorPickerPreference, defStyle, defStyle);
try {
mItemLayoutId = a.getResourceId(R.styleable.ColorPickerPreference_cal_itemLayout, mItemLayoutId);
mNumColumns = a.getInteger(R.styleable.ColorPickerPreference_cal_numColumns, mNumColumns);
int choicesResId = a.getResourceId(R.styleable.ColorPickerPreference_cal_choices,
R.array.default_color_choice_values);
if (choicesResId > 0) {
mColorChoices = a.getResources().getIntArray(choicesResId);
}
} finally {
a.recycle();
}
setWidgetLayoutResource(mItemLayoutId);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
mPreviewView = view.findViewById(R.id.calendar_color_view); | Colorizer.colorizeView((ImageView) mPreviewView, mValue, GradientDrawable.OVAL); |
profesorfalken/jSensors | src/main/java/com/profesorfalken/jsensors/manager/windows/powershell/PowerShellScriptHelper.java | // Path: src/main/java/com/profesorfalken/jsensors/util/SensorsUtils.java
// public class SensorsUtils {
// private static final Logger LOGGER = LoggerFactory.getLogger(PowerShellOperations.class);
//
// private static File tempFile = null;
//
// // Hides constructor
// private SensorsUtils() {
//
// }
//
// public static String generateLibTmpPath(String libName) {
// return generateLibTmpPath("/", libName);
// }
//
// public static String generateLibTmpPath(String path, String libName) {
// if (tempFile == null) {
// InputStream in = SensorsUtils.class.getResourceAsStream(path + libName);
// try {
// tempFile = File.createTempFile(libName, "");
// tempFile.deleteOnExit();
// byte[] buffer = new byte[1024];
// int read;
// FileOutputStream fos = new FileOutputStream(tempFile);
// while ((read = in.read(buffer)) != -1) {
// fos.write(buffer, 0, read);
// }
// fos.close();
// in.close();
// } catch (IOException ex) {
// LOGGER.error("Cannot generate temporary file", ex);
// return "";
// }
// }
//
// return tempFile.getAbsolutePath();
// }
// }
| import com.profesorfalken.jsensors.util.SensorsUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.manager.windows.powershell;
/**
*
* @author Javier Garcia Alonso
*/
class PowerShellScriptHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(PowerShellOperations.class);
private static final String LINE_BREAK = "\r\n";
private static File tmpFile = null;
// Hides constructor
private PowerShellScriptHelper() {
}
private static String dllImport() {
return "[System.Reflection.Assembly]::LoadFile(\"" | // Path: src/main/java/com/profesorfalken/jsensors/util/SensorsUtils.java
// public class SensorsUtils {
// private static final Logger LOGGER = LoggerFactory.getLogger(PowerShellOperations.class);
//
// private static File tempFile = null;
//
// // Hides constructor
// private SensorsUtils() {
//
// }
//
// public static String generateLibTmpPath(String libName) {
// return generateLibTmpPath("/", libName);
// }
//
// public static String generateLibTmpPath(String path, String libName) {
// if (tempFile == null) {
// InputStream in = SensorsUtils.class.getResourceAsStream(path + libName);
// try {
// tempFile = File.createTempFile(libName, "");
// tempFile.deleteOnExit();
// byte[] buffer = new byte[1024];
// int read;
// FileOutputStream fos = new FileOutputStream(tempFile);
// while ((read = in.read(buffer)) != -1) {
// fos.write(buffer, 0, read);
// }
// fos.close();
// in.close();
// } catch (IOException ex) {
// LOGGER.error("Cannot generate temporary file", ex);
// return "";
// }
// }
//
// return tempFile.getAbsolutePath();
// }
// }
// Path: src/main/java/com/profesorfalken/jsensors/manager/windows/powershell/PowerShellScriptHelper.java
import com.profesorfalken.jsensors.util.SensorsUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.manager.windows.powershell;
/**
*
* @author Javier Garcia Alonso
*/
class PowerShellScriptHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(PowerShellOperations.class);
private static final String LINE_BREAK = "\r\n";
private static File tmpFile = null;
// Hides constructor
private PowerShellScriptHelper() {
}
private static String dllImport() {
return "[System.Reflection.Assembly]::LoadFile(\"" | + SensorsUtils.generateLibTmpPath("/lib/win/", "OpenHardwareMonitorLib.dll") + "\")" + " | Out-Null" |
profesorfalken/jSensors | src/test/java/com/profesorfalken/jsensors/integration/JSensorsIntegrationTest.java | // Path: src/main/java/com/profesorfalken/jsensors/JSensors.java
// public enum JSensors {
//
// get;
//
// private static final Logger LOGGER = LoggerFactory.getLogger(JSensors.class);
//
// final Map<String, String> baseConfig;
//
// private Map<String, String> usedConfig = null;
//
// static {
// checkRights();
// }
//
// private static void checkRights() {
// if (OSDetector.isWindows() && !PowerShellOperations.isAdministrator()) {
// LOGGER.warn("You have not executed jSensors in Administrator mode, so CPU temperature sensors will not be detected.");
// }
// }
//
// JSensors() {
// // Load config from file
// baseConfig = SensorsConfig.getConfigMap();
// }
//
// /**
// * Updates default config (configurationon jsensors.properties) with a new one
// *
// * @param config
// * maps that contains the new config values
// * @return {@link JSensors} instance
// */
// public JSensors config(Map<String, String> config) {
// // Initialise config if necessary
// if (this.usedConfig == null) {
// this.usedConfig = this.baseConfig;
// }
//
// // Override values
// for (final Map.Entry<String, String> entry : config.entrySet()) {
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug(String.format("Overriding config entry %s, %s by %s", entry.getKey(),
// this.usedConfig.get(entry.getKey()), entry.getValue()));
// }
// this.usedConfig.put(entry.getKey(), entry.getValue());
// }
//
// return this;
// }
//
// /**
// * Retrieve all sensors components values. The supported sensors types are:
// * <ul>
// * <li>Fan: fan speed</li>
// * <li>Load: component load %</li>
// * <li>Temperature: temperature of sensor in C(Centigrader) or F(Farenheit)
// * depending on system settings</li>
// * </ul>
// * <p>
// *
// * @return {@link Components} object that containt the lists of components
// */
// public Components components() {
// if (this.usedConfig == null) {
// this.usedConfig = new HashMap<String, String>();
// }
//
// Components components = SensorsLocator.get.getComponents(this.usedConfig);
//
// // Reset config
// this.usedConfig = this.baseConfig;
//
// return components;
// }
//
// /**
// * Standalone entry point
// *
// * @param args program arguments
// */
// public static void main(String[] args) {
// boolean guiMode = false;
// Map<String, String> overriddenConfig = new HashMap<String, String>();
// for (final String arg : args) {
// if ("--debug".equals(arg)) {
// overriddenConfig.put("debugMode", "true");
// }
// if ("--gui".equals(arg)) {
// guiMode = true;
// }
// }
//
// if (guiMode) {
// GuiOutput.showOutput(overriddenConfig);
// } else {
// ConsoleOutput.showOutput(overriddenConfig);
// }
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/components/Components.java
// public class Components {
// public final List<Cpu> cpus;
// public final List<Gpu> gpus;
// public final List<Disk> disks;
// public final List<Mobo> mobos;
//
// public Components(List<Cpu> cpus, List<Gpu> gpus, List<Disk> disks, List<Mobo> mobos) {
// this.cpus = cpus;
// this.gpus = gpus;
// this.disks = disks;
// this.mobos = mobos;
// }
// }
| import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.profesorfalken.jsensors.JSensors;
import com.profesorfalken.jsensors.model.components.Components;
| /*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class JSensorsIntegrationTest {
public JSensorsIntegrationTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/*
* Make a real call and check that components are retrieved
*/
@Test
public void testJSensorsRealReturn() {
Map<String, String> config = new HashMap<String, String>();
config.put("testMode", "REAL");
| // Path: src/main/java/com/profesorfalken/jsensors/JSensors.java
// public enum JSensors {
//
// get;
//
// private static final Logger LOGGER = LoggerFactory.getLogger(JSensors.class);
//
// final Map<String, String> baseConfig;
//
// private Map<String, String> usedConfig = null;
//
// static {
// checkRights();
// }
//
// private static void checkRights() {
// if (OSDetector.isWindows() && !PowerShellOperations.isAdministrator()) {
// LOGGER.warn("You have not executed jSensors in Administrator mode, so CPU temperature sensors will not be detected.");
// }
// }
//
// JSensors() {
// // Load config from file
// baseConfig = SensorsConfig.getConfigMap();
// }
//
// /**
// * Updates default config (configurationon jsensors.properties) with a new one
// *
// * @param config
// * maps that contains the new config values
// * @return {@link JSensors} instance
// */
// public JSensors config(Map<String, String> config) {
// // Initialise config if necessary
// if (this.usedConfig == null) {
// this.usedConfig = this.baseConfig;
// }
//
// // Override values
// for (final Map.Entry<String, String> entry : config.entrySet()) {
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug(String.format("Overriding config entry %s, %s by %s", entry.getKey(),
// this.usedConfig.get(entry.getKey()), entry.getValue()));
// }
// this.usedConfig.put(entry.getKey(), entry.getValue());
// }
//
// return this;
// }
//
// /**
// * Retrieve all sensors components values. The supported sensors types are:
// * <ul>
// * <li>Fan: fan speed</li>
// * <li>Load: component load %</li>
// * <li>Temperature: temperature of sensor in C(Centigrader) or F(Farenheit)
// * depending on system settings</li>
// * </ul>
// * <p>
// *
// * @return {@link Components} object that containt the lists of components
// */
// public Components components() {
// if (this.usedConfig == null) {
// this.usedConfig = new HashMap<String, String>();
// }
//
// Components components = SensorsLocator.get.getComponents(this.usedConfig);
//
// // Reset config
// this.usedConfig = this.baseConfig;
//
// return components;
// }
//
// /**
// * Standalone entry point
// *
// * @param args program arguments
// */
// public static void main(String[] args) {
// boolean guiMode = false;
// Map<String, String> overriddenConfig = new HashMap<String, String>();
// for (final String arg : args) {
// if ("--debug".equals(arg)) {
// overriddenConfig.put("debugMode", "true");
// }
// if ("--gui".equals(arg)) {
// guiMode = true;
// }
// }
//
// if (guiMode) {
// GuiOutput.showOutput(overriddenConfig);
// } else {
// ConsoleOutput.showOutput(overriddenConfig);
// }
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/components/Components.java
// public class Components {
// public final List<Cpu> cpus;
// public final List<Gpu> gpus;
// public final List<Disk> disks;
// public final List<Mobo> mobos;
//
// public Components(List<Cpu> cpus, List<Gpu> gpus, List<Disk> disks, List<Mobo> mobos) {
// this.cpus = cpus;
// this.gpus = gpus;
// this.disks = disks;
// this.mobos = mobos;
// }
// }
// Path: src/test/java/com/profesorfalken/jsensors/integration/JSensorsIntegrationTest.java
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.profesorfalken.jsensors.JSensors;
import com.profesorfalken.jsensors.model.components.Components;
/*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class JSensorsIntegrationTest {
public JSensorsIntegrationTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/*
* Make a real call and check that components are retrieved
*/
@Test
public void testJSensorsRealReturn() {
Map<String, String> config = new HashMap<String, String>();
config.put("testMode", "REAL");
| Components components = JSensors.get.config(config).components();
|
profesorfalken/jSensors | src/test/java/com/profesorfalken/jsensors/integration/JSensorsIntegrationTest.java | // Path: src/main/java/com/profesorfalken/jsensors/JSensors.java
// public enum JSensors {
//
// get;
//
// private static final Logger LOGGER = LoggerFactory.getLogger(JSensors.class);
//
// final Map<String, String> baseConfig;
//
// private Map<String, String> usedConfig = null;
//
// static {
// checkRights();
// }
//
// private static void checkRights() {
// if (OSDetector.isWindows() && !PowerShellOperations.isAdministrator()) {
// LOGGER.warn("You have not executed jSensors in Administrator mode, so CPU temperature sensors will not be detected.");
// }
// }
//
// JSensors() {
// // Load config from file
// baseConfig = SensorsConfig.getConfigMap();
// }
//
// /**
// * Updates default config (configurationon jsensors.properties) with a new one
// *
// * @param config
// * maps that contains the new config values
// * @return {@link JSensors} instance
// */
// public JSensors config(Map<String, String> config) {
// // Initialise config if necessary
// if (this.usedConfig == null) {
// this.usedConfig = this.baseConfig;
// }
//
// // Override values
// for (final Map.Entry<String, String> entry : config.entrySet()) {
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug(String.format("Overriding config entry %s, %s by %s", entry.getKey(),
// this.usedConfig.get(entry.getKey()), entry.getValue()));
// }
// this.usedConfig.put(entry.getKey(), entry.getValue());
// }
//
// return this;
// }
//
// /**
// * Retrieve all sensors components values. The supported sensors types are:
// * <ul>
// * <li>Fan: fan speed</li>
// * <li>Load: component load %</li>
// * <li>Temperature: temperature of sensor in C(Centigrader) or F(Farenheit)
// * depending on system settings</li>
// * </ul>
// * <p>
// *
// * @return {@link Components} object that containt the lists of components
// */
// public Components components() {
// if (this.usedConfig == null) {
// this.usedConfig = new HashMap<String, String>();
// }
//
// Components components = SensorsLocator.get.getComponents(this.usedConfig);
//
// // Reset config
// this.usedConfig = this.baseConfig;
//
// return components;
// }
//
// /**
// * Standalone entry point
// *
// * @param args program arguments
// */
// public static void main(String[] args) {
// boolean guiMode = false;
// Map<String, String> overriddenConfig = new HashMap<String, String>();
// for (final String arg : args) {
// if ("--debug".equals(arg)) {
// overriddenConfig.put("debugMode", "true");
// }
// if ("--gui".equals(arg)) {
// guiMode = true;
// }
// }
//
// if (guiMode) {
// GuiOutput.showOutput(overriddenConfig);
// } else {
// ConsoleOutput.showOutput(overriddenConfig);
// }
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/components/Components.java
// public class Components {
// public final List<Cpu> cpus;
// public final List<Gpu> gpus;
// public final List<Disk> disks;
// public final List<Mobo> mobos;
//
// public Components(List<Cpu> cpus, List<Gpu> gpus, List<Disk> disks, List<Mobo> mobos) {
// this.cpus = cpus;
// this.gpus = gpus;
// this.disks = disks;
// this.mobos = mobos;
// }
// }
| import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.profesorfalken.jsensors.JSensors;
import com.profesorfalken.jsensors.model.components.Components;
| /*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class JSensorsIntegrationTest {
public JSensorsIntegrationTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/*
* Make a real call and check that components are retrieved
*/
@Test
public void testJSensorsRealReturn() {
Map<String, String> config = new HashMap<String, String>();
config.put("testMode", "REAL");
| // Path: src/main/java/com/profesorfalken/jsensors/JSensors.java
// public enum JSensors {
//
// get;
//
// private static final Logger LOGGER = LoggerFactory.getLogger(JSensors.class);
//
// final Map<String, String> baseConfig;
//
// private Map<String, String> usedConfig = null;
//
// static {
// checkRights();
// }
//
// private static void checkRights() {
// if (OSDetector.isWindows() && !PowerShellOperations.isAdministrator()) {
// LOGGER.warn("You have not executed jSensors in Administrator mode, so CPU temperature sensors will not be detected.");
// }
// }
//
// JSensors() {
// // Load config from file
// baseConfig = SensorsConfig.getConfigMap();
// }
//
// /**
// * Updates default config (configurationon jsensors.properties) with a new one
// *
// * @param config
// * maps that contains the new config values
// * @return {@link JSensors} instance
// */
// public JSensors config(Map<String, String> config) {
// // Initialise config if necessary
// if (this.usedConfig == null) {
// this.usedConfig = this.baseConfig;
// }
//
// // Override values
// for (final Map.Entry<String, String> entry : config.entrySet()) {
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug(String.format("Overriding config entry %s, %s by %s", entry.getKey(),
// this.usedConfig.get(entry.getKey()), entry.getValue()));
// }
// this.usedConfig.put(entry.getKey(), entry.getValue());
// }
//
// return this;
// }
//
// /**
// * Retrieve all sensors components values. The supported sensors types are:
// * <ul>
// * <li>Fan: fan speed</li>
// * <li>Load: component load %</li>
// * <li>Temperature: temperature of sensor in C(Centigrader) or F(Farenheit)
// * depending on system settings</li>
// * </ul>
// * <p>
// *
// * @return {@link Components} object that containt the lists of components
// */
// public Components components() {
// if (this.usedConfig == null) {
// this.usedConfig = new HashMap<String, String>();
// }
//
// Components components = SensorsLocator.get.getComponents(this.usedConfig);
//
// // Reset config
// this.usedConfig = this.baseConfig;
//
// return components;
// }
//
// /**
// * Standalone entry point
// *
// * @param args program arguments
// */
// public static void main(String[] args) {
// boolean guiMode = false;
// Map<String, String> overriddenConfig = new HashMap<String, String>();
// for (final String arg : args) {
// if ("--debug".equals(arg)) {
// overriddenConfig.put("debugMode", "true");
// }
// if ("--gui".equals(arg)) {
// guiMode = true;
// }
// }
//
// if (guiMode) {
// GuiOutput.showOutput(overriddenConfig);
// } else {
// ConsoleOutput.showOutput(overriddenConfig);
// }
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/components/Components.java
// public class Components {
// public final List<Cpu> cpus;
// public final List<Gpu> gpus;
// public final List<Disk> disks;
// public final List<Mobo> mobos;
//
// public Components(List<Cpu> cpus, List<Gpu> gpus, List<Disk> disks, List<Mobo> mobos) {
// this.cpus = cpus;
// this.gpus = gpus;
// this.disks = disks;
// this.mobos = mobos;
// }
// }
// Path: src/test/java/com/profesorfalken/jsensors/integration/JSensorsIntegrationTest.java
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.profesorfalken.jsensors.JSensors;
import com.profesorfalken.jsensors.model.components.Components;
/*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class JSensorsIntegrationTest {
public JSensorsIntegrationTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/*
* Make a real call and check that components are retrieved
*/
@Test
public void testJSensorsRealReturn() {
Map<String, String> config = new HashMap<String, String>();
config.put("testMode", "REAL");
| Components components = JSensors.get.config(config).components();
|
profesorfalken/jSensors | src/main/java/com/profesorfalken/jsensors/manager/SensorsManager.java | // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Fan.java
// public class Fan {
// public final String name;
// public final Double value;
//
// public Fan(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Load.java
// public class Load {
// public final String name;
// public final Double value;
//
// public Load(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Temperature.java
// public class Temperature {
// public final String name;
// public final Double value;
//
// public Temperature(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
| import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.profesorfalken.jsensors.model.components.*;
import com.profesorfalken.jsensors.model.sensors.Fan;
import com.profesorfalken.jsensors.model.sensors.Load;
import com.profesorfalken.jsensors.model.sensors.Sensors;
import com.profesorfalken.jsensors.model.sensors.Temperature; | private Cpu getCpu(String cpuData) {
return new Cpu(getName(cpuData), getSensors(cpuData));
}
private Gpu getGpu(String gpuData) {
return new Gpu(getName(gpuData), getSensors(gpuData));
}
private Disk getDisk(String diskData) {
return new Disk(getName(diskData), getSensors(diskData));
}
private Mobo getMobo(String moboData) {
return new Mobo(getName(moboData), getSensors(moboData));
}
private static String getName(String componentData) {
String name = null;
String[] dataLines = componentData.split("\\r?\\n");
for (final String dataLine : dataLines) {
if (dataLine.startsWith("Label")) {
name = dataLine.split(":")[1].trim();
break;
}
}
return name;
}
| // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Fan.java
// public class Fan {
// public final String name;
// public final Double value;
//
// public Fan(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Load.java
// public class Load {
// public final String name;
// public final Double value;
//
// public Load(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Temperature.java
// public class Temperature {
// public final String name;
// public final Double value;
//
// public Temperature(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
// Path: src/main/java/com/profesorfalken/jsensors/manager/SensorsManager.java
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.profesorfalken.jsensors.model.components.*;
import com.profesorfalken.jsensors.model.sensors.Fan;
import com.profesorfalken.jsensors.model.sensors.Load;
import com.profesorfalken.jsensors.model.sensors.Sensors;
import com.profesorfalken.jsensors.model.sensors.Temperature;
private Cpu getCpu(String cpuData) {
return new Cpu(getName(cpuData), getSensors(cpuData));
}
private Gpu getGpu(String gpuData) {
return new Gpu(getName(gpuData), getSensors(gpuData));
}
private Disk getDisk(String diskData) {
return new Disk(getName(diskData), getSensors(diskData));
}
private Mobo getMobo(String moboData) {
return new Mobo(getName(moboData), getSensors(moboData));
}
private static String getName(String componentData) {
String name = null;
String[] dataLines = componentData.split("\\r?\\n");
for (final String dataLine : dataLines) {
if (dataLine.startsWith("Label")) {
name = dataLine.split(":")[1].trim();
break;
}
}
return name;
}
| private Sensors getSensors(String componentData) { |
profesorfalken/jSensors | src/main/java/com/profesorfalken/jsensors/manager/SensorsManager.java | // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Fan.java
// public class Fan {
// public final String name;
// public final Double value;
//
// public Fan(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Load.java
// public class Load {
// public final String name;
// public final Double value;
//
// public Load(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Temperature.java
// public class Temperature {
// public final String name;
// public final Double value;
//
// public Temperature(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
| import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.profesorfalken.jsensors.model.components.*;
import com.profesorfalken.jsensors.model.sensors.Fan;
import com.profesorfalken.jsensors.model.sensors.Load;
import com.profesorfalken.jsensors.model.sensors.Sensors;
import com.profesorfalken.jsensors.model.sensors.Temperature; | return new Cpu(getName(cpuData), getSensors(cpuData));
}
private Gpu getGpu(String gpuData) {
return new Gpu(getName(gpuData), getSensors(gpuData));
}
private Disk getDisk(String diskData) {
return new Disk(getName(diskData), getSensors(diskData));
}
private Mobo getMobo(String moboData) {
return new Mobo(getName(moboData), getSensors(moboData));
}
private static String getName(String componentData) {
String name = null;
String[] dataLines = componentData.split("\\r?\\n");
for (final String dataLine : dataLines) {
if (dataLine.startsWith("Label")) {
name = dataLine.split(":")[1].trim();
break;
}
}
return name;
}
private Sensors getSensors(String componentData) { | // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Fan.java
// public class Fan {
// public final String name;
// public final Double value;
//
// public Fan(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Load.java
// public class Load {
// public final String name;
// public final Double value;
//
// public Load(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Temperature.java
// public class Temperature {
// public final String name;
// public final Double value;
//
// public Temperature(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
// Path: src/main/java/com/profesorfalken/jsensors/manager/SensorsManager.java
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.profesorfalken.jsensors.model.components.*;
import com.profesorfalken.jsensors.model.sensors.Fan;
import com.profesorfalken.jsensors.model.sensors.Load;
import com.profesorfalken.jsensors.model.sensors.Sensors;
import com.profesorfalken.jsensors.model.sensors.Temperature;
return new Cpu(getName(cpuData), getSensors(cpuData));
}
private Gpu getGpu(String gpuData) {
return new Gpu(getName(gpuData), getSensors(gpuData));
}
private Disk getDisk(String diskData) {
return new Disk(getName(diskData), getSensors(diskData));
}
private Mobo getMobo(String moboData) {
return new Mobo(getName(moboData), getSensors(moboData));
}
private static String getName(String componentData) {
String name = null;
String[] dataLines = componentData.split("\\r?\\n");
for (final String dataLine : dataLines) {
if (dataLine.startsWith("Label")) {
name = dataLine.split(":")[1].trim();
break;
}
}
return name;
}
private Sensors getSensors(String componentData) { | List<Temperature> temperatures = new ArrayList<Temperature>(); |
profesorfalken/jSensors | src/main/java/com/profesorfalken/jsensors/manager/SensorsManager.java | // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Fan.java
// public class Fan {
// public final String name;
// public final Double value;
//
// public Fan(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Load.java
// public class Load {
// public final String name;
// public final Double value;
//
// public Load(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Temperature.java
// public class Temperature {
// public final String name;
// public final Double value;
//
// public Temperature(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
| import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.profesorfalken.jsensors.model.components.*;
import com.profesorfalken.jsensors.model.sensors.Fan;
import com.profesorfalken.jsensors.model.sensors.Load;
import com.profesorfalken.jsensors.model.sensors.Sensors;
import com.profesorfalken.jsensors.model.sensors.Temperature; | }
private Gpu getGpu(String gpuData) {
return new Gpu(getName(gpuData), getSensors(gpuData));
}
private Disk getDisk(String diskData) {
return new Disk(getName(diskData), getSensors(diskData));
}
private Mobo getMobo(String moboData) {
return new Mobo(getName(moboData), getSensors(moboData));
}
private static String getName(String componentData) {
String name = null;
String[] dataLines = componentData.split("\\r?\\n");
for (final String dataLine : dataLines) {
if (dataLine.startsWith("Label")) {
name = dataLine.split(":")[1].trim();
break;
}
}
return name;
}
private Sensors getSensors(String componentData) {
List<Temperature> temperatures = new ArrayList<Temperature>(); | // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Fan.java
// public class Fan {
// public final String name;
// public final Double value;
//
// public Fan(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Load.java
// public class Load {
// public final String name;
// public final Double value;
//
// public Load(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Temperature.java
// public class Temperature {
// public final String name;
// public final Double value;
//
// public Temperature(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
// Path: src/main/java/com/profesorfalken/jsensors/manager/SensorsManager.java
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.profesorfalken.jsensors.model.components.*;
import com.profesorfalken.jsensors.model.sensors.Fan;
import com.profesorfalken.jsensors.model.sensors.Load;
import com.profesorfalken.jsensors.model.sensors.Sensors;
import com.profesorfalken.jsensors.model.sensors.Temperature;
}
private Gpu getGpu(String gpuData) {
return new Gpu(getName(gpuData), getSensors(gpuData));
}
private Disk getDisk(String diskData) {
return new Disk(getName(diskData), getSensors(diskData));
}
private Mobo getMobo(String moboData) {
return new Mobo(getName(moboData), getSensors(moboData));
}
private static String getName(String componentData) {
String name = null;
String[] dataLines = componentData.split("\\r?\\n");
for (final String dataLine : dataLines) {
if (dataLine.startsWith("Label")) {
name = dataLine.split(":")[1].trim();
break;
}
}
return name;
}
private Sensors getSensors(String componentData) {
List<Temperature> temperatures = new ArrayList<Temperature>(); | List<Fan> fans = new ArrayList<Fan>(); |
profesorfalken/jSensors | src/main/java/com/profesorfalken/jsensors/manager/SensorsManager.java | // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Fan.java
// public class Fan {
// public final String name;
// public final Double value;
//
// public Fan(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Load.java
// public class Load {
// public final String name;
// public final Double value;
//
// public Load(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Temperature.java
// public class Temperature {
// public final String name;
// public final Double value;
//
// public Temperature(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
| import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.profesorfalken.jsensors.model.components.*;
import com.profesorfalken.jsensors.model.sensors.Fan;
import com.profesorfalken.jsensors.model.sensors.Load;
import com.profesorfalken.jsensors.model.sensors.Sensors;
import com.profesorfalken.jsensors.model.sensors.Temperature; |
private Gpu getGpu(String gpuData) {
return new Gpu(getName(gpuData), getSensors(gpuData));
}
private Disk getDisk(String diskData) {
return new Disk(getName(diskData), getSensors(diskData));
}
private Mobo getMobo(String moboData) {
return new Mobo(getName(moboData), getSensors(moboData));
}
private static String getName(String componentData) {
String name = null;
String[] dataLines = componentData.split("\\r?\\n");
for (final String dataLine : dataLines) {
if (dataLine.startsWith("Label")) {
name = dataLine.split(":")[1].trim();
break;
}
}
return name;
}
private Sensors getSensors(String componentData) {
List<Temperature> temperatures = new ArrayList<Temperature>();
List<Fan> fans = new ArrayList<Fan>(); | // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Fan.java
// public class Fan {
// public final String name;
// public final Double value;
//
// public Fan(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Load.java
// public class Load {
// public final String name;
// public final Double value;
//
// public Load(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Temperature.java
// public class Temperature {
// public final String name;
// public final Double value;
//
// public Temperature(String name, Double value) {
// this.name = name;
// this.value = value;
// }
// }
// Path: src/main/java/com/profesorfalken/jsensors/manager/SensorsManager.java
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.profesorfalken.jsensors.model.components.*;
import com.profesorfalken.jsensors.model.sensors.Fan;
import com.profesorfalken.jsensors.model.sensors.Load;
import com.profesorfalken.jsensors.model.sensors.Sensors;
import com.profesorfalken.jsensors.model.sensors.Temperature;
private Gpu getGpu(String gpuData) {
return new Gpu(getName(gpuData), getSensors(gpuData));
}
private Disk getDisk(String diskData) {
return new Disk(getName(diskData), getSensors(diskData));
}
private Mobo getMobo(String moboData) {
return new Mobo(getName(moboData), getSensors(moboData));
}
private static String getName(String componentData) {
String name = null;
String[] dataLines = componentData.split("\\r?\\n");
for (final String dataLine : dataLines) {
if (dataLine.startsWith("Label")) {
name = dataLine.split(":")[1].trim();
break;
}
}
return name;
}
private Sensors getSensors(String componentData) {
List<Temperature> temperatures = new ArrayList<Temperature>();
List<Fan> fans = new ArrayList<Fan>(); | List<Load> loads = new ArrayList<Load>(); |
profesorfalken/jSensors | src/test/java/com/profesorfalken/jsensors/integration/TestSensorsLinux.java | // Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSubFeature.java
// public class CSubFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int mapping;
// public int flags;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "mapping", "flags");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CChip.java
// public class CChip extends Structure {
//
// public String prefix;
// public CBus bus;
// public String path;
// public int addr;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("prefix", "bus", "path", "addr");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CFeature.java
// public class CFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int first_subfeature;
// public int padding;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "first_subfeature", "padding");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSensors.java
// public interface CSensors extends Library {
//
// int sensors_init(File input);
//
// void sensors_cleanup();
//
// CChip sensors_get_detected_chips(CChip[] match, IntByReference nr);
//
// CFeature sensors_get_features(CChip name, IntByReference nr);
//
// String sensors_get_label(CChip name, CFeature feature);
//
// int sensors_get_value(CChip name, int subfeat_nr, DoubleByReference value);
//
// String sensors_get_adapter_name(CBus bus);
//
// CSubFeature sensors_get_all_subfeatures(CChip name, CFeature feature, IntByReference nr);
// }
| import com.profesorfalken.jsensors.manager.unix.jna.CSubFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CChip;
import com.profesorfalken.jsensors.manager.unix.jna.CFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CSensors;
import com.sun.jna.Native;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.ptr.IntByReference;
| /*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class TestSensorsLinux {
public static void main(String[] args) {
| // Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSubFeature.java
// public class CSubFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int mapping;
// public int flags;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "mapping", "flags");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CChip.java
// public class CChip extends Structure {
//
// public String prefix;
// public CBus bus;
// public String path;
// public int addr;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("prefix", "bus", "path", "addr");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CFeature.java
// public class CFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int first_subfeature;
// public int padding;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "first_subfeature", "padding");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSensors.java
// public interface CSensors extends Library {
//
// int sensors_init(File input);
//
// void sensors_cleanup();
//
// CChip sensors_get_detected_chips(CChip[] match, IntByReference nr);
//
// CFeature sensors_get_features(CChip name, IntByReference nr);
//
// String sensors_get_label(CChip name, CFeature feature);
//
// int sensors_get_value(CChip name, int subfeat_nr, DoubleByReference value);
//
// String sensors_get_adapter_name(CBus bus);
//
// CSubFeature sensors_get_all_subfeatures(CChip name, CFeature feature, IntByReference nr);
// }
// Path: src/test/java/com/profesorfalken/jsensors/integration/TestSensorsLinux.java
import com.profesorfalken.jsensors.manager.unix.jna.CSubFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CChip;
import com.profesorfalken.jsensors.manager.unix.jna.CFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CSensors;
import com.sun.jna.Native;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.ptr.IntByReference;
/*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class TestSensorsLinux {
public static void main(String[] args) {
| CSensors INSTANCE = Native.loadLibrary("sensors", CSensors.class);
|
profesorfalken/jSensors | src/test/java/com/profesorfalken/jsensors/integration/TestSensorsLinux.java | // Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSubFeature.java
// public class CSubFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int mapping;
// public int flags;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "mapping", "flags");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CChip.java
// public class CChip extends Structure {
//
// public String prefix;
// public CBus bus;
// public String path;
// public int addr;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("prefix", "bus", "path", "addr");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CFeature.java
// public class CFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int first_subfeature;
// public int padding;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "first_subfeature", "padding");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSensors.java
// public interface CSensors extends Library {
//
// int sensors_init(File input);
//
// void sensors_cleanup();
//
// CChip sensors_get_detected_chips(CChip[] match, IntByReference nr);
//
// CFeature sensors_get_features(CChip name, IntByReference nr);
//
// String sensors_get_label(CChip name, CFeature feature);
//
// int sensors_get_value(CChip name, int subfeat_nr, DoubleByReference value);
//
// String sensors_get_adapter_name(CBus bus);
//
// CSubFeature sensors_get_all_subfeatures(CChip name, CFeature feature, IntByReference nr);
// }
| import com.profesorfalken.jsensors.manager.unix.jna.CSubFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CChip;
import com.profesorfalken.jsensors.manager.unix.jna.CFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CSensors;
import com.sun.jna.Native;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.ptr.IntByReference;
| /*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class TestSensorsLinux {
public static void main(String[] args) {
CSensors INSTANCE = Native.loadLibrary("sensors", CSensors.class);
System.err.println("Return method: " + INSTANCE.sensors_init(null));
| // Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSubFeature.java
// public class CSubFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int mapping;
// public int flags;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "mapping", "flags");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CChip.java
// public class CChip extends Structure {
//
// public String prefix;
// public CBus bus;
// public String path;
// public int addr;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("prefix", "bus", "path", "addr");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CFeature.java
// public class CFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int first_subfeature;
// public int padding;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "first_subfeature", "padding");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSensors.java
// public interface CSensors extends Library {
//
// int sensors_init(File input);
//
// void sensors_cleanup();
//
// CChip sensors_get_detected_chips(CChip[] match, IntByReference nr);
//
// CFeature sensors_get_features(CChip name, IntByReference nr);
//
// String sensors_get_label(CChip name, CFeature feature);
//
// int sensors_get_value(CChip name, int subfeat_nr, DoubleByReference value);
//
// String sensors_get_adapter_name(CBus bus);
//
// CSubFeature sensors_get_all_subfeatures(CChip name, CFeature feature, IntByReference nr);
// }
// Path: src/test/java/com/profesorfalken/jsensors/integration/TestSensorsLinux.java
import com.profesorfalken.jsensors.manager.unix.jna.CSubFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CChip;
import com.profesorfalken.jsensors.manager.unix.jna.CFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CSensors;
import com.sun.jna.Native;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.ptr.IntByReference;
/*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class TestSensorsLinux {
public static void main(String[] args) {
CSensors INSTANCE = Native.loadLibrary("sensors", CSensors.class);
System.err.println("Return method: " + INSTANCE.sensors_init(null));
| CChip result;
|
profesorfalken/jSensors | src/test/java/com/profesorfalken/jsensors/integration/TestSensorsLinux.java | // Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSubFeature.java
// public class CSubFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int mapping;
// public int flags;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "mapping", "flags");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CChip.java
// public class CChip extends Structure {
//
// public String prefix;
// public CBus bus;
// public String path;
// public int addr;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("prefix", "bus", "path", "addr");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CFeature.java
// public class CFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int first_subfeature;
// public int padding;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "first_subfeature", "padding");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSensors.java
// public interface CSensors extends Library {
//
// int sensors_init(File input);
//
// void sensors_cleanup();
//
// CChip sensors_get_detected_chips(CChip[] match, IntByReference nr);
//
// CFeature sensors_get_features(CChip name, IntByReference nr);
//
// String sensors_get_label(CChip name, CFeature feature);
//
// int sensors_get_value(CChip name, int subfeat_nr, DoubleByReference value);
//
// String sensors_get_adapter_name(CBus bus);
//
// CSubFeature sensors_get_all_subfeatures(CChip name, CFeature feature, IntByReference nr);
// }
| import com.profesorfalken.jsensors.manager.unix.jna.CSubFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CChip;
import com.profesorfalken.jsensors.manager.unix.jna.CFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CSensors;
import com.sun.jna.Native;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.ptr.IntByReference;
| /*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class TestSensorsLinux {
public static void main(String[] args) {
CSensors INSTANCE = Native.loadLibrary("sensors", CSensors.class);
System.err.println("Return method: " + INSTANCE.sensors_init(null));
CChip result;
int numSensor = 0;
while ((result = INSTANCE.sensors_get_detected_chips(null, new IntByReference(numSensor))) != null) {
// System.out.println("Found " + result);
numSensor++;
System.out.println("Adapter " + INSTANCE.sensors_get_adapter_name(result.bus));
| // Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSubFeature.java
// public class CSubFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int mapping;
// public int flags;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "mapping", "flags");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CChip.java
// public class CChip extends Structure {
//
// public String prefix;
// public CBus bus;
// public String path;
// public int addr;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("prefix", "bus", "path", "addr");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CFeature.java
// public class CFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int first_subfeature;
// public int padding;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "first_subfeature", "padding");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSensors.java
// public interface CSensors extends Library {
//
// int sensors_init(File input);
//
// void sensors_cleanup();
//
// CChip sensors_get_detected_chips(CChip[] match, IntByReference nr);
//
// CFeature sensors_get_features(CChip name, IntByReference nr);
//
// String sensors_get_label(CChip name, CFeature feature);
//
// int sensors_get_value(CChip name, int subfeat_nr, DoubleByReference value);
//
// String sensors_get_adapter_name(CBus bus);
//
// CSubFeature sensors_get_all_subfeatures(CChip name, CFeature feature, IntByReference nr);
// }
// Path: src/test/java/com/profesorfalken/jsensors/integration/TestSensorsLinux.java
import com.profesorfalken.jsensors.manager.unix.jna.CSubFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CChip;
import com.profesorfalken.jsensors.manager.unix.jna.CFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CSensors;
import com.sun.jna.Native;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.ptr.IntByReference;
/*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class TestSensorsLinux {
public static void main(String[] args) {
CSensors INSTANCE = Native.loadLibrary("sensors", CSensors.class);
System.err.println("Return method: " + INSTANCE.sensors_init(null));
CChip result;
int numSensor = 0;
while ((result = INSTANCE.sensors_get_detected_chips(null, new IntByReference(numSensor))) != null) {
// System.out.println("Found " + result);
numSensor++;
System.out.println("Adapter " + INSTANCE.sensors_get_adapter_name(result.bus));
| CFeature feature;
|
profesorfalken/jSensors | src/test/java/com/profesorfalken/jsensors/integration/TestSensorsLinux.java | // Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSubFeature.java
// public class CSubFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int mapping;
// public int flags;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "mapping", "flags");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CChip.java
// public class CChip extends Structure {
//
// public String prefix;
// public CBus bus;
// public String path;
// public int addr;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("prefix", "bus", "path", "addr");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CFeature.java
// public class CFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int first_subfeature;
// public int padding;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "first_subfeature", "padding");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSensors.java
// public interface CSensors extends Library {
//
// int sensors_init(File input);
//
// void sensors_cleanup();
//
// CChip sensors_get_detected_chips(CChip[] match, IntByReference nr);
//
// CFeature sensors_get_features(CChip name, IntByReference nr);
//
// String sensors_get_label(CChip name, CFeature feature);
//
// int sensors_get_value(CChip name, int subfeat_nr, DoubleByReference value);
//
// String sensors_get_adapter_name(CBus bus);
//
// CSubFeature sensors_get_all_subfeatures(CChip name, CFeature feature, IntByReference nr);
// }
| import com.profesorfalken.jsensors.manager.unix.jna.CSubFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CChip;
import com.profesorfalken.jsensors.manager.unix.jna.CFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CSensors;
import com.sun.jna.Native;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.ptr.IntByReference;
| /*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class TestSensorsLinux {
public static void main(String[] args) {
CSensors INSTANCE = Native.loadLibrary("sensors", CSensors.class);
System.err.println("Return method: " + INSTANCE.sensors_init(null));
CChip result;
int numSensor = 0;
while ((result = INSTANCE.sensors_get_detected_chips(null, new IntByReference(numSensor))) != null) {
// System.out.println("Found " + result);
numSensor++;
System.out.println("Adapter " + INSTANCE.sensors_get_adapter_name(result.bus));
CFeature feature;
int numFeature = 0;
while ((feature = INSTANCE.sensors_get_features(result, new IntByReference(numFeature))) != null) {
// System.out.println("Found " + feature);
numFeature++;
String label = INSTANCE.sensors_get_label(result, feature);
| // Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSubFeature.java
// public class CSubFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int mapping;
// public int flags;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "mapping", "flags");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CChip.java
// public class CChip extends Structure {
//
// public String prefix;
// public CBus bus;
// public String path;
// public int addr;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("prefix", "bus", "path", "addr");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CFeature.java
// public class CFeature extends Structure {
//
// public String name;
// public int number;
// public int type;
// public int first_subfeature;
// public int padding;
//
// @Override
// protected List getFieldOrder() {
// return Arrays.asList("name", "number", "type", "first_subfeature", "padding");
// }
//
// }
//
// Path: src/main/java/com/profesorfalken/jsensors/manager/unix/jna/CSensors.java
// public interface CSensors extends Library {
//
// int sensors_init(File input);
//
// void sensors_cleanup();
//
// CChip sensors_get_detected_chips(CChip[] match, IntByReference nr);
//
// CFeature sensors_get_features(CChip name, IntByReference nr);
//
// String sensors_get_label(CChip name, CFeature feature);
//
// int sensors_get_value(CChip name, int subfeat_nr, DoubleByReference value);
//
// String sensors_get_adapter_name(CBus bus);
//
// CSubFeature sensors_get_all_subfeatures(CChip name, CFeature feature, IntByReference nr);
// }
// Path: src/test/java/com/profesorfalken/jsensors/integration/TestSensorsLinux.java
import com.profesorfalken.jsensors.manager.unix.jna.CSubFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CChip;
import com.profesorfalken.jsensors.manager.unix.jna.CFeature;
import com.profesorfalken.jsensors.manager.unix.jna.CSensors;
import com.sun.jna.Native;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.ptr.IntByReference;
/*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.integration;
/**
*
* @author javier
*/
public class TestSensorsLinux {
public static void main(String[] args) {
CSensors INSTANCE = Native.loadLibrary("sensors", CSensors.class);
System.err.println("Return method: " + INSTANCE.sensors_init(null));
CChip result;
int numSensor = 0;
while ((result = INSTANCE.sensors_get_detected_chips(null, new IntByReference(numSensor))) != null) {
// System.out.println("Found " + result);
numSensor++;
System.out.println("Adapter " + INSTANCE.sensors_get_adapter_name(result.bus));
CFeature feature;
int numFeature = 0;
while ((feature = INSTANCE.sensors_get_features(result, new IntByReference(numFeature))) != null) {
// System.out.println("Found " + feature);
numFeature++;
String label = INSTANCE.sensors_get_label(result, feature);
| CSubFeature subFeature;
|
profesorfalken/jSensors | src/main/java/com/profesorfalken/jsensors/model/components/Component.java | // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
| import com.profesorfalken.jsensors.model.sensors.Sensors; | /*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.model.components;
/**
*
* @author javier
*/
public abstract class Component {
public final String name; | // Path: src/main/java/com/profesorfalken/jsensors/model/sensors/Sensors.java
// public class Sensors {
// public final List<Temperature> temperatures;
// public final List<Fan> fans;
// public final List<Load> loads;
//
// public Sensors(List<Temperature> temperatures, List<Fan> fans, List<Load> loads) {
// this.temperatures = temperatures;
// this.fans = fans;
// this.loads = loads;
// }
// }
// Path: src/main/java/com/profesorfalken/jsensors/model/components/Component.java
import com.profesorfalken.jsensors.model.sensors.Sensors;
/*
* Copyright 2016-2018 Javier Garcia Alonso.
*
* 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.profesorfalken.jsensors.model.components;
/**
*
* @author javier
*/
public abstract class Component {
public final String name; | public final Sensors sensors; |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/AdvancedWordVectorParams.java | // Path: src/edu/stanford/nlp/semparse/open/ling/WordVectorTable.java
// public class WordVectorTable {
// public static class Options {
// @Option public String wordVectorFilename = null;
//
// @Option(gloss = "vector to use for UNKNOWN words (-1 = don't use any vector)")
// public int wordVectorUNKindex = 0;
// }
// public static Options opts = new Options();
//
// public static Map<String, Integer> wordToIndex;
// public static double[][] wordVectors;
// public static int numWords, numDimensions;
//
// public static void initModels() {
// if (wordVectors != null || opts.wordVectorFilename == null || opts.wordVectorFilename.isEmpty()) return;
// Path dataPath = Paths.get(opts.wordVectorFilename);
// LogInfo.logs("Reading word vectors from %s", dataPath);
// try (BufferedReader in = Files.newBufferedReader(dataPath, Charset.forName("UTF-8"))) {
// String[] headerTokens = in.readLine().split(" ");
// numWords = Integer.parseInt(headerTokens[0]);
// numDimensions = Integer.parseInt(headerTokens[1]);
// wordToIndex = new HashMap<>();
// wordVectors = new double[numWords][numDimensions];
// for (int i = 0; i < numWords; i++) {
// String[] tokens = in.readLine().split(" ");
// wordToIndex.put(tokens[0], i);
// for (int j = 0; j < numDimensions; j++) {
// wordVectors[i][j] = Double.parseDouble(tokens[j+1]);
// }
// }
// LogInfo.logs("Neural network vectors: %s words; %s dimensions per word", numWords, numDimensions);
// } catch (IOException e) {
// LogInfo.fails("Cannot load neural network vectors from %s", dataPath);
// }
// }
//
// public static double[] getVector(String word) {
// initModels();
// Integer index = wordToIndex.get(word);
// if (index == null) {
// index = opts.wordVectorUNKindex;
// if (index < 0) return null;
// }
// return wordVectors[index];
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import edu.stanford.nlp.semparse.open.ling.WordVectorTable;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.Option; | package edu.stanford.nlp.semparse.open.model;
/**
* Parameters for advanced word vector features.
*/
public abstract class AdvancedWordVectorParams {
public static class Options {
@Option(gloss = "Whether to use full rank")
public boolean vecFullRank = true;
@Option(gloss = "Use pooling (vecOpenPOSOnly and vecFreqWeighted will be ignored)")
public boolean vecPooling = false;
@Option(gloss = "Only use Open POS words")
public boolean vecOpenPOSOnly = false;
@Option(gloss = "Use frequency-weighted vectors")
public boolean vecFreqWeighted = false;
}
public static Options opts = new Options();
public static AdvancedWordVectorParams create() {
if (opts.vecFullRank)
return new AdvancedWordVectorParamsFullRank();
else
return new AdvancedWordVectorParamsLowRank();
}
protected static int getDim() {
if (opts.vecPooling) { | // Path: src/edu/stanford/nlp/semparse/open/ling/WordVectorTable.java
// public class WordVectorTable {
// public static class Options {
// @Option public String wordVectorFilename = null;
//
// @Option(gloss = "vector to use for UNKNOWN words (-1 = don't use any vector)")
// public int wordVectorUNKindex = 0;
// }
// public static Options opts = new Options();
//
// public static Map<String, Integer> wordToIndex;
// public static double[][] wordVectors;
// public static int numWords, numDimensions;
//
// public static void initModels() {
// if (wordVectors != null || opts.wordVectorFilename == null || opts.wordVectorFilename.isEmpty()) return;
// Path dataPath = Paths.get(opts.wordVectorFilename);
// LogInfo.logs("Reading word vectors from %s", dataPath);
// try (BufferedReader in = Files.newBufferedReader(dataPath, Charset.forName("UTF-8"))) {
// String[] headerTokens = in.readLine().split(" ");
// numWords = Integer.parseInt(headerTokens[0]);
// numDimensions = Integer.parseInt(headerTokens[1]);
// wordToIndex = new HashMap<>();
// wordVectors = new double[numWords][numDimensions];
// for (int i = 0; i < numWords; i++) {
// String[] tokens = in.readLine().split(" ");
// wordToIndex.put(tokens[0], i);
// for (int j = 0; j < numDimensions; j++) {
// wordVectors[i][j] = Double.parseDouble(tokens[j+1]);
// }
// }
// LogInfo.logs("Neural network vectors: %s words; %s dimensions per word", numWords, numDimensions);
// } catch (IOException e) {
// LogInfo.fails("Cannot load neural network vectors from %s", dataPath);
// }
// }
//
// public static double[] getVector(String word) {
// initModels();
// Integer index = wordToIndex.get(word);
// if (index == null) {
// index = opts.wordVectorUNKindex;
// if (index < 0) return null;
// }
// return wordVectors[index];
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/model/AdvancedWordVectorParams.java
import edu.stanford.nlp.semparse.open.ling.WordVectorTable;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.Option;
package edu.stanford.nlp.semparse.open.model;
/**
* Parameters for advanced word vector features.
*/
public abstract class AdvancedWordVectorParams {
public static class Options {
@Option(gloss = "Whether to use full rank")
public boolean vecFullRank = true;
@Option(gloss = "Use pooling (vecOpenPOSOnly and vecFreqWeighted will be ignored)")
public boolean vecPooling = false;
@Option(gloss = "Only use Open POS words")
public boolean vecOpenPOSOnly = false;
@Option(gloss = "Use frequency-weighted vectors")
public boolean vecFreqWeighted = false;
}
public static Options opts = new Options();
public static AdvancedWordVectorParams create() {
if (opts.vecFullRank)
return new AdvancedWordVectorParamsFullRank();
else
return new AdvancedWordVectorParamsLowRank();
}
protected static int getDim() {
if (opts.vecPooling) { | return 2 * WordVectorTable.numDimensions; |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/AdvancedWordVectorParams.java | // Path: src/edu/stanford/nlp/semparse/open/ling/WordVectorTable.java
// public class WordVectorTable {
// public static class Options {
// @Option public String wordVectorFilename = null;
//
// @Option(gloss = "vector to use for UNKNOWN words (-1 = don't use any vector)")
// public int wordVectorUNKindex = 0;
// }
// public static Options opts = new Options();
//
// public static Map<String, Integer> wordToIndex;
// public static double[][] wordVectors;
// public static int numWords, numDimensions;
//
// public static void initModels() {
// if (wordVectors != null || opts.wordVectorFilename == null || opts.wordVectorFilename.isEmpty()) return;
// Path dataPath = Paths.get(opts.wordVectorFilename);
// LogInfo.logs("Reading word vectors from %s", dataPath);
// try (BufferedReader in = Files.newBufferedReader(dataPath, Charset.forName("UTF-8"))) {
// String[] headerTokens = in.readLine().split(" ");
// numWords = Integer.parseInt(headerTokens[0]);
// numDimensions = Integer.parseInt(headerTokens[1]);
// wordToIndex = new HashMap<>();
// wordVectors = new double[numWords][numDimensions];
// for (int i = 0; i < numWords; i++) {
// String[] tokens = in.readLine().split(" ");
// wordToIndex.put(tokens[0], i);
// for (int j = 0; j < numDimensions; j++) {
// wordVectors[i][j] = Double.parseDouble(tokens[j+1]);
// }
// }
// LogInfo.logs("Neural network vectors: %s words; %s dimensions per word", numWords, numDimensions);
// } catch (IOException e) {
// LogInfo.fails("Cannot load neural network vectors from %s", dataPath);
// }
// }
//
// public static double[] getVector(String word) {
// initModels();
// Integer index = wordToIndex.get(word);
// if (index == null) {
// index = opts.wordVectorUNKindex;
// if (index < 0) return null;
// }
// return wordVectors[index];
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import edu.stanford.nlp.semparse.open.ling.WordVectorTable;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.Option; | package edu.stanford.nlp.semparse.open.model;
/**
* Parameters for advanced word vector features.
*/
public abstract class AdvancedWordVectorParams {
public static class Options {
@Option(gloss = "Whether to use full rank")
public boolean vecFullRank = true;
@Option(gloss = "Use pooling (vecOpenPOSOnly and vecFreqWeighted will be ignored)")
public boolean vecPooling = false;
@Option(gloss = "Only use Open POS words")
public boolean vecOpenPOSOnly = false;
@Option(gloss = "Use frequency-weighted vectors")
public boolean vecFreqWeighted = false;
}
public static Options opts = new Options();
public static AdvancedWordVectorParams create() {
if (opts.vecFullRank)
return new AdvancedWordVectorParamsFullRank();
else
return new AdvancedWordVectorParamsLowRank();
}
protected static int getDim() {
if (opts.vecPooling) {
return 2 * WordVectorTable.numDimensions;
}
return WordVectorTable.numDimensions;
}
| // Path: src/edu/stanford/nlp/semparse/open/ling/WordVectorTable.java
// public class WordVectorTable {
// public static class Options {
// @Option public String wordVectorFilename = null;
//
// @Option(gloss = "vector to use for UNKNOWN words (-1 = don't use any vector)")
// public int wordVectorUNKindex = 0;
// }
// public static Options opts = new Options();
//
// public static Map<String, Integer> wordToIndex;
// public static double[][] wordVectors;
// public static int numWords, numDimensions;
//
// public static void initModels() {
// if (wordVectors != null || opts.wordVectorFilename == null || opts.wordVectorFilename.isEmpty()) return;
// Path dataPath = Paths.get(opts.wordVectorFilename);
// LogInfo.logs("Reading word vectors from %s", dataPath);
// try (BufferedReader in = Files.newBufferedReader(dataPath, Charset.forName("UTF-8"))) {
// String[] headerTokens = in.readLine().split(" ");
// numWords = Integer.parseInt(headerTokens[0]);
// numDimensions = Integer.parseInt(headerTokens[1]);
// wordToIndex = new HashMap<>();
// wordVectors = new double[numWords][numDimensions];
// for (int i = 0; i < numWords; i++) {
// String[] tokens = in.readLine().split(" ");
// wordToIndex.put(tokens[0], i);
// for (int j = 0; j < numDimensions; j++) {
// wordVectors[i][j] = Double.parseDouble(tokens[j+1]);
// }
// }
// LogInfo.logs("Neural network vectors: %s words; %s dimensions per word", numWords, numDimensions);
// } catch (IOException e) {
// LogInfo.fails("Cannot load neural network vectors from %s", dataPath);
// }
// }
//
// public static double[] getVector(String word) {
// initModels();
// Integer index = wordToIndex.get(word);
// if (index == null) {
// index = opts.wordVectorUNKindex;
// if (index < 0) return null;
// }
// return wordVectors[index];
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/model/AdvancedWordVectorParams.java
import edu.stanford.nlp.semparse.open.ling.WordVectorTable;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.Option;
package edu.stanford.nlp.semparse.open.model;
/**
* Parameters for advanced word vector features.
*/
public abstract class AdvancedWordVectorParams {
public static class Options {
@Option(gloss = "Whether to use full rank")
public boolean vecFullRank = true;
@Option(gloss = "Use pooling (vecOpenPOSOnly and vecFreqWeighted will be ignored)")
public boolean vecPooling = false;
@Option(gloss = "Only use Open POS words")
public boolean vecOpenPOSOnly = false;
@Option(gloss = "Use frequency-weighted vectors")
public boolean vecFreqWeighted = false;
}
public static Options opts = new Options();
public static AdvancedWordVectorParams create() {
if (opts.vecFullRank)
return new AdvancedWordVectorParamsFullRank();
else
return new AdvancedWordVectorParamsLowRank();
}
protected static int getDim() {
if (opts.vecPooling) {
return 2 * WordVectorTable.numDimensions;
}
return WordVectorTable.numDimensions;
}
| protected static double[] getX(Candidate candidate) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/AdvancedWordVectorParamsLowRank.java | // Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import java.util.Random;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.Fmt;
import fig.basic.ListUtils;
import fig.basic.LogInfo;
import fig.basic.Option; | package edu.stanford.nlp.semparse.open.model;
public class AdvancedWordVectorParamsLowRank extends AdvancedWordVectorParams {
public static class Options {
@Option(gloss = "Rank of advanced word vector feature parameters (ignored when full rank)")
public int vecRank = 5;
@Option(gloss = "Randomly initialize the weights (ignored when full rank)")
public boolean vecInitWeightsRandomly = true;
@Option(gloss = "Randomly initialize the weights (ignored when full rank)")
public Random vecInitRandom = new Random(1);
}
public static Options opts = new Options();
// A = sum{u[i] v[i]^T} (i = 0, ..., rank - 1)
protected final double[][] u, v;
// Shorthands for rank and word vector dimension
protected final int rank, dim;
public AdvancedWordVectorParamsLowRank() {
rank = opts.vecRank;
dim = getDim();
u = new double[rank][dim];
v = new double[rank][dim];
if (opts.vecInitWeightsRandomly) {
for (int i = 0; i < rank; i++) {
for (int j = 0; j < dim; j++) {
u[i][j] = 2 * opts.vecInitRandom.nextDouble() - 1;
v[i][j] = 2 * opts.vecInitRandom.nextDouble() - 1;
}
}
}
initGradientStats();
}
// ============================================================
// Get score
// ============================================================
@Override | // Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/model/AdvancedWordVectorParamsLowRank.java
import java.util.Random;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.Fmt;
import fig.basic.ListUtils;
import fig.basic.LogInfo;
import fig.basic.Option;
package edu.stanford.nlp.semparse.open.model;
public class AdvancedWordVectorParamsLowRank extends AdvancedWordVectorParams {
public static class Options {
@Option(gloss = "Rank of advanced word vector feature parameters (ignored when full rank)")
public int vecRank = 5;
@Option(gloss = "Randomly initialize the weights (ignored when full rank)")
public boolean vecInitWeightsRandomly = true;
@Option(gloss = "Randomly initialize the weights (ignored when full rank)")
public Random vecInitRandom = new Random(1);
}
public static Options opts = new Options();
// A = sum{u[i] v[i]^T} (i = 0, ..., rank - 1)
protected final double[][] u, v;
// Shorthands for rank and word vector dimension
protected final int rank, dim;
public AdvancedWordVectorParamsLowRank() {
rank = opts.vecRank;
dim = getDim();
u = new double[rank][dim];
v = new double[rank][dim];
if (opts.vecInitWeightsRandomly) {
for (int i = 0; i < rank; i++) {
for (int j = 0; j < dim; j++) {
u[i][j] = 2 * opts.vecInitRandom.nextDouble() - 1;
v[i][j] = 2 * opts.vecInitRandom.nextDouble() - 1;
}
}
}
initGradientStats();
}
// ============================================================
// Get score
// ============================================================
@Override | public double getScore(Candidate candidate) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/FeatureCountPruner.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.LogInfo; | package edu.stanford.nlp.semparse.open.model;
public class FeatureCountPruner implements FeatureMatcher {
public Multiset<String> counts = new Multiset<>();
public boolean beVeryQuiet;
public FeatureCountPruner(boolean beVeryQuiet) {
this.beVeryQuiet = beVeryQuiet;
}
/**
* Add features from the example to the count.
*
* The same feature within the same example counts as 1 feature.
*/ | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/model/FeatureCountPruner.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.LogInfo;
package edu.stanford.nlp.semparse.open.model;
public class FeatureCountPruner implements FeatureMatcher {
public Multiset<String> counts = new Multiset<>();
public boolean beVeryQuiet;
public FeatureCountPruner(boolean beVeryQuiet) {
this.beVeryQuiet = beVeryQuiet;
}
/**
* Add features from the example to the count.
*
* The same feature within the same example counts as 1 feature.
*/ | public void add(Example example) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/FeatureCountPruner.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.LogInfo; | package edu.stanford.nlp.semparse.open.model;
public class FeatureCountPruner implements FeatureMatcher {
public Multiset<String> counts = new Multiset<>();
public boolean beVeryQuiet;
public FeatureCountPruner(boolean beVeryQuiet) {
this.beVeryQuiet = beVeryQuiet;
}
/**
* Add features from the example to the count.
*
* The same feature within the same example counts as 1 feature.
*/
public void add(Example example) {
if (!beVeryQuiet) LogInfo.begin_track("Collecting features from %s ...", example);
Set<String> uniqued = new HashSet<>(); | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/model/FeatureCountPruner.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.LogInfo;
package edu.stanford.nlp.semparse.open.model;
public class FeatureCountPruner implements FeatureMatcher {
public Multiset<String> counts = new Multiset<>();
public boolean beVeryQuiet;
public FeatureCountPruner(boolean beVeryQuiet) {
this.beVeryQuiet = beVeryQuiet;
}
/**
* Add features from the example to the count.
*
* The same feature within the same example counts as 1 feature.
*/
public void add(Example example) {
if (!beVeryQuiet) LogInfo.begin_track("Collecting features from %s ...", example);
Set<String> uniqued = new HashSet<>(); | for (Candidate candidate : example.candidates) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/FeatureVector.java | // Path: src/edu/stanford/nlp/semparse/open/util/StringDoubleArrayList.java
// public class StringDoubleArrayList implements Iterable<StringDoublePair> {
//
// public static final int DEFAULT_CAPACITY = 10;
//
// private int size;
//
// // The two data arrays must have equal length.
// private String[] strings;
// private double[] doubles;
//
// public StringDoubleArrayList(int capacity) {
// if (capacity < 0)
// throw new IllegalArgumentException();
// strings = new String[capacity];
// doubles = new double[capacity];
// }
//
// public StringDoubleArrayList() {
// this(DEFAULT_CAPACITY);
// }
//
// public int size() {
// return size;
// }
//
// public void ensureCapacity(int minCapacity) {
// if (minCapacity - strings.length > 0) { // subtract to prevent overflow
// {
// String[] newStrings = new String[Math.max(strings.length * 2, minCapacity)];
// System.arraycopy(strings, 0, newStrings, 0, size);
// strings = newStrings;
// }
// {
// double[] newDoubles = new double[Math.max(doubles.length * 2, minCapacity)];
// System.arraycopy(doubles, 0, newDoubles, 0, size);
// doubles = newDoubles;
// }
// }
// }
//
// public void add(String s, double d) {
// if (size == strings.length)
// ensureCapacity(size + 1);
// strings[size] = s;
// doubles[size] = d;
// size++;
// }
//
// private void checkBoundExclusive(int index) {
// if (index >= size)
// throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
// }
//
// public String getString(int index) {
// checkBoundExclusive(index);
// return strings[index];
// }
//
// public double getDouble(int index) {
// checkBoundExclusive(index);
// return doubles[index];
// }
//
// public class StringDoubleArrayListIterator implements Iterator<StringDoublePair>, StringDoublePair {
// int index = -1;
//
// @Override
// public boolean hasNext() {
// return index < size - 1;
// }
//
// @Override
// public StringDoublePair next() {
// index++;
// return this;
// }
//
// @Override
// public void remove() {
// throw new RuntimeException("Cannot remove stuff from StringDoubleArrayList");
// }
//
// @Override
// public String getFirst() {
// return strings[index];
// }
//
// @Override
// public double getSecond() {
// return doubles[index];
// }
// }
//
// @Override
// public Iterator<StringDoublePair> iterator() {
// return new StringDoubleArrayListIterator();
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/StringDoublePair.java
// public interface StringDoublePair {
// public String getFirst();
// public double getSecond();
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import edu.stanford.nlp.semparse.open.util.StringDoubleArrayList;
import edu.stanford.nlp.semparse.open.util.StringDoublePair;
import fig.basic.Fmt;
import fig.basic.LogInfo;
import fig.basic.MapUtils;
import fig.basic.ValueComparator; | package edu.stanford.nlp.semparse.open.model;
/**
* A FeatureVector represents a mapping from feature (string) to value (double).
*
* We enforce the convention that each feature is (domain, name), so that the key space isn't a free-for-all.
*
* @author Percy Liang
*/
public class FeatureVector {
// These features map to the value 1 (most common case in NLP).
private List<String> indicatorFeatures;
// General features | // Path: src/edu/stanford/nlp/semparse/open/util/StringDoubleArrayList.java
// public class StringDoubleArrayList implements Iterable<StringDoublePair> {
//
// public static final int DEFAULT_CAPACITY = 10;
//
// private int size;
//
// // The two data arrays must have equal length.
// private String[] strings;
// private double[] doubles;
//
// public StringDoubleArrayList(int capacity) {
// if (capacity < 0)
// throw new IllegalArgumentException();
// strings = new String[capacity];
// doubles = new double[capacity];
// }
//
// public StringDoubleArrayList() {
// this(DEFAULT_CAPACITY);
// }
//
// public int size() {
// return size;
// }
//
// public void ensureCapacity(int minCapacity) {
// if (minCapacity - strings.length > 0) { // subtract to prevent overflow
// {
// String[] newStrings = new String[Math.max(strings.length * 2, minCapacity)];
// System.arraycopy(strings, 0, newStrings, 0, size);
// strings = newStrings;
// }
// {
// double[] newDoubles = new double[Math.max(doubles.length * 2, minCapacity)];
// System.arraycopy(doubles, 0, newDoubles, 0, size);
// doubles = newDoubles;
// }
// }
// }
//
// public void add(String s, double d) {
// if (size == strings.length)
// ensureCapacity(size + 1);
// strings[size] = s;
// doubles[size] = d;
// size++;
// }
//
// private void checkBoundExclusive(int index) {
// if (index >= size)
// throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
// }
//
// public String getString(int index) {
// checkBoundExclusive(index);
// return strings[index];
// }
//
// public double getDouble(int index) {
// checkBoundExclusive(index);
// return doubles[index];
// }
//
// public class StringDoubleArrayListIterator implements Iterator<StringDoublePair>, StringDoublePair {
// int index = -1;
//
// @Override
// public boolean hasNext() {
// return index < size - 1;
// }
//
// @Override
// public StringDoublePair next() {
// index++;
// return this;
// }
//
// @Override
// public void remove() {
// throw new RuntimeException("Cannot remove stuff from StringDoubleArrayList");
// }
//
// @Override
// public String getFirst() {
// return strings[index];
// }
//
// @Override
// public double getSecond() {
// return doubles[index];
// }
// }
//
// @Override
// public Iterator<StringDoublePair> iterator() {
// return new StringDoubleArrayListIterator();
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/StringDoublePair.java
// public interface StringDoublePair {
// public String getFirst();
// public double getSecond();
// }
// Path: src/edu/stanford/nlp/semparse/open/model/FeatureVector.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import edu.stanford.nlp.semparse.open.util.StringDoubleArrayList;
import edu.stanford.nlp.semparse.open.util.StringDoublePair;
import fig.basic.Fmt;
import fig.basic.LogInfo;
import fig.basic.MapUtils;
import fig.basic.ValueComparator;
package edu.stanford.nlp.semparse.open.model;
/**
* A FeatureVector represents a mapping from feature (string) to value (double).
*
* We enforce the convention that each feature is (domain, name), so that the key space isn't a free-for-all.
*
* @author Percy Liang
*/
public class FeatureVector {
// These features map to the value 1 (most common case in NLP).
private List<String> indicatorFeatures;
// General features | private StringDoubleArrayList generalFeatures; |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/FeatureVector.java | // Path: src/edu/stanford/nlp/semparse/open/util/StringDoubleArrayList.java
// public class StringDoubleArrayList implements Iterable<StringDoublePair> {
//
// public static final int DEFAULT_CAPACITY = 10;
//
// private int size;
//
// // The two data arrays must have equal length.
// private String[] strings;
// private double[] doubles;
//
// public StringDoubleArrayList(int capacity) {
// if (capacity < 0)
// throw new IllegalArgumentException();
// strings = new String[capacity];
// doubles = new double[capacity];
// }
//
// public StringDoubleArrayList() {
// this(DEFAULT_CAPACITY);
// }
//
// public int size() {
// return size;
// }
//
// public void ensureCapacity(int minCapacity) {
// if (minCapacity - strings.length > 0) { // subtract to prevent overflow
// {
// String[] newStrings = new String[Math.max(strings.length * 2, minCapacity)];
// System.arraycopy(strings, 0, newStrings, 0, size);
// strings = newStrings;
// }
// {
// double[] newDoubles = new double[Math.max(doubles.length * 2, minCapacity)];
// System.arraycopy(doubles, 0, newDoubles, 0, size);
// doubles = newDoubles;
// }
// }
// }
//
// public void add(String s, double d) {
// if (size == strings.length)
// ensureCapacity(size + 1);
// strings[size] = s;
// doubles[size] = d;
// size++;
// }
//
// private void checkBoundExclusive(int index) {
// if (index >= size)
// throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
// }
//
// public String getString(int index) {
// checkBoundExclusive(index);
// return strings[index];
// }
//
// public double getDouble(int index) {
// checkBoundExclusive(index);
// return doubles[index];
// }
//
// public class StringDoubleArrayListIterator implements Iterator<StringDoublePair>, StringDoublePair {
// int index = -1;
//
// @Override
// public boolean hasNext() {
// return index < size - 1;
// }
//
// @Override
// public StringDoublePair next() {
// index++;
// return this;
// }
//
// @Override
// public void remove() {
// throw new RuntimeException("Cannot remove stuff from StringDoubleArrayList");
// }
//
// @Override
// public String getFirst() {
// return strings[index];
// }
//
// @Override
// public double getSecond() {
// return doubles[index];
// }
// }
//
// @Override
// public Iterator<StringDoublePair> iterator() {
// return new StringDoubleArrayListIterator();
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/StringDoublePair.java
// public interface StringDoublePair {
// public String getFirst();
// public double getSecond();
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import edu.stanford.nlp.semparse.open.util.StringDoubleArrayList;
import edu.stanford.nlp.semparse.open.util.StringDoublePair;
import fig.basic.Fmt;
import fig.basic.LogInfo;
import fig.basic.MapUtils;
import fig.basic.ValueComparator; |
public void add(String domain, String name, double value) {
add(toFeature(domain, name), value);
}
private void add(String feature, double value) {
if (generalFeatures == null) generalFeatures = new StringDoubleArrayList();
generalFeatures.add(feature, value);
}
public void addWithBias(String domain, String name, double value) {
add(domain, name, value);
add(domain, name + "-bias", 1);
}
public void addFromString(String feature, double value) {
assert feature.contains(" :: ") : feature;
if (value == 1) add(feature);
else add(feature, value);
}
public void add(FeatureVector that) { add(that, AllFeatureMatcher.matcher); }
public void add(FeatureVector that, FeatureMatcher matcher) {
if (that.indicatorFeatures != null) {
if (indicatorFeatures == null) indicatorFeatures = new ArrayList<String>();
for (String f : that.indicatorFeatures)
if (matcher.matches(f))
indicatorFeatures.add(f);
}
if (that.generalFeatures != null) {
if (generalFeatures == null) generalFeatures = new StringDoubleArrayList(); | // Path: src/edu/stanford/nlp/semparse/open/util/StringDoubleArrayList.java
// public class StringDoubleArrayList implements Iterable<StringDoublePair> {
//
// public static final int DEFAULT_CAPACITY = 10;
//
// private int size;
//
// // The two data arrays must have equal length.
// private String[] strings;
// private double[] doubles;
//
// public StringDoubleArrayList(int capacity) {
// if (capacity < 0)
// throw new IllegalArgumentException();
// strings = new String[capacity];
// doubles = new double[capacity];
// }
//
// public StringDoubleArrayList() {
// this(DEFAULT_CAPACITY);
// }
//
// public int size() {
// return size;
// }
//
// public void ensureCapacity(int minCapacity) {
// if (minCapacity - strings.length > 0) { // subtract to prevent overflow
// {
// String[] newStrings = new String[Math.max(strings.length * 2, minCapacity)];
// System.arraycopy(strings, 0, newStrings, 0, size);
// strings = newStrings;
// }
// {
// double[] newDoubles = new double[Math.max(doubles.length * 2, minCapacity)];
// System.arraycopy(doubles, 0, newDoubles, 0, size);
// doubles = newDoubles;
// }
// }
// }
//
// public void add(String s, double d) {
// if (size == strings.length)
// ensureCapacity(size + 1);
// strings[size] = s;
// doubles[size] = d;
// size++;
// }
//
// private void checkBoundExclusive(int index) {
// if (index >= size)
// throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
// }
//
// public String getString(int index) {
// checkBoundExclusive(index);
// return strings[index];
// }
//
// public double getDouble(int index) {
// checkBoundExclusive(index);
// return doubles[index];
// }
//
// public class StringDoubleArrayListIterator implements Iterator<StringDoublePair>, StringDoublePair {
// int index = -1;
//
// @Override
// public boolean hasNext() {
// return index < size - 1;
// }
//
// @Override
// public StringDoublePair next() {
// index++;
// return this;
// }
//
// @Override
// public void remove() {
// throw new RuntimeException("Cannot remove stuff from StringDoubleArrayList");
// }
//
// @Override
// public String getFirst() {
// return strings[index];
// }
//
// @Override
// public double getSecond() {
// return doubles[index];
// }
// }
//
// @Override
// public Iterator<StringDoublePair> iterator() {
// return new StringDoubleArrayListIterator();
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/StringDoublePair.java
// public interface StringDoublePair {
// public String getFirst();
// public double getSecond();
// }
// Path: src/edu/stanford/nlp/semparse/open/model/FeatureVector.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import edu.stanford.nlp.semparse.open.util.StringDoubleArrayList;
import edu.stanford.nlp.semparse.open.util.StringDoublePair;
import fig.basic.Fmt;
import fig.basic.LogInfo;
import fig.basic.MapUtils;
import fig.basic.ValueComparator;
public void add(String domain, String name, double value) {
add(toFeature(domain, name), value);
}
private void add(String feature, double value) {
if (generalFeatures == null) generalFeatures = new StringDoubleArrayList();
generalFeatures.add(feature, value);
}
public void addWithBias(String domain, String name, double value) {
add(domain, name, value);
add(domain, name + "-bias", 1);
}
public void addFromString(String feature, double value) {
assert feature.contains(" :: ") : feature;
if (value == 1) add(feature);
else add(feature, value);
}
public void add(FeatureVector that) { add(that, AllFeatureMatcher.matcher); }
public void add(FeatureVector that, FeatureMatcher matcher) {
if (that.indicatorFeatures != null) {
if (indicatorFeatures == null) indicatorFeatures = new ArrayList<String>();
for (String f : that.indicatorFeatures)
if (matcher.matches(f))
indicatorFeatures.add(f);
}
if (that.generalFeatures != null) {
if (generalFeatures == null) generalFeatures = new StringDoubleArrayList(); | for (StringDoublePair pair : that.generalFeatures) |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/core/eval/Evaluator.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/Learner.java
// public interface Learner {
//
// // ============================================================
// // Log
// // ============================================================
//
// public void logParam();
// public void logFeatureWeights(Candidate candidate);
// public void logFeatureDiff(Candidate trueCandidate, Candidate predCandidate);
// public void shutUp();
//
// // ============================================================
// // Predict
// // ============================================================
//
// public List<Pair<Candidate, Double>> getRankedCandidates(Example example);
//
// // ============================================================
// // Learn
// // ============================================================
//
// public void learn(Dataset dataset, FeatureMatcher additionalFeatureMatcher);
// public void setIterativeTester(IterativeTester tester);
//
// // ============================================================
// // Persistence
// // ============================================================
//
// public void saveModel(String path);
// public void loadModel(String path);
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.Learner;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.Fmt;
import fig.basic.ListUtils;
import fig.basic.LogInfo;
import fig.exec.Execution; | package edu.stanford.nlp.semparse.open.core.eval;
/**
* Deal with evaluation.
* With zero-one loss, "correct" means matching all criteria
* - Wiki : match all target entities
* - Web : match first, second, and last
*
* pred = predicted candidate (first candidate in rankedCandidates)
* true = first correct candidate in rankedCandidates
* best = the best thing we can ever select from the web page (may not match all target entities)
*
* SUPER FAIL = (firstTrue == null)
* NORMAL FAIL = (firstTrue.rank != 1)
* SUCCESS = (firstTrue.rank == 1)
*/
public class Evaluator {
String testSuiteName; | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/Learner.java
// public interface Learner {
//
// // ============================================================
// // Log
// // ============================================================
//
// public void logParam();
// public void logFeatureWeights(Candidate candidate);
// public void logFeatureDiff(Candidate trueCandidate, Candidate predCandidate);
// public void shutUp();
//
// // ============================================================
// // Predict
// // ============================================================
//
// public List<Pair<Candidate, Double>> getRankedCandidates(Example example);
//
// // ============================================================
// // Learn
// // ============================================================
//
// public void learn(Dataset dataset, FeatureMatcher additionalFeatureMatcher);
// public void setIterativeTester(IterativeTester tester);
//
// // ============================================================
// // Persistence
// // ============================================================
//
// public void saveModel(String path);
// public void loadModel(String path);
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/core/eval/Evaluator.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.Learner;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.Fmt;
import fig.basic.ListUtils;
import fig.basic.LogInfo;
import fig.exec.Execution;
package edu.stanford.nlp.semparse.open.core.eval;
/**
* Deal with evaluation.
* With zero-one loss, "correct" means matching all criteria
* - Wiki : match all target entities
* - Web : match first, second, and last
*
* pred = predicted candidate (first candidate in rankedCandidates)
* true = first correct candidate in rankedCandidates
* best = the best thing we can ever select from the web page (may not match all target entities)
*
* SUPER FAIL = (firstTrue == null)
* NORMAL FAIL = (firstTrue.rank != 1)
* SUCCESS = (firstTrue.rank == 1)
*/
public class Evaluator {
String testSuiteName; | Learner learner; |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/core/eval/Evaluator.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/Learner.java
// public interface Learner {
//
// // ============================================================
// // Log
// // ============================================================
//
// public void logParam();
// public void logFeatureWeights(Candidate candidate);
// public void logFeatureDiff(Candidate trueCandidate, Candidate predCandidate);
// public void shutUp();
//
// // ============================================================
// // Predict
// // ============================================================
//
// public List<Pair<Candidate, Double>> getRankedCandidates(Example example);
//
// // ============================================================
// // Learn
// // ============================================================
//
// public void learn(Dataset dataset, FeatureMatcher additionalFeatureMatcher);
// public void setIterativeTester(IterativeTester tester);
//
// // ============================================================
// // Persistence
// // ============================================================
//
// public void saveModel(String path);
// public void loadModel(String path);
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.Learner;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.Fmt;
import fig.basic.ListUtils;
import fig.basic.LogInfo;
import fig.exec.Execution; | package edu.stanford.nlp.semparse.open.core.eval;
/**
* Deal with evaluation.
* With zero-one loss, "correct" means matching all criteria
* - Wiki : match all target entities
* - Web : match first, second, and last
*
* pred = predicted candidate (first candidate in rankedCandidates)
* true = first correct candidate in rankedCandidates
* best = the best thing we can ever select from the web page (may not match all target entities)
*
* SUPER FAIL = (firstTrue == null)
* NORMAL FAIL = (firstTrue.rank != 1)
* SUCCESS = (firstTrue.rank == 1)
*/
public class Evaluator {
String testSuiteName;
Learner learner;
int numExamples = 0, numSuccess = 0, numNormalFail = 0, numSuperFail = 0, numFound = 0;
List<EvaluationCase> successes, normalFails, superFails;
double sumF1onExpectedEntities = 0, sumF1onBest = 0; | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/Learner.java
// public interface Learner {
//
// // ============================================================
// // Log
// // ============================================================
//
// public void logParam();
// public void logFeatureWeights(Candidate candidate);
// public void logFeatureDiff(Candidate trueCandidate, Candidate predCandidate);
// public void shutUp();
//
// // ============================================================
// // Predict
// // ============================================================
//
// public List<Pair<Candidate, Double>> getRankedCandidates(Example example);
//
// // ============================================================
// // Learn
// // ============================================================
//
// public void learn(Dataset dataset, FeatureMatcher additionalFeatureMatcher);
// public void setIterativeTester(IterativeTester tester);
//
// // ============================================================
// // Persistence
// // ============================================================
//
// public void saveModel(String path);
// public void loadModel(String path);
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/core/eval/Evaluator.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.Learner;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.Fmt;
import fig.basic.ListUtils;
import fig.basic.LogInfo;
import fig.exec.Execution;
package edu.stanford.nlp.semparse.open.core.eval;
/**
* Deal with evaluation.
* With zero-one loss, "correct" means matching all criteria
* - Wiki : match all target entities
* - Web : match first, second, and last
*
* pred = predicted candidate (first candidate in rankedCandidates)
* true = first correct candidate in rankedCandidates
* best = the best thing we can ever select from the web page (may not match all target entities)
*
* SUPER FAIL = (firstTrue == null)
* NORMAL FAIL = (firstTrue.rank != 1)
* SUCCESS = (firstTrue.rank == 1)
*/
public class Evaluator {
String testSuiteName;
Learner learner;
int numExamples = 0, numSuccess = 0, numNormalFail = 0, numSuperFail = 0, numFound = 0;
List<EvaluationCase> successes, normalFails, superFails;
double sumF1onExpectedEntities = 0, sumF1onBest = 0; | Multiset<Integer> firstTrueUniqueRanks; |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/core/eval/Evaluator.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/Learner.java
// public interface Learner {
//
// // ============================================================
// // Log
// // ============================================================
//
// public void logParam();
// public void logFeatureWeights(Candidate candidate);
// public void logFeatureDiff(Candidate trueCandidate, Candidate predCandidate);
// public void shutUp();
//
// // ============================================================
// // Predict
// // ============================================================
//
// public List<Pair<Candidate, Double>> getRankedCandidates(Example example);
//
// // ============================================================
// // Learn
// // ============================================================
//
// public void learn(Dataset dataset, FeatureMatcher additionalFeatureMatcher);
// public void setIterativeTester(IterativeTester tester);
//
// // ============================================================
// // Persistence
// // ============================================================
//
// public void saveModel(String path);
// public void loadModel(String path);
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.Learner;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.Fmt;
import fig.basic.ListUtils;
import fig.basic.LogInfo;
import fig.exec.Execution; | package edu.stanford.nlp.semparse.open.core.eval;
/**
* Deal with evaluation.
* With zero-one loss, "correct" means matching all criteria
* - Wiki : match all target entities
* - Web : match first, second, and last
*
* pred = predicted candidate (first candidate in rankedCandidates)
* true = first correct candidate in rankedCandidates
* best = the best thing we can ever select from the web page (may not match all target entities)
*
* SUPER FAIL = (firstTrue == null)
* NORMAL FAIL = (firstTrue.rank != 1)
* SUCCESS = (firstTrue.rank == 1)
*/
public class Evaluator {
String testSuiteName;
Learner learner;
int numExamples = 0, numSuccess = 0, numNormalFail = 0, numSuperFail = 0, numFound = 0;
List<EvaluationCase> successes, normalFails, superFails;
double sumF1onExpectedEntities = 0, sumF1onBest = 0;
Multiset<Integer> firstTrueUniqueRanks;
public Evaluator(String testSuiteName, Learner learner) {
this.testSuiteName = testSuiteName;
this.learner = learner;
successes = new ArrayList<>();
normalFails = new ArrayList<>();
superFails = new ArrayList<>();
firstTrueUniqueRanks = new Multiset<>();
}
| // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/Learner.java
// public interface Learner {
//
// // ============================================================
// // Log
// // ============================================================
//
// public void logParam();
// public void logFeatureWeights(Candidate candidate);
// public void logFeatureDiff(Candidate trueCandidate, Candidate predCandidate);
// public void shutUp();
//
// // ============================================================
// // Predict
// // ============================================================
//
// public List<Pair<Candidate, Double>> getRankedCandidates(Example example);
//
// // ============================================================
// // Learn
// // ============================================================
//
// public void learn(Dataset dataset, FeatureMatcher additionalFeatureMatcher);
// public void setIterativeTester(IterativeTester tester);
//
// // ============================================================
// // Persistence
// // ============================================================
//
// public void saveModel(String path);
// public void loadModel(String path);
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/Multiset.java
// public class Multiset<T> {
// protected final HashMap<T, Integer> map = new HashMap<>();
// protected int size = 0;
//
// public void add(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + 1);
// size++;
// }
//
// public void add(T entry, int incr) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// map.put(entry, count + incr);
// size += incr;
// }
//
// public boolean contains(T entry) {
// return map.containsKey(entry);
// }
//
// public int count(T entry) {
// Integer count = map.get(entry);
// if (count == null)
// count = 0;
// return count;
// }
//
// public Set<T> elementSet() {
// return map.keySet();
// }
//
// public Set<Map.Entry<T, Integer>> entrySet() {
// return map.entrySet();
// }
//
// public int size() {
// return size;
// }
//
// public boolean isEmpty() {
// return size == 0;
// }
//
// public Multiset<T> getPrunedByCount(int minCount) {
// Multiset<T> pruned = new Multiset<>();
// for (Map.Entry<T, Integer> entry : map.entrySet()) {
// if (entry.getValue() >= minCount)
// pruned.add(entry.getKey(), entry.getValue());
// }
// return pruned;
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/core/eval/Evaluator.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.Learner;
import edu.stanford.nlp.semparse.open.util.Multiset;
import fig.basic.Fmt;
import fig.basic.ListUtils;
import fig.basic.LogInfo;
import fig.exec.Execution;
package edu.stanford.nlp.semparse.open.core.eval;
/**
* Deal with evaluation.
* With zero-one loss, "correct" means matching all criteria
* - Wiki : match all target entities
* - Web : match first, second, and last
*
* pred = predicted candidate (first candidate in rankedCandidates)
* true = first correct candidate in rankedCandidates
* best = the best thing we can ever select from the web page (may not match all target entities)
*
* SUPER FAIL = (firstTrue == null)
* NORMAL FAIL = (firstTrue.rank != 1)
* SUCCESS = (firstTrue.rank == 1)
*/
public class Evaluator {
String testSuiteName;
Learner learner;
int numExamples = 0, numSuccess = 0, numNormalFail = 0, numSuperFail = 0, numFound = 0;
List<EvaluationCase> successes, normalFails, superFails;
double sumF1onExpectedEntities = 0, sumF1onBest = 0;
Multiset<Integer> firstTrueUniqueRanks;
public Evaluator(String testSuiteName, Learner learner) {
this.testSuiteName = testSuiteName;
this.learner = learner;
successes = new ArrayList<>();
normalFails = new ArrayList<>();
superFails = new ArrayList<>();
firstTrueUniqueRanks = new Multiset<>();
}
| public EvaluationCase add(Example ex, CandidateStatistics pred, CandidateStatistics firstTrue, CandidateStatistics best) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/LearnerMaxEntWithBeamSearch.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo;
import fig.basic.Option;
import fig.basic.Pair; | package edu.stanford.nlp.semparse.open.model;
public class LearnerMaxEntWithBeamSearch extends LearnerMaxEnt {
public static class Options {
@Option public int beamSize = 500;
@Option public int beamTrainStartIter = 1;
@Option public String beamCandidateType = "cutrange";
}
public static Options opts = new Options();
@Override | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/model/LearnerMaxEntWithBeamSearch.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo;
import fig.basic.Option;
import fig.basic.Pair;
package edu.stanford.nlp.semparse.open.model;
public class LearnerMaxEntWithBeamSearch extends LearnerMaxEnt {
public static class Options {
@Option public int beamSize = 500;
@Option public int beamTrainStartIter = 1;
@Option public String beamCandidateType = "cutrange";
}
public static Options opts = new Options();
@Override | protected List<Candidate> getCandidates(Example example) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/LearnerMaxEntWithBeamSearch.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo;
import fig.basic.Option;
import fig.basic.Pair; | package edu.stanford.nlp.semparse.open.model;
public class LearnerMaxEntWithBeamSearch extends LearnerMaxEnt {
public static class Options {
@Option public int beamSize = 500;
@Option public int beamTrainStartIter = 1;
@Option public String beamCandidateType = "cutrange";
}
public static Options opts = new Options();
@Override | // Path: src/edu/stanford/nlp/semparse/open/dataset/Example.java
// public class Example {
// public String displayId; // For debugging
//
// public final String phrase;
// public final ExpectedAnswer expectedAnswer;
// public KNode tree; // Deterministic function of the phrase
// public List<CandidateGroup> candidateGroups;
// public List<Candidate> candidates; // Candidate predictions
// public AveragedWordVector averagedWordVector;
//
// public Example(String phrase) {
// this(phrase, null);
// }
//
// public Example(String phrase, ExpectedAnswer expectedAnswer) {
// this.phrase = phrase;
// this.expectedAnswer = expectedAnswer;
// }
//
// @Override public String toString() {
// return "[" + phrase + "]";
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(phrase);
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/model/LearnerMaxEntWithBeamSearch.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.Example;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo;
import fig.basic.Option;
import fig.basic.Pair;
package edu.stanford.nlp.semparse.open.model;
public class LearnerMaxEntWithBeamSearch extends LearnerMaxEnt {
public static class Options {
@Option public int beamSize = 500;
@Option public int beamTrainStartIter = 1;
@Option public String beamCandidateType = "cutrange";
}
public static Options opts = new Options();
@Override | protected List<Candidate> getCandidates(Example example) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/ExpectedAnswerInjectiveMatch.java | // Path: src/edu/stanford/nlp/semparse/open/core/eval/CandidateStatistics.java
// public class CandidateStatistics {
// public final Candidate candidate;
// public final int rank, uniqueRank; // rank and uniqueRank are 1-indexed
// public final double score;
//
// public CandidateStatistics(Candidate candidate, int rank, int uniqueRank, double score) {
// this.candidate = candidate;
// this.rank = rank;
// this.uniqueRank = uniqueRank;
// this.score = score;
// }
//
// /**
// * Convert Pair<Candidate, Double> to CandidateStatistics
// */
// public static List<CandidateStatistics> getRankedCandidateStats(List<Pair<Candidate, Double>> rankedCandidates) {
// List<CandidateStatistics> answer = new ArrayList<>();
// Set<List<String>> foundPredictedEntities = new HashSet<>();
// for (int rank = 0; rank < rankedCandidates.size(); rank++) {
// Pair<Candidate, Double> entry = rankedCandidates.get(rank);
// Candidate candidate = entry.getFirst();
// foundPredictedEntities.add(candidate.predictedEntities);
// answer.add(new CandidateStatistics(candidate, rank + 1, foundPredictedEntities.size(), entry.getSecond()));
// }
// return answer;
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java
// public class BipartiteMatcher {
//
// private final int SOURCE = 1;
// private final int SINK = -1;
//
// private final Map<Object, Integer> fromMap;
// private final Map<Object, Integer> toMap;
// private final Map<Integer, List<Integer>> edges;
//
// public BipartiteMatcher() {
// this.fromMap = new HashMap<>();
// this.toMap = new HashMap<>();
// this.edges = new HashMap<>();
// }
//
// public BipartiteMatcher(List<TargetEntity> targetEntities, List<String> predictedEntities) {
// this();
// for (int i = 0; i < targetEntities.size(); i++) {
// TargetEntity targetEntity = targetEntities.get(i);
// for (int j = 0; j < predictedEntities.size(); j++) {
// if (targetEntity.match(predictedEntities.get(j))) {
// this.addEdge(i, j);
// }
// }
// }
// }
//
// public void addEdge(Object fromObj, Object toObj) {
// Integer from = fromMap.get(fromObj), to = toMap.get(toObj);
// if (from == null) {
// from = 2 + fromMap.size();
// fromMap.put(fromObj, from);
// if (!edges.containsKey(SOURCE)) edges.put(SOURCE, new ArrayList<>());
// edges.get(SOURCE).add(from);
// }
// if (to == null) {
// to = - 2 - toMap.size();
// toMap.put(toObj, to);
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(SINK);
// }
// if (!edges.containsKey(from)) edges.put(from, new ArrayList<>());
// edges.get(from).add(to);
// }
//
// private List<Integer> foundPath;
// private Set<Integer> foundNodes;
//
// public int findMaximumMatch() {
// int count = 0;
// this.foundPath = new ArrayList<>();
// this.foundNodes = new HashSet<>();
// while (findPath(SOURCE)) {
// count++;
// for (int i = 0; i < foundPath.size() - 1; i++) {
// int from = foundPath.get(i), to = foundPath.get(i+1);
// edges.get(from).remove(Integer.valueOf(to));
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(from);
// }
// foundPath.clear();
// foundNodes.clear();
// }
// return count;
// }
//
// private boolean findPath(int node) {
// // DFS
// foundNodes.add(node);
// foundPath.add(node);
// if (node == SINK) return true;
// for (int dest : edges.get(node)) {
// if (!foundNodes.contains(dest)) {
// if (findPath(dest)) return true;
// }
// }
// foundPath.remove(foundPath.size() - 1);
// return false;
// }
//
// public static void main(String[] args) {
// // Test Method
// BipartiteMatcher bm = new BipartiteMatcher();
// bm.addEdge("A", 1); bm.addEdge("A", 2); bm.addEdge("A", 4);
// bm.addEdge("B", 1); bm.addEdge("C", 2); bm.addEdge("C", 1);
// bm.addEdge("D", 4); bm.addEdge("D", 5); bm.addEdge("E", 3);
// System.out.println(bm.findMaximumMatch());
// }
//
// }
| import java.util.List;
import edu.stanford.nlp.semparse.open.core.eval.CandidateStatistics;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.util.BipartiteMatcher;
import fig.basic.LogInfo;
import fig.basic.Option; | package edu.stanford.nlp.semparse.open.dataset;
public class ExpectedAnswerInjectiveMatch extends ExpectedAnswer {
public static class Options {
@Option public double irThreshold = 0.8;
@Option public String irCriterion = "recall";
}
public static Options opts = new Options();
| // Path: src/edu/stanford/nlp/semparse/open/core/eval/CandidateStatistics.java
// public class CandidateStatistics {
// public final Candidate candidate;
// public final int rank, uniqueRank; // rank and uniqueRank are 1-indexed
// public final double score;
//
// public CandidateStatistics(Candidate candidate, int rank, int uniqueRank, double score) {
// this.candidate = candidate;
// this.rank = rank;
// this.uniqueRank = uniqueRank;
// this.score = score;
// }
//
// /**
// * Convert Pair<Candidate, Double> to CandidateStatistics
// */
// public static List<CandidateStatistics> getRankedCandidateStats(List<Pair<Candidate, Double>> rankedCandidates) {
// List<CandidateStatistics> answer = new ArrayList<>();
// Set<List<String>> foundPredictedEntities = new HashSet<>();
// for (int rank = 0; rank < rankedCandidates.size(); rank++) {
// Pair<Candidate, Double> entry = rankedCandidates.get(rank);
// Candidate candidate = entry.getFirst();
// foundPredictedEntities.add(candidate.predictedEntities);
// answer.add(new CandidateStatistics(candidate, rank + 1, foundPredictedEntities.size(), entry.getSecond()));
// }
// return answer;
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java
// public class BipartiteMatcher {
//
// private final int SOURCE = 1;
// private final int SINK = -1;
//
// private final Map<Object, Integer> fromMap;
// private final Map<Object, Integer> toMap;
// private final Map<Integer, List<Integer>> edges;
//
// public BipartiteMatcher() {
// this.fromMap = new HashMap<>();
// this.toMap = new HashMap<>();
// this.edges = new HashMap<>();
// }
//
// public BipartiteMatcher(List<TargetEntity> targetEntities, List<String> predictedEntities) {
// this();
// for (int i = 0; i < targetEntities.size(); i++) {
// TargetEntity targetEntity = targetEntities.get(i);
// for (int j = 0; j < predictedEntities.size(); j++) {
// if (targetEntity.match(predictedEntities.get(j))) {
// this.addEdge(i, j);
// }
// }
// }
// }
//
// public void addEdge(Object fromObj, Object toObj) {
// Integer from = fromMap.get(fromObj), to = toMap.get(toObj);
// if (from == null) {
// from = 2 + fromMap.size();
// fromMap.put(fromObj, from);
// if (!edges.containsKey(SOURCE)) edges.put(SOURCE, new ArrayList<>());
// edges.get(SOURCE).add(from);
// }
// if (to == null) {
// to = - 2 - toMap.size();
// toMap.put(toObj, to);
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(SINK);
// }
// if (!edges.containsKey(from)) edges.put(from, new ArrayList<>());
// edges.get(from).add(to);
// }
//
// private List<Integer> foundPath;
// private Set<Integer> foundNodes;
//
// public int findMaximumMatch() {
// int count = 0;
// this.foundPath = new ArrayList<>();
// this.foundNodes = new HashSet<>();
// while (findPath(SOURCE)) {
// count++;
// for (int i = 0; i < foundPath.size() - 1; i++) {
// int from = foundPath.get(i), to = foundPath.get(i+1);
// edges.get(from).remove(Integer.valueOf(to));
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(from);
// }
// foundPath.clear();
// foundNodes.clear();
// }
// return count;
// }
//
// private boolean findPath(int node) {
// // DFS
// foundNodes.add(node);
// foundPath.add(node);
// if (node == SINK) return true;
// for (int dest : edges.get(node)) {
// if (!foundNodes.contains(dest)) {
// if (findPath(dest)) return true;
// }
// }
// foundPath.remove(foundPath.size() - 1);
// return false;
// }
//
// public static void main(String[] args) {
// // Test Method
// BipartiteMatcher bm = new BipartiteMatcher();
// bm.addEdge("A", 1); bm.addEdge("A", 2); bm.addEdge("A", 4);
// bm.addEdge("B", 1); bm.addEdge("C", 2); bm.addEdge("C", 1);
// bm.addEdge("D", 4); bm.addEdge("D", 5); bm.addEdge("E", 3);
// System.out.println(bm.findMaximumMatch());
// }
//
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/ExpectedAnswerInjectiveMatch.java
import java.util.List;
import edu.stanford.nlp.semparse.open.core.eval.CandidateStatistics;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.util.BipartiteMatcher;
import fig.basic.LogInfo;
import fig.basic.Option;
package edu.stanford.nlp.semparse.open.dataset;
public class ExpectedAnswerInjectiveMatch extends ExpectedAnswer {
public static class Options {
@Option public double irThreshold = 0.8;
@Option public String irCriterion = "recall";
}
public static Options opts = new Options();
| public ExpectedAnswerInjectiveMatch(TargetEntity... targetEntities) {super(targetEntities);} |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/feature/FeaturePostProcessor.java | // Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/CandidateGroup.java
// public class CandidateGroup {
// public static class Options {
// @Option(gloss = "level of entity string normalization when creating candidate group "
// + "(0 = none / 1 = whitespace / 2 = simple / 3 = aggressive)")
// public int lateNormalizeEntities = 2;
// }
// public static Options opts = new Options();
//
// public final Example ex;
// public final List<KNode> selectedNodes;
// public final List<String> predictedEntities;
// final List<Candidate> candidates;
// public FeatureVector features;
// public AveragedWordVector averagedWordVector;
//
// public CandidateGroup(Example ex, List<KNode> selectedNodes) {
// this.ex = ex;
// this.selectedNodes = new ArrayList<>(selectedNodes);
// List<String> entities = new ArrayList<>();
// for (KNode node : selectedNodes) {
// entities.add(LingUtils.normalize(node.fullText, opts.lateNormalizeEntities));
// }
// predictedEntities = new ArrayList<>(entities);
// candidates = new ArrayList<>();
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(predictedEntities);
// }
//
// public int numEntities() {
// return predictedEntities.size();
// }
//
// public int numCandidate() {
// return candidates.size();
// }
//
// public List<Candidate> getCandidates() {
// return Collections.unmodifiableList(candidates);
// }
//
// public Candidate addCandidate(TreePattern pattern) {
// return new Candidate(this, pattern);
// }
//
// public double getReward() {
// return ex.expectedAnswer.reward(this);
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return StringSampler.sampleEntities(predictedEntities, StringSampler.DEFAULT_LIMIT);
// }
//
// public String allEntities() {
// return StringSampler.sampleEntities(predictedEntities);
// }
//
// }
| import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import edu.stanford.nlp.semparse.open.model.candidate.CandidateGroup;
import fig.basic.LogInfo; | package edu.stanford.nlp.semparse.open.model.feature;
public abstract class FeaturePostProcessor {
public abstract void process(Candidate candidate); | // Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/CandidateGroup.java
// public class CandidateGroup {
// public static class Options {
// @Option(gloss = "level of entity string normalization when creating candidate group "
// + "(0 = none / 1 = whitespace / 2 = simple / 3 = aggressive)")
// public int lateNormalizeEntities = 2;
// }
// public static Options opts = new Options();
//
// public final Example ex;
// public final List<KNode> selectedNodes;
// public final List<String> predictedEntities;
// final List<Candidate> candidates;
// public FeatureVector features;
// public AveragedWordVector averagedWordVector;
//
// public CandidateGroup(Example ex, List<KNode> selectedNodes) {
// this.ex = ex;
// this.selectedNodes = new ArrayList<>(selectedNodes);
// List<String> entities = new ArrayList<>();
// for (KNode node : selectedNodes) {
// entities.add(LingUtils.normalize(node.fullText, opts.lateNormalizeEntities));
// }
// predictedEntities = new ArrayList<>(entities);
// candidates = new ArrayList<>();
// }
//
// public void initAveragedWordVector() {
// if (averagedWordVector == null)
// averagedWordVector = new AveragedWordVector(predictedEntities);
// }
//
// public int numEntities() {
// return predictedEntities.size();
// }
//
// public int numCandidate() {
// return candidates.size();
// }
//
// public List<Candidate> getCandidates() {
// return Collections.unmodifiableList(candidates);
// }
//
// public Candidate addCandidate(TreePattern pattern) {
// return new Candidate(this, pattern);
// }
//
// public double getReward() {
// return ex.expectedAnswer.reward(this);
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return StringSampler.sampleEntities(predictedEntities, StringSampler.DEFAULT_LIMIT);
// }
//
// public String allEntities() {
// return StringSampler.sampleEntities(predictedEntities);
// }
//
// }
// Path: src/edu/stanford/nlp/semparse/open/model/feature/FeaturePostProcessor.java
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import edu.stanford.nlp.semparse.open.model.candidate.CandidateGroup;
import fig.basic.LogInfo;
package edu.stanford.nlp.semparse.open.model.feature;
public abstract class FeaturePostProcessor {
public abstract void process(Candidate candidate); | public abstract void process(CandidateGroup group); |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/CriteriaExactMatch.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java
// public class BipartiteMatcher {
//
// private final int SOURCE = 1;
// private final int SINK = -1;
//
// private final Map<Object, Integer> fromMap;
// private final Map<Object, Integer> toMap;
// private final Map<Integer, List<Integer>> edges;
//
// public BipartiteMatcher() {
// this.fromMap = new HashMap<>();
// this.toMap = new HashMap<>();
// this.edges = new HashMap<>();
// }
//
// public BipartiteMatcher(List<TargetEntity> targetEntities, List<String> predictedEntities) {
// this();
// for (int i = 0; i < targetEntities.size(); i++) {
// TargetEntity targetEntity = targetEntities.get(i);
// for (int j = 0; j < predictedEntities.size(); j++) {
// if (targetEntity.match(predictedEntities.get(j))) {
// this.addEdge(i, j);
// }
// }
// }
// }
//
// public void addEdge(Object fromObj, Object toObj) {
// Integer from = fromMap.get(fromObj), to = toMap.get(toObj);
// if (from == null) {
// from = 2 + fromMap.size();
// fromMap.put(fromObj, from);
// if (!edges.containsKey(SOURCE)) edges.put(SOURCE, new ArrayList<>());
// edges.get(SOURCE).add(from);
// }
// if (to == null) {
// to = - 2 - toMap.size();
// toMap.put(toObj, to);
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(SINK);
// }
// if (!edges.containsKey(from)) edges.put(from, new ArrayList<>());
// edges.get(from).add(to);
// }
//
// private List<Integer> foundPath;
// private Set<Integer> foundNodes;
//
// public int findMaximumMatch() {
// int count = 0;
// this.foundPath = new ArrayList<>();
// this.foundNodes = new HashSet<>();
// while (findPath(SOURCE)) {
// count++;
// for (int i = 0; i < foundPath.size() - 1; i++) {
// int from = foundPath.get(i), to = foundPath.get(i+1);
// edges.get(from).remove(Integer.valueOf(to));
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(from);
// }
// foundPath.clear();
// foundNodes.clear();
// }
// return count;
// }
//
// private boolean findPath(int node) {
// // DFS
// foundNodes.add(node);
// foundPath.add(node);
// if (node == SINK) return true;
// for (int dest : edges.get(node)) {
// if (!foundNodes.contains(dest)) {
// if (findPath(dest)) return true;
// }
// }
// foundPath.remove(foundPath.size() - 1);
// return false;
// }
//
// public static void main(String[] args) {
// // Test Method
// BipartiteMatcher bm = new BipartiteMatcher();
// bm.addEdge("A", 1); bm.addEdge("A", 2); bm.addEdge("A", 4);
// bm.addEdge("B", 1); bm.addEdge("C", 2); bm.addEdge("C", 1);
// bm.addEdge("D", 4); bm.addEdge("D", 5); bm.addEdge("E", 3);
// System.out.println(bm.findMaximumMatch());
// }
//
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.util.BipartiteMatcher; | package edu.stanford.nlp.semparse.open.dataset;
/**
* Only 1 criteria: whether the lists are exactly the same.
*/
public class CriteriaExactMatch implements Criteria {
public final List<TargetEntity> targetEntities;
public CriteriaExactMatch(TargetEntity... targetEntities) {
this.targetEntities = Arrays.asList(targetEntities);
}
public CriteriaExactMatch(List<TargetEntity> targetEntities) {
this.targetEntities = targetEntities;
}
@Override
public List<TargetEntity> getTargetEntities() {
return targetEntities;
}
@Override
public int numCriteria() {
return 1;
}
@Override
public int countMatchedCriteria(List<String> predictedEntities) {
if (predictedEntities.size() == targetEntities.size()) | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java
// public class BipartiteMatcher {
//
// private final int SOURCE = 1;
// private final int SINK = -1;
//
// private final Map<Object, Integer> fromMap;
// private final Map<Object, Integer> toMap;
// private final Map<Integer, List<Integer>> edges;
//
// public BipartiteMatcher() {
// this.fromMap = new HashMap<>();
// this.toMap = new HashMap<>();
// this.edges = new HashMap<>();
// }
//
// public BipartiteMatcher(List<TargetEntity> targetEntities, List<String> predictedEntities) {
// this();
// for (int i = 0; i < targetEntities.size(); i++) {
// TargetEntity targetEntity = targetEntities.get(i);
// for (int j = 0; j < predictedEntities.size(); j++) {
// if (targetEntity.match(predictedEntities.get(j))) {
// this.addEdge(i, j);
// }
// }
// }
// }
//
// public void addEdge(Object fromObj, Object toObj) {
// Integer from = fromMap.get(fromObj), to = toMap.get(toObj);
// if (from == null) {
// from = 2 + fromMap.size();
// fromMap.put(fromObj, from);
// if (!edges.containsKey(SOURCE)) edges.put(SOURCE, new ArrayList<>());
// edges.get(SOURCE).add(from);
// }
// if (to == null) {
// to = - 2 - toMap.size();
// toMap.put(toObj, to);
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(SINK);
// }
// if (!edges.containsKey(from)) edges.put(from, new ArrayList<>());
// edges.get(from).add(to);
// }
//
// private List<Integer> foundPath;
// private Set<Integer> foundNodes;
//
// public int findMaximumMatch() {
// int count = 0;
// this.foundPath = new ArrayList<>();
// this.foundNodes = new HashSet<>();
// while (findPath(SOURCE)) {
// count++;
// for (int i = 0; i < foundPath.size() - 1; i++) {
// int from = foundPath.get(i), to = foundPath.get(i+1);
// edges.get(from).remove(Integer.valueOf(to));
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(from);
// }
// foundPath.clear();
// foundNodes.clear();
// }
// return count;
// }
//
// private boolean findPath(int node) {
// // DFS
// foundNodes.add(node);
// foundPath.add(node);
// if (node == SINK) return true;
// for (int dest : edges.get(node)) {
// if (!foundNodes.contains(dest)) {
// if (findPath(dest)) return true;
// }
// }
// foundPath.remove(foundPath.size() - 1);
// return false;
// }
//
// public static void main(String[] args) {
// // Test Method
// BipartiteMatcher bm = new BipartiteMatcher();
// bm.addEdge("A", 1); bm.addEdge("A", 2); bm.addEdge("A", 4);
// bm.addEdge("B", 1); bm.addEdge("C", 2); bm.addEdge("C", 1);
// bm.addEdge("D", 4); bm.addEdge("D", 5); bm.addEdge("E", 3);
// System.out.println(bm.findMaximumMatch());
// }
//
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/CriteriaExactMatch.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.util.BipartiteMatcher;
package edu.stanford.nlp.semparse.open.dataset;
/**
* Only 1 criteria: whether the lists are exactly the same.
*/
public class CriteriaExactMatch implements Criteria {
public final List<TargetEntity> targetEntities;
public CriteriaExactMatch(TargetEntity... targetEntities) {
this.targetEntities = Arrays.asList(targetEntities);
}
public CriteriaExactMatch(List<TargetEntity> targetEntities) {
this.targetEntities = targetEntities;
}
@Override
public List<TargetEntity> getTargetEntities() {
return targetEntities;
}
@Override
public int numCriteria() {
return 1;
}
@Override
public int countMatchedCriteria(List<String> predictedEntities) {
if (predictedEntities.size() == targetEntities.size()) | if (new BipartiteMatcher(targetEntities, predictedEntities).findMaximumMatch() == targetEntities.size()) |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/core/InteractiveDemo.java | // Path: src/edu/stanford/nlp/semparse/open/core/eval/CandidateStatistics.java
// public class CandidateStatistics {
// public final Candidate candidate;
// public final int rank, uniqueRank; // rank and uniqueRank are 1-indexed
// public final double score;
//
// public CandidateStatistics(Candidate candidate, int rank, int uniqueRank, double score) {
// this.candidate = candidate;
// this.rank = rank;
// this.uniqueRank = uniqueRank;
// this.score = score;
// }
//
// /**
// * Convert Pair<Candidate, Double> to CandidateStatistics
// */
// public static List<CandidateStatistics> getRankedCandidateStats(List<Pair<Candidate, Double>> rankedCandidates) {
// List<CandidateStatistics> answer = new ArrayList<>();
// Set<List<String>> foundPredictedEntities = new HashSet<>();
// for (int rank = 0; rank < rankedCandidates.size(); rank++) {
// Pair<Candidate, Double> entry = rankedCandidates.get(rank);
// Candidate candidate = entry.getFirst();
// foundPredictedEntities.add(candidate.predictedEntities);
// answer.add(new CandidateStatistics(candidate, rank + 1, foundPredictedEntities.size(), entry.getSecond()));
// }
// return answer;
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import edu.stanford.nlp.semparse.open.core.eval.CandidateStatistics;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo; | package edu.stanford.nlp.semparse.open.core;
public class InteractiveDemo {
public final OpenSemanticParser parser;
public InteractiveDemo(OpenSemanticParser parser) {
this.parser = parser;
}
public void run() {
LogInfo.log("Starting interactive mode ...");
try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
while (true) {
System.out.println("============================================================");
System.out.print("Query: list of ");
String phrase = in.readLine();
if (phrase == null) {System.out.println(); break;}
if (phrase.isEmpty()) continue;
System.out.print("Web Page URL (blank for Google Search): ");
String url = in.readLine();
if (url == null) {System.out.println(); break;} | // Path: src/edu/stanford/nlp/semparse/open/core/eval/CandidateStatistics.java
// public class CandidateStatistics {
// public final Candidate candidate;
// public final int rank, uniqueRank; // rank and uniqueRank are 1-indexed
// public final double score;
//
// public CandidateStatistics(Candidate candidate, int rank, int uniqueRank, double score) {
// this.candidate = candidate;
// this.rank = rank;
// this.uniqueRank = uniqueRank;
// this.score = score;
// }
//
// /**
// * Convert Pair<Candidate, Double> to CandidateStatistics
// */
// public static List<CandidateStatistics> getRankedCandidateStats(List<Pair<Candidate, Double>> rankedCandidates) {
// List<CandidateStatistics> answer = new ArrayList<>();
// Set<List<String>> foundPredictedEntities = new HashSet<>();
// for (int rank = 0; rank < rankedCandidates.size(); rank++) {
// Pair<Candidate, Double> entry = rankedCandidates.get(rank);
// Candidate candidate = entry.getFirst();
// foundPredictedEntities.add(candidate.predictedEntities);
// answer.add(new CandidateStatistics(candidate, rank + 1, foundPredictedEntities.size(), entry.getSecond()));
// }
// return answer;
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/core/InteractiveDemo.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import edu.stanford.nlp.semparse.open.core.eval.CandidateStatistics;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo;
package edu.stanford.nlp.semparse.open.core;
public class InteractiveDemo {
public final OpenSemanticParser parser;
public InteractiveDemo(OpenSemanticParser parser) {
this.parser = parser;
}
public void run() {
LogInfo.log("Starting interactive mode ...");
try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
while (true) {
System.out.println("============================================================");
System.out.print("Query: list of ");
String phrase = in.readLine();
if (phrase == null) {System.out.println(); break;}
if (phrase.isEmpty()) continue;
System.out.print("Web Page URL (blank for Google Search): ");
String url = in.readLine();
if (url == null) {System.out.println(); break;} | CandidateStatistics pred = url.isEmpty() ? parser.predict(phrase) : parser.predict(phrase, url); |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/core/InteractiveDemo.java | // Path: src/edu/stanford/nlp/semparse/open/core/eval/CandidateStatistics.java
// public class CandidateStatistics {
// public final Candidate candidate;
// public final int rank, uniqueRank; // rank and uniqueRank are 1-indexed
// public final double score;
//
// public CandidateStatistics(Candidate candidate, int rank, int uniqueRank, double score) {
// this.candidate = candidate;
// this.rank = rank;
// this.uniqueRank = uniqueRank;
// this.score = score;
// }
//
// /**
// * Convert Pair<Candidate, Double> to CandidateStatistics
// */
// public static List<CandidateStatistics> getRankedCandidateStats(List<Pair<Candidate, Double>> rankedCandidates) {
// List<CandidateStatistics> answer = new ArrayList<>();
// Set<List<String>> foundPredictedEntities = new HashSet<>();
// for (int rank = 0; rank < rankedCandidates.size(); rank++) {
// Pair<Candidate, Double> entry = rankedCandidates.get(rank);
// Candidate candidate = entry.getFirst();
// foundPredictedEntities.add(candidate.predictedEntities);
// answer.add(new CandidateStatistics(candidate, rank + 1, foundPredictedEntities.size(), entry.getSecond()));
// }
// return answer;
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import edu.stanford.nlp.semparse.open.core.eval.CandidateStatistics;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo; | package edu.stanford.nlp.semparse.open.core;
public class InteractiveDemo {
public final OpenSemanticParser parser;
public InteractiveDemo(OpenSemanticParser parser) {
this.parser = parser;
}
public void run() {
LogInfo.log("Starting interactive mode ...");
try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
while (true) {
System.out.println("============================================================");
System.out.print("Query: list of ");
String phrase = in.readLine();
if (phrase == null) {System.out.println(); break;}
if (phrase.isEmpty()) continue;
System.out.print("Web Page URL (blank for Google Search): ");
String url = in.readLine();
if (url == null) {System.out.println(); break;}
CandidateStatistics pred = url.isEmpty() ? parser.predict(phrase) : parser.predict(phrase, url);
LogInfo.begin_track("PRED (top scoring candidate):");
if (pred == null) {
LogInfo.log("Rank 1 [Unique Rank 1]: NO CANDIDATE FOUND!");
} else {
LogInfo.logs("Rank 1 [Unique Rank 1]: (Total Feature Score = %s)", pred.score); | // Path: src/edu/stanford/nlp/semparse/open/core/eval/CandidateStatistics.java
// public class CandidateStatistics {
// public final Candidate candidate;
// public final int rank, uniqueRank; // rank and uniqueRank are 1-indexed
// public final double score;
//
// public CandidateStatistics(Candidate candidate, int rank, int uniqueRank, double score) {
// this.candidate = candidate;
// this.rank = rank;
// this.uniqueRank = uniqueRank;
// this.score = score;
// }
//
// /**
// * Convert Pair<Candidate, Double> to CandidateStatistics
// */
// public static List<CandidateStatistics> getRankedCandidateStats(List<Pair<Candidate, Double>> rankedCandidates) {
// List<CandidateStatistics> answer = new ArrayList<>();
// Set<List<String>> foundPredictedEntities = new HashSet<>();
// for (int rank = 0; rank < rankedCandidates.size(); rank++) {
// Pair<Candidate, Double> entry = rankedCandidates.get(rank);
// Candidate candidate = entry.getFirst();
// foundPredictedEntities.add(candidate.predictedEntities);
// answer.add(new CandidateStatistics(candidate, rank + 1, foundPredictedEntities.size(), entry.getSecond()));
// }
// return answer;
// }
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/core/InteractiveDemo.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import edu.stanford.nlp.semparse.open.core.eval.CandidateStatistics;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo;
package edu.stanford.nlp.semparse.open.core;
public class InteractiveDemo {
public final OpenSemanticParser parser;
public InteractiveDemo(OpenSemanticParser parser) {
this.parser = parser;
}
public void run() {
LogInfo.log("Starting interactive mode ...");
try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
while (true) {
System.out.println("============================================================");
System.out.print("Query: list of ");
String phrase = in.readLine();
if (phrase == null) {System.out.println(); break;}
if (phrase.isEmpty()) continue;
System.out.print("Web Page URL (blank for Google Search): ");
String url = in.readLine();
if (url == null) {System.out.println(); break;}
CandidateStatistics pred = url.isEmpty() ? parser.predict(phrase) : parser.predict(phrase, url);
LogInfo.begin_track("PRED (top scoring candidate):");
if (pred == null) {
LogInfo.log("Rank 1 [Unique Rank 1]: NO CANDIDATE FOUND!");
} else {
LogInfo.logs("Rank 1 [Unique Rank 1]: (Total Feature Score = %s)", pred.score); | Candidate candidate = pred.candidate; |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/Dataset.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityPersonName.java
// public class TargetEntityPersonName implements TargetEntity {
//
// public final String first;
// public final String mid;
// public final String last;
// final List<String> patterns = new ArrayList<>();
//
// public TargetEntityPersonName(String first, String last) {
// this.first = first;
// this.mid = null;
// this.last = last;
// generatePatterns();
// }
//
// public TargetEntityPersonName(String first, String mid, String last) {
// this.first = first;
// if (mid.length() == 2 && mid.charAt(1) == '.')
// this.mid = mid.substring(0, 1);
// else
// this.mid = mid;
// this.last = last;
// generatePatterns();
// }
//
// private void generatePatterns() {
// patterns.add(first + " " + last);
// patterns.add(last + ", " + first);
// patterns.add(first.charAt(0) + ". " + last);
// patterns.add(last + ", " + first.charAt(0) + ".");
// if (mid != null) {
// if (mid.length() > 1) {
// patterns.add(first + " " + mid + " " + last);
// patterns.add(last + ", " + first + " " + mid);
// }
// patterns.add(first + " " + mid.charAt(0) + ". " + last);
// patterns.add(last + ", " + first + " " + mid.charAt(0) + ".");
// }
// }
//
// @Override
// public String toString() {
// if (mid != null)
// return first + " " + mid + " " + last;
// return first + " " + last;
// }
//
// @Override
// public boolean match(String predictedEntity) {
// for (String pattern : patterns)
// if (pattern.equals(predictedEntity)) return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String pattern : patterns)
// if (predictedEntities.contains(pattern)) return true;
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityPersonName;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo; | return new Dataset(newTrain, newTest);
}
/**
* @return a new Dataset with the specified train/test ratio.
*/
public Dataset getNewSplitDataset(double trainRatio) {
List<Example> allExamples = new ArrayList<>(trainExamples);
allExamples.addAll(testExamples);
Collections.shuffle(allExamples, new Random(42));
int trainEndIndex = (int) (allExamples.size() * trainRatio);
List<Example> newTrain = allExamples.subList(0, trainEndIndex);
List<Example> newTest = allExamples.subList(trainEndIndex, allExamples.size());
return new Dataset(newTrain, newTest);
}
// ============================================================
// Caching rewards
// ============================================================
public void cacheRewards() {
List<Example> uncached = new ArrayList<>();
for (Example ex : trainExamples)
if (!ex.expectedAnswer.frozenReward) uncached.add(ex);
for (Example ex : testExamples)
if (!ex.expectedAnswer.frozenReward) uncached.add(ex);
if (uncached.isEmpty()) return;
LogInfo.begin_track("Cache rewards ...");
for (Example ex : uncached) {
LogInfo.begin_track("Computing rewards for example %s ...", ex); | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityPersonName.java
// public class TargetEntityPersonName implements TargetEntity {
//
// public final String first;
// public final String mid;
// public final String last;
// final List<String> patterns = new ArrayList<>();
//
// public TargetEntityPersonName(String first, String last) {
// this.first = first;
// this.mid = null;
// this.last = last;
// generatePatterns();
// }
//
// public TargetEntityPersonName(String first, String mid, String last) {
// this.first = first;
// if (mid.length() == 2 && mid.charAt(1) == '.')
// this.mid = mid.substring(0, 1);
// else
// this.mid = mid;
// this.last = last;
// generatePatterns();
// }
//
// private void generatePatterns() {
// patterns.add(first + " " + last);
// patterns.add(last + ", " + first);
// patterns.add(first.charAt(0) + ". " + last);
// patterns.add(last + ", " + first.charAt(0) + ".");
// if (mid != null) {
// if (mid.length() > 1) {
// patterns.add(first + " " + mid + " " + last);
// patterns.add(last + ", " + first + " " + mid);
// }
// patterns.add(first + " " + mid.charAt(0) + ". " + last);
// patterns.add(last + ", " + first + " " + mid.charAt(0) + ".");
// }
// }
//
// @Override
// public String toString() {
// if (mid != null)
// return first + " " + mid + " " + last;
// return first + " " + last;
// }
//
// @Override
// public boolean match(String predictedEntity) {
// for (String pattern : patterns)
// if (pattern.equals(predictedEntity)) return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String pattern : patterns)
// if (predictedEntities.contains(pattern)) return true;
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/Dataset.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityPersonName;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo;
return new Dataset(newTrain, newTest);
}
/**
* @return a new Dataset with the specified train/test ratio.
*/
public Dataset getNewSplitDataset(double trainRatio) {
List<Example> allExamples = new ArrayList<>(trainExamples);
allExamples.addAll(testExamples);
Collections.shuffle(allExamples, new Random(42));
int trainEndIndex = (int) (allExamples.size() * trainRatio);
List<Example> newTrain = allExamples.subList(0, trainEndIndex);
List<Example> newTest = allExamples.subList(trainEndIndex, allExamples.size());
return new Dataset(newTrain, newTest);
}
// ============================================================
// Caching rewards
// ============================================================
public void cacheRewards() {
List<Example> uncached = new ArrayList<>();
for (Example ex : trainExamples)
if (!ex.expectedAnswer.frozenReward) uncached.add(ex);
for (Example ex : testExamples)
if (!ex.expectedAnswer.frozenReward) uncached.add(ex);
if (uncached.isEmpty()) return;
LogInfo.begin_track("Cache rewards ...");
for (Example ex : uncached) {
LogInfo.begin_track("Computing rewards for example %s ...", ex); | for (Candidate candidate : ex.candidates) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/Dataset.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityPersonName.java
// public class TargetEntityPersonName implements TargetEntity {
//
// public final String first;
// public final String mid;
// public final String last;
// final List<String> patterns = new ArrayList<>();
//
// public TargetEntityPersonName(String first, String last) {
// this.first = first;
// this.mid = null;
// this.last = last;
// generatePatterns();
// }
//
// public TargetEntityPersonName(String first, String mid, String last) {
// this.first = first;
// if (mid.length() == 2 && mid.charAt(1) == '.')
// this.mid = mid.substring(0, 1);
// else
// this.mid = mid;
// this.last = last;
// generatePatterns();
// }
//
// private void generatePatterns() {
// patterns.add(first + " " + last);
// patterns.add(last + ", " + first);
// patterns.add(first.charAt(0) + ". " + last);
// patterns.add(last + ", " + first.charAt(0) + ".");
// if (mid != null) {
// if (mid.length() > 1) {
// patterns.add(first + " " + mid + " " + last);
// patterns.add(last + ", " + first + " " + mid);
// }
// patterns.add(first + " " + mid.charAt(0) + ". " + last);
// patterns.add(last + ", " + first + " " + mid.charAt(0) + ".");
// }
// }
//
// @Override
// public String toString() {
// if (mid != null)
// return first + " " + mid + " " + last;
// return first + " " + last;
// }
//
// @Override
// public boolean match(String predictedEntity) {
// for (String pattern : patterns)
// if (pattern.equals(predictedEntity)) return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String pattern : patterns)
// if (predictedEntities.contains(pattern)) return true;
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityPersonName;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo; | // ============================================================
// Shorthands for creating datasets.
// ============================================================
public Example E(String phrase, ExpectedAnswer expectedAnswer) {
return E(phrase, expectedAnswer, true);
}
public Example E(String phrase, ExpectedAnswer expectedAnswer, boolean isTrain) {
Example ex = new Example(phrase, expectedAnswer);
if (isTrain)
addTrainExample(ex);
else
addTestExample(ex);
return ex;
}
public ExpectedAnswer L(String... items) {
return L(false, items);
}
public ExpectedAnswer L(boolean exact, String... items) {
return new ExpectedAnswerInjectiveMatch(items);
}
public ExpectedAnswer LN(String... items) {
return LN(false, items);
}
public ExpectedAnswer LN(boolean exact, String... items) { | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityPersonName.java
// public class TargetEntityPersonName implements TargetEntity {
//
// public final String first;
// public final String mid;
// public final String last;
// final List<String> patterns = new ArrayList<>();
//
// public TargetEntityPersonName(String first, String last) {
// this.first = first;
// this.mid = null;
// this.last = last;
// generatePatterns();
// }
//
// public TargetEntityPersonName(String first, String mid, String last) {
// this.first = first;
// if (mid.length() == 2 && mid.charAt(1) == '.')
// this.mid = mid.substring(0, 1);
// else
// this.mid = mid;
// this.last = last;
// generatePatterns();
// }
//
// private void generatePatterns() {
// patterns.add(first + " " + last);
// patterns.add(last + ", " + first);
// patterns.add(first.charAt(0) + ". " + last);
// patterns.add(last + ", " + first.charAt(0) + ".");
// if (mid != null) {
// if (mid.length() > 1) {
// patterns.add(first + " " + mid + " " + last);
// patterns.add(last + ", " + first + " " + mid);
// }
// patterns.add(first + " " + mid.charAt(0) + ". " + last);
// patterns.add(last + ", " + first + " " + mid.charAt(0) + ".");
// }
// }
//
// @Override
// public String toString() {
// if (mid != null)
// return first + " " + mid + " " + last;
// return first + " " + last;
// }
//
// @Override
// public boolean match(String predictedEntity) {
// for (String pattern : patterns)
// if (pattern.equals(predictedEntity)) return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String pattern : patterns)
// if (predictedEntities.contains(pattern)) return true;
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/Dataset.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityPersonName;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo;
// ============================================================
// Shorthands for creating datasets.
// ============================================================
public Example E(String phrase, ExpectedAnswer expectedAnswer) {
return E(phrase, expectedAnswer, true);
}
public Example E(String phrase, ExpectedAnswer expectedAnswer, boolean isTrain) {
Example ex = new Example(phrase, expectedAnswer);
if (isTrain)
addTrainExample(ex);
else
addTestExample(ex);
return ex;
}
public ExpectedAnswer L(String... items) {
return L(false, items);
}
public ExpectedAnswer L(boolean exact, String... items) {
return new ExpectedAnswerInjectiveMatch(items);
}
public ExpectedAnswer LN(String... items) {
return LN(false, items);
}
public ExpectedAnswer LN(boolean exact, String... items) { | TargetEntity[] targetEntities = new TargetEntity[items.length]; |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/Dataset.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityPersonName.java
// public class TargetEntityPersonName implements TargetEntity {
//
// public final String first;
// public final String mid;
// public final String last;
// final List<String> patterns = new ArrayList<>();
//
// public TargetEntityPersonName(String first, String last) {
// this.first = first;
// this.mid = null;
// this.last = last;
// generatePatterns();
// }
//
// public TargetEntityPersonName(String first, String mid, String last) {
// this.first = first;
// if (mid.length() == 2 && mid.charAt(1) == '.')
// this.mid = mid.substring(0, 1);
// else
// this.mid = mid;
// this.last = last;
// generatePatterns();
// }
//
// private void generatePatterns() {
// patterns.add(first + " " + last);
// patterns.add(last + ", " + first);
// patterns.add(first.charAt(0) + ". " + last);
// patterns.add(last + ", " + first.charAt(0) + ".");
// if (mid != null) {
// if (mid.length() > 1) {
// patterns.add(first + " " + mid + " " + last);
// patterns.add(last + ", " + first + " " + mid);
// }
// patterns.add(first + " " + mid.charAt(0) + ". " + last);
// patterns.add(last + ", " + first + " " + mid.charAt(0) + ".");
// }
// }
//
// @Override
// public String toString() {
// if (mid != null)
// return first + " " + mid + " " + last;
// return first + " " + last;
// }
//
// @Override
// public boolean match(String predictedEntity) {
// for (String pattern : patterns)
// if (pattern.equals(predictedEntity)) return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String pattern : patterns)
// if (predictedEntities.contains(pattern)) return true;
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityPersonName;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo; | return E(phrase, expectedAnswer, true);
}
public Example E(String phrase, ExpectedAnswer expectedAnswer, boolean isTrain) {
Example ex = new Example(phrase, expectedAnswer);
if (isTrain)
addTrainExample(ex);
else
addTestExample(ex);
return ex;
}
public ExpectedAnswer L(String... items) {
return L(false, items);
}
public ExpectedAnswer L(boolean exact, String... items) {
return new ExpectedAnswerInjectiveMatch(items);
}
public ExpectedAnswer LN(String... items) {
return LN(false, items);
}
public ExpectedAnswer LN(boolean exact, String... items) {
TargetEntity[] targetEntities = new TargetEntity[items.length];
for (int i = 0; i < items.length; i++) targetEntities[i] = N(items[i]);
return new ExpectedAnswerInjectiveMatch(items);
}
| // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityPersonName.java
// public class TargetEntityPersonName implements TargetEntity {
//
// public final String first;
// public final String mid;
// public final String last;
// final List<String> patterns = new ArrayList<>();
//
// public TargetEntityPersonName(String first, String last) {
// this.first = first;
// this.mid = null;
// this.last = last;
// generatePatterns();
// }
//
// public TargetEntityPersonName(String first, String mid, String last) {
// this.first = first;
// if (mid.length() == 2 && mid.charAt(1) == '.')
// this.mid = mid.substring(0, 1);
// else
// this.mid = mid;
// this.last = last;
// generatePatterns();
// }
//
// private void generatePatterns() {
// patterns.add(first + " " + last);
// patterns.add(last + ", " + first);
// patterns.add(first.charAt(0) + ". " + last);
// patterns.add(last + ", " + first.charAt(0) + ".");
// if (mid != null) {
// if (mid.length() > 1) {
// patterns.add(first + " " + mid + " " + last);
// patterns.add(last + ", " + first + " " + mid);
// }
// patterns.add(first + " " + mid.charAt(0) + ". " + last);
// patterns.add(last + ", " + first + " " + mid.charAt(0) + ".");
// }
// }
//
// @Override
// public String toString() {
// if (mid != null)
// return first + " " + mid + " " + last;
// return first + " " + last;
// }
//
// @Override
// public boolean match(String predictedEntity) {
// for (String pattern : patterns)
// if (pattern.equals(predictedEntity)) return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String pattern : patterns)
// if (predictedEntities.contains(pattern)) return true;
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/Dataset.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityPersonName;
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.LogInfo;
return E(phrase, expectedAnswer, true);
}
public Example E(String phrase, ExpectedAnswer expectedAnswer, boolean isTrain) {
Example ex = new Example(phrase, expectedAnswer);
if (isTrain)
addTrainExample(ex);
else
addTestExample(ex);
return ex;
}
public ExpectedAnswer L(String... items) {
return L(false, items);
}
public ExpectedAnswer L(boolean exact, String... items) {
return new ExpectedAnswerInjectiveMatch(items);
}
public ExpectedAnswer LN(String... items) {
return LN(false, items);
}
public ExpectedAnswer LN(boolean exact, String... items) {
TargetEntity[] targetEntities = new TargetEntity[items.length];
for (int i = 0; i < items.length; i++) targetEntities[i] = N(items[i]);
return new ExpectedAnswerInjectiveMatch(items);
}
| public TargetEntityPersonName N(String full) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/model/AdvancedWordVectorParamsFullRank.java | // Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
| import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.Fmt;
import fig.basic.LogInfo; | package edu.stanford.nlp.semparse.open.model;
public class AdvancedWordVectorParamsFullRank extends AdvancedWordVectorParams {
double[][] weights;
// Shorthands for word vector dimension
protected final int dim;
public AdvancedWordVectorParamsFullRank() {
dim = getDim();
weights = new double[dim][dim];
if (Params.opts.initWeightsRandomly) {
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
weights[i][j] = 2 * Params.opts.initRandom.nextDouble() - 1;
}
}
}
initGradientStats();
}
// ============================================================
// Get score
// ============================================================
@Override | // Path: src/edu/stanford/nlp/semparse/open/model/candidate/Candidate.java
// public class Candidate {
// public final Example ex;
// public final CandidateGroup group;
// public final TreePattern pattern;
// public final List<String> predictedEntities;
// public FeatureVector features;
//
// public Candidate(CandidateGroup group, TreePattern pattern) {
// this.pattern = pattern;
// this.group = group;
// group.candidates.add(this);
// // Perform shallow copy
// this.ex = group.ex;
// this.predictedEntities = group.predictedEntities;
// }
//
// public int numEntities() {
// return group.numEntities();
// }
//
// public double getReward() {
// return group.ex.expectedAnswer.reward(this);
// }
//
// public Map<String, Double> getCombinedFeatures() {
// Map<String, Double> map = new HashMap<>();
// features.increment(1, map);
// group.features.increment(1, map);
// return map;
// }
//
// // ============================================================
// // Debug Print
// // ============================================================
//
// public String sampleEntities() {
// return group.sampleEntities();
// }
//
// public String allEntities() {
// return group.allEntities();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/model/AdvancedWordVectorParamsFullRank.java
import edu.stanford.nlp.semparse.open.model.candidate.Candidate;
import fig.basic.Fmt;
import fig.basic.LogInfo;
package edu.stanford.nlp.semparse.open.model;
public class AdvancedWordVectorParamsFullRank extends AdvancedWordVectorParams {
double[][] weights;
// Shorthands for word vector dimension
protected final int dim;
public AdvancedWordVectorParamsFullRank() {
dim = getDim();
weights = new double[dim][dim];
if (Params.opts.initWeightsRandomly) {
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
weights[i][j] = 2 * Params.opts.initRandom.nextDouble() - 1;
}
}
}
initGradientStats();
}
// ============================================================
// Get score
// ============================================================
@Override | public double getScore(Candidate candidate) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/CriteriaGeneralWeb.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityNearMatch.java
// public class TargetEntityNearMatch implements TargetEntity {
// public static class Options {
// @Option public int nearMatchMaxEditDistance = 2;
// @Option(gloss = "level of target entity string normalization "
// + "(0 = none / 1 = whitespace / 2 = simple / 3 = aggressive)")
// public int targetNormalizeEntities = 2;
// }
// public static Options opts = new Options();
//
// public final String expected, normalizedExpected;
//
// public TargetEntityNearMatch(String expected) {
// this.expected = expected;
// this.normalizedExpected = LingUtils.normalize(expected, opts.targetNormalizeEntities);
// }
//
// @Override public String toString() {
// StringBuilder sb = new StringBuilder(expected);
// if (!expected.equals(normalizedExpected))
// sb.append(" || ").append(normalizedExpected);
// return sb.toString();
// }
//
// @Override
// public boolean match(String predictedEntity) {
// // Easy cases
// if (expected.equals(predictedEntity))
// return true;
// // Edit distance
// if (EditDistance.withinEditDistance(normalizedExpected, predictedEntity, opts.nearMatchMaxEditDistance))
// return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String predictedEntity : predictedEntities) {
// if (match(predictedEntity)) return true;
// }
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/library/JSONDataset.java
// @JsonIgnoreProperties(ignoreUnknown=true)
// public static class JSONDatasetDatum {
// public String hashcode;
// public String query;
// public String url;
// public List<String> entities;
// public List<JSONDatasetRawAnswers> rawanswers;
// public JSONDatasetCriteria criteria;
//
// @Override
// public String toString() {
// return new StringBuilder()
// .append("[").append(query)
// .append(hashcode == null ? "" : " " + hashcode).append("]")
// .toString();
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityNearMatch;
import edu.stanford.nlp.semparse.open.dataset.library.JSONDataset.JSONDatasetDatum; | package edu.stanford.nlp.semparse.open.dataset;
/**
* Must match first, second, and last entities
*/
public class CriteriaGeneralWeb implements Criteria {
public final JSONDatasetDatum datum; | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityNearMatch.java
// public class TargetEntityNearMatch implements TargetEntity {
// public static class Options {
// @Option public int nearMatchMaxEditDistance = 2;
// @Option(gloss = "level of target entity string normalization "
// + "(0 = none / 1 = whitespace / 2 = simple / 3 = aggressive)")
// public int targetNormalizeEntities = 2;
// }
// public static Options opts = new Options();
//
// public final String expected, normalizedExpected;
//
// public TargetEntityNearMatch(String expected) {
// this.expected = expected;
// this.normalizedExpected = LingUtils.normalize(expected, opts.targetNormalizeEntities);
// }
//
// @Override public String toString() {
// StringBuilder sb = new StringBuilder(expected);
// if (!expected.equals(normalizedExpected))
// sb.append(" || ").append(normalizedExpected);
// return sb.toString();
// }
//
// @Override
// public boolean match(String predictedEntity) {
// // Easy cases
// if (expected.equals(predictedEntity))
// return true;
// // Edit distance
// if (EditDistance.withinEditDistance(normalizedExpected, predictedEntity, opts.nearMatchMaxEditDistance))
// return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String predictedEntity : predictedEntities) {
// if (match(predictedEntity)) return true;
// }
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/library/JSONDataset.java
// @JsonIgnoreProperties(ignoreUnknown=true)
// public static class JSONDatasetDatum {
// public String hashcode;
// public String query;
// public String url;
// public List<String> entities;
// public List<JSONDatasetRawAnswers> rawanswers;
// public JSONDatasetCriteria criteria;
//
// @Override
// public String toString() {
// return new StringBuilder()
// .append("[").append(query)
// .append(hashcode == null ? "" : " " + hashcode).append("]")
// .toString();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/CriteriaGeneralWeb.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityNearMatch;
import edu.stanford.nlp.semparse.open.dataset.library.JSONDataset.JSONDatasetDatum;
package edu.stanford.nlp.semparse.open.dataset;
/**
* Must match first, second, and last entities
*/
public class CriteriaGeneralWeb implements Criteria {
public final JSONDatasetDatum datum; | public final TargetEntity first, second, last; |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/CriteriaGeneralWeb.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityNearMatch.java
// public class TargetEntityNearMatch implements TargetEntity {
// public static class Options {
// @Option public int nearMatchMaxEditDistance = 2;
// @Option(gloss = "level of target entity string normalization "
// + "(0 = none / 1 = whitespace / 2 = simple / 3 = aggressive)")
// public int targetNormalizeEntities = 2;
// }
// public static Options opts = new Options();
//
// public final String expected, normalizedExpected;
//
// public TargetEntityNearMatch(String expected) {
// this.expected = expected;
// this.normalizedExpected = LingUtils.normalize(expected, opts.targetNormalizeEntities);
// }
//
// @Override public String toString() {
// StringBuilder sb = new StringBuilder(expected);
// if (!expected.equals(normalizedExpected))
// sb.append(" || ").append(normalizedExpected);
// return sb.toString();
// }
//
// @Override
// public boolean match(String predictedEntity) {
// // Easy cases
// if (expected.equals(predictedEntity))
// return true;
// // Edit distance
// if (EditDistance.withinEditDistance(normalizedExpected, predictedEntity, opts.nearMatchMaxEditDistance))
// return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String predictedEntity : predictedEntities) {
// if (match(predictedEntity)) return true;
// }
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/library/JSONDataset.java
// @JsonIgnoreProperties(ignoreUnknown=true)
// public static class JSONDatasetDatum {
// public String hashcode;
// public String query;
// public String url;
// public List<String> entities;
// public List<JSONDatasetRawAnswers> rawanswers;
// public JSONDatasetCriteria criteria;
//
// @Override
// public String toString() {
// return new StringBuilder()
// .append("[").append(query)
// .append(hashcode == null ? "" : " " + hashcode).append("]")
// .toString();
// }
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityNearMatch;
import edu.stanford.nlp.semparse.open.dataset.library.JSONDataset.JSONDatasetDatum; | package edu.stanford.nlp.semparse.open.dataset;
/**
* Must match first, second, and last entities
*/
public class CriteriaGeneralWeb implements Criteria {
public final JSONDatasetDatum datum;
public final TargetEntity first, second, last;
public CriteriaGeneralWeb(JSONDatasetDatum datum) {
this.datum = datum; | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntityNearMatch.java
// public class TargetEntityNearMatch implements TargetEntity {
// public static class Options {
// @Option public int nearMatchMaxEditDistance = 2;
// @Option(gloss = "level of target entity string normalization "
// + "(0 = none / 1 = whitespace / 2 = simple / 3 = aggressive)")
// public int targetNormalizeEntities = 2;
// }
// public static Options opts = new Options();
//
// public final String expected, normalizedExpected;
//
// public TargetEntityNearMatch(String expected) {
// this.expected = expected;
// this.normalizedExpected = LingUtils.normalize(expected, opts.targetNormalizeEntities);
// }
//
// @Override public String toString() {
// StringBuilder sb = new StringBuilder(expected);
// if (!expected.equals(normalizedExpected))
// sb.append(" || ").append(normalizedExpected);
// return sb.toString();
// }
//
// @Override
// public boolean match(String predictedEntity) {
// // Easy cases
// if (expected.equals(predictedEntity))
// return true;
// // Edit distance
// if (EditDistance.withinEditDistance(normalizedExpected, predictedEntity, opts.nearMatchMaxEditDistance))
// return true;
// return false;
// }
//
// @Override
// public boolean matchAny(Collection<String> predictedEntities) {
// for (String predictedEntity : predictedEntities) {
// if (match(predictedEntity)) return true;
// }
// return false;
// }
//
// }
//
// Path: src/edu/stanford/nlp/semparse/open/dataset/library/JSONDataset.java
// @JsonIgnoreProperties(ignoreUnknown=true)
// public static class JSONDatasetDatum {
// public String hashcode;
// public String query;
// public String url;
// public List<String> entities;
// public List<JSONDatasetRawAnswers> rawanswers;
// public JSONDatasetCriteria criteria;
//
// @Override
// public String toString() {
// return new StringBuilder()
// .append("[").append(query)
// .append(hashcode == null ? "" : " " + hashcode).append("]")
// .toString();
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/CriteriaGeneralWeb.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntityNearMatch;
import edu.stanford.nlp.semparse.open.dataset.library.JSONDataset.JSONDatasetDatum;
package edu.stanford.nlp.semparse.open.dataset;
/**
* Must match first, second, and last entities
*/
public class CriteriaGeneralWeb implements Criteria {
public final JSONDatasetDatum datum;
public final TargetEntity first, second, last;
public CriteriaGeneralWeb(JSONDatasetDatum datum) {
this.datum = datum; | this.first = new TargetEntityNearMatch(datum.criteria.first); |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
| import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity; | package edu.stanford.nlp.semparse.open.util;
public class BipartiteMatcher {
private final int SOURCE = 1;
private final int SINK = -1;
private final Map<Object, Integer> fromMap;
private final Map<Object, Integer> toMap;
private final Map<Integer, List<Integer>> edges;
public BipartiteMatcher() {
this.fromMap = new HashMap<>();
this.toMap = new HashMap<>();
this.edges = new HashMap<>();
}
| // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
// Path: src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java
import java.util.*;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
package edu.stanford.nlp.semparse.open.util;
public class BipartiteMatcher {
private final int SOURCE = 1;
private final int SINK = -1;
private final Map<Object, Integer> fromMap;
private final Map<Object, Integer> toMap;
private final Map<Integer, List<Integer>> edges;
public BipartiteMatcher() {
this.fromMap = new HashMap<>();
this.toMap = new HashMap<>();
this.edges = new HashMap<>();
}
| public BipartiteMatcher(List<TargetEntity> targetEntities, List<String> predictedEntities) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/ExpectedAnswerCriteriaMatch.java | // Path: src/edu/stanford/nlp/semparse/open/core/eval/CandidateStatistics.java
// public class CandidateStatistics {
// public final Candidate candidate;
// public final int rank, uniqueRank; // rank and uniqueRank are 1-indexed
// public final double score;
//
// public CandidateStatistics(Candidate candidate, int rank, int uniqueRank, double score) {
// this.candidate = candidate;
// this.rank = rank;
// this.uniqueRank = uniqueRank;
// this.score = score;
// }
//
// /**
// * Convert Pair<Candidate, Double> to CandidateStatistics
// */
// public static List<CandidateStatistics> getRankedCandidateStats(List<Pair<Candidate, Double>> rankedCandidates) {
// List<CandidateStatistics> answer = new ArrayList<>();
// Set<List<String>> foundPredictedEntities = new HashSet<>();
// for (int rank = 0; rank < rankedCandidates.size(); rank++) {
// Pair<Candidate, Double> entry = rankedCandidates.get(rank);
// Candidate candidate = entry.getFirst();
// foundPredictedEntities.add(candidate.predictedEntities);
// answer.add(new CandidateStatistics(candidate, rank + 1, foundPredictedEntities.size(), entry.getSecond()));
// }
// return answer;
// }
// }
| import java.util.List;
import edu.stanford.nlp.semparse.open.core.eval.CandidateStatistics;
import fig.basic.Option; | this.criteria = criteria;
}
@Override
public IRScore getIRScore(List<String> predictedEntities) {
return criteria.getIRScore(predictedEntities);
}
@Override
public double reward(List<String> predictedEntities) {
if (!opts.generous) {
return countCorrectEntities(predictedEntities) == criteria.numCriteria() ? 1 : 0;
} else {
// Generous reward
double f1 = criteria.getIRScore(predictedEntities).f1;
return f1 > ExpectedAnswerInjectiveMatch.opts.irThreshold ? f1 : 0;
}
}
@Override
public int computeCountCorrectEntities(List<String> predictedEntities) {
return criteria.countMatchedCriteria(predictedEntities);
}
@Override
public boolean isLikelyCorrect(List<String> predictedEntities) {
return countCorrectEntities(predictedEntities) == criteria.numCriteria();
}
@Override | // Path: src/edu/stanford/nlp/semparse/open/core/eval/CandidateStatistics.java
// public class CandidateStatistics {
// public final Candidate candidate;
// public final int rank, uniqueRank; // rank and uniqueRank are 1-indexed
// public final double score;
//
// public CandidateStatistics(Candidate candidate, int rank, int uniqueRank, double score) {
// this.candidate = candidate;
// this.rank = rank;
// this.uniqueRank = uniqueRank;
// this.score = score;
// }
//
// /**
// * Convert Pair<Candidate, Double> to CandidateStatistics
// */
// public static List<CandidateStatistics> getRankedCandidateStats(List<Pair<Candidate, Double>> rankedCandidates) {
// List<CandidateStatistics> answer = new ArrayList<>();
// Set<List<String>> foundPredictedEntities = new HashSet<>();
// for (int rank = 0; rank < rankedCandidates.size(); rank++) {
// Pair<Candidate, Double> entry = rankedCandidates.get(rank);
// Candidate candidate = entry.getFirst();
// foundPredictedEntities.add(candidate.predictedEntities);
// answer.add(new CandidateStatistics(candidate, rank + 1, foundPredictedEntities.size(), entry.getSecond()));
// }
// return answer;
// }
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/ExpectedAnswerCriteriaMatch.java
import java.util.List;
import edu.stanford.nlp.semparse.open.core.eval.CandidateStatistics;
import fig.basic.Option;
this.criteria = criteria;
}
@Override
public IRScore getIRScore(List<String> predictedEntities) {
return criteria.getIRScore(predictedEntities);
}
@Override
public double reward(List<String> predictedEntities) {
if (!opts.generous) {
return countCorrectEntities(predictedEntities) == criteria.numCriteria() ? 1 : 0;
} else {
// Generous reward
double f1 = criteria.getIRScore(predictedEntities).f1;
return f1 > ExpectedAnswerInjectiveMatch.opts.irThreshold ? f1 : 0;
}
}
@Override
public int computeCountCorrectEntities(List<String> predictedEntities) {
return criteria.countMatchedCriteria(predictedEntities);
}
@Override
public boolean isLikelyCorrect(List<String> predictedEntities) {
return countCorrectEntities(predictedEntities) == criteria.numCriteria();
}
@Override | public CandidateStatistics findBestCandidate(List<CandidateStatistics> rankedCandidateStats) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/IRScore.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java
// public class BipartiteMatcher {
//
// private final int SOURCE = 1;
// private final int SINK = -1;
//
// private final Map<Object, Integer> fromMap;
// private final Map<Object, Integer> toMap;
// private final Map<Integer, List<Integer>> edges;
//
// public BipartiteMatcher() {
// this.fromMap = new HashMap<>();
// this.toMap = new HashMap<>();
// this.edges = new HashMap<>();
// }
//
// public BipartiteMatcher(List<TargetEntity> targetEntities, List<String> predictedEntities) {
// this();
// for (int i = 0; i < targetEntities.size(); i++) {
// TargetEntity targetEntity = targetEntities.get(i);
// for (int j = 0; j < predictedEntities.size(); j++) {
// if (targetEntity.match(predictedEntities.get(j))) {
// this.addEdge(i, j);
// }
// }
// }
// }
//
// public void addEdge(Object fromObj, Object toObj) {
// Integer from = fromMap.get(fromObj), to = toMap.get(toObj);
// if (from == null) {
// from = 2 + fromMap.size();
// fromMap.put(fromObj, from);
// if (!edges.containsKey(SOURCE)) edges.put(SOURCE, new ArrayList<>());
// edges.get(SOURCE).add(from);
// }
// if (to == null) {
// to = - 2 - toMap.size();
// toMap.put(toObj, to);
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(SINK);
// }
// if (!edges.containsKey(from)) edges.put(from, new ArrayList<>());
// edges.get(from).add(to);
// }
//
// private List<Integer> foundPath;
// private Set<Integer> foundNodes;
//
// public int findMaximumMatch() {
// int count = 0;
// this.foundPath = new ArrayList<>();
// this.foundNodes = new HashSet<>();
// while (findPath(SOURCE)) {
// count++;
// for (int i = 0; i < foundPath.size() - 1; i++) {
// int from = foundPath.get(i), to = foundPath.get(i+1);
// edges.get(from).remove(Integer.valueOf(to));
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(from);
// }
// foundPath.clear();
// foundNodes.clear();
// }
// return count;
// }
//
// private boolean findPath(int node) {
// // DFS
// foundNodes.add(node);
// foundPath.add(node);
// if (node == SINK) return true;
// for (int dest : edges.get(node)) {
// if (!foundNodes.contains(dest)) {
// if (findPath(dest)) return true;
// }
// }
// foundPath.remove(foundPath.size() - 1);
// return false;
// }
//
// public static void main(String[] args) {
// // Test Method
// BipartiteMatcher bm = new BipartiteMatcher();
// bm.addEdge("A", 1); bm.addEdge("A", 2); bm.addEdge("A", 4);
// bm.addEdge("B", 1); bm.addEdge("C", 2); bm.addEdge("C", 1);
// bm.addEdge("D", 4); bm.addEdge("D", 5); bm.addEdge("E", 3);
// System.out.println(bm.findMaximumMatch());
// }
//
// }
| import java.util.List;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.util.BipartiteMatcher; | package edu.stanford.nlp.semparse.open.dataset;
public class IRScore {
public final int numCorrect, numPredicted, numGold;
public final double precision, recall, f1;
public IRScore(int numCorrect, int numPredicted, int numGold) {
this.numCorrect = numCorrect;
this.numPredicted = numPredicted;
this.numGold = numGold;
precision = (numPredicted == 0) ? 0 : numCorrect * 1.0 / numPredicted;
recall = numCorrect * 1.0 / numGold;
f1 = (numCorrect == 0) ? 0 : (2 * precision * recall) / (precision + recall);
}
| // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java
// public class BipartiteMatcher {
//
// private final int SOURCE = 1;
// private final int SINK = -1;
//
// private final Map<Object, Integer> fromMap;
// private final Map<Object, Integer> toMap;
// private final Map<Integer, List<Integer>> edges;
//
// public BipartiteMatcher() {
// this.fromMap = new HashMap<>();
// this.toMap = new HashMap<>();
// this.edges = new HashMap<>();
// }
//
// public BipartiteMatcher(List<TargetEntity> targetEntities, List<String> predictedEntities) {
// this();
// for (int i = 0; i < targetEntities.size(); i++) {
// TargetEntity targetEntity = targetEntities.get(i);
// for (int j = 0; j < predictedEntities.size(); j++) {
// if (targetEntity.match(predictedEntities.get(j))) {
// this.addEdge(i, j);
// }
// }
// }
// }
//
// public void addEdge(Object fromObj, Object toObj) {
// Integer from = fromMap.get(fromObj), to = toMap.get(toObj);
// if (from == null) {
// from = 2 + fromMap.size();
// fromMap.put(fromObj, from);
// if (!edges.containsKey(SOURCE)) edges.put(SOURCE, new ArrayList<>());
// edges.get(SOURCE).add(from);
// }
// if (to == null) {
// to = - 2 - toMap.size();
// toMap.put(toObj, to);
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(SINK);
// }
// if (!edges.containsKey(from)) edges.put(from, new ArrayList<>());
// edges.get(from).add(to);
// }
//
// private List<Integer> foundPath;
// private Set<Integer> foundNodes;
//
// public int findMaximumMatch() {
// int count = 0;
// this.foundPath = new ArrayList<>();
// this.foundNodes = new HashSet<>();
// while (findPath(SOURCE)) {
// count++;
// for (int i = 0; i < foundPath.size() - 1; i++) {
// int from = foundPath.get(i), to = foundPath.get(i+1);
// edges.get(from).remove(Integer.valueOf(to));
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(from);
// }
// foundPath.clear();
// foundNodes.clear();
// }
// return count;
// }
//
// private boolean findPath(int node) {
// // DFS
// foundNodes.add(node);
// foundPath.add(node);
// if (node == SINK) return true;
// for (int dest : edges.get(node)) {
// if (!foundNodes.contains(dest)) {
// if (findPath(dest)) return true;
// }
// }
// foundPath.remove(foundPath.size() - 1);
// return false;
// }
//
// public static void main(String[] args) {
// // Test Method
// BipartiteMatcher bm = new BipartiteMatcher();
// bm.addEdge("A", 1); bm.addEdge("A", 2); bm.addEdge("A", 4);
// bm.addEdge("B", 1); bm.addEdge("C", 2); bm.addEdge("C", 1);
// bm.addEdge("D", 4); bm.addEdge("D", 5); bm.addEdge("E", 3);
// System.out.println(bm.findMaximumMatch());
// }
//
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/IRScore.java
import java.util.List;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.util.BipartiteMatcher;
package edu.stanford.nlp.semparse.open.dataset;
public class IRScore {
public final int numCorrect, numPredicted, numGold;
public final double precision, recall, f1;
public IRScore(int numCorrect, int numPredicted, int numGold) {
this.numCorrect = numCorrect;
this.numPredicted = numPredicted;
this.numGold = numGold;
precision = (numPredicted == 0) ? 0 : numCorrect * 1.0 / numPredicted;
recall = numCorrect * 1.0 / numGold;
f1 = (numCorrect == 0) ? 0 : (2 * precision * recall) / (precision + recall);
}
| public IRScore(List<TargetEntity> expected, List<String> predicted) { |
ppasupat/web-entity-extractor-ACL2014 | src/edu/stanford/nlp/semparse/open/dataset/IRScore.java | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java
// public class BipartiteMatcher {
//
// private final int SOURCE = 1;
// private final int SINK = -1;
//
// private final Map<Object, Integer> fromMap;
// private final Map<Object, Integer> toMap;
// private final Map<Integer, List<Integer>> edges;
//
// public BipartiteMatcher() {
// this.fromMap = new HashMap<>();
// this.toMap = new HashMap<>();
// this.edges = new HashMap<>();
// }
//
// public BipartiteMatcher(List<TargetEntity> targetEntities, List<String> predictedEntities) {
// this();
// for (int i = 0; i < targetEntities.size(); i++) {
// TargetEntity targetEntity = targetEntities.get(i);
// for (int j = 0; j < predictedEntities.size(); j++) {
// if (targetEntity.match(predictedEntities.get(j))) {
// this.addEdge(i, j);
// }
// }
// }
// }
//
// public void addEdge(Object fromObj, Object toObj) {
// Integer from = fromMap.get(fromObj), to = toMap.get(toObj);
// if (from == null) {
// from = 2 + fromMap.size();
// fromMap.put(fromObj, from);
// if (!edges.containsKey(SOURCE)) edges.put(SOURCE, new ArrayList<>());
// edges.get(SOURCE).add(from);
// }
// if (to == null) {
// to = - 2 - toMap.size();
// toMap.put(toObj, to);
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(SINK);
// }
// if (!edges.containsKey(from)) edges.put(from, new ArrayList<>());
// edges.get(from).add(to);
// }
//
// private List<Integer> foundPath;
// private Set<Integer> foundNodes;
//
// public int findMaximumMatch() {
// int count = 0;
// this.foundPath = new ArrayList<>();
// this.foundNodes = new HashSet<>();
// while (findPath(SOURCE)) {
// count++;
// for (int i = 0; i < foundPath.size() - 1; i++) {
// int from = foundPath.get(i), to = foundPath.get(i+1);
// edges.get(from).remove(Integer.valueOf(to));
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(from);
// }
// foundPath.clear();
// foundNodes.clear();
// }
// return count;
// }
//
// private boolean findPath(int node) {
// // DFS
// foundNodes.add(node);
// foundPath.add(node);
// if (node == SINK) return true;
// for (int dest : edges.get(node)) {
// if (!foundNodes.contains(dest)) {
// if (findPath(dest)) return true;
// }
// }
// foundPath.remove(foundPath.size() - 1);
// return false;
// }
//
// public static void main(String[] args) {
// // Test Method
// BipartiteMatcher bm = new BipartiteMatcher();
// bm.addEdge("A", 1); bm.addEdge("A", 2); bm.addEdge("A", 4);
// bm.addEdge("B", 1); bm.addEdge("C", 2); bm.addEdge("C", 1);
// bm.addEdge("D", 4); bm.addEdge("D", 5); bm.addEdge("E", 3);
// System.out.println(bm.findMaximumMatch());
// }
//
// }
| import java.util.List;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.util.BipartiteMatcher; | package edu.stanford.nlp.semparse.open.dataset;
public class IRScore {
public final int numCorrect, numPredicted, numGold;
public final double precision, recall, f1;
public IRScore(int numCorrect, int numPredicted, int numGold) {
this.numCorrect = numCorrect;
this.numPredicted = numPredicted;
this.numGold = numGold;
precision = (numPredicted == 0) ? 0 : numCorrect * 1.0 / numPredicted;
recall = numCorrect * 1.0 / numGold;
f1 = (numCorrect == 0) ? 0 : (2 * precision * recall) / (precision + recall);
}
public IRScore(List<TargetEntity> expected, List<String> predicted) { | // Path: src/edu/stanford/nlp/semparse/open/dataset/entity/TargetEntity.java
// public interface TargetEntity {
// public boolean match(String predictedEntity);
// public boolean matchAny(Collection<String> predictedEntities);
// }
//
// Path: src/edu/stanford/nlp/semparse/open/util/BipartiteMatcher.java
// public class BipartiteMatcher {
//
// private final int SOURCE = 1;
// private final int SINK = -1;
//
// private final Map<Object, Integer> fromMap;
// private final Map<Object, Integer> toMap;
// private final Map<Integer, List<Integer>> edges;
//
// public BipartiteMatcher() {
// this.fromMap = new HashMap<>();
// this.toMap = new HashMap<>();
// this.edges = new HashMap<>();
// }
//
// public BipartiteMatcher(List<TargetEntity> targetEntities, List<String> predictedEntities) {
// this();
// for (int i = 0; i < targetEntities.size(); i++) {
// TargetEntity targetEntity = targetEntities.get(i);
// for (int j = 0; j < predictedEntities.size(); j++) {
// if (targetEntity.match(predictedEntities.get(j))) {
// this.addEdge(i, j);
// }
// }
// }
// }
//
// public void addEdge(Object fromObj, Object toObj) {
// Integer from = fromMap.get(fromObj), to = toMap.get(toObj);
// if (from == null) {
// from = 2 + fromMap.size();
// fromMap.put(fromObj, from);
// if (!edges.containsKey(SOURCE)) edges.put(SOURCE, new ArrayList<>());
// edges.get(SOURCE).add(from);
// }
// if (to == null) {
// to = - 2 - toMap.size();
// toMap.put(toObj, to);
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(SINK);
// }
// if (!edges.containsKey(from)) edges.put(from, new ArrayList<>());
// edges.get(from).add(to);
// }
//
// private List<Integer> foundPath;
// private Set<Integer> foundNodes;
//
// public int findMaximumMatch() {
// int count = 0;
// this.foundPath = new ArrayList<>();
// this.foundNodes = new HashSet<>();
// while (findPath(SOURCE)) {
// count++;
// for (int i = 0; i < foundPath.size() - 1; i++) {
// int from = foundPath.get(i), to = foundPath.get(i+1);
// edges.get(from).remove(Integer.valueOf(to));
// if (!edges.containsKey(to)) edges.put(to, new ArrayList<>());
// edges.get(to).add(from);
// }
// foundPath.clear();
// foundNodes.clear();
// }
// return count;
// }
//
// private boolean findPath(int node) {
// // DFS
// foundNodes.add(node);
// foundPath.add(node);
// if (node == SINK) return true;
// for (int dest : edges.get(node)) {
// if (!foundNodes.contains(dest)) {
// if (findPath(dest)) return true;
// }
// }
// foundPath.remove(foundPath.size() - 1);
// return false;
// }
//
// public static void main(String[] args) {
// // Test Method
// BipartiteMatcher bm = new BipartiteMatcher();
// bm.addEdge("A", 1); bm.addEdge("A", 2); bm.addEdge("A", 4);
// bm.addEdge("B", 1); bm.addEdge("C", 2); bm.addEdge("C", 1);
// bm.addEdge("D", 4); bm.addEdge("D", 5); bm.addEdge("E", 3);
// System.out.println(bm.findMaximumMatch());
// }
//
// }
// Path: src/edu/stanford/nlp/semparse/open/dataset/IRScore.java
import java.util.List;
import edu.stanford.nlp.semparse.open.dataset.entity.TargetEntity;
import edu.stanford.nlp.semparse.open.util.BipartiteMatcher;
package edu.stanford.nlp.semparse.open.dataset;
public class IRScore {
public final int numCorrect, numPredicted, numGold;
public final double precision, recall, f1;
public IRScore(int numCorrect, int numPredicted, int numGold) {
this.numCorrect = numCorrect;
this.numPredicted = numPredicted;
this.numGold = numGold;
precision = (numPredicted == 0) ? 0 : numCorrect * 1.0 / numPredicted;
recall = numCorrect * 1.0 / numGold;
f1 = (numCorrect == 0) ? 0 : (2 * precision * recall) / (precision + recall);
}
public IRScore(List<TargetEntity> expected, List<String> predicted) { | this(new BipartiteMatcher(expected, predicted).findMaximumMatch(), |
MindscapeHQ/raygun4java | core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunStripWrappedExceptionFilterTest.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunErrorMessage.java
// public class RaygunErrorMessage {
//
// private transient WeakReference<Throwable> throwable;
// private RaygunErrorMessage innerError;
// private String message;
// private String className;
// private RaygunErrorStackTraceLineMessage[] stackTrace;
//
// public RaygunErrorMessage(Throwable throwable) {
// if (throwable == null) {
// return;
// }
//
// this.throwable = new WeakReference<Throwable>(throwable);
// message = throwable.getClass().getSimpleName();
// String throwableMessage = throwable.getMessage();
// if (throwableMessage != null) {
// message = message.concat(": ").concat(throwableMessage);
// }
// className = throwable.getClass().getCanonicalName();
//
// if (throwable.getCause() != null) {
// innerError = new RaygunErrorMessage(throwable.getCause());
// }
//
// StackTraceElement[] ste = throwable.getStackTrace();
// stackTrace = new RaygunErrorStackTraceLineMessage[ste.length];
//
// for (int i = 0; i < ste.length; i++) {
// stackTrace[i] = new RaygunErrorStackTraceLineMessage(ste[i]);
// }
// }
//
// public RaygunErrorMessage getInnerError() {
// return innerError;
// }
//
// public void setInnerError(RaygunErrorMessage innerError) {
// this.innerError = innerError;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public RaygunErrorStackTraceLineMessage[] getStackTrace() {
// return stackTrace;
// }
//
// public void setStackTrace(RaygunErrorStackTraceLineMessage[] stackTrace) {
// this.stackTrace = stackTrace;
// }
//
// public Throwable getThrowable() {
// if(throwable != null && throwable.get() != null) {
// return throwable.get();
// }
// return null;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunStripWrappedExceptionFilterTest {
@Test
public void shouldStripException () {
RaygunStripWrappedExceptionFilter f = new RaygunStripWrappedExceptionFilter(ClassNotFoundException.class);
| // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunErrorMessage.java
// public class RaygunErrorMessage {
//
// private transient WeakReference<Throwable> throwable;
// private RaygunErrorMessage innerError;
// private String message;
// private String className;
// private RaygunErrorStackTraceLineMessage[] stackTrace;
//
// public RaygunErrorMessage(Throwable throwable) {
// if (throwable == null) {
// return;
// }
//
// this.throwable = new WeakReference<Throwable>(throwable);
// message = throwable.getClass().getSimpleName();
// String throwableMessage = throwable.getMessage();
// if (throwableMessage != null) {
// message = message.concat(": ").concat(throwableMessage);
// }
// className = throwable.getClass().getCanonicalName();
//
// if (throwable.getCause() != null) {
// innerError = new RaygunErrorMessage(throwable.getCause());
// }
//
// StackTraceElement[] ste = throwable.getStackTrace();
// stackTrace = new RaygunErrorStackTraceLineMessage[ste.length];
//
// for (int i = 0; i < ste.length; i++) {
// stackTrace[i] = new RaygunErrorStackTraceLineMessage(ste[i]);
// }
// }
//
// public RaygunErrorMessage getInnerError() {
// return innerError;
// }
//
// public void setInnerError(RaygunErrorMessage innerError) {
// this.innerError = innerError;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public RaygunErrorStackTraceLineMessage[] getStackTrace() {
// return stackTrace;
// }
//
// public void setStackTrace(RaygunErrorStackTraceLineMessage[] stackTrace) {
// this.stackTrace = stackTrace;
// }
//
// public Throwable getThrowable() {
// if(throwable != null && throwable.get() != null) {
// return throwable.get();
// }
// return null;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
// Path: core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunStripWrappedExceptionFilterTest.java
import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunStripWrappedExceptionFilterTest {
@Test
public void shouldStripException () {
RaygunStripWrappedExceptionFilter f = new RaygunStripWrappedExceptionFilter(ClassNotFoundException.class);
| RaygunMessage message = new RaygunMessage(); |
MindscapeHQ/raygun4java | core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunStripWrappedExceptionFilterTest.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunErrorMessage.java
// public class RaygunErrorMessage {
//
// private transient WeakReference<Throwable> throwable;
// private RaygunErrorMessage innerError;
// private String message;
// private String className;
// private RaygunErrorStackTraceLineMessage[] stackTrace;
//
// public RaygunErrorMessage(Throwable throwable) {
// if (throwable == null) {
// return;
// }
//
// this.throwable = new WeakReference<Throwable>(throwable);
// message = throwable.getClass().getSimpleName();
// String throwableMessage = throwable.getMessage();
// if (throwableMessage != null) {
// message = message.concat(": ").concat(throwableMessage);
// }
// className = throwable.getClass().getCanonicalName();
//
// if (throwable.getCause() != null) {
// innerError = new RaygunErrorMessage(throwable.getCause());
// }
//
// StackTraceElement[] ste = throwable.getStackTrace();
// stackTrace = new RaygunErrorStackTraceLineMessage[ste.length];
//
// for (int i = 0; i < ste.length; i++) {
// stackTrace[i] = new RaygunErrorStackTraceLineMessage(ste[i]);
// }
// }
//
// public RaygunErrorMessage getInnerError() {
// return innerError;
// }
//
// public void setInnerError(RaygunErrorMessage innerError) {
// this.innerError = innerError;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public RaygunErrorStackTraceLineMessage[] getStackTrace() {
// return stackTrace;
// }
//
// public void setStackTrace(RaygunErrorStackTraceLineMessage[] stackTrace) {
// this.stackTrace = stackTrace;
// }
//
// public Throwable getThrowable() {
// if(throwable != null && throwable.get() != null) {
// return throwable.get();
// }
// return null;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunStripWrappedExceptionFilterTest {
@Test
public void shouldStripException () {
RaygunStripWrappedExceptionFilter f = new RaygunStripWrappedExceptionFilter(ClassNotFoundException.class);
RaygunMessage message = new RaygunMessage(); | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunErrorMessage.java
// public class RaygunErrorMessage {
//
// private transient WeakReference<Throwable> throwable;
// private RaygunErrorMessage innerError;
// private String message;
// private String className;
// private RaygunErrorStackTraceLineMessage[] stackTrace;
//
// public RaygunErrorMessage(Throwable throwable) {
// if (throwable == null) {
// return;
// }
//
// this.throwable = new WeakReference<Throwable>(throwable);
// message = throwable.getClass().getSimpleName();
// String throwableMessage = throwable.getMessage();
// if (throwableMessage != null) {
// message = message.concat(": ").concat(throwableMessage);
// }
// className = throwable.getClass().getCanonicalName();
//
// if (throwable.getCause() != null) {
// innerError = new RaygunErrorMessage(throwable.getCause());
// }
//
// StackTraceElement[] ste = throwable.getStackTrace();
// stackTrace = new RaygunErrorStackTraceLineMessage[ste.length];
//
// for (int i = 0; i < ste.length; i++) {
// stackTrace[i] = new RaygunErrorStackTraceLineMessage(ste[i]);
// }
// }
//
// public RaygunErrorMessage getInnerError() {
// return innerError;
// }
//
// public void setInnerError(RaygunErrorMessage innerError) {
// this.innerError = innerError;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public RaygunErrorStackTraceLineMessage[] getStackTrace() {
// return stackTrace;
// }
//
// public void setStackTrace(RaygunErrorStackTraceLineMessage[] stackTrace) {
// this.stackTrace = stackTrace;
// }
//
// public Throwable getThrowable() {
// if(throwable != null && throwable.get() != null) {
// return throwable.get();
// }
// return null;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
// Path: core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunStripWrappedExceptionFilterTest.java
import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunStripWrappedExceptionFilterTest {
@Test
public void shouldStripException () {
RaygunStripWrappedExceptionFilter f = new RaygunStripWrappedExceptionFilter(ClassNotFoundException.class);
RaygunMessage message = new RaygunMessage(); | message.getDetails().setError(new RaygunErrorMessage(new ClassNotFoundException("wrapper", new Exception("keep me!")))); |
MindscapeHQ/raygun4java | webprovider/src/main/java/com/mindscapehq/raygun4java/webprovider/RaygunServletMessageBuilder.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/RaygunMessageBuilder.java
// public class RaygunMessageBuilder implements IRaygunMessageBuilder {
//
// protected RaygunMessage raygunMessage;
//
// public RaygunMessageBuilder() {
// raygunMessage = new RaygunMessage();
// }
//
// public RaygunMessage build() {
// return raygunMessage;
// }
//
// public static IRaygunMessageBuilder newMessageBuilder() {
// return new RaygunMessageBuilder();
// }
//
// public IRaygunMessageBuilder setMachineName(String machineName) {
// raygunMessage.getDetails().setMachineName(machineName);
// return this;
// }
//
// public IRaygunMessageBuilder setExceptionDetails(Throwable throwable) {
// raygunMessage.getDetails().setError(new RaygunErrorMessage(throwable));
// return this;
// }
//
// public IRaygunMessageBuilder setClientDetails() {
// raygunMessage.getDetails().setClient(new RaygunClientMessage());
// return this;
// }
//
// public IRaygunMessageBuilder setEnvironmentDetails() {
// raygunMessage.getDetails().setEnvironment(new RaygunEnvironmentMessage());
// return this;
// }
//
// public IRaygunMessageBuilder setVersion(String version) {
// if (version != null) {
// raygunMessage.getDetails().setVersion(version);
// } else {
// raygunMessage.getDetails().setVersion(ReadVersion(null));
// }
// return this;
// }
//
// public IRaygunMessageBuilder setVersionFrom(Class versionFrom) {
// raygunMessage.getDetails().setVersion(ReadVersion(versionFrom));
//
// return this;
// }
//
// public IRaygunMessageBuilder setTags(Set<String> tags) {
// raygunMessage.getDetails().setTags(tags);
// return this;
// }
//
// public IRaygunMessageBuilder setUserCustomData(Map<?, ?> userCustomData) {
// raygunMessage.getDetails().setUserCustomData(userCustomData);
// return this;
// }
//
// public IRaygunMessageBuilder setUser(RaygunIdentifier user) {
// raygunMessage.getDetails().setUser(user);
// return this;
// }
//
// public IRaygunMessageBuilder setGroupingKey(String groupingKey) {
// raygunMessage.getDetails().setGroupingKey(groupingKey);
// return this;
// }
//
// public IRaygunMessageBuilder setBreadrumbs(List<RaygunBreadcrumbMessage> breadcrumbs) {
// raygunMessage.getDetails().setBreadcrumbs(breadcrumbs);
// return this;
// }
//
// private String ReadVersion(Class readVersionFrom) {
//
// String mainClass;
// if (readVersionFrom == null) {
// StackTraceElement[] stack = Thread.currentThread().getStackTrace();
// StackTraceElement main = stack[stack.length - 1];
// mainClass = main.getClassName();
// } else {
// mainClass = readVersionFrom.getName();
// }
//
// try {
// Class<?> cl = getClass().getClassLoader().loadClass(mainClass);
// String className = cl.getSimpleName() + ".class";
// String classPath = cl.getResource(className).toString();
//
// String jarPath = classPath.substring(0, classPath.lastIndexOf("!") + 1);
// if (jarPath.length() > 0) {
// String manifestPath = jarPath + "/META-INF/MANIFEST.MF";
// return readVersionFromManifest(new URL(manifestPath).openStream());
// }
// } catch (Exception e) {
// Logger.getLogger("Raygun4Java").warning("Cannot read version from manifest: " + e.getMessage());
// }
//
// return noManifestVersion();
// }
//
// protected String readVersionFromManifest(InputStream manifestInputStream) {
// try {
// Manifest manifest = new Manifest(manifestInputStream);
// Attributes attr = manifest.getMainAttributes();
//
// if (attr.getValue("Specification-Version") != null) {
// return attr.getValue("Specification-Version");
// } else if (attr.getValue("Implementation-Version") != null) {
// return attr.getValue("Implementation-Version");
// }
// } catch (Exception e) {
// Logger.getLogger("Raygun4Java").warning("Cannot read version from manifest: " + e.getMessage());
// }
// return noManifestVersion();
// }
//
// protected String noManifestVersion() {
// return "Not supplied";
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunResponseMessage.java
// public class RaygunResponseMessage {
// private Integer statusCode;
//
// public RaygunResponseMessage(Integer statusCode) {
// this.statusCode = statusCode;
// }
//
// public Integer getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(Integer statusCode) {
// this.statusCode = statusCode;
// }
// }
| import com.mindscapehq.raygun4java.core.RaygunMessageBuilder;
import com.mindscapehq.raygun4java.core.messages.RaygunResponseMessage;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL; | package com.mindscapehq.raygun4java.webprovider;
public class RaygunServletMessageBuilder extends RaygunMessageBuilder implements IRaygunHttpMessageBuilder {
public RaygunServletMessageBuilder() {
raygunMessage = new RaygunServletMessage();
}
public static RaygunServletMessageBuilder newMessageBuilder() {
return new RaygunServletMessageBuilder();
}
@Override
public RaygunServletMessage build() {
return (RaygunServletMessage) raygunMessage;
}
public IRaygunHttpMessageBuilder setRequestDetails(HttpServletRequest request, HttpServletResponse response) {
RaygunServletMessage servletMessage = (RaygunServletMessage) raygunMessage;
servletMessage.getDetails().setRequest(new RaygunRequestMessage(request));
if(response != null) { | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/RaygunMessageBuilder.java
// public class RaygunMessageBuilder implements IRaygunMessageBuilder {
//
// protected RaygunMessage raygunMessage;
//
// public RaygunMessageBuilder() {
// raygunMessage = new RaygunMessage();
// }
//
// public RaygunMessage build() {
// return raygunMessage;
// }
//
// public static IRaygunMessageBuilder newMessageBuilder() {
// return new RaygunMessageBuilder();
// }
//
// public IRaygunMessageBuilder setMachineName(String machineName) {
// raygunMessage.getDetails().setMachineName(machineName);
// return this;
// }
//
// public IRaygunMessageBuilder setExceptionDetails(Throwable throwable) {
// raygunMessage.getDetails().setError(new RaygunErrorMessage(throwable));
// return this;
// }
//
// public IRaygunMessageBuilder setClientDetails() {
// raygunMessage.getDetails().setClient(new RaygunClientMessage());
// return this;
// }
//
// public IRaygunMessageBuilder setEnvironmentDetails() {
// raygunMessage.getDetails().setEnvironment(new RaygunEnvironmentMessage());
// return this;
// }
//
// public IRaygunMessageBuilder setVersion(String version) {
// if (version != null) {
// raygunMessage.getDetails().setVersion(version);
// } else {
// raygunMessage.getDetails().setVersion(ReadVersion(null));
// }
// return this;
// }
//
// public IRaygunMessageBuilder setVersionFrom(Class versionFrom) {
// raygunMessage.getDetails().setVersion(ReadVersion(versionFrom));
//
// return this;
// }
//
// public IRaygunMessageBuilder setTags(Set<String> tags) {
// raygunMessage.getDetails().setTags(tags);
// return this;
// }
//
// public IRaygunMessageBuilder setUserCustomData(Map<?, ?> userCustomData) {
// raygunMessage.getDetails().setUserCustomData(userCustomData);
// return this;
// }
//
// public IRaygunMessageBuilder setUser(RaygunIdentifier user) {
// raygunMessage.getDetails().setUser(user);
// return this;
// }
//
// public IRaygunMessageBuilder setGroupingKey(String groupingKey) {
// raygunMessage.getDetails().setGroupingKey(groupingKey);
// return this;
// }
//
// public IRaygunMessageBuilder setBreadrumbs(List<RaygunBreadcrumbMessage> breadcrumbs) {
// raygunMessage.getDetails().setBreadcrumbs(breadcrumbs);
// return this;
// }
//
// private String ReadVersion(Class readVersionFrom) {
//
// String mainClass;
// if (readVersionFrom == null) {
// StackTraceElement[] stack = Thread.currentThread().getStackTrace();
// StackTraceElement main = stack[stack.length - 1];
// mainClass = main.getClassName();
// } else {
// mainClass = readVersionFrom.getName();
// }
//
// try {
// Class<?> cl = getClass().getClassLoader().loadClass(mainClass);
// String className = cl.getSimpleName() + ".class";
// String classPath = cl.getResource(className).toString();
//
// String jarPath = classPath.substring(0, classPath.lastIndexOf("!") + 1);
// if (jarPath.length() > 0) {
// String manifestPath = jarPath + "/META-INF/MANIFEST.MF";
// return readVersionFromManifest(new URL(manifestPath).openStream());
// }
// } catch (Exception e) {
// Logger.getLogger("Raygun4Java").warning("Cannot read version from manifest: " + e.getMessage());
// }
//
// return noManifestVersion();
// }
//
// protected String readVersionFromManifest(InputStream manifestInputStream) {
// try {
// Manifest manifest = new Manifest(manifestInputStream);
// Attributes attr = manifest.getMainAttributes();
//
// if (attr.getValue("Specification-Version") != null) {
// return attr.getValue("Specification-Version");
// } else if (attr.getValue("Implementation-Version") != null) {
// return attr.getValue("Implementation-Version");
// }
// } catch (Exception e) {
// Logger.getLogger("Raygun4Java").warning("Cannot read version from manifest: " + e.getMessage());
// }
// return noManifestVersion();
// }
//
// protected String noManifestVersion() {
// return "Not supplied";
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunResponseMessage.java
// public class RaygunResponseMessage {
// private Integer statusCode;
//
// public RaygunResponseMessage(Integer statusCode) {
// this.statusCode = statusCode;
// }
//
// public Integer getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(Integer statusCode) {
// this.statusCode = statusCode;
// }
// }
// Path: webprovider/src/main/java/com/mindscapehq/raygun4java/webprovider/RaygunServletMessageBuilder.java
import com.mindscapehq.raygun4java.core.RaygunMessageBuilder;
import com.mindscapehq.raygun4java.core.messages.RaygunResponseMessage;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
package com.mindscapehq.raygun4java.webprovider;
public class RaygunServletMessageBuilder extends RaygunMessageBuilder implements IRaygunHttpMessageBuilder {
public RaygunServletMessageBuilder() {
raygunMessage = new RaygunServletMessage();
}
public static RaygunServletMessageBuilder newMessageBuilder() {
return new RaygunServletMessageBuilder();
}
@Override
public RaygunServletMessage build() {
return (RaygunServletMessage) raygunMessage;
}
public IRaygunHttpMessageBuilder setRequestDetails(HttpServletRequest request, HttpServletResponse response) {
RaygunServletMessage servletMessage = (RaygunServletMessage) raygunMessage;
servletMessage.getDetails().setRequest(new RaygunRequestMessage(request));
if(response != null) { | servletMessage.getDetails().setResponse(new RaygunResponseMessage(response.getStatus())); |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestFormFilter.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import java.util.Map; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Given a list of form field names, this will replace the field values with an optional replacement
*/
public class RaygunRequestFormFilter extends AbstractRaygunRequestMapFilter {
public RaygunRequestFormFilter(String... keysToFilter) {
super(keysToFilter);
}
| // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestFormFilter.java
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import java.util.Map;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Given a list of form field names, this will replace the field values with an optional replacement
*/
public class RaygunRequestFormFilter extends AbstractRaygunRequestMapFilter {
public RaygunRequestFormFilter(String... keysToFilter) {
super(keysToFilter);
}
| public Map<String, String> getMapToFilter(RaygunRequestMessage requestMessage) { |
MindscapeHQ/raygun4java | core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeExceptionFilterTest.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunErrorMessage.java
// public class RaygunErrorMessage {
//
// private transient WeakReference<Throwable> throwable;
// private RaygunErrorMessage innerError;
// private String message;
// private String className;
// private RaygunErrorStackTraceLineMessage[] stackTrace;
//
// public RaygunErrorMessage(Throwable throwable) {
// if (throwable == null) {
// return;
// }
//
// this.throwable = new WeakReference<Throwable>(throwable);
// message = throwable.getClass().getSimpleName();
// String throwableMessage = throwable.getMessage();
// if (throwableMessage != null) {
// message = message.concat(": ").concat(throwableMessage);
// }
// className = throwable.getClass().getCanonicalName();
//
// if (throwable.getCause() != null) {
// innerError = new RaygunErrorMessage(throwable.getCause());
// }
//
// StackTraceElement[] ste = throwable.getStackTrace();
// stackTrace = new RaygunErrorStackTraceLineMessage[ste.length];
//
// for (int i = 0; i < ste.length; i++) {
// stackTrace[i] = new RaygunErrorStackTraceLineMessage(ste[i]);
// }
// }
//
// public RaygunErrorMessage getInnerError() {
// return innerError;
// }
//
// public void setInnerError(RaygunErrorMessage innerError) {
// this.innerError = innerError;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public RaygunErrorStackTraceLineMessage[] getStackTrace() {
// return stackTrace;
// }
//
// public void setStackTrace(RaygunErrorStackTraceLineMessage[] stackTrace) {
// this.stackTrace = stackTrace;
// }
//
// public Throwable getThrowable() {
// if(throwable != null && throwable.get() != null) {
// return throwable.get();
// }
// return null;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import org.junit.Test;
import static org.junit.Assert.*; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeExceptionFilterTest {
@Test
public void shouldExcludeNestedException() {
RaygunExcludeExceptionFilter f = new RaygunExcludeExceptionFilter(IllegalStateException.class);
| // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunErrorMessage.java
// public class RaygunErrorMessage {
//
// private transient WeakReference<Throwable> throwable;
// private RaygunErrorMessage innerError;
// private String message;
// private String className;
// private RaygunErrorStackTraceLineMessage[] stackTrace;
//
// public RaygunErrorMessage(Throwable throwable) {
// if (throwable == null) {
// return;
// }
//
// this.throwable = new WeakReference<Throwable>(throwable);
// message = throwable.getClass().getSimpleName();
// String throwableMessage = throwable.getMessage();
// if (throwableMessage != null) {
// message = message.concat(": ").concat(throwableMessage);
// }
// className = throwable.getClass().getCanonicalName();
//
// if (throwable.getCause() != null) {
// innerError = new RaygunErrorMessage(throwable.getCause());
// }
//
// StackTraceElement[] ste = throwable.getStackTrace();
// stackTrace = new RaygunErrorStackTraceLineMessage[ste.length];
//
// for (int i = 0; i < ste.length; i++) {
// stackTrace[i] = new RaygunErrorStackTraceLineMessage(ste[i]);
// }
// }
//
// public RaygunErrorMessage getInnerError() {
// return innerError;
// }
//
// public void setInnerError(RaygunErrorMessage innerError) {
// this.innerError = innerError;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public RaygunErrorStackTraceLineMessage[] getStackTrace() {
// return stackTrace;
// }
//
// public void setStackTrace(RaygunErrorStackTraceLineMessage[] stackTrace) {
// this.stackTrace = stackTrace;
// }
//
// public Throwable getThrowable() {
// if(throwable != null && throwable.get() != null) {
// return throwable.get();
// }
// return null;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
// Path: core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeExceptionFilterTest.java
import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import org.junit.Test;
import static org.junit.Assert.*;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeExceptionFilterTest {
@Test
public void shouldExcludeNestedException() {
RaygunExcludeExceptionFilter f = new RaygunExcludeExceptionFilter(IllegalStateException.class);
| RaygunMessage message = new RaygunMessage(); |
MindscapeHQ/raygun4java | core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeExceptionFilterTest.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunErrorMessage.java
// public class RaygunErrorMessage {
//
// private transient WeakReference<Throwable> throwable;
// private RaygunErrorMessage innerError;
// private String message;
// private String className;
// private RaygunErrorStackTraceLineMessage[] stackTrace;
//
// public RaygunErrorMessage(Throwable throwable) {
// if (throwable == null) {
// return;
// }
//
// this.throwable = new WeakReference<Throwable>(throwable);
// message = throwable.getClass().getSimpleName();
// String throwableMessage = throwable.getMessage();
// if (throwableMessage != null) {
// message = message.concat(": ").concat(throwableMessage);
// }
// className = throwable.getClass().getCanonicalName();
//
// if (throwable.getCause() != null) {
// innerError = new RaygunErrorMessage(throwable.getCause());
// }
//
// StackTraceElement[] ste = throwable.getStackTrace();
// stackTrace = new RaygunErrorStackTraceLineMessage[ste.length];
//
// for (int i = 0; i < ste.length; i++) {
// stackTrace[i] = new RaygunErrorStackTraceLineMessage(ste[i]);
// }
// }
//
// public RaygunErrorMessage getInnerError() {
// return innerError;
// }
//
// public void setInnerError(RaygunErrorMessage innerError) {
// this.innerError = innerError;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public RaygunErrorStackTraceLineMessage[] getStackTrace() {
// return stackTrace;
// }
//
// public void setStackTrace(RaygunErrorStackTraceLineMessage[] stackTrace) {
// this.stackTrace = stackTrace;
// }
//
// public Throwable getThrowable() {
// if(throwable != null && throwable.get() != null) {
// return throwable.get();
// }
// return null;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import org.junit.Test;
import static org.junit.Assert.*; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeExceptionFilterTest {
@Test
public void shouldExcludeNestedException() {
RaygunExcludeExceptionFilter f = new RaygunExcludeExceptionFilter(IllegalStateException.class);
RaygunMessage message = new RaygunMessage(); | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunErrorMessage.java
// public class RaygunErrorMessage {
//
// private transient WeakReference<Throwable> throwable;
// private RaygunErrorMessage innerError;
// private String message;
// private String className;
// private RaygunErrorStackTraceLineMessage[] stackTrace;
//
// public RaygunErrorMessage(Throwable throwable) {
// if (throwable == null) {
// return;
// }
//
// this.throwable = new WeakReference<Throwable>(throwable);
// message = throwable.getClass().getSimpleName();
// String throwableMessage = throwable.getMessage();
// if (throwableMessage != null) {
// message = message.concat(": ").concat(throwableMessage);
// }
// className = throwable.getClass().getCanonicalName();
//
// if (throwable.getCause() != null) {
// innerError = new RaygunErrorMessage(throwable.getCause());
// }
//
// StackTraceElement[] ste = throwable.getStackTrace();
// stackTrace = new RaygunErrorStackTraceLineMessage[ste.length];
//
// for (int i = 0; i < ste.length; i++) {
// stackTrace[i] = new RaygunErrorStackTraceLineMessage(ste[i]);
// }
// }
//
// public RaygunErrorMessage getInnerError() {
// return innerError;
// }
//
// public void setInnerError(RaygunErrorMessage innerError) {
// this.innerError = innerError;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getClassName() {
// return className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public RaygunErrorStackTraceLineMessage[] getStackTrace() {
// return stackTrace;
// }
//
// public void setStackTrace(RaygunErrorStackTraceLineMessage[] stackTrace) {
// this.stackTrace = stackTrace;
// }
//
// public Throwable getThrowable() {
// if(throwable != null && throwable.get() != null) {
// return throwable.get();
// }
// return null;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
// Path: core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeExceptionFilterTest.java
import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import org.junit.Test;
import static org.junit.Assert.*;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeExceptionFilterTest {
@Test
public void shouldExcludeNestedException() {
RaygunExcludeExceptionFilter f = new RaygunExcludeExceptionFilter(IllegalStateException.class);
RaygunMessage message = new RaygunMessage(); | message.getDetails().setError(new RaygunErrorMessage(new ClassNotFoundException("wrapper1", new IllegalStateException("wrapper2", new ClassNotFoundException("wrapper3"))))); |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestQueryStringFilter.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import java.util.Map; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Given a list of query string field names, this will replace the field values with an optional replacement
*/
public class RaygunRequestQueryStringFilter extends AbstractRaygunRequestMapFilter {
public RaygunRequestQueryStringFilter(String... keysToFilter) {
super(keysToFilter);
}
| // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestQueryStringFilter.java
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import java.util.Map;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Given a list of query string field names, this will replace the field values with an optional replacement
*/
public class RaygunRequestQueryStringFilter extends AbstractRaygunRequestMapFilter {
public RaygunRequestQueryStringFilter(String... keysToFilter) {
super(keysToFilter);
}
| public Map<String, String> getMapToFilter(RaygunRequestMessage requestMessage) { |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestHeaderFilter.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import java.util.Map; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Given a list of header names, this will replace the header values with an optional replacement
*/
public class RaygunRequestHeaderFilter extends AbstractRaygunRequestMapFilter {
public RaygunRequestHeaderFilter(String... keysToFilter) {
super(keysToFilter);
}
| // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestHeaderFilter.java
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import java.util.Map;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Given a list of header names, this will replace the header values with an optional replacement
*/
public class RaygunRequestHeaderFilter extends AbstractRaygunRequestMapFilter {
public RaygunRequestHeaderFilter(String... keysToFilter) {
super(keysToFilter);
}
| public Map<String, String> getMapToFilter(RaygunRequestMessage requestMessage) { |
MindscapeHQ/raygun4java | core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilterTest.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilter.java
// public class RaygunExcludeLocalRequestFilter extends RaygunExcludeRequestFilter {
// private static final String LOCALHOST = "localhost";
// public RaygunExcludeLocalRequestFilter() {
// super(new Filter() {
// public boolean shouldFilterOut(RaygunRequestMessageDetails requestMessage) {
// return requestMessage.getRequest().getHostName().toLowerCase().startsWith(LOCALHOST);
// }
// });
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
| import com.mindscapehq.raygun4java.core.handlers.requestfilters.RaygunExcludeLocalRequestFilter;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeLocalRequestFilterTest {
RaygunMessage localMessage; | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilter.java
// public class RaygunExcludeLocalRequestFilter extends RaygunExcludeRequestFilter {
// private static final String LOCALHOST = "localhost";
// public RaygunExcludeLocalRequestFilter() {
// super(new Filter() {
// public boolean shouldFilterOut(RaygunRequestMessageDetails requestMessage) {
// return requestMessage.getRequest().getHostName().toLowerCase().startsWith(LOCALHOST);
// }
// });
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
// Path: core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilterTest.java
import com.mindscapehq.raygun4java.core.handlers.requestfilters.RaygunExcludeLocalRequestFilter;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeLocalRequestFilterTest {
RaygunMessage localMessage; | RaygunRequestMessageDetails details; |
MindscapeHQ/raygun4java | core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilterTest.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilter.java
// public class RaygunExcludeLocalRequestFilter extends RaygunExcludeRequestFilter {
// private static final String LOCALHOST = "localhost";
// public RaygunExcludeLocalRequestFilter() {
// super(new Filter() {
// public boolean shouldFilterOut(RaygunRequestMessageDetails requestMessage) {
// return requestMessage.getRequest().getHostName().toLowerCase().startsWith(LOCALHOST);
// }
// });
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
| import com.mindscapehq.raygun4java.core.handlers.requestfilters.RaygunExcludeLocalRequestFilter;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeLocalRequestFilterTest {
RaygunMessage localMessage;
RaygunRequestMessageDetails details;
@Before
public void setup() {
localMessage = new RaygunMessage();
details = new RaygunRequestMessageDetails();
}
@Test
public void shouldExcludeLocalHostRequests() { | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilter.java
// public class RaygunExcludeLocalRequestFilter extends RaygunExcludeRequestFilter {
// private static final String LOCALHOST = "localhost";
// public RaygunExcludeLocalRequestFilter() {
// super(new Filter() {
// public boolean shouldFilterOut(RaygunRequestMessageDetails requestMessage) {
// return requestMessage.getRequest().getHostName().toLowerCase().startsWith(LOCALHOST);
// }
// });
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
// Path: core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilterTest.java
import com.mindscapehq.raygun4java.core.handlers.requestfilters.RaygunExcludeLocalRequestFilter;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeLocalRequestFilterTest {
RaygunMessage localMessage;
RaygunRequestMessageDetails details;
@Before
public void setup() {
localMessage = new RaygunMessage();
details = new RaygunRequestMessageDetails();
}
@Test
public void shouldExcludeLocalHostRequests() { | RaygunRequestMessage request = new RaygunRequestMessage(); |
MindscapeHQ/raygun4java | core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilterTest.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilter.java
// public class RaygunExcludeLocalRequestFilter extends RaygunExcludeRequestFilter {
// private static final String LOCALHOST = "localhost";
// public RaygunExcludeLocalRequestFilter() {
// super(new Filter() {
// public boolean shouldFilterOut(RaygunRequestMessageDetails requestMessage) {
// return requestMessage.getRequest().getHostName().toLowerCase().startsWith(LOCALHOST);
// }
// });
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
| import com.mindscapehq.raygun4java.core.handlers.requestfilters.RaygunExcludeLocalRequestFilter;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeLocalRequestFilterTest {
RaygunMessage localMessage;
RaygunRequestMessageDetails details;
@Before
public void setup() {
localMessage = new RaygunMessage();
details = new RaygunRequestMessageDetails();
}
@Test
public void shouldExcludeLocalHostRequests() {
RaygunRequestMessage request = new RaygunRequestMessage();
request.setHostName("localhost:9090");
details.setRequest(request);
localMessage.setDetails(details);
| // Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilter.java
// public class RaygunExcludeLocalRequestFilter extends RaygunExcludeRequestFilter {
// private static final String LOCALHOST = "localhost";
// public RaygunExcludeLocalRequestFilter() {
// super(new Filter() {
// public boolean shouldFilterOut(RaygunRequestMessageDetails requestMessage) {
// return requestMessage.getRequest().getHostName().toLowerCase().startsWith(LOCALHOST);
// }
// });
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
// Path: core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilterTest.java
import com.mindscapehq.raygun4java.core.handlers.requestfilters.RaygunExcludeLocalRequestFilter;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunExcludeLocalRequestFilterTest {
RaygunMessage localMessage;
RaygunRequestMessageDetails details;
@Before
public void setup() {
localMessage = new RaygunMessage();
details = new RaygunRequestMessageDetails();
}
@Test
public void shouldExcludeLocalHostRequests() {
RaygunRequestMessage request = new RaygunRequestMessage();
request.setHostName("localhost:9090");
details.setRequest(request);
localMessage.setDetails(details);
| assertNull(new RaygunExcludeLocalRequestFilter().onBeforeSend(null, localMessage)); |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestHttpStatusFilter.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
import java.util.Collections;
import java.util.HashSet; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Will filter out errors with the given http status codes
*/
public class RaygunRequestHttpStatusFilter extends RaygunExcludeRequestFilter {
public RaygunRequestHttpStatusFilter(final Integer... excludeHttpCodes) {
super(new ExcludeHttpCodesFilter(excludeHttpCodes));
}
private static class ExcludeHttpCodesFilter implements Filter {
private HashSet<Integer> excludedCodes;
private ExcludeHttpCodesFilter(final Integer... excludeHttpCodes) {
excludedCodes = new HashSet<Integer>();
Collections.addAll(excludedCodes, excludeHttpCodes);
}
| // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestHttpStatusFilter.java
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
import java.util.Collections;
import java.util.HashSet;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Will filter out errors with the given http status codes
*/
public class RaygunRequestHttpStatusFilter extends RaygunExcludeRequestFilter {
public RaygunRequestHttpStatusFilter(final Integer... excludeHttpCodes) {
super(new ExcludeHttpCodesFilter(excludeHttpCodes));
}
private static class ExcludeHttpCodesFilter implements Filter {
private HashSet<Integer> excludedCodes;
private ExcludeHttpCodesFilter(final Integer... excludeHttpCodes) {
excludedCodes = new HashSet<Integer>();
Collections.addAll(excludedCodes, excludeHttpCodes);
}
| public boolean shouldFilterOut(RaygunRequestMessageDetails requestMessage) { |
MindscapeHQ/raygun4java | webprovider/src/main/java/com/mindscapehq/raygun4java/webprovider/RaygunServletMessage.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails; | package com.mindscapehq.raygun4java.webprovider;
public class RaygunServletMessage extends RaygunMessage {
public RaygunServletMessage() { | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunMessage.java
// public class RaygunMessage {
//
// protected String occurredOn;
// protected RaygunMessageDetails details;
//
// public RaygunMessage() {
// details = new RaygunMessageDetails();
//
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// df.setTimeZone(TimeZone.getTimeZone("UTC"));
// occurredOn = df.format(Calendar.getInstance().getTime());
// }
//
// public String getOccurredOn() {
// return occurredOn;
// }
//
// public void setOccurredOn(String occurredOn) {
// this.occurredOn = occurredOn;
// }
//
// public RaygunMessageDetails getDetails() {
// return details;
// }
//
// public void setDetails(RaygunMessageDetails details) {
// this.details = details;
// }
// }
//
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
// Path: webprovider/src/main/java/com/mindscapehq/raygun4java/webprovider/RaygunServletMessage.java
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
package com.mindscapehq.raygun4java.webprovider;
public class RaygunServletMessage extends RaygunMessage {
public RaygunServletMessage() { | details = new RaygunRequestMessageDetails(); |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilter.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Excludes requests that come from host names starting with "localhost"
*/
public class RaygunExcludeLocalRequestFilter extends RaygunExcludeRequestFilter {
private static final String LOCALHOST = "localhost";
public RaygunExcludeLocalRequestFilter() {
super(new Filter() { | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessageDetails.java
// public class RaygunRequestMessageDetails extends RaygunMessageDetails {
//
// private RaygunRequestMessage request;
// private RaygunResponseMessage response;
//
// public RaygunRequestMessage getRequest() {
// return request;
// }
//
// public void setRequest(RaygunRequestMessage request) {
// this.request = request;
// }
//
// public RaygunResponseMessage getResponse() {
// return response;
// }
//
// public void setResponse(RaygunResponseMessage response) {
// this.response = response;
// }
// }
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunExcludeLocalRequestFilter.java
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessageDetails;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Excludes requests that come from host names starting with "localhost"
*/
public class RaygunExcludeLocalRequestFilter extends RaygunExcludeRequestFilter {
private static final String LOCALHOST = "localhost";
public RaygunExcludeLocalRequestFilter() {
super(new Filter() { | public boolean shouldFilterOut(RaygunRequestMessageDetails requestMessage) { |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestCookieFilter.java | // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
| import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import java.util.Map; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Given a list of cookie names, this will replace the cookie values with an optional replacement
*/
public class RaygunRequestCookieFilter extends AbstractRaygunRequestMapFilter {
public RaygunRequestCookieFilter(String... keysToFilter) {
super(keysToFilter);
}
| // Path: core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunRequestMessage.java
// public class RaygunRequestMessage {
//
// protected String hostName;
// protected String url;
// protected String httpMethod;
// protected String ipAddress;
// protected Map<String, String> queryString;
// protected Map<String, String> data;
// protected Map<String, String> form;
// protected Map<String, String> headers;
// protected Map<String, String> cookies;
// protected String rawData;
//
// public Map<String, String> queryStringToMap(String query) {
// String[] params = query.split("&");
// Map<String, String> map = new HashMap<String, String>();
// for (String param : params) {
// int equalIndex = param.indexOf("=");
// String key = param;
// String value = null;
// if (equalIndex > 0) {
// key = param.substring(0, equalIndex);
// if (param.length() > equalIndex + 1) {
// value = param.substring(equalIndex + 1);
// }
// }
// map.put(key, value);
// }
// return map;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public Map<String, String> getForm() {
// return form;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public Map<String, String> getQueryString() {
// return queryString;
// }
//
// public Map<String, String> getCookies() {
// return cookies;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public void setHostName(String hostName) {
// this.hostName = hostName;
// }
//
// public String getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(String httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public String getIpAddress() {
// return ipAddress;
// }
//
// public void setIpAddress(String ipAddress) {
// this.ipAddress = ipAddress;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
// Path: core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunRequestCookieFilter.java
import com.mindscapehq.raygun4java.core.messages.RaygunRequestMessage;
import java.util.Map;
package com.mindscapehq.raygun4java.core.handlers.requestfilters;
/**
* Given a list of cookie names, this will replace the cookie values with an optional replacement
*/
public class RaygunRequestCookieFilter extends AbstractRaygunRequestMapFilter {
public RaygunRequestCookieFilter(String... keysToFilter) {
super(keysToFilter);
}
| public Map<String, String> getMapToFilter(RaygunRequestMessage requestMessage) { |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java
// public interface IBlockModelRegister
// {
// List<IBlockState> getBlockStates ();
//
// IBakedModel getModel (IBlockState state, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java
// public interface IItemModelRegister
// {
// Item getItem ();
//
// List<ItemStack> getItemVariants ();
//
// IBakedModel getModel (ItemStack stack, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java
// public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister
// {
// }
| import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*; | package com.jaquadro.minecraft.chameleon.resources;
@SideOnly(Side.CLIENT)
public class ModelRegistry
{ | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java
// public interface IBlockModelRegister
// {
// List<IBlockState> getBlockStates ();
//
// IBakedModel getModel (IBlockState state, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java
// public interface IItemModelRegister
// {
// Item getItem ();
//
// List<ItemStack> getItemVariants ();
//
// IBakedModel getModel (ItemStack stack, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java
// public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister
// {
// }
// Path: src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java
import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*;
package com.jaquadro.minecraft.chameleon.resources;
@SideOnly(Side.CLIENT)
public class ModelRegistry
{ | private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>(); |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java
// public interface IBlockModelRegister
// {
// List<IBlockState> getBlockStates ();
//
// IBakedModel getModel (IBlockState state, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java
// public interface IItemModelRegister
// {
// Item getItem ();
//
// List<ItemStack> getItemVariants ();
//
// IBakedModel getModel (ItemStack stack, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java
// public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister
// {
// }
| import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*; | package com.jaquadro.minecraft.chameleon.resources;
@SideOnly(Side.CLIENT)
public class ModelRegistry
{
private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>(); | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java
// public interface IBlockModelRegister
// {
// List<IBlockState> getBlockStates ();
//
// IBakedModel getModel (IBlockState state, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java
// public interface IItemModelRegister
// {
// Item getItem ();
//
// List<ItemStack> getItemVariants ();
//
// IBakedModel getModel (ItemStack stack, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java
// public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister
// {
// }
// Path: src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java
import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*;
package com.jaquadro.minecraft.chameleon.resources;
@SideOnly(Side.CLIENT)
public class ModelRegistry
{
private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>(); | private final Set<IItemModelRegister> itemRegistry = new HashSet<IItemModelRegister>(); |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java
// public interface IBlockModelRegister
// {
// List<IBlockState> getBlockStates ();
//
// IBakedModel getModel (IBlockState state, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java
// public interface IItemModelRegister
// {
// Item getItem ();
//
// List<ItemStack> getItemVariants ();
//
// IBakedModel getModel (ItemStack stack, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java
// public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister
// {
// }
| import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*; | package com.jaquadro.minecraft.chameleon.resources;
@SideOnly(Side.CLIENT)
public class ModelRegistry
{
private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>();
private final Set<IItemModelRegister> itemRegistry = new HashSet<IItemModelRegister>();
public final ChamModelLoader loader = new ChamModelLoader();
public void registerModel (IBlockModelRegister modelRegister) {
if (modelRegister != null)
blockRegistry.add(modelRegister);
}
public void registerModel (IItemModelRegister modelRegister) {
if (modelRegister != null) {
itemRegistry.add(modelRegister);
registerItemVariants(modelRegister.getItem());
}
}
| // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java
// public interface IBlockModelRegister
// {
// List<IBlockState> getBlockStates ();
//
// IBakedModel getModel (IBlockState state, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java
// public interface IItemModelRegister
// {
// Item getItem ();
//
// List<ItemStack> getItemVariants ();
//
// IBakedModel getModel (ItemStack stack, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java
// public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister
// {
// }
// Path: src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java
import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*;
package com.jaquadro.minecraft.chameleon.resources;
@SideOnly(Side.CLIENT)
public class ModelRegistry
{
private final Set<IBlockModelRegister> blockRegistry = new HashSet<IBlockModelRegister>();
private final Set<IItemModelRegister> itemRegistry = new HashSet<IItemModelRegister>();
public final ChamModelLoader loader = new ChamModelLoader();
public void registerModel (IBlockModelRegister modelRegister) {
if (modelRegister != null)
blockRegistry.add(modelRegister);
}
public void registerModel (IItemModelRegister modelRegister) {
if (modelRegister != null) {
itemRegistry.add(modelRegister);
registerItemVariants(modelRegister.getItem());
}
}
| public void registerModel (IUnifiedRegister modelRegister) { |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java
// public interface IBlockModelRegister
// {
// List<IBlockState> getBlockStates ();
//
// IBakedModel getModel (IBlockState state, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java
// public interface IItemModelRegister
// {
// Item getItem ();
//
// List<ItemStack> getItemVariants ();
//
// IBakedModel getModel (ItemStack stack, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java
// public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister
// {
// }
| import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*; | registerItemMapping(item, register);
}
}
}
private void registerItemMapping (Item item) {
registerItemMapping(item, null);
}
private void registerItemMapping (Item item, IItemModelRegister register) {
if (item instanceof IItemMeshResolver)
ModelLoader.setCustomMeshDefinition(item, ((IItemMeshResolver) item).getMeshResolver());
else if (register != null) {
for (ItemStack stack : register.getItemVariants())
ModelLoader.setCustomModelResourceLocation(item, stack.getMetadata(), getResourceLocation(stack));
}
else if (item instanceof IItemMeshMapper) {
for (Pair<ItemStack, ModelResourceLocation> pair : ((IItemMeshMapper) item).getMeshMappings())
ModelLoader.setCustomModelResourceLocation(item, pair.getKey().getMetadata(), pair.getValue());
}
else {
NonNullList<ItemStack> variants = NonNullList.create();
item.getSubItems(item.getCreativeTab(), variants);
for (ItemStack stack : variants)
ModelLoader.setCustomModelResourceLocation(item, stack.getMetadata(), getResourceLocation(stack));
}
}
private void registerTextureResources (List<ResourceLocation> resources) {
for (ResourceLocation resource : resources) | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IBlockModelRegister.java
// public interface IBlockModelRegister
// {
// List<IBlockState> getBlockStates ();
//
// IBakedModel getModel (IBlockState state, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IItemModelRegister.java
// public interface IItemModelRegister
// {
// Item getItem ();
//
// List<ItemStack> getItemVariants ();
//
// IBakedModel getModel (ItemStack stack, IBakedModel existingModel);
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/IUnifiedRegister.java
// public interface IUnifiedRegister extends IBlockModelRegister, IItemModelRegister, ITextureRegister
// {
// }
// Path: src/com/jaquadro/minecraft/chameleon/resources/ModelRegistry.java
import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.resources.register.IBlockModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IItemModelRegister;
import com.jaquadro.minecraft.chameleon.resources.register.IUnifiedRegister;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*;
registerItemMapping(item, register);
}
}
}
private void registerItemMapping (Item item) {
registerItemMapping(item, null);
}
private void registerItemMapping (Item item, IItemModelRegister register) {
if (item instanceof IItemMeshResolver)
ModelLoader.setCustomMeshDefinition(item, ((IItemMeshResolver) item).getMeshResolver());
else if (register != null) {
for (ItemStack stack : register.getItemVariants())
ModelLoader.setCustomModelResourceLocation(item, stack.getMetadata(), getResourceLocation(stack));
}
else if (item instanceof IItemMeshMapper) {
for (Pair<ItemStack, ModelResourceLocation> pair : ((IItemMeshMapper) item).getMeshMappings())
ModelLoader.setCustomModelResourceLocation(item, pair.getKey().getMetadata(), pair.getValue());
}
else {
NonNullList<ItemStack> variants = NonNullList.create();
item.getSubItems(item.getCreativeTab(), variants);
for (ItemStack stack : variants)
ModelLoader.setCustomModelResourceLocation(item, stack.getMetadata(), getResourceLocation(stack));
}
}
private void registerTextureResources (List<ResourceLocation> resources) {
for (ResourceLocation resource : resources) | Chameleon.instance.iconRegistry.registerIcon(resource); |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/block/ChamLockableTileEntity.java | // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/LockableData.java
// public class LockableData extends TileDataShim
// {
// private LockCode code = LockCode.EMPTY_CODE;
//
// @Override
// public void readFromNBT (NBTTagCompound tag) {
// code = LockCode.fromNBT(tag);
// }
//
// @Override
// public NBTTagCompound writeToNBT (NBTTagCompound tag) {
// if (code != null)
// code.toNBT(tag);
//
// return tag;
// }
//
// public boolean isLocked ()
// {
// return this.code != null && !this.code.isEmpty();
// }
//
// public LockCode getLockCode ()
// {
// return this.code;
// }
//
// public void setLockCode (LockCode code)
// {
// this.code = code;
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
| import com.jaquadro.minecraft.chameleon.block.tiledata.LockableData;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.LockCode; | package com.jaquadro.minecraft.chameleon.block;
public abstract class ChamLockableTileEntity extends ChamInvTileEntity implements ILockableContainer
{ | // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/LockableData.java
// public class LockableData extends TileDataShim
// {
// private LockCode code = LockCode.EMPTY_CODE;
//
// @Override
// public void readFromNBT (NBTTagCompound tag) {
// code = LockCode.fromNBT(tag);
// }
//
// @Override
// public NBTTagCompound writeToNBT (NBTTagCompound tag) {
// if (code != null)
// code.toNBT(tag);
//
// return tag;
// }
//
// public boolean isLocked ()
// {
// return this.code != null && !this.code.isEmpty();
// }
//
// public LockCode getLockCode ()
// {
// return this.code;
// }
//
// public void setLockCode (LockCode code)
// {
// this.code = code;
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
// Path: src/com/jaquadro/minecraft/chameleon/block/ChamLockableTileEntity.java
import com.jaquadro.minecraft.chameleon.block.tiledata.LockableData;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.LockCode;
package com.jaquadro.minecraft.chameleon.block;
public abstract class ChamLockableTileEntity extends ChamInvTileEntity implements ILockableContainer
{ | private LockableData lockableData; |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/block/ChamLockableTileEntity.java | // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/LockableData.java
// public class LockableData extends TileDataShim
// {
// private LockCode code = LockCode.EMPTY_CODE;
//
// @Override
// public void readFromNBT (NBTTagCompound tag) {
// code = LockCode.fromNBT(tag);
// }
//
// @Override
// public NBTTagCompound writeToNBT (NBTTagCompound tag) {
// if (code != null)
// code.toNBT(tag);
//
// return tag;
// }
//
// public boolean isLocked ()
// {
// return this.code != null && !this.code.isEmpty();
// }
//
// public LockCode getLockCode ()
// {
// return this.code;
// }
//
// public void setLockCode (LockCode code)
// {
// this.code = code;
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
| import com.jaquadro.minecraft.chameleon.block.tiledata.LockableData;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.LockCode; | package com.jaquadro.minecraft.chameleon.block;
public abstract class ChamLockableTileEntity extends ChamInvTileEntity implements ILockableContainer
{
private LockableData lockableData;
@Override | // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/LockableData.java
// public class LockableData extends TileDataShim
// {
// private LockCode code = LockCode.EMPTY_CODE;
//
// @Override
// public void readFromNBT (NBTTagCompound tag) {
// code = LockCode.fromNBT(tag);
// }
//
// @Override
// public NBTTagCompound writeToNBT (NBTTagCompound tag) {
// if (code != null)
// code.toNBT(tag);
//
// return tag;
// }
//
// public boolean isLocked ()
// {
// return this.code != null && !this.code.isEmpty();
// }
//
// public LockCode getLockCode ()
// {
// return this.code;
// }
//
// public void setLockCode (LockCode code)
// {
// this.code = code;
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
// Path: src/com/jaquadro/minecraft/chameleon/block/ChamLockableTileEntity.java
import com.jaquadro.minecraft.chameleon.block.tiledata.LockableData;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.LockCode;
package com.jaquadro.minecraft.chameleon.block;
public abstract class ChamLockableTileEntity extends ChamInvTileEntity implements ILockableContainer
{
private LockableData lockableData;
@Override | public void injectData (TileDataShim shim) { |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/integration/IntegrationRegistry.java | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
| import com.jaquadro.minecraft.chameleon.Chameleon;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import org.apache.logging.log4j.Level;
import java.util.ArrayList;
import java.util.List; | package com.jaquadro.minecraft.chameleon.integration;
public class IntegrationRegistry
{
private String modId;
private List<IntegrationModule> registry;
public IntegrationRegistry (String modId) {
this.modId = modId;
this.registry = new ArrayList<IntegrationModule>();
}
public void add (IntegrationModule module) {
if (module.versionCheck())
registry.add(module);
}
public void init () {
for (int i = 0; i < registry.size(); i++) {
IntegrationModule module = registry.get(i);
if (module.getModID() != null && !Loader.isModLoaded(module.getModID())) {
registry.remove(i--);
continue;
}
try {
module.init();
}
catch (Throwable t) {
registry.remove(i--); | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
// Path: src/com/jaquadro/minecraft/chameleon/integration/IntegrationRegistry.java
import com.jaquadro.minecraft.chameleon.Chameleon;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import org.apache.logging.log4j.Level;
import java.util.ArrayList;
import java.util.List;
package com.jaquadro.minecraft.chameleon.integration;
public class IntegrationRegistry
{
private String modId;
private List<IntegrationModule> registry;
public IntegrationRegistry (String modId) {
this.modId = modId;
this.registry = new ArrayList<IntegrationModule>();
}
public void add (IntegrationModule module) {
if (module.versionCheck())
registry.add(module);
}
public void init () {
for (int i = 0; i < registry.size(); i++) {
IntegrationModule module = registry.get(i);
if (module.getModID() != null && !Loader.isModLoaded(module.getModID())) {
registry.remove(i--);
continue;
}
try {
module.init();
}
catch (Throwable t) {
registry.remove(i--); | Chameleon.log.info("Could not load integration module: " + module.getClass().getName()); |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/block/ChamTileEntity.java | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
| import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; | package com.jaquadro.minecraft.chameleon.block;
public class ChamTileEntity extends TileEntity
{
private NBTTagCompound failureSnapshot; | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
// Path: src/com/jaquadro/minecraft/chameleon/block/ChamTileEntity.java
import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
package com.jaquadro.minecraft.chameleon.block;
public class ChamTileEntity extends TileEntity
{
private NBTTagCompound failureSnapshot; | private List<TileDataShim> fixedShims; |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/block/ChamTileEntity.java | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
| import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; |
@Override
public final void readFromNBT (NBTTagCompound tag) {
super.readFromNBT(tag);
failureSnapshot = null;
try {
readFromFixedNBT(tag);
readFromPortableNBT(tag);
}
catch (Throwable t) {
trapLoadFailure(t, tag);
}
}
@Override
public final NBTTagCompound writeToNBT (NBTTagCompound tag) {
super.writeToNBT(tag);
if (failureSnapshot != null) {
restoreLoadFailure(tag);
return tag;
}
try {
tag = writeToFixedNBT(tag);
tag = writeToPortableNBT(tag);
}
catch (Throwable t) { | // Path: src/com/jaquadro/minecraft/chameleon/Chameleon.java
// @Mod(modid = Chameleon.MOD_ID, name = Chameleon.MOD_NAME, version = Chameleon.MOD_VERSION, dependencies = "required-after:forge@[14.21.0.2362,);", acceptedMinecraftVersions = "[1.12,1.13)")
// public class Chameleon
// {
// public static final String MOD_ID = "chameleon";
// public static final String MOD_NAME = "Chameleon";
// public static final String MOD_VERSION = "@VERSION@";
// public static final String SOURCE_PATH = "com.jaquadro.minecraft.chameleon.";
//
// public static Logger log;
//
// @SideOnly(Side.CLIENT)
// public IconRegistry iconRegistry;
//
// @SideOnly(Side.CLIENT)
// public ModelRegistry modelRegistry;
//
// @Mod.Instance(MOD_ID)
// public static Chameleon instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "core.ClientProxy", serverSide = SOURCE_PATH + "core.CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// log = event.getModLog();
//
// MinecraftForge.EVENT_BUS.register(proxy);
// proxy.preInitSidedResources();
// }
//
// @Mod.EventHandler
// public void init (FMLInitializationEvent event) {
// proxy.initSidedResources();
//
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
// Path: src/com/jaquadro/minecraft/chameleon/block/ChamTileEntity.java
import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Override
public final void readFromNBT (NBTTagCompound tag) {
super.readFromNBT(tag);
failureSnapshot = null;
try {
readFromFixedNBT(tag);
readFromPortableNBT(tag);
}
catch (Throwable t) {
trapLoadFailure(t, tag);
}
}
@Override
public final NBTTagCompound writeToNBT (NBTTagCompound tag) {
super.writeToNBT(tag);
if (failureSnapshot != null) {
restoreLoadFailure(tag);
return tag;
}
try {
tag = writeToFixedNBT(tag);
tag = writeToPortableNBT(tag);
}
catch (Throwable t) { | Chameleon.log.error("Tile Save Failure.", t); |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/block/ChamInvTileEntity.java | // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/CustomNameData.java
// public class CustomNameData extends TileDataShim implements IWorldNameable
// {
// private String defaultName;
// private String customName;
//
// public CustomNameData (String defaultName) {
// this.defaultName = defaultName;
// }
//
// @Override
// public void readFromNBT (NBTTagCompound tag) {
// customName = null;
// if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING))
// customName = tag.getString("CustomName");
// }
//
// @Override
// public NBTTagCompound writeToNBT (NBTTagCompound tag) {
// if (hasCustomName())
// tag.setString("CustomName", customName);
//
// return tag;
// }
//
// @Override
// public String getName () {
// return hasCustomName() ? customName : defaultName;
// }
//
// @Override
// public boolean hasCustomName () {
// return customName != null && customName.length() > 0;
// }
//
// @Override
// public ITextComponent getDisplayName () {
// return hasCustomName() ? new TextComponentString(customName) : new TextComponentTranslation(defaultName);
// }
//
// public void setName (String name) {
// customName = name;
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
| import com.jaquadro.minecraft.chameleon.block.tiledata.CustomNameData;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.IWorldNameable;
import javax.annotation.Nullable; | package com.jaquadro.minecraft.chameleon.block;
public class ChamInvTileEntity extends ChamTileEntity implements IInventory, IWorldNameable
{
private static final InventoryBasic emptyInventory = new InventoryBasic("[null]", true, 0);
| // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/CustomNameData.java
// public class CustomNameData extends TileDataShim implements IWorldNameable
// {
// private String defaultName;
// private String customName;
//
// public CustomNameData (String defaultName) {
// this.defaultName = defaultName;
// }
//
// @Override
// public void readFromNBT (NBTTagCompound tag) {
// customName = null;
// if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING))
// customName = tag.getString("CustomName");
// }
//
// @Override
// public NBTTagCompound writeToNBT (NBTTagCompound tag) {
// if (hasCustomName())
// tag.setString("CustomName", customName);
//
// return tag;
// }
//
// @Override
// public String getName () {
// return hasCustomName() ? customName : defaultName;
// }
//
// @Override
// public boolean hasCustomName () {
// return customName != null && customName.length() > 0;
// }
//
// @Override
// public ITextComponent getDisplayName () {
// return hasCustomName() ? new TextComponentString(customName) : new TextComponentTranslation(defaultName);
// }
//
// public void setName (String name) {
// customName = name;
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
// Path: src/com/jaquadro/minecraft/chameleon/block/ChamInvTileEntity.java
import com.jaquadro.minecraft.chameleon.block.tiledata.CustomNameData;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.IWorldNameable;
import javax.annotation.Nullable;
package com.jaquadro.minecraft.chameleon.block;
public class ChamInvTileEntity extends ChamTileEntity implements IInventory, IWorldNameable
{
private static final InventoryBasic emptyInventory = new InventoryBasic("[null]", true, 0);
| private CustomNameData customNameData; |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/block/ChamInvTileEntity.java | // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/CustomNameData.java
// public class CustomNameData extends TileDataShim implements IWorldNameable
// {
// private String defaultName;
// private String customName;
//
// public CustomNameData (String defaultName) {
// this.defaultName = defaultName;
// }
//
// @Override
// public void readFromNBT (NBTTagCompound tag) {
// customName = null;
// if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING))
// customName = tag.getString("CustomName");
// }
//
// @Override
// public NBTTagCompound writeToNBT (NBTTagCompound tag) {
// if (hasCustomName())
// tag.setString("CustomName", customName);
//
// return tag;
// }
//
// @Override
// public String getName () {
// return hasCustomName() ? customName : defaultName;
// }
//
// @Override
// public boolean hasCustomName () {
// return customName != null && customName.length() > 0;
// }
//
// @Override
// public ITextComponent getDisplayName () {
// return hasCustomName() ? new TextComponentString(customName) : new TextComponentTranslation(defaultName);
// }
//
// public void setName (String name) {
// customName = name;
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
| import com.jaquadro.minecraft.chameleon.block.tiledata.CustomNameData;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.IWorldNameable;
import javax.annotation.Nullable; | package com.jaquadro.minecraft.chameleon.block;
public class ChamInvTileEntity extends ChamTileEntity implements IInventory, IWorldNameable
{
private static final InventoryBasic emptyInventory = new InventoryBasic("[null]", true, 0);
private CustomNameData customNameData;
@Override | // Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/CustomNameData.java
// public class CustomNameData extends TileDataShim implements IWorldNameable
// {
// private String defaultName;
// private String customName;
//
// public CustomNameData (String defaultName) {
// this.defaultName = defaultName;
// }
//
// @Override
// public void readFromNBT (NBTTagCompound tag) {
// customName = null;
// if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING))
// customName = tag.getString("CustomName");
// }
//
// @Override
// public NBTTagCompound writeToNBT (NBTTagCompound tag) {
// if (hasCustomName())
// tag.setString("CustomName", customName);
//
// return tag;
// }
//
// @Override
// public String getName () {
// return hasCustomName() ? customName : defaultName;
// }
//
// @Override
// public boolean hasCustomName () {
// return customName != null && customName.length() > 0;
// }
//
// @Override
// public ITextComponent getDisplayName () {
// return hasCustomName() ? new TextComponentString(customName) : new TextComponentTranslation(defaultName);
// }
//
// public void setName (String name) {
// customName = name;
// }
// }
//
// Path: src/com/jaquadro/minecraft/chameleon/block/tiledata/TileDataShim.java
// public abstract class TileDataShim implements INBTSerializable<NBTTagCompound>
// {
// public abstract void readFromNBT (NBTTagCompound tag);
//
// public abstract NBTTagCompound writeToNBT (NBTTagCompound tag);
//
// @Override
// public NBTTagCompound serializeNBT () {
// NBTTagCompound tag = new NBTTagCompound();
// return writeToNBT(tag);
// }
//
// @Override
// public void deserializeNBT (NBTTagCompound nbt) {
// readFromNBT(nbt);
// }
// }
// Path: src/com/jaquadro/minecraft/chameleon/block/ChamInvTileEntity.java
import com.jaquadro.minecraft.chameleon.block.tiledata.CustomNameData;
import com.jaquadro.minecraft.chameleon.block.tiledata.TileDataShim;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.IWorldNameable;
import javax.annotation.Nullable;
package com.jaquadro.minecraft.chameleon.block;
public class ChamInvTileEntity extends ChamTileEntity implements IInventory, IWorldNameable
{
private static final InventoryBasic emptyInventory = new InventoryBasic("[null]", true, 0);
private CustomNameData customNameData;
@Override | public void injectData (TileDataShim shim) { |
jaquadro/Chameleon | src/com/jaquadro/minecraft/chameleon/resources/register/DefaultRegister.java | // Path: src/com/jaquadro/minecraft/chameleon/resources/IItemMeshMapper.java
// public interface IItemMeshMapper
// {
// List<Pair<ItemStack, ModelResourceLocation>> getMeshMappings ();
// }
| import com.jaquadro.minecraft.chameleon.resources.IItemMeshMapper;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.List; | package com.jaquadro.minecraft.chameleon.resources.register;
public abstract class DefaultRegister<T extends Block> implements IUnifiedRegister
{
private final T block;
public DefaultRegister (T block) {
this.block = block;
}
@Override
public Item getItem () {
return Item.getItemFromBlock(block);
}
@Override
public List<ItemStack> getItemVariants () {
Item item = getItem();
NonNullList<ItemStack> variants = NonNullList.create();
| // Path: src/com/jaquadro/minecraft/chameleon/resources/IItemMeshMapper.java
// public interface IItemMeshMapper
// {
// List<Pair<ItemStack, ModelResourceLocation>> getMeshMappings ();
// }
// Path: src/com/jaquadro/minecraft/chameleon/resources/register/DefaultRegister.java
import com.jaquadro.minecraft.chameleon.resources.IItemMeshMapper;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.List;
package com.jaquadro.minecraft.chameleon.resources.register;
public abstract class DefaultRegister<T extends Block> implements IUnifiedRegister
{
private final T block;
public DefaultRegister (T block) {
this.block = block;
}
@Override
public Item getItem () {
return Item.getItemFromBlock(block);
}
@Override
public List<ItemStack> getItemVariants () {
Item item = getItem();
NonNullList<ItemStack> variants = NonNullList.create();
| if (item instanceof IItemMeshMapper) { |
NICTA/nicta-ner | conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/cmdline/Main.java | // Path: conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/ConllEvaluation.java
// public class ConllEvaluation {
//
// private final File testInput;
// private final File config;
//
// public ConllEvaluation(final File testInput, final File config) {
// this.testInput = testInput;
// this.config = config;
// }
//
// public void evaluate() throws IOException, InterruptedException {
// final Configuration conf =
// config == null ? new Configuration(true)
// : new Configuration(new BufferedInputStream(new FileInputStream(config)), true);
// final NamedEntityAnalyser nea = new NamedEntityAnalyser(conf);
//
// try (final ConllReader r = new ConllReader(testInput)) {
// while (r.hasNext()) {
// // each section in the test results data starts with a DOCSTART
// System.out.println("-DOCSTART- -X- O O O\n");
// final Collection<Sentence> sentences = r.next();
//
// for (final Sentence conllSentence : sentences) {
// final NerResultSet nerResultSet = nea.process(conllSentence.sentence);
// final Map<Integer, NerClassification> phraseMap = Util.positionClassificationMap(nerResultSet);
// final Map<ConllToken, String> disagreements = new LinkedHashMap<>();
//
// ConllToken previousToken = null;
// for (final ConllToken conllToken : conllSentence.tokens) {
// final NerClassification nerClas = phraseMap.get(conllToken.startIndex);
// final NerClassification previousClas = previousToken == null
// ? null : phraseMap.get(previousToken.startIndex);
// final String clas = Util.translateClassification(nerClas, previousClas);
//
// // print out the token, the test annotations, and our classification of the token
// System.out.printf("%s %s %s %s\n",
// conllToken.token, conllToken.classifiers, conllToken.truth, clas);
// previousToken = conllToken;
//
// // if the truth doesn't match the NICTA result then print out more info on stderr
// if (!conllToken.truth.equals(clas)) {
// disagreements.put(conllToken, clas);
// }
// }
// // finish each sentence with a newline
// System.out.println();
//
// if (!disagreements.isEmpty()) {
// printDisagreements(conllSentence, phraseMap, disagreements, nea.trace);
// }
// }
// }
// }
// }
//
// private static void printDisagreements(final Sentence conllSentence,
// final Map<Integer, NerClassification> phraseMap,
// final Map<ConllToken, String> disagreements,
// final Collection<String> trace) {
// System.err.println(conllSentence.sentence);
// for (final Map.Entry<ConllToken, String> e : disagreements.entrySet()) {
// final ConllToken conllToken = e.getKey();
// final NerClassification nerClassification = phraseMap.get(conllToken.startIndex);
//
// if (nerClassification == null) {
// System.err.printf("%d: '%s':%s <no match>\n", conllToken.startIndex, conllToken.token,
// conllToken.truth);
//
// }
// else {
// System.err.printf("%d: '%s':%s '%s':%s %s\n", conllToken.startIndex, conllToken.token,
// conllToken.truth, nerClassification.nerToken, e.getValue(),
// nerClassification.scores);
// }
// }
// for (final String t : trace) System.err.println(t);
// System.err.println();
// }
// }
| import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import org.t3as.ner.conll2003.ConllEvaluation;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | /*
* #%L
* NICTA t3as NER CoNLL 2003 evaluation
* %%
* Copyright (C) 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.conll2003.cmdline;
public final class Main {
private Main() {}
@SuppressWarnings("MethodNamesDifferingOnlyByCase")
public static void main(final String[] args) throws IOException, InterruptedException {
final Options opts = getOptions(args);
| // Path: conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/ConllEvaluation.java
// public class ConllEvaluation {
//
// private final File testInput;
// private final File config;
//
// public ConllEvaluation(final File testInput, final File config) {
// this.testInput = testInput;
// this.config = config;
// }
//
// public void evaluate() throws IOException, InterruptedException {
// final Configuration conf =
// config == null ? new Configuration(true)
// : new Configuration(new BufferedInputStream(new FileInputStream(config)), true);
// final NamedEntityAnalyser nea = new NamedEntityAnalyser(conf);
//
// try (final ConllReader r = new ConllReader(testInput)) {
// while (r.hasNext()) {
// // each section in the test results data starts with a DOCSTART
// System.out.println("-DOCSTART- -X- O O O\n");
// final Collection<Sentence> sentences = r.next();
//
// for (final Sentence conllSentence : sentences) {
// final NerResultSet nerResultSet = nea.process(conllSentence.sentence);
// final Map<Integer, NerClassification> phraseMap = Util.positionClassificationMap(nerResultSet);
// final Map<ConllToken, String> disagreements = new LinkedHashMap<>();
//
// ConllToken previousToken = null;
// for (final ConllToken conllToken : conllSentence.tokens) {
// final NerClassification nerClas = phraseMap.get(conllToken.startIndex);
// final NerClassification previousClas = previousToken == null
// ? null : phraseMap.get(previousToken.startIndex);
// final String clas = Util.translateClassification(nerClas, previousClas);
//
// // print out the token, the test annotations, and our classification of the token
// System.out.printf("%s %s %s %s\n",
// conllToken.token, conllToken.classifiers, conllToken.truth, clas);
// previousToken = conllToken;
//
// // if the truth doesn't match the NICTA result then print out more info on stderr
// if (!conllToken.truth.equals(clas)) {
// disagreements.put(conllToken, clas);
// }
// }
// // finish each sentence with a newline
// System.out.println();
//
// if (!disagreements.isEmpty()) {
// printDisagreements(conllSentence, phraseMap, disagreements, nea.trace);
// }
// }
// }
// }
// }
//
// private static void printDisagreements(final Sentence conllSentence,
// final Map<Integer, NerClassification> phraseMap,
// final Map<ConllToken, String> disagreements,
// final Collection<String> trace) {
// System.err.println(conllSentence.sentence);
// for (final Map.Entry<ConllToken, String> e : disagreements.entrySet()) {
// final ConllToken conllToken = e.getKey();
// final NerClassification nerClassification = phraseMap.get(conllToken.startIndex);
//
// if (nerClassification == null) {
// System.err.printf("%d: '%s':%s <no match>\n", conllToken.startIndex, conllToken.token,
// conllToken.truth);
//
// }
// else {
// System.err.printf("%d: '%s':%s '%s':%s %s\n", conllToken.startIndex, conllToken.token,
// conllToken.truth, nerClassification.nerToken, e.getValue(),
// nerClassification.scores);
// }
// }
// for (final String t : trace) System.err.println(t);
// System.err.println();
// }
// }
// Path: conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/cmdline/Main.java
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import org.t3as.ner.conll2003.ConllEvaluation;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/*
* #%L
* NICTA t3as NER CoNLL 2003 evaluation
* %%
* Copyright (C) 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.conll2003.cmdline;
public final class Main {
private Main() {}
@SuppressWarnings("MethodNamesDifferingOnlyByCase")
public static void main(final String[] args) throws IOException, InterruptedException {
final Options opts = getOptions(args);
| new ConllEvaluation(opts.file.get(0), opts.config).evaluate(); |
NICTA/nicta-ner | conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/NerClassification.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public class EntityClass {
//
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
// public static final EntityClass DATE = new EntityClass("DATE");
//
// private final String entityClass;
//
// @JsonCreator
// public EntityClass(@JsonProperty("entityClass") final String entityClass) { this.entityClass = entityClass; }
//
// // required for JSON
// @SuppressWarnings("UnusedDeclaration")
// public String getEntityClass() { return entityClass; }
//
// @Override
// public String toString() { return entityClass; }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final EntityClass that = (EntityClass) o;
// return entityClass.equals(that.entityClass);
// }
//
// @Override
// public int hashCode() { return entityClass.hashCode(); }
// }
| import org.t3as.ner.EntityClass;
import java.util.Map;
import com.google.common.collect.ImmutableMap; | /*
* #%L
* NICTA t3as NER CoNLL 2003 evaluation
* %%
* Copyright (C) 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.conll2003;
public class NerClassification {
public final String nerToken; | // Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public class EntityClass {
//
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
// public static final EntityClass DATE = new EntityClass("DATE");
//
// private final String entityClass;
//
// @JsonCreator
// public EntityClass(@JsonProperty("entityClass") final String entityClass) { this.entityClass = entityClass; }
//
// // required for JSON
// @SuppressWarnings("UnusedDeclaration")
// public String getEntityClass() { return entityClass; }
//
// @Override
// public String toString() { return entityClass; }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final EntityClass that = (EntityClass) o;
// return entityClass.equals(that.entityClass);
// }
//
// @Override
// public int hashCode() { return entityClass.hashCode(); }
// }
// Path: conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/NerClassification.java
import org.t3as.ner.EntityClass;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
/*
* #%L
* NICTA t3as NER CoNLL 2003 evaluation
* %%
* Copyright (C) 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.conll2003;
public class NerClassification {
public final String nerToken; | public final EntityClass type; |
NICTA/nicta-ner | nicta-ner/src/test/java/org/t3as/ner/util/TokenizerTest.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
| import org.t3as.ner.Token;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.List;
import static com.google.common.collect.ImmutableList.of; | {"A can't won't don't : foo",
of(of(t(0, "A"), t(2, "ca"), t(4, "n't"), t(8, "wo"), t(10, "n't"), t(14, "do"), t(16, "n't"),
t(20, ":"), t(22, "foo")))},
{"Dr Foo, Dr. Foo. Mr Bar, Miss Bar, Ms Bar.",
of(of(t(0, "Dr"), t(3, "Foo"), t(6, ","), t(8, "Dr."), t(12, "Foo"), t(15, ".")),
of(t(17, "Mr"), t(20, "Bar"), t(23, ","), t(25, "Miss"), t(30, "Bar"), t(33, ","), t(35, "Ms"),
t(38, "Bar"), t(41, ".")))},
{"A day in Jan. Jan 2, 2008.",
of(of(t(0, "A"), t(2, "day"), t(6, "in"), t(9, "Jan."), t(14, "Jan"), t(18, "2"), t(19, ","),
t(21, "2008"), t(25, ".")))},
{"", of()},
{":", of(of(t(0, ":")))},
{"foo:", of(of(t(0, "foo"), t(3, ":")))},
{"a: b", of(of(t(0, "a"), t(1, ":"), t(3, "b")))},
};
}
@Test
public void testDataProviders() {
text();
}
@Test(dataProvider = "text") | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
// Path: nicta-ner/src/test/java/org/t3as/ner/util/TokenizerTest.java
import org.t3as.ner.Token;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.List;
import static com.google.common.collect.ImmutableList.of;
{"A can't won't don't : foo",
of(of(t(0, "A"), t(2, "ca"), t(4, "n't"), t(8, "wo"), t(10, "n't"), t(14, "do"), t(16, "n't"),
t(20, ":"), t(22, "foo")))},
{"Dr Foo, Dr. Foo. Mr Bar, Miss Bar, Ms Bar.",
of(of(t(0, "Dr"), t(3, "Foo"), t(6, ","), t(8, "Dr."), t(12, "Foo"), t(15, ".")),
of(t(17, "Mr"), t(20, "Bar"), t(23, ","), t(25, "Miss"), t(30, "Bar"), t(33, ","), t(35, "Ms"),
t(38, "Bar"), t(41, ".")))},
{"A day in Jan. Jan 2, 2008.",
of(of(t(0, "A"), t(2, "day"), t(6, "in"), t(9, "Jan."), t(14, "Jan"), t(18, "2"), t(19, ","),
t(21, "2008"), t(25, ".")))},
{"", of()},
{":", of(of(t(0, ":")))},
{"foo:", of(of(t(0, "foo"), t(3, ":")))},
{"a: b", of(of(t(0, "a"), t(1, ":"), t(3, "b")))},
};
}
@Test
public void testDataProviders() {
text();
}
@Test(dataProvider = "text") | public void testProcess(final String text, final List<List<Token>> expected) { |
NICTA/nicta-ner | nicta-ner-client/src/main/java/org/t3as/ner/client/cmdline/Main.java | // Path: nicta-ner-client/src/main/java/org/t3as/ner/client/NerClient.java
// public class NerClient {
//
// public static final String DEFAULT_BASE_URL = "http://ner.t3as.org/nicta-ner-web/";
// private static final String NER_SERVICE_PATH = "rest/v1.0/ner";
//
// private final WebTarget target;
//
// public NerClient(final String url) {
// //final ClientConfig config = new DefaultClientConfig();
// //config.getClasses().add(JacksonJsonProvider.class);
// //config.getClasses().add(ObjectMapperProvider.class);
// target = ClientBuilder.newClient().register(new JacksonFeature()).target(url + NER_SERVICE_PATH);
// }
//
// public NerResultSet call(final String input) throws UnsupportedEncodingException {
// final String encodedInput = URLEncoder.encode(input, "UTF-8");
// final Response response = target.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON_TYPE)
// .post(Entity.entity(encodedInput, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
// if (Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
// final Response.StatusType statusInfo = response.getStatusInfo();
// throw new RuntimeException("NER request failed with status " + statusInfo.getStatusCode()
// + ": " + statusInfo.getReasonPhrase());
// }
// return response.readEntity(NerResultSet.class);
// }
// }
| import java.util.Collection;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.t3as.ner.client.NerClient;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList; | /*
* #%L
* NICTA t3as Named-Entity Recognition client
* %%
* Copyright (C) 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.client.cmdline;
public final class Main {
private Main() {}
@SuppressWarnings("MethodNamesDifferingOnlyByCase")
public static void main(final String[] args) throws IOException {
final Options opts = getOptions(args);
// create a web service client | // Path: nicta-ner-client/src/main/java/org/t3as/ner/client/NerClient.java
// public class NerClient {
//
// public static final String DEFAULT_BASE_URL = "http://ner.t3as.org/nicta-ner-web/";
// private static final String NER_SERVICE_PATH = "rest/v1.0/ner";
//
// private final WebTarget target;
//
// public NerClient(final String url) {
// //final ClientConfig config = new DefaultClientConfig();
// //config.getClasses().add(JacksonJsonProvider.class);
// //config.getClasses().add(ObjectMapperProvider.class);
// target = ClientBuilder.newClient().register(new JacksonFeature()).target(url + NER_SERVICE_PATH);
// }
//
// public NerResultSet call(final String input) throws UnsupportedEncodingException {
// final String encodedInput = URLEncoder.encode(input, "UTF-8");
// final Response response = target.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON_TYPE)
// .post(Entity.entity(encodedInput, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
// if (Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
// final Response.StatusType statusInfo = response.getStatusInfo();
// throw new RuntimeException("NER request failed with status " + statusInfo.getStatusCode()
// + ": " + statusInfo.getReasonPhrase());
// }
// return response.readEntity(NerResultSet.class);
// }
// }
// Path: nicta-ner-client/src/main/java/org/t3as/ner/client/cmdline/Main.java
import java.util.Collection;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.t3as.ner.client.NerClient;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/*
* #%L
* NICTA t3as Named-Entity Recognition client
* %%
* Copyright (C) 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.client.cmdline;
public final class Main {
private Main() {}
@SuppressWarnings("MethodNamesDifferingOnlyByCase")
public static void main(final String[] args) throws IOException {
final Options opts = getOptions(args);
// create a web service client | final NerClient client = new NerClient(opts.url); |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Dictionary.java | // Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import java.util.Map;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import java.io.IOException; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
public final class Dictionary {
private static final Map<String, String> dict;
static {
try { dict = IO.dictionary(Dictionary.class, "DICT"); }
catch (final IOException e) { throw new RuntimeException(e); }
}
/**
* Private constructor which creates the only dictionary instance.
* Call getDict() method to get the shared dictionary.
*/
private Dictionary() {}
public static String checkup(final String word) {
return dict.get(word);
}
/** This method checks if the word is a plural form. */
public static boolean isPlural(final String _word) { | // Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Dictionary.java
import java.util.Map;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import java.io.IOException;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
public final class Dictionary {
private static final Map<String, String> dict;
static {
try { dict = IO.dictionary(Dictionary.class, "DICT"); }
catch (final IOException e) { throw new RuntimeException(e); }
}
/**
* Private constructor which creates the only dictionary instance.
* Call getDict() method to get the shared dictionary.
*/
private Dictionary() {}
public static String checkup(final String word) {
return dict.get(word);
}
/** This method checks if the word is a plural form. */
public static boolean isPlural(final String _word) { | final String word = toEngLowerCase(_word); |
NICTA/nicta-ner | nicta-ner-client/src/main/java/org/t3as/ner/client/NerClient.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/NerResultSet.java
// public class NerResultSet {
//
// public final List<List<Token>> tokens;
// public final List<List<Phrase>> phrases;
//
// @JsonCreator
// @SuppressWarnings("AssignmentToCollectionOrArrayFieldFromParameter")
// public NerResultSet(@JsonProperty("phrases") final List<List<Phrase>> phrases,
// @JsonProperty("tokens") final List<List<Token>> tokens) {
// this.phrases = phrases;
// this.tokens = tokens;
// }
//
// /** This method returns a map format set of the result. */
// @JsonIgnore
// public Map<EntityClass, Set<String>> getMappedResult() {
// final Map<EntityClass, Set<String>> m = new HashMap<>();
// for (final List<Phrase> pa : phrases) {
// for (final Phrase p : pa) {
// Set<String> c = m.get(p.phraseType);
// if (c == null) {
// c = new HashSet<>();
// m.put(p.phraseType, c);
// }
// c.add(p.phraseString());
// }
// }
// return m;
// }
//
// public String toString() {
// final StringBuilder sb = new StringBuilder();
//
// for (int si = 0; si < tokens.size(); si++) {
// final List<Token> sentence = tokens.get(si);
// final List<Phrase> phraseList = this.phrases.get(si);
// for (final Token aSentence : sentence) sb.append(aSentence.text).append(" ");
// sb.append("\n===============================================\n");
// for (final Phrase p : phraseList) {
// String ptext = "";
// for (int wi = 0; wi < p.phrase.size(); wi++) {
// ptext += (p.phrase.get(wi).text + " ");
// }
// ptext = ptext.trim();
//
// final StringBuilder stext = new StringBuilder();
// for (final Map.Entry<EntityClass, Double> e : p.score.entrySet()) {
// if (stext.length() != 0) stext.append(", ");
// stext.append(e.getKey()).append(":").append(e.getValue());
// }
//
// // what we are trying to generate:
// // 0: John PERSON 11.25, 40.0, -10.0 null 0:0:0:1:1
//
// // 0: John\t
// sb.append(format("%s: %s\t", p.phrasePosition, ptext));
// // PERSON\t
// sb.append(format("%s\t", p.phraseType));
// // 11.25, 40.0, -10.0\t
// sb.append(format("%s\t", stext));
// // null\t
// sb.append(format("%s\t", p.attachedWordMap.get("prep")));
// // 0:0:1:1\n
// sb.append(format("%d:%d:%d:%d:%d\n", p.phrase.iterator().next().startIndex, p.phrasePosition,
// p.phraseStubPosition, p.phraseStubLength, p.phraseLength));
// }
// sb.append("\n\n");
// }
// return sb.toString();
// }
// }
| import java.net.URLEncoder;
import static javax.ws.rs.core.Response.Status.Family;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.t3as.ner.NerResultSet;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException; | /*
* #%L
* NICTA t3as Named-Entity Recognition client
* %%
* Copyright (C) 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.client;
public class NerClient {
public static final String DEFAULT_BASE_URL = "http://ner.t3as.org/nicta-ner-web/";
private static final String NER_SERVICE_PATH = "rest/v1.0/ner";
private final WebTarget target;
public NerClient(final String url) {
//final ClientConfig config = new DefaultClientConfig();
//config.getClasses().add(JacksonJsonProvider.class);
//config.getClasses().add(ObjectMapperProvider.class);
target = ClientBuilder.newClient().register(new JacksonFeature()).target(url + NER_SERVICE_PATH);
}
| // Path: nicta-ner-common/src/main/java/org/t3as/ner/NerResultSet.java
// public class NerResultSet {
//
// public final List<List<Token>> tokens;
// public final List<List<Phrase>> phrases;
//
// @JsonCreator
// @SuppressWarnings("AssignmentToCollectionOrArrayFieldFromParameter")
// public NerResultSet(@JsonProperty("phrases") final List<List<Phrase>> phrases,
// @JsonProperty("tokens") final List<List<Token>> tokens) {
// this.phrases = phrases;
// this.tokens = tokens;
// }
//
// /** This method returns a map format set of the result. */
// @JsonIgnore
// public Map<EntityClass, Set<String>> getMappedResult() {
// final Map<EntityClass, Set<String>> m = new HashMap<>();
// for (final List<Phrase> pa : phrases) {
// for (final Phrase p : pa) {
// Set<String> c = m.get(p.phraseType);
// if (c == null) {
// c = new HashSet<>();
// m.put(p.phraseType, c);
// }
// c.add(p.phraseString());
// }
// }
// return m;
// }
//
// public String toString() {
// final StringBuilder sb = new StringBuilder();
//
// for (int si = 0; si < tokens.size(); si++) {
// final List<Token> sentence = tokens.get(si);
// final List<Phrase> phraseList = this.phrases.get(si);
// for (final Token aSentence : sentence) sb.append(aSentence.text).append(" ");
// sb.append("\n===============================================\n");
// for (final Phrase p : phraseList) {
// String ptext = "";
// for (int wi = 0; wi < p.phrase.size(); wi++) {
// ptext += (p.phrase.get(wi).text + " ");
// }
// ptext = ptext.trim();
//
// final StringBuilder stext = new StringBuilder();
// for (final Map.Entry<EntityClass, Double> e : p.score.entrySet()) {
// if (stext.length() != 0) stext.append(", ");
// stext.append(e.getKey()).append(":").append(e.getValue());
// }
//
// // what we are trying to generate:
// // 0: John PERSON 11.25, 40.0, -10.0 null 0:0:0:1:1
//
// // 0: John\t
// sb.append(format("%s: %s\t", p.phrasePosition, ptext));
// // PERSON\t
// sb.append(format("%s\t", p.phraseType));
// // 11.25, 40.0, -10.0\t
// sb.append(format("%s\t", stext));
// // null\t
// sb.append(format("%s\t", p.attachedWordMap.get("prep")));
// // 0:0:1:1\n
// sb.append(format("%d:%d:%d:%d:%d\n", p.phrase.iterator().next().startIndex, p.phrasePosition,
// p.phraseStubPosition, p.phraseStubLength, p.phraseLength));
// }
// sb.append("\n\n");
// }
// return sb.toString();
// }
// }
// Path: nicta-ner-client/src/main/java/org/t3as/ner/client/NerClient.java
import java.net.URLEncoder;
import static javax.ws.rs.core.Response.Status.Family;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.t3as.ner.NerResultSet;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
/*
* #%L
* NICTA t3as Named-Entity Recognition client
* %%
* Copyright (C) 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.client;
public class NerClient {
public static final String DEFAULT_BASE_URL = "http://ner.t3as.org/nicta-ner-web/";
private static final String NER_SERVICE_PATH = "rest/v1.0/ner";
private final WebTarget target;
public NerClient(final String url) {
//final ClientConfig config = new DefaultClientConfig();
//config.getClasses().add(JacksonJsonProvider.class);
//config.getClasses().add(ObjectMapperProvider.class);
target = ClientBuilder.newClient().register(new JacksonFeature()).target(url + NER_SERVICE_PATH);
}
| public NerResultSet call(final String input) throws UnsupportedEncodingException { |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/classifier/feature/FeatureMap.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public class EntityClass {
//
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
// public static final EntityClass DATE = new EntityClass("DATE");
//
// private final String entityClass;
//
// @JsonCreator
// public EntityClass(@JsonProperty("entityClass") final String entityClass) { this.entityClass = entityClass; }
//
// // required for JSON
// @SuppressWarnings("UnusedDeclaration")
// public String getEntityClass() { return entityClass; }
//
// @Override
// public String toString() { return entityClass; }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final EntityClass that = (EntityClass) o;
// return entityClass.equals(that.entityClass);
// }
//
// @Override
// public int hashCode() { return entityClass.hashCode(); }
// }
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/Phrase.java
// public class Phrase {
// // TODO: getters and setters for these
// /** phrase text array */
// public final List<Token> phrase;
// /** corresponding name type */
// public EntityClass phraseType;
// /** the start position of the phase in a sentence */
// public final int phrasePosition;
// /** the length of the phrase */
// public final int phraseLength;
// /** the start position of the phrase stub in a sentence */
// public final int phraseStubPosition;
// /** the length of the phrase stub */
// public final int phraseStubLength;
// /** score array, dimension equals to name type array */
// public Map<EntityClass, Double> score = new LinkedHashMap<>();
// /** attached word map */
// public Map<String, String> attachedWordMap;
// /** true if the phrase is a date; false if not */
// public boolean isDate;
//
// @JsonCreator
// public Phrase(@JsonProperty("phrase") final List<Token> tokens,
// @JsonProperty("phrasePosition") final int _phrasePos,
// @JsonProperty("phraseLength") final int _phraseLen,
// @JsonProperty("phraseStubPosition") final int _stubPos,
// @JsonProperty("phraseType") final EntityClass type) {
// phrasePosition = _phrasePos;
// phraseLength = _phraseLen;
// phrase = ImmutableList.copyOf(tokens);
// phraseType = type;
// attachedWordMap = new HashMap<>();
// phraseStubPosition = _stubPos;
// phraseStubLength = phrase.size();
// }
//
// public String phraseString() {
// final StringBuilder sb = new StringBuilder();
// for (final Token aPhrase : phrase) sb.append(aPhrase.text).append(" ");
// return sb.toString().trim();
// }
//
// /** Test if the phrase is a sub phrase of the input phrase. */
// public boolean isSubPhraseOf(final Phrase other) {
// if (phrase.isEmpty()) return false;
//
// // TODO: this should be refactored - the intent is not clear, implementation is sketchy
// boolean is = false;
// for (int i = 0; i < other.phrase.size() - phrase.size() + 1; i++) {
// boolean flag = true;
// for (int j = 0; j < phrase.size(); j++) {
// if (!phrase.get(j).text.equalsIgnoreCase(other.phrase.get(i + j).text)) {
// flag = false;
// break;
// }
// }
// if (flag) {
// is = true;
// break;
// }
// }
// return is;
// }
//
// /** This method will do the classification of a Phrase with a EntityClass. */
// public void classify() {
// EntityClass type = null;
// double s = 0;
// boolean ambiguous = false;
// for (final Map.Entry<EntityClass, Double> e : score.entrySet()) {
// if (type == null) {
// type = e.getKey();
// s = e.getValue();
// }
// else {
// if (Double.compare(e.getValue(), s) > 0) {
// type = e.getKey();
// s = e.getValue();
// ambiguous = false;
// }
// else if (Double.compare(s, e.getValue()) == 0) {
// ambiguous = true;
// }
// }
// }
// this.phraseType = ambiguous ? UNKNOWN : type;
// }
//
// @Override
// public String toString() {
// return "Phrase{" +
// "phrase=" + phrase +
// ", phraseType=" + phraseType +
// ", phrasePosition=" + phrasePosition +
// ", phraseLength=" + phraseLength +
// ", phraseStubPosition=" + phraseStubPosition +
// ", phraseStubLength=" + phraseStubLength +
// ", score=" + score.toString() +
// ", attachedWordMap=" + attachedWordMap +
// ", isDate=" + isDate +
// '}';
// }
// }
| import org.t3as.ner.EntityClass;
import org.t3as.ner.Phrase;
import javax.annotation.concurrent.Immutable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.classifier.feature;
@Immutable
public class FeatureMap {
| // Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public class EntityClass {
//
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
// public static final EntityClass DATE = new EntityClass("DATE");
//
// private final String entityClass;
//
// @JsonCreator
// public EntityClass(@JsonProperty("entityClass") final String entityClass) { this.entityClass = entityClass; }
//
// // required for JSON
// @SuppressWarnings("UnusedDeclaration")
// public String getEntityClass() { return entityClass; }
//
// @Override
// public String toString() { return entityClass; }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final EntityClass that = (EntityClass) o;
// return entityClass.equals(that.entityClass);
// }
//
// @Override
// public int hashCode() { return entityClass.hashCode(); }
// }
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/Phrase.java
// public class Phrase {
// // TODO: getters and setters for these
// /** phrase text array */
// public final List<Token> phrase;
// /** corresponding name type */
// public EntityClass phraseType;
// /** the start position of the phase in a sentence */
// public final int phrasePosition;
// /** the length of the phrase */
// public final int phraseLength;
// /** the start position of the phrase stub in a sentence */
// public final int phraseStubPosition;
// /** the length of the phrase stub */
// public final int phraseStubLength;
// /** score array, dimension equals to name type array */
// public Map<EntityClass, Double> score = new LinkedHashMap<>();
// /** attached word map */
// public Map<String, String> attachedWordMap;
// /** true if the phrase is a date; false if not */
// public boolean isDate;
//
// @JsonCreator
// public Phrase(@JsonProperty("phrase") final List<Token> tokens,
// @JsonProperty("phrasePosition") final int _phrasePos,
// @JsonProperty("phraseLength") final int _phraseLen,
// @JsonProperty("phraseStubPosition") final int _stubPos,
// @JsonProperty("phraseType") final EntityClass type) {
// phrasePosition = _phrasePos;
// phraseLength = _phraseLen;
// phrase = ImmutableList.copyOf(tokens);
// phraseType = type;
// attachedWordMap = new HashMap<>();
// phraseStubPosition = _stubPos;
// phraseStubLength = phrase.size();
// }
//
// public String phraseString() {
// final StringBuilder sb = new StringBuilder();
// for (final Token aPhrase : phrase) sb.append(aPhrase.text).append(" ");
// return sb.toString().trim();
// }
//
// /** Test if the phrase is a sub phrase of the input phrase. */
// public boolean isSubPhraseOf(final Phrase other) {
// if (phrase.isEmpty()) return false;
//
// // TODO: this should be refactored - the intent is not clear, implementation is sketchy
// boolean is = false;
// for (int i = 0; i < other.phrase.size() - phrase.size() + 1; i++) {
// boolean flag = true;
// for (int j = 0; j < phrase.size(); j++) {
// if (!phrase.get(j).text.equalsIgnoreCase(other.phrase.get(i + j).text)) {
// flag = false;
// break;
// }
// }
// if (flag) {
// is = true;
// break;
// }
// }
// return is;
// }
//
// /** This method will do the classification of a Phrase with a EntityClass. */
// public void classify() {
// EntityClass type = null;
// double s = 0;
// boolean ambiguous = false;
// for (final Map.Entry<EntityClass, Double> e : score.entrySet()) {
// if (type == null) {
// type = e.getKey();
// s = e.getValue();
// }
// else {
// if (Double.compare(e.getValue(), s) > 0) {
// type = e.getKey();
// s = e.getValue();
// ambiguous = false;
// }
// else if (Double.compare(s, e.getValue()) == 0) {
// ambiguous = true;
// }
// }
// }
// this.phraseType = ambiguous ? UNKNOWN : type;
// }
//
// @Override
// public String toString() {
// return "Phrase{" +
// "phrase=" + phrase +
// ", phraseType=" + phraseType +
// ", phrasePosition=" + phrasePosition +
// ", phraseLength=" + phraseLength +
// ", phraseStubPosition=" + phraseStubPosition +
// ", phraseStubLength=" + phraseStubLength +
// ", score=" + score.toString() +
// ", attachedWordMap=" + attachedWordMap +
// ", isDate=" + isDate +
// '}';
// }
// }
// Path: nicta-ner/src/main/java/org/t3as/ner/classifier/feature/FeatureMap.java
import org.t3as.ner.EntityClass;
import org.t3as.ner.Phrase;
import javax.annotation.concurrent.Immutable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.classifier.feature;
@Immutable
public class FeatureMap {
| private final Map<EntityClass, List<Feature>> featureMap = new LinkedHashMap<>(); |
NICTA/nicta-ner | nicta-ner/src/test/java/org/t3as/ner/NamedEntityAnalyserTest.java | // Path: nicta-ner/src/main/java/org/t3as/ner/resource/Configuration.java
// @Immutable
// public class Configuration {
//
// public static final String DEFAULT_CONFIG_RESOURCE = "config";
//
// public final boolean tracing;
// private final FeatureMap featureMap;
//
// public Configuration() throws IOException, InterruptedException { this(false); }
//
// public Configuration(final boolean tracing) throws IOException, InterruptedException {
// this(Configuration.class.getResourceAsStream(DEFAULT_CONFIG_RESOURCE), tracing);
// }
//
// /** Constructor. Read in the config file. */
// public Configuration(final InputStream config, final boolean tracing) throws IOException, InterruptedException {
// this.tracing = tracing;
// final Pattern COLONS = Pattern.compile(":");
// final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
// final ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//
// featureMap = new FeatureMap(tracing);
//
// try (final BufferedReader br = new BufferedReader(new InputStreamReader(config))) {
//
// for (String line; (line = br.readLine()) != null; ) {
// final String s = line.trim();
// if (s.startsWith("#")) continue;
// if (s.trim().isEmpty()) continue;
//
// final String[] parts = COLONS.split(s, 2);
// switch (parts[0]) {
// case "Feature":
// final List<String> l = SPACES.limit(4).splitToList(parts[1]);
// final String featureType = l.get(0);
// final String entityType = l.get(1);
// final int weight = Integer.parseInt(l.get(2));
// final List<String> resourceNames = SPACES.splitToList(l.get(3));
// final Feature f = Feature.generateFeatureByName(featureType, weight, resourceNames);
// featureMap.addFeature(entityType, f);
// exec.execute(new FeatureInitialiserRunnable(f));
// break;
//
// default:
// throw new IllegalArgumentException("Unexpected config keyword: '" + parts[0] + "'");
// }
// }
// }
// exec.shutdown();
// exec.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
// }
//
// public FeatureMap getFeatureMap() { return featureMap; }
//
// private static class FeatureInitialiserRunnable implements Runnable {
//
// final Feature f;
//
// FeatureInitialiserRunnable(final Feature f) { this.f = f; }
//
// @Override
// public void run() {
// final String s = Objects.toStringHelper(f)
// .add("weight", f.getWeight())
// .add("resources", f.getResources())
// .toString();
// try { f.loadResources(); }
// catch (final IOException e) { throw new RuntimeException("Could not load resources for feature: " + s, e); }
// }
// }
// }
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass DATE = new EntityClass("DATE");
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.collect.ImmutableMap.of;
import static org.t3as.ner.EntityClass.DATE;
import static org.t3as.ner.EntityClass.UNKNOWN;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import org.t3as.ner.resource.Configuration;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner;
public class NamedEntityAnalyserTest {
static final EntityClass PER = new EntityClass("PERSON");
static final EntityClass ORG = new EntityClass("ORGANIZATION");
static final EntityClass LOC = new EntityClass("LOCATION");
static final EntityClass ETH = new EntityClass("ETHNIC");
private NamedEntityAnalyser namedEntityAnalyser;
/**
* NOTE: as can be seen in the results of this test there are lots of places where the NER can be improved!
*/
@SuppressWarnings("MagicNumber")
@DataProvider(name = "testProcess")
public static Object[][] primeNumbers() throws IOException {
return new Object[][]{
{"John",
new ArrayList<Result>() {{
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
}}},
{"John and Jane Doe Doe live in New Zealand in November.",
new ArrayList<Result>() {{
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
add(new Result("Jane Doe Doe", PER, of(LOC, 12.0, PER, 30.0, ORG, 15.0, ETH, 0.0), none()));
add(new Result("New Zealand", LOC, of(LOC, 47.0, PER, 8.75, ORG, 31.0, ETH, 15.0),
of("prep", "in"))); | // Path: nicta-ner/src/main/java/org/t3as/ner/resource/Configuration.java
// @Immutable
// public class Configuration {
//
// public static final String DEFAULT_CONFIG_RESOURCE = "config";
//
// public final boolean tracing;
// private final FeatureMap featureMap;
//
// public Configuration() throws IOException, InterruptedException { this(false); }
//
// public Configuration(final boolean tracing) throws IOException, InterruptedException {
// this(Configuration.class.getResourceAsStream(DEFAULT_CONFIG_RESOURCE), tracing);
// }
//
// /** Constructor. Read in the config file. */
// public Configuration(final InputStream config, final boolean tracing) throws IOException, InterruptedException {
// this.tracing = tracing;
// final Pattern COLONS = Pattern.compile(":");
// final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
// final ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//
// featureMap = new FeatureMap(tracing);
//
// try (final BufferedReader br = new BufferedReader(new InputStreamReader(config))) {
//
// for (String line; (line = br.readLine()) != null; ) {
// final String s = line.trim();
// if (s.startsWith("#")) continue;
// if (s.trim().isEmpty()) continue;
//
// final String[] parts = COLONS.split(s, 2);
// switch (parts[0]) {
// case "Feature":
// final List<String> l = SPACES.limit(4).splitToList(parts[1]);
// final String featureType = l.get(0);
// final String entityType = l.get(1);
// final int weight = Integer.parseInt(l.get(2));
// final List<String> resourceNames = SPACES.splitToList(l.get(3));
// final Feature f = Feature.generateFeatureByName(featureType, weight, resourceNames);
// featureMap.addFeature(entityType, f);
// exec.execute(new FeatureInitialiserRunnable(f));
// break;
//
// default:
// throw new IllegalArgumentException("Unexpected config keyword: '" + parts[0] + "'");
// }
// }
// }
// exec.shutdown();
// exec.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
// }
//
// public FeatureMap getFeatureMap() { return featureMap; }
//
// private static class FeatureInitialiserRunnable implements Runnable {
//
// final Feature f;
//
// FeatureInitialiserRunnable(final Feature f) { this.f = f; }
//
// @Override
// public void run() {
// final String s = Objects.toStringHelper(f)
// .add("weight", f.getWeight())
// .add("resources", f.getResources())
// .toString();
// try { f.loadResources(); }
// catch (final IOException e) { throw new RuntimeException("Could not load resources for feature: " + s, e); }
// }
// }
// }
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass DATE = new EntityClass("DATE");
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
// Path: nicta-ner/src/test/java/org/t3as/ner/NamedEntityAnalyserTest.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.collect.ImmutableMap.of;
import static org.t3as.ner.EntityClass.DATE;
import static org.t3as.ner.EntityClass.UNKNOWN;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import org.t3as.ner.resource.Configuration;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner;
public class NamedEntityAnalyserTest {
static final EntityClass PER = new EntityClass("PERSON");
static final EntityClass ORG = new EntityClass("ORGANIZATION");
static final EntityClass LOC = new EntityClass("LOCATION");
static final EntityClass ETH = new EntityClass("ETHNIC");
private NamedEntityAnalyser namedEntityAnalyser;
/**
* NOTE: as can be seen in the results of this test there are lots of places where the NER can be improved!
*/
@SuppressWarnings("MagicNumber")
@DataProvider(name = "testProcess")
public static Object[][] primeNumbers() throws IOException {
return new Object[][]{
{"John",
new ArrayList<Result>() {{
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
}}},
{"John and Jane Doe Doe live in New Zealand in November.",
new ArrayList<Result>() {{
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
add(new Result("Jane Doe Doe", PER, of(LOC, 12.0, PER, 30.0, ORG, 15.0, ETH, 0.0), none()));
add(new Result("New Zealand", LOC, of(LOC, 47.0, PER, 8.75, ORG, 31.0, ETH, 15.0),
of("prep", "in"))); | add(new Result("November", DATE, ImmutableMap.<EntityClass, Double>of(), of("prep", "in"))); |
NICTA/nicta-ner | nicta-ner/src/test/java/org/t3as/ner/NamedEntityAnalyserTest.java | // Path: nicta-ner/src/main/java/org/t3as/ner/resource/Configuration.java
// @Immutable
// public class Configuration {
//
// public static final String DEFAULT_CONFIG_RESOURCE = "config";
//
// public final boolean tracing;
// private final FeatureMap featureMap;
//
// public Configuration() throws IOException, InterruptedException { this(false); }
//
// public Configuration(final boolean tracing) throws IOException, InterruptedException {
// this(Configuration.class.getResourceAsStream(DEFAULT_CONFIG_RESOURCE), tracing);
// }
//
// /** Constructor. Read in the config file. */
// public Configuration(final InputStream config, final boolean tracing) throws IOException, InterruptedException {
// this.tracing = tracing;
// final Pattern COLONS = Pattern.compile(":");
// final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
// final ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//
// featureMap = new FeatureMap(tracing);
//
// try (final BufferedReader br = new BufferedReader(new InputStreamReader(config))) {
//
// for (String line; (line = br.readLine()) != null; ) {
// final String s = line.trim();
// if (s.startsWith("#")) continue;
// if (s.trim().isEmpty()) continue;
//
// final String[] parts = COLONS.split(s, 2);
// switch (parts[0]) {
// case "Feature":
// final List<String> l = SPACES.limit(4).splitToList(parts[1]);
// final String featureType = l.get(0);
// final String entityType = l.get(1);
// final int weight = Integer.parseInt(l.get(2));
// final List<String> resourceNames = SPACES.splitToList(l.get(3));
// final Feature f = Feature.generateFeatureByName(featureType, weight, resourceNames);
// featureMap.addFeature(entityType, f);
// exec.execute(new FeatureInitialiserRunnable(f));
// break;
//
// default:
// throw new IllegalArgumentException("Unexpected config keyword: '" + parts[0] + "'");
// }
// }
// }
// exec.shutdown();
// exec.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
// }
//
// public FeatureMap getFeatureMap() { return featureMap; }
//
// private static class FeatureInitialiserRunnable implements Runnable {
//
// final Feature f;
//
// FeatureInitialiserRunnable(final Feature f) { this.f = f; }
//
// @Override
// public void run() {
// final String s = Objects.toStringHelper(f)
// .add("weight", f.getWeight())
// .add("resources", f.getResources())
// .toString();
// try { f.loadResources(); }
// catch (final IOException e) { throw new RuntimeException("Could not load resources for feature: " + s, e); }
// }
// }
// }
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass DATE = new EntityClass("DATE");
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.collect.ImmutableMap.of;
import static org.t3as.ner.EntityClass.DATE;
import static org.t3as.ner.EntityClass.UNKNOWN;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import org.t3as.ner.resource.Configuration;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths; | */
@SuppressWarnings("MagicNumber")
@DataProvider(name = "testProcess")
public static Object[][] primeNumbers() throws IOException {
return new Object[][]{
{"John",
new ArrayList<Result>() {{
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
}}},
{"John and Jane Doe Doe live in New Zealand in November.",
new ArrayList<Result>() {{
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
add(new Result("Jane Doe Doe", PER, of(LOC, 12.0, PER, 30.0, ORG, 15.0, ETH, 0.0), none()));
add(new Result("New Zealand", LOC, of(LOC, 47.0, PER, 8.75, ORG, 31.0, ETH, 15.0),
of("prep", "in")));
add(new Result("November", DATE, ImmutableMap.<EntityClass, Double>of(), of("prep", "in")));
}}},
{"Jim bought 300 shares of Acme Corp. in 2006.",
new ArrayList<Result>() {{
add(new Result("Jim", PER, of(LOC, 3.0, PER, 7.5, ORG, 7.0, ETH, 0.0), none()));
add(new Result("Acme Corp", ORG, of(LOC, 9.0, PER, 6.5, ORG, 14.0, ETH, 0.0), of("prep", "of")));
add(new Result("2006", DATE, ImmutableMap.<EntityClass, Double>of(), of("prep", "in")));
}}},
{"Næsby is in Denmark, as is Næsbyholm Slot, which is outside the town of Glumsø.",
new ArrayList<Result>() {{
add(new Result("Næsby", ORG, of(LOC, 0.0, PER, 1.5, ORG, 4.0, ETH, 0.0), none()));
add(new Result("Denmark", LOC, of(LOC, 17.0, PER, 6.0, ORG, 7.0, ETH, 0.0), of("prep", "in"))); | // Path: nicta-ner/src/main/java/org/t3as/ner/resource/Configuration.java
// @Immutable
// public class Configuration {
//
// public static final String DEFAULT_CONFIG_RESOURCE = "config";
//
// public final boolean tracing;
// private final FeatureMap featureMap;
//
// public Configuration() throws IOException, InterruptedException { this(false); }
//
// public Configuration(final boolean tracing) throws IOException, InterruptedException {
// this(Configuration.class.getResourceAsStream(DEFAULT_CONFIG_RESOURCE), tracing);
// }
//
// /** Constructor. Read in the config file. */
// public Configuration(final InputStream config, final boolean tracing) throws IOException, InterruptedException {
// this.tracing = tracing;
// final Pattern COLONS = Pattern.compile(":");
// final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
// final ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//
// featureMap = new FeatureMap(tracing);
//
// try (final BufferedReader br = new BufferedReader(new InputStreamReader(config))) {
//
// for (String line; (line = br.readLine()) != null; ) {
// final String s = line.trim();
// if (s.startsWith("#")) continue;
// if (s.trim().isEmpty()) continue;
//
// final String[] parts = COLONS.split(s, 2);
// switch (parts[0]) {
// case "Feature":
// final List<String> l = SPACES.limit(4).splitToList(parts[1]);
// final String featureType = l.get(0);
// final String entityType = l.get(1);
// final int weight = Integer.parseInt(l.get(2));
// final List<String> resourceNames = SPACES.splitToList(l.get(3));
// final Feature f = Feature.generateFeatureByName(featureType, weight, resourceNames);
// featureMap.addFeature(entityType, f);
// exec.execute(new FeatureInitialiserRunnable(f));
// break;
//
// default:
// throw new IllegalArgumentException("Unexpected config keyword: '" + parts[0] + "'");
// }
// }
// }
// exec.shutdown();
// exec.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
// }
//
// public FeatureMap getFeatureMap() { return featureMap; }
//
// private static class FeatureInitialiserRunnable implements Runnable {
//
// final Feature f;
//
// FeatureInitialiserRunnable(final Feature f) { this.f = f; }
//
// @Override
// public void run() {
// final String s = Objects.toStringHelper(f)
// .add("weight", f.getWeight())
// .add("resources", f.getResources())
// .toString();
// try { f.loadResources(); }
// catch (final IOException e) { throw new RuntimeException("Could not load resources for feature: " + s, e); }
// }
// }
// }
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass DATE = new EntityClass("DATE");
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
// Path: nicta-ner/src/test/java/org/t3as/ner/NamedEntityAnalyserTest.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.collect.ImmutableMap.of;
import static org.t3as.ner.EntityClass.DATE;
import static org.t3as.ner.EntityClass.UNKNOWN;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import org.t3as.ner.resource.Configuration;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
*/
@SuppressWarnings("MagicNumber")
@DataProvider(name = "testProcess")
public static Object[][] primeNumbers() throws IOException {
return new Object[][]{
{"John",
new ArrayList<Result>() {{
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
}}},
{"John and Jane Doe Doe live in New Zealand in November.",
new ArrayList<Result>() {{
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
add(new Result("Jane Doe Doe", PER, of(LOC, 12.0, PER, 30.0, ORG, 15.0, ETH, 0.0), none()));
add(new Result("New Zealand", LOC, of(LOC, 47.0, PER, 8.75, ORG, 31.0, ETH, 15.0),
of("prep", "in")));
add(new Result("November", DATE, ImmutableMap.<EntityClass, Double>of(), of("prep", "in")));
}}},
{"Jim bought 300 shares of Acme Corp. in 2006.",
new ArrayList<Result>() {{
add(new Result("Jim", PER, of(LOC, 3.0, PER, 7.5, ORG, 7.0, ETH, 0.0), none()));
add(new Result("Acme Corp", ORG, of(LOC, 9.0, PER, 6.5, ORG, 14.0, ETH, 0.0), of("prep", "of")));
add(new Result("2006", DATE, ImmutableMap.<EntityClass, Double>of(), of("prep", "in")));
}}},
{"Næsby is in Denmark, as is Næsbyholm Slot, which is outside the town of Glumsø.",
new ArrayList<Result>() {{
add(new Result("Næsby", ORG, of(LOC, 0.0, PER, 1.5, ORG, 4.0, ETH, 0.0), none()));
add(new Result("Denmark", LOC, of(LOC, 17.0, PER, 6.0, ORG, 7.0, ETH, 0.0), of("prep", "in"))); | add(new Result("Næsbyholm Slot", UNKNOWN, of(LOC, 3.0, PER, 5.0, ORG, 5.0, ETH, 0.0), none())); |
NICTA/nicta-ner | nicta-ner/src/test/java/org/t3as/ner/NamedEntityAnalyserTest.java | // Path: nicta-ner/src/main/java/org/t3as/ner/resource/Configuration.java
// @Immutable
// public class Configuration {
//
// public static final String DEFAULT_CONFIG_RESOURCE = "config";
//
// public final boolean tracing;
// private final FeatureMap featureMap;
//
// public Configuration() throws IOException, InterruptedException { this(false); }
//
// public Configuration(final boolean tracing) throws IOException, InterruptedException {
// this(Configuration.class.getResourceAsStream(DEFAULT_CONFIG_RESOURCE), tracing);
// }
//
// /** Constructor. Read in the config file. */
// public Configuration(final InputStream config, final boolean tracing) throws IOException, InterruptedException {
// this.tracing = tracing;
// final Pattern COLONS = Pattern.compile(":");
// final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
// final ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//
// featureMap = new FeatureMap(tracing);
//
// try (final BufferedReader br = new BufferedReader(new InputStreamReader(config))) {
//
// for (String line; (line = br.readLine()) != null; ) {
// final String s = line.trim();
// if (s.startsWith("#")) continue;
// if (s.trim().isEmpty()) continue;
//
// final String[] parts = COLONS.split(s, 2);
// switch (parts[0]) {
// case "Feature":
// final List<String> l = SPACES.limit(4).splitToList(parts[1]);
// final String featureType = l.get(0);
// final String entityType = l.get(1);
// final int weight = Integer.parseInt(l.get(2));
// final List<String> resourceNames = SPACES.splitToList(l.get(3));
// final Feature f = Feature.generateFeatureByName(featureType, weight, resourceNames);
// featureMap.addFeature(entityType, f);
// exec.execute(new FeatureInitialiserRunnable(f));
// break;
//
// default:
// throw new IllegalArgumentException("Unexpected config keyword: '" + parts[0] + "'");
// }
// }
// }
// exec.shutdown();
// exec.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
// }
//
// public FeatureMap getFeatureMap() { return featureMap; }
//
// private static class FeatureInitialiserRunnable implements Runnable {
//
// final Feature f;
//
// FeatureInitialiserRunnable(final Feature f) { this.f = f; }
//
// @Override
// public void run() {
// final String s = Objects.toStringHelper(f)
// .add("weight", f.getWeight())
// .add("resources", f.getResources())
// .toString();
// try { f.loadResources(); }
// catch (final IOException e) { throw new RuntimeException("Could not load resources for feature: " + s, e); }
// }
// }
// }
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass DATE = new EntityClass("DATE");
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.collect.ImmutableMap.of;
import static org.t3as.ner.EntityClass.DATE;
import static org.t3as.ner.EntityClass.UNKNOWN;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import org.t3as.ner.resource.Configuration;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths; | //When it is December 7th.
add(new Result("December 7th", DATE, ImmutableMap.<EntityClass, Double>of(), none()));
//Sometime in February.
add(new Result("February", DATE, ImmutableMap.<EntityClass, Double>of(), of("prep", "in")));
//It is now 2014.
add(new Result("2014", DATE, ImmutableMap.<EntityClass, Double>of(), none()));
//Some date 2014-05-21.
add(new Result("2014", DATE, ImmutableMap.<EntityClass, Double>of(), none()));
//It happened in 200 BC.
add(new Result("BC", LOC, of(LOC, 8.0, PER, 3.75, ORG, 4.0, ETH, 0.0), none()));
//Around 2am, then at 4pm, and also 17:00.
add(new Result("17:00", DATE, ImmutableMap.<EntityClass, Double>of(), none()));
}}},
{"John Smith, John.",
new ArrayList<Result>() {{
add(new Result("John Smith", PER, of(LOC, 12.0, PER, 39.5, ORG, 18.0, ETH, 0.0), none()));
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
}}},
// TODO: add these tests
// BC , British Columbia - this conflicts with 'years BC'...
// TX , Texas
// should AM/PM conflict?
// other locations
};
}
@BeforeClass
public void init() throws IOException, InterruptedException { | // Path: nicta-ner/src/main/java/org/t3as/ner/resource/Configuration.java
// @Immutable
// public class Configuration {
//
// public static final String DEFAULT_CONFIG_RESOURCE = "config";
//
// public final boolean tracing;
// private final FeatureMap featureMap;
//
// public Configuration() throws IOException, InterruptedException { this(false); }
//
// public Configuration(final boolean tracing) throws IOException, InterruptedException {
// this(Configuration.class.getResourceAsStream(DEFAULT_CONFIG_RESOURCE), tracing);
// }
//
// /** Constructor. Read in the config file. */
// public Configuration(final InputStream config, final boolean tracing) throws IOException, InterruptedException {
// this.tracing = tracing;
// final Pattern COLONS = Pattern.compile(":");
// final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
// final ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//
// featureMap = new FeatureMap(tracing);
//
// try (final BufferedReader br = new BufferedReader(new InputStreamReader(config))) {
//
// for (String line; (line = br.readLine()) != null; ) {
// final String s = line.trim();
// if (s.startsWith("#")) continue;
// if (s.trim().isEmpty()) continue;
//
// final String[] parts = COLONS.split(s, 2);
// switch (parts[0]) {
// case "Feature":
// final List<String> l = SPACES.limit(4).splitToList(parts[1]);
// final String featureType = l.get(0);
// final String entityType = l.get(1);
// final int weight = Integer.parseInt(l.get(2));
// final List<String> resourceNames = SPACES.splitToList(l.get(3));
// final Feature f = Feature.generateFeatureByName(featureType, weight, resourceNames);
// featureMap.addFeature(entityType, f);
// exec.execute(new FeatureInitialiserRunnable(f));
// break;
//
// default:
// throw new IllegalArgumentException("Unexpected config keyword: '" + parts[0] + "'");
// }
// }
// }
// exec.shutdown();
// exec.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
// }
//
// public FeatureMap getFeatureMap() { return featureMap; }
//
// private static class FeatureInitialiserRunnable implements Runnable {
//
// final Feature f;
//
// FeatureInitialiserRunnable(final Feature f) { this.f = f; }
//
// @Override
// public void run() {
// final String s = Objects.toStringHelper(f)
// .add("weight", f.getWeight())
// .add("resources", f.getResources())
// .toString();
// try { f.loadResources(); }
// catch (final IOException e) { throw new RuntimeException("Could not load resources for feature: " + s, e); }
// }
// }
// }
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass DATE = new EntityClass("DATE");
//
// Path: nicta-ner-common/src/main/java/org/t3as/ner/EntityClass.java
// public static final EntityClass UNKNOWN = new EntityClass("UNKNOWN");
// Path: nicta-ner/src/test/java/org/t3as/ner/NamedEntityAnalyserTest.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.collect.ImmutableMap.of;
import static org.t3as.ner.EntityClass.DATE;
import static org.t3as.ner.EntityClass.UNKNOWN;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import org.t3as.ner.resource.Configuration;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
//When it is December 7th.
add(new Result("December 7th", DATE, ImmutableMap.<EntityClass, Double>of(), none()));
//Sometime in February.
add(new Result("February", DATE, ImmutableMap.<EntityClass, Double>of(), of("prep", "in")));
//It is now 2014.
add(new Result("2014", DATE, ImmutableMap.<EntityClass, Double>of(), none()));
//Some date 2014-05-21.
add(new Result("2014", DATE, ImmutableMap.<EntityClass, Double>of(), none()));
//It happened in 200 BC.
add(new Result("BC", LOC, of(LOC, 8.0, PER, 3.75, ORG, 4.0, ETH, 0.0), none()));
//Around 2am, then at 4pm, and also 17:00.
add(new Result("17:00", DATE, ImmutableMap.<EntityClass, Double>of(), none()));
}}},
{"John Smith, John.",
new ArrayList<Result>() {{
add(new Result("John Smith", PER, of(LOC, 12.0, PER, 39.5, ORG, 18.0, ETH, 0.0), none()));
add(new Result("John", ORG, of(LOC, 6.0, PER, 7.5, ORG, 11.0, ETH, 0.0), none()));
}}},
// TODO: add these tests
// BC , British Columbia - this conflicts with 'years BC'...
// TX , Texas
// should AM/PM conflict?
// other locations
};
}
@BeforeClass
public void init() throws IOException, InterruptedException { | this.namedEntityAnalyser = new NamedEntityAnalyser(new Configuration()); |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/IO.java | // Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String clean(final String s) { return CLEAN.matcher(s).replaceAll(""); }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// @SuppressWarnings("ReturnOfNull")
// public static String simplify(final String s) {
// if (s == null) return null;
// final String s1 = Normalizer.normalize(s, Normalizer.Form.NFC);
// return s1.trim();
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import java.util.List;
import java.util.Set;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.io.Resources.getResource;
import static com.google.common.io.Resources.readLines;
import static org.t3as.ner.util.Strings.clean;
import static org.t3as.ner.util.Strings.simplify;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.LineProcessor;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
public final class IO {
private static final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
private static final Splitter TABS = Splitter.on('\t').trimResults().omitEmptyStrings();
private IO() {}
/** Return a Set containing trimmed lowercaseLines read from a file, skipping comments. */
public static Set<String> lowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) { | // Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String clean(final String s) { return CLEAN.matcher(s).replaceAll(""); }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// @SuppressWarnings("ReturnOfNull")
// public static String simplify(final String s) {
// if (s == null) return null;
// final String s1 = Normalizer.normalize(s, Normalizer.Form.NFC);
// return s1.trim();
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/IO.java
import java.util.List;
import java.util.Set;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.io.Resources.getResource;
import static com.google.common.io.Resources.readLines;
import static org.t3as.ner.util.Strings.clean;
import static org.t3as.ner.util.Strings.simplify;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.LineProcessor;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
public final class IO {
private static final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
private static final Splitter TABS = Splitter.on('\t').trimResults().omitEmptyStrings();
private IO() {}
/** Return a Set containing trimmed lowercaseLines read from a file, skipping comments. */
public static Set<String> lowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) { | final String l = simplify(line); |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/IO.java | // Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String clean(final String s) { return CLEAN.matcher(s).replaceAll(""); }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// @SuppressWarnings("ReturnOfNull")
// public static String simplify(final String s) {
// if (s == null) return null;
// final String s1 = Normalizer.normalize(s, Normalizer.Form.NFC);
// return s1.trim();
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import java.util.List;
import java.util.Set;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.io.Resources.getResource;
import static com.google.common.io.Resources.readLines;
import static org.t3as.ner.util.Strings.clean;
import static org.t3as.ner.util.Strings.simplify;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.LineProcessor;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
public final class IO {
private static final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
private static final Splitter TABS = Splitter.on('\t').trimResults().omitEmptyStrings();
private IO() {}
/** Return a Set containing trimmed lowercaseLines read from a file, skipping comments. */
public static Set<String> lowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of | // Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String clean(final String s) { return CLEAN.matcher(s).replaceAll(""); }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// @SuppressWarnings("ReturnOfNull")
// public static String simplify(final String s) {
// if (s == null) return null;
// final String s1 = Normalizer.normalize(s, Normalizer.Form.NFC);
// return s1.trim();
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/IO.java
import java.util.List;
import java.util.Set;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.io.Resources.getResource;
import static com.google.common.io.Resources.readLines;
import static org.t3as.ner.util.Strings.clean;
import static org.t3as.ner.util.Strings.simplify;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.LineProcessor;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
public final class IO {
private static final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
private static final Splitter TABS = Splitter.on('\t').trimResults().omitEmptyStrings();
private IO() {}
/** Return a Set containing trimmed lowercaseLines read from a file, skipping comments. */
public static Set<String> lowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of | if (!l.startsWith("#") && !l.isEmpty()) add(toEngLowerCase(l)); |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/IO.java | // Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String clean(final String s) { return CLEAN.matcher(s).replaceAll(""); }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// @SuppressWarnings("ReturnOfNull")
// public static String simplify(final String s) {
// if (s == null) return null;
// final String s1 = Normalizer.normalize(s, Normalizer.Form.NFC);
// return s1.trim();
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import java.util.List;
import java.util.Set;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.io.Resources.getResource;
import static com.google.common.io.Resources.readLines;
import static org.t3as.ner.util.Strings.clean;
import static org.t3as.ner.util.Strings.simplify;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.LineProcessor;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
public final class IO {
private static final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
private static final Splitter TABS = Splitter.on('\t').trimResults().omitEmptyStrings();
private IO() {}
/** Return a Set containing trimmed lowercaseLines read from a file, skipping comments. */
public static Set<String> lowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of
if (!l.startsWith("#") && !l.isEmpty()) add(toEngLowerCase(l));
return true;
}
});
}});
}
/** Return a Set containing lines with just the word characters of lines read from a file, skipping comments. */
public static Set<String> cleanLowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of | // Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String clean(final String s) { return CLEAN.matcher(s).replaceAll(""); }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// @SuppressWarnings("ReturnOfNull")
// public static String simplify(final String s) {
// if (s == null) return null;
// final String s1 = Normalizer.normalize(s, Normalizer.Form.NFC);
// return s1.trim();
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/IO.java
import java.util.List;
import java.util.Set;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.io.Resources.getResource;
import static com.google.common.io.Resources.readLines;
import static org.t3as.ner.util.Strings.clean;
import static org.t3as.ner.util.Strings.simplify;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.LineProcessor;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
public final class IO {
private static final Splitter SPACES = Splitter.on(' ').trimResults().omitEmptyStrings();
private static final Splitter TABS = Splitter.on('\t').trimResults().omitEmptyStrings();
private IO() {}
/** Return a Set containing trimmed lowercaseLines read from a file, skipping comments. */
public static Set<String> lowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of
if (!l.startsWith("#") && !l.isEmpty()) add(toEngLowerCase(l));
return true;
}
});
}});
}
/** Return a Set containing lines with just the word characters of lines read from a file, skipping comments. */
public static Set<String> cleanLowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of | if (!l.startsWith("#") && !l.isEmpty()) add(toEngLowerCase(clean(l))); |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
/**
* This class utilizes a Java standard class to token the input sentence.
* <p/>
* This class is not thread safe.
*/
public class Tokenizer {
public enum Mode {
WITH_PUNCTUATION,
WITHOUT_PUNCTUATION
}
private static final ImmutableCollection<String> ABBREVIATION_EXCEPTIONS;
static {
try { ABBREVIATION_EXCEPTIONS = ImmutableList.copyOf(IO.lowercaseLines(Tokenizer.class, "TokenizerAbbreviation")); }
catch (final IOException e) { throw new RuntimeException("Could not load the TokenizerAbbreviation file.", e); }
}
private final Mode mode; | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
/**
* This class utilizes a Java standard class to token the input sentence.
* <p/>
* This class is not thread safe.
*/
public class Tokenizer {
public enum Mode {
WITH_PUNCTUATION,
WITHOUT_PUNCTUATION
}
private static final ImmutableCollection<String> ABBREVIATION_EXCEPTIONS;
static {
try { ABBREVIATION_EXCEPTIONS = ImmutableList.copyOf(IO.lowercaseLines(Tokenizer.class, "TokenizerAbbreviation")); }
catch (final IOException e) { throw new RuntimeException("Could not load the TokenizerAbbreviation file.", e); }
}
private final Mode mode; | private List<Token> currentSentence; |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
/**
* This class utilizes a Java standard class to token the input sentence.
* <p/>
* This class is not thread safe.
*/
public class Tokenizer {
public enum Mode {
WITH_PUNCTUATION,
WITHOUT_PUNCTUATION
}
private static final ImmutableCollection<String> ABBREVIATION_EXCEPTIONS;
static {
try { ABBREVIATION_EXCEPTIONS = ImmutableList.copyOf(IO.lowercaseLines(Tokenizer.class, "TokenizerAbbreviation")); }
catch (final IOException e) { throw new RuntimeException("Could not load the TokenizerAbbreviation file.", e); }
}
private final Mode mode;
private List<Token> currentSentence;
public Tokenizer(final Mode mode) { this.mode = mode; }
/**
* Tokenize some text - not thread safe.
* @param text tokenize this
* @return tokenized text
*/
public List<List<Token>> process(final String text) {
final List<List<Token>> paragraph = new ArrayList<>();
currentSentence = new ArrayList<>();
final Tokens tokens = splitText(text);
while (tokens.hasNext()) {
final Token t = tokens.next();
final String trimmedWord = t.text.trim();
// skip spaces
if (trimmedWord.isEmpty()) continue;
| // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.util;
/**
* This class utilizes a Java standard class to token the input sentence.
* <p/>
* This class is not thread safe.
*/
public class Tokenizer {
public enum Mode {
WITH_PUNCTUATION,
WITHOUT_PUNCTUATION
}
private static final ImmutableCollection<String> ABBREVIATION_EXCEPTIONS;
static {
try { ABBREVIATION_EXCEPTIONS = ImmutableList.copyOf(IO.lowercaseLines(Tokenizer.class, "TokenizerAbbreviation")); }
catch (final IOException e) { throw new RuntimeException("Could not load the TokenizerAbbreviation file.", e); }
}
private final Mode mode;
private List<Token> currentSentence;
public Tokenizer(final Mode mode) { this.mode = mode; }
/**
* Tokenize some text - not thread safe.
* @param text tokenize this
* @return tokenized text
*/
public List<List<Token>> process(final String text) {
final List<List<Token>> paragraph = new ArrayList<>();
currentSentence = new ArrayList<>();
final Tokens tokens = splitText(text);
while (tokens.hasNext()) {
final Token t = tokens.next();
final String trimmedWord = t.text.trim();
// skip spaces
if (trimmedWord.isEmpty()) continue;
| if (((mode == WITH_PUNCTUATION) || (mode == WITHOUT_PUNCTUATION && isLetterOrDigit(initChar(t.text))))) { |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION; | * Tokenize some text - not thread safe.
* @param text tokenize this
* @return tokenized text
*/
public List<List<Token>> process(final String text) {
final List<List<Token>> paragraph = new ArrayList<>();
currentSentence = new ArrayList<>();
final Tokens tokens = splitText(text);
while (tokens.hasNext()) {
final Token t = tokens.next();
final String trimmedWord = t.text.trim();
// skip spaces
if (trimmedWord.isEmpty()) continue;
if (((mode == WITH_PUNCTUATION) || (mode == WITHOUT_PUNCTUATION && isLetterOrDigit(initChar(t.text))))) {
boolean canBreakSentence = true;
if (t.text.contains("'")) {
wordContainsApostrophe(t);
}
else if (".".equals(trimmedWord)) {
canBreakSentence = wordIsFullStop(t);
}
else if (":".equals(trimmedWord)) {
wordIsColon(tokens, t);
}
else currentSentence.add(t);
// handling the end of a sentence | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION;
* Tokenize some text - not thread safe.
* @param text tokenize this
* @return tokenized text
*/
public List<List<Token>> process(final String text) {
final List<List<Token>> paragraph = new ArrayList<>();
currentSentence = new ArrayList<>();
final Tokens tokens = splitText(text);
while (tokens.hasNext()) {
final Token t = tokens.next();
final String trimmedWord = t.text.trim();
// skip spaces
if (trimmedWord.isEmpty()) continue;
if (((mode == WITH_PUNCTUATION) || (mode == WITHOUT_PUNCTUATION && isLetterOrDigit(initChar(t.text))))) {
boolean canBreakSentence = true;
if (t.text.contains("'")) {
wordContainsApostrophe(t);
}
else if (".".equals(trimmedWord)) {
canBreakSentence = wordIsFullStop(t);
}
else if (":".equals(trimmedWord)) {
wordIsColon(tokens, t);
}
else currentSentence.add(t);
// handling the end of a sentence | if (canBreakSentence && equalss(trimmedWord, ".", ";", "?", "!")) { |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION; |
if (((mode == WITH_PUNCTUATION) || (mode == WITHOUT_PUNCTUATION && isLetterOrDigit(initChar(t.text))))) {
boolean canBreakSentence = true;
if (t.text.contains("'")) {
wordContainsApostrophe(t);
}
else if (".".equals(trimmedWord)) {
canBreakSentence = wordIsFullStop(t);
}
else if (":".equals(trimmedWord)) {
wordIsColon(tokens, t);
}
else currentSentence.add(t);
// handling the end of a sentence
if (canBreakSentence && equalss(trimmedWord, ".", ";", "?", "!")) {
paragraph.add(currentSentence);
currentSentence = new ArrayList<>();
}
}
}
if (!currentSentence.isEmpty()) paragraph.add(currentSentence);
return paragraph;
}
private void wordIsColon(final Tokens tokens, final Token t) {
// check we can get a previous and next word to merge together
if (!currentSentence.isEmpty() && tokens.hasNext()) {
// if the colon does not have a space on either side | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION;
if (((mode == WITH_PUNCTUATION) || (mode == WITHOUT_PUNCTUATION && isLetterOrDigit(initChar(t.text))))) {
boolean canBreakSentence = true;
if (t.text.contains("'")) {
wordContainsApostrophe(t);
}
else if (".".equals(trimmedWord)) {
canBreakSentence = wordIsFullStop(t);
}
else if (":".equals(trimmedWord)) {
wordIsColon(tokens, t);
}
else currentSentence.add(t);
// handling the end of a sentence
if (canBreakSentence && equalss(trimmedWord, ".", ";", "?", "!")) {
paragraph.add(currentSentence);
currentSentence = new ArrayList<>();
}
}
}
if (!currentSentence.isEmpty()) paragraph.add(currentSentence);
return paragraph;
}
private void wordIsColon(final Tokens tokens, final Token t) {
// check we can get a previous and next word to merge together
if (!currentSentence.isEmpty() && tokens.hasNext()) {
// if the colon does not have a space on either side | if (!isSpaceChar(lastChar(tokens.peekPrev().text)) && !isSpaceChar(initChar(tokens.peekNext().text))) { |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION; | int startIdx = wordIterator.first();
for (int endIdx = wordIterator.next(); endIdx != DONE; startIdx = endIdx, endIdx = wordIterator.next()) {
final String word = text.substring(startIdx, endIdx);
l.add(new Token(startIdx, word));
}
return new Tokens(l);
}
private void mergeWordsIntoSentence(final Token previousWord, final Token word, final Token nextWord,
final int previousWordIndex) {
// make sure the previous and next words both start with a letter or digit
if (isLetterOrDigit(initChar(previousWord.text)) && isLetterOrDigit(initChar(nextWord.text))) {
// merge the 3 words again and add the result, replace previous word from sentence
currentSentence.set(previousWordIndex,
new Token(previousWord.startIndex, previousWord.text + word.text + nextWord.text));
}
// otherwise just add the word and next word
else {
currentSentence.add(word);
currentSentence.add(nextWord);
}
}
private boolean wordIsFullStop(final Token t) {
boolean canBreakSentence = true;
if (currentSentence.isEmpty()) currentSentence.add(t);
else {
final int previousWordIndex = currentSentence.size() - 1;
final Token previousWord = currentSentence.get(previousWordIndex); | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION;
int startIdx = wordIterator.first();
for (int endIdx = wordIterator.next(); endIdx != DONE; startIdx = endIdx, endIdx = wordIterator.next()) {
final String word = text.substring(startIdx, endIdx);
l.add(new Token(startIdx, word));
}
return new Tokens(l);
}
private void mergeWordsIntoSentence(final Token previousWord, final Token word, final Token nextWord,
final int previousWordIndex) {
// make sure the previous and next words both start with a letter or digit
if (isLetterOrDigit(initChar(previousWord.text)) && isLetterOrDigit(initChar(nextWord.text))) {
// merge the 3 words again and add the result, replace previous word from sentence
currentSentence.set(previousWordIndex,
new Token(previousWord.startIndex, previousWord.text + word.text + nextWord.text));
}
// otherwise just add the word and next word
else {
currentSentence.add(word);
currentSentence.add(nextWord);
}
}
private boolean wordIsFullStop(final Token t) {
boolean canBreakSentence = true;
if (currentSentence.isEmpty()) currentSentence.add(t);
else {
final int previousWordIndex = currentSentence.size() - 1;
final Token previousWord = currentSentence.get(previousWordIndex); | if (ABBREVIATION_EXCEPTIONS.contains(toEngLowerCase(previousWord.text)) |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION; | for (int endIdx = wordIterator.next(); endIdx != DONE; startIdx = endIdx, endIdx = wordIterator.next()) {
final String word = text.substring(startIdx, endIdx);
l.add(new Token(startIdx, word));
}
return new Tokens(l);
}
private void mergeWordsIntoSentence(final Token previousWord, final Token word, final Token nextWord,
final int previousWordIndex) {
// make sure the previous and next words both start with a letter or digit
if (isLetterOrDigit(initChar(previousWord.text)) && isLetterOrDigit(initChar(nextWord.text))) {
// merge the 3 words again and add the result, replace previous word from sentence
currentSentence.set(previousWordIndex,
new Token(previousWord.startIndex, previousWord.text + word.text + nextWord.text));
}
// otherwise just add the word and next word
else {
currentSentence.add(word);
currentSentence.add(nextWord);
}
}
private boolean wordIsFullStop(final Token t) {
boolean canBreakSentence = true;
if (currentSentence.isEmpty()) currentSentence.add(t);
else {
final int previousWordIndex = currentSentence.size() - 1;
final Token previousWord = currentSentence.get(previousWordIndex);
if (ABBREVIATION_EXCEPTIONS.contains(toEngLowerCase(previousWord.text)) | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION;
for (int endIdx = wordIterator.next(); endIdx != DONE; startIdx = endIdx, endIdx = wordIterator.next()) {
final String word = text.substring(startIdx, endIdx);
l.add(new Token(startIdx, word));
}
return new Tokens(l);
}
private void mergeWordsIntoSentence(final Token previousWord, final Token word, final Token nextWord,
final int previousWordIndex) {
// make sure the previous and next words both start with a letter or digit
if (isLetterOrDigit(initChar(previousWord.text)) && isLetterOrDigit(initChar(nextWord.text))) {
// merge the 3 words again and add the result, replace previous word from sentence
currentSentence.set(previousWordIndex,
new Token(previousWord.startIndex, previousWord.text + word.text + nextWord.text));
}
// otherwise just add the word and next word
else {
currentSentence.add(word);
currentSentence.add(nextWord);
}
}
private boolean wordIsFullStop(final Token t) {
boolean canBreakSentence = true;
if (currentSentence.isEmpty()) currentSentence.add(t);
else {
final int previousWordIndex = currentSentence.size() - 1;
final Token previousWord = currentSentence.get(previousWordIndex);
if (ABBREVIATION_EXCEPTIONS.contains(toEngLowerCase(previousWord.text)) | || isSingleUppercaseChar(previousWord.text) |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
| import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION; | // merge the 3 words again and add the result, replace previous word from sentence
currentSentence.set(previousWordIndex,
new Token(previousWord.startIndex, previousWord.text + word.text + nextWord.text));
}
// otherwise just add the word and next word
else {
currentSentence.add(word);
currentSentence.add(nextWord);
}
}
private boolean wordIsFullStop(final Token t) {
boolean canBreakSentence = true;
if (currentSentence.isEmpty()) currentSentence.add(t);
else {
final int previousWordIndex = currentSentence.size() - 1;
final Token previousWord = currentSentence.get(previousWordIndex);
if (ABBREVIATION_EXCEPTIONS.contains(toEngLowerCase(previousWord.text))
|| isSingleUppercaseChar(previousWord.text)
|| previousWord.text.contains(".")) {
currentSentence.set(previousWordIndex, new Token(previousWord.startIndex, previousWord.text + "."));
// do not break the sentence
canBreakSentence = false;
}
else currentSentence.add(t);
}
return canBreakSentence;
}
private void wordContainsApostrophe(final Token t) { | // Path: nicta-ner-common/src/main/java/org/t3as/ner/Token.java
// @Immutable
// public class Token {
//
// /** 0-indexed position of the first character of this token from the original text being analysed. */
// public final int startIndex;
// /** The text that this token is representing. */
// public final String text;
//
// @JsonCreator
// public Token(@JsonProperty("startIndex") final int startIndex, @JsonProperty("text") final String text) {
// this.startIndex = startIndex;
// this.text = text;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final Token token = (Token) o;
// return startIndex == token.startIndex && text.equals(token.text);
// }
//
// @Override
// public int hashCode() {
// int result = startIndex;
// result = 31 * result + text.hashCode();
// return result;
// }
//
// public String toString() { return startIndex + ":" + text; }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean endsWith(final String word, final String... suffixes) {
// if (word == null || suffixes == null) return false;
// for (final String s : suffixes) {
// if (word.endsWith(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean equalss(final String word, final String... words) {
// if (word == null || words == null) return false;
// for (final String s : words) {
// if (word.equals(s)) return true;
// }
// return false;
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char initChar(final String s) {
// return s.charAt(0);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static boolean isSingleUppercaseChar(final String word) {
// return word.length() == 1 && isUpperCase(word.charAt(0));
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static char lastChar(final String s) {
// return s.charAt(s.length() -1);
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Strings.java
// public static String toEngLowerCase(final String s) { return s.toLowerCase(Locale.ENGLISH); }
// Path: nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import org.t3as.ner.Token;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import static java.lang.Character.isLetterOrDigit;
import static java.lang.Character.isSpaceChar;
import static java.text.BreakIterator.DONE;
import static org.t3as.ner.util.Strings.endsWith;
import static org.t3as.ner.util.Strings.equalss;
import static org.t3as.ner.util.Strings.initChar;
import static org.t3as.ner.util.Strings.isSingleUppercaseChar;
import static org.t3as.ner.util.Strings.lastChar;
import static org.t3as.ner.util.Strings.toEngLowerCase;
import static org.t3as.ner.util.Tokenizer.Mode.WITHOUT_PUNCTUATION;
import static org.t3as.ner.util.Tokenizer.Mode.WITH_PUNCTUATION;
// merge the 3 words again and add the result, replace previous word from sentence
currentSentence.set(previousWordIndex,
new Token(previousWord.startIndex, previousWord.text + word.text + nextWord.text));
}
// otherwise just add the word and next word
else {
currentSentence.add(word);
currentSentence.add(nextWord);
}
}
private boolean wordIsFullStop(final Token t) {
boolean canBreakSentence = true;
if (currentSentence.isEmpty()) currentSentence.add(t);
else {
final int previousWordIndex = currentSentence.size() - 1;
final Token previousWord = currentSentence.get(previousWordIndex);
if (ABBREVIATION_EXCEPTIONS.contains(toEngLowerCase(previousWord.text))
|| isSingleUppercaseChar(previousWord.text)
|| previousWord.text.contains(".")) {
currentSentence.set(previousWordIndex, new Token(previousWord.startIndex, previousWord.text + "."));
// do not break the sentence
canBreakSentence = false;
}
else currentSentence.add(t);
}
return canBreakSentence;
}
private void wordContainsApostrophe(final Token t) { | if (t.text.endsWith("n't")) { |
NICTA/nicta-ner | nicta-ner/src/test/java/org/t3as/ner/resource/ConfigurationTest.java | // Path: nicta-ner/src/main/java/org/t3as/ner/classifier/feature/FeatureMap.java
// @Immutable
// public class FeatureMap {
//
// private final Map<EntityClass, List<Feature>> featureMap = new LinkedHashMap<>();
// private final boolean tracing;
// public Collection<String> trace;
//
// public FeatureMap(final boolean tracing) { this.tracing = tracing; }
//
// public void addFeature(final String entityType, final Feature feature) {
// final EntityClass type = new EntityClass(entityType);
// List<Feature> features = featureMap.get(type);
// if (features == null) {
// features = new ArrayList<>();
// featureMap.put(type, features);
// }
// features.add(feature);
// }
//
// public Map<EntityClass, Double> score(final Phrase p) {
// final Map<EntityClass, Double> scores = new LinkedHashMap<>();
// if (tracing) trace = new ArrayList<>();
// for (final Map.Entry<EntityClass, List<Feature>> e : featureMap.entrySet()) {
// double score = 0;
// for (final Feature f : e.getValue()) {
// final double s = f.score(p);
// score += s;
// if (tracing && s != 0) {
// trace.add("'" + p.phraseString() + "', w=" + e.getKey() + ":" + f.getWeight()
// + ", s=" + s + ", " + f.ident());
// }
// }
// scores.put(e.getKey(), score);
// }
// return scores;
// }
//
// @Override
// public String toString() {
// return "FeatureMap{" +
// "featureMap=" + featureMap +
// '}';
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final FeatureMap that = (FeatureMap) o;
// return featureMap.equals(that.featureMap);
// }
//
// @Override
// public int hashCode() { return featureMap.hashCode(); }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/classifier/feature/Feature.java
// public static Feature generateFeatureByName(final String featureType, final int weight, final List<String> resourceNames)
// throws IllegalArgumentException, IOException {
// switch (featureType) {
// case "RuledWordFeature":
// return new RuledWordFeature(resourceNames, weight);
// case "PrepositionContextFeature":
// return new PrepositionContextFeature(resourceNames, weight);
// case "ExistingPhraseFeature":
// return new ExistingPhraseFeature(resourceNames, weight);
// case "ExistingCleanPhraseFeature":
// return new ExistingCleanPhraseFeature(resourceNames, weight);
// case "CaseSensitiveWordLookup":
// return new CaseSensitiveWordLookup(resourceNames, weight);
// case "CaseInsensitiveWordLookup":
// return new CaseInsensitiveWordLookup(resourceNames, weight);
// default:
// throw new IllegalArgumentException("Unknown feature: '" + featureType + "'");
// }
// }
| import org.t3as.ner.classifier.feature.FeatureMap;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import static com.google.common.collect.ImmutableList.of;
import static org.t3as.ner.classifier.feature.Feature.generateFeatureByName;
import static org.testng.Assert.assertEquals; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.resource;
public class ConfigurationTest {
@DataProvider(name = "configTest")
public Object[][] configTestProvider() throws IOException { | // Path: nicta-ner/src/main/java/org/t3as/ner/classifier/feature/FeatureMap.java
// @Immutable
// public class FeatureMap {
//
// private final Map<EntityClass, List<Feature>> featureMap = new LinkedHashMap<>();
// private final boolean tracing;
// public Collection<String> trace;
//
// public FeatureMap(final boolean tracing) { this.tracing = tracing; }
//
// public void addFeature(final String entityType, final Feature feature) {
// final EntityClass type = new EntityClass(entityType);
// List<Feature> features = featureMap.get(type);
// if (features == null) {
// features = new ArrayList<>();
// featureMap.put(type, features);
// }
// features.add(feature);
// }
//
// public Map<EntityClass, Double> score(final Phrase p) {
// final Map<EntityClass, Double> scores = new LinkedHashMap<>();
// if (tracing) trace = new ArrayList<>();
// for (final Map.Entry<EntityClass, List<Feature>> e : featureMap.entrySet()) {
// double score = 0;
// for (final Feature f : e.getValue()) {
// final double s = f.score(p);
// score += s;
// if (tracing && s != 0) {
// trace.add("'" + p.phraseString() + "', w=" + e.getKey() + ":" + f.getWeight()
// + ", s=" + s + ", " + f.ident());
// }
// }
// scores.put(e.getKey(), score);
// }
// return scores;
// }
//
// @Override
// public String toString() {
// return "FeatureMap{" +
// "featureMap=" + featureMap +
// '}';
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final FeatureMap that = (FeatureMap) o;
// return featureMap.equals(that.featureMap);
// }
//
// @Override
// public int hashCode() { return featureMap.hashCode(); }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/classifier/feature/Feature.java
// public static Feature generateFeatureByName(final String featureType, final int weight, final List<String> resourceNames)
// throws IllegalArgumentException, IOException {
// switch (featureType) {
// case "RuledWordFeature":
// return new RuledWordFeature(resourceNames, weight);
// case "PrepositionContextFeature":
// return new PrepositionContextFeature(resourceNames, weight);
// case "ExistingPhraseFeature":
// return new ExistingPhraseFeature(resourceNames, weight);
// case "ExistingCleanPhraseFeature":
// return new ExistingCleanPhraseFeature(resourceNames, weight);
// case "CaseSensitiveWordLookup":
// return new CaseSensitiveWordLookup(resourceNames, weight);
// case "CaseInsensitiveWordLookup":
// return new CaseInsensitiveWordLookup(resourceNames, weight);
// default:
// throw new IllegalArgumentException("Unknown feature: '" + featureType + "'");
// }
// }
// Path: nicta-ner/src/test/java/org/t3as/ner/resource/ConfigurationTest.java
import org.t3as.ner.classifier.feature.FeatureMap;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import static com.google.common.collect.ImmutableList.of;
import static org.t3as.ner.classifier.feature.Feature.generateFeatureByName;
import static org.testng.Assert.assertEquals;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.resource;
public class ConfigurationTest {
@DataProvider(name = "configTest")
public Object[][] configTestProvider() throws IOException { | final FeatureMap featureMap = new FeatureMap(false); |
NICTA/nicta-ner | nicta-ner/src/test/java/org/t3as/ner/resource/ConfigurationTest.java | // Path: nicta-ner/src/main/java/org/t3as/ner/classifier/feature/FeatureMap.java
// @Immutable
// public class FeatureMap {
//
// private final Map<EntityClass, List<Feature>> featureMap = new LinkedHashMap<>();
// private final boolean tracing;
// public Collection<String> trace;
//
// public FeatureMap(final boolean tracing) { this.tracing = tracing; }
//
// public void addFeature(final String entityType, final Feature feature) {
// final EntityClass type = new EntityClass(entityType);
// List<Feature> features = featureMap.get(type);
// if (features == null) {
// features = new ArrayList<>();
// featureMap.put(type, features);
// }
// features.add(feature);
// }
//
// public Map<EntityClass, Double> score(final Phrase p) {
// final Map<EntityClass, Double> scores = new LinkedHashMap<>();
// if (tracing) trace = new ArrayList<>();
// for (final Map.Entry<EntityClass, List<Feature>> e : featureMap.entrySet()) {
// double score = 0;
// for (final Feature f : e.getValue()) {
// final double s = f.score(p);
// score += s;
// if (tracing && s != 0) {
// trace.add("'" + p.phraseString() + "', w=" + e.getKey() + ":" + f.getWeight()
// + ", s=" + s + ", " + f.ident());
// }
// }
// scores.put(e.getKey(), score);
// }
// return scores;
// }
//
// @Override
// public String toString() {
// return "FeatureMap{" +
// "featureMap=" + featureMap +
// '}';
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final FeatureMap that = (FeatureMap) o;
// return featureMap.equals(that.featureMap);
// }
//
// @Override
// public int hashCode() { return featureMap.hashCode(); }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/classifier/feature/Feature.java
// public static Feature generateFeatureByName(final String featureType, final int weight, final List<String> resourceNames)
// throws IllegalArgumentException, IOException {
// switch (featureType) {
// case "RuledWordFeature":
// return new RuledWordFeature(resourceNames, weight);
// case "PrepositionContextFeature":
// return new PrepositionContextFeature(resourceNames, weight);
// case "ExistingPhraseFeature":
// return new ExistingPhraseFeature(resourceNames, weight);
// case "ExistingCleanPhraseFeature":
// return new ExistingCleanPhraseFeature(resourceNames, weight);
// case "CaseSensitiveWordLookup":
// return new CaseSensitiveWordLookup(resourceNames, weight);
// case "CaseInsensitiveWordLookup":
// return new CaseInsensitiveWordLookup(resourceNames, weight);
// default:
// throw new IllegalArgumentException("Unknown feature: '" + featureType + "'");
// }
// }
| import org.t3as.ner.classifier.feature.FeatureMap;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import static com.google.common.collect.ImmutableList.of;
import static org.t3as.ner.classifier.feature.Feature.generateFeatureByName;
import static org.testng.Assert.assertEquals; | /*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.resource;
public class ConfigurationTest {
@DataProvider(name = "configTest")
public Object[][] configTestProvider() throws IOException {
final FeatureMap featureMap = new FeatureMap(false); | // Path: nicta-ner/src/main/java/org/t3as/ner/classifier/feature/FeatureMap.java
// @Immutable
// public class FeatureMap {
//
// private final Map<EntityClass, List<Feature>> featureMap = new LinkedHashMap<>();
// private final boolean tracing;
// public Collection<String> trace;
//
// public FeatureMap(final boolean tracing) { this.tracing = tracing; }
//
// public void addFeature(final String entityType, final Feature feature) {
// final EntityClass type = new EntityClass(entityType);
// List<Feature> features = featureMap.get(type);
// if (features == null) {
// features = new ArrayList<>();
// featureMap.put(type, features);
// }
// features.add(feature);
// }
//
// public Map<EntityClass, Double> score(final Phrase p) {
// final Map<EntityClass, Double> scores = new LinkedHashMap<>();
// if (tracing) trace = new ArrayList<>();
// for (final Map.Entry<EntityClass, List<Feature>> e : featureMap.entrySet()) {
// double score = 0;
// for (final Feature f : e.getValue()) {
// final double s = f.score(p);
// score += s;
// if (tracing && s != 0) {
// trace.add("'" + p.phraseString() + "', w=" + e.getKey() + ":" + f.getWeight()
// + ", s=" + s + ", " + f.ident());
// }
// }
// scores.put(e.getKey(), score);
// }
// return scores;
// }
//
// @Override
// public String toString() {
// return "FeatureMap{" +
// "featureMap=" + featureMap +
// '}';
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final FeatureMap that = (FeatureMap) o;
// return featureMap.equals(that.featureMap);
// }
//
// @Override
// public int hashCode() { return featureMap.hashCode(); }
// }
//
// Path: nicta-ner/src/main/java/org/t3as/ner/classifier/feature/Feature.java
// public static Feature generateFeatureByName(final String featureType, final int weight, final List<String> resourceNames)
// throws IllegalArgumentException, IOException {
// switch (featureType) {
// case "RuledWordFeature":
// return new RuledWordFeature(resourceNames, weight);
// case "PrepositionContextFeature":
// return new PrepositionContextFeature(resourceNames, weight);
// case "ExistingPhraseFeature":
// return new ExistingPhraseFeature(resourceNames, weight);
// case "ExistingCleanPhraseFeature":
// return new ExistingCleanPhraseFeature(resourceNames, weight);
// case "CaseSensitiveWordLookup":
// return new CaseSensitiveWordLookup(resourceNames, weight);
// case "CaseInsensitiveWordLookup":
// return new CaseInsensitiveWordLookup(resourceNames, weight);
// default:
// throw new IllegalArgumentException("Unknown feature: '" + featureType + "'");
// }
// }
// Path: nicta-ner/src/test/java/org/t3as/ner/resource/ConfigurationTest.java
import org.t3as.ner.classifier.feature.FeatureMap;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import static com.google.common.collect.ImmutableList.of;
import static org.t3as.ner.classifier.feature.Feature.generateFeatureByName;
import static org.testng.Assert.assertEquals;
/*
* #%L
* NICTA t3as Named-Entity Recognition library
* %%
* Copyright (C) 2010 - 2014 NICTA
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.t3as.ner.resource;
public class ConfigurationTest {
@DataProvider(name = "configTest")
public Object[][] configTestProvider() throws IOException {
final FeatureMap featureMap = new FeatureMap(false); | featureMap.addFeature("LOCATION", generateFeatureByName("ExistingPhraseFeature", 3, |
lisicnu/Log4Android | src/main/java/com/github/lisicnu/log4android/format/command/CategoryFormatCommand.java | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
| import android.util.Log;
import com.github.lisicnu.log4android.Level; | /*
* Copyright 2008 The MicroLog project @sourceforge.net
* 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.github.lisicnu.log4android.format.command;
/**
* The <code>CategoryFormatCommand</code> is used for printing the category,
* i.e. the name of the logging class.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*
* @since 1.0
*/
public class CategoryFormatCommand implements FormatCommandInterface {
private static final String TAG = CategoryFormatCommand.class.getSimpleName();
public static final int FULL_CLASS_NAME_SPECIFIER = -1;
public static final int DEFAULT_PRECISION_SPECIFIER = 1;
private int precisionSpecifier = DEFAULT_PRECISION_SPECIFIER;
/**
*
*
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#execute(String,
* String, long, com.github.lisicnu.log4android.Level, Object,
* Throwable)
*/ | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
// Path: src/main/java/com/github/lisicnu/log4android/format/command/CategoryFormatCommand.java
import android.util.Log;
import com.github.lisicnu.log4android.Level;
/*
* Copyright 2008 The MicroLog project @sourceforge.net
* 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.github.lisicnu.log4android.format.command;
/**
* The <code>CategoryFormatCommand</code> is used for printing the category,
* i.e. the name of the logging class.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*
* @since 1.0
*/
public class CategoryFormatCommand implements FormatCommandInterface {
private static final String TAG = CategoryFormatCommand.class.getSimpleName();
public static final int FULL_CLASS_NAME_SPECIFIER = -1;
public static final int DEFAULT_PRECISION_SPECIFIER = 1;
private int precisionSpecifier = DEFAULT_PRECISION_SPECIFIER;
/**
*
*
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#execute(String,
* String, long, com.github.lisicnu.log4android.Level, Object,
* Throwable)
*/ | public String execute(String clientID, String name, long time, Level level, Object message, |
lisicnu/Log4Android | src/main/java/com/github/lisicnu/log4android/format/command/PriorityFormatCommand.java | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
| import com.github.lisicnu.log4android.Level; | /*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.format.command;
/**
* Convert the <code>Level</code> to message.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public class PriorityFormatCommand implements FormatCommandInterface {
/**
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#init(String)
*/
public void init(String initString){
// Do nothing.
}
/**
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#execute(String,
* String, long, com.github.lisicnu.log4android.Level, Object,
* Throwable)
*/ | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
// Path: src/main/java/com/github/lisicnu/log4android/format/command/PriorityFormatCommand.java
import com.github.lisicnu.log4android.Level;
/*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.format.command;
/**
* Convert the <code>Level</code> to message.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public class PriorityFormatCommand implements FormatCommandInterface {
/**
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#init(String)
*/
public void init(String initString){
// Do nothing.
}
/**
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#execute(String,
* String, long, com.github.lisicnu.log4android.Level, Object,
* Throwable)
*/ | public String execute(String clientID, String name, long time, Level level, |
lisicnu/Log4Android | src/main/java/com/github/lisicnu/log4android/format/command/ThreadFormatCommand.java | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
| import com.github.lisicnu.log4android.Level; | /*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.format.command;
/**
* A converter that is used for printing the current thread name.
*
* Minimum requirements: CLDC 1.1
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public class ThreadFormatCommand implements FormatCommandInterface {
/**
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#init(String)
*/
public void init(String preFormatString){
// Do nothing.
}
/**
* Execute the <code>ThreadFormatCommand</code>.
*/ | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
// Path: src/main/java/com/github/lisicnu/log4android/format/command/ThreadFormatCommand.java
import com.github.lisicnu.log4android.Level;
/*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.format.command;
/**
* A converter that is used for printing the current thread name.
*
* Minimum requirements: CLDC 1.1
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public class ThreadFormatCommand implements FormatCommandInterface {
/**
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#init(String)
*/
public void init(String preFormatString){
// Do nothing.
}
/**
* Execute the <code>ThreadFormatCommand</code>.
*/ | public String execute(String clientID, String name, long time, Level level, |
lisicnu/Log4Android | src/main/java/com/github/lisicnu/log4android/appender/DatagramAppender.java | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
| import android.util.Log;
import com.github.lisicnu.log4android.Level;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; | /*
* Copyright 2009 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.appender;
/**
* The <code>DatagramAppender</code> uses a <code>DatagramSocket</code> to send
* <code>Datagram</code> to a server. This can be used on Android or in a Java
* SE environment.
*
* @author Johan Karlsson
*
*/
public class DatagramAppender extends AbstractAppender {
private static final String TAG = DatagramAppender.class.getSimpleName();
public static final String DEFAULT_HOST = "127.0.0.1";
private DatagramSocket datagramSocket;
private InetAddress address;
private String host = DEFAULT_HOST;
private int port;
private DatagramPacket datagramPacket;
/**
* @see com.github.lisicnu.log4android.appender.AbstractAppender#open()
*/
@Override
public void open() throws IOException{
datagramSocket = new DatagramSocket();
address = InetAddress.getByName(host);
// We create the datagram packet here, but with dummy data. This is
// done instead of lazy initialization to have better performance when
// logging. The datagram is re-used and we set new data each time before
// logging.
datagramPacket = new DatagramPacket(new byte[] { }, 0, address, port);
logOpen = true;
}
/**
*
* @see com.github.lisicnu.log4android.appender.AbstractAppender#doLog(String,
* String, long, com.github.lisicnu.log4android.Level,
* Object, Throwable)
*/
@Override | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
// Path: src/main/java/com/github/lisicnu/log4android/appender/DatagramAppender.java
import android.util.Log;
import com.github.lisicnu.log4android.Level;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/*
* Copyright 2009 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.appender;
/**
* The <code>DatagramAppender</code> uses a <code>DatagramSocket</code> to send
* <code>Datagram</code> to a server. This can be used on Android or in a Java
* SE environment.
*
* @author Johan Karlsson
*
*/
public class DatagramAppender extends AbstractAppender {
private static final String TAG = DatagramAppender.class.getSimpleName();
public static final String DEFAULT_HOST = "127.0.0.1";
private DatagramSocket datagramSocket;
private InetAddress address;
private String host = DEFAULT_HOST;
private int port;
private DatagramPacket datagramPacket;
/**
* @see com.github.lisicnu.log4android.appender.AbstractAppender#open()
*/
@Override
public void open() throws IOException{
datagramSocket = new DatagramSocket();
address = InetAddress.getByName(host);
// We create the datagram packet here, but with dummy data. This is
// done instead of lazy initialization to have better performance when
// logging. The datagram is re-used and we set new data each time before
// logging.
datagramPacket = new DatagramPacket(new byte[] { }, 0, address, port);
logOpen = true;
}
/**
*
* @see com.github.lisicnu.log4android.appender.AbstractAppender#doLog(String,
* String, long, com.github.lisicnu.log4android.Level,
* Object, Throwable)
*/
@Override | public void doLog(String clientID, String name, long time, Level level, Object message, |
lisicnu/Log4Android | src/main/java/com/github/lisicnu/log4android/format/command/TimeFormatCommand.java | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
| import com.github.lisicnu.log4android.Level; | /*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.format.command;
/**
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public class TimeFormatCommand implements FormatCommandInterface {
/**
*
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#init(String)
*/
public void init(String preFormatString) {
// Do nothing.
}
/**
*
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#execute(String,
* String, long, com.github.lisicnu.log4android.Level, Object, Throwable)
*/ | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
// Path: src/main/java/com/github/lisicnu/log4android/format/command/TimeFormatCommand.java
import com.github.lisicnu.log4android.Level;
/*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.format.command;
/**
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public class TimeFormatCommand implements FormatCommandInterface {
/**
*
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#init(String)
*/
public void init(String preFormatString) {
// Do nothing.
}
/**
*
* @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#execute(String,
* String, long, com.github.lisicnu.log4android.Level, Object, Throwable)
*/ | public String execute(String clientID, String name, long time, Level level, Object message, Throwable throwable) { |
lisicnu/Log4Android | src/main/java/com/github/lisicnu/log4android/appender/LogCatAppender.java | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
| import android.util.Log;
import com.github.lisicnu.log4android.Level;
import java.io.IOException; | package com.github.lisicnu.log4android.appender;
public class LogCatAppender extends AbstractAppender {
@Override
public void clear() {
}
@Override | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
// Path: src/main/java/com/github/lisicnu/log4android/appender/LogCatAppender.java
import android.util.Log;
import com.github.lisicnu.log4android.Level;
import java.io.IOException;
package com.github.lisicnu.log4android.appender;
public class LogCatAppender extends AbstractAppender {
@Override
public void clear() {
}
@Override | public void doLog(String clientID, String name, long time, Level level, Object message, Throwable t) { |
lisicnu/Log4Android | src/main/java/com/github/lisicnu/log4android/appender/Appender.java | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
//
// Path: src/main/java/com/github/lisicnu/log4android/format/Formatter.java
// public interface Formatter {
//
// /**
// * Format the given message and the Throwable object.
// *
// * @param clientID
// * the id of the client
// * @param name
// * the name of the logger.
// * @param time
// * the time since the first logging has done (in milliseconds).
// * @param level
// * the logging level
// * @param message
// * the message
// * @param t
// * the exception.
// *
// * @return a String that is not null.
// */
// String format(String clientID, String name, long time, Level level,
// Object message, Throwable t);
//
// /**
// * Get the appender specific property names. This is workaround for the lack
// * of reflection in Java ME and is used for configuration.
// *
// * @return an array of the supported properties.
// */
// String[] getPropertyNames();
//
// /**
// * Set the specified property to the supplied value.
// *
// * @param name
// * the name of the property to set.
// * @param value
// * the value to set.
// */
// void setProperty(String name, String value);
// }
| import com.github.lisicnu.log4android.Level;
import com.github.lisicnu.log4android.format.Formatter;
import java.io.IOException; | /*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.appender;
/**
* The interface that all <code>Appender</code> classes must implement. An
* <code>Appender</code> is responsible for doing the actual logging.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public interface Appender {
/**
* Size returned if log size cannot be determined.
*/
int SIZE_UNDEFINED = -1;
/**
* Do the logging.
*
* @param clientID
* the id of the client.
* @param name
* the name of the logger.
* @param time
* the time since the first logging has done (in milliseconds).
* @param level
* the logging level
* @param message
* the message to log.
* @param t
* the exception to log.
*/ | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
//
// Path: src/main/java/com/github/lisicnu/log4android/format/Formatter.java
// public interface Formatter {
//
// /**
// * Format the given message and the Throwable object.
// *
// * @param clientID
// * the id of the client
// * @param name
// * the name of the logger.
// * @param time
// * the time since the first logging has done (in milliseconds).
// * @param level
// * the logging level
// * @param message
// * the message
// * @param t
// * the exception.
// *
// * @return a String that is not null.
// */
// String format(String clientID, String name, long time, Level level,
// Object message, Throwable t);
//
// /**
// * Get the appender specific property names. This is workaround for the lack
// * of reflection in Java ME and is used for configuration.
// *
// * @return an array of the supported properties.
// */
// String[] getPropertyNames();
//
// /**
// * Set the specified property to the supplied value.
// *
// * @param name
// * the name of the property to set.
// * @param value
// * the value to set.
// */
// void setProperty(String name, String value);
// }
// Path: src/main/java/com/github/lisicnu/log4android/appender/Appender.java
import com.github.lisicnu.log4android.Level;
import com.github.lisicnu.log4android.format.Formatter;
import java.io.IOException;
/*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.appender;
/**
* The interface that all <code>Appender</code> classes must implement. An
* <code>Appender</code> is responsible for doing the actual logging.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public interface Appender {
/**
* Size returned if log size cannot be determined.
*/
int SIZE_UNDEFINED = -1;
/**
* Do the logging.
*
* @param clientID
* the id of the client.
* @param name
* the name of the logger.
* @param time
* the time since the first logging has done (in milliseconds).
* @param level
* the logging level
* @param message
* the message to log.
* @param t
* the exception to log.
*/ | void doLog(String clientID, String name, long time, Level level, Object message, Throwable t); |
lisicnu/Log4Android | src/main/java/com/github/lisicnu/log4android/appender/Appender.java | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
//
// Path: src/main/java/com/github/lisicnu/log4android/format/Formatter.java
// public interface Formatter {
//
// /**
// * Format the given message and the Throwable object.
// *
// * @param clientID
// * the id of the client
// * @param name
// * the name of the logger.
// * @param time
// * the time since the first logging has done (in milliseconds).
// * @param level
// * the logging level
// * @param message
// * the message
// * @param t
// * the exception.
// *
// * @return a String that is not null.
// */
// String format(String clientID, String name, long time, Level level,
// Object message, Throwable t);
//
// /**
// * Get the appender specific property names. This is workaround for the lack
// * of reflection in Java ME and is used for configuration.
// *
// * @return an array of the supported properties.
// */
// String[] getPropertyNames();
//
// /**
// * Set the specified property to the supplied value.
// *
// * @param name
// * the name of the property to set.
// * @param value
// * the value to set.
// */
// void setProperty(String name, String value);
// }
| import com.github.lisicnu.log4android.Level;
import com.github.lisicnu.log4android.format.Formatter;
import java.io.IOException; | /*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.appender;
/**
* The interface that all <code>Appender</code> classes must implement. An
* <code>Appender</code> is responsible for doing the actual logging.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public interface Appender {
/**
* Size returned if log size cannot be determined.
*/
int SIZE_UNDEFINED = -1;
/**
* Do the logging.
*
* @param clientID
* the id of the client.
* @param name
* the name of the logger.
* @param time
* the time since the first logging has done (in milliseconds).
* @param level
* the logging level
* @param message
* the message to log.
* @param t
* the exception to log.
*/
void doLog(String clientID, String name, long time, Level level, Object message, Throwable t);
/**
* Clear the log.
*/
void clear();
/**
* Close the log. The consequence is that the logging is disabled until the
* log is opened. The logging could be enabled by calling
* <code>open()</code>.
*
* @throws java.io.IOException
* if the close failed.
*/
void close() throws IOException;
/**
* Open the log. The consequence is that the logging is enabled.
*
* @throws java.io.IOException
* if the open failed.
*
*/
void open() throws IOException;
/**
* Check if the log is open.
*
* @return true if the log is open, false otherwise.
*/
boolean isLogOpen();
/**
* Get the size of the log. This may not be applicable to all types of
* appenders.
*
* @return the size of the log.
*/
long getLogSize();
/**
* Set the formatter to use.
*
* @param formatter
* The formatter to set.
*/ | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
//
// Path: src/main/java/com/github/lisicnu/log4android/format/Formatter.java
// public interface Formatter {
//
// /**
// * Format the given message and the Throwable object.
// *
// * @param clientID
// * the id of the client
// * @param name
// * the name of the logger.
// * @param time
// * the time since the first logging has done (in milliseconds).
// * @param level
// * the logging level
// * @param message
// * the message
// * @param t
// * the exception.
// *
// * @return a String that is not null.
// */
// String format(String clientID, String name, long time, Level level,
// Object message, Throwable t);
//
// /**
// * Get the appender specific property names. This is workaround for the lack
// * of reflection in Java ME and is used for configuration.
// *
// * @return an array of the supported properties.
// */
// String[] getPropertyNames();
//
// /**
// * Set the specified property to the supplied value.
// *
// * @param name
// * the name of the property to set.
// * @param value
// * the value to set.
// */
// void setProperty(String name, String value);
// }
// Path: src/main/java/com/github/lisicnu/log4android/appender/Appender.java
import com.github.lisicnu.log4android.Level;
import com.github.lisicnu.log4android.format.Formatter;
import java.io.IOException;
/*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.appender;
/**
* The interface that all <code>Appender</code> classes must implement. An
* <code>Appender</code> is responsible for doing the actual logging.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
*/
public interface Appender {
/**
* Size returned if log size cannot be determined.
*/
int SIZE_UNDEFINED = -1;
/**
* Do the logging.
*
* @param clientID
* the id of the client.
* @param name
* the name of the logger.
* @param time
* the time since the first logging has done (in milliseconds).
* @param level
* the logging level
* @param message
* the message to log.
* @param t
* the exception to log.
*/
void doLog(String clientID, String name, long time, Level level, Object message, Throwable t);
/**
* Clear the log.
*/
void clear();
/**
* Close the log. The consequence is that the logging is disabled until the
* log is opened. The logging could be enabled by calling
* <code>open()</code>.
*
* @throws java.io.IOException
* if the close failed.
*/
void close() throws IOException;
/**
* Open the log. The consequence is that the logging is enabled.
*
* @throws java.io.IOException
* if the open failed.
*
*/
void open() throws IOException;
/**
* Check if the log is open.
*
* @return true if the log is open, false otherwise.
*/
boolean isLogOpen();
/**
* Get the size of the log. This may not be applicable to all types of
* appenders.
*
* @return the size of the log.
*/
long getLogSize();
/**
* Set the formatter to use.
*
* @param formatter
* The formatter to set.
*/ | void setFormatter(Formatter formatter); |
lisicnu/Log4Android | src/main/java/com/github/lisicnu/log4android/format/SimpleFormatter.java | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
| import com.github.lisicnu.log4android.Level; | /*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.format;
/**
* A simple formatter that only outputs the level, the message and the Throwable
* object if available.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
* @since 0.1
*/
public final class SimpleFormatter implements Formatter {
public static final String DEFAULT_DELIMITER = "-";
private static final int INITIAL_BUFFER_SIZE = 256;
StringBuffer buffer = new StringBuffer(INITIAL_BUFFER_SIZE);
private String delimiter = DEFAULT_DELIMITER;
/**
* Create a SimpleFormatter.
*/
public SimpleFormatter() {
}
/**
* Get the delimiter that is used between the different fields when logging.
*
* @return the delimiter
*/
public String getDelimiter(){
return delimiter;
}
/**
* Set the delimiter that is used between the different fields when logging.
*
* @param delimiter
* the delimiter to set
*/
public void setDelimeter(String delimiter){
this.delimiter = delimiter;
}
/**
* Format the given message and the Throwable object. The format is
* <code>{Level}{-message.toString()}{-t}</code>
*
* @param level
* the logging level. If null, it is not appended to the String.
* @param message
* the message. If null, it is not appended to the String.
* @param t
* the exception. If null, it is not appended to the String.
* @return a String that is not null.
*/ | // Path: src/main/java/com/github/lisicnu/log4android/Level.java
// public enum Level {
// FATAL(Level.FATAL_INT),
// ERROR(Level.ERROR_INT),
// WARN(Level.WARN_INT),
// INFO(Level.INFO_INT),
// DEBUG(Level.DEBUG_INT),
// TRACE(Level.TRACE_INT),
// OFF(Level.OFF_INT);
//
// public static final int FATAL_INT = 16;
// public static final int ERROR_INT = 8;
// public static final int WARN_INT = 4;
// public static final int INFO_INT = 2;
// public static final int DEBUG_INT = 1;
// public static final int TRACE_INT = 0;
// public static final int OFF_INT = -1;
//
// private final int levelValue;
//
// private Level(final int levelValue) {
// this.levelValue = levelValue;
// }
//
// public int toInt() {
// return levelValue;
// }
//
// public String toString() {
// return this.name();
// }
// }
// Path: src/main/java/com/github/lisicnu/log4android/format/SimpleFormatter.java
import com.github.lisicnu.log4android.Level;
/*
* Copyright 2008 The Microlog project @sourceforge.net
* 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.github.lisicnu.log4android.format;
/**
* A simple formatter that only outputs the level, the message and the Throwable
* object if available.
*
* @author Johan Karlsson (johan.karlsson@jayway.se)
* @since 0.1
*/
public final class SimpleFormatter implements Formatter {
public static final String DEFAULT_DELIMITER = "-";
private static final int INITIAL_BUFFER_SIZE = 256;
StringBuffer buffer = new StringBuffer(INITIAL_BUFFER_SIZE);
private String delimiter = DEFAULT_DELIMITER;
/**
* Create a SimpleFormatter.
*/
public SimpleFormatter() {
}
/**
* Get the delimiter that is used between the different fields when logging.
*
* @return the delimiter
*/
public String getDelimiter(){
return delimiter;
}
/**
* Set the delimiter that is used between the different fields when logging.
*
* @param delimiter
* the delimiter to set
*/
public void setDelimeter(String delimiter){
this.delimiter = delimiter;
}
/**
* Format the given message and the Throwable object. The format is
* <code>{Level}{-message.toString()}{-t}</code>
*
* @param level
* the logging level. If null, it is not appended to the String.
* @param message
* the message. If null, it is not appended to the String.
* @param t
* the exception. If null, it is not appended to the String.
* @return a String that is not null.
*/ | public String format(String clientID, String name, long time, Level level, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.