conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
private static Drawable createCloseCrossIcon(Context context, int width, int height, int color, int inset) {
Bitmap canvasBitmap = Bitmap.createBitmap(width + inset * 2, height + inset * 2, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(3);
paint.setColor(color);
paint.setAntiAlias(true);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(inset, inset);
path.lineTo(width + inset, height + inset);
path.moveTo(width + inset, inset);
path.lineTo(inset, height + inset);
path.close();
canvas.drawPath(path, paint);
return new BitmapDrawable(context.getResources(), canvasBitmap);
}
=======
public static Drawable createBadgeDrawable(Context context, BootstrapBrand brand, int width, int height, int badgeCount, boolean allowZeroValue, boolean insideAnObject) {
if (allowZeroValue || badgeCount > 0) {
Paint badgePaint = new Paint();
Rect canvasBounds = new Rect();
TextPaint badgeTextPaint = new TextPaint();
badgePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
badgeTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
badgeTextPaint.setTextAlign(Paint.Align.CENTER);
badgeTextPaint.setTextSize((float) (height * 0.7));
if (insideAnObject) {
badgePaint.setColor(brand.defaultTextColor(context));
badgeTextPaint.setColor(brand.defaultFill(context));
} else {
badgePaint.setColor(brand.defaultFill(context));
badgeTextPaint.setColor(brand.defaultTextColor(context));
}
int rectLength = (int) badgeTextPaint.measureText(String.valueOf(badgeCount).substring(0, String.valueOf(badgeCount).length() - 1));
Bitmap canvasBitmap = Bitmap.createBitmap(width + rectLength, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
canvas.getClipBounds(canvasBounds);
int firstCircleDx = canvasBounds.left + canvasBounds.height() / 2;
int circleDy = canvasBounds.height() / 2;
int circleRadius = canvasBounds.height() / 2;
int secondCircleDx = firstCircleDx + rectLength;
Rect rect = new Rect();
rect.left = firstCircleDx;
rect.top = 0;
rect.right = rect.left + rectLength;
rect.bottom = canvasBounds.height();
canvas.drawCircle(firstCircleDx, circleDy, circleRadius, badgePaint);
canvas.drawRect(rect, badgePaint);
canvas.drawCircle(secondCircleDx, circleDy, circleRadius, badgePaint);
canvas.drawText(String.valueOf(badgeCount), canvasBounds.width() / 2, canvasBounds.height() / 2 - ((badgeTextPaint.descent() + badgeTextPaint.ascent()) / 2), badgeTextPaint);
return new BitmapDrawable(context.getResources(), canvasBitmap);
} else return null;
}
>>>>>>>
private static Drawable createCloseCrossIcon(Context context, int width, int height, int color, int inset) {
Bitmap canvasBitmap = Bitmap.createBitmap(width + inset * 2, height + inset * 2, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(3);
paint.setColor(color);
paint.setAntiAlias(true);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(inset, inset);
path.lineTo(width + inset, height + inset);
path.moveTo(width + inset, inset);
path.lineTo(inset, height + inset);
path.close();
canvas.drawPath(path, paint);
return new BitmapDrawable(context.getResources(), canvasBitmap);
}
public static Drawable createBadgeDrawable(Context context, BootstrapBrand brand, int width, int height, int badgeCount, boolean allowZeroValue, boolean insideAnObject) {
if (allowZeroValue || badgeCount > 0) {
Paint badgePaint = new Paint();
Rect canvasBounds = new Rect();
TextPaint badgeTextPaint = new TextPaint();
badgePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
badgeTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
badgeTextPaint.setTextAlign(Paint.Align.CENTER);
badgeTextPaint.setTextSize((float) (height * 0.7));
if (insideAnObject) {
badgePaint.setColor(brand.defaultTextColor(context));
badgeTextPaint.setColor(brand.defaultFill(context));
} else {
badgePaint.setColor(brand.defaultFill(context));
badgeTextPaint.setColor(brand.defaultTextColor(context));
}
int rectLength = (int) badgeTextPaint.measureText(String.valueOf(badgeCount).substring(0, String.valueOf(badgeCount).length() - 1));
Bitmap canvasBitmap = Bitmap.createBitmap(width + rectLength, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
canvas.getClipBounds(canvasBounds);
int firstCircleDx = canvasBounds.left + canvasBounds.height() / 2;
int circleDy = canvasBounds.height() / 2;
int circleRadius = canvasBounds.height() / 2;
int secondCircleDx = firstCircleDx + rectLength;
Rect rect = new Rect();
rect.left = firstCircleDx;
rect.top = 0;
rect.right = rect.left + rectLength;
rect.bottom = canvasBounds.height();
canvas.drawCircle(firstCircleDx, circleDy, circleRadius, badgePaint);
canvas.drawRect(rect, badgePaint);
canvas.drawCircle(secondCircleDx, circleDy, circleRadius, badgePaint);
canvas.drawText(String.valueOf(badgeCount), canvasBounds.width() / 2, canvasBounds.height() / 2 - ((badgeTextPaint.descent() + badgeTextPaint.ascent()) / 2), badgeTextPaint);
return new BitmapDrawable(context.getResources(), canvasBitmap);
} else return null;
} |
<<<<<<<
public final static CommandLineOption<Integer> indicesToWatch =
CommandLine.makeInteger("indices", Integer.MAX_VALUE, CommandLineOption.Kind.EXPERIMENTAL, "Specifies max array index to watch", new Runnable() {
public void run() {
maxArrayIndex = indicesToWatch.get();
}
});
protected static int maxArrayIndex;
=======
public final static CommandLineOption<String> indicesToWatch =
CommandLine.makeString("indices", "0", CommandLineOption.Kind.EXPERIMENTAL, "Specifies which array indices sites to watch, ie 0:1:2:3:4", new Runnable() {
public void run() {
Assert.fail("indices not currently working...");
}
// final String indices = indicesToWatch.get();
// if (indices == null) {
// Assert.panic("Must specify indices to watch");
// } else {
// String is[] = indices.split(":");
// Util.log("Array Indices to watch: " + Arrays.toString(is));
// int max = 0;
// for (String i : is) {
// max = Math.max(max, Integer.parseInt(i));
// }
// bits = new boolean[max+1];
// for (String i : is) {
// bits[Integer.parseInt(i)] = true;
// }
// }
// }
//
});
// protected static boolean bits[];
//
// protected static boolean matches(final int index) {
// return bits == null || index < bits.length && bits[index];
// }
>>>>>>>
public final static CommandLineOption<Integer> indicesToWatch =
CommandLine.makeInteger("indices", Integer.MAX_VALUE, CommandLineOption.Kind.EXPERIMENTAL, "Specifies max array index to watch", new Runnable() {
public void run() {
maxArrayIndex = indicesToWatch.get();
}
});
protected static int maxArrayIndex;
<<<<<<<
return index <= maxArrayIndex;
}
=======
return true;
}
>>>>>>>
return index <= maxArrayIndex;
}
<<<<<<<
int invokeId = td.invokeId;
final InvokeInfo invokeInfo = invokeId == InvokeInfo.NULL_ID ? InvokeInfo.NULL : MetaDataInfoMaps.getInvokes().get(invokeId);
=======
>>>>>>> |
<<<<<<<
if (mEditListener != null) {
getBottomEditBar(mEditListener.getBottomGroup()).setVisibility(View.GONE);
}
=======
contentView.setEnabled(true);
>>>>>>>
contentView.setEnabled(true);
if (mEditListener != null) {
getBottomEditBar(mEditListener.getBottomGroup()).setVisibility(View.GONE);
}
<<<<<<<
toolbarBookcaseEdit.startAnimation(mTopInAnim);
if (mEditListener != null) {
getBottomEditBar(mEditListener.getBottomGroup()).setVisibility(View.VISIBLE);
}
=======
contentView.setEnabled(false);
>>>>>>>
contentView.setEnabled(false);
if (mEditListener != null) {
getBottomEditBar(mEditListener.getBottomGroup()).setVisibility(View.VISIBLE);
}
<<<<<<<
public interface OnBookCaseEditListener {
ViewGroup getBottomGroup();
}
=======
@Override
public boolean onBackPressed() {
if (toolbarBookcaseEdit.getVisibility() == VISIBLE) {
toggleEditMenu();
bookcaseAdapter.cancelEdit();
//外理返回键
return true;
}
return false;
}
>>>>>>>
public interface OnBookCaseEditListener {
ViewGroup getBottomGroup();
}
@Override
public boolean onBackPressed() {
if (toolbarBookcaseEdit.getVisibility() == VISIBLE) {
toggleEditMenu();
bookcaseAdapter.cancelEdit();
//外理返回键
return true;
}
return false;
} |
<<<<<<<
if (loadMoreView != null) {
loadMoreView.makeMoreLoading();
}
=======
if (loadMoreView != null)
loadMoreView.showLoading();
>>>>>>>
if (loadMoreView != null) {
loadMoreView.showTheEnd();
}
<<<<<<<
if (loadMoreView != null) {
loadMoreView.makeMoreError();
}
=======
if (loadMoreView != null)
loadMoreView.showError();
>>>>>>>
if (loadMoreView != null) {
loadMoreView.showError();
}
<<<<<<<
if (loadMoreView != null) {
loadMoreView.makeTheEnd();
}
=======
if (loadMoreView != null)
loadMoreView.showTheEnd();
>>>>>>>
if (loadMoreView != null) {
loadMoreView.showTheEnd();
}
<<<<<<<
if (loadMoreView != null) {
loadMoreView.makeMoreGone();
}
=======
if (loadMoreView != null)
loadMoreView.showNone();
>>>>>>>
if (loadMoreView != null) {
loadMoreView.showNone();
} |
<<<<<<<
kinectRegions = new ArrayList<KinectRegion>();
int colW = (IKinectWrapper.KWIDTH - padding*(cols-1)) / cols;
=======
int colW = (KinectWrapper.KWIDTH - padding*(cols-1)) / cols;
>>>>>>>
int colW = (IKinectWrapper.KWIDTH - padding*(cols-1)) / cols; |
<<<<<<<
import com.google.common.collect.Sets;
=======
import com.google.common.collect.Sets;
>>>>>>>
import com.google.common.collect.Sets;
<<<<<<<
=======
import com.spotify.reaper.core.RepairUnit;
>>>>>>>
import com.spotify.reaper.core.RepairUnit;
<<<<<<<
=======
import com.spotify.reaper.cassandra.JmxConnectionFactory;
>>>>>>>
import com.spotify.reaper.cassandra.JmxConnectionFactory;
<<<<<<<
=======
>>>>>>>
<<<<<<<
* @return repair run ID in case of everything going well,
* and a status code 500 in case of errors.
=======
* Notice that query parameter "tables" can be a single String, or a comma-separated list
* of table names. If the "tables" parameter is omitted, and only the keyspace is defined,
* then created repair run will target all the tables in the keyspace.
*
* @return repair run ID in case of everything going well,
* and a status code 500 in case of errors.
>>>>>>>
* @return repair run ID in case of everything going well,
* and a status code 500 in case of errors.
<<<<<<<
Optional<Cluster> cluster = storage.getCluster(clusterName.get());
if (!cluster.isPresent()) {
return Response.status(Response.Status.NOT_FOUND).entity(
"no cluster found with name '" + clusterName + "'").build();
}
JmxProxy jmxProxy = jmxFactory.create(cluster.get().getSeedHosts().iterator().next());
Set<String> knownTables = jmxProxy.getTableNamesForKeyspace(keyspace.get());
if (knownTables.size() == 0) {
LOG.debug("no known tables for keyspace {} in cluster {}", keyspace.get(),
clusterName.get());
return Response.status(Response.Status.NOT_FOUND).entity(
"no column families found for keyspace").build();
}
jmxProxy.close();
Set<String> tableNames;
if (tableNamesParam.isPresent()) {
tableNames = Sets.newHashSet(COMMA_SEPARATED_LIST_SPLITTER.split(tableNamesParam.get()));
} else {
tableNames = knownTables;
}
Optional<RepairUnit> storedRepairUnit =
storage.getRepairUnit(clusterName.get(), keyspace.get(), tableNames);
RepairUnit theRepairUnit;
if (storedRepairUnit.isPresent()) {
if (segmentCount.isPresent()) {
LOG.warn("stored repair unit already exists, and segment count given, "
+ "which is thus ignored");
}
theRepairUnit = storedRepairUnit.get();
} else {
int segments = config.getSegmentCount();
if (segmentCount.isPresent()) {
LOG.debug("using given segment count {} instead of configured value {}",
segmentCount.get(), config.getSegmentCount());
segments = segmentCount.get();
}
LOG.info("create new repair unit for cluster '{}', keyspace '{}', and column families: {}",
clusterName.get(), keyspace.get(), tableNames);
theRepairUnit = storage.addRepairUnit(new RepairUnit.Builder(clusterName.get(),
keyspace.get(), tableNames, segments, config.getSnapshotRepair()));
}
RepairRun newRepairRun = registerRepairRun(cluster.get(), theRepairUnit, cause, owner.get());
=======
Cluster cluster = getCluster(clusterName.get());
JmxProxy jmxProxy = jmxFactory.create(cluster.getSeedHosts().iterator().next());
Set<String> knownTables = jmxProxy.getTableNamesForKeyspace(keyspace.get());
if (knownTables.size() == 0) {
LOG.debug("no known tables for keyspace {} in cluster {}", keyspace.get(),
clusterName.get());
return Response.status(Response.Status.NOT_FOUND).entity(
"no column families found for keyspace").build();
}
jmxProxy.close();
Set<String> tableNames;
if (tableNamesParam.isPresent()) {
tableNames = Sets.newHashSet(COMMA_SEPARATED_LIST_SPLITTER.split(tableNamesParam.get()));
} else {
tableNames = knownTables;
}
Optional<RepairUnit> storedRepairUnit =
storage.getRepairUnit(clusterName.get(), keyspace.get(), tableNames);
RepairUnit theRepairUnit;
if (storedRepairUnit.isPresent()) {
if (segmentCount.isPresent()) {
LOG.warn("stored repair unit already exists, and segment count given, "
+ "which is thus ignored");
}
theRepairUnit = storedRepairUnit.get();
} else {
int segments = config.getSegmentCount();
if (segmentCount.isPresent()) {
LOG.debug("using given segment count {} instead of configured value {}",
segmentCount.get(), config.getSegmentCount());
segments = segmentCount.get();
}
LOG.info("create new repair unit for cluster '{}', keyspace '{}', and column families: {}",
clusterName.get(), keyspace.get(), tableNames);
theRepairUnit = storage.addRepairUnit(new RepairUnit.Builder(clusterName.get(),
keyspace.get(), tableNames, segments, config.getSnapshotRepair()));
}
RepairRun newRepairRun = registerRepairRun(cluster, theRepairUnit, cause, owner.get());
>>>>>>>
Optional<Cluster> cluster = storage.getCluster(clusterName.get());
if (!cluster.isPresent()) {
return Response.status(Response.Status.NOT_FOUND).entity(
"no cluster found with name '" + clusterName + "'").build();
}
JmxProxy jmxProxy = jmxFactory.create(cluster.get().getSeedHosts().iterator().next());
Set<String> knownTables = jmxProxy.getTableNamesForKeyspace(keyspace.get());
if (knownTables.size() == 0) {
LOG.debug("no known tables for keyspace {} in cluster {}", keyspace.get(),
clusterName.get());
return Response.status(Response.Status.NOT_FOUND).entity(
"no column families found for keyspace").build();
}
jmxProxy.close();
Set<String> tableNames;
if (tableNamesParam.isPresent()) {
tableNames = Sets.newHashSet(COMMA_SEPARATED_LIST_SPLITTER.split(tableNamesParam.get()));
} else {
tableNames = knownTables;
}
Optional<RepairUnit> storedRepairUnit =
storage.getRepairUnit(clusterName.get(), keyspace.get(), tableNames);
RepairUnit theRepairUnit;
if (storedRepairUnit.isPresent()) {
if (segmentCount.isPresent()) {
LOG.warn("stored repair unit already exists, and segment count given, "
+ "which is thus ignored");
}
theRepairUnit = storedRepairUnit.get();
} else {
int segments = config.getSegmentCount();
if (segmentCount.isPresent()) {
LOG.debug("using given segment count {} instead of configured value {}",
segmentCount.get(), config.getSegmentCount());
segments = segmentCount.get();
}
LOG.info("create new repair unit for cluster '{}', keyspace '{}', and column families: {}",
clusterName.get(), keyspace.get(), tableNames);
theRepairUnit = storage.addRepairUnit(new RepairUnit.Builder(clusterName.get(),
keyspace.get(), tableNames, segments, config.getSnapshotRepair()));
}
RepairRun newRepairRun = registerRepairRun(cluster.get(), theRepairUnit, cause, owner.get());
<<<<<<<
return Response.status(Response.Status.OK).entity(new RepairRunStatus(repairRun, repairUnit))
.build();
=======
return Response.status(Response.Status.OK).entity(new RepairRunStatus(repairRun, repairUnit))
.build();
>>>>>>>
return Response.status(Response.Status.OK).entity(new RepairRunStatus(repairRun, repairUnit))
.build();
<<<<<<<
Optional<RepairRun> repairRun = storage.getRepairRun(repairRunId);
if (repairRun.isPresent()) {
return Response.ok().entity(getRepairRunStatus(repairRun.get())).build();
} else {
return Response.status(404).entity(
"repair run with id " + repairRunId + " doesn't exist").build();
=======
Optional<RepairRun> repairRun = storage.getRepairRun(repairRunId);
if (repairRun.isPresent()) {
return Response.ok().entity(getRepairRunStatus(repairRun.get())).build();
}
else {
return Response.status(404).entity(
"repair run with id " + repairRunId + " doesn't exist").build();
>>>>>>>
Optional<RepairRun> repairRun = storage.getRepairRun(repairRunId);
if (repairRun.isPresent()) {
return Response.ok().entity(getRepairRunStatus(repairRun.get())).build();
} else {
return Response.status(404).entity(
"repair run with id " + repairRunId + " doesn't exist").build();
<<<<<<<
=======
* @return cluster information for the given cluster name
* @throws ReaperException if cluster with given name is not found
*/
private Cluster getCluster(String clusterName) throws ReaperException {
Cluster cluster = storage.getCluster(clusterName);
if (cluster == null) {
throw new ReaperException(String.format("Cluster \"%s\" not found", clusterName));
}
return cluster;
}
/**
>>>>>>>
<<<<<<<
RepairUnit repairUnit) throws ReaperException {
List<RepairSegment.Builder> repairSegmentBuilders = Lists.newArrayList();
=======
RepairUnit table) throws ReaperException {
List <RepairSegment.Builder> repairSegmentBuilders = Lists.newArrayList();
>>>>>>>
RepairUnit repairUnit) throws ReaperException {
List<RepairSegment.Builder> repairSegmentBuilders = Lists.newArrayList();
<<<<<<<
boolean success = storage.addRepairSegments(repairSegmentBuilders, repairRun.getId());
if (!success) {
throw new ReaperException("failed adding repair segments to storage");
}
if (repairUnit.getSegmentCount() != tokenSegments.size()) {
LOG.debug("created segment amount differs from expected default {} != {}",
repairUnit.getSegmentCount(), tokenSegments.size());
// TODO: update the RepairUnit with new segment count
}
=======
boolean success = storage.addRepairSegments(repairSegmentBuilders, repairRun.getId());
if (!success) {
throw new ReaperException("failed adding repair segments to storage");
}
>>>>>>>
boolean success = storage.addRepairSegments(repairSegmentBuilders, repairRun.getId());
if (!success) {
throw new ReaperException("failed adding repair segments to storage");
}
if (repairUnit.getSegmentCount() != tokenSegments.size()) {
LOG.debug("created segment amount differs from expected default {} != {}",
repairUnit.getSegmentCount(), tokenSegments.size());
// TODO: update the RepairUnit with new segment count
}
<<<<<<<
Optional<RepairUnit> repairUnit = storage.getRepairUnit(repairRun.getRepairUnitId());
assert repairUnit.isPresent() : "no repair unit found with id: " + repairRun.getRepairUnitId();
RepairRunStatus repairRunStatus = new RepairRunStatus(repairRun, repairUnit.get());
=======
RepairUnit repairUnit = storage.getColumnFamily(repairRun.getRepairUnitId());
RepairRunStatus repairRunStatus = new RepairRunStatus(repairRun, repairUnit);
>>>>>>>
Optional<RepairUnit> repairUnit = storage.getRepairUnit(repairRun.getRepairUnitId());
assert repairUnit.isPresent() : "no repair unit found with id: " + repairRun.getRepairUnitId();
RepairRunStatus repairRunStatus = new RepairRunStatus(repairRun, repairUnit.get()); |
<<<<<<<
private final Integer repairCommandId; // received when triggering repair in Cassandra
private final long repairUnitId;
=======
>>>>>>>
<<<<<<<
public Integer getRepairCommandId() {
return repairCommandId;
}
public long getRepairUnitId() {
return repairUnitId;
}
=======
>>>>>>>
<<<<<<<
this.repairCommandId = builder.repairCommandId;
this.repairUnitId = builder.repairUnitId;
=======
>>>>>>>
<<<<<<<
private final long repairUnitId;
private State state;
=======
>>>>>>>
<<<<<<<
this.repairUnitId = repairUnitId;
this.state = State.NOT_STARTED;
=======
>>>>>>>
<<<<<<<
repairUnitId = original.repairUnitId;
=======
state = original.state;
coordinatorHost = original.coordinatorHost;
>>>>>>>
state = original.state;
coordinatorHost = original.coordinatorHost; |
<<<<<<<
import io.cassandrareaper.core.DroppedMessages;
import io.cassandrareaper.core.MetricsHistogram;
import io.cassandrareaper.core.Node;
=======
>>>>>>>
import io.cassandrareaper.core.DroppedMessages;
import io.cassandrareaper.core.MetricsHistogram;
<<<<<<<
import io.cassandrareaper.core.ThreadPoolStat;
import io.cassandrareaper.jmx.JmxConnectionFactory;
import io.cassandrareaper.jmx.JmxProxy;
=======
>>>>>>>
import io.cassandrareaper.core.ThreadPoolStat; |
<<<<<<<
=======
import org.apache.cassandra.utils.SimpleCondition;
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.LazyInitializer;
>>>>>>>
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.LazyInitializer; |
<<<<<<<
import android.os.Environment;
=======
import android.os.IBinder;
>>>>>>>
import android.os.Environment;
import android.os.IBinder;
<<<<<<<
private static final int MENU_RHIZOME = 3;
private static final int MENU_ABOUT = 4;
=======
private static final int MENU_ABOUT = 3;
private static final int MENU_REDETECT = 4;
>>>>>>>
private static final int MENU_REDETECT = 3;
private static final int MENU_RHIZOME = 4;
private static final int MENU_ABOUT = 5;
<<<<<<<
m = menu
.addSubMenu(0, MENU_RHIZOME, 0, getString(R.string.rhizometext));
m.setIcon(drawable.ic_menu_agenda);
=======
m = menu.addSubMenu(0, MENU_REDETECT, 0,
getString(R.string.redetecttext));
m.setIcon(R.drawable.ic_menu_refresh);
>>>>>>>
m = menu.addSubMenu(0, MENU_REDETECT, 0,
getString(R.string.redetecttext));
m.setIcon(R.drawable.ic_menu_refresh);
m = menu
.addSubMenu(0, MENU_RHIZOME, 0, getString(R.string.rhizometext));
m.setIcon(drawable.ic_menu_agenda);
<<<<<<<
case MENU_RHIZOME:
// Check if there's a SD card, because no SD card will lead Rhizome
// to crash - code from Android doc
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
startActivity(new Intent(this, RhizomeRetriever.class));
} else {
app.displayToastMessage(getString(R.string.rhizomesdcard));
}
break;
=======
case MENU_REDETECT:
// Clear out old attempt_ files
File varDir = new File("/data/data/org.servalproject/var/");
if (varDir.isDirectory())
for (File f : varDir.listFiles()) {
if (!f.getName().startsWith("attempt_"))
continue;
f.delete();
}
// Re-run wizard
PreparationWizard.currentAction = Action.NotStarted;
Intent prepintent = new Intent(this, PreparationWizard.class);
prepintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(prepintent);
break;
>>>>>>>
case MENU_REDETECT:
// Clear out old attempt_ files
File varDir = new File("/data/data/org.servalproject/var/");
if (varDir.isDirectory())
for (File f : varDir.listFiles()) {
if (!f.getName().startsWith("attempt_"))
continue;
f.delete();
}
// Re-run wizard
PreparationWizard.currentAction = Action.NotStarted;
Intent prepintent = new Intent(this, PreparationWizard.class);
prepintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(prepintent);
break;
case MENU_RHIZOME:
// Check if there's a SD card, because no SD card will lead Rhizome
// to crash - code from Android doc
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
startActivity(new Intent(this, RhizomeRetriever.class));
} else {
app.displayToastMessage(getString(R.string.rhizomesdcard));
}
break; |
<<<<<<<
import org.servalproject.wizard.Wizard;
=======
import org.servalproject.wizard.Wizard;
import org.sipdroid.sipua.UserAgent;
import org.sipdroid.sipua.ui.Receiver;
>>>>>>>
import org.servalproject.wizard.Wizard;
<<<<<<<
// show the messages activity
ImageView mImageView = (ImageView) findViewById(R.id.messageLabel);
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
startActivityForResult(new Intent(getApplicationContext(),
org.servalproject.messages.MessagesListActivity.class),
0);
}
});
=======
// check on the state of the storage
String mStorageState = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(mStorageState) == false) {
// show a dialog and disable the button
AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
mBuilder.setMessage(R.string.disclaimer_ui_dialog_no_storage)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mAlert = mBuilder.create();
mAlert.show();
mContinue = false;
}
if(Environment.MEDIA_MOUNTED.equals(mStorageState) == false) {
// show a dialog and disable the button
AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
mBuilder.setMessage(R.string.disclaimer_ui_dialog_no_storage)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mAlert = mBuilder.create();
mAlert.show();
mContinue = false;
}
>>>>>>>
// show the messages activity
ImageView mImageView = (ImageView) findViewById(R.id.messageLabel);
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
startActivityForResult(new Intent(getApplicationContext(),
org.servalproject.messages.MessagesListActivity.class),
0);
}
});
<<<<<<<
PackageManager mManager = getPackageManager();
mManager.getApplicationInfo("org.servalproject.maps",
PackageManager.GET_META_DATA);
Intent mIntent = mManager
.getLaunchIntentForPackage("org.servalproject.maps");
mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(mIntent);
} catch (NameNotFoundException e) {
startActivityForResult(new Intent(getApplicationContext(),
org.servalproject.ui.MapsActivity.class),
0);
=======
getPackageManager().getApplicationInfo("org.servalproject.maps",
PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
//Log.e(TAG, "serval maps was not found", e);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
mBuilder.setMessage(R.string.disclaimer_ui_dialog_no_serval_mesh)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mAlert = mBuilder.create();
mAlert.show();
mContinue = false;
>>>>>>>
PackageManager mManager = getPackageManager();
mManager.getApplicationInfo("org.servalproject.maps",
PackageManager.GET_META_DATA);
Intent mIntent = mManager
.getLaunchIntentForPackage("org.servalproject.maps");
mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(mIntent);
} catch (NameNotFoundException e) {
startActivityForResult(new Intent(getApplicationContext(),
org.servalproject.ui.MapsActivity.class),
0);
<<<<<<<
private void stateChanged(State state) {
buttonToggle.setText(state.getResourceId());
}
=======
>>>>>>>
private void stateChanged(State state) {
buttonToggle.setText(state.getResourceId());
}
<<<<<<<
case MENU_RHIZOME:
// If there is no SD card, then instead of starting the rhizome activity, pop a message.
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
startActivity(new Intent(this, RhizomeList.class));
} else {
app.displayToastMessage(getString(R.string.rhizomesdcard));
}
break;
=======
// case MENU_RHIZOME:
// // If there is no SD card, then instead of starting the rhizome
// activity, pop a message.
// String state = Environment.getExternalStorageState();
// if (Environment.MEDIA_MOUNTED.equals(state)) {
// startActivity(new Intent(this, RhizomeMain.class));
// } else {
// app.displayToastMessage(getString(R.string.rhizomesdcard));
// }
// break;
>>>>>>>
// case MENU_RHIZOME:
// // If there is no SD card, then instead of starting the rhizome
// activity, pop a message.
// String state = Environment.getExternalStorageState();
// if (Environment.MEDIA_MOUNTED.equals(state)) {
// startActivity(new Intent(this, RhizomeMain.class));
// } else {
// app.displayToastMessage(getString(R.string.rhizomesdcard));
// }
// break; |
<<<<<<<
import jenkins.model.Jenkins;
=======
import jenkins.model.ArtifactManager;
>>>>>>>
import jenkins.model.ArtifactManager;
import jenkins.model.Jenkins;
<<<<<<<
final File artifactsDir = build.getArtifactsDir();
final FilePath workspace = build.getWorkspace();
if (workspace == null) {
throw new BuildNodeUnavailableException();
}
final FilePath logcatFile = workspace.createTextTempFile("logcat_", ".log", "", false);
=======
final ArtifactManager artifactManager = build.getArtifactManager();
final FilePath logcatFile = build.getWorkspace().createTextTempFile("logcat_", ".log", "", false);
>>>>>>>
final FilePath workspace = build.getWorkspace();
if (workspace == null) {
throw new BuildNodeUnavailableException();
}
final ArtifactManager artifactManager = build.getArtifactManager();
final FilePath logcatFile = build.getWorkspace().createTextTempFile("logcat_", ".log", "", false);
<<<<<<<
cleanUp(emuConfig, emu, androidSdk, logWriter, logcatFile, logcatStream, artifactsDir);
=======
cleanUp(emuConfig, emu, logWriter, logcatFile, logcatStream, artifactManager, launcher, listener);
>>>>>>>
cleanUp(emuConfig, emu, androidSdk, logWriter, logcatFile, logcatStream, artifactManager, launcher, listener);
<<<<<<<
cleanUp(emuConfig, emu, androidSdk, logWriter, logcatFile, logcatStream, artifactsDir);
=======
cleanUp(emuConfig, emu, logWriter, logcatFile, logcatStream, artifactManager, launcher, listener);
>>>>>>>
cleanUp(emuConfig, emu, androidSdk, logWriter, logcatFile, logcatStream, artifactManager, launcher, listener);
<<<<<<<
private void cleanUp(EmulatorConfig emulatorConfig, AndroidEmulatorContext emu, final AndroidSdk androidSdk) throws IOException, InterruptedException {
cleanUp(emulatorConfig, emu, androidSdk, null, null, null, null);
=======
private void cleanUp(EmulatorConfig emulatorConfig, AndroidEmulatorContext emu) throws IOException, InterruptedException {
cleanUp(emulatorConfig, emu, null, null, null, null, null, null);
>>>>>>>
private void cleanUp(EmulatorConfig emulatorConfig, AndroidEmulatorContext emu, final AndroidSdk androidSdk) throws IOException, InterruptedException {
cleanUp(emulatorConfig, emu, androidSdk, null, null, null, null, null, null);
<<<<<<<
private void cleanUp(EmulatorConfig emulatorConfig, AndroidEmulatorContext emu, final AndroidSdk androidSdk, Proc logcatProcess,
FilePath logcatFile, OutputStream logcatStream, File artifactsDir) throws IOException, InterruptedException {
=======
private void cleanUp(EmulatorConfig emulatorConfig, AndroidEmulatorContext emu,
Proc logcatProcess, FilePath logcatFile, OutputStream logcatStream,
ArtifactManager artifactManager, Launcher launcher, BuildListener listener)
throws IOException, InterruptedException {
>>>>>>>
private void cleanUp(EmulatorConfig emulatorConfig, AndroidEmulatorContext emu, AndroidSdk androidSdk,
@Nullable Proc logcatProcess, @Nullable FilePath logcatFile, @Nullable OutputStream logcatStream,
@Nullable ArtifactManager artifactManager, @Nullable Launcher launcher, @Nullable BuildListener listener)
throws IOException, InterruptedException { |
<<<<<<<
=======
import dk.alexandra.fresco.lib.arithmetic.LogicTests;
import dk.alexandra.fresco.lib.arithmetic.SortingTests;
import dk.alexandra.fresco.suite.ProtocolSuite;
import dk.alexandra.fresco.suite.spdz.configuration.SpdzConfiguration;
import dk.alexandra.fresco.suite.spdz.configuration.SpdzConfigurationFromProperties;
import dk.alexandra.fresco.suite.spdz.evaluation.strategy.SpdzProtocolSuite;
import dk.alexandra.fresco.suite.spdz.storage.InitializeStorage;
public class TestSpdzComparison {
private static final int noOfParties = 2;
private void runTest(TestThreadFactory f, EvaluationStrategy evalStrategy,
StorageStrategy storageStrategy) throws Exception {
Level logLevel = Level.FINE;
Reporter.init(logLevel);
// Since SCAPI currently does not work with ports > 9999 we use fixed
// ports
// here instead of relying on ephemeral ports which are often > 9999.
List<Integer> ports = new ArrayList<Integer>(noOfParties);
for (int i = 1; i <= noOfParties; i++) {
ports.add(9000 + i);
}
Map<Integer, NetworkConfiguration> netConf = TestConfiguration
.getNetworkConfigurations(noOfParties, ports, logLevel);
Map<Integer, TestThreadConfiguration> conf = new HashMap<Integer, TestThreadConfiguration>();
for (int playerId : netConf.keySet()) {
TestThreadConfiguration ttc = new TestThreadConfiguration();
ttc.netConf = netConf.get(playerId);
>>>>>>>
<<<<<<<
=======
@Test
public void test_isSorted() throws Exception {
runTest(new SortingTests.TestIsSorted(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
}
@Test
public void test_compareAndSwap() throws Exception {
runTest(new SortingTests.TestCompareAndSwap(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
}
@Test
public void test_Sort() throws Exception {
runTest(new SortingTests.TestSort(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
}
@Test
@Ignore
public void test_Big_Sort() throws Exception {
runTest(new SortingTests.TestBigSort(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
}
@Test
public void test_logic() throws Exception {
runTest(new LogicTests.TestLogic(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
}
>>>>>>>
@Test
public void test_isSorted() throws Exception {
runTest(new SortingTests.TestIsSorted(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
}
@Test
public void test_compareAndSwap() throws Exception {
runTest(new SortingTests.TestCompareAndSwap(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
}
@Test
public void test_Sort() throws Exception {
runTest(new SortingTests.TestSort(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
}
@Test
@Ignore
public void test_Big_Sort() throws Exception {
runTest(new SortingTests.TestBigSort(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
}
@Test
public void test_logic() throws Exception {
runTest(new LogicTests.TestLogic(),
EvaluationStrategy.SEQUENTIAL,StorageStrategy.IN_MEMORY);
} |
<<<<<<<
=======
/*******************************************************************************
* Copyright (c) 2015 FRESCO (http://github.com/aicis/fresco).
*
* This file is part of the FRESCO project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* FRESCO uses SCAPI - http://crypto.biu.ac.il/SCAPI, Crypto++, Miracl, NTL, and Bouncy Castle.
* Please see these projects for any further licensing issues.
*******************************************************************************/
>>>>>>> |
<<<<<<<
=======
import java.util.ArrayList;
import org.junit.Test;
>>>>>>> |
<<<<<<<
private Computation<SInt> sign(ProtocolBuilderNumeric builder, Computation<SInt> input) {
Computation<SInt> result = gte(builder, input,
builder.numeric().known(BigInteger.valueOf(0)));
BigInteger two = BigInteger.valueOf(2);
BigInteger one = BigInteger.valueOf(1);
result = builder.numeric().mult(two, result);
result = builder.numeric().sub(result, one);
return result;
}
private Computation<SInt> gte(ProtocolBuilderNumeric builder, Computation<SInt> left,
Computation<SInt> right) {
// TODO: workaround for the fact that the GreaterThanProtocol actually calculated left <= right.
Computation<SInt> actualLeft = right;
Computation<SInt> actualRight = left;
return builder.comparison().compareLEQ(actualLeft, actualRight);
}
private Computation<SInt> exp2(ProtocolBuilderNumeric builder, Computation<SInt> exponent,
=======
private Computation<SInt> exp2(SequentialNumericBuilder builder, Computation<SInt> exponent,
>>>>>>>
private Computation<SInt> sign(ProtocolBuilderNumeric builder, Computation<SInt> input) {
Computation<SInt> result = gte(builder, input,
builder.numeric().known(BigInteger.valueOf(0)));
BigInteger two = BigInteger.valueOf(2);
BigInteger one = BigInteger.valueOf(1);
result = builder.numeric().mult(two, result);
result = builder.numeric().sub(result, one);
return result;
}
private Computation<SInt> gte(ProtocolBuilderNumeric builder, Computation<SInt> left,
Computation<SInt> right) {
// TODO: workaround for the fact that the GreaterThanProtocol actually calculated left <= right.
Computation<SInt> actualLeft = right;
Computation<SInt> actualRight = left;
return builder.comparison().compareLEQ(actualLeft, actualRight);
}
private Computation<SInt> exp2(ProtocolBuilderNumeric builder, Computation<SInt> exponent,
private Computation<SInt> exp2(SequentialNumericBuilder builder, Computation<SInt> exponent, |
<<<<<<<
=======
/*
* Copyright (c) 2015, 2016 FRESCO (http://github.com/aicis/fresco).
*
* This file is part of the FRESCO project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* FRESCO uses SCAPI - http://crypto.biu.ac.il/SCAPI, Crypto++, Miracl, NTL, and Bouncy Castle.
* Please see these projects for any further licensing issues.
*/
>>>>>>> |
<<<<<<<
public static void main(String[] args) throws NoSuchAlgorithmException {
=======
public static void main(String[] args) throws IOException {
>>>>>>>
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
<<<<<<<
Network network = new KryoNetNetwork();
network.init(getNetworkConfiguration(pid), 1);
SpdzStorage store = new SpdzStorageImpl(new DummyDataSupplierImpl(pid, getNetworkConfiguration(pid).noOfParties()));
SpdzResourcePool rp = new SpdzResourcePoolImpl(pid, getNetworkConfiguration(pid).noOfParties(),
network, new Random(), new DetermSecureRandom(), store);
=======
try (KryoNetNetwork network = new KryoNetNetwork(getNetworkConfiguration(pid))) {
SpdzStorage store = new SpdzStorageDummyImpl(pid, getNetworkConfiguration(pid).noOfParties());
SpdzResourcePool rp = new SpdzResourcePoolImpl(pid,
getNetworkConfiguration(pid).noOfParties(),
new Random(), new DetermSecureRandom(), store);
>>>>>>>
try (KryoNetNetwork network = new KryoNetNetwork(getNetworkConfiguration(pid))) {
SpdzStorage store = new SpdzStorageImpl(new DummyDataSupplierImpl(pid, getNetworkConfiguration(pid).noOfParties()));
SpdzResourcePool rp = new SpdzResourcePoolImpl(pid, getNetworkConfiguration(pid).noOfParties(),
new Random(), new DetermSecureRandom(), store); |
<<<<<<<
=======
/*
* Copyright (c) 2015, 2016 FRESCO (http://github.com/aicis/fresco).
*
* This file is part of the FRESCO project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* FRESCO uses SCAPI - http://crypto.biu.ac.il/SCAPI, Crypto++, Miracl, NTL, and Bouncy Castle.
* Please see these projects for any further licensing issues.
*******************************************************************************/
>>>>>>> |
<<<<<<<
import java.util.ArrayList;
import java.util.List;
import dk.alexandra.fresco.framework.Computation;
import dk.alexandra.fresco.framework.builder.ComputationBuilder;
import dk.alexandra.fresco.framework.builder.ProtocolBuilderNumeric.SequentialNumericBuilder;
=======
import dk.alexandra.fresco.framework.DRes;
import dk.alexandra.fresco.framework.builder.Computation;
import dk.alexandra.fresco.framework.builder.numeric.ProtocolBuilderNumeric;
>>>>>>>
import java.util.ArrayList;
import java.util.List;
import dk.alexandra.fresco.framework.DRes;
import dk.alexandra.fresco.framework.builder.Computation;
import dk.alexandra.fresco.framework.builder.numeric.ProtocolBuilderNumeric; |
<<<<<<<
import dk.alexandra.fresco.framework.network.NetworkCreator;
import dk.alexandra.fresco.framework.sce.resources.ResourcePool;
import dk.alexandra.fresco.framework.sce.resources.ResourcePoolImpl;
import dk.alexandra.fresco.framework.value.OInt;
=======
import dk.alexandra.fresco.framework.builder.BuilderFactoryNumeric;
import dk.alexandra.fresco.framework.builder.ProtocolBuilderNumeric;
import dk.alexandra.fresco.framework.builder.ProtocolBuilderNumeric.SequentialNumericBuilder;
import dk.alexandra.fresco.framework.network.ResourcePoolCreator;
import dk.alexandra.fresco.framework.sce.resources.ResourcePool;
>>>>>>>
import dk.alexandra.fresco.framework.sce.resources.ResourcePool;
import dk.alexandra.fresco.framework.sce.resources.ResourcePoolImpl;
import dk.alexandra.fresco.framework.builder.BuilderFactoryNumeric;
import dk.alexandra.fresco.framework.builder.ProtocolBuilderNumeric;
import dk.alexandra.fresco.framework.builder.ProtocolBuilderNumeric.SequentialNumericBuilder;
import dk.alexandra.fresco.framework.network.ResourcePoolCreator;
<<<<<<<
import dk.alexandra.fresco.lib.field.integer.RandomFieldElementFactory;
import dk.alexandra.fresco.lib.helper.builder.NumericIOBuilder;
import dk.alexandra.fresco.lib.helper.sequential.SequentialProtocolProducer;
import dk.alexandra.fresco.lib.lp.LPFactory;
import dk.alexandra.fresco.lib.lp.LPFactoryImpl;
import dk.alexandra.fresco.lib.math.integer.NumericBitFactory;
import dk.alexandra.fresco.lib.math.integer.exp.ExpFromOIntFactory;
import dk.alexandra.fresco.lib.math.integer.exp.PreprocessedExpPipeFactory;
import dk.alexandra.fresco.lib.math.integer.inv.LocalInversionFactory;
=======
import dk.alexandra.fresco.lib.helper.SequentialProtocolProducer;
import java.util.ArrayList;
>>>>>>>
import dk.alexandra.fresco.lib.helper.builder.NumericIOBuilder;
import dk.alexandra.fresco.lib.helper.SequentialProtocolProducer;
import java.util.ArrayList;
<<<<<<<
public static class TestIsSortedMultiOutput extends TestThreadFactory {
@Override
public TestThread next(TestThreadConfiguration conf) {
return new TestThread() {
@Override
public void test() throws Exception {
final int PAIRS = 10;
final int MAXVALUE = 20000;
final int NOTFOUND = -1;
int[] keys = new int[PAIRS];
int[] values = new int[PAIRS];
SInt[] sKeys = new SInt[PAIRS];
SInt[][] sValues = new SInt[10][PAIRS];
TestApplication app = new TestApplication() {
private static final long serialVersionUID = 7960372460887688296L;
@Override
public ProtocolProducer prepareApplication(
ProtocolFactory factory) {
BasicNumericFactory bnFactory = (BasicNumericFactory) factory;
NumericIOBuilder ioBuilder = new NumericIOBuilder(bnFactory);
SequentialProtocolProducer seq = new SequentialProtocolProducer();
Random rand = new Random(0);
for (int i = 0; i < PAIRS; i++) {
keys[i] = i;
sKeys[i] = bnFactory.getSInt();
for(int j= 0; j< 10; j++) {
sValues[j][i] = bnFactory.getSInt();
}
seq.append(bnFactory.getSInt(i, sKeys[i]));
values[i] = rand.nextInt(MAXVALUE);
for(int j= 0; j< 10; j++) {
seq.append(bnFactory.getSInt(values[i], sValues[j][i]));
}
}
return seq;
}
};
ResourcePoolImpl resourcePool = NetworkCreator.createResourcePool(conf.sceConf);
secureComputationEngine
.runApplication(app, resourcePool);
for (int i = 0; i < 10; i++) {
final int counter = i;
TestApplication app1 = new TestApplication() {
@Override
public ProtocolProducer prepareApplication(ProtocolFactory factory) {
BasicNumericFactory bnf = (BasicNumericFactory) factory;
LocalInversionFactory localInvFactory = (LocalInversionFactory) factory;
NumericBitFactory numericBitFactory = (NumericBitFactory) factory;
ExpFromOIntFactory expFromOIntFactory = (ExpFromOIntFactory) factory;
PreprocessedExpPipeFactory expFactory = (PreprocessedExpPipeFactory) factory;
RandomFieldElementFactory randFactory = (RandomFieldElementFactory) factory;
LPFactory lpFactory = new LPFactoryImpl(80, bnf, localInvFactory, numericBitFactory,
expFromOIntFactory, expFactory, randFactory);
LookUpProtocolFactory<SInt> lpf = new LookupProtocolFactoryImpl(80, lpFactory, bnf);
SInt[] sOut = new SInt[10];
NumericIOBuilder ioBuilder = new NumericIOBuilder(bnf);
for(int j= 0; j<sOut.length; j++) {
sOut[j] = bnf.getSInt(NOTFOUND);
}
SequentialProtocolProducer sequentialProtocolProducer = new SequentialProtocolProducer();
sequentialProtocolProducer.append(lpf
.getLookUpProtocol(sKeys[counter], sKeys, sValues,
sOut));
OInt[] out = new OInt[5];
for(int j = 0; j<5; j++) {
out[j] = bnf.getOInt();
sequentialProtocolProducer.append(bnf.getOpenProtocol(sOut[j], out[j]));
}
this.outputs = out;
return sequentialProtocolProducer;
}
};
secureComputationEngine
.runApplication(app1, resourcePool);
for(int j = 0; j<5; j++) {
Assert.assertEquals(values[j], app1.outputs[j].getValue()
.intValue());
}
}
}
};
}
}
/**
* Tests that looking up keys that are present in the key/value pairs works
* also when the value is a list of values.
*
* @throws Exception
*/
/*
@Test
public void testCorrectLookUpArray() throws Exception {
TestThreadRunner.run(new TestThreadFactory() {
@Override
public TestThread next(TestThreadConfiguration conf) {
return new TestThread() {
@Override
public void test() throws Exception {
NumericCircuitFactory ncb = new NumericCircuitFactory(
provider);
NumericIOFactory niob = new NumericIOFactory(provider);
final int PAIRS = 50;
final int MAXVALUE = 20000;
final int NOTFOUND = -1;
final int LISTLENGTH = 10;
int[] notfound = new int[LISTLENGTH];
Arrays.fill(notfound, NOTFOUND);
int[] keys = new int[PAIRS];
int[][] values = new int[PAIRS][LISTLENGTH];
SInt[] sKeys = new SInt[PAIRS];
SInt[][] sValues = new SInt[PAIRS][LISTLENGTH];
for (int i = 0; i < PAIRS; i++) {
keys[i] = i;
sKeys[i] = provider.getSInt(i);
for (int j = 0; j < LISTLENGTH; j++) {
values[i][j] = rand.nextInt(MAXVALUE);
sValues[i][j] = provider.getSInt(values[i][j]);
}
}
sKeys = ncb.getSIntArray(keys);
sValues = ncb.getSIntMatrix(values);
for (int i = 0; i < PAIRS; i++) {
SInt[] sOut = ncb.getSIntArray(notfound);
LookUpCircuit<SInt> luc = provider
.getLookUpCircuit(sKeys[i], sKeys, sValues,
sOut);
niob.beginSeqScope();
niob.addGateProducer(luc);
OInt[] outs = niob.outputArray(sOut);
niob.endCurScope();
secureComputationEngine.runApplication(niob.getCircuit());
for (int j = 0; j < outs.length; j++) {
Assert.assertEquals(values[i][j], outs[j]
.getValue().intValue());
}
}
}
};
}
}, 2);
}
*/
/**
* Tests that looking up keys that are not present in the key/value pairs
* works also when the value is a list of values.
*
* @throws Exception
*/
/*
@Test
public void testIncorrectLookUpArray() throws Exception {
TestThreadRunner.run(new TestThreadFactory() {
@Override
public TestThread next(TestThreadConfiguration conf) {
return new TestThread() {
@Override
public void test() throws Exception {
NumericCircuitFactory ncb = new NumericCircuitFactory(
provider);
NumericIOFactory niob = new NumericIOFactory(provider);
final int PAIRS = 50;
final int BADKEY = PAIRS + 1;
final int MAXVALUE = 20000;
final int NOTFOUND = -1;
final int LISTLENGTH = 10;
int[] notfound = new int[LISTLENGTH];
Arrays.fill(notfound, NOTFOUND);
int[] keys = new int[PAIRS];
int[][] values = new int[PAIRS][LISTLENGTH];
SInt[] sKeys = new SInt[PAIRS];
SInt[][] sValues = new SInt[PAIRS][LISTLENGTH];
for (int i = 0; i < PAIRS; i++) {
keys[i] = i;
sKeys[i] = provider.getSInt(i);
for (int j = 0; j < LISTLENGTH; j++) {
values[i][j] = rand.nextInt(MAXVALUE);
sValues[i][j] = provider.getSInt(values[i][j]);
}
}
sKeys = ncb.getSIntArray(keys);
sValues = ncb.getSIntMatrix(values);
SInt lookUpKey = provider.getSInt(PAIRS + 1);
for (int i = 0; i < PAIRS; i++) {
SInt[] sOut = ncb.getSIntArray(notfound);
LookUpCircuit<SInt> luc = provider
.getLookUpCircuit(lookUpKey, sKeys,
sValues, sOut);
niob.beginSeqScope();
niob.addGateProducer(luc);
OInt[] outs = niob.outputArray(sOut);
niob.endCurScope();
secureComputationEngine.runApplication(niob.getCircuit());
for (int j = 0; j < outs.length; j++) {
Assert.assertEquals(NOTFOUND, outs[j]
.getValue().intValue());
}
}
}
};
}
}, 2);
}
*/
/**
* Tests that looking up keys that are not present in the key/value pairs
* works
*
* @throws Exception
*/
/*
@Test
public void testIncorrectLookUp() throws Exception {
TestThreadRunner.run(new TestThreadFactory() {
@Override
public TestThread next(TestThreadConfiguration conf) {
return new TestThread() {
@Override
public void test() throws Exception {
final int PAIRS = 50;
final int MAXVALUE = 20000;
final int NOTFOUND = -1;
int[] keys = new int[PAIRS];
int[] values = new int[PAIRS];
SInt[] sKeys = new SInt[PAIRS];
SInt[] sValues = new SInt[PAIRS];
for (int i = 0; i < PAIRS; i++) {
keys[i] = i;
sKeys[i] = provider.getSInt(i);
values[i] = rand.nextInt(MAXVALUE);
sValues[i] = provider.getSInt(values[i]);
}
SInt lookUpKey = provider.getSInt(PAIRS + 1);
for (int i = 0; i < 1; i++) {
SInt sOut = provider.getSInt(NOTFOUND);
OInt out = provider.getOInt();
AppendableGateProducer agp = new SequentialProtocolProducer();
LookUpCircuit<SInt> luc = provider
.getLookUpCircuit(lookUpKey, sKeys,
sValues, sOut);
agp.append(luc);
agp.append(provider.getOpenIntCircuit(sOut, out));
secureComputationEngine.runApplication(agp);
Assert.assertEquals(NOTFOUND, out.getValue()
.intValue());
}
}
};
}
}, 2);
}
*/
=======
>>>>>>> |
<<<<<<<
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
=======
import java.util.Random;
>>>>>>>
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.Random;
<<<<<<<
public DummyBooleanBuilderFactory(int myId) {
this.myId = myId;
performanceLoggers.putIfAbsent(myId, new ArrayList<PerformanceLogger>());
=======
public DummyBooleanBuilderFactory() {
loggerInstance = this;
this.rand = new Random(0);
>>>>>>>
public DummyBooleanBuilderFactory(int myId) {
this.myId = myId;
performanceLoggers.putIfAbsent(myId, new ArrayList<PerformanceLogger>());
this.rand = new Random(0); |
<<<<<<<
* @param input The arrays of which to retrieve a bit
* @param bit The index of the bit, counting from 0
* @return Returns the "bit" number bit, reading from left-to-right, from "input"
=======
* @param input
* The arrays of which to retrieve a bit
* @param index
* The index of the bit, counting from 0
* @return Returns the "bit" number bit, reading from left-to-right, from
* "input"
>>>>>>>
* @param input The arrays of which to retrieve a bit
* @param bit The index of the bit, counting from 0
* @return Returns the "bit" number bit, reading from left-to-right, from "input"
<<<<<<<
=======
public static void shiftArray(byte[] input, byte[] output, int positions) {
for (int i = 0; i < input.length * 8; i++) {
setBit(output, positions + i, getBit(input, i));
}
}
>>>>>>>
public static void shiftArray(byte[] input, byte[] output, int positions) {
for (int i = 0; i < input.length * 8; i++) {
setBit(output, positions + i, getBit(input, i));
}
} |
<<<<<<<
import dk.alexandra.fresco.lib.statistics.DEASolverTests;
import dk.alexandra.fresco.services.DataGeneratorImpl;
=======
import dk.alexandra.fresco.lib.statistics.DEASolverTests;
import dk.alexandra.fresco.rest.FuelEndpoint;
import dk.alexandra.fresco.services.DataGeneratorImpl;
>>>>>>>
import dk.alexandra.fresco.lib.statistics.DEASolverTests;
import dk.alexandra.fresco.services.DataGeneratorImpl;
<<<<<<<
=======
import dk.alexandra.fresco.suite.spdz.storage.rest.RetrieverThread;
import org.junit.Assert;
>>>>>>>
<<<<<<<
=======
private static final int noOfParties = 2;
>>>>>>>
<<<<<<<
StorageStrategy storageStrategy, int noOfParties) throws Exception {
Level logLevel = Level.FINE;
Reporter.init(logLevel);
=======
StorageStrategy storageStrategy) throws Exception {
Level logLevel = Level.INFO;
>>>>>>>
StorageStrategy storageStrategy) throws Exception {
Level logLevel = Level.INFO;
<<<<<<<
ttc.sceConf = new TestSCEConfiguration(suite, evaluator,
noOfThreads, noOfVMThreads, ttc.netConf, new InMemoryStorage(),
=======
ttc.sceConf = new TestSCEConfiguration(suite, NetworkingStrategy.KRYONET, evaluator,
noOfThreads, noOfVMThreads, ttc.netConf, new InMemoryStorage(),
>>>>>>>
ttc.sceConf = new TestSCEConfiguration(suite, NetworkingStrategy.KRYONET, evaluator,
noOfThreads, noOfVMThreads, ttc.netConf, new InMemoryStorage(),
<<<<<<<
runTest(new MiMCTests.TestMiMCEncSameEnc(),
EvaluationStrategy.SEQUENTIAL_BATCHED, StorageStrategy.IN_MEMORY, 2);
=======
runTest(new MiMCTests.TestMiMCEncSameEnc(),
EvaluationStrategy.SEQUENTIAL_BATCHED, StorageStrategy.IN_MEMORY);
}
@Test
public void test_dea() throws Exception {
runTest(new DEASolverTests.TestDEASolver(5, 1, 5, 1),
EvaluationStrategy.PARALLEL_BATCHED, StorageStrategy.IN_MEMORY);
}
@Test
public void test_mult_single() throws Exception {
runTest(new BasicArithmeticTests.TestSumAndMult(),
EvaluationStrategy.SEQUENTIAL_BATCHED, StorageStrategy.IN_MEMORY);
>>>>>>>
runTest(new MiMCTests.TestMiMCEncSameEnc(),
EvaluationStrategy.SEQUENTIAL_BATCHED, StorageStrategy.IN_MEMORY, 2); |
<<<<<<<
* Appends a close protocol where the inputting party is the inputter,
* inputting the given value as an OBool.
*
* @param inputter the party to input the value
* @param value the value to input (can be null if you are not the inputter)
* @return
*/
public SBool input(int inputter, OBool value) {
SBool res = bp.getSBool();
append(this.bp.getCloseProtocol(inputter, value, res));
return res;
}
/**
* Appends a close protocol where the inputting party is the inputter,
* inputting the given value as a boolean.
*
* @param inputter the party to input the value
* @param value the value to input (can be null if you are not the inputter)
* @return
*/
public SBool input(int inputter, boolean value) {
SBool res = bp.getSBool();
OBool known = bp.getKnownConstantOBool(value);
append(this.bp.getCloseProtocol(inputter, known, res));
return res;
}
/**
* Appends a number of close protocols where the inputting party is the inputter,
* inputting the given values as booleans.
*
* @param inputter the party to input the values
* @param values the values to input (can be null if you are not the inputter)
* @return
*/
public SBool[] input(int inputter, boolean[] values) {
SBool[] res = new SBool[values.length];
beginParScope();
for (int i = 0; i < values.length; i++) {
res[i] = input(inputter, values[i]);
}
endCurScope();
return res;
}
/**
* Appends an open to all protocol for an array of SBools
*
* @param sb
* the SBools to be output
=======
* Appends an output protocol for an array of SBools
* @param sb the SBools to be output
>>>>>>>
* Appends an output protocol for an array of SBools
*
* @param sb the SBools to be output
<<<<<<<
* Appends an open to all circuit for a single SBool
*
* @param sb
* the SBool to be output
=======
* Appends an output protocol for a single SBool
* @param sb the SBool to be output
>>>>>>>
* Appends an output protocol for a single SBool
*
* @param sb the SBool to be output
<<<<<<<
if (bs[i] == 0) {
result[i] = bp.getKnownConstantSBool(false);
} else {
result[i] = bp.getKnownConstantSBool(true);
=======
if(bs[i] == 0){
result[i] = bf.getKnownConstantSBool(false);
}else{
result[i] = bf.getKnownConstantSBool(true);
>>>>>>>
if (bs[i] == 0){
result[i] = bf.getKnownConstantSBool(false);
} else {
result[i] = bf.getKnownConstantSBool(true);
<<<<<<<
append(bp.getAndCircuit(left, right, result));
=======
append(bf.getAndProtocol(left, right, result));
>>>>>>>
append(bf.getAndProtocol(left, right, result));
<<<<<<<
append(bp.getXorCircuit(left, right, result));
=======
append(bf.getXorProtocol(left, right, result));
>>>>>>>
append(bf.getXorProtocol(left, right, result));
<<<<<<<
append(bp.getOrCircuit(left, right, result));
=======
append(bf.getOrProtocol(left, right, result));
>>>>>>>
append(bf.getOrProtocol(left, right, result));
<<<<<<<
append(bp.getKeyedCompareAndSwapCircuit(leftKey, leftValue, rightKey, rightValue));
=======
append(bf.getKeyedCompareAndSwapProtocol(leftKey, leftValue, rightKey,
rightValue));
>>>>>>>
append(bf.getKeyedCompareAndSwapProtocol(leftKey, leftValue, rightKey,
rightValue)); |
<<<<<<<
import dk.alexandra.fresco.suite.spdz.configuration.PreprocessingStrategy;
import dk.alexandra.fresco.suite.spdz.storage.DataSupplier;
import dk.alexandra.fresco.suite.spdz.storage.DataSupplierImpl;
import dk.alexandra.fresco.suite.spdz.storage.DummyDataSupplierImpl;
=======
>>>>>>>
import dk.alexandra.fresco.suite.spdz.storage.DummyDataSupplierImpl;
<<<<<<<
import dk.alexandra.fresco.suite.spdz.storage.SpdzStorageConstants;
import dk.alexandra.fresco.suite.spdz.storage.SpdzStorageImpl;
=======
import dk.alexandra.fresco.suite.spdz.storage.SpdzStorageDummyImpl;
import java.io.IOException;
>>>>>>>
import dk.alexandra.fresco.suite.spdz.storage.SpdzStorageImpl;
import java.io.IOException;
<<<<<<<
private SpdzResourcePool createResourcePool(int myId, int size, Network network, Random rand,
SecureRandom secRand, PreprocessingStrategy preproStrat) throws NoSuchAlgorithmException {
DataSupplier supplier;
switch (preproStrat) {
case DUMMY:
supplier = new DummyDataSupplierImpl(myId, size);
break;
case STATIC:
int noOfThreadsUsed = 1;
String storageName =
SpdzStorageConstants.STORAGE_NAME_PREFIX + noOfThreadsUsed + "_" + myId + "_" + 0
+ "_";
supplier = new DataSupplierImpl(new FilebasedStreamedStorageImpl(new InMemoryStorage()), storageName, size);
break;
default:
throw new ConfigurationException("Unkonwn preprocessing strategy: " + preproStrat);
}
SpdzStorage store = new SpdzStorageImpl(supplier);
return new SpdzResourcePoolImpl(myId, size, network, rand, secRand, store);
=======
private SpdzResourcePool createResourcePool(int myId, int size, Random rand,
SecureRandom secRand) {
SpdzStorage store;
store = new SpdzStorageDummyImpl(myId, size);
return new SpdzResourcePoolImpl(myId, size, rand, secRand, store);
>>>>>>>
private SpdzResourcePool createResourcePool(int myId, int size, Random rand,
SecureRandom secRand) {
SpdzStorage store;
store = new SpdzStorageImpl(new DummyDataSupplierImpl(myId, size));
try {
return new SpdzResourcePoolImpl(myId, size, rand, secRand, store);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Your system does not support the necessary hash function.", e);
} |
<<<<<<<
import org.junit.Assert;
=======
import org.junit.Ignore;
>>>>>>>
import org.junit.Assert;
import org.junit.Ignore;
<<<<<<<
NetworkingStrategy.KRYONET, PreprocessingStrategy.STATIC, 2);
} catch (Exception e) {
//Should not fail
Assert.fail();
=======
PreprocessingStrategy.STATIC, 2);
>>>>>>>
PreprocessingStrategy.STATIC, 2);
} catch (Exception e) {
//Should not fail
Assert.fail(); |
<<<<<<<
DRes<SInt> increased = numeric.add(BigInteger.ONE, input);
DRes<SInt> maskedS = numeric.mult(increased, () -> expPipe[0]);
=======
DRes<SInt> increased = numeric.add(one, input);
DRes<SInt> maskedS = numeric.mult(increased, expPipe.get(0));
>>>>>>>
DRes<SInt> increased = numeric.add(BigInteger.ONE, input);
DRes<SInt> maskedS = numeric.mult(increased, expPipe.get(0)); |
<<<<<<<
return this.builder.createSequentialSub(new BinaryEqualityProtocol(inLeft, inRight));
=======
return this.builder.seq(new BinaryEqualityProtocolImpl(inLeft, inRight));
>>>>>>>
return this.builder.seq(new BinaryEqualityProtocol(inLeft, inRight)); |
<<<<<<<
final SpdzCommitment commitment = new SpdzCommitment(digest,
new BigInteger(modulus.bitLength(), rand).mod(modulus), rand);
return builder.seq((seq) -> seq.append(new SpdzCommitProtocol(commitment)))
.seq((seq, commitProtocol) ->
seq.append(new SpdzOpenCommitProtocol(commitment, commitProtocol)))
.seq((seq, openCommit) -> {
// Add all s's to get the common random value:
BigInteger sum = BigInteger.ZERO;
for (BigInteger otherS : openCommit.values()) {
sum = sum.add(otherS);
}
int openedValuesSize = openedValues.size();
BigInteger[] rs = new BigInteger[openedValuesSize];
BigInteger temporaryR = sum;
for (int i = 0; i < openedValuesSize; i++) {
temporaryR = new BigInteger(digest.digest(temporaryR.toByteArray())).mod(modulus);
rs[i] = temporaryR;
}
BigInteger a = BigInteger.ZERO;
=======
return builder
.seq(seq -> {
FieldDefinition fieldDefinition = builder.getBasicNumericContext().getFieldDefinition();
FieldElement[] rs = sampleRandomCoefficients(openedValues.size(), fieldDefinition);
FieldElement a = fieldDefinition.createElement(0);
>>>>>>>
return builder.seq(new CoinTossingComputation(
builder.getBasicNumericContext().getFieldDefinition().getBitLength(),
new HashBasedCommitmentSerializer(), builder.getBasicNumericContext().getNoOfParties(),
new AesCtrDrbg()))
.seq((seq, seed) -> {
FieldDefinition fieldDefinition = builder.getBasicNumericContext().getFieldDefinition();
FieldElement[] rs = sampleRandomCoefficients(openedValues.size(), fieldDefinition);
FieldElement a = fieldDefinition.createElement(0);
<<<<<<<
for (SpdzSInt c : closedValues) {
gamma = gamma.add(rs[index++].multiply(c.getMac())).mod(modulus);
=======
for (SpdzSInt closedValue : closedValues) {
FieldElement closedValueHidden = rs[index++].multiply(closedValue.getMac());
gamma = gamma.add(closedValueHidden);
>>>>>>>
for (SpdzSInt closedValue : closedValues) {
FieldElement closedValueHidden = rs[index++].multiply(closedValue.getMac());
gamma = gamma.add(closedValueHidden);
<<<<<<<
=======
private FieldElement[] sampleRandomCoefficients(int numCoefficients,
FieldDefinition fieldDefinition) {
FieldElement[] coefficients = new FieldElement[numCoefficients];
for (int i = 0; i < numCoefficients; i++) {
byte[] bytes = new byte[modulus.bitLength() / Byte.SIZE];
jointDrbg.nextBytes(bytes);
coefficients[i] = fieldDefinition.createElement(new BigInteger(bytes));
}
return coefficients;
}
>>>>>>>
private FieldElement[] sampleRandomCoefficients(int numCoefficients,
FieldDefinition fieldDefinition) {
FieldElement[] coefficients = new FieldElement[numCoefficients];
for (int i = 0; i < numCoefficients; i++) {
byte[] bytes = new byte[modulus.bitLength() / Byte.SIZE];
jointDrbg.nextBytes(bytes);
coefficients[i] = fieldDefinition.createElement(new BigInteger(bytes));
}
return coefficients;
} |
<<<<<<<
private ProtocolProducer gp;
private NumericProtocolBuilder builder;
=======
private ProtocolProducer pp;
>>>>>>>
private NumericProtocolBuilder builder;
private ProtocolProducer pp;
<<<<<<<
case 0:
builder.reset();
builder.beginSeqScope();
// Load random r including binary expansion
SInt r = basicNumericFactory.getSInt();
SInt[] rExpansion = new SInt[bitLength];
for (int i = 0; i < rExpansion.length; i++) {
rExpansion[i] = basicNumericFactory.getSInt();
}
builder.addGateProducer(randomAdditiveMaskFactory
.getRandomAdditiveMaskCircuit(securityParameter, rExpansion, r));
// rBottom is the least significant bit of r
rBottom = rExpansion[0];
/*
* Calculate rTop = (r - rBottom) * 2^{-1}. Note that r -
* rBottom must be even so the division in the field are
* actually a division in the integers.
*/
builder.beginParScope();
=======
case 0:
// Load random r including binary expansion
SInt rOutput = basicNumericFactory.getSInt();
Protocol additiveMaskProtocol = randomAdditiveMaskFactory.getRandomAdditiveMaskProtocol(bitLength,
securityParameter, rOutput); // TODO: It seems the r we get here is wrong, so we need to calculate it in next round
rExpansion = (SInt[]) additiveMaskProtocol.getOutputValues();
pp = additiveMaskProtocol;
break;
case 1:
// rBottom is the least significant bit of r
rBottom = rExpansion[0];
// Calculate 1, 2, 2^2, ..., 2^{l - 1}
int l = rExpansion.length - 2;
OInt[] twoPowers = miscOIntGenerator.getTwoPowers(l);
// Calculate rTop = (r - rBottom) >> 1 = (r_1, r_2, ..., r_l) . (1, 2, 4, ..., 2^{l-1})
rTop = basicNumericFactory.getSInt();
SInt[] rTopBits = new SInt[l];
System.arraycopy(rExpansion, 1, rTopBits, 0, l);
Protocol findRTop = innerProductFactory.getInnerProductProtocol(rTopBits, twoPowers, rTop);
// r = 2 * rTop + rBottom
SInt r = basicNumericFactory.getSInt();
SInt tmp = basicNumericFactory.getSInt();
Protocol twoTimesRTop = basicNumericFactory.getMultProtocol(basicNumericFactory.getOInt(BigInteger.valueOf(2)), rTop, tmp);
Protocol addRBottom = basicNumericFactory.getAddProtocol(tmp, rBottom, r);
// mOpen = open(x + r)
SInt mClosed = basicNumericFactory.getSInt();
mOpen = basicNumericFactory.getOInt();
Protocol addR = basicNumericFactory.getAddProtocol(input, r, mClosed);
OpenIntProtocol openAddMask = basicNumericFactory.getOpenProtocol(mClosed, mOpen);
pp = new SequentialProtocolProducer(findRTop, twoTimesRTop, addRBottom, addR, openAddMask);
break;
case 2:
// 'carry' is either 0 or 1. It is 1 if and only if the addition
// m = x + r gave a carry from the first (least significant) bit
// to the second, ie. if the first bit of both x and r is 1.
// This happens if and only if the first bit of r is 1 and the
// first bit of m is 0 which in turn is equal to r_0 * (m + 1 (mod 2)).
SInt carry = basicNumericFactory.getSInt();
OInt mBottomNegated = basicNumericFactory
.getOInt(mOpen.getValue().add(BigInteger.ONE).mod(BigInteger.valueOf(2)));
Protocol calculateCarry = basicNumericFactory.getMultProtocol(mBottomNegated, rBottom, carry);
// The carry is needed by both the calculation of the shift and the remainder
SequentialProtocolProducer protocol = new SequentialProtocolProducer(calculateCarry);
// The shift and the remainder can be calculated in parallel
ParallelProtocolProducer findShiftAndRemainder = new ParallelProtocolProducer();
// Now we calculate the shift, x >> 1 = mTop - rTop - carry
SInt mTopMinusRTop = basicNumericFactory.getSInt();
OInt mTop = basicNumericFactory.getOInt(mOpen.getValue().shiftRight(1));
Protocol subtractprotocol = basicNumericFactory.getSubtractProtocol(mTop, rTop, mTopMinusRTop);
Protocol addCarryprotocol = basicNumericFactory.getSubtractProtocol(mTopMinusRTop, carry, result);
SequentialProtocolProducer calculateShift = new SequentialProtocolProducer(subtractprotocol, addCarryprotocol);
findShiftAndRemainder.append(calculateShift);
if (remainder != null) {
// We also need to calculate the remainder, aka. the bit we throw away in the shift:
// x (mod 2) = xor(r_0, m mod 2) = r_0 + (m mod 2) - 2 (r_0 * (m mod 2))
OInt mBottom = basicNumericFactory.getOInt(mOpen.getValue().mod(BigInteger.valueOf(2)));
OInt twoMBottom = basicNumericFactory.getOInt(mBottom.getValue().shiftLeft(1));
SInt product = basicNumericFactory.getSInt();
SInt sum = basicNumericFactory.getSInt();
Protocol remainderProtocolMult = basicNumericFactory.getMultProtocol(twoMBottom, rBottom, product);
Protocol remainderProtocolAdd = basicNumericFactory.getAddProtocol(rBottom, mBottom, sum);
Protocol remainderProtodolSubtract = basicNumericFactory.getSubtractProtocol(sum, product, remainder);
>>>>>>>
case 0:
builder.reset();
builder.beginSeqScope();
// Load random r including binary expansion
SInt r = basicNumericFactory.getSInt();
SInt[] rExpansion = new SInt[bitLength];
for (int i = 0; i < rExpansion.length; i++) {
rExpansion[i] = basicNumericFactory.getSInt();
}
builder.addProtocolProducer(randomAdditiveMaskFactory
.getRandomAdditiveMaskProtocol(securityParameter, rExpansion, r));
// rBottom is the least significant bit of r
rBottom = rExpansion[0];
/*
* Calculate rTop = (r - rBottom) * 2^{-1}. Note that r -
* rBottom must be even so the division in the field are
* actually a division in the integers.
*/
builder.beginParScope();
<<<<<<<
// mOpen = open(x + r)
builder.beginSeqScope();
mOpen = basicNumericFactory.getOInt();
SInt mClosed = builder.add(input, r);
builder.addGateProducer(basicNumericFactory.getOpenProtocol(mClosed, mOpen));
builder.endCurScope();
builder.endCurScope();
builder.endCurScope();
gp = builder.getCircuit();
break;
case 1:
builder.reset();
builder.beginSeqScope();
/*
* 'carry' is either 0 or 1. It is 1 if and only if the
* addition m = x + r gave a carry from the first (least
* significant) bit to the second, ie. if the first bit of
* both x and r is 1. This happens if and only if the first
* bit of r is 1 and the first bit of m is 0 which in turn
* is equal to r_0 * (m + 1 (mod 2)).
*/
OInt mBottomNegated = basicNumericFactory.getOInt(mOpen.getValue()
.add(BigInteger.ONE).mod(BigInteger.valueOf(2)));
SInt carry = builder.mult(mBottomNegated, rBottom);
// The carry is needed by both the calculation of the shift
// and the remainder, but the shift and the remainder can be
// calculated in parallel.
builder.beginParScope();
builder.beginSeqScope();
// Now we calculate the shift, x >> 1 = mTop - rTop - carry
OInt mTop = basicNumericFactory.getOInt(mOpen.getValue().shiftRight(1));
builder.copy(result, builder.sub(builder.sub(mTop, rTop), carry));
builder.endCurScope();
if (remainder != null) {
builder.beginSeqScope();
/*
* We also need to calculate the remainder, aka. the bit
* we throw away in the shift: x (mod 2) = xor(r_0, m
* mod 2) = r_0 + (m mod 2) - 2 (r_0 * (m mod 2)).
*/
OInt mBottom = basicNumericFactory.getOInt(mOpen.getValue().mod(
BigInteger.valueOf(2)));
OInt twoMBottom = basicNumericFactory.getOInt(mBottom.getValue().shiftLeft(
1));
builder.beginParScope();
SInt product = builder.mult(twoMBottom, rBottom);
SInt sum = builder.add(rBottom, mBottom);
builder.endCurScope();
builder.copy(remainder, builder.sub(sum, product));
builder.endCurScope();
}
builder.endCurScope();
builder.endCurScope();
gp = builder.getCircuit();
break;
default:
throw new MPCException("Protocol only has two rounds.");
=======
findShiftAndRemainder.append(calculateRemainder);
}
protocol.append(findShiftAndRemainder);
pp = protocol;
break;
default:
// ...
>>>>>>>
// mOpen = open(x + r)
builder.beginSeqScope();
mOpen = basicNumericFactory.getOInt();
SInt mClosed = builder.add(input, r);
builder.addProtocolProducer(basicNumericFactory.getOpenProtocol(mClosed, mOpen));
builder.endCurScope();
builder.endCurScope();
builder.endCurScope();
pp = builder.getProtocol();
break;
case 1:
builder.reset();
builder.beginSeqScope();
/*
* 'carry' is either 0 or 1. It is 1 if and only if the
* addition m = x + r gave a carry from the first (least
* significant) bit to the second, ie. if the first bit of
* both x and r is 1. This happens if and only if the first
* bit of r is 1 and the first bit of m is 0 which in turn
* is equal to r_0 * (m + 1 (mod 2)).
*/
OInt mBottomNegated = basicNumericFactory.getOInt(mOpen.getValue()
.add(BigInteger.ONE).mod(BigInteger.valueOf(2)));
SInt carry = builder.mult(mBottomNegated, rBottom);
// The carry is needed by both the calculation of the shift
// and the remainder, but the shift and the remainder can be
// calculated in parallel.
builder.beginParScope();
builder.beginSeqScope();
// Now we calculate the shift, x >> 1 = mTop - rTop - carry
OInt mTop = basicNumericFactory.getOInt(mOpen.getValue().shiftRight(1));
builder.copy(result, builder.sub(builder.sub(mTop, rTop), carry));
builder.endCurScope();
if (remainder != null) {
builder.beginSeqScope();
/*
* We also need to calculate the remainder, aka. the bit
* we throw away in the shift: x (mod 2) = xor(r_0, m
* mod 2) = r_0 + (m mod 2) - 2 (r_0 * (m mod 2)).
*/
OInt mBottom = basicNumericFactory.getOInt(mOpen.getValue().mod(
BigInteger.valueOf(2)));
OInt twoMBottom = basicNumericFactory.getOInt(mBottom.getValue().shiftLeft(
1));
builder.beginParScope();
SInt product = builder.mult(twoMBottom, rBottom);
SInt sum = builder.add(rBottom, mBottom);
builder.endCurScope();
builder.copy(remainder, builder.sub(sum, product));
builder.endCurScope();
}
builder.endCurScope();
builder.endCurScope();
pp = builder.getProtocol();
break;
default:
throw new MPCException("Protocol only has two rounds."); |
<<<<<<<
builder -> {
ProtocolBuilderBinary seqBuilder = (ProtocolBuilderBinary) builder;
return seqBuilder.seq(seq -> {
List<Computation<SBool>> leftKey =
rawLeftKey.stream().map(builder.binary()::known).collect(Collectors.toList());
List<Computation<SBool>> rightKey =
rawRightKey.stream().map(builder.binary()::known).collect(Collectors.toList());
List<Computation<SBool>> leftValue =
rawLeftValue.stream().map(builder.binary()::known).collect(Collectors.toList());
List<Computation<SBool>> rightValue =
rawRightValue.stream().map(builder.binary()::known).collect(Collectors.toList());
return seq.advancedBinary().keyedCompareAndSwap(new Pair<>(leftKey, leftValue),
new Pair<>(rightKey, rightValue));
}).seq((seq, data) -> {
List<Pair<List<Computation<Boolean>>, List<Computation<Boolean>>>> open =
new ArrayList<>();
for (Pair<List<Computation<SBool>>, List<Computation<SBool>>> o : data) {
List<Computation<Boolean>> first =
o.getFirst().stream().map(seq.binary()::open).collect(Collectors.toList());
List<Computation<Boolean>> second =
o.getSecond().stream().map(seq.binary()::open).collect(Collectors.toList());
Pair<List<Computation<Boolean>>, List<Computation<Boolean>>> pair =
new Pair<>(first, second);
open.add(pair);
}
return () -> open;
}).seq((seq, data) -> {
List<Pair<List<Boolean>, List<Boolean>>> out = new ArrayList<>();
for (Pair<List<Computation<Boolean>>, List<Computation<Boolean>>> o : data) {
List<Boolean> first =
o.getFirst().stream().map(Computation::out).collect(Collectors.toList());
List<Boolean> second =
o.getSecond().stream().map(Computation::out).collect(Collectors.toList());
Pair<List<Boolean>, List<Boolean>> pair = new Pair<>(first, second);
out.add(pair);
}
return () -> out;
});
};
=======
builder -> builder.seq(seq -> {
List<Computation<SBool>> leftKey =
rawLeftKey.stream().map(builder.binary()::known).collect(Collectors.toList());
List<Computation<SBool>> rightKey =
rawRightKey.stream().map(builder.binary()::known).collect(Collectors.toList());
List<Computation<SBool>> leftValue =
rawLeftValue.stream().map(builder.binary()::known).collect(Collectors.toList());
List<Computation<SBool>> rightValue =
rawRightValue.stream().map(builder.binary()::known)
.collect(Collectors.toList());
return seq.advancedBinary().keyedCompareAndSwap(leftKey, leftValue, rightKey,
rightValue);
}).seq((seq, data) -> {
List<Pair<List<Computation<Boolean>>, List<Computation<Boolean>>>> open =
new ArrayList<>();
for (Pair<List<Computation<SBool>>, List<Computation<SBool>>> o : data) {
List<Computation<Boolean>> first =
o.getFirst().stream().map(seq.binary()::open).collect(Collectors.toList());
List<Computation<Boolean>> second =
o.getSecond().stream().map(seq.binary()::open).collect(Collectors.toList());
Pair<List<Computation<Boolean>>, List<Computation<Boolean>>> pair =
new Pair<>(first, second);
open.add(pair);
}
return () -> open;
}).seq((seq, data) -> {
List<Pair<List<Boolean>, List<Boolean>>> out = new ArrayList<>();
for (Pair<List<Computation<Boolean>>, List<Computation<Boolean>>> o : data) {
List<Boolean> first =
o.getFirst().stream().map(Computation::out).collect(Collectors.toList());
List<Boolean> second =
o.getSecond().stream().map(Computation::out).collect(Collectors.toList());
Pair<List<Boolean>, List<Boolean>> pair = new Pair<>(first, second);
out.add(pair);
}
return () -> out;
});
>>>>>>>
builder -> {
ProtocolBuilderBinary seqBuilder = (ProtocolBuilderBinary) builder;
return seqBuilder.seq(seq -> {
List<Computation<SBool>> leftKey =
rawLeftKey.stream().map(builder.binary()::known).collect(Collectors.toList());
List<Computation<SBool>> rightKey =
rawRightKey.stream().map(builder.binary()::known).collect(Collectors.toList());
List<Computation<SBool>> leftValue =
rawLeftValue.stream().map(builder.binary()::known).collect(Collectors.toList());
List<Computation<SBool>> rightValue =
rawRightValue.stream().map(builder.binary()::known).collect(Collectors.toList());
return seq.advancedBinary().keyedCompareAndSwap(new Pair<>(leftKey, leftValue),
new Pair<>(rightKey, rightValue));
}).seq((seq, data) -> {
List<Pair<List<Computation<Boolean>>, List<Computation<Boolean>>>> open =
new ArrayList<>();
for (Pair<List<Computation<SBool>>, List<Computation<SBool>>> o : data) {
List<Computation<Boolean>> first =
o.getFirst().stream().map(seq.binary()::open).collect(Collectors.toList());
List<Computation<Boolean>> second =
o.getSecond().stream().map(seq.binary()::open).collect(Collectors.toList());
Pair<List<Computation<Boolean>>, List<Computation<Boolean>>> pair =
new Pair<>(first, second);
open.add(pair);
}
return () -> open;
}).seq((seq, data) -> {
List<Pair<List<Boolean>, List<Boolean>>> out = new ArrayList<>();
for (Pair<List<Computation<Boolean>>, List<Computation<Boolean>>> o : data) {
List<Boolean> first =
o.getFirst().stream().map(Computation::out).collect(Collectors.toList());
List<Boolean> second =
o.getSecond().stream().map(Computation::out).collect(Collectors.toList());
Pair<List<Boolean>, List<Boolean>> pair = new Pair<>(first, second);
out.add(pair);
}
return () -> out;
});
};
<<<<<<<
=======
/*
* boolean[] left11 = ByteArithmetic.toBoolean("ff"); boolean[] left12 =
* ByteArithmetic.toBoolean("ee"); boolean[] left21 = ByteArithmetic.toBoolean("bb");
* boolean[] left22 = ByteArithmetic.toBoolean("ba"); boolean[] left31 =
* ByteArithmetic.toBoolean("ab"); boolean[] left32 = ByteArithmetic.toBoolean("aa");
* boolean[] right11 = ByteArithmetic.toBoolean("49"); boolean[] right12 =
* ByteArithmetic.toBoolean("00");
*
* OBool[][] results = new OBool[16][];
*
* TestApplication app = new TestApplication() {
*
* private static final long serialVersionUID = 4338818809103728010L;
*
* @Override public ProtocolProducer buildComputation( BuilderFactory factoryProducer) {
* ProtocolFactory producer = factoryProducer.getProtocolFactory(); AbstractBinaryFactory
* prov = (AbstractBinaryFactory) producer; BasicLogicBuilder builder = new
* BasicLogicBuilder(prov); SequentialProtocolProducer sseq = new
* SequentialProtocolProducer(); SBool[] l11 = builder.knownSBool(left11); SBool[] l12 =
* builder.knownSBool(left12); SBool[] l21 = builder.knownSBool(left21); SBool[] l22 =
* builder.knownSBool(left22); SBool[] l31 = builder.knownSBool(left31); SBool[] l32 =
* builder.knownSBool(left32);
*
* SBool[] r11 = builder.knownSBool(right11); SBool[] r12 = builder.knownSBool(right12);
*
* SBool[] s11 = prov.getSBools(8); SBool[] s12 = prov.getSBools(8); SBool[] s21 =
* prov.getSBools(8); SBool[] s22 = prov.getSBools(8); SBool[] s31 = prov.getSBools(8);
* SBool[] s32 = prov.getSBools(8); SBool[] s41 = prov.getSBools(8); SBool[] s42 =
* prov.getSBools(8);
*
* SBool[] sr11 = prov.getSBools(8); SBool[] sr12 = prov.getSBools(8); SBool[] sr21 =
* prov.getSBools(8); SBool[] sr22 = prov.getSBools(8); SBool[] sr31 = prov.getSBools(8);
* SBool[] sr32 = prov.getSBools(8); SBool[] sr41 = prov.getSBools(8); SBool[] sr42 =
* prov.getSBools(8);
*
* sseq.append(builder.getProtocol());
*
* List<Pair<SBool[], SBool[]>> left = new ArrayList<Pair<SBool[], SBool[]>>();
* List<Pair<SBool[], SBool[]>> right = new ArrayList<Pair<SBool[], SBool[]>>();
* List<Pair<SBool[], SBool[]>> sorted = new ArrayList<Pair<SBool[], SBool[]>>();
* List<Pair<SBool[], SBool[]>> sorted2 = new ArrayList<Pair<SBool[], SBool[]>>();
*
* left.add(new Pair<SBool[], SBool[]>(l11, l12)); left.add(new Pair<SBool[],
* SBool[]>(l21, l22)); left.add(new Pair<SBool[], SBool[]>(l31, l32)); right.add(new
* Pair<SBool[], SBool[]>(r11, r12)); sorted.add(new Pair<SBool[], SBool[]>(s11, s12));
* sorted.add(new Pair<SBool[], SBool[]>(s21, s22)); sorted.add(new Pair<SBool[],
* SBool[]>(s31, s32)); sorted.add(new Pair<SBool[], SBool[]>(s41, s42)); sorted2.add(new
* Pair<SBool[], SBool[]>(sr11, sr12)); sorted2.add(new Pair<SBool[], SBool[]>(sr21,
* sr22)); sorted2.add(new Pair<SBool[], SBool[]>(sr31, sr32)); sorted2.add(new
* Pair<SBool[], SBool[]>(sr41, sr42));
*
* OddEvenMergeProtocolImpl mergeProtocol = new OddEvenMergeProtocolImpl(left, right,
* sorted, prov);
*
* OddEvenMergeProtocolImpl mergeProtocolReversed = new OddEvenMergeProtocolImpl(right,
* left, sorted2, prov);
*
* sseq.append(mergeProtocol); sseq.append(mergeProtocolReversed);
*
* results[0] = builder.output(sorted.get(0).getFirst()); results[1] =
* builder.output(sorted.get(0).getSecond()); results[2] =
* builder.output(sorted.get(1).getFirst()); results[3] =
* builder.output(sorted.get(1).getSecond()); results[4] =
* builder.output(sorted.get(2).getFirst()); results[5] =
* builder.output(sorted.get(2).getSecond()); results[6] =
* builder.output(sorted.get(3).getFirst()); results[7] =
* builder.output(sorted.get(3).getSecond()); results[0+8] =
* builder.output(sorted2.get(0).getFirst()); results[1+8] =
* builder.output(sorted2.get(0).getSecond()); results[2+8] =
* builder.output(sorted2.get(1).getFirst()); results[3+8] =
* builder.output(sorted2.get(1).getSecond()); results[4+8] =
* builder.output(sorted2.get(2).getFirst()); results[5+8] =
* builder.output(sorted2.get(2).getSecond()); results[6+8] =
* builder.output(sorted2.get(3).getFirst()); results[7+8] =
* builder.output(sorted2.get(3).getSecond()); sseq.append(builder.getProtocol());
*
* return sseq; } }; secureComputationEngine .runApplication(app,
* ResourcePoolCreator.createResourcePool(conf.sceConf));
*
* Assert.assertArrayEquals(left11, convertOBoolToBool(results[0]));
* Assert.assertArrayEquals(left12, convertOBoolToBool(results[1]));
* Assert.assertArrayEquals(left21, convertOBoolToBool(results[2]));
* Assert.assertArrayEquals(left22, convertOBoolToBool(results[3]));
* Assert.assertArrayEquals(left31, convertOBoolToBool(results[4]));
* Assert.assertArrayEquals(left32, convertOBoolToBool(results[5]));
* Assert.assertArrayEquals(right11, convertOBoolToBool(results[6]));
* Assert.assertArrayEquals(right12, convertOBoolToBool(results[7]));
*
* Assert.assertArrayEquals(left11, convertOBoolToBool(results[0+8]));
* Assert.assertArrayEquals(left12, convertOBoolToBool(results[1+8]));
* Assert.assertArrayEquals(left21, convertOBoolToBool(results[2+8]));
* Assert.assertArrayEquals(left22, convertOBoolToBool(results[3+8]));
* Assert.assertArrayEquals(left31, convertOBoolToBool(results[4+8]));
* Assert.assertArrayEquals(left32, convertOBoolToBool(results[5+8]));
* Assert.assertArrayEquals(right11, convertOBoolToBool(results[6+8]));
* Assert.assertArrayEquals(right12, convertOBoolToBool(results[7+8]));
*/
}
};
}
}
public static class TestOddEvenMergeRec extends TestThreadFactory {
>>>>>>> |
<<<<<<<
ByteSerializer<BigInteger> serializer = spdzResourcePool.getSerializer();
switch (round) {
case 0:
network.sendToAll(serializer
.serialize(commitment.computeCommitment(spdzResourcePool.getModulus())));
break;
case 1:
List<byte[]> commitments = network.receiveFromAll();
for (int i = 0; i < commitments.size(); i++) {
comms.put(i + 1, serializer.deserialize(commitments.get(i)));
}
if (players < 3) {
done = true;
} else {
broadcastDigest = sendBroadcastValidation(
spdzResourcePool.getMessageDigest(), network, comms.values()
);
}
break;
case 2:
boolean validated = receiveBroadcastValidation(network, broadcastDigest);
if (!validated) {
throw new MPCException(
"Broadcast of commitments was not validated. Abort protocol.");
}
done = true;
break;
default:
throw new MPCException("No further rounds.");
}
if (done) {
return EvaluationStatus.IS_DONE;
} else {
=======
BigIntegerSerializer serializer = spdzResourcePool.getSerializer();
if (round == 0) {
network.sendToAll(serializer
.toBytes(commitment.computeCommitment(spdzResourcePool.getModulus())));
>>>>>>>
ByteSerializer<BigInteger> serializer = spdzResourcePool.getSerializer();
if (round == 0) {
network.sendToAll(serializer
.serialize(commitment.computeCommitment(spdzResourcePool.getModulus()))); |
<<<<<<<
public TestThread<?, ProtocolBuilderNumeric> next() {
=======
public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() {
>>>>>>>
public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() {
<<<<<<<
List<DRes<SInt>> input1 = data1.stream().map(BigInteger::valueOf)
.map(sIntFactory::known).collect(Collectors.toList());
List<DRes<SInt>> tmp = data2.stream().map(BigInteger::valueOf)
.map(sIntFactory::known).collect(Collectors.toList());
List<DRes<SInt>> input2 = new LinkedList<DRes<SInt>>();
input2.addAll(tmp);
DRes<SInt> min =
builder.seq(new InnerProduct(input1, input2));
=======
List<DRes<SInt>> input1 = data1.stream().map(BigInteger::valueOf)
.map(sIntFactory::known).collect(Collectors.toList());
// LinkedList<Computation<SInt>> bleh = new LinkedList(input1);
System.out.println(input1);
List<DRes<SInt>> input2 = data2.stream().map(BigInteger::valueOf)
.map(sIntFactory::known).collect(Collectors.toList());
DRes<SInt> min = builder.seq(new InnerProduct(input1, input2));
>>>>>>>
List<DRes<SInt>> input1 = data1.stream().map(BigInteger::valueOf)
.map(sIntFactory::known).collect(Collectors.toList());
List<DRes<SInt>> input2 = data2.stream().map(BigInteger::valueOf)
.map(sIntFactory::known).collect(Collectors.toList());
DRes<SInt> min = builder.seq(new InnerProduct(input1, input2));
<<<<<<<
public TestThread<?, ProtocolBuilderNumeric> next() {
=======
public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() {
>>>>>>>
public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() { |
<<<<<<<
ByteSerializer<BigInteger> serializer = spdzResourcePool.getSerializer();
switch (round) {
case 0:
this.triple = store.getSupplier().getNextTriple();
=======
BigIntegerSerializer serializer = spdzResourcePool.getSerializer();
>>>>>>>
ByteSerializer<BigInteger> serializer = spdzResourcePool.getSerializer(); |
<<<<<<<
ByteSerializer<BigInteger> serializer = spdzResourcePool.getSerializer();
switch (round) {
case 0:
this.inputMask = storage.getSupplier().getNextInputMask(this.inputter);
if (myId == this.inputter) {
BigInteger bcValue = this.input.subtract(this.inputMask.getRealValue());
bcValue = bcValue.mod(modulus);
network.sendToAll(serializer.serialize(bcValue));
}
return EvaluationStatus.HAS_MORE_ROUNDS;
case 1:
this.value_masked = serializer.deserialize(network.receive(inputter));
this.digest = sendBroadcastValidation(
spdzResourcePool.getMessageDigest(), network,
value_masked);
return EvaluationStatus.HAS_MORE_ROUNDS;
case 2:
boolean validated = receiveBroadcastValidation(network, digest);
if (!validated) {
throw new MPCException("Broadcast digests did not match");
}
SpdzElement value_masked_elm =
new SpdzElement(
value_masked,
storage.getSSK().multiply(value_masked).mod(modulus),
modulus);
this.out = new SpdzSInt(this.inputMask.getMask().add(value_masked_elm, myId));
return EvaluationStatus.IS_DONE;
=======
BigIntegerSerializer serializer = spdzResourcePool.getSerializer();
if (round == 0) {
this.inputMask = storage.getSupplier().getNextInputMask(this.inputter);
if (myId == this.inputter) {
BigInteger bcValue = this.input.subtract(this.inputMask.getRealValue());
bcValue = bcValue.mod(modulus);
network.sendToAll(serializer.toBytes(bcValue));
}
return EvaluationStatus.HAS_MORE_ROUNDS;
} else if (round == 1) {
this.valueMasked = serializer.toBigInteger(network.receive(inputter));
this.digest = sendBroadcastValidation(
spdzResourcePool.getMessageDigest(), network,
valueMasked);
return EvaluationStatus.HAS_MORE_ROUNDS;
} else {
boolean validated = receiveBroadcastValidation(network, digest);
if (!validated) {
throw new MPCException("Broadcast digests did not match");
}
SpdzElement valueMaskedElement =
new SpdzElement(
valueMasked,
storage.getSecretSharedKey().multiply(valueMasked).mod(modulus),
modulus);
this.out = new SpdzSInt(this.inputMask.getMask().add(valueMaskedElement, myId));
return EvaluationStatus.IS_DONE;
>>>>>>>
ByteSerializer<BigInteger> serializer = spdzResourcePool.getSerializer();
if (round == 0) {
this.inputMask = storage.getSupplier().getNextInputMask(this.inputter);
if (myId == this.inputter) {
BigInteger bcValue = this.input.subtract(this.inputMask.getRealValue());
bcValue = bcValue.mod(modulus);
network.sendToAll(serializer.serialize(bcValue));
}
return EvaluationStatus.HAS_MORE_ROUNDS;
} else if (round == 1) {
this.valueMasked = serializer.deserialize(network.receive(inputter));
this.digest = sendBroadcastValidation(
spdzResourcePool.getMessageDigest(), network,
valueMasked);
return EvaluationStatus.HAS_MORE_ROUNDS;
} else {
boolean validated = receiveBroadcastValidation(network, digest);
if (!validated) {
throw new MPCException("Broadcast digests did not match");
}
SpdzElement valueMaskedElement =
new SpdzElement(
valueMasked,
storage.getSecretSharedKey().multiply(valueMasked).mod(modulus),
modulus);
this.out = new SpdzSInt(this.inputMask.getMask().add(valueMaskedElement, myId));
return EvaluationStatus.IS_DONE; |
<<<<<<<
=======
import com.jaquadro.minecraft.storagedrawers.security.SecurityRegistry;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.relauncher.Side;
>>>>>>>
import com.jaquadro.minecraft.storagedrawers.security.SecurityRegistry;
<<<<<<<
//public static BlockRegistry blockRegistry;
=======
public static BlockRegistry blockRegistry;
public static SecurityRegistry securityRegistry;
>>>>>>>
//public static BlockRegistry blockRegistry;
public static SecurityRegistry securityRegistry;
<<<<<<<
//blockRegistry = new BlockRegistry();
=======
blockRegistry = new BlockRegistry();
securityRegistry = new SecurityRegistry();
>>>>>>>
//blockRegistry = new BlockRegistry();
securityRegistry = new SecurityRegistry(); |
<<<<<<<
import com.jaquadro.minecraft.storagedrawers.client.model.BasicDrawerModel;
import com.jaquadro.minecraft.storagedrawers.client.model.CompDrawerModel;
import com.jaquadro.minecraft.storagedrawers.client.model.TrimModel;
=======
import com.jaquadro.minecraft.storagedrawers.client.renderer.ControllerRenderer;
import com.jaquadro.minecraft.storagedrawers.client.renderer.DrawersItemRenderer;
import com.jaquadro.minecraft.storagedrawers.client.renderer.DrawersRenderer;
>>>>>>>
import com.jaquadro.minecraft.storagedrawers.client.model.BasicDrawerModel;
import com.jaquadro.minecraft.storagedrawers.client.model.CompDrawerModel;
import com.jaquadro.minecraft.storagedrawers.client.model.TrimModel;
import com.jaquadro.minecraft.storagedrawers.client.renderer.DrawersItemRenderer;
<<<<<<<
import com.jaquadro.minecraft.storagedrawers.item.EnumUpgradeStatus;
import com.jaquadro.minecraft.storagedrawers.item.EnumUpgradeStorage;
import com.jaquadro.minecraft.storagedrawers.item.ItemBasicDrawers;
import com.jaquadro.minecraft.storagedrawers.item.ItemTrim;
import net.minecraft.block.BlockPlanks;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
=======
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.client.MinecraftForgeClient;
>>>>>>>
import com.jaquadro.minecraft.storagedrawers.item.EnumUpgradeStatus;
import com.jaquadro.minecraft.storagedrawers.item.EnumUpgradeStorage;
import com.jaquadro.minecraft.storagedrawers.item.ItemBasicDrawers;
import com.jaquadro.minecraft.storagedrawers.item.ItemTrim;
import net.minecraft.block.Block;
import net.minecraft.block.BlockPlanks;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
<<<<<<<
@SubscribeEvent
public void onModelBakeEvent (ModelBakeEvent event) {
BasicDrawerModel.initialize(event.modelRegistry);
CompDrawerModel.initialize(event.modelRegistry);
//TrimModel.initialize(event.modelRegistry);
}
=======
private DrawersItemRenderer itemRenderer = new DrawersItemRenderer();
@Override
public void registerRenderers () {
drawersRenderID = RenderingRegistry.getNextAvailableRenderId();
controllerRenderID = RenderingRegistry.getNextAvailableRenderId();
>>>>>>>
private DrawersItemRenderer itemRenderer = new DrawersItemRenderer();
@SubscribeEvent
public void onModelBakeEvent (ModelBakeEvent event) {
BasicDrawerModel.initialize(event.modelRegistry);
CompDrawerModel.initialize(event.modelRegistry);
//TrimModel.initialize(event.modelRegistry);
} |
<<<<<<<
//public boolean enableSortingUpgrades;
=======
public boolean enableSortingUpgrades;
public boolean enableRedstoneUpgrades;
public boolean renderStorageUpgrades;
>>>>>>>
//public boolean enableSortingUpgrades;
public boolean enableRedstoneUpgrades;
public boolean renderStorageUpgrades;
<<<<<<<
//cache.enableSortingUpgrades = config.get(Configuration.CATEGORY_GENERAL, "enableSortingUpgrades", true).setLanguageKey(LANG_PREFIX + "prop.enableSortingUpgrades").setRequiresMcRestart(true).getBoolean();
=======
cache.enableSortingUpgrades = config.get(Configuration.CATEGORY_GENERAL, "enableSortingUpgrades", true).setLanguageKey(LANG_PREFIX + "prop.enableSortingUpgrades").setRequiresMcRestart(true).getBoolean();
cache.enableRedstoneUpgrades = config.get(Configuration.CATEGORY_GENERAL, "enableRedstoneUpgrades", true).setLanguageKey(LANG_PREFIX + "prop.enableRedstoneUpgrades").setRequiresMcRestart(true).getBoolean();
>>>>>>>
//cache.enableSortingUpgrades = config.get(Configuration.CATEGORY_GENERAL, "enableSortingUpgrades", true).setLanguageKey(LANG_PREFIX + "prop.enableSortingUpgrades").setRequiresMcRestart(true).getBoolean();
cache.enableRedstoneUpgrades = config.get(Configuration.CATEGORY_GENERAL, "enableRedstoneUpgrades", true).setLanguageKey(LANG_PREFIX + "prop.enableRedstoneUpgrades").setRequiresMcRestart(true).getBoolean(); |
<<<<<<<
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
=======
import net.minecraft.util.IChatComponent;
import net.minecraft.util.MathHelper;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.LockCode;
>>>>>>>
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.LockCode;
<<<<<<<
import net.minecraftforge.items.CapabilityItemHandler;
=======
import net.minecraftforge.items.IItemHandler;
>>>>>>>
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import org.apache.logging.log4j.Level; |
<<<<<<<
//resolver = new DataResolver(StorageDrawers.MOD_ID);
basicDrawers = new BlockVariantDrawers("basicdrawers", "basicDrawers");
compDrawers = new BlockCompDrawers("compdrawers", "compDrawers");
=======
basicDrawers = new BlockVariantDrawers("basicDrawers");
compDrawers = new BlockCompDrawers("compDrawers");
>>>>>>>
basicDrawers = new BlockVariantDrawers("basicdrawers", "basicDrawers");
compDrawers = new BlockCompDrawers("compdrawers", "compDrawers"); |
<<<<<<<
public boolean retrimBlock (World world, BlockPos pos, @Nonnull ItemStack prototype) {
if (retrimType() == null)
return false;
IBlockState curState = getActualState(world.getBlockState(pos), world, pos);
if (curState == null || !(curState.getBlock() instanceof BlockDrawers))
return false;
Block protoBlock = Block.getBlockFromItem(prototype.getItem());
int protoMeta = prototype.getItemDamage();
IBlockState newState = protoBlock.getStateFromMeta(protoMeta);
if (newState == null || !(newState.getBlock() instanceof BlockTrim))
return false;
BlockPlanks.EnumType curVariant = curState.getValue(VARIANT);
BlockPlanks.EnumType newVariant = newState.getValue(VARIANT);
if (curVariant == newVariant)
return false;
TileEntityDrawers tile = getTileEntity(world, pos);
tile.setMaterial(newVariant.getName());
world.setBlockState(pos, curState.withProperty(VARIANT, newVariant));
return true;
=======
public boolean retrimBlock (World world, BlockPos pos, ItemStack prototype) {
return false;
>>>>>>>
public boolean retrimBlock (World world, BlockPos pos, ItemStack prototype) {
return false;
<<<<<<<
if (state != null && state.getBlock() instanceof BlockDrawers) {
EnumBasicDrawer info = state.getValue(BLOCK);
if (info != null)
return info.getDrawerCount();
}
=======
>>>>>>>
<<<<<<<
if (state != null && state.getBlock() instanceof BlockDrawers) {
EnumBasicDrawer info = state.getValue(BLOCK);
if (info != null)
return info.isHalfDepth();
}
=======
>>>>>>>
<<<<<<<
if (state != null) {
EnumBasicDrawer info = state.getValue(BLOCK);
if (info != null)
return statusInfo[info.getMetadata()];
}
=======
>>>>>>>
<<<<<<<
public IBlockState getStateForPlacement (World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand) {
return getDefaultState().withProperty(BLOCK, EnumBasicDrawer.byMetadata(meta));
}
@Override
=======
>>>>>>>
public IBlockState getStateForPlacement (World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand) {
return getDefaultState().withProperty(BLOCK, EnumBasicDrawer.byMetadata(meta));
}
@Override
<<<<<<<
ItemStack dropStack = getMainDrop(world, pos, state);
List<ItemStack> drops = new ArrayList<>();
drops.add(dropStack);
=======
List<ItemStack> drops = new ArrayList<ItemStack>();
drops.add(getMainDrop(world, pos, state));
return drops;
}
protected ItemStack getMainDrop (IBlockAccess world, BlockPos pos, IBlockState state) {
ItemStack drop = new ItemStack(Item.getItemFromBlock(this), 1, state.getBlock().getMetaFromState(state));
>>>>>>>
List<ItemStack> drops = new ArrayList<ItemStack>();
drops.add(getMainDrop(world, pos, state));
return drops;
}
protected ItemStack getMainDrop (IBlockAccess world, BlockPos pos, IBlockState state) {
ItemStack drop = new ItemStack(Item.getItemFromBlock(this), 1, state.getBlock().getMetaFromState(state));
<<<<<<<
dropStack.setTagCompound(data);
return drops;
}
@Nonnull
protected ItemStack getMainDrop (IBlockAccess world, BlockPos pos, IBlockState state) {
return new ItemStack(Item.getItemFromBlock(this), 1, state.getBlock().getMetaFromState(state));
=======
drop.setTagCompound(data);
return drop;
>>>>>>>
drop.setTagCompound(data);
return drop;
<<<<<<<
public void getSubBlocks (Item item, CreativeTabs creativeTabs, NonNullList<ItemStack> list) {
for (EnumBasicDrawer type : EnumBasicDrawer.values()) {
for (BlockPlanks.EnumType material : BlockPlanks.EnumType.values()) {
ItemStack stack = new ItemStack(item, 1, type.getMetadata());
NBTTagCompound data = new NBTTagCompound();
data.setString("material", material.getName());
stack.setTagCompound(data);
if (StorageDrawers.config.cache.creativeTabVanillaWoods || material == BlockPlanks.EnumType.OAK)
list.add(stack);
}
}
}
@Override
=======
>>>>>>>
<<<<<<<
public IBlockState getStateFromMeta (int meta) {
return getDefaultState().withProperty(BLOCK, EnumBasicDrawer.byMetadata(meta));
}
@Override
public int getMetaFromState (IBlockState state) {
return (state.getValue(BLOCK)).getMetadata();
}
@Override
protected BlockStateContainer createBlockState () {
return new ExtendedBlockState(this, new IProperty[] { BLOCK, VARIANT, FACING }, new IUnlistedProperty[] { STATE_MODEL });
}
@Override
@SuppressWarnings("deprecation")
=======
>>>>>>> |
<<<<<<<
tile = createNewTileEntity(world, 0);
world.setTileEntity(pos, tile);
=======
tile = createNewTileEntity(world, world.getBlockMetadata(x, y, z));
world.setTileEntity(x, y, z, tile);
>>>>>>>
tile = (TileEntityDrawers)createNewTileEntity(world, world.getBlockMetadata(x, y, z));
world.setTileEntity(pos, tile);
<<<<<<<
@Override
protected BlockState createBlockState () {
return new ExtendedBlockState(this, new IProperty[] { BLOCK, VARIANT, FACING }, new IUnlistedProperty[] { TILE });
=======
@SideOnly(Side.CLIENT)
protected IIcon getIcon (IBlockAccess blockAccess, int x, int y, int z, int side, int level) {
int meta = blockAccess.getBlockMetadata(x, y, z);
meta = (meta < 0 || meta >= iconSide.length) ? 0 : meta;
TileEntityDrawers tile = getTileEntity(blockAccess, x, y, z);
if (tile == null || side == tile.getDirection()) {
if (drawerCount == 1)
return iconFront1[meta];
else if (drawerCount == 2)
return iconFront2[meta];
else
return iconFront4[meta];
}
switch (side) {
case 0:
case 1:
if (halfDepth) {
switch (tile.getDirection()) {
case 2:
case 3:
case 4:
case 5:
return (level > 0) ? iconOverlayH[level] : iconSideH[meta];
}
}
break;
case 2:
case 3:
if (halfDepth) {
switch (tile.getDirection()) {
case 2:
case 3:
return (level > 0) ? iconOverlay[level] : iconSide[meta];
case 4:
case 5:
return (level > 0) ? iconOverlayV[level] : iconSideV[meta];
}
}
break;
case 4:
case 5:
if (halfDepth) {
switch (tile.getDirection()) {
case 2:
case 3:
return (level > 0) ? iconOverlayV[level] : iconSideV[meta];
case 4:
case 5:
return (level > 0) ? iconOverlay[level] : iconSide[meta];
}
}
break;
}
return (level > 0) ? iconOverlay[level] : iconSide[meta];
>>>>>>>
@Override
protected BlockState createBlockState () {
return new ExtendedBlockState(this, new IProperty[] { BLOCK, VARIANT, FACING }, new IUnlistedProperty[] { TILE });
<<<<<<<
private BlockPlanks.EnumType translateMaterial (String materal) {
for (BlockPlanks.EnumType type : BlockPlanks.EnumType.values()) {
if (materal.equals(type.getName()))
return type;
=======
@SideOnly(Side.CLIENT)
protected void loadBlockConfig () {
try {
IResource configResource = Minecraft.getMinecraft().getResourceManager().getResource(blockConfig);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(configResource.getInputStream()));
JsonObject root = (new JsonParser()).parse(reader).getAsJsonObject();
JsonObject entry = root.getAsJsonObject(getConfigName());
if (entry != null) {
if (entry.has("trimWidth"))
trimWidth = entry.get("trimWidth").getAsFloat();
if (entry.has("trimDepth"))
trimDepth = entry.get("trimDepth").getAsFloat();
if (entry.has("indStart"))
indStart = entry.get("indStart").getAsFloat();
if (entry.has("indEnd"))
indEnd = entry.get("indEnd").getAsFloat();
if (entry.has("indSteps"))
indSteps = entry.get("indSteps").getAsInt();
}
}
finally {
IOUtils.closeQuietly(reader);
}
} catch (IOException e) {
e.printStackTrace();
>>>>>>>
private BlockPlanks.EnumType translateMaterial (String materal) {
for (BlockPlanks.EnumType type : BlockPlanks.EnumType.values()) {
if (materal.equals(type.getName()))
return type; |
<<<<<<<
String[] enderRecipe = {"blocks.obsidian", "items.ender_eye", "blocks.obsidian", "blocks.obsidian", "items.ironbackpacks:ironBackpack", "blocks.obsidian", "blocks.obsidian", "blocks.obsidian", "blocks.obsidian"};
// this comment refers to balance changes, if the recipe defaults need to be tweaked or are good for the time being
=======
>>>>>>>
String[] enderRecipe = {"blocks.obsidian", "items.ender_eye", "blocks.obsidian", "blocks.obsidian", "items.ironbackpacks:ironBackpack", "blocks.obsidian", "blocks.obsidian", "blocks.obsidian", "blocks.obsidian"};
// this comment refers to balance changes, if the recipe defaults need to be tweaked or are good for the time being |
<<<<<<<
drawerKey = new ItemDrawerKey("drawerKey");
=======
shroudKey = new ItemShroudKey("shroudKey");
>>>>>>>
drawerKey = new ItemDrawerKey("drawerKey");
shroudKey = new ItemShroudKey("shroudKey");
<<<<<<<
if (StorageDrawers.config.cache.enableLockUpgrades)
GameRegistry.registerItem(drawerKey, "drawerKey");
}
public static String getQualifiedName (Item item) {
return GameData.getItemRegistry().getNameForObject(item).toString();
=======
if (StorageDrawers.config.cache.enableLockUpgrades)
GameRegistry.registerItem(upgradeLock, "upgradeLock");
if (StorageDrawers.config.cache.enableShroudUpgrades)
GameRegistry.registerItem(shroudKey, "shroudKey");
>>>>>>>
if (StorageDrawers.config.cache.enableLockUpgrades)
GameRegistry.registerItem(drawerKey, "drawerKey");
if (StorageDrawers.config.cache.enableShroudUpgrades)
GameRegistry.registerItem(shroudKey, "shroudKey");
}
public static String getQualifiedName (Item item) {
return GameData.getItemRegistry().getNameForObject(item).toString(); |
<<<<<<<
else if (item.getItem() == ModItems.upgradeStorage || item.getItem() == ModItems.upgradeStatus || item.getItem() == ModItems.upgradeVoid || item.getItem() == ModItems.upgradeCreative) {
if (!tileDrawers.addUpgrade(item) && !world.isRemote) {
=======
else if (item.getItem() == ModItems.upgrade || item.getItem() == ModItems.upgradeStatus || item.getItem() == ModItems.upgradeVoid ||
item.getItem() == ModItems.upgradeCreative || item.getItem() == ModItems.upgradeRedstone) {
if (!tileDrawers.addUpgrade(item)) {
>>>>>>>
else if (item.getItem() == ModItems.upgrade || item.getItem() == ModItems.upgradeStatus || item.getItem() == ModItems.upgradeVoid ||
item.getItem() == ModItems.upgradeCreative || item.getItem() == ModItems.upgradeRedstone) {
if (!tileDrawers.addUpgrade(item) && !world.isRemote) {
<<<<<<<
public IBlockState getStateForEntityRender (IBlockState state) {
return getDefaultState();
=======
public void getSubBlocks (Item item, CreativeTabs creativeTabs, List list) {
list.add(new ItemStack(item, 1, 0));
if (StorageDrawers.config.cache.creativeTabVanillaWoods) {
for (int i = 1; i < BlockWood.field_150096_a.length; i++)
list.add(new ItemStack(item, 1, i));
}
}
@Override
public boolean canProvidePower () {
return true;
}
@Override
public int isProvidingWeakPower (IBlockAccess blockAccess, int x, int y, int z, int dir) {
if (!canProvidePower())
return 0;
TileEntityDrawers tile = getTileEntity(blockAccess, x, y, z);
if (tile == null || !tile.isRedstone())
return 0;
return tile.getRedstoneLevel();
}
@Override
public int isProvidingStrongPower (IBlockAccess blockAccess, int x, int y, int z, int dir) {
return (dir == 1) ? isProvidingWeakPower(blockAccess, x, y, z, dir) : 0;
}
@SideOnly(Side.CLIENT)
public IIcon getIconTrim (int meta) {
meta = (meta < 0 || meta >= iconTrim.length) ? 0 : meta;
return iconTrim[meta];
>>>>>>>
public IBlockState getStateForEntityRender (IBlockState state) {
return getDefaultState(); |
<<<<<<<
setUnlocalizedName(blockName);
initDefaultState();
=======
setBlockName(blockName);
if (!halfDepth)
setLightOpacity(255);
>>>>>>>
setUnlocalizedName(blockName);
initDefaultState();
<<<<<<<
super.onBlockAdded(world, pos, state);
}
@Override
public IBlockState onBlockPlaced (World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) {
return getDefaultState().withProperty(BLOCK, EnumBasicDrawer.byMetadata(meta));
}
@Override
public void onBlockPlacedBy (World world, BlockPos pos, IBlockState state, EntityLivingBase entity, ItemStack itemStack) {
EnumFacing facing = entity.getHorizontalFacing().getOpposite();
TileEntityDrawers tile = getTileEntitySafe(world, pos);
tile.setDirection(facing.ordinal());
tile.markDirty();
=======
if (itemStack.hasDisplayName())
tile.setInventoryName(itemStack.getDisplayName());
if (world.isRemote) {
tile.invalidate();
world.markBlockForUpdate(x, y, z);
}
>>>>>>>
super.onBlockAdded(world, pos, state);
}
@Override
public IBlockState onBlockPlaced (World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) {
return getDefaultState().withProperty(BLOCK, EnumBasicDrawer.byMetadata(meta));
}
@Override
public void onBlockPlacedBy (World world, BlockPos pos, IBlockState state, EntityLivingBase entity, ItemStack itemStack) {
EnumFacing facing = entity.getHorizontalFacing().getOpposite();
TileEntityDrawers tile = getTileEntitySafe(world, pos);
tile.setDirection(facing.ordinal());
tile.markDirty();
if (itemStack.hasDisplayName())
tile.setInventoryName(itemStack.getDisplayName());
<<<<<<<
public IBlockState getStateFromMeta (int meta) {
IBlockState state = getDefaultState().withProperty(BLOCK, EnumBasicDrawer.byMetadata(meta));
return state;
=======
@SideOnly(Side.CLIENT)
public IIcon getIcon (int side, int meta) {
meta %= iconSide.length;
switch (side) {
case 0:
case 1:
return halfDepth ? iconSideH[meta] : iconSide[meta];
case 2:
case 3:
return halfDepth ? iconSideV[meta] : iconSide[meta];
case 4:
switch (drawerCount) {
case 1: return iconFront1[meta];
case 2: return iconFront2[meta];
case 4: return iconFront4[meta];
}
return null;
case 5:
return iconSide[meta];
}
return null;
>>>>>>>
public IBlockState getStateFromMeta (int meta) {
IBlockState state = getDefaultState().withProperty(BLOCK, EnumBasicDrawer.byMetadata(meta));
return state;
<<<<<<<
EnumFacing facing = EnumFacing.getFront(tile.getDirection());
if (facing.getAxis() == EnumFacing.Axis.Y)
facing = EnumFacing.NORTH;
=======
switch (side) {
case 0:
case 1:
if (halfDepth) {
switch (tile.getDirection()) {
case 2:
case 3:
case 4:
case 5:
return (level > 0) ? iconOverlayH[level] : iconSideH[meta];
}
}
break;
case 2:
case 3:
if (halfDepth) {
switch (tile.getDirection()) {
case 2:
case 3:
return (level > 0) ? iconOverlay[level] : iconSide[meta];
case 4:
case 5:
return (level > 0) ? iconOverlayV[level] : iconSideV[meta];
}
}
break;
case 4:
case 5:
if (halfDepth) {
switch (tile.getDirection()) {
case 2:
case 3:
return (level > 0) ? iconOverlayV[level] : iconSideV[meta];
case 4:
case 5:
return (level > 0) ? iconOverlay[level] : iconSide[meta];
}
}
break;
}
>>>>>>>
EnumFacing facing = EnumFacing.getFront(tile.getDirection());
if (facing.getAxis() == EnumFacing.Axis.Y)
facing = EnumFacing.NORTH; |
<<<<<<<
public void setMongoOptionTrustStorePath(String trustStorePath) {
this.mongoOptionTrustStorePath = trustStorePath;
}
public void setMongoOptionTrustStorePassword(String trustStorePassword) {
this.mongoOptionTrustStorePassword = trustStorePassword;
}
public void setMongoOptionTrustStoreType(String trustStoreType) {
this.mongoOptionTrustStoreType = trustStoreType;
}
public void setMongoOptionKeyStorePath(String keyStorePath) {
this.mongoOptionKeyStorePath = keyStorePath;
}
public void setMongoOptionKeyStorePassword(String keyStorePassword) {
this.mongoOptionKeyStorePassword = keyStorePassword;
}
public void setMongoOptionKeyStoreType(String keyStoreType) {
this.mongoOptionKeyStoreType = keyStoreType;
}
=======
public void setMongoOptionWriteConcernW(String mongoOptionWriteConcernW) {
this.mongoOptionWriteConcernW = mongoOptionWriteConcernW;
}
>>>>>>>
public void setMongoOptionTrustStorePath(String trustStorePath) {
this.mongoOptionTrustStorePath = trustStorePath;
}
public void setMongoOptionTrustStorePassword(String trustStorePassword) {
this.mongoOptionTrustStorePassword = trustStorePassword;
}
public void setMongoOptionTrustStoreType(String trustStoreType) {
this.mongoOptionTrustStoreType = trustStoreType;
}
public void setMongoOptionKeyStorePath(String keyStorePath) {
this.mongoOptionKeyStorePath = keyStorePath;
}
public void setMongoOptionKeyStorePassword(String keyStorePassword) {
this.mongoOptionKeyStorePassword = keyStorePassword;
}
public void setMongoOptionKeyStoreType(String keyStoreType) {
this.mongoOptionKeyStoreType = keyStoreType;
public void setMongoOptionWriteConcernW(String mongoOptionWriteConcernW) {
this.mongoOptionWriteConcernW = mongoOptionWriteConcernW;
} |
<<<<<<<
import com.jaquadro.minecraft.storagedrawers.item.ItemUpgradeStorage;
=======
import com.jaquadro.minecraft.storagedrawers.item.ItemUpgrade;
import com.jaquadro.minecraft.storagedrawers.item.ItemUpgradeCreative;
>>>>>>>
import com.jaquadro.minecraft.storagedrawers.item.ItemUpgradeStorage;
<<<<<<<
if (stack != null)
spawnAsEntity(world, pos, stack);
=======
if (stack != null) {
if (stack.getItem() instanceof ItemUpgradeCreative)
continue;
dropBlockAsItem(world, x, y, z, stack);
}
}
if (!tile.isVending()) {
for (int i = 0; i < tile.getDrawerCount(); i++) {
if (!tile.isDrawerEnabled(i))
continue;
IDrawer drawer = tile.getDrawer(i);
while (drawer.getStoredItemCount() > 0) {
ItemStack stack = tile.takeItemsFromSlot(i, drawer.getStoredItemStackSize());
if (stack == null || stack.stackSize == 0)
break;
dropStackInBatches(world, x, y, z, stack);
}
}
>>>>>>>
if (stack != null) {
if (stack.getItem() instanceof ItemUpgradeCreative)
continue;
spawnAsEntity(world, pos, stack);
} |
<<<<<<<
.withTrustStore(jobStore.mongoOptionTrustStorePath, jobStore.mongoOptionTrustStorePassword, jobStore.mongoOptionTrustStoreType)
.withKeyStore(jobStore.mongoOptionKeyStorePath, jobStore.mongoOptionKeyStorePassword, jobStore.mongoOptionKeyStoreType)
.withWriteTimeout(jobStore.mongoOptionWriteConcernTimeoutMillis)
=======
.withWriteConcernWriteTimeout(jobStore.mongoOptionWriteConcernTimeoutMillis)
.withWriteConcernW(jobStore.mongoOptionWriteConcernW)
>>>>>>>
.withTrustStore(jobStore.mongoOptionTrustStorePath, jobStore.mongoOptionTrustStorePassword, jobStore.mongoOptionTrustStoreType)
.withKeyStore(jobStore.mongoOptionKeyStorePath, jobStore.mongoOptionKeyStorePassword, jobStore.mongoOptionKeyStoreType)
.withWriteConcernWriteTimeout(jobStore.mongoOptionWriteConcernTimeoutMillis)
.withWriteConcernW(jobStore.mongoOptionWriteConcernW) |
<<<<<<<
import com.jaquadro.minecraft.storagedrawers.block.BlockFramingTable;
=======
import com.jaquadro.minecraft.storagedrawers.block.BlockTrimCustom;
>>>>>>>
import com.jaquadro.minecraft.storagedrawers.block.BlockFramingTable;
import com.jaquadro.minecraft.storagedrawers.block.BlockTrimCustom;
<<<<<<<
=======
import com.jaquadro.minecraft.storagedrawers.item.ItemCustomTrim;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
>>>>>>>
import com.jaquadro.minecraft.storagedrawers.item.ItemCustomTrim; |
<<<<<<<
public void getSubBlocks (Item item, CreativeTabs creativeTabs, NonNullList<ItemStack> list) {
if (StorageDrawers.config.cache.addonShowVanilla)
list.add(new ItemStack(item));
=======
@SideOnly(Side.CLIENT)
public void getSubBlocks (Item item, CreativeTabs creativeTabs, List<ItemStack> list) {
list.add(new ItemStack(item));
>>>>>>>
@SideOnly(Side.CLIENT)
public void getSubBlocks (Item item, CreativeTabs creativeTabs, NonNullList<ItemStack> list) {
list.add(new ItemStack(item)); |
<<<<<<<
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
=======
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.ForgeDirection;
>>>>>>>
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
<<<<<<<
=======
setDirection(tag.getByte("Dir"));
if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING))
customName = tag.getString("CustomName");
>>>>>>>
if (tag.hasKey("CustomName", Constants.NBT.TAG_STRING))
customName = tag.getString("CustomName");
<<<<<<<
=======
tag.setByte("Dir", (byte)direction);
if (hasCustomInventoryName())
tag.setString("CustomName", customName);
>>>>>>>
if (hasCustomName())
tag.setString("CustomName", customName); |
<<<<<<<
public BlockDrawers (String registryName, String blockName) {
this(Material.WOOD, registryName, blockName);
=======
private static final ThreadLocal<Boolean> inTileLookup = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue () {
return false;
}
};
public BlockDrawers (String blockName) {
this(Material.WOOD, blockName);
>>>>>>>
private static final ThreadLocal<Boolean> inTileLookup = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue () {
return false;
}
};
public BlockDrawers (String registryName, String blockName) {
this(Material.WOOD, registryName, blockName); |
<<<<<<<
markBlockForUpdate();
=======
IBlockState state = getWorld().getBlockState(getPos());
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForUpdate();
<<<<<<<
=======
IBlockState state = getWorld().getBlockState(getPos());
>>>>>>>
<<<<<<<
markBlockForUpdate();
=======
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForUpdate();
<<<<<<<
markBlockForUpdate();
=======
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForUpdate();
<<<<<<<
markBlockForUpdate();
=======
IBlockState state = getWorld().getBlockState(getPos());
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForUpdate();
<<<<<<<
markBlockForUpdate();
=======
IBlockState state = getWorld().getBlockState(getPos());
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForUpdate();
<<<<<<<
markBlockForUpdate();
=======
IBlockState state = getWorld().getBlockState(getPos());
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForUpdate();
<<<<<<<
markBlockForUpdate();
=======
IBlockState state = getWorld().getBlockState(getPos());
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForUpdate();
<<<<<<<
markBlockForUpdate();
=======
IBlockState state = getWorld().getBlockState(getPos());
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForUpdate();
<<<<<<<
if (isRedstone() && worldObj != null) {
worldObj.notifyNeighborsOfStateChange(getPos(), getBlockType());
worldObj.notifyNeighborsOfStateChange(getPos().down(), getBlockType());
=======
inventory.markDirty();
if (isRedstone() && getWorld() != null) {
getWorld().notifyNeighborsOfStateChange(getPos(), getBlockType());
getWorld().notifyNeighborsOfStateChange(getPos().down(), getBlockType());
>>>>>>>
if (isRedstone() && getWorld() != null) {
getWorld().notifyNeighborsOfStateChange(getPos(), getBlockType());
getWorld().notifyNeighborsOfStateChange(getPos().down(), getBlockType());
<<<<<<<
=======
IBlockState state = getWorld().getBlockState(getPos());
>>>>>>>
<<<<<<<
markBlockForUpdateClient();
=======
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForUpdateClient();
<<<<<<<
markBlockForRenderUpdate();
=======
getWorld().notifyBlockUpdate(getPos(), state, state, 3);
>>>>>>>
markBlockForRenderUpdate();
<<<<<<<
=======
private void syncClientCount (int slot) {
IMessage message = new CountUpdateMessage(getPos(), slot, drawers[slot].getStoredItemCount());
NetworkRegistry.TargetPoint targetPoint = new NetworkRegistry.TargetPoint(getWorld().provider.getDimension(), getPos().getX(), getPos().getY(), getPos().getZ(), 500);
StorageDrawers.network.sendToAllAround(message, targetPoint);
}
public boolean canUpdate () {
return false;
}
>>>>>>>
<<<<<<<
=======
@Override
public int[] getSlotsForFace (EnumFacing side) {
return inventory.getSlotsForFace(side);
}
@Override
public boolean canInsertItem (int slot, ItemStack stack, EnumFacing side) {
if (isSealed())
return false;
if (isItemLocked(LockAttribute.LOCK_EMPTY) && inventory instanceof StorageInventory) {
IDrawer drawer = getDrawer(inventory.getDrawerSlot(slot));
if (drawer != null && drawer.isEmpty())
return false;
}
return inventory.canInsertItem(slot, stack, side);
}
@Override
public boolean canExtractItem (int slot, ItemStack stack, EnumFacing side) {
if (isSealed())
return false;
return inventory.canExtractItem(slot, stack, side);
}
@Override
public int getSizeInventory () {
return inventory.getSizeInventory();
}
@Override
public ItemStack getStackInSlot (int slot) {
return inventory.getStackInSlot(slot);
}
@Override
public ItemStack decrStackSize (int slot, int count) {
return inventory.decrStackSize(slot, count);
}
@Override
public ItemStack removeStackFromSlot (int slot) {
return inventory.removeStackFromSlot(slot);
}
@Override
public void setInventorySlotContents (int slot, ItemStack stack) {
inventory.setInventorySlotContents(slot, stack);
}
public void setInventoryName (String name) {
customNameData.setName(name);
}
@Override
public String getName () {
return customNameData.getName();
}
@Override
public boolean hasCustomName () {
return customNameData.hasCustomName();
}
@Override
public ITextComponent getDisplayName () {
return customNameData.getDisplayName();
}
@Override
public int getInventoryStackLimit () {
return inventory.getInventoryStackLimit();
}
@Override
public boolean isUseableByPlayer (EntityPlayer player) {
if (getWorld().getTileEntity(getPos()) != this)
return false;
return player.getDistanceSq(getPos().getX() + .5, getPos().getY() + .5, getPos().getZ() + .5) <= 64;
}
@Override
public void openInventory (EntityPlayer player) {
inventory.openInventory(player);
}
@Override
public void closeInventory (EntityPlayer player) {
inventory.closeInventory(player);
}
@Override
public boolean isItemValidForSlot (int slot, ItemStack stack) {
return inventory.isItemValidForSlot(slot, stack);
}
@Override
public int getField (int id) {
return 0;
}
@Override
public void setField (int id, int value) {}
@Override
public int getFieldCount () {
return 0;
}
@Override
public void clear () {
inventory.clear();
}
>>>>>>> |
<<<<<<<
=======
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
>>>>>>>
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.util.IIcon;
<<<<<<<
private void renderCutFace (int face, RenderBlocks renderer, Block block, double x, double y, double z) {
renderFace(face, renderer, block, x, y, z, cutIcon[face], cutColor[face][0], cutColor[face][1], cutColor[face][2]);
}*/
=======
private void renderCutFace (int face, IBlockAccess blockAccess, Block block, double x, double y, double z) {
renderFace(face, blockAccess, block, x, y, z, cutIcon[face], cutColor[face][0], cutColor[face][1], cutColor[face][2]);
}
>>>>>>>
private void renderCutFace (int face, IBlockAccess blockAccess, Block block, double x, double y, double z) {
renderFace(face, blockAccess, block, x, y, z, cutIcon[face], cutColor[face][0], cutColor[face][1], cutColor[face][2]);
}
*/ |
<<<<<<<
import java.util.ArrayList;
=======
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
>>>>>>>
import java.util.ArrayList;
<<<<<<<
public static final PropertyEnum BLOCK = PropertyEnum.create("block", EnumBasicDrawer.class);
public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);
public static final PropertyEnum VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class);
=======
private static final ResourceLocation blockConfig = new ResourceLocation(StorageDrawers.MOD_ID + ":textures/blocks/block_config.mcmeta");
public final boolean halfDepth;
public final int drawerCount;
private float trimWidth = 0.0625f;
private float trimDepth = 0.0625f;
private float indStart = 0;
private float indEnd = 0;
private int indSteps = 0;
private String blockConfigName;
@SideOnly(Side.CLIENT)
protected IIcon[] iconSide;
@SideOnly(Side.CLIENT)
protected IIcon[] iconSideV;
@SideOnly(Side.CLIENT)
protected IIcon[] iconSideH;
@SideOnly(Side.CLIENT)
protected IIcon[] iconFront1;
@SideOnly(Side.CLIENT)
protected IIcon[] iconFront2;
@SideOnly(Side.CLIENT)
protected IIcon[] iconFront4;
@SideOnly(Side.CLIENT)
protected IIcon[] iconTrim;
@SideOnly(Side.CLIENT)
private IIcon[] iconOverlay;
@SideOnly(Side.CLIENT)
private IIcon[] iconOverlayV;
@SideOnly(Side.CLIENT)
private IIcon[] iconOverlayH;
@SideOnly(Side.CLIENT)
private IIcon[] iconOverlayTrim;
@SideOnly(Side.CLIENT)
private IIcon[] iconIndicator1;
@SideOnly(Side.CLIENT)
private IIcon[] iconIndicator2;
@SideOnly(Side.CLIENT)
private IIcon[] iconIndicator4;
>>>>>>>
public static final PropertyEnum BLOCK = PropertyEnum.create("block", EnumBasicDrawer.class);
public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);
public static final PropertyEnum VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class);
<<<<<<<
public BlockDrawers (String blockName) {
this(Material.wood, blockName);
=======
@SideOnly(Side.CLIENT)
private IIcon iconTaped;
public BlockDrawers (String blockName, int drawerCount, boolean halfDepth) {
this(Material.wood, blockName, drawerCount, halfDepth);
>>>>>>>
public BlockDrawers (String blockName) {
this(Material.wood, blockName);
<<<<<<<
setUnlocalizedName(blockName);
=======
setBlockName(blockName);
setConfigName(blockName);
>>>>>>>
setUnlocalizedName(blockName);
<<<<<<<
else if (item == null && player.isSneaking() && StorageDrawers.config.cache.enableDrawerUI) {
player.openGui(StorageDrawers.instance, GuiHandler.drawersGuiID, world, pos.getX(), pos.getY(), pos.getZ());
return true;
=======
else if (item == null && player.isSneaking()) {
if (tileDrawers.isSealed()) {
tileDrawers.setIsSealed(false);
return true;
}
else if (StorageDrawers.config.cache.enableDrawerUI) {
player.openGui(StorageDrawers.instance, GuiHandler.drawersGuiID, world, x, y, z);
return true;
}
>>>>>>>
else if (item == null && player.isSneaking()) {
if (tileDrawers.isSealed()) {
tileDrawers.setIsSealed(false);
return true;
}
else if (StorageDrawers.config.cache.enableDrawerUI) {
player.openGui(StorageDrawers.instance, GuiHandler.drawersGuiID, world, pos.getX(), pos.getY(), pos.getZ());
return true;
}
<<<<<<<
int slot = getDrawerSlot(getDrawerCount(state), side.ordinal(), hitX, hitY, hitZ);
=======
if (tileDrawers.isSealed())
return false;
int slot = getDrawerSlot(side, hitX, hitY, hitZ);
>>>>>>>
if (tileDrawers.isSealed())
return false;
int slot = getDrawerSlot(getDrawerCount(state), side.ordinal(), hitX, hitY, hitZ);
<<<<<<<
int slot = getDrawerSlot(getDrawerCount(world.getBlockState(pos)), side.ordinal(), hitX, hitY, hitZ);
=======
if (tileDrawers.isSealed())
return;
int slot = getDrawerSlot(side, hitX, hitY, hitZ);
>>>>>>>
if (tileDrawers.isSealed())
return;
int slot = getDrawerSlot(getDrawerCount(world.getBlockState(pos)), side.ordinal(), hitX, hitY, hitZ);
<<<<<<<
private BlockPlanks.EnumType translateMaterial (String materal) {
for (BlockPlanks.EnumType type : BlockPlanks.EnumType.values()) {
if (materal.equals(type.getName()))
return type;
=======
@SideOnly(Side.CLIENT)
private void loadBlockConfig () {
try {
IResource configResource = Minecraft.getMinecraft().getResourceManager().getResource(blockConfig);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(configResource.getInputStream()));
JsonObject root = (new JsonParser()).parse(reader).getAsJsonObject();
JsonObject entry = root.getAsJsonObject(getConfigName());
if (entry != null) {
if (entry.has("trimWidth"))
trimWidth = entry.get("trimWidth").getAsFloat();
if (entry.has("trimDepth"))
trimDepth = entry.get("trimDepth").getAsFloat();
if (entry.has("indStart"))
indStart = entry.get("indStart").getAsFloat();
if (entry.has("indEnd"))
indEnd = entry.get("indEnd").getAsFloat();
if (entry.has("indSteps"))
indSteps = entry.get("indSteps").getAsInt();
}
}
finally {
IOUtils.closeQuietly(reader);
}
} catch (IOException e) {
e.printStackTrace();
>>>>>>>
private BlockPlanks.EnumType translateMaterial (String materal) {
for (BlockPlanks.EnumType type : BlockPlanks.EnumType.values()) {
if (materal.equals(type.getName()))
return type; |
<<<<<<<
=======
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.api.security.ISecurityProvider;
>>>>>>>
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.api.security.ISecurityProvider;
<<<<<<<
=======
import com.jaquadro.minecraft.storagedrawers.item.ItemPersonalKey;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
>>>>>>>
import com.jaquadro.minecraft.storagedrawers.item.ItemPersonalKey; |
<<<<<<<
import com.jaquadro.minecraft.storagedrawers.block.EnumBasicDrawer;
=======
import com.jaquadro.minecraft.storagedrawers.core.ModBlocks;
>>>>>>>
<<<<<<<
}
*/
=======
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon (int side, int meta) {
meta = (meta < 0 || meta >= iconSide.length) ? 0 : meta;
if (!resolver.isValidMetaValue(meta))
getSimilarBlock().getIcon(side, meta);
return super.getIcon(side, meta);
}
@Override
@SideOnly(Side.CLIENT)
protected IIcon getIcon (IBlockAccess blockAccess, int x, int y, int z, int side, int level) {
int meta = blockAccess.getBlockMetadata(x, y, z);
meta = (meta < 0 || meta >= iconSide.length) ? 0 : meta;
if (!resolver.isValidMetaValue(meta))
getSimilarBlock().getIcon(side, meta);
return super.getIcon(blockAccess, x, y, z, side, level);
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconTrim (int meta) {
meta = (meta < 0 || meta >= iconSide.length) ? 0 : meta;
if (!resolver.isValidMetaValue(meta))
getSimilarBlock().getIconTrim(meta);
return super.getIconTrim(meta);
}
private BlockDrawers getSimilarBlock () {
if (drawerCount == 1 && !halfDepth)
return ModBlocks.fullDrawers1;
if (drawerCount == 2 && !halfDepth)
return ModBlocks.fullDrawers2;
if (drawerCount == 4 && !halfDepth)
return ModBlocks.fullDrawers4;
if (drawerCount == 2 && halfDepth)
return ModBlocks.halfDrawers2;
if (drawerCount == 4 && halfDepth)
return ModBlocks.halfDrawers4;
return ModBlocks.fullDrawers1;
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons (IIconRegister register) {
super.registerBlockIcons(register);
iconSide = new IIcon[16];
iconSideH = new IIcon[16];
iconSideV = new IIcon[16];
iconFront1 = new IIcon[16];
iconFront2 = new IIcon[16];
iconFront4 = new IIcon[16];
iconTrim = new IIcon[16];
for (int i = 0; i < 16; i++) {
if (!resolver.isValidMetaValue(i))
continue;
iconFront1[i] = register.registerIcon(resolver.getTexturePath(TextureType.Front1, i));
iconFront2[i] = register.registerIcon(resolver.getTexturePath(TextureType.Front2, i));
iconFront4[i] = register.registerIcon(resolver.getTexturePath(TextureType.Front4, i));
iconSide[i] = register.registerIcon(resolver.getTexturePath(TextureType.Side, i));
iconSideV[i] = register.registerIcon(resolver.getTexturePath(TextureType.SideVSplit, i));
iconSideH[i] = register.registerIcon(resolver.getTexturePath(TextureType.SideHSplit, i));
iconTrim[i] = register.registerIcon(resolver.getTexturePath(TextureType.TrimBorder, i));
}
}
}
>>>>>>>
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon (int side, int meta) {
meta = (meta < 0 || meta >= iconSide.length) ? 0 : meta;
if (!resolver.isValidMetaValue(meta))
getSimilarBlock().getIcon(side, meta);
return super.getIcon(side, meta);
}
@Override
@SideOnly(Side.CLIENT)
protected IIcon getIcon (IBlockAccess blockAccess, int x, int y, int z, int side, int level) {
int meta = blockAccess.getBlockMetadata(x, y, z);
meta = (meta < 0 || meta >= iconSide.length) ? 0 : meta;
if (!resolver.isValidMetaValue(meta))
getSimilarBlock().getIcon(side, meta);
return super.getIcon(blockAccess, x, y, z, side, level);
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconTrim (int meta) {
meta = (meta < 0 || meta >= iconSide.length) ? 0 : meta;
if (!resolver.isValidMetaValue(meta))
getSimilarBlock().getIconTrim(meta);
return super.getIconTrim(meta);
}
private BlockDrawers getSimilarBlock () {
if (drawerCount == 1 && !halfDepth)
return ModBlocks.fullDrawers1;
if (drawerCount == 2 && !halfDepth)
return ModBlocks.fullDrawers2;
if (drawerCount == 4 && !halfDepth)
return ModBlocks.fullDrawers4;
if (drawerCount == 2 && halfDepth)
return ModBlocks.halfDrawers2;
if (drawerCount == 4 && halfDepth)
return ModBlocks.halfDrawers4;
return ModBlocks.fullDrawers1;
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons (IIconRegister register) {
super.registerBlockIcons(register);
iconSide = new IIcon[16];
iconSideH = new IIcon[16];
iconSideV = new IIcon[16];
iconFront1 = new IIcon[16];
iconFront2 = new IIcon[16];
iconFront4 = new IIcon[16];
iconTrim = new IIcon[16];
for (int i = 0; i < 16; i++) {
if (!resolver.isValidMetaValue(i))
continue;
iconFront1[i] = register.registerIcon(resolver.getTexturePath(TextureType.Front1, i));
iconFront2[i] = register.registerIcon(resolver.getTexturePath(TextureType.Front2, i));
iconFront4[i] = register.registerIcon(resolver.getTexturePath(TextureType.Front4, i));
iconSide[i] = register.registerIcon(resolver.getTexturePath(TextureType.Side, i));
iconSideV[i] = register.registerIcon(resolver.getTexturePath(TextureType.SideVSplit, i));
iconSideH[i] = register.registerIcon(resolver.getTexturePath(TextureType.SideHSplit, i));
iconTrim[i] = register.registerIcon(resolver.getTexturePath(TextureType.TrimBorder, i));
}
}
}
*/ |
<<<<<<<
/**
* The configured settings.
*/
private Settings settings;
=======
/**
* The path to optional dependency-check properties file. This will be
* used to side-load additional user-defined properties.
* {@link Settings#mergeProperties(String)}
*/
private String propertiesFilePath;
>>>>>>>
/**
* The configured settings.
*/
private Settings settings;
/**
* The path to optional dependency-check properties file. This will be
* used to side-load additional user-defined properties.
* {@link Settings#mergeProperties(String)}
*/
private String propertiesFilePath; |
<<<<<<<
import java.util.Set;
=======
import static org.fest.assertions.Assertions.assertThat;
import java.util.Set;
>>>>>>>
import static org.fest.assertions.Assertions.assertThat;
import java.util.Set;
<<<<<<<
import static org.fest.assertions.Assertions.assertThat;
=======
>>>>>>>
import static org.fest.assertions.Assertions.assertThat; |
<<<<<<<
providersImplMap.put(Constants.GOOGLE_PLUS,
org.brickred.socialauth.provider.GooglePlusImpl.class);
=======
providersImplMap.put(Constants.INSTAGRAM,
org.brickred.socialauth.provider.RunkeeperImpl.class);
>>>>>>>
providersImplMap.put(Constants.GOOGLE_PLUS,
org.brickred.socialauth.provider.GooglePlusImpl.class);
providersImplMap.put(Constants.INSTAGRAM,
org.brickred.socialauth.provider.RunkeeperImpl.class);
<<<<<<<
domainMap.put(Constants.GOOGLE_PLUS, "googleapis.com");
=======
domainMap.put(Constants.INSTAGRAM, "api.instagram.com");
>>>>>>>
domainMap.put(Constants.GOOGLE_PLUS, "googleapis.com");
domainMap.put(Constants.INSTAGRAM, "api.instagram.com"); |
<<<<<<<
import com.yahoo.squidb.android.SquidCursorWrapper;
import com.yahoo.squidb.data.ICursor;
import com.yahoo.squidb.data.ISQLiteDatabase;
import com.yahoo.squidb.data.SQLExceptionWrapper;
import com.yahoo.squidb.data.SquidTransactionListener;
=======
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Pair;
import com.yahoo.squidb.data.adapter.SQLiteDatabaseWrapper;
import com.yahoo.squidb.data.adapter.SquidTransactionListener;
>>>>>>>
import com.yahoo.squidb.android.SquidCursorWrapper;
import com.yahoo.squidb.data.ICursor;
import com.yahoo.squidb.data.ISQLiteDatabase;
import com.yahoo.squidb.data.SquidTransactionListener; |
<<<<<<<
protected synchronized final ISQLiteDatabase getDatabase() {
=======
protected synchronized final SQLiteDatabaseWrapper getDatabase() {
// If we get here, we should already have the non-exclusive lock
>>>>>>>
protected synchronized final ISQLiteDatabase getDatabase() {
// If we get here, we should already have the non-exclusive lock
<<<<<<<
// Some platforms need to wait for transactions to finish,
// so we acquire an exclusive lock before attaching
acquireExclusiveLock();
=======
boolean walEnabled;
acquireNonExclusiveLock();
try {
walEnabled = (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN)
&& getDatabase().isWriteAheadLoggingEnabled();
} finally {
releaseNonExclusiveLock();
}
if (walEnabled) {
// need to wait for transactions to finish
acquireExclusiveLock();
}
>>>>>>>
// Some platforms need to wait for transactions to finish,
// so we acquire an exclusive lock before attaching
acquireExclusiveLock();
<<<<<<<
public synchronized final void clear() {
close();
getOpenHelper().deleteDatabase();
=======
public final void clear() {
acquireExclusiveLock();
try {
close();
context.deleteDatabase(getName());
} finally {
releaseExclusiveLock();
}
>>>>>>>
public final void clear() {
acquireExclusiveLock();
try {
close();
getOpenHelper().deleteDatabase();
} finally {
releaseExclusiveLock();
} |
<<<<<<<
import com.yahoo.aptutils.writer.parameters.MethodDeclarationParameters;
import com.yahoo.squidb.processor.plugins.defaults.properties.generators.PropertyGenerator;
=======
import com.yahoo.squidb.processor.data.ModelSpec;
>>>>>>>
import com.yahoo.aptutils.writer.parameters.MethodDeclarationParameters;
import com.yahoo.squidb.processor.plugins.defaults.properties.generators.PropertyGenerator;
import com.yahoo.squidb.processor.data.ModelSpec; |
<<<<<<<
testThrowsException(new Runnable() {
@Override
public void run() {
// insert into testModels (firstName, lastName) values ("Jack", "Sparrow"), ("James", "Bond", 007),
// ("Bugs", "Bunny");
Object[] values1 = new Object[]{"Jack", "Sparrow"};
Object[] values2 = new Object[]{"James", "Bond", Integer.valueOf(007)};
Object[] values3 = new Object[]{"Bugs", "Bunny"};
Insert insert = Insert.into(TestModel.TABLE).columns(TestModel.FIRST_NAME, TestModel.LAST_NAME)
.values(values1).values(values2).values(values3);
insert.compile(database.getSqliteVersion());
}
}, IllegalStateException.class);
=======
// insert into testModels (firstName, lastName) values ("Jack", "Sparrow"), ("James", "Bond", 007),
// ("Bugs", "Bunny");
Object[] values1 = new Object[]{"Jack", "Sparrow"};
Object[] values2 = new Object[]{"James", "Bond", Integer.parseInt("007")};
Object[] values3 = new Object[]{"Bugs", "Bunny"};
Insert insert = Insert.into(TestModel.TABLE).columns(TestModel.FIRST_NAME, TestModel.LAST_NAME)
.values(values1).values(values2).values(values3);
insert.compile(database.getSqliteVersion());
>>>>>>>
testThrowsException(new Runnable() {
@Override
public void run() {
// insert into testModels (firstName, lastName) values ("Jack", "Sparrow"), ("James", "Bond", 007),
// ("Bugs", "Bunny");
Object[] values1 = new Object[]{"Jack", "Sparrow"};
Object[] values2 = new Object[]{"James", "Bond", Integer.parseInt("007")};
Object[] values3 = new Object[]{"Bugs", "Bunny"};
Insert insert = Insert.into(TestModel.TABLE).columns(TestModel.FIRST_NAME, TestModel.LAST_NAME)
.values(values1).values(values2).values(values3);
insert.compile(database.getSqliteVersion());
}
}, IllegalStateException.class); |
<<<<<<<
import com.yahoo.squidb.test.Thing;
=======
import com.yahoo.squidb.test.Thing;
import com.yahoo.squidb.utility.VersionCode;
>>>>>>>
import com.yahoo.squidb.test.Thing;
<<<<<<<
throw new SQLExceptionWrapper(
new RuntimeException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"));
} else if (shouldRecreate) {
=======
throw new SQLiteException("My name is \"NO! NO! BAD DATABASE!\". What's yours?");
} else if (shouldRecreateInMigration) {
>>>>>>>
throw new SQLExceptionWrapper(
new RuntimeException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"));
} else if (shouldRecreateInMigration) {
<<<<<<<
throw new SQLExceptionWrapper(
new RuntimeException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"));
} else if (shouldRecreate) {
=======
throw new SQLiteException("My name is \"NO! NO! BAD DATABASE!\". What's yours?");
} else if (shouldRecreateInMigration) {
>>>>>>>
throw new SQLExceptionWrapper(
new RuntimeException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"));
} else if (shouldRecreateInMigration) {
<<<<<<<
public void testSimpleQueries() {
database.beginTransactionNonExclusive();
try {
// the changes() function only works inside a transaction, because otherwise you may not get
// the same connection to the sqlite database depending on what the connection pool feels like giving you.
String sql = "SELECT CHANGES()";
insertBasicTestModel();
assertEquals(1, database.simpleQueryForLong(sql, null));
assertEquals("1", database.simpleQueryForString(sql, null));
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
=======
public void testConcurrencyStressTest() {
int numThreads = 20;
final AtomicReference<Exception> exception = new AtomicReference<Exception>();
List<Thread> workers = new ArrayList<Thread>();
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
concurrencyStressTest(exception);
}
});
t.start();
workers.add(t);
}
for (Thread t : workers) {
try {
t.join();
} catch (Exception e) {
exception.set(e);
}
}
assertNull(exception.get());
}
private void concurrencyStressTest(AtomicReference<Exception> exception) {
try {
Random r = new Random();
int numOperations = 100;
Thing t = new Thing();
for (int i = 0; i < numOperations; i++) {
int rand = r.nextInt(10);
if (rand == 0) {
database.close();
} else if (rand == 1) {
database.clear();
} else if (rand == 2) {
database.recreate();
} else if (rand == 3) {
database.beginTransactionNonExclusive();
try {
for (int j = 0; j < 20; j++) {
t.setFoo(Integer.toString(j))
.setBar(-j);
database.createNew(t);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
} else {
t.setFoo(Integer.toString(i))
.setBar(-i);
database.createNew(t);
}
}
} catch (Exception e) {
exception.set(e);
}
}
>>>>>>>
public void testSimpleQueries() {
database.beginTransactionNonExclusive();
try {
// the changes() function only works inside a transaction, because otherwise you may not get
// the same connection to the sqlite database depending on what the connection pool feels like giving you.
String sql = "SELECT CHANGES()";
insertBasicTestModel();
assertEquals(1, database.simpleQueryForLong(sql, null));
assertEquals("1", database.simpleQueryForString(sql, null));
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public void testConcurrencyStressTest() {
int numThreads = 20;
final AtomicReference<Exception> exception = new AtomicReference<Exception>();
List<Thread> workers = new ArrayList<Thread>();
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
concurrencyStressTest(exception);
}
});
t.start();
workers.add(t);
}
for (Thread t : workers) {
try {
t.join();
} catch (Exception e) {
exception.set(e);
}
}
assertNull(exception.get());
}
private void concurrencyStressTest(AtomicReference<Exception> exception) {
try {
Random r = new Random();
int numOperations = 100;
Thing t = new Thing();
for (int i = 0; i < numOperations; i++) {
int rand = r.nextInt(10);
if (rand == 0) {
database.close();
} else if (rand == 1) {
database.clear();
} else if (rand == 2) {
database.recreate();
} else if (rand == 3) {
database.beginTransactionNonExclusive();
try {
for (int j = 0; j < 20; j++) {
t.setFoo(Integer.toString(j))
.setBar(-j);
database.createNew(t);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
} else {
t.setFoo(Integer.toString(i))
.setBar(-i);
database.createNew(t);
}
}
} catch (Exception e) {
exception.set(e);
}
} |
<<<<<<<
import static org.junit.Assert.*;
import org.owasp.dependencycheck.data.nvdcve.BaseDBTestCase;
=======
import org.owasp.dependencycheck.BaseTest;
>>>>>>>
import org.owasp.dependencycheck.data.nvdcve.BaseDBTestCase; |
<<<<<<<
=======
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import com.yahoo.squidb.data.adapter.SQLiteDatabaseWrapper;
import com.yahoo.squidb.sql.Field;
>>>>>>>
import com.yahoo.squidb.sql.Field;
<<<<<<<
import java.util.Random;
=======
>>>>>>>
import java.util.Random; |
<<<<<<<
=======
import com.yahoo.squidb.data.adapter.DefaultOpenHelperWrapper;
import com.yahoo.squidb.data.adapter.SQLiteDatabaseWrapper;
import com.yahoo.squidb.data.adapter.SQLiteOpenHelperWrapper;
import com.yahoo.squidb.data.adapter.SquidTransactionListener;
>>>>>>>
<<<<<<<
* @throws SQLExceptionWrapper if there is an error parsing the SQL or some other error
* @see ISQLiteDatabase#execSQL(String)
=======
* @see SQLiteDatabase#execSQL(String)
>>>>>>>
* @see ISQLiteDatabase#execSQL(String)
<<<<<<<
* @throws SQLExceptionWrapper if there is an error parsing the SQL or some other error
* @see ISQLiteDatabase#execSQL(String, Object[])
=======
* @see SQLiteDatabase#execSQL(String, Object[])
>>>>>>>
* @see ISQLiteDatabase#execSQL(String, Object[]) |
<<<<<<<
=======
if (helper == null) {
helper = getOpenHelper(context, getName(), new OpenHelperDelegate(), getVersion());
}
boolean areDataChangedNotificationsEnabled = areDataChangedNotificationsEnabled();
setDataChangedNotificationsEnabled(false);
>>>>>>>
boolean areDataChangedNotificationsEnabled = areDataChangedNotificationsEnabled();
setDataChangedNotificationsEnabled(false);
<<<<<<<
=======
* See the note at the top of this file about the potential bugs when using String[] whereArgs
* <br>
* This method is deprecated and will be removed in SquiDB 3.0
* @see SQLiteDatabase#delete(String, String, String[])
*/
@Deprecated
protected int delete(String table, String whereClause, String[] whereArgs) {
acquireNonExclusiveLock();
try {
return getDatabase().delete(table, whereClause, whereArgs);
} finally {
releaseNonExclusiveLock();
}
}
/**
>>>>>>>
<<<<<<<
=======
* See the note at the top of this file about the potential bugs when using String[] whereArgs
* <br>
* This method is deprecated and will be removed in SquiDB 3.0
* @see SQLiteDatabase#update(String table, ContentValues values, String whereClause, String[] whereArgs)
*/
@Deprecated
protected int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
acquireNonExclusiveLock();
try {
return getDatabase().update(table, values, whereClause, whereArgs);
} finally {
releaseNonExclusiveLock();
}
}
/**
* See the note at the top of this file about the potential bugs when using String[] whereArgs
* <br>
* This method is deprecated and will be removed in SquiDB 3.0
* @see SQLiteDatabase#updateWithOnConflict(String table, ContentValues values, String whereClause, String[]
* whereArgs, int conflictAlgorithm)
*/
@Deprecated
protected int updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs,
int conflictAlgorithm) {
acquireNonExclusiveLock();
try {
return getDatabase().updateWithOnConflict(table, values, whereClause, whereArgs, conflictAlgorithm);
} finally {
releaseNonExclusiveLock();
}
}
/**
>>>>>>> |
<<<<<<<
void render(CAS aCas, AnnotatorState aState, VDocument vdoc);
=======
void render(JCas jCas, AnnotatorState aState, VDocument vdoc,
int aWindowBeginOffset, int aWindowEndOffset);
>>>>>>>
void render(CAS aCas, AnnotatorState aState, VDocument vdoc, int aWindowBeginOffset,
int aWindowEndOffset); |
<<<<<<<
{
neLayer.setOverlapMode(OverlapMode.NO_OVERLAP);
VDocument vdoc = new VDocument();
sut.render(jcas, asList(), vdoc, 0, jcas.getDocumentText().length());
assertThat(vdoc.comments())
.usingFieldByFieldElementComparator()
.containsExactlyInAnyOrder(
new VComment(ne1, VCommentType.ERROR, "Overlaps are not permitted."),
new VComment(ne2, VCommentType.ERROR, "Overlaps are not permitted."));
}
=======
VDocument vdoc = new VDocument();
sut.render(jcas.getCas(), asList(), vdoc, 0, jcas.getDocumentText().length());
>>>>>>>
{
neLayer.setOverlapMode(OverlapMode.NO_OVERLAP);
VDocument vdoc = new VDocument();
sut.render(jcas.getCas(), asList(), vdoc, 0, jcas.getDocumentText().length());
assertThat(vdoc.comments())
.usingFieldByFieldElementComparator()
.containsExactlyInAnyOrder(
new VComment(ne1, VCommentType.ERROR, "Overlaps are not permitted."),
new VComment(ne2, VCommentType.ERROR, "Overlaps are not permitted."));
} |
<<<<<<<
if (aExLayer.getOverlapMode() == null) {
// This allows importing old projects which did not have the overlap mode yet
aLayer.setOverlapMode(aExLayer.isAllowStacking() ? ANY_OVERLAP : OVERLAP_ONLY);
}
else {
aLayer.setOverlapMode(aExLayer.getOverlapMode());
}
=======
aLayer.setValidationMode(aExLayer.getValidationMode() != null ? aExLayer.getValidationMode()
: ValidationMode.NEVER);
>>>>>>>
if (aExLayer.getOverlapMode() == null) {
// This allows importing old projects which did not have the overlap mode yet
aLayer.setOverlapMode(aExLayer.isAllowStacking() ? ANY_OVERLAP : OVERLAP_ONLY);
}
else {
aLayer.setOverlapMode(aExLayer.getOverlapMode());
}
aLayer.setValidationMode(aExLayer.getValidationMode() != null ? aExLayer.getValidationMode()
: ValidationMode.NEVER); |
<<<<<<<
import de.tudarmstadt.ukp.clarin.webanno.model.OverlapMode;
=======
import de.tudarmstadt.ukp.clarin.webanno.model.ValidationMode;
>>>>>>>
import de.tudarmstadt.ukp.clarin.webanno.model.OverlapMode;
import de.tudarmstadt.ukp.clarin.webanno.model.ValidationMode;
<<<<<<<
@JsonProperty("overlap_mode")
private OverlapMode overlapMode;
=======
@JsonProperty("validation_mode")
private ValidationMode validationMode;
>>>>>>>
@JsonProperty("overlap_mode")
private OverlapMode overlapMode;
@JsonProperty("validation_mode")
private ValidationMode validationMode; |
<<<<<<<
if (layer.getType().equals(RELATION_TYPE) && layer.getAttachType() == null) {
=======
if (layer.getType().equals(RELATION_TYPE)
&& layer.getAttachType() == null) {
>>>>>>>
if (layer.getType().equals(RELATION_TYPE) && layer.getAttachType() == null) {
<<<<<<<
=======
annotationService.createLayer(layer);
>>>>>>>
annotationService.createLayer(layer); |
<<<<<<<
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.NumberFeatureTraits;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.NumberFeatureTraitsEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.RatingFeatureEditor;
=======
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.TextAreaFeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.UimaStringTraits;
>>>>>>>
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.NumberFeatureTraits;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.NumberFeatureTraitsEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.RatingFeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.TextAreaFeatureEditor;
import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.editor.UimaStringTraits;
<<<<<<<
private final Logger log = LoggerFactory.getLogger(getClass());
=======
private final Logger log = LoggerFactory.getLogger(getClass());
>>>>>>>
private final Logger log = LoggerFactory.getLogger(getClass());
<<<<<<<
// TODO: trait reading/writing needs to be handled in another way to avoid duplicate code
public NumberFeatureTraits readNumberFeatureTraits(AnnotationFeature aFeature)
{
NumberFeatureTraits traits = null;
try {
traits = JSONUtil.fromJsonString(NumberFeatureTraits.class, aFeature.getTraits());
}
catch (IOException e) {
log.error("Unable to read traits", e);
}
if (traits == null) {
traits = new NumberFeatureTraits();
}
return traits;
}
public void writeNumberFeatureTraits(AnnotationFeature aFeature, NumberFeatureTraits aTraits)
{
try {
aFeature.setTraits(JSONUtil.toJsonString(aTraits));
}
catch (IOException e) {
log.error("Unable to write traits", e);
}
}
=======
public UimaStringTraits readUimaStringTraits(AnnotationFeature aFeature)
{
UimaStringTraits traits = null;
try {
traits = JSONUtil.fromJsonString(UimaStringTraits.class, aFeature.getTraits());
}
catch (IOException e) {
log.error("Unable to read traits", e);
}
if (traits == null) {
traits = new UimaStringTraits();
}
return traits;
}
public void writeUimaStringTraits(AnnotationFeature aFeature, UimaStringTraits aTraits)
{
try {
aFeature.setTraits(JSONUtil.toJsonString(aTraits));
}
catch (IOException e) {
log.error("Unable to write traits", e);
}
}
>>>>>>>
// TODO: trait reading/writing needs to be handled in another way to avoid duplicate code
public NumberFeatureTraits readNumberFeatureTraits(AnnotationFeature aFeature)
{
NumberFeatureTraits traits = null;
try {
traits = JSONUtil.fromJsonString(NumberFeatureTraits.class, aFeature.getTraits());
}
catch (IOException e) {
log.error("Unable to read traits", e);
}
if (traits == null) {
traits = new NumberFeatureTraits();
}
return traits;
}
public UimaStringTraits readUimaStringTraits(AnnotationFeature aFeature)
{
UimaStringTraits traits = null;
try {
traits = JSONUtil.fromJsonString(UimaStringTraits.class, aFeature.getTraits());
}
catch (IOException e) {
log.error("Unable to read traits", e);
}
if (traits == null) {
traits = new UimaStringTraits();
}
return traits;
}
public void writeNumberFeatureTraits(AnnotationFeature aFeature, NumberFeatureTraits aTraits)
{
try {
aFeature.setTraits(JSONUtil.toJsonString(aTraits));
}
catch (IOException e) {
log.error("Unable to write traits", e);
}
}
public void writeUimaStringTraits(AnnotationFeature aFeature, UimaStringTraits aTraits)
{
try {
aFeature.setTraits(JSONUtil.toJsonString(aTraits));
}
catch (IOException e) {
log.error("Unable to write traits", e);
}
} |
<<<<<<<
=======
@Override
public List<AnnotationLayer> getAllAnnotationLayers()
{
return allAnnotationLayers;
}
@Override
public void setAllAnnotationLayers(List<AnnotationLayer> aLayers)
{
allAnnotationLayers = unmodifiableList(new ArrayList<>(aLayers));
}
>>>>>>>
@Override
public List<AnnotationLayer> getAllAnnotationLayers()
{
return allAnnotationLayers;
}
@Override
public void setAllAnnotationLayers(List<AnnotationLayer> aLayers)
{
allAnnotationLayers = unmodifiableList(new ArrayList<>(aLayers));
}
<<<<<<<
return !user.getUsername().equals(CURATION_USER) && !user.equals(aCurrentUser);
=======
return !CURATION_USER.equals(aCurrentUserName) &&
!user.getUsername().equals(aCurrentUserName);
>>>>>>>
return !CURATION_USER.equals(aCurrentUserName)
&& !user.getUsername().equals(aCurrentUserName); |
<<<<<<<
=======
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentStateTransition;
import de.tudarmstadt.ukp.clarin.webanno.model.Mode;
>>>>>>>
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentStateTransition; |
<<<<<<<
protected VDocument render(CAS aCas, int windowBeginOffset, int windowEndOffset)
=======
protected VDocument render(JCas aJCas, int aWindowBeginOffset, int aWindowEndOffset)
>>>>>>>
protected VDocument render(CAS aCas, int aWindowBeginOffset, int aWindowEndOffset)
<<<<<<<
preRenderer.render(vdoc, windowBeginOffset, windowEndOffset,
aCas, getLayersToRender());
=======
preRenderer.render(vdoc, aWindowBeginOffset, aWindowEndOffset,
aJCas, getLayersToRender());
>>>>>>>
preRenderer.render(vdoc, aWindowBeginOffset, aWindowEndOffset,
aCas, getLayersToRender());
<<<<<<<
extensionRegistry.fireRender(aCas, getModelObject(), vdoc);
=======
extensionRegistry.fireRender(aJCas, getModelObject(), vdoc,
aWindowBeginOffset, aWindowEndOffset);
>>>>>>>
extensionRegistry.fireRender(aCas, getModelObject(), vdoc,
aWindowBeginOffset, aWindowEndOffset); |
<<<<<<<
=======
import de.agilecoders.wicket.core.markup.html.bootstrap.components.PopoverBehavior;
import de.agilecoders.wicket.core.markup.html.bootstrap.components.PopoverConfig;
import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig.Placement;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelect;
>>>>>>>
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelect;
<<<<<<<
import de.tudarmstadt.ukp.clarin.webanno.support.bootstrap.select.BootstrapSelect;
import de.tudarmstadt.ukp.clarin.webanno.support.lambda.LambdaAjaxButton;
=======
import de.tudarmstadt.ukp.clarin.webanno.support.AJAXDownload;
>>>>>>>
import de.tudarmstadt.ukp.clarin.webanno.support.lambda.LambdaAjaxButton; |
<<<<<<<
if (!isUserViewingOthersWork(state, userRepository.getCurrentUser())
&& SourceDocumentState.NEW.equals(state.getDocument().getState())) {
documentService.transitionSourceDocumentState(state.getDocument(),
NEW_TO_ANNOTATION_IN_PROGRESS);
=======
if (!isUserViewingOthersWork()) {
if (SourceDocumentState.NEW.equals(state.getDocument().getState())) {
documentService.transitionSourceDocumentState(state.getDocument(),
NEW_TO_ANNOTATION_IN_PROGRESS);
}
if (AnnotationDocumentState.NEW.equals(annotationDocument.getState())) {
documentService.transitionAnnotationDocumentState(annotationDocument,
AnnotationDocumentStateTransition.NEW_TO_ANNOTATION_IN_PROGRESS);
}
>>>>>>>
if (!isUserViewingOthersWork(state, userRepository.getCurrentUser())
&& SourceDocumentState.NEW.equals(state.getDocument().getState())) {
if (SourceDocumentState.NEW.equals(state.getDocument().getState())) {
documentService.transitionSourceDocumentState(state.getDocument(),
NEW_TO_ANNOTATION_IN_PROGRESS);
}
if (AnnotationDocumentState.NEW.equals(annotationDocument.getState())) {
documentService.transitionAnnotationDocumentState(annotationDocument,
AnnotationDocumentStateTransition.NEW_TO_ANNOTATION_IN_PROGRESS);
} |
<<<<<<<
=======
Map<AnnotationFS, Integer> sentenceIndexes = null;
>>>>>>>
Map<AnnotationFS, Integer> sentenceIndexes = null;
<<<<<<<
List<AnnotationFS> sentences = new ArrayList<>(select(aCas, getType(aCas, Sentence.class)));
=======
>>>>>>>
<<<<<<<
if (!vcomment.getVid().isSynthetic()
&& ((fs = selectAnnotationByAddr(aCas, vcomment.getVid().getId())) != null
&& fs.getType().getName().equals(Sentence.class.getName()))) {
int index = sentences.indexOf(fs) + 1;
=======
if (
!vcomment.getVid().isSynthetic() &&
((fs = selectAnnotationByAddr(aCas, vcomment.getVid().getId())) != null &&
fs.getType().getName().equals(Sentence.class.getName()))
) {
// Lazily fetching the sentences because we only need them for the comments
if (sentenceIndexes == null) {
sentenceIndexes = new HashMap<>();
int i = 1;
for (AnnotationFS s : select(aCas, getType(aCas, Sentence.class))) {
sentenceIndexes.put(s, i);
i++;
}
}
int index = sentenceIndexes.get(fs);
>>>>>>>
if (!vcomment.getVid().isSynthetic()
&& ((fs = selectAnnotationByAddr(aCas, vcomment.getVid().getId())) != null
&& fs.getType().getName().equals(Sentence.class.getName()))) {
// Lazily fetching the sentences because we only need them for the comments
if (sentenceIndexes == null) {
sentenceIndexes = new HashMap<>();
int i = 1;
for (AnnotationFS s : select(aCas, getType(aCas, Sentence.class))) {
sentenceIndexes.put(s, i);
i++;
}
}
int index = sentenceIndexes.get(fs); |
<<<<<<<
userRepository = aUserRepository;
=======
>>>>>>>
<<<<<<<
this(aRepositoryProperties, aUserRepository, aCasStorageService, aImportExportService,
aProjectService, aApplicationEventPublisher);
=======
this(aRepositoryProperties, aCasStorageService, aImportExportService, aProjectService,
aApplicationEventPublisher);
>>>>>>>
this(aRepositoryProperties, aCasStorageService, aImportExportService, aProjectService,
aApplicationEventPublisher);
<<<<<<<
=======
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
>>>>>>>
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
<<<<<<<
=======
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
>>>>>>>
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
<<<<<<<
@Transactional
public boolean existsCas(SourceDocument aDocument, String aUser) throws IOException
=======
public boolean existsCas(SourceDocument aDocument, String aUser)
throws IOException
>>>>>>>
public boolean existsCas(SourceDocument aDocument, String aUser) throws IOException
<<<<<<<
@Transactional
public boolean existsAnnotationCas(AnnotationDocument aAnnotationDocument) throws IOException
=======
public boolean existsAnnotationCas(AnnotationDocument aAnnotationDocument)
throws IOException
>>>>>>>
public boolean existsAnnotationCas(AnnotationDocument aAnnotationDocument) throws IOException
<<<<<<<
=======
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
>>>>>>>
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
<<<<<<<
=======
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
>>>>>>>
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
<<<<<<<
log.debug("Loading initial CAS for source document " + "[{}]({}) in project [{}]({})",
=======
log.debug("Loading initial CAS for source document [{}]({}) in project [{}]({})",
>>>>>>>
log.debug("Loading initial CAS for source document [{}]({}) in project [{}]({})",
<<<<<<<
return casStorageService.readOrCreateCas(aDocument, INITIAL_CAS_PSEUDO_USER, aUpgradeMode,
() -> {
// Normally, the initial CAS should be created on document import, but after
// adding this feature, the existing projects do not yet have initial CASes, so
// we create them here lazily
try {
return importExportService.importCasFromFile(
getSourceDocumentFile(aDocument), aDocument.getProject(),
aDocument.getFormat(), aFullProjectTypeSystem);
}
catch (UIMAException e) {
throw new IOException("Unable to create CAS: " + e.getMessage(), e);
}
}, aAccessMode);
}
=======
return casStorageService.readOrCreateCas(aDocument, INITIAL_CAS_PSEUDO_USER,
aUpgradeMode, () -> {
// Normally, the initial CAS should be created on document import, but after
// adding this feature, the existing projects do not yet have initial CASes, so
// we create them here lazily
try {
return importExportService.importCasFromFile(
getSourceDocumentFile(aDocument), aDocument.getProject(),
aDocument.getFormat(), aFullProjectTypeSystem);
}
catch (UIMAException e) {
throw new IOException("Unable to create CAS: " + e.getMessage(), e);
}
}, aAccessMode);
}
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
>>>>>>>
return casStorageService.readOrCreateCas(aDocument, INITIAL_CAS_PSEUDO_USER, aUpgradeMode,
() -> {
// Normally, the initial CAS should be created on document import, but after
// adding this feature, the existing projects do not yet have initial CASes, so
// we create them here lazily
try {
return importExportService.importCasFromFile(
getSourceDocumentFile(aDocument), aDocument.getProject(),
aDocument.getFormat(), aFullProjectTypeSystem);
}
catch (UIMAException e) {
throw new IOException("Unable to create CAS: " + e.getMessage(), e);
}
}, aAccessMode);
}
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
<<<<<<<
=======
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
>>>>>>>
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
<<<<<<<
=======
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
>>>>>>>
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
<<<<<<<
@Transactional
public CAS readAnnotationCas(AnnotationDocument aAnnotationDocument) throws IOException
=======
public CAS readAnnotationCas(AnnotationDocument aAnnotationDocument)
throws IOException
>>>>>>>
public CAS readAnnotationCas(AnnotationDocument aAnnotationDocument) throws IOException
<<<<<<<
=======
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
>>>>>>>
// NO TRANSACTION REQUIRED - This does not do any should not do a database access, so we do not
// need to be in a transaction here. Avoiding the transaction speeds up the call.
<<<<<<<
String query = String.join("\n", "SELECT COUNT(*) FROM AnnotationDocument",
"WHERE document = :document", " AND user = :user", " AND state = :state");
return entityManager.createQuery(query, Long.class).setParameter("document", aDocument)
.setParameter("user", aUser.getUsername())
.setParameter("state", AnnotationDocumentState.FINISHED).getSingleResult() > 0;
// try {
// AnnotationDocument annotationDocument = entityManager
// .createQuery(
// "FROM AnnotationDocument WHERE document = :document AND "
// + "user =:user", AnnotationDocument.class)
// .setParameter("document", aDocument)
// .setParameter("user", aUser.getUsername())
// .getSingleResult();
// if (annotationDocument.getState().equals(AnnotationDocumentState.FINISHED)) {
// return true;
// }
// else {
// return false;
// }
// }
// // User even didn't start annotating
// catch (NoResultException e) {
// return false;
// }
=======
return isAnnotationFinished(aDocument, aUser.getUsername());
}
@Override
@Transactional
public boolean isAnnotationFinished(SourceDocument aDocument, String aUsername)
{
String query = String.join("\n",
"SELECT COUNT(*) FROM AnnotationDocument",
"WHERE document = :document",
" AND user = :user",
" AND state = :state");
return entityManager.createQuery(query, Long.class)
.setParameter("document", aDocument)
.setParameter("user", aUsername)
.setParameter("state", AnnotationDocumentState.FINISHED)
.getSingleResult() > 0;
>>>>>>>
return isAnnotationFinished(aDocument, aUser.getUsername());
}
@Override
@Transactional
public boolean isAnnotationFinished(SourceDocument aDocument, String aUsername)
{
String query = String.join("\n", "SELECT COUNT(*) FROM AnnotationDocument",
"WHERE document = :document", " AND user = :user", " AND state = :state");
return entityManager.createQuery(query, Long.class) //
.setParameter("document", aDocument) //
.setParameter("user", aUsername) //
.setParameter("state", AnnotationDocumentState.FINISHED).getSingleResult() > 0; |
<<<<<<<
import static de.tudarmstadt.ukp.clarin.webanno.model.AnchoringMode.SINGLE_TOKEN;
import static de.tudarmstadt.ukp.clarin.webanno.model.OverlapMode.NO_OVERLAP;
=======
import static de.tudarmstadt.ukp.clarin.webanno.model.ValidationMode.NEVER;
>>>>>>>
import static de.tudarmstadt.ukp.clarin.webanno.model.AnchoringMode.SINGLE_TOKEN;
import static de.tudarmstadt.ukp.clarin.webanno.model.OverlapMode.NO_OVERLAP;
import static de.tudarmstadt.ukp.clarin.webanno.model.ValidationMode.NEVER;
<<<<<<<
aProject, true, SINGLE_TOKEN, NO_OVERLAP);
=======
aProject, true, AnchoringMode.SINGLE_TOKEN);
// Since the user cannot turn off validation for the token layer if there is any kind of
// problem with the validation functionality we are conservative here and disable validation
// from the start.
tokenLayer.setValidationMode(NEVER);
>>>>>>>
aProject, true, SINGLE_TOKEN, NO_OVERLAP);
// Since the user cannot turn off validation for the token layer if there is any kind of
// problem with the validation functionality we are conservative here and disable validation
// from the start.
tokenLayer.setValidationMode(NEVER); |
<<<<<<<
import de.tudarmstadt.ukp.clarin.webanno.export.model.ExportedProjectPermission;
=======
import de.tudarmstadt.ukp.clarin.webanno.api.event.ProjectStateChangedEvent;
>>>>>>>
import de.tudarmstadt.ukp.clarin.webanno.api.event.ProjectStateChangedEvent;
import de.tudarmstadt.ukp.clarin.webanno.export.model.ExportedProjectPermission; |
<<<<<<<
final String exMsg = String.format("An error occurred while analyzing '%s'.", d.getActualFilePath());
Logger.getLogger(Engine.class.getName()).log(Level.WARNING, exMsg);
Logger.getLogger(Engine.class.getName()).log(Level.FINE, "", ex);
=======
final String exMsg = String.format("An error occured while analyzing '%s'.", d.getActualFilePath());
LOGGER.log(Level.WARNING, exMsg);
LOGGER.log(Level.FINE, "", ex);
>>>>>>>
final String exMsg = String.format("An error occurred while analyzing '%s'.", d.getActualFilePath());
LOGGER.log(Level.WARNING, exMsg);
LOGGER.log(Level.FINE, "", ex); |
<<<<<<<
import org.owasp.dependencycheck.dependency.Evidence;
import org.owasp.dependencycheck.dependency.Identifier;
=======
import org.owasp.dependencycheck.dependency.Vulnerability;
>>>>>>>
import org.owasp.dependencycheck.dependency.Evidence;
import org.owasp.dependencycheck.dependency.Identifier;
import org.owasp.dependencycheck.dependency.Vulnerability;
<<<<<<<
assertTrue(size >= 1);
=======
assertThat(size, is(1));
>>>>>>>
assertTrue(size >= 1);
<<<<<<<
assertTrue(dependency.getFilePath().endsWith(resource));
assertTrue(dependency.getFileName().equals("Gemfile.lock"));
=======
>>>>>>>
assertTrue(dependency.getFilePath().endsWith(resource));
assertTrue(dependency.getFileName().equals("Gemfile.lock"));
<<<<<<<
/**
* Test Ruby dependencies and their paths.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testDependenciesPath() throws AnalysisException, DatabaseException {
final Engine engine = new Engine();
engine.scan(BaseTest.getResourceAsFile(this,
// "ruby/vulnerable/gems/chef-12.8.4/"));
"ruby/vulnerable/gems/rails-4.1.15/"));
// "java"));
engine.analyzeDependencies();
List<Dependency> dependencies = engine.getDependencies();
LOGGER.info(dependencies.size() + " dependencies found.");
Iterator<Dependency> dIterator = dependencies.iterator();
while(dIterator.hasNext()) {
Dependency dept = dIterator.next();
LOGGER.info("dept path: " + dept.getActualFilePath());
Set<Identifier> identifiers = dept.getIdentifiers();
Iterator<Identifier> idIterator = identifiers.iterator();
while(idIterator.hasNext()) {
Identifier id = idIterator.next();
LOGGER.info(" Identifier: " + id.getValue() + ", type=" + id.getType() + ", url=" + id.getUrl() + ", conf="+ id.getConfidence());
}
Set<Evidence> prodEv = dept.getProductEvidence().getEvidence();
Iterator<Evidence> it = prodEv.iterator();
while(it.hasNext()) {
Evidence e = it.next();
LOGGER.info(" prod: name=" + e.getName() + ", value=" + e.getValue() + ", source=" + e.getSource() + ", confidence=" + e.getConfidence());
}
Set<Evidence> versionEv = dept.getVersionEvidence().getEvidence();
Iterator<Evidence> vIt = versionEv.iterator();
while(vIt.hasNext()) {
Evidence e = vIt.next();
LOGGER.info(" version: name=" + e.getName() + ", value=" + e.getValue() + ", source=" + e.getSource() + ", confidence=" + e.getConfidence());
}
Set<Evidence> vendorEv = dept.getVendorEvidence().getEvidence();
Iterator<Evidence> vendorIt = vendorEv.iterator();
while(vendorIt.hasNext()) {
Evidence e = vendorIt.next();
LOGGER.info(" vendor: name=" + e.getName() + ", value=" + e.getValue() + ", source=" + e.getSource() + ", confidence=" + e.getConfidence());
}
}
}
=======
>>>>>>>
/**
* Test Ruby dependencies and their paths.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testDependenciesPath() throws AnalysisException, DatabaseException {
final Engine engine = new Engine();
engine.scan(BaseTest.getResourceAsFile(this,
// "ruby/vulnerable/gems/chef-12.8.4/"));
"ruby/vulnerable/gems/rails-4.1.15/"));
// "java"));
engine.analyzeDependencies();
List<Dependency> dependencies = engine.getDependencies();
LOGGER.info(dependencies.size() + " dependencies found.");
Iterator<Dependency> dIterator = dependencies.iterator();
while(dIterator.hasNext()) {
Dependency dept = dIterator.next();
LOGGER.info("dept path: " + dept.getActualFilePath());
Set<Identifier> identifiers = dept.getIdentifiers();
Iterator<Identifier> idIterator = identifiers.iterator();
while(idIterator.hasNext()) {
Identifier id = idIterator.next();
LOGGER.info(" Identifier: " + id.getValue() + ", type=" + id.getType() + ", url=" + id.getUrl() + ", conf="+ id.getConfidence());
}
Set<Evidence> prodEv = dept.getProductEvidence().getEvidence();
Iterator<Evidence> it = prodEv.iterator();
while(it.hasNext()) {
Evidence e = it.next();
LOGGER.info(" prod: name=" + e.getName() + ", value=" + e.getValue() + ", source=" + e.getSource() + ", confidence=" + e.getConfidence());
}
Set<Evidence> versionEv = dept.getVersionEvidence().getEvidence();
Iterator<Evidence> vIt = versionEv.iterator();
while(vIt.hasNext()) {
Evidence e = vIt.next();
LOGGER.info(" version: name=" + e.getName() + ", value=" + e.getValue() + ", source=" + e.getSource() + ", confidence=" + e.getConfidence());
}
Set<Evidence> vendorEv = dept.getVendorEvidence().getEvidence();
Iterator<Evidence> vendorIt = vendorEv.iterator();
while(vendorIt.hasNext()) {
Evidence e = vendorIt.next();
LOGGER.info(" vendor: name=" + e.getName() + ", value=" + e.getValue() + ", source=" + e.getSource() + ", confidence=" + e.getConfidence());
}
}
} |
<<<<<<<
=======
@Value("${server.ajp.secret-required:true}")
private String ajpSecretRequired;
@Value("${server.ajp.secret:}")
private String ajpSecret;
@Value("${server.ajp.address:127.0.0.1}")
private String ajpAddress;
@Bean
public SessionRegistry sessionRegistry()
{
return new SessionRegistryImpl();
}
>>>>>>>
@Value("${server.ajp.secret-required:true}")
private String ajpSecretRequired;
@Value("${server.ajp.secret:}")
private String ajpSecret;
@Value("${server.ajp.address:127.0.0.1}")
private String ajpAddress;
@Bean
public SessionRegistry sessionRegistry()
{
return new SessionRegistryImpl();
}
<<<<<<<
PluginManagerImpl pluginManager = new PluginManagerImpl(
SettingsUtil.getApplicationHome().toPath().resolve("plugins"));
Runtime.getRuntime().addShutdownHook(new Thread(() -> pluginManager.stopPlugins()));
return pluginManager;
}
// The WebAnno User model class picks this bean up by name!
@Bean
public PasswordEncoder passwordEncoder()
{
// Set up a DelegatingPasswordEncoder which decodes legacy passwords using the
// StandardPasswordEncoder but encodes passwords using the modern BCryptPasswordEncoder
String encoderForEncoding = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(encoderForEncoding, new BCryptPasswordEncoder());
DelegatingPasswordEncoder delegatingEncoder = new DelegatingPasswordEncoder(
encoderForEncoding, encoders);
// Decode legacy passwords without encoder ID using the StandardPasswordEncoder
delegatingEncoder.setDefaultPasswordEncoderForMatches(new StandardPasswordEncoder());
return delegatingEncoder;
}
@Bean
public TomcatServletWebServerFactory servletContainer()
{
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
=======
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
>>>>>>>
PluginManagerImpl pluginManager = new PluginManagerImpl(
SettingsUtil.getApplicationHome().toPath().resolve("plugins"));
Runtime.getRuntime().addShutdownHook(new Thread(() -> pluginManager.stopPlugins()));
return pluginManager;
}
// The WebAnno User model class picks this bean up by name!
@Bean
public PasswordEncoder passwordEncoder()
{
// Set up a DelegatingPasswordEncoder which decodes legacy passwords using the
// StandardPasswordEncoder but encodes passwords using the modern BCryptPasswordEncoder
String encoderForEncoding = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(encoderForEncoding, new BCryptPasswordEncoder());
DelegatingPasswordEncoder delegatingEncoder = new DelegatingPasswordEncoder(
encoderForEncoding, encoders);
// Decode legacy passwords without encoder ID using the StandardPasswordEncoder
delegatingEncoder.setDefaultPasswordEncoderForMatches(new StandardPasswordEncoder());
return delegatingEncoder;
}
@Bean
public TomcatServletWebServerFactory servletContainer()
{
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); |
<<<<<<<
if (aExLayer.getOverlapMode() == null) {
// This allows importing old projects which did not have the overlap mode yet
aLayer.setOverlapMode(aExLayer.isAllowStacking() ? ANY_OVERLAP : OVERLAP_ONLY);
}
else {
aLayer.setOverlapMode(aExLayer.getOverlapMode());
}
=======
aLayer.setValidationMode(aExLayer.getValidationMode() != null ? aExLayer.getValidationMode()
: ValidationMode.NEVER);
>>>>>>>
if (aExLayer.getOverlapMode() == null) {
// This allows importing old projects which did not have the overlap mode yet
aLayer.setOverlapMode(aExLayer.isAllowStacking() ? ANY_OVERLAP : OVERLAP_ONLY);
}
else {
aLayer.setOverlapMode(aExLayer.getOverlapMode());
}
aLayer.setValidationMode(aExLayer.getValidationMode() != null ? aExLayer.getValidationMode()
: ValidationMode.NEVER); |
<<<<<<<
// remove existing annotations of this type, after all it is an
// automation, no care
clearAnnotations(aCas, type);
=======
// remove existing annotations of this type, after all it is an automation, no care
clearAnnotations(aJcas, aFeature);
>>>>>>>
// remove existing annotations of this type, after all it is an automation, no care
clearAnnotations(aCas, aFeature);
<<<<<<<
newAnnotation = aCas.createAnnotation(type, begin, end);
=======
AnnotationFS newAnnotation = aJcas.getCas().createAnnotation(type, begin, end);
>>>>>>>
AnnotationFS newAnnotation = aCas.createAnnotation(type, begin, end);
<<<<<<<
newAnnotation = aCas.createAnnotation(type, begin, end);
=======
AnnotationFS newAnnotation = aJcas.getCas().createAnnotation(type, begin,
end);
>>>>>>>
AnnotationFS newAnnotation = aCas.createAnnotation(type, begin, end);
<<<<<<<
attachType = CasUtil.getType(aCas, attachTypeName);
attachFeature = attachType.getFeatureByBaseName(attachTypeName);
=======
Type attachType = CasUtil.getType(aJcas.getCas(), attachTypeName);
attachFeature = attachType
.getFeatureByBaseName(aFeature.getLayer().getAttachFeature().getName());
>>>>>>>
Type attachType = CasUtil.getType(aCas, attachTypeName);
attachFeature = attachType.getFeatureByBaseName(attachTypeName);
<<<<<<<
LOG.info(annotations.size() + " Predictions found to be written to the CAS");
CAS cas = null;
=======
LOG.info("[{}] predictions found to be written to the CAS", annotations.size());
JCas jCas = null;
>>>>>>>
LOG.info("[{}] predictions found to be written to the CAS", annotations.size());
CAS cas = null;
<<<<<<<
cas = aRepository.readAnnotationCas(annoDocument);
automate(cas, layerFeature, annotations);
}
catch (DataRetrievalFailureException e) {
automate(cas, layerFeature, annotations);
LOG.info("Predictions found are written to the CAS");
aCorrectionDocumentService.writeCorrectionCas(cas, document);
=======
jCas = aRepository.readAnnotationCas(annoDocument);
automate(jCas, layerFeature, annotations);
// We need to clear the timestamp since we read from the annotation CAS and write
// to the correction CAS - this makes the comparison between the time stamp
// stored in the CAS and the on-disk timestamp of the correction CAS invalid
CasMetadataUtils.clearCasMetadata(jCas);
aCorrectionDocumentService.writeCorrectionCas(jCas, document);
>>>>>>>
cas = aRepository.readAnnotationCas(annoDocument);
automate(cas, layerFeature, annotations);
// We need to clear the timestamp since we read from the annotation CAS and write
// to the correction CAS - this makes the comparison between the time stamp
// stored in the CAS and the on-disk timestamp of the correction CAS invalid
CasMetadataUtils.clearCasMetadata(cas);
aCorrectionDocumentService.writeCorrectionCas(cas, document);
<<<<<<<
annotationsToRemove.addAll(select(aCas, aType));
=======
Type type = CasUtil.getType(cas, aFeature.getLayer().getName());
annotationsToRemove.addAll(select(cas, type));
>>>>>>>
Type type = CasUtil.getType(aCas, aFeature.getLayer().getName());
annotationsToRemove.addAll(select(aCas, type));
<<<<<<<
aCas.removeFsFromIndexes(annotation);
=======
if (attachFeature != null) {
// Unattach the annotation to be removed
for (AnnotationFS attach : selectCovered(attachType, annotation)) {
FeatureStructure existing = attach.getFeatureValue(attachFeature);
if (annotation.equals(existing)) {
attach.setFeatureValue(attachFeature, null);
}
}
}
cas.removeFsFromIndexes(annotation);
>>>>>>>
if (attachFeature != null) {
// Unattach the annotation to be removed
for (AnnotationFS attach : selectCovered(attachType, annotation)) {
FeatureStructure existing = attach.getFeatureValue(attachFeature);
if (annotation.equals(existing)) {
attach.setFeatureValue(attachFeature, null);
}
}
}
aCas.removeFsFromIndexes(annotation); |
<<<<<<<
corefLayer.setOverlapMode(ANY_OVERLAP);
sut.addSpan(document, username, jcas, 0, 1);
=======
sut.addSpan(document, username, jcas.getCas(), 0, 1);
>>>>>>>
corefLayer.setOverlapMode(ANY_OVERLAP);
sut.addSpan(document, username, jcas.getCas(), 0, 1);
<<<<<<<
.isThrownBy(() -> sut.addSpan(document, username, jcas, 0, 1))
.withMessageContaining("no overlap or stacking");
corefLayer.setOverlapMode(OVERLAP_ONLY);
assertThatExceptionOfType(AnnotationException.class)
.isThrownBy(() -> sut.addSpan(document, username, jcas, 0, 1))
.withMessageContaining("stacking is not allowed");
// Adding another annotation at the same place DOES work
corefLayer.setOverlapMode(STACKING_ONLY);
assertThatCode(() -> sut.addSpan(document, username, jcas, 0, 1))
.doesNotThrowAnyException();
corefLayer.setOverlapMode(ANY_OVERLAP);
assertThatCode(() -> sut.addSpan(document, username, jcas, 0, 1))
.doesNotThrowAnyException();
=======
.isThrownBy(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.withMessageContaining("stacking is not enabled");
>>>>>>>
.isThrownBy(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.withMessageContaining("no overlap or stacking");
corefLayer.setOverlapMode(OVERLAP_ONLY);
assertThatExceptionOfType(AnnotationException.class)
.isThrownBy(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.withMessageContaining("stacking is not allowed");
// Adding another annotation at the same place DOES work
corefLayer.setOverlapMode(STACKING_ONLY);
assertThatCode(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.doesNotThrowAnyException();
corefLayer.setOverlapMode(ANY_OVERLAP);
assertThatCode(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.doesNotThrowAnyException();
<<<<<<<
corefLayer.setOverlapMode(ANY_OVERLAP);
sut.addSpan(document, username, jcas, 0, 4);
=======
sut.addSpan(document, username, jcas.getCas(), 0, 4);
>>>>>>>
corefLayer.setOverlapMode(ANY_OVERLAP);
sut.addSpan(document, username, jcas.getCas(), 0, 4);
<<<<<<<
.isThrownBy(() -> sut.addSpan(document, username, jcas, 0, 1))
.withMessageContaining("no overlap or stacking");
corefLayer.setOverlapMode(OVERLAP_ONLY);
assertThatExceptionOfType(AnnotationException.class)
.isThrownBy(() -> sut.addSpan(document, username, jcas, 0, 1))
.withMessageContaining("stacking is not allowed");
// Adding another annotation at the same place DOES work
// Here we annotate "T" but it should be expanded to "This"
corefLayer.setOverlapMode(STACKING_ONLY);
assertThatCode(() -> sut.addSpan(document, username, jcas, 0, 1))
.doesNotThrowAnyException();
corefLayer.setOverlapMode(ANY_OVERLAP);
assertThatCode(() -> sut.addSpan(document, username, jcas, 0, 1))
.doesNotThrowAnyException(); }
=======
.isThrownBy(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.withMessageContaining("stacking is not enabled");
}
>>>>>>>
.isThrownBy(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.withMessageContaining("no overlap or stacking");
corefLayer.setOverlapMode(OVERLAP_ONLY);
assertThatExceptionOfType(AnnotationException.class)
.isThrownBy(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.withMessageContaining("stacking is not allowed");
// Adding another annotation at the same place DOES work
// Here we annotate "T" but it should be expanded to "This"
corefLayer.setOverlapMode(STACKING_ONLY);
assertThatCode(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.doesNotThrowAnyException();
corefLayer.setOverlapMode(ANY_OVERLAP);
assertThatCode(() -> sut.addSpan(document, username, jcas.getCas(), 0, 1))
.doesNotThrowAnyException();
} |
<<<<<<<
for (Feature feature : aType.getFeatures()) {
if (feature.getName().equals(CAS.FEATURE_FULL_NAME_SOFA)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_BEGIN)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_END)
=======
List<Feature> features = aType.getFeatures();
Collections.sort(features, (a, b) ->
StringUtils.compare(a.getShortName(), b.getShortName()));
for (Feature feature : features) {
if (feature.toString().equals("uima.cas.AnnotationBase:sofa")
|| feature.toString().equals("uima.tcas.Annotation:begin")
|| feature.toString().equals("uima.tcas.Annotation:end")
>>>>>>>
List<Feature> features = aType.getFeatures();
Collections.sort(features, (a, b) ->
StringUtils.compare(a.getShortName(), b.getShortName()));
for (Feature feature : features) {
if (feature.getName().equals(CAS.FEATURE_FULL_NAME_SOFA)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_BEGIN)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_END)
<<<<<<<
for (Feature feature : aType.getFeatures()) {
if (feature.getName().equals(CAS.FEATURE_FULL_NAME_SOFA)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_BEGIN)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_END)
=======
List<Feature> features = aType.getFeatures();
Collections.sort(features, (a, b) ->
StringUtils.compare(a.getShortName(), b.getShortName()));
for (Feature feature : features) {
if (feature.toString().equals("uima.cas.AnnotationBase:sofa")
|| feature.toString().equals("uima.tcas.Annotation:begin")
|| feature.toString().equals("uima.tcas.Annotation:end")
>>>>>>>
List<Feature> features = aType.getFeatures();
Collections.sort(features, (a, b) ->
StringUtils.compare(a.getShortName(), b.getShortName()));
for (Feature feature : features) {
if (feature.getName().equals(CAS.FEATURE_FULL_NAME_SOFA)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_BEGIN)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_END)
<<<<<<<
for (Feature feature : type.getFeatures()) {
if (feature.getName().equals(CAS.FEATURE_FULL_NAME_SOFA)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_BEGIN)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_END)
=======
List<Feature> features = type.getFeatures();
Collections.sort(features, (a, b) ->
StringUtils.compare(a.getShortName(), b.getShortName()));
for (Feature feature : features) {
if (feature.toString().equals("uima.cas.AnnotationBase:sofa")
|| feature.toString().equals("uima.tcas.Annotation:begin")
|| feature.toString().equals("uima.tcas.Annotation:end")
>>>>>>>
List<Feature> features = type.getFeatures();
Collections.sort(features, (a, b) ->
StringUtils.compare(a.getShortName(), b.getShortName()));
for (Feature feature : features) {
if (feature.getName().equals(CAS.FEATURE_FULL_NAME_SOFA)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_BEGIN)
|| feature.getName().equals(CAS.FEATURE_FULL_NAME_END) |
<<<<<<<
public static double getTileValue(
final int x,
final int y,
final int b,
final int tileSize ) {
// just use an arbitrary 'r'
return getTileValue(
x,
y,
b,
3,
tileSize);
}
public static void fillTestRasters(
final WritableRaster raster1,
final WritableRaster raster2,
final int tileSize ) {
// for raster1 do the following:
// set every even row in bands 0 and 1
// set every value incorrectly in band 2
// set no values in band 3 and set every value in 4
// for raster2 do the following:
// set no value in band 0 and 4
// set every odd row in band 1
// set every value in bands 2 and 3
// for band 5, set the lower 2x2 samples for raster 1 and the rest for
// raster 2
// for band 6, set the upper quadrant samples for raster 1 and the rest
// for raster 2
// for band 7, set the lower 2x2 samples to the wrong value for raster 1
// and the expected value for raster 2 and set everything but the upper
// quadrant for raster 2
for (int x = 0; x < tileSize; x++) {
for (int y = 0; y < tileSize; y++) {
// just use x and y to arbitrarily end up with some wrong value
// that can be ingested
final double wrongValue = (getTileValue(
y,
x,
y,
tileSize) * 3) + 1;
if ((x < 2) && (y < 2)) {
raster1.setSample(
x,
y,
5,
getTileValue(
x,
y,
5,
tileSize));
raster1.setSample(
x,
y,
7,
wrongValue);
raster2.setSample(
x,
y,
7,
getTileValue(
x,
y,
7,
tileSize));
}
else {
raster2.setSample(
x,
y,
5,
getTileValue(
x,
y,
5,
tileSize));
}
if ((x > ((tileSize * 3) / 4)) && (y > ((tileSize * 3) / 4))) {
raster1.setSample(
x,
y,
6,
getTileValue(
x,
y,
6,
tileSize));
}
else {
raster2.setSample(
x,
y,
6,
getTileValue(
x,
y,
6,
tileSize));
raster2.setSample(
x,
y,
7,
getTileValue(
x,
y,
7,
tileSize));
}
if ((y % 2) == 0) {
raster1.setSample(
x,
y,
0,
getTileValue(
x,
y,
0,
tileSize));
raster1.setSample(
x,
y,
1,
getTileValue(
x,
y,
1,
tileSize));
}
raster1.setSample(
x,
y,
2,
wrongValue);
raster1.setSample(
x,
y,
4,
getTileValue(
x,
y,
4,
tileSize));
if ((y % 2) != 0) {
raster2.setSample(
x,
y,
1,
getTileValue(
x,
y,
1,
tileSize));
}
raster2.setSample(
x,
y,
2,
TestUtils.getTileValue(
x,
y,
2,
tileSize));
raster2.setSample(
x,
y,
3,
getTileValue(
x,
y,
3,
tileSize));
}
}
}
private static Random rng = null;
public static double getTileValue(
final int x,
final int y,
final int b,
final int r,
final int tileSize ) {
// make this some random but repeatable and vary the scale
final double resultOfFunction = randomFunction(
x,
y,
b,
r,
tileSize);
// this is meant to just vary the scale
if ((r % 2) == 0) {
return resultOfFunction;
}
else {
if (rng == null) {
rng = new Random(
(long) resultOfFunction);
}
else {
rng.setSeed((long) resultOfFunction);
}
return rng.nextDouble() * resultOfFunction;
}
}
private static double randomFunction(
final int x,
final int y,
final int b,
final int r,
final int tileSize ) {
return (((x + (y * tileSize)) * .1) / (b + 1)) + r;
}
=======
@Deprecated
public static void assert200(
String msg,
int responseCode ) {
Assert.assertEquals(
msg,
200,
responseCode);
}
@Deprecated
public static void assert400(
String msg,
int responseCode ) {
Assert.assertEquals(
msg,
400,
responseCode);
}
@Deprecated
public static void assert404(
String msg,
int responseCode ) {
Assert.assertEquals(
msg,
404,
responseCode);
}
public static void assertStatusCode(
String msg,
int expectedCode,
Response response ) {
String assertionMsg = msg + String.format(
": A %s response code should be received",
expectedCode);
Assert.assertEquals(
assertionMsg,
expectedCode,
response.getStatus());
}
// Overload method with option to automatically generate assertion message.
public static void assertStatusCode(
int expectedCode,
Response response ) {
assertStatusCode(
"REST call",
expectedCode,
response);
}
>>>>>>>
public static double getTileValue(
final int x,
final int y,
final int b,
final int tileSize ) {
// just use an arbitrary 'r'
return getTileValue(
x,
y,
b,
3,
tileSize);
}
public static void fillTestRasters(
final WritableRaster raster1,
final WritableRaster raster2,
final int tileSize ) {
// for raster1 do the following:
// set every even row in bands 0 and 1
// set every value incorrectly in band 2
// set no values in band 3 and set every value in 4
// for raster2 do the following:
// set no value in band 0 and 4
// set every odd row in band 1
// set every value in bands 2 and 3
// for band 5, set the lower 2x2 samples for raster 1 and the rest for
// raster 2
// for band 6, set the upper quadrant samples for raster 1 and the rest
// for raster 2
// for band 7, set the lower 2x2 samples to the wrong value for raster 1
// and the expected value for raster 2 and set everything but the upper
// quadrant for raster 2
for (int x = 0; x < tileSize; x++) {
for (int y = 0; y < tileSize; y++) {
// just use x and y to arbitrarily end up with some wrong value
// that can be ingested
final double wrongValue = (getTileValue(
y,
x,
y,
tileSize) * 3) + 1;
if ((x < 2) && (y < 2)) {
raster1.setSample(
x,
y,
5,
getTileValue(
x,
y,
5,
tileSize));
raster1.setSample(
x,
y,
7,
wrongValue);
raster2.setSample(
x,
y,
7,
getTileValue(
x,
y,
7,
tileSize));
}
else {
raster2.setSample(
x,
y,
5,
getTileValue(
x,
y,
5,
tileSize));
}
if ((x > ((tileSize * 3) / 4)) && (y > ((tileSize * 3) / 4))) {
raster1.setSample(
x,
y,
6,
getTileValue(
x,
y,
6,
tileSize));
}
else {
raster2.setSample(
x,
y,
6,
getTileValue(
x,
y,
6,
tileSize));
raster2.setSample(
x,
y,
7,
getTileValue(
x,
y,
7,
tileSize));
}
if ((y % 2) == 0) {
raster1.setSample(
x,
y,
0,
getTileValue(
x,
y,
0,
tileSize));
raster1.setSample(
x,
y,
1,
getTileValue(
x,
y,
1,
tileSize));
}
raster1.setSample(
x,
y,
2,
wrongValue);
raster1.setSample(
x,
y,
4,
getTileValue(
x,
y,
4,
tileSize));
if ((y % 2) != 0) {
raster2.setSample(
x,
y,
1,
getTileValue(
x,
y,
1,
tileSize));
}
raster2.setSample(
x,
y,
2,
TestUtils.getTileValue(
x,
y,
2,
tileSize));
raster2.setSample(
x,
y,
3,
getTileValue(
x,
y,
3,
tileSize));
}
}
}
private static Random rng = null;
public static double getTileValue(
final int x,
final int y,
final int b,
final int r,
final int tileSize ) {
// make this some random but repeatable and vary the scale
final double resultOfFunction = randomFunction(
x,
y,
b,
r,
tileSize);
// this is meant to just vary the scale
if ((r % 2) == 0) {
return resultOfFunction;
}
else {
if (rng == null) {
rng = new Random(
(long) resultOfFunction);
}
else {
rng.setSeed((long) resultOfFunction);
}
return rng.nextDouble() * resultOfFunction;
}
}
private static double randomFunction(
final int x,
final int y,
final int b,
final int r,
final int tileSize ) {
return (((x + (y * tileSize)) * .1) / (b + 1)) + r;
}
@Deprecated
public static void assert200(
String msg,
int responseCode ) {
Assert.assertEquals(
msg,
200,
responseCode);
}
@Deprecated
public static void assert400(
String msg,
int responseCode ) {
Assert.assertEquals(
msg,
400,
responseCode);
}
@Deprecated
public static void assert404(
String msg,
int responseCode ) {
Assert.assertEquals(
msg,
404,
responseCode);
}
public static void assertStatusCode(
String msg,
int expectedCode,
Response response ) {
String assertionMsg = msg + String.format(
": A %s response code should be received",
expectedCode);
Assert.assertEquals(
assertionMsg,
expectedCode,
response.getStatus());
}
// Overload method with option to automatically generate assertion message.
public static void assertStatusCode(
int expectedCode,
Response response ) {
assertStatusCode(
"REST call",
expectedCode,
response);
} |
<<<<<<<
=======
public static ByteArrayId decomposeFromId(
final ByteArrayId id ) {
final int idLength = id.getBytes().length - STATS_ID.getBytes().length;
final byte[] idBytes = new byte[idLength];
System.arraycopy(
id.getBytes(),
STATS_ID.getBytes().length,
idBytes,
0,
idLength);
return new ByteArrayId(
idBytes);
}
public ByteArrayId getIndexId() {
return indexId;
}
>>>>>>>
public static ByteArrayId decomposeFromId(
final ByteArrayId id ) {
final int idLength = id.getBytes().length - STATS_ID.getBytes().length;
final byte[] idBytes = new byte[idLength];
System.arraycopy(
id.getBytes(),
STATS_ID.getBytes().length,
idBytes,
0,
idLength);
return new ByteArrayId(
idBytes);
}
<<<<<<<
final DataStoreEntryInfo entryInfo,
final T entry ) {
for (final IndexMetaData imd : this.metaData) {
imd.insertionIdsAdded(entryInfo.getRowIds());
=======
final DataStoreEntryInfo entryInfo,
final T entry ) {
for (final IndexMetaData imd : this.metaData) {
imd.update(entryInfo.getInsertionIds());
>>>>>>>
final DataStoreEntryInfo entryInfo,
final T entry ) {
for (final IndexMetaData imd : this.metaData) {
imd.insertionIdsAdded(entryInfo.getRowIds()); |
<<<<<<<
import mil.nga.giat.geowave.core.cli.operations.config.options.ConfigOptions;
import mil.nga.giat.geowave.core.store.cli.remote.options.StoreLoader;
import mil.nga.giat.geowave.datastore.accumulo.AccumuloStoreFactoryFamily;
import mil.nga.giat.geowave.datastore.accumulo.cli.config.AccumuloOptions;
import mil.nga.giat.geowave.datastore.accumulo.cli.config.AccumuloRequiredOptions;
import mil.nga.giat.geowave.datastore.accumulo.operations.AccumuloOperations;
import mil.nga.giat.geowave.datastore.hbase.HBaseStoreFactoryFamily;
=======
import mil.nga.giat.geowave.core.store.operations.remote.options.StoreLoader;
import mil.nga.giat.geowave.datastore.accumulo.AccumuloDataStore;
import mil.nga.giat.geowave.datastore.accumulo.AccumuloOperations;
import mil.nga.giat.geowave.datastore.accumulo.BasicAccumuloOperations;
import mil.nga.giat.geowave.datastore.accumulo.operations.config.AccumuloRequiredOptions;
import mil.nga.giat.geowave.datastore.hbase.HBaseDataStore;
>>>>>>>
import mil.nga.giat.geowave.core.store.cli.remote.options.StoreLoader;
import mil.nga.giat.geowave.datastore.accumulo.AccumuloStoreFactoryFamily;
import mil.nga.giat.geowave.datastore.accumulo.cli.config.AccumuloOptions;
import mil.nga.giat.geowave.datastore.accumulo.cli.config.AccumuloRequiredOptions;
import mil.nga.giat.geowave.datastore.accumulo.operations.AccumuloOperations;
import mil.nga.giat.geowave.datastore.hbase.HBaseStoreFactoryFamily;
<<<<<<<
private static Logger LOGGER = Logger.getLogger(
MinimalFullTable.class);
=======
private static Logger LOGGER = LoggerFactory.getLogger(MinimalFullTable.class);
>>>>>>>
private static Logger LOGGER = LoggerFactory.getLogger(MinimalFullTable.class);
<<<<<<<
// Config file
final File configFile = (File) params.getContext().get(
ConfigOptions.PROPERTIES_FILE_CONTEXT);
=======
>>>>>>>
<<<<<<<
if (!storeOptions.loadFromConfig(
configFile)) {
=======
if (!storeOptions.loadFromConfig(getGeoWaveConfigFile(params))) {
>>>>>>>
if (!storeOptions.loadFromConfig(getGeoWaveConfigFile(params))) { |
<<<<<<<
return new QueryRanges(
TieredSFCIndexStrategy.getQueryRanges(
binnedQueries,
sfc,
maxRangeDecomposition,
tier));
=======
return BinnedSFCUtils.getQueryRanges(
binnedQueries,
sfc,
maxRangeDecomposition,
tier);
>>>>>>>
return new QueryRanges(
BinnedSFCUtils.getQueryRanges(
binnedQueries,
sfc,
maxRangeDecomposition,
tier));
<<<<<<<
final ByteArrayId partitionKey,
final ByteArrayId sortKey ) {
final List<ByteArrayId> insertionIds = new SinglePartitionInsertionIds(
partitionKey,
sortKey).getCompositeInsertionIds();
if (insertionIds.isEmpty()) {
LOGGER.warn("Unexpected empty insertion ID in getRangeForId()");
return null;
}
final byte[] rowId = insertionIds.get(
0).getBytes();
return TieredSFCIndexStrategy.getRangeForId(
=======
final ByteArrayId insertionId ) {
final byte[] rowId = insertionId.getBytes();
return BinnedSFCUtils.getRangeForId(
>>>>>>>
final ByteArrayId partitionKey,
final ByteArrayId sortKey ) {
final List<ByteArrayId> insertionIds = new SinglePartitionInsertionIds(
partitionKey,
sortKey).getCompositeInsertionIds();
if (insertionIds.isEmpty()) {
LOGGER.warn("Unexpected empty insertion ID in getRangeForId()");
return null;
}
final byte[] rowId = insertionIds.get(
0).getBytes();
return BinnedSFCUtils.getRangeForId( |
<<<<<<<
import mil.nga.giat.geowave.datastore.accumulo.Writer;
import mil.nga.giat.geowave.datastore.accumulo.encoding.AccumuloDataSet;
=======
>>>>>>>
import mil.nga.giat.geowave.datastore.accumulo.encoding.AccumuloDataSet;
<<<<<<<
import mil.nga.giat.geowave.datastore.accumulo.encoding.AccumuloUnreadDataSingleRow;
import mil.nga.giat.geowave.datastore.accumulo.metadata.AbstractAccumuloPersistence;
=======
>>>>>>>
import mil.nga.giat.geowave.datastore.accumulo.encoding.AccumuloUnreadDataSingleRow;
import mil.nga.giat.geowave.datastore.accumulo.metadata.AbstractAccumuloPersistence;
<<<<<<<
final boolean wholeRowEncoding,
final AccumuloRowId rowId,
=======
final boolean wholeRowEncoding,
final GeowaveRowId rowId,
>>>>>>>
final boolean wholeRowEncoding,
final GeowaveRowId rowId,
<<<<<<<
final boolean wholeRowEncoding,
final AccumuloRowId rowId,
=======
final boolean wholeRowEncoding,
final GeowaveRowId rowId,
>>>>>>>
final boolean wholeRowEncoding,
final GeowaveRowId rowId,
<<<<<<<
final boolean wholeRowEncoding,
final AccumuloRowId rowId,
=======
final boolean wholeRowEncoding,
final GeowaveRowId rowId,
>>>>>>>
final boolean wholeRowEncoding,
final GeowaveRowId rowId, |
<<<<<<<
import org.apache.accumulo.core.client.impl.TabletLocator;
import org.apache.accumulo.core.client.impl.Tables;
=======
import org.apache.accumulo.core.client.security.tokens.NullToken;
>>>>>>>
import org.apache.accumulo.core.client.impl.TabletLocator;
import org.apache.accumulo.core.client.impl.Tables;
import org.apache.accumulo.core.client.security.tokens.NullToken;
<<<<<<<
public static Range toAccumuloRange(
final GeoWaveRowRange range,
final int partitionKeyLength ) {
if ((range.getPartitionKey() == null) || (range.getPartitionKey().length == 0)) {
return new Range(
(range.getStartSortKey() == null) ? null : new Text(
range.getStartSortKey()),
range.isStartSortKeyInclusive(),
(range.getEndSortKey() == null) ? null : new Text(
range.getEndSortKey()),
range.isEndSortKeyInclusive());
}
else {
return new Range(
(range.getStartSortKey() == null) ? null : new Text(
ArrayUtils.addAll(
range.getPartitionKey(),
range.getStartSortKey())),
range.isStartSortKeyInclusive(),
(range.getEndSortKey() == null) ? new Text(
new ByteArrayId(
range.getPartitionKey()).getNextPrefix()) : new Text(
ArrayUtils.addAll(
range.getPartitionKey(),
range.getEndSortKey())),
(range.getEndSortKey() != null) && range.isEndSortKeyInclusive());
=======
/**
* Returns data structure to be filled by binnedRanges Extracted out to
* facilitate testing
*/
public Map<String, Map<KeyExtent, List<Range>>> getBinnedRangesStructure() {
final Map<String, Map<KeyExtent, List<Range>>> tserverBinnedRanges = new HashMap<String, Map<KeyExtent, List<Range>>>();
return tserverBinnedRanges;
}
/**
* Returns host name cache data structure Extracted out to facilitate
* testing
*/
public HashMap<String, String> getHostNameCache() {
final HashMap<String, String> hostNameCache = new HashMap<String, String>();
return hostNameCache;
}
public static GeoWaveRowRange wrapRange(
final Range range ) {
return new AccumuloRowRange(
range);
}
public static Range unwrapRange(
final GeoWaveRowRange range ) {
if (range instanceof AccumuloRowRange) {
return ((AccumuloRowRange) range).getRange();
>>>>>>>
public static Range toAccumuloRange(
final GeoWaveRowRange range,
final int partitionKeyLength ) {
if ((range.getPartitionKey() == null) || (range.getPartitionKey().length == 0)) {
return new Range(
(range.getStartSortKey() == null) ? null : new Text(
range.getStartSortKey()),
range.isStartSortKeyInclusive(),
(range.getEndSortKey() == null) ? null : new Text(
range.getEndSortKey()),
range.isEndSortKeyInclusive());
}
else {
return new Range(
(range.getStartSortKey() == null) ? null : new Text(
ArrayUtils.addAll(
range.getPartitionKey(),
range.getStartSortKey())),
range.isStartSortKeyInclusive(),
(range.getEndSortKey() == null) ? new Text(
new ByteArrayId(
range.getPartitionKey()).getNextPrefix()) : new Text(
ArrayUtils.addAll(
range.getPartitionKey(),
range.getEndSortKey())),
(range.getEndSortKey() != null) && range.isEndSortKeyInclusive()); |
<<<<<<<
import mil.nga.giat.geowave.core.store.CloseableIteratorWrapper;
=======
import mil.nga.giat.geowave.core.store.DataStoreOperations;
>>>>>>>
<<<<<<<
import mil.nga.giat.geowave.core.store.operations.DataStoreOperations;
import mil.nga.giat.geowave.core.store.operations.Deleter;
import mil.nga.giat.geowave.core.store.operations.Writer;
=======
import mil.nga.giat.geowave.core.store.query.DistributableQuery;
>>>>>>>
import mil.nga.giat.geowave.core.store.operations.DataStoreOperations;
import mil.nga.giat.geowave.core.store.operations.Deleter;
import mil.nga.giat.geowave.core.store.operations.Writer;
import mil.nga.giat.geowave.core.store.query.DistributableQuery; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.