before stringlengths 12 3.21M | after stringlengths 41 3.21M | repo stringlengths 1 56 | type stringclasses 1
value | __index_level_0__ int64 0 442k |
|---|---|---|---|---|
private static void runBenchmark(final String[] args, final String packageName, final String applicationName, RWLogger outLogger) throws ParseException, IllegalArgumentException, IOException, InterruptedException, ExecutionException, TimeoutException, HelpException, ClassNotFoundException, InvocationTargetException, InstantiationException, NoSuchMethodException, IllegalAccessException {
final String version = io.sbk.api.impl.SbkYal.class.getPackage().getImplementationVersion();
final String appName = StringUtils.isNotEmpty(applicationName) ? applicationName : SbkYal.NAME;
Printer.log.info(IOUtils.toString(io.sbk.api.impl.SbkYal.class.getClassLoader().getResourceAsStream(BANNER_FILE)));
Printer.log.info(SbkYal.DESC);
Printer.log.info(SbkYal.NAME.toUpperCase() + " Version: " + Objects.requireNonNullElse(version, ""));
Printer.log.info("Arguments List: " + Arrays.toString(args));
Printer.log.info("Java Runtime Version: " + System.getProperty("java.runtime.version"));
final ObjectMapper mapper = new ObjectMapper(new JavaPropsFactory()).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
yalConfig = mapper.readValue(io.sbk.api.impl.SbkYal.class.getClassLoader().getResourceAsStream(CONFIG_FILE), YalConfig.class);
params = new SbkYalParameters(appName, SbkYal.DESC, yalConfig);
final boolean isPrintOption = SbkUtils.hasArg(args, YalConfig.PRINT_OPTION_ARG);
String[] nextArgs = SbkUtils.removeOptionArgs(args, new String[] { YalConfig.PRINT_OPTION_ARG });
nextArgs = SbkUtils.removeOptionArgsAndValues(nextArgs, new String[] { YalConfig.FILE_OPTION_ARG });
try {
params.parseArgs(args);
yalFileName = params.getFileName();
} catch (HelpException ex) {
params.printHelp();
throw ex;
} catch (ParseException | IllegalArgumentException ignored) {
Printer.log.warn("SBK-YAL: Overriding options are supplied!");
if (SbkUtils.hasHelp(args)) {
params.printHelp();
throw new HelpException(params.getHelpText());
}
final String fileName = SbkUtils.getArgValue(args, YalConfig.FILE_OPTION_ARG);
yalFileName = StringUtils.isNotEmpty(fileName) ? fileName : yalConfig.yamlFileName;
}
try {
yalArgs = YmlMap.getYmlArgs(yalFileName, SbkYmlMap.class);
} catch (FileNotFoundException ex) {
Printer.log.error(ex.toString());
if (isPrintOption) {
Sbk.run(new String[] { Config.HELP_OPTION_ARG }, packageName, applicationName, outLogger);
throw new HelpException(ex.toString());
}
params.printHelp();
throw new HelpException(ex.toString());
}
final String[] mergeArgs = SbkUtils.mergeArgs(yalArgs, nextArgs);
String[] sbkArgs = mergeArgs;
if (isPrintOption) {
sbkArgs = Arrays.copyOf(mergeArgs, mergeArgs.length + 1);
sbkArgs[mergeArgs.length] = Config.HELP_OPTION_ARG;
}
runBenchmark(sbkArgs, packageName, applicationName, outLogger);
} | private static void runBenchmark(final String[] args, final String packageName, final String applicationName, RWLogger outLogger) throws ParseException, IllegalArgumentException, IOException, InterruptedException, ExecutionException, TimeoutException, HelpException, ClassNotFoundException, InvocationTargetException, InstantiationException, NoSuchMethodException, IllegalAccessException {
final String version = io.sbk.api.impl.SbkYal.class.getPackage().getImplementationVersion();
final String appName = StringUtils.isNotEmpty(applicationName) ? applicationName : SbkYal.NAME;
Printer.log.info(IOUtils.toString(io.sbk.api.impl.SbkYal.class.getClassLoader().getResourceAsStream(BANNER_FILE)));
Printer.log.info(SbkYal.DESC);
Printer.log.info(SbkYal.NAME.toUpperCase() + " Version: " + Objects.requireNonNullElse(version, ""));
Printer.log.info("Arguments List: " + Arrays.toString(args));
Printer.log.info("Java Runtime Version: " + System.getProperty("java.runtime.version"));
final ObjectMapper mapper = new ObjectMapper(new JavaPropsFactory()).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
yalConfig = mapper.readValue(io.sbk.api.impl.SbkYal.class.getClassLoader().getResourceAsStream(CONFIG_FILE), YalConfig.class);
params = new SbkYalParameters(appName, SbkYal.DESC, yalConfig);
final boolean isPrintOption = SbkUtils.hasArg(args, YalConfig.PRINT_OPTION_ARG);
String[] nextArgs = SbkUtils.removeOptionArgs(args, new String[] { YalConfig.PRINT_OPTION_ARG });
nextArgs = SbkUtils.removeOptionArgsAndValues(nextArgs, new String[] { YalConfig.FILE_OPTION_ARG });
try {
params.parseArgs(args);
yalFileName = params.getFileName();
} catch (HelpException ex) {
params.printHelp();
throw ex;
} catch (ParseException | IllegalArgumentException ignored) {
Printer.log.warn("SBK-YAL: Overriding options are supplied!");
if (SbkUtils.hasHelp(args)) {
params.printHelp();
throw new HelpException(params.getHelpText());
}
final String fileName = SbkUtils.getArgValue(args, YalConfig.FILE_OPTION_ARG);
yalFileName = StringUtils.isNotEmpty(fileName) ? fileName : yalConfig.yamlFileName;
}
try {
yalArgs = YmlMap.getYmlArgs(yalFileName, SbkYmlMap.class);
} catch (FileNotFoundException ex) {
Printer.log.error(ex.toString());
if (isPrintOption) {
Sbk.run(new String[] { Config.HELP_OPTION_ARG }, packageName, applicationName, outLogger);
throw new HelpException(ex.toString());
}
params.printHelp();
throw new HelpException(ex.toString());
}
final String[] mergeArgs = SbkUtils.mergeArgs(yalArgs, nextArgs);
String[] sbkArgs = mergeArgs;
if (isPrintOption) {
sbkArgs = Arrays.copyOf(mergeArgs, mergeArgs.length + 1);
sbkArgs[mergeArgs.length] = Config.HELP_OPTION_ARG;
}
<DeepExtract>
runBenchmark(sbkArgs, packageName, applicationName, outLogger);
</DeepExtract>
} | SBK | positive | 3,510 |
@Override
public void caseInterfaceInvokeExpr(InterfaceInvokeExpr v) {
SootMethod method = v.getMethod();
SootMethodRef methodRef = v.getMethodRef();
if (methodRef.getSignature().equals("<android.telephony.SmsMessage: " + "android.telephony.SmsMessage createFromPdu(byte[])>")) {
ExpressionSet op1 = resolveValue(v.getArg(0), _in);
if (op1 != null) {
_data = ExpressionSet.transform(op1, e -> {
if (e.isVariable()) {
return new VariableExpression(new MethodCallVariable(v, e.getVariable()));
} else {
return new VariableExpression(new MethodCallVariable(v));
}
});
return;
}
} else if (methodRef.getSignature().startsWith("<android.os.Bundle: java.lang.Object get(java.lang.String")) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet base = resolveValue(instanceExpr.getBase(), _in);
ExpressionSet op1 = resolveValue(instanceExpr.getArg(0), _in);
if (base != null && op1 != null) {
List<ExpressionSet> results = new ArrayList<ExpressionSet>();
for (Expression baseExpr : base.getExpressions()) {
if (!baseExpr.isVariable()) {
results.add(new ExpressionSet(new VariableExpression(new KeyValueAccessVariable(null, null, KeyValueAccessVariable.DatabaseType.BUNDLE, v.getMethod().getReturnType()))));
continue;
}
ExpressionSet partialResult = ExpressionSet.transform(op1, e -> {
if (e.isVariable()) {
return new VariableExpression(new KeyValueAccessVariable(baseExpr.getVariable(), e.getVariable(), KeyValueAccessVariable.DatabaseType.BUNDLE, v.getMethod().getReturnType()));
} else {
return new VariableExpression(new KeyValueAccessVariable(baseExpr.getVariable(), null, KeyValueAccessVariable.DatabaseType.BUNDLE, v.getMethod().getReturnType()));
}
});
results.add(partialResult);
}
_data = ExpressionSet.merge(results);
return;
}
} else if (methodRef.getSignature().startsWith("<android.content.Context: java.lang.String getString(int") || methodRef.getSignature().equals("<android.content.Context: java.lang.CharSequence getText(int)>")) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet op1 = resolveValue(instanceExpr.getArg(0), _in);
if (op1 != null) {
_data = ExpressionSet.transform(op1, e -> {
Variable opVariable = e.isVariable() ? e.getVariable() : null;
return new VariableExpression(new KeyValueAccessVariable(new PlaceholderVariable("Context", RefType.v("android.content.Context")), opVariable, KeyValueAccessVariable.DatabaseType.STRING_TABLE, RefType.v("java.lang.String")));
});
return;
}
} else if (methodRef.getSignature().startsWith("<java.lang.StringBuilder: java.lang.StringBuilder append(")) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet op1 = resolveValue(instanceExpr.getBase(), _in);
ExpressionSet op2 = resolveValue(instanceExpr.getArg(0), _in);
if (op1 != null && op2 != null) {
_data = ExpressionSet.combine(Expression.Operator.APPEND, op1, op2);
return;
}
} else if (methodRef.getSignature().endsWith("java.lang.String toString()>") || methodRef.getSignature().endsWith("char[] toCharArray()>")) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
_data = resolveValue(instanceExpr.getBase(), _in);
return;
} else if (methodRef.getSignature().equals("<java.lang.String: boolean equals(java.lang.Object)>") || methodRef.getSignature().equals("<java.lang.String: boolean contains(java.lang.CharSequence)>")) {
String returnString = "Return<" + methodRef.declaringClass().getShortName() + "." + methodRef.name() + "(){" + v.hashCode() + "}>";
VariableExpression returnExpr = new VariableExpression(new PlaceholderVariable(returnString, BooleanType.v()));
_data = new ExpressionSet(returnExpr);
return;
} else if (methodRef.getSignature().endsWith("boolean equals(java.lang.Object)>")) {
String returnString = "Return<" + methodRef.declaringClass().getShortName() + "." + methodRef.name() + "(){" + v.hashCode() + "}>";
VariableExpression returnExpr = new VariableExpression(new PlaceholderVariable(returnString, BooleanType.v()));
_data = new ExpressionSet(returnExpr);
return;
} else if (method.getDeclaringClass().isApplicationClass() && !_excludeMethods.contains(method) && _auxDepth == 0) {
String returnString = "Return<" + methodRef.declaringClass().getShortName() + "." + methodRef.name() + "(){" + v.hashCode() + "}>";
if (v instanceof InstanceInvokeExpr) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet base = resolveValue(instanceExpr.getBase(), _in);
if (base != null) {
for (Expression baseExpr : base.getExpressions()) {
if (baseExpr.isVariable()) {
returnString = "Return<" + baseExpr.getVariable() + "." + v.getMethodRef().name() + "(){" + v.hashCode() + "}>";
break;
}
}
}
}
VariableExpression returnIdentifier = new VariableExpression(new PlaceholderVariable(returnString, v.getMethod().getReturnType()));
_data = new ExpressionSet(returnIdentifier);
return;
}
if (v instanceof InstanceInvokeExpr) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet base = resolveValue(instanceExpr.getBase(), _in);
if (base != null) {
_data = ExpressionSet.transform(base, e -> {
if (e.isVariable()) {
return new VariableExpression(new MethodCallVariable(v, e.getVariable()));
} else {
return new VariableExpression(new MethodCallVariable(v));
}
});
}
}
} | @Override
public void caseInterfaceInvokeExpr(InterfaceInvokeExpr v) {
<DeepExtract>
SootMethod method = v.getMethod();
SootMethodRef methodRef = v.getMethodRef();
if (methodRef.getSignature().equals("<android.telephony.SmsMessage: " + "android.telephony.SmsMessage createFromPdu(byte[])>")) {
ExpressionSet op1 = resolveValue(v.getArg(0), _in);
if (op1 != null) {
_data = ExpressionSet.transform(op1, e -> {
if (e.isVariable()) {
return new VariableExpression(new MethodCallVariable(v, e.getVariable()));
} else {
return new VariableExpression(new MethodCallVariable(v));
}
});
return;
}
} else if (methodRef.getSignature().startsWith("<android.os.Bundle: java.lang.Object get(java.lang.String")) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet base = resolveValue(instanceExpr.getBase(), _in);
ExpressionSet op1 = resolveValue(instanceExpr.getArg(0), _in);
if (base != null && op1 != null) {
List<ExpressionSet> results = new ArrayList<ExpressionSet>();
for (Expression baseExpr : base.getExpressions()) {
if (!baseExpr.isVariable()) {
results.add(new ExpressionSet(new VariableExpression(new KeyValueAccessVariable(null, null, KeyValueAccessVariable.DatabaseType.BUNDLE, v.getMethod().getReturnType()))));
continue;
}
ExpressionSet partialResult = ExpressionSet.transform(op1, e -> {
if (e.isVariable()) {
return new VariableExpression(new KeyValueAccessVariable(baseExpr.getVariable(), e.getVariable(), KeyValueAccessVariable.DatabaseType.BUNDLE, v.getMethod().getReturnType()));
} else {
return new VariableExpression(new KeyValueAccessVariable(baseExpr.getVariable(), null, KeyValueAccessVariable.DatabaseType.BUNDLE, v.getMethod().getReturnType()));
}
});
results.add(partialResult);
}
_data = ExpressionSet.merge(results);
return;
}
} else if (methodRef.getSignature().startsWith("<android.content.Context: java.lang.String getString(int") || methodRef.getSignature().equals("<android.content.Context: java.lang.CharSequence getText(int)>")) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet op1 = resolveValue(instanceExpr.getArg(0), _in);
if (op1 != null) {
_data = ExpressionSet.transform(op1, e -> {
Variable opVariable = e.isVariable() ? e.getVariable() : null;
return new VariableExpression(new KeyValueAccessVariable(new PlaceholderVariable("Context", RefType.v("android.content.Context")), opVariable, KeyValueAccessVariable.DatabaseType.STRING_TABLE, RefType.v("java.lang.String")));
});
return;
}
} else if (methodRef.getSignature().startsWith("<java.lang.StringBuilder: java.lang.StringBuilder append(")) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet op1 = resolveValue(instanceExpr.getBase(), _in);
ExpressionSet op2 = resolveValue(instanceExpr.getArg(0), _in);
if (op1 != null && op2 != null) {
_data = ExpressionSet.combine(Expression.Operator.APPEND, op1, op2);
return;
}
} else if (methodRef.getSignature().endsWith("java.lang.String toString()>") || methodRef.getSignature().endsWith("char[] toCharArray()>")) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
_data = resolveValue(instanceExpr.getBase(), _in);
return;
} else if (methodRef.getSignature().equals("<java.lang.String: boolean equals(java.lang.Object)>") || methodRef.getSignature().equals("<java.lang.String: boolean contains(java.lang.CharSequence)>")) {
String returnString = "Return<" + methodRef.declaringClass().getShortName() + "." + methodRef.name() + "(){" + v.hashCode() + "}>";
VariableExpression returnExpr = new VariableExpression(new PlaceholderVariable(returnString, BooleanType.v()));
_data = new ExpressionSet(returnExpr);
return;
} else if (methodRef.getSignature().endsWith("boolean equals(java.lang.Object)>")) {
String returnString = "Return<" + methodRef.declaringClass().getShortName() + "." + methodRef.name() + "(){" + v.hashCode() + "}>";
VariableExpression returnExpr = new VariableExpression(new PlaceholderVariable(returnString, BooleanType.v()));
_data = new ExpressionSet(returnExpr);
return;
} else if (method.getDeclaringClass().isApplicationClass() && !_excludeMethods.contains(method) && _auxDepth == 0) {
String returnString = "Return<" + methodRef.declaringClass().getShortName() + "." + methodRef.name() + "(){" + v.hashCode() + "}>";
if (v instanceof InstanceInvokeExpr) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet base = resolveValue(instanceExpr.getBase(), _in);
if (base != null) {
for (Expression baseExpr : base.getExpressions()) {
if (baseExpr.isVariable()) {
returnString = "Return<" + baseExpr.getVariable() + "." + v.getMethodRef().name() + "(){" + v.hashCode() + "}>";
break;
}
}
}
}
VariableExpression returnIdentifier = new VariableExpression(new PlaceholderVariable(returnString, v.getMethod().getReturnType()));
_data = new ExpressionSet(returnIdentifier);
return;
}
if (v instanceof InstanceInvokeExpr) {
InstanceInvokeExpr instanceExpr = (InstanceInvokeExpr) v;
ExpressionSet base = resolveValue(instanceExpr.getBase(), _in);
if (base != null) {
_data = ExpressionSet.transform(base, e -> {
if (e.isVariable()) {
return new VariableExpression(new MethodCallVariable(v, e.getVariable()));
} else {
return new VariableExpression(new MethodCallVariable(v));
}
});
}
}
</DeepExtract>
} | tiro | positive | 3,511 |
@Override
public void setSurface(Surface surface) throws IOException {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
if (surface != null) {
mSurfaceHolder = new DummySurfaceHolder(surface);
startPreview(mSurfaceHolder);
} else {
mSurfaceHolder = null;
startPreview(null);
}
} | @Override
public void setSurface(Surface surface) throws IOException {
<DeepExtract>
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
</DeepExtract>
if (surface != null) {
mSurfaceHolder = new DummySurfaceHolder(surface);
startPreview(mSurfaceHolder);
} else {
mSurfaceHolder = null;
startPreview(null);
}
} | spynet-camera | positive | 3,512 |
public String getFieldName() {
if (this.fieldDescriptor == null) {
return "";
}
return this.name;
} | public String getFieldName() {
if (this.fieldDescriptor == null) {
return "";
}
<DeepExtract>
return this.name;
</DeepExtract>
} | xresloader | positive | 3,513 |
protected void init() {
source.addTextSourceListener(this);
ITextBlock[] blocks = source.getBlocks();
entries = new ArrayList<SearchScopeEntry>(blocks.length);
for (ITextBlock block : blocks) {
SearchScopeEntry entry = createEntry(block);
entries.add(entry);
}
Collections.sort(entries);
if (source.getSelection() != null && source.getSelection().equals(this.selection)) {
return;
}
if (source.getSelection() == null && entries.size() > 0) {
ITextBlock block = entries.get(0).getBlock();
source.getSelection() = new SourceSelection(block, 0, 0);
}
this.selection = source.getSelection();
updateStart();
} | protected void init() {
source.addTextSourceListener(this);
ITextBlock[] blocks = source.getBlocks();
entries = new ArrayList<SearchScopeEntry>(blocks.length);
for (ITextBlock block : blocks) {
SearchScopeEntry entry = createEntry(block);
entries.add(entry);
}
Collections.sort(entries);
<DeepExtract>
if (source.getSelection() != null && source.getSelection().equals(this.selection)) {
return;
}
if (source.getSelection() == null && entries.size() > 0) {
ITextBlock block = entries.get(0).getBlock();
source.getSelection() = new SourceSelection(block, 0, 0);
}
this.selection = source.getSelection();
updateStart();
</DeepExtract>
} | glance | positive | 3,514 |
@Override
public void actionPerformed(ActionEvent e) {
dispose();
} | @Override
public void actionPerformed(ActionEvent e) {
<DeepExtract>
dispose();
</DeepExtract>
} | hrider | positive | 3,515 |
@Test
public void testSkippedField2() throws IOException {
SortedMap<Key, Value> map = new TreeMap<>();
map.put(new Key("key1", "cf0", "cq1"), new Value("xxx"));
map.put(new Key("key1", "cf1", "cq1"), new Value("abc"));
map.put(new Key("key1", "cf1", "cq2"), new Value("def"));
SortedMapIterator parentIterator = new SortedMapIterator(map);
AvroRowEncoderIterator iterator = new AvroRowEncoderIterator();
Map<String, String> options = new HashMap<>();
options.put(AvroRowEncoderIterator.SCHEMA, "[{\"cf\":\"cf1\",\"cq\":\"cq1\",\"t\":\"STRING\",\"o\":true}]");
iterator.init(parentIterator, options, new DefaultIteratorEnvironment());
iterator.seek(new Range(), AvroUtil.EMPTY_SET, false);
Schema schema = SchemaBuilder.record("root").fields().name("cf1").type(SchemaBuilder.record("cf1").fields().optionalString("cq1").endRecord()).noDefault().endRecord();
for (MyRow row : new MyRow("key1", "abc")) {
assertTrue(iterator.hasTop());
assertEquals(row.key, iterator.getTopKey().getRow().toString());
byte[] data = iterator.getTopValue().get();
GenericRecord record = AvroUtil.deserialize(data, schema);
GenericRecord cf1Record = (GenericRecord) record.get("cf1");
assertEquals(row.cf1cq1, cf1Record.get("cq1").toString());
iterator.next();
}
assertFalse(iterator.hasTop());
} | @Test
public void testSkippedField2() throws IOException {
SortedMap<Key, Value> map = new TreeMap<>();
map.put(new Key("key1", "cf0", "cq1"), new Value("xxx"));
map.put(new Key("key1", "cf1", "cq1"), new Value("abc"));
map.put(new Key("key1", "cf1", "cq2"), new Value("def"));
<DeepExtract>
SortedMapIterator parentIterator = new SortedMapIterator(map);
AvroRowEncoderIterator iterator = new AvroRowEncoderIterator();
Map<String, String> options = new HashMap<>();
options.put(AvroRowEncoderIterator.SCHEMA, "[{\"cf\":\"cf1\",\"cq\":\"cq1\",\"t\":\"STRING\",\"o\":true}]");
iterator.init(parentIterator, options, new DefaultIteratorEnvironment());
iterator.seek(new Range(), AvroUtil.EMPTY_SET, false);
Schema schema = SchemaBuilder.record("root").fields().name("cf1").type(SchemaBuilder.record("cf1").fields().optionalString("cq1").endRecord()).noDefault().endRecord();
for (MyRow row : new MyRow("key1", "abc")) {
assertTrue(iterator.hasTop());
assertEquals(row.key, iterator.getTopKey().getRow().toString());
byte[] data = iterator.getTopValue().get();
GenericRecord record = AvroUtil.deserialize(data, schema);
GenericRecord cf1Record = (GenericRecord) record.get("cf1");
assertEquals(row.cf1cq1, cf1Record.get("cq1").toString());
iterator.next();
}
assertFalse(iterator.hasTop());
</DeepExtract>
} | masc | positive | 3,516 |
@NonNull
public TSnackbarBig setColor(ColorStateList colors) {
final Button btn = mView.getActionView();
btn.setTextColor(colors);
return this;
final TextView tv = mView.getMessageView();
tv.setTextColor(colors);
return this;
return this;
} | @NonNull
public TSnackbarBig setColor(ColorStateList colors) {
final Button btn = mView.getActionView();
btn.setTextColor(colors);
return this;
<DeepExtract>
final TextView tv = mView.getMessageView();
tv.setTextColor(colors);
return this;
</DeepExtract>
return this;
} | GarbageSorting | positive | 3,517 |
public synchronized <T extends Event> void removeEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler) {
typedEvents.removeIf(g -> g.filter == false && g.type == eventType && g.handle == eventHandler);
if (false)
n.removeEventFilter(eventType, eventHandler);
else
n.removeEventHandler(eventType, eventHandler);
} | public synchronized <T extends Event> void removeEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler) {
<DeepExtract>
typedEvents.removeIf(g -> g.filter == false && g.type == eventType && g.handle == eventHandler);
if (false)
n.removeEventFilter(eventType, eventHandler);
else
n.removeEventHandler(eventType, eventHandler);
</DeepExtract>
} | Simulizer | positive | 3,518 |
@JsonCreator
private static ServerDto.Builder create() {
return new AutoValue_ServerDto.Builder().setHostName(Optional.empty()).setStartupDateTime(Optional.empty());
} | @JsonCreator
private static ServerDto.Builder create() {
<DeepExtract>
return new AutoValue_ServerDto.Builder().setHostName(Optional.empty()).setStartupDateTime(Optional.empty());
</DeepExtract>
} | beadledom | positive | 3,519 |
@Override
public boolean showParticles() {
return false;
} | @Override
public boolean showParticles() {
<DeepExtract>
return false;
</DeepExtract>
} | SuperMassiveTech | positive | 3,520 |
public Tweet setStatus(Status status) {
this.status = status;
this.id = "" + status.getId();
this.sentence = new Sentence(status.getText());
if (status.getUser() != null) {
if (status.getUser().getLocation() != null)
this.userLocation = status.getUser().getLocation();
if (status.getUser().getDescription() != null)
this.userDescription = status.getUser().getDescription();
if (status.getUser().getTimeZone() != null)
this.timezone = status.getUser().getTimeZone();
}
if (status.getGeoLocation() != null) {
this.latitude = status.getGeoLocation().getLatitude();
this.longitude = status.getGeoLocation().getLongitude();
}
if (status.getPlace() != null) {
this.place = status.getPlace().getFullName();
this.placeCountry = status.getPlace().getCountry();
placeBounds = status.getPlace().getBoundingBoxCoordinates();
this.placeType = status.getPlace().getPlaceType();
}
return this;
} | public Tweet setStatus(Status status) {
this.status = status;
<DeepExtract>
this.id = "" + status.getId();
this.sentence = new Sentence(status.getText());
if (status.getUser() != null) {
if (status.getUser().getLocation() != null)
this.userLocation = status.getUser().getLocation();
if (status.getUser().getDescription() != null)
this.userDescription = status.getUser().getDescription();
if (status.getUser().getTimeZone() != null)
this.timezone = status.getUser().getTimeZone();
}
if (status.getGeoLocation() != null) {
this.latitude = status.getGeoLocation().getLatitude();
this.longitude = status.getGeoLocation().getLongitude();
}
if (status.getPlace() != null) {
this.place = status.getPlace().getFullName();
this.placeCountry = status.getPlace().getCountry();
placeBounds = status.getPlace().getBoundingBoxCoordinates();
this.placeType = status.getPlace().getPlaceType();
}
</DeepExtract>
return this;
} | geolocator-3.0 | positive | 3,521 |
public Criteria andConfigModeBetween(String value1, String value2) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "configMode" + " cannot be null");
}
criteria.add(new Criterion("config_mode between", value1, value2));
return (Criteria) this;
} | public Criteria andConfigModeBetween(String value1, String value2) {
<DeepExtract>
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "configMode" + " cannot be null");
}
criteria.add(new Criterion("config_mode between", value1, value2));
</DeepExtract>
return (Criteria) this;
} | AnyMock | positive | 3,522 |
@Override
public void calculateDamageDisplay(AbstractMonster mo) {
this.block = this.baseDamage + AbstractDungeon.player.exhaustPile.size() * this.magicNumber;
super.calculateCardDamage(mo);
} | @Override
public void calculateDamageDisplay(AbstractMonster mo) {
<DeepExtract>
this.block = this.baseDamage + AbstractDungeon.player.exhaustPile.size() * this.magicNumber;
super.calculateCardDamage(mo);
</DeepExtract>
} | STS_ThMod_MRS | positive | 3,523 |
void attachTopFragment(Fragment topFragment) {
fragmentManager.beginTransaction().replace(R.id.drag_view, topFragment).commit();
} | void attachTopFragment(Fragment topFragment) {
<DeepExtract>
fragmentManager.beginTransaction().replace(R.id.drag_view, topFragment).commit();
</DeepExtract>
} | DiscogsBrowser | positive | 3,524 |
public CCObserviableAttributeCollection Observe(Item item) {
CCObserviableAttributeCollection atts = new CCObserviableAttributeCollection();
atts.resourceType = CCResourceType.ITEM;
atts.resourceId = item.getRegistryName().toString();
List<String> valueMap = null;
if (!attributeMap.containsKey(CCAttributeId.ITEM_ID)) {
valueMap = new ArrayList<String>();
attributeMap.put(CCAttributeId.ITEM_ID, valueMap);
} else {
valueMap = attributeMap.get(CCAttributeId.ITEM_ID);
}
if (!valueMap.contains(atts.resourceId)) {
valueMap.add(atts.resourceId);
ObservedAttributesElement newAttribute = new ObservedAttributesElement();
newAttribute.setAttributeId(CCAttributeId.ITEM_ID);
newAttribute.setAttributeValue(atts.resourceId);
newAttribute.setSpecies(organism.getSpeciesNamespace());
newAttributes.add(newAttribute);
return true;
}
return false;
return atts;
} | public CCObserviableAttributeCollection Observe(Item item) {
CCObserviableAttributeCollection atts = new CCObserviableAttributeCollection();
atts.resourceType = CCResourceType.ITEM;
atts.resourceId = item.getRegistryName().toString();
<DeepExtract>
List<String> valueMap = null;
if (!attributeMap.containsKey(CCAttributeId.ITEM_ID)) {
valueMap = new ArrayList<String>();
attributeMap.put(CCAttributeId.ITEM_ID, valueMap);
} else {
valueMap = attributeMap.get(CCAttributeId.ITEM_ID);
}
if (!valueMap.contains(atts.resourceId)) {
valueMap.add(atts.resourceId);
ObservedAttributesElement newAttribute = new ObservedAttributesElement();
newAttribute.setAttributeId(CCAttributeId.ITEM_ID);
newAttribute.setAttributeValue(atts.resourceId);
newAttribute.setSpecies(organism.getSpeciesNamespace());
newAttributes.add(newAttribute);
return true;
}
return false;
</DeepExtract>
return atts;
} | chaoscraft-mod | positive | 3,525 |
public String[] getDirectives(String key) {
if (directives == null) {
return new String[] {};
}
Object result = directives.get(key);
if (result == null) {
return new String[] {};
}
if (result instanceof String) {
return new String[] { (String) result };
}
@SuppressWarnings("unchecked")
List<String> valueList = (List<String>) result;
return valueList.toArray(new String[valueList.size()]);
} | public String[] getDirectives(String key) {
<DeepExtract>
if (directives == null) {
return new String[] {};
}
Object result = directives.get(key);
if (result == null) {
return new String[] {};
}
if (result instanceof String) {
return new String[] { (String) result };
}
@SuppressWarnings("unchecked")
List<String> valueList = (List<String>) result;
return valueList.toArray(new String[valueList.size()]);
</DeepExtract>
} | carbon-kernel | positive | 3,526 |
void exchange(final BigInteger amountInWei) {
atomicSwapSenderError = amountInWei.compareTo(MAX_VALUE) == 1;
if (atomicSwapSenderError) {
return;
}
BigInteger swapAmountOtherChain = amountInWei.multiply(this.atomicSwapSender_Exchange_exchangeRate);
swapAmountOtherChain = swapAmountOtherChain.divide(DECIMAL_POINT);
this.atomicSwapReceiverError = this.receiverBalanceInWei.compareTo(swapAmountOtherChain) == -1;
if (this.atomicSwapReceiverError) {
return;
}
this.receiverBalanceInWei = this.receiverBalanceInWei.subtract(swapAmountOtherChain);
this.accepterBalanceInWei = this.accepterBalanceInWei.add(swapAmountOtherChain);
if (this.atomicSwapReceiverError) {
return;
}
this.atomicSwapReceiver_Exchange_amount = swapAmountOtherChain;
this.senderBalanceInWei.add(amountInWei);
} | void exchange(final BigInteger amountInWei) {
atomicSwapSenderError = amountInWei.compareTo(MAX_VALUE) == 1;
if (atomicSwapSenderError) {
return;
}
BigInteger swapAmountOtherChain = amountInWei.multiply(this.atomicSwapSender_Exchange_exchangeRate);
swapAmountOtherChain = swapAmountOtherChain.divide(DECIMAL_POINT);
<DeepExtract>
this.atomicSwapReceiverError = this.receiverBalanceInWei.compareTo(swapAmountOtherChain) == -1;
if (this.atomicSwapReceiverError) {
return;
}
this.receiverBalanceInWei = this.receiverBalanceInWei.subtract(swapAmountOtherChain);
this.accepterBalanceInWei = this.accepterBalanceInWei.add(swapAmountOtherChain);
</DeepExtract>
if (this.atomicSwapReceiverError) {
return;
}
this.atomicSwapReceiver_Exchange_amount = swapAmountOtherChain;
this.senderBalanceInWei.add(amountInWei);
} | sidechains-samples | positive | 3,527 |
public void setSys(AvalonSystem s) {
sys = s;
if (sys != null) {
AbstractSopcGenerator gen = GeneratorFactory.createGeneratorFor(sys, genType);
if (gen != null) {
if (gen.isTextOutput()) {
txtDts.setText(gen.getTextOutput((bi == null ? new BoardInfo() : bi)));
} else {
txtDts.setText(bin2HexString(gen.getBinaryOutput((bi == null ? new BoardInfo() : bi))));
}
} else {
txtDts.setText("");
}
} else {
txtDts.setText("");
}
} | public void setSys(AvalonSystem s) {
sys = s;
<DeepExtract>
if (sys != null) {
AbstractSopcGenerator gen = GeneratorFactory.createGeneratorFor(sys, genType);
if (gen != null) {
if (gen.isTextOutput()) {
txtDts.setText(gen.getTextOutput((bi == null ? new BoardInfo() : bi)));
} else {
txtDts.setText(bin2HexString(gen.getBinaryOutput((bi == null ? new BoardInfo() : bi))));
}
} else {
txtDts.setText("");
}
} else {
txtDts.setText("");
}
</DeepExtract>
} | sopc2dts | positive | 3,529 |
public static final int resemblanceOrder(final int order1, final int order2, final int figure) {
int order = ORDER_INVALID;
int order1Reverse;
if (order1 == ORDER_NONE) {
order1Reverse = ORDER_NONE;
} else {
order1Reverse = -order1;
}
if ((order2 == TemporalRules.ORDER_NONE)) {
order = (figure > 20) ? order1 : order1Reverse;
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = (figure % 10 == 1) ? order2 : reverseOrder(order2);
} else if (order2 == TemporalRules.ORDER_CONCURRENT) {
order = (figure > 20) ? order1 : order1Reverse;
} else if (order1 == order2) {
order = (figure == 21) ? order1 : -order1;
}
return order;
} | public static final int resemblanceOrder(final int order1, final int order2, final int figure) {
int order = ORDER_INVALID;
<DeepExtract>
int order1Reverse;
if (order1 == ORDER_NONE) {
order1Reverse = ORDER_NONE;
} else {
order1Reverse = -order1;
}
</DeepExtract>
if ((order2 == TemporalRules.ORDER_NONE)) {
order = (figure > 20) ? order1 : order1Reverse;
} else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) {
order = (figure % 10 == 1) ? order2 : reverseOrder(order2);
} else if (order2 == TemporalRules.ORDER_CONCURRENT) {
order = (figure > 20) ? order1 : order1Reverse;
} else if (order1 == order2) {
order = (figure == 21) ? order1 : -order1;
}
return order;
} | opennars | positive | 3,530 |
@Override
public AstNode visitExpression_identifier(Expression_identifierContext ctx) {
if (this != null) {
return (T) this.accept(this);
}
return null;
} | @Override
public AstNode visitExpression_identifier(Expression_identifierContext ctx) {
<DeepExtract>
if (this != null) {
return (T) this.accept(this);
}
return null;
</DeepExtract>
} | jetbrick-template-2x | positive | 3,531 |
public int climbStairs2(int n) {
int[] memo = new int[n + 1];
if (0 > n)
return 0;
if (0 == n)
return 1;
if (memo[0] > 0)
return memo[0];
memo[0] = climbStairsHelper(0 + 1, n, memo) + climbStairsHelper(0 + 2, n, memo) + climbStairsHelper(0 + 3, n, memo);
return memo[0];
} | public int climbStairs2(int n) {
int[] memo = new int[n + 1];
<DeepExtract>
if (0 > n)
return 0;
if (0 == n)
return 1;
if (memo[0] > 0)
return memo[0];
memo[0] = climbStairsHelper(0 + 1, n, memo) + climbStairsHelper(0 + 2, n, memo) + climbStairsHelper(0 + 3, n, memo);
return memo[0];
</DeepExtract>
} | LintCode | positive | 3,532 |
private static void addTrailingDefaultLine(List<Text[]> result, ArgSpec arg, ColorScheme scheme) {
Text EMPTY = Ansi.EMPTY_TEXT;
return new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, scheme.ansi().new Text(" Default: " + arg.defaultValueString()) }.isOption() ? addOption((OptionSpec) new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, scheme.ansi().new Text(" Default: " + arg.defaultValueString()) }) : addPositional((PositionalParamSpec) new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, scheme.ansi().new Text(" Default: " + arg.defaultValueString()) });
} | private static void addTrailingDefaultLine(List<Text[]> result, ArgSpec arg, ColorScheme scheme) {
Text EMPTY = Ansi.EMPTY_TEXT;
<DeepExtract>
return new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, scheme.ansi().new Text(" Default: " + arg.defaultValueString()) }.isOption() ? addOption((OptionSpec) new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, scheme.ansi().new Text(" Default: " + arg.defaultValueString()) }) : addPositional((PositionalParamSpec) new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, scheme.ansi().new Text(" Default: " + arg.defaultValueString()) });
</DeepExtract>
} | eclipstyle | positive | 3,533 |
@Override
public void onClick(DialogInterface dialog, int which) {
try {
dialog.dismiss();
} catch (Exception ignore) {
}
SharedPreferences.Editor editor = getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE).edit();
editor.putBoolean(PREFERENCE_PERMISSION_DENIED + permission, true).commit();
mRequestPermissionsInProcess.set(false);
} | @Override
public void onClick(DialogInterface dialog, int which) {
try {
dialog.dismiss();
} catch (Exception ignore) {
}
<DeepExtract>
SharedPreferences.Editor editor = getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE).edit();
editor.putBoolean(PREFERENCE_PERMISSION_DENIED + permission, true).commit();
</DeepExtract>
mRequestPermissionsInProcess.set(false);
} | Android-RTEditor | positive | 3,534 |
public static String getNextDateShort() {
return LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern(DATE_FORMATTER_SHORT));
} | public static String getNextDateShort() {
<DeepExtract>
return LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern(DATE_FORMATTER_SHORT));
</DeepExtract>
} | lion | positive | 3,535 |
public boolean isZero() {
if (RatNum.ZERO instanceof RatTerm) {
RatTerm rt = (RatTerm) RatNum.ZERO;
if (this.isNaN() && rt.isNaN()) {
return true;
} else {
return this.expt == rt.expt && this.coeff.equals(rt.coeff);
}
} else {
return false;
}
} | public boolean isZero() {
<DeepExtract>
if (RatNum.ZERO instanceof RatTerm) {
RatTerm rt = (RatTerm) RatNum.ZERO;
if (this.isNaN() && rt.isNaN()) {
return true;
} else {
return this.expt == rt.expt && this.coeff.equals(rt.coeff);
}
} else {
return false;
}
</DeepExtract>
} | CSE331 | positive | 3,538 |
@Override
public void visit(GreaterThanEquals arg0) {
Expression expression1 = arg0.getLeftExpression();
Expression expression2 = arg0.getRightExpression();
expression1.accept(this);
expression2.accept(this);
outputType.put(arg0, SQLtype.BOOL);
propagateScope(expression1, arg0);
propagateScope(expression2, arg0);
castInputs(arg0);
} | @Override
public void visit(GreaterThanEquals arg0) {
<DeepExtract>
Expression expression1 = arg0.getLeftExpression();
Expression expression2 = arg0.getRightExpression();
expression1.accept(this);
expression2.accept(this);
outputType.put(arg0, SQLtype.BOOL);
propagateScope(expression1, arg0);
propagateScope(expression2, arg0);
castInputs(arg0);
</DeepExtract>
} | skinnerdb | positive | 3,539 |
public Object invokeWithoutCheck(Object bean) throws Exception {
try {
return getterMethod.invoke(bean);
} catch (IllegalAccessException e) {
throw new BristleRuntimeException(e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new BristleRuntimeException(e.getMessage(), e);
}
} | public Object invokeWithoutCheck(Object bean) throws Exception {
<DeepExtract>
try {
return getterMethod.invoke(bean);
} catch (IllegalAccessException e) {
throw new BristleRuntimeException(e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new BristleRuntimeException(e.getMessage(), e);
}
</DeepExtract>
} | bristleback | positive | 3,540 |
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (getWidth() == 0 && getHeight() == 0) {
return;
}
if (mBitmap == null) {
invalidate();
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
mFillPaint.setColor(mFillColor);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(calculateBounds());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f);
mDrawableRect.set(mBorderRect);
if (!mBorderOverlay && mBorderWidth > 0) {
mDrawableRect.inset(mBorderWidth - 1.0f, mBorderWidth - 1.0f);
}
mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f);
if (mBitmapPaint != null) {
mBitmapPaint.setColorFilter(mColorFilter);
}
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mDrawableRect.left, (int) (dy + 0.5f) + mDrawableRect.top);
mBitmapShader.setLocalMatrix(mShaderMatrix);
invalidate();
} | private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (getWidth() == 0 && getHeight() == 0) {
return;
}
if (mBitmap == null) {
invalidate();
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
mFillPaint.setColor(mFillColor);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(calculateBounds());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f);
mDrawableRect.set(mBorderRect);
if (!mBorderOverlay && mBorderWidth > 0) {
mDrawableRect.inset(mBorderWidth - 1.0f, mBorderWidth - 1.0f);
}
mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f);
if (mBitmapPaint != null) {
mBitmapPaint.setColorFilter(mColorFilter);
}
<DeepExtract>
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mDrawableRect.left, (int) (dy + 0.5f) + mDrawableRect.top);
mBitmapShader.setLocalMatrix(mShaderMatrix);
</DeepExtract>
invalidate();
} | ToDoList | positive | 3,541 |
public void writeFullyInt64(long address, long[] b, int off, int len) throws IOException {
data.offset(address - header.address);
data.writeFullyInt64(b, off, len);
} | public void writeFullyInt64(long address, long[] b, int off, int len) throws IOException {
<DeepExtract>
data.offset(address - header.address);
</DeepExtract>
data.writeFullyInt64(b, off, len);
} | org.cakelab.blender.io | positive | 3,542 |
public void testSelftRSA_PKCS1() {
short k = KeyBuilder.LENGTH_RSA_512 / Byte.SIZE;
short maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_512);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_512 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_736 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_736);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_736 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_768 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_768);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_768 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_896 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_896);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_896 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1024 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_1024);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1024 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1280 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_1280);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1280 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1536 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_1536);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1536 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1984 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_1984);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1984 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_2048 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_2048);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_2048 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_3072 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_3072);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_3072 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_4096);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_512 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_512);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_512 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_736 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_736);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_736 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_768 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_768);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_768 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_896 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_896);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_896 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1024 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1024);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1024 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1280 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1280);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1280 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1536 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1536);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1536 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1984 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1984);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1984 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_2048 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_2048);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_2048 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_3072 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_3072);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_3072 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_4096);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_4096);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE);
byte[] msg = new byte[(short) (maxMsgLen - 1)];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
try {
testSelftRSA(Cipher.ALG_RSA_PKCS1, KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_4096, (short) (maxMsgLen + 1));
assert (false);
} catch (CryptoException ex) {
assertEquals(CryptoException.ILLEGAL_USE, ex.getReason());
}
} | public void testSelftRSA_PKCS1() {
short k = KeyBuilder.LENGTH_RSA_512 / Byte.SIZE;
short maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_512);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_512 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_736 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_736);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_736 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_768 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_768);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_768 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_896 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_896);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_896 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1024 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_1024);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1024 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1280 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_1280);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1280 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1536 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_1536);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1536 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1984 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_1984);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1984 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_2048 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_2048);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_2048 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_3072 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_3072);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_3072 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_4096);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_512 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_512);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_512 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_736 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_736);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_736 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_768 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_768);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_768 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_896 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_896);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_896 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1024 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1024);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1024 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1280 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1280);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1280 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1536 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1536);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1536 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_1984 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1984);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_1984 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_2048 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_2048);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_2048 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_3072 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_3072);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_3072 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
k = KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE;
maxMsgLen = (short) (k - 11);
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_4096);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE);
byte[] msg = new byte[maxMsgLen];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
<DeepExtract>
Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_4096);
kp.genKeyPair();
cipher.init(kp.getPublic(), Cipher.MODE_ENCRYPT);
short keySizeInBytes = (short) (KeyBuilder.LENGTH_RSA_4096 / Byte.SIZE);
byte[] msg = new byte[(short) (maxMsgLen - 1)];
byte[] encryptedMsg = new byte[keySizeInBytes];
new Random().nextBytes(msg);
cipher.doFinal(msg, (short) 0, (short) msg.length, encryptedMsg, (short) 0);
cipher.init(kp.getPrivate(), Cipher.MODE_DECRYPT);
byte[] decryptedMsg = new byte[msg.length];
cipher.doFinal(encryptedMsg, (short) 0, (short) encryptedMsg.length, decryptedMsg, (short) 0);
assertEquals(true, Arrays.areEqual(msg, decryptedMsg));
</DeepExtract>
try {
testSelftRSA(Cipher.ALG_RSA_PKCS1, KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_4096, (short) (maxMsgLen + 1));
assert (false);
} catch (CryptoException ex) {
assertEquals(CryptoException.ILLEGAL_USE, ex.getReason());
}
} | jcardsim | positive | 3,543 |
public Criteria andBookIdIsNotNull() {
if ("book_id is not null" == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion("book_id is not null"));
return (Criteria) this;
} | public Criteria andBookIdIsNotNull() {
<DeepExtract>
if ("book_id is not null" == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion("book_id is not null"));
</DeepExtract>
return (Criteria) this;
} | springboot-BMSystem | positive | 3,544 |
public final AC shrinkWeight(float w, int... indexes) {
Float sw = new Float(w);
for (int i = indexes.length - 1; i >= 0; i--) {
int ix = indexes[i];
makeSize(ix);
cList.get(ix).setShrink(sw);
}
return this;
} | public final AC shrinkWeight(float w, int... indexes) {
<DeepExtract>
Float sw = new Float(w);
for (int i = indexes.length - 1; i >= 0; i--) {
int ix = indexes[i];
makeSize(ix);
cList.get(ix).setShrink(sw);
}
return this;
</DeepExtract>
} | miglayout | positive | 3,545 |
public static String generateSignedXml(final Map<String, String> data, String key, SignType signType) throws Exception {
String sign;
Set<String> keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (k.equals(WXPayConstants.FIELD_SIGN)) {
continue;
}
if (data.get(k).trim().length() > 0)
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
if (SignType.MD5.equals(signType)) {
sign = MD5(sb.toString()).toUpperCase();
} else if (SignType.HMACSHA256.equals(signType)) {
sign = HMACSHA256(sb.toString(), key);
} else {
throw new Exception(String.format("Invalid sign_type: %s", signType));
}
data.put(WXPayConstants.FIELD_SIGN, sign);
org.w3c.dom.Document document = WXPayXmlUtil.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key : data.keySet()) {
String value = data.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString();
try {
writer.close();
} catch (Exception ex) {
}
return output;
} | public static String generateSignedXml(final Map<String, String> data, String key, SignType signType) throws Exception {
String sign;
Set<String> keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (k.equals(WXPayConstants.FIELD_SIGN)) {
continue;
}
if (data.get(k).trim().length() > 0)
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
if (SignType.MD5.equals(signType)) {
sign = MD5(sb.toString()).toUpperCase();
} else if (SignType.HMACSHA256.equals(signType)) {
sign = HMACSHA256(sb.toString(), key);
} else {
throw new Exception(String.format("Invalid sign_type: %s", signType));
}
data.put(WXPayConstants.FIELD_SIGN, sign);
<DeepExtract>
org.w3c.dom.Document document = WXPayXmlUtil.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key : data.keySet()) {
String value = data.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString();
try {
writer.close();
} catch (Exception ex) {
}
return output;
</DeepExtract>
} | r-mall | positive | 3,547 |
public Criteria andWxNotIn(List<String> values) {
if (values == null) {
throw new RuntimeException("Value for " + "wx" + " cannot be null");
}
criteria.add(new Criterion("wx not in", values));
return (Criteria) this;
} | public Criteria andWxNotIn(List<String> values) {
<DeepExtract>
if (values == null) {
throw new RuntimeException("Value for " + "wx" + " cannot be null");
}
criteria.add(new Criterion("wx not in", values));
</DeepExtract>
return (Criteria) this;
} | uccn | positive | 3,548 |
public Criteria andNumberGreaterThan(Integer value) {
if (value == null) {
throw new RuntimeException("Value for " + "number" + " cannot be null");
}
criteria.add(new Criterion("number >", value));
return (Criteria) this;
} | public Criteria andNumberGreaterThan(Integer value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "number" + " cannot be null");
}
criteria.add(new Criterion("number >", value));
</DeepExtract>
return (Criteria) this;
} | SSM_VUE | positive | 3,550 |
private static final int[] body(int[] schedule, int Eswap0, int Eswap1) {
int left = 0;
int right = 0;
int t = 0;
for (int j = 0; j < 25; j++) {
for (int i = 0; i < ITERATIONS * 2; i += 4) {
left = D_ENCRYPT(left, right, i, Eswap0, Eswap1, schedule);
right = D_ENCRYPT(right, left, i + 2, Eswap0, Eswap1, schedule);
}
t = left;
left = right;
right = t;
}
t = right;
right = (left >>> 1) | (left << 31);
left = (t >>> 1) | (t << 31);
left &= 0xffffffff;
right &= 0xffffffff;
int[] results = new int[2];
int t;
t = ((right >>> 1) ^ left) & 0x55555555;
right ^= t << 1;
left ^= t;
results[0] = right;
results[1] = left;
right = results[0];
left = results[1];
int t;
t = ((left >>> 8) ^ right) & 0x00ff00ff;
left ^= t << 8;
right ^= t;
results[0] = left;
results[1] = right;
left = results[0];
right = results[1];
int t;
t = ((right >>> 2) ^ left) & 0x33333333;
right ^= t << 2;
left ^= t;
results[0] = right;
results[1] = left;
right = results[0];
left = results[1];
int t;
t = ((left >>> 16) ^ right) & 0x0000ffff;
left ^= t << 16;
right ^= t;
results[0] = left;
results[1] = right;
left = results[0];
right = results[1];
int t;
t = ((right >>> 4) ^ left) & 0x0f0f0f0f;
right ^= t << 4;
left ^= t;
results[0] = right;
results[1] = left;
right = results[0];
left = results[1];
int[] out = new int[2];
out[0] = left;
out[1] = right;
return (out);
} | private static final int[] body(int[] schedule, int Eswap0, int Eswap1) {
int left = 0;
int right = 0;
int t = 0;
for (int j = 0; j < 25; j++) {
for (int i = 0; i < ITERATIONS * 2; i += 4) {
left = D_ENCRYPT(left, right, i, Eswap0, Eswap1, schedule);
right = D_ENCRYPT(right, left, i + 2, Eswap0, Eswap1, schedule);
}
t = left;
left = right;
right = t;
}
t = right;
right = (left >>> 1) | (left << 31);
left = (t >>> 1) | (t << 31);
left &= 0xffffffff;
right &= 0xffffffff;
int[] results = new int[2];
int t;
t = ((right >>> 1) ^ left) & 0x55555555;
right ^= t << 1;
left ^= t;
results[0] = right;
results[1] = left;
right = results[0];
left = results[1];
int t;
t = ((left >>> 8) ^ right) & 0x00ff00ff;
left ^= t << 8;
right ^= t;
results[0] = left;
results[1] = right;
left = results[0];
right = results[1];
int t;
t = ((right >>> 2) ^ left) & 0x33333333;
right ^= t << 2;
left ^= t;
results[0] = right;
results[1] = left;
right = results[0];
left = results[1];
int t;
t = ((left >>> 16) ^ right) & 0x0000ffff;
left ^= t << 16;
right ^= t;
results[0] = left;
results[1] = right;
left = results[0];
right = results[1];
<DeepExtract>
int t;
t = ((right >>> 4) ^ left) & 0x0f0f0f0f;
right ^= t << 4;
left ^= t;
results[0] = right;
results[1] = left;
</DeepExtract>
right = results[0];
left = results[1];
int[] out = new int[2];
out[0] = left;
out[1] = right;
return (out);
} | deployr-rserve | positive | 3,551 |
@Override
public void onBackPressed() {
super.onBackPressed();
setResult(RESULT_CANCELED);
finish();
} | @Override
public void onBackPressed() {
super.onBackPressed();
<DeepExtract>
setResult(RESULT_CANCELED);
finish();
</DeepExtract>
} | iLiveSDK_Android_Suixinbo | positive | 3,552 |
public void one() {
Util.arrayFillNonAtomic(value, (short) 0, this.size, (byte) 0);
value[(short) (size - 1)] = 1;
} | public void one() {
<DeepExtract>
Util.arrayFillNonAtomic(value, (short) 0, this.size, (byte) 0);
</DeepExtract>
value[(short) (size - 1)] = 1;
} | JCMathLib | positive | 3,553 |
private void enableController() {
if (null == play_pauseButton)
return;
play_pauseButton.setClickable(true);
if (null == videoBar)
return;
videoBar.setClickable(true);
if (null == mContainerLayout)
return;
mContainerLayout.setClickable(true);
if (null == full_screenButton)
return;
full_screenButton.setClickable(true);
if (null == videoBar)
return;
videoBar.setClickable(true);
} | private void enableController() {
if (null == play_pauseButton)
return;
play_pauseButton.setClickable(true);
<DeepExtract>
if (null == videoBar)
return;
videoBar.setClickable(true);
</DeepExtract>
if (null == mContainerLayout)
return;
mContainerLayout.setClickable(true);
if (null == full_screenButton)
return;
full_screenButton.setClickable(true);
<DeepExtract>
if (null == videoBar)
return;
videoBar.setClickable(true);
</DeepExtract>
} | YouKuPlayerDemo | positive | 3,554 |
public Builder stringField(String name) {
fields.add(new Field(name, FieldType.STRING));
return this;
} | public Builder stringField(String name) {
<DeepExtract>
fields.add(new Field(name, FieldType.STRING));
return this;
</DeepExtract>
} | exhibit | positive | 3,555 |
@Override
public void mouseEntered(MouseEvent evt) {
m_jlStatusBar.setText((String) m_keyStoreReportAction.getValue(Action.LONG_DESCRIPTION));
} | @Override
public void mouseEntered(MouseEvent evt) {
<DeepExtract>
m_jlStatusBar.setText((String) m_keyStoreReportAction.getValue(Action.LONG_DESCRIPTION));
</DeepExtract>
} | portecle | positive | 3,556 |
@SuppressWarnings("WeakerAccess")
public int getGreenInt() {
return ((int) getGreen()) & 0xff;
} | @SuppressWarnings("WeakerAccess")
public int getGreenInt() {
<DeepExtract>
return ((int) getGreen()) & 0xff;
</DeepExtract>
} | JavaOSC | positive | 3,557 |
public Criteria andN_dateNotIn(List<Date> values) {
if (values == null) {
throw new RuntimeException("Value for " + "n_date" + " cannot be null");
}
criteria.add(new Criterion("n_date not in", values));
return (Criteria) this;
} | public Criteria andN_dateNotIn(List<Date> values) {
<DeepExtract>
if (values == null) {
throw new RuntimeException("Value for " + "n_date" + " cannot be null");
}
criteria.add(new Criterion("n_date not in", values));
</DeepExtract>
return (Criteria) this;
} | BaiChengNews | positive | 3,558 |
@Override
public ServerDirectory createDirectory(AuthToken u, ServerPath serverPath) throws OWLServerException {
if (!loginService.checkAuthentication(u)) {
throw new AuthenticationFailedException();
}
return getDelegate().createDirectory(u, serverPath);
} | @Override
public ServerDirectory createDirectory(AuthToken u, ServerPath serverPath) throws OWLServerException {
<DeepExtract>
if (!loginService.checkAuthentication(u)) {
throw new AuthenticationFailedException();
}
</DeepExtract>
return getDelegate().createDirectory(u, serverPath);
} | protege-server | positive | 3,559 |
@Override
public void trace(final Marker marker, final String msg, final Throwable t) {
if (!TRACE.isGreaterOrEqual(minimum))
throw new IllegalStateException(format("%s logging disabled for logger \"%s\" [%s]", TRACE, getName(), getClass().getName()));
super.trace(marker, msg, t);
} | @Override
public void trace(final Marker marker, final String msg, final Throwable t) {
<DeepExtract>
if (!TRACE.isGreaterOrEqual(minimum))
throw new IllegalStateException(format("%s logging disabled for logger \"%s\" [%s]", TRACE, getName(), getClass().getName()));
</DeepExtract>
super.trace(marker, msg, t);
} | binkley | positive | 3,560 |
public static <T> Response<T> error(String msg) {
return result(null, ResultCodeEnum.CODE_500.code(), msg);
} | public static <T> Response<T> error(String msg) {
<DeepExtract>
return result(null, ResultCodeEnum.CODE_500.code(), msg);
</DeepExtract>
} | chao-cloud | positive | 3,561 |
@Override
public synchronized void addVotingBlockToCache(Block block) {
if (block.getHeight() > height) {
this.blockCache.get(block.getHeight(), k -> new HashMap<>(7)).put(block.getHash(), block);
}
} | @Override
public synchronized void addVotingBlockToCache(Block block) {
<DeepExtract>
if (block.getHeight() > height) {
this.blockCache.get(block.getHeight(), k -> new HashMap<>(7)).put(block.getHash(), block);
}
</DeepExtract>
} | Swiftglobal | positive | 3,563 |
public static Type getBigMapKeyType(Field field) {
Type[] mapTypes;
if (BigMap.class.equals(field.getType())) {
if (field.getGenericType() instanceof ParameterizedType) {
ParameterizedType mapType = (ParameterizedType) field.getGenericType();
mapTypes = mapType.getActualTypeArguments();
}
mapTypes = null;
} else {
mapTypes = null;
}
return mapTypes == null ? Object.class : mapTypes[0];
} | public static Type getBigMapKeyType(Field field) {
<DeepExtract>
Type[] mapTypes;
if (BigMap.class.equals(field.getType())) {
if (field.getGenericType() instanceof ParameterizedType) {
ParameterizedType mapType = (ParameterizedType) field.getGenericType();
mapTypes = mapType.getActualTypeArguments();
}
mapTypes = null;
} else {
mapTypes = null;
}
</DeepExtract>
return mapTypes == null ? Object.class : mapTypes[0];
} | spikeify | positive | 3,564 |
public static synchronized void saveFile(String fileIndex, String fileName, Map<String, String> contentList) {
try {
File fileDir = new File(fileIndex);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
String filePath = fileIndex + File.separator + fileName;
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
String filePath = fileIndex + File.separator + fileName;
File file = new File(filePath);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
for (String lineStr : contentList.keySet()) {
writer.append(lineStr);
writer.newLine();
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} | public static synchronized void saveFile(String fileIndex, String fileName, Map<String, String> contentList) {
<DeepExtract>
try {
File fileDir = new File(fileIndex);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
String filePath = fileIndex + File.separator + fileName;
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
</DeepExtract>
String filePath = fileIndex + File.separator + fileName;
File file = new File(filePath);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
for (String lineStr : contentList.keySet()) {
writer.append(lineStr);
writer.newLine();
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} | FanucCNCInfo | positive | 3,565 |
public static void i(String tag, String message, int methodCount) {
if (methodCount < 0 || methodCount > MAX_METHOD_COUNT) {
throw new IllegalStateException("methodCount must be > 0 and < 5");
}
if (settings.logLevel == LogLevel.NONE) {
return;
}
logTopBorder(Log.INFO, tag);
logHeaderContent(Log.INFO, tag, methodCount);
byte[] bytes = message.getBytes();
int length = bytes.length;
if (length <= CHUNK_SIZE) {
if (methodCount > 0) {
logDivider(Log.INFO, tag);
}
logContent(Log.INFO, tag, message);
logBottomBorder(Log.INFO, tag);
return;
}
if (methodCount > 0) {
logDivider(Log.INFO, tag);
}
for (int i = 0; i < length; i += CHUNK_SIZE) {
int count = Math.min(length - i, CHUNK_SIZE);
logContent(Log.INFO, tag, new String(bytes, i, count));
}
logBottomBorder(Log.INFO, tag);
} | public static void i(String tag, String message, int methodCount) {
if (methodCount < 0 || methodCount > MAX_METHOD_COUNT) {
throw new IllegalStateException("methodCount must be > 0 and < 5");
}
<DeepExtract>
if (settings.logLevel == LogLevel.NONE) {
return;
}
logTopBorder(Log.INFO, tag);
logHeaderContent(Log.INFO, tag, methodCount);
byte[] bytes = message.getBytes();
int length = bytes.length;
if (length <= CHUNK_SIZE) {
if (methodCount > 0) {
logDivider(Log.INFO, tag);
}
logContent(Log.INFO, tag, message);
logBottomBorder(Log.INFO, tag);
return;
}
if (methodCount > 0) {
logDivider(Log.INFO, tag);
}
for (int i = 0; i < length; i += CHUNK_SIZE) {
int count = Math.min(length - i, CHUNK_SIZE);
logContent(Log.INFO, tag, new String(bytes, i, count));
}
logBottomBorder(Log.INFO, tag);
</DeepExtract>
} | JianDan_AsyncHttpClient | positive | 3,566 |
public void startCountdown() {
mCountdownSpring.addListener(mSpringListener);
mCurrentCount = mStartCount;
setText(String.valueOf(mCurrentCount));
mCountdownSpring.setCurrentValue(0.01);
mCountdownSpring.setEndValue(1);
show();
if (mCountdownCallback != null) {
mCountdownCallback.onStart();
}
mCountdownSubscription = Observable.interval(100, TimeUnit.MILLISECONDS).take((mStartCount - mStopCount + 1) * 10).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
countdown();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long count) {
if (count > 0 && count % 10 == 0) {
countdown();
} else if (count % 10 == 8) {
hide();
}
}
});
} | public void startCountdown() {
mCountdownSpring.addListener(mSpringListener);
mCurrentCount = mStartCount;
<DeepExtract>
setText(String.valueOf(mCurrentCount));
mCountdownSpring.setCurrentValue(0.01);
mCountdownSpring.setEndValue(1);
show();
</DeepExtract>
if (mCountdownCallback != null) {
mCountdownCallback.onStart();
}
mCountdownSubscription = Observable.interval(100, TimeUnit.MILLISECONDS).take((mStartCount - mStopCount + 1) * 10).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
countdown();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long count) {
if (count > 0 && count % 10 == 0) {
countdown();
} else if (count % 10 == 8) {
hide();
}
}
});
} | AndroidPlayground | positive | 3,567 |
@Override
public IndexOperation remove(Iterable<T> objects) {
if (Expressive.isEmpty(objects)) {
return new IndexOperation(null);
}
List<K> ids = new ArrayList<>();
for (T object : objects) {
ids.add(metadata.getId(object));
}
return super.removeById(ids);
} | @Override
public IndexOperation remove(Iterable<T> objects) {
if (Expressive.isEmpty(objects)) {
return new IndexOperation(null);
}
List<K> ids = new ArrayList<>();
for (T object : objects) {
ids.add(metadata.getId(object));
}
<DeepExtract>
return super.removeById(ids);
</DeepExtract>
} | AppleSeed | positive | 3,568 |
@Test
public void unsampledSpan() {
brave.Span unsampledRemote = tracing.tracer().nextSpan(TraceContextOrSamplingFlags.NOT_SAMPLED).name("test").start(1L);
assertThat(unsampledRemote.isNoop()).isTrue();
assertThat(unsampledRemote.context().sampled()).isFalse();
assertThat(unsampledRemote.context().sampledLocal()).isFalse();
unsampledRemote.finish(2L);
assertThat(spans).isEmpty();
} | @Test
<DeepExtract>
</DeepExtract>
public void unsampledSpan() {
<DeepExtract>
</DeepExtract>
brave.Span unsampledRemote = tracing.tracer().nextSpan(TraceContextOrSamplingFlags.NOT_SAMPLED).name("test").start(1L);
<DeepExtract>
</DeepExtract>
assertThat(unsampledRemote.isNoop()).isTrue();
<DeepExtract>
</DeepExtract>
assertThat(unsampledRemote.context().sampled()).isFalse();
<DeepExtract>
</DeepExtract>
assertThat(unsampledRemote.context().sampledLocal()).isFalse();
<DeepExtract>
</DeepExtract>
unsampledRemote.finish(2L);
<DeepExtract>
</DeepExtract>
assertThat(spans).isEmpty();
<DeepExtract>
</DeepExtract>
} | zipkin-reporter-java | positive | 3,569 |
private void showExitAlert() {
AlertDialog.Builder exitBuilder = new AlertDialog.Builder(MainActivity.this);
this.title = "Close application";
getActionBar().setTitle("Close application");
exitBuilder.setMessage("Do you really want to exit the application?");
exitBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
exitBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
MainActivity.this.finish();
}
});
exitBuilder.setIcon(R.drawable.ic_launcher_smal);
exitBuilder.show();
} | private void showExitAlert() {
AlertDialog.Builder exitBuilder = new AlertDialog.Builder(MainActivity.this);
<DeepExtract>
this.title = "Close application";
getActionBar().setTitle("Close application");
</DeepExtract>
exitBuilder.setMessage("Do you really want to exit the application?");
exitBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
exitBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
MainActivity.this.finish();
}
});
exitBuilder.setIcon(R.drawable.ic_launcher_smal);
exitBuilder.show();
} | owasp-seraphimdroid | positive | 3,570 |
public int getDuration() {
return mDuration;
} | public int getDuration() {
<DeepExtract>
return mDuration;
</DeepExtract>
} | wanAndroid | positive | 3,571 |
public Criteria andPaidAmountNotEqualTo(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "paidAmount" + " cannot be null");
}
criteria.add(new Criterion("paid_amount <>", value));
return (Criteria) this;
} | public Criteria andPaidAmountNotEqualTo(String value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "paidAmount" + " cannot be null");
}
criteria.add(new Criterion("paid_amount <>", value));
</DeepExtract>
return (Criteria) this;
} | bw-pay | positive | 3,572 |
private static Fraction divide(int a1, int b1, int a2, int b2) {
return new Fraction(a1 * b2, b1 * a2);
} | private static Fraction divide(int a1, int b1, int a2, int b2) {
<DeepExtract>
return new Fraction(a1 * b2, b1 * a2);
</DeepExtract>
} | Java-Nov-2020 | positive | 3,573 |
private void sendTeamPacket(int score, TeamMode mode) throws Throwable {
if (mode == TeamMode.ADD_PLAYERS || mode == TeamMode.REMOVE_PLAYERS) {
throw new UnsupportedOperationException();
}
int maxLength = hasLinesMaxLength() ? 16 : 1024;
Object packet = PACKET_SB_TEAM.invoke();
setField(packet, String.class, this.id + ':' + score, 0);
int i = 0;
for (Field field : PACKETS.get(packet.getClass())) {
if (field.getType() == int.class && VERSION_TYPE == VersionType.V1_8 ? 1 : 0 == i++) {
field.set(packet, mode.ordinal());
}
}
if (mode == TeamMode.CREATE || mode == TeamMode.UPDATE) {
String line = getLineByScore(score);
String prefix;
String suffix = null;
if (line == null || line.isEmpty()) {
prefix = COLOR_CODES[score] + ChatColor.RESET;
} else if (line.length() <= maxLength) {
prefix = line;
} else {
int index = line.charAt(maxLength - 1) == ChatColor.COLOR_CHAR ? (maxLength - 1) : maxLength;
prefix = line.substring(0, index);
String suffixTmp = line.substring(index);
ChatColor chatColor = null;
if (suffixTmp.length() >= 2 && suffixTmp.charAt(0) == ChatColor.COLOR_CHAR) {
chatColor = ChatColor.getByChar(suffixTmp.charAt(1));
}
String color = ChatColor.getLastColors(prefix);
boolean addColor = chatColor == null || chatColor.isFormat();
suffix = (addColor ? (color.isEmpty() ? ChatColor.RESET.toString() : color) : "") + suffixTmp;
}
if (prefix.length() > maxLength || (suffix != null && suffix.length() > maxLength)) {
prefix = prefix.substring(0, maxLength);
suffix = (suffix != null) ? suffix.substring(0, maxLength) : null;
}
if (VersionType.V1_17.isHigherOrEqual()) {
Object team = PACKET_SB_SERIALIZABLE_TEAM.invoke();
setComponentField(team, "", 0);
setField(team, CHAT_FORMAT_ENUM, RESET_FORMATTING);
setComponentField(team, prefix, 1);
setComponentField(team, suffix == null ? "" : suffix, 2);
setField(team, String.class, "always", 0);
setField(team, String.class, "always", 1);
setField(packet, Optional.class, Optional.of(team));
} else {
setComponentField(packet, prefix, 2);
setComponentField(packet, suffix == null ? "" : suffix, 3);
setField(packet, String.class, "always", 4);
setField(packet, String.class, "always", 5);
}
if (mode == TeamMode.CREATE) {
setField(packet, Collection.class, Collections.singletonList(COLOR_CODES[score]));
}
}
if (this.deleted) {
throw new IllegalStateException("This FastBoard is deleted");
}
if (this.player.isOnline()) {
Object entityPlayer = PLAYER_GET_HANDLE.invoke(this.player);
Object playerConnection = PLAYER_CONNECTION.invoke(entityPlayer);
SEND_PACKET.invoke(playerConnection, packet);
}
} | private void sendTeamPacket(int score, TeamMode mode) throws Throwable {
if (mode == TeamMode.ADD_PLAYERS || mode == TeamMode.REMOVE_PLAYERS) {
throw new UnsupportedOperationException();
}
int maxLength = hasLinesMaxLength() ? 16 : 1024;
Object packet = PACKET_SB_TEAM.invoke();
setField(packet, String.class, this.id + ':' + score, 0);
int i = 0;
for (Field field : PACKETS.get(packet.getClass())) {
if (field.getType() == int.class && VERSION_TYPE == VersionType.V1_8 ? 1 : 0 == i++) {
field.set(packet, mode.ordinal());
}
}
if (mode == TeamMode.CREATE || mode == TeamMode.UPDATE) {
String line = getLineByScore(score);
String prefix;
String suffix = null;
if (line == null || line.isEmpty()) {
prefix = COLOR_CODES[score] + ChatColor.RESET;
} else if (line.length() <= maxLength) {
prefix = line;
} else {
int index = line.charAt(maxLength - 1) == ChatColor.COLOR_CHAR ? (maxLength - 1) : maxLength;
prefix = line.substring(0, index);
String suffixTmp = line.substring(index);
ChatColor chatColor = null;
if (suffixTmp.length() >= 2 && suffixTmp.charAt(0) == ChatColor.COLOR_CHAR) {
chatColor = ChatColor.getByChar(suffixTmp.charAt(1));
}
String color = ChatColor.getLastColors(prefix);
boolean addColor = chatColor == null || chatColor.isFormat();
suffix = (addColor ? (color.isEmpty() ? ChatColor.RESET.toString() : color) : "") + suffixTmp;
}
if (prefix.length() > maxLength || (suffix != null && suffix.length() > maxLength)) {
prefix = prefix.substring(0, maxLength);
suffix = (suffix != null) ? suffix.substring(0, maxLength) : null;
}
if (VersionType.V1_17.isHigherOrEqual()) {
Object team = PACKET_SB_SERIALIZABLE_TEAM.invoke();
setComponentField(team, "", 0);
setField(team, CHAT_FORMAT_ENUM, RESET_FORMATTING);
setComponentField(team, prefix, 1);
setComponentField(team, suffix == null ? "" : suffix, 2);
setField(team, String.class, "always", 0);
setField(team, String.class, "always", 1);
setField(packet, Optional.class, Optional.of(team));
} else {
setComponentField(packet, prefix, 2);
setComponentField(packet, suffix == null ? "" : suffix, 3);
setField(packet, String.class, "always", 4);
setField(packet, String.class, "always", 5);
}
if (mode == TeamMode.CREATE) {
setField(packet, Collection.class, Collections.singletonList(COLOR_CODES[score]));
}
}
<DeepExtract>
if (this.deleted) {
throw new IllegalStateException("This FastBoard is deleted");
}
if (this.player.isOnline()) {
Object entityPlayer = PLAYER_GET_HANDLE.invoke(this.player);
Object playerConnection = PLAYER_CONNECTION.invoke(entityPlayer);
SEND_PACKET.invoke(playerConnection, packet);
}
</DeepExtract>
} | TemplatePlugin | positive | 3,574 |
@Subscribe(threadMode = ThreadMode.MAIN)
public void onFocalsDisconnected(FocalsDisconnectedEvent e) {
Log.i(TAG, "ConnectActivity::onFocalsDisconnected");
if (device_.shouldDiscover()) {
startDiscovery();
} else {
startConnecting();
}
} | @Subscribe(threadMode = ThreadMode.MAIN)
public void onFocalsDisconnected(FocalsDisconnectedEvent e) {
Log.i(TAG, "ConnectActivity::onFocalsDisconnected");
<DeepExtract>
if (device_.shouldDiscover()) {
startDiscovery();
} else {
startConnecting();
}
</DeepExtract>
} | openfocals | positive | 3,575 |
public void close() {
mCloseAnimatorSet.start();
for (ItemAnimator anim : mMenuItemAnimators) {
anim.startCloseAnimator();
}
mOpen = false;
if (onMenuToggleListener != null) {
onMenuToggleListener.onMenuToggle(true);
}
} | public void close() {
<DeepExtract>
mCloseAnimatorSet.start();
for (ItemAnimator anim : mMenuItemAnimators) {
anim.startCloseAnimator();
}
</DeepExtract>
mOpen = false;
if (onMenuToggleListener != null) {
onMenuToggleListener.onMenuToggle(true);
}
} | dttv-android | positive | 3,576 |
public static Date setDayStart(Date date) {
if (null == date) {
return null;
}
if (null == dateToLocalDateTime(date).withHour(0).withMinute(0).withSecond(0).withNano(0)) {
return null;
}
return Date.from(dateToLocalDateTime(date).withHour(0).withMinute(0).withSecond(0).withNano(0).atZone(ZoneId.systemDefault()).toInstant());
} | public static Date setDayStart(Date date) {
if (null == date) {
return null;
}
<DeepExtract>
if (null == dateToLocalDateTime(date).withHour(0).withMinute(0).withSecond(0).withNano(0)) {
return null;
}
return Date.from(dateToLocalDateTime(date).withHour(0).withMinute(0).withSecond(0).withNano(0).atZone(ZoneId.systemDefault()).toInstant());
</DeepExtract>
} | Doramon | positive | 3,577 |
@Override
public void banned(Jid actor, String reason) {
if (LogConstants.LOG_DEBUG) {
Log.d(TAG, "Banned from " + room + " by " + actor + ": " + reason);
}
ContentValues cvR = new ContentValues();
String message;
if (actor != null && actor.length() > 0)
message = mService.getString(true ? R.string.muc_banned_by : R.string.muc_kicked_by, actor, reason);
else
message = mService.getString(true ? R.string.muc_banned : R.string.muc_kicked, reason);
cvR.put(RosterProvider.RosterConstants.STATUS_MESSAGE, message);
cvR.put(RosterProvider.RosterConstants.STATUS_MODE, StatusMode.offline.ordinal());
upsertRoster(cvR, room);
} | @Override
public void banned(Jid actor, String reason) {
if (LogConstants.LOG_DEBUG) {
Log.d(TAG, "Banned from " + room + " by " + actor + ": " + reason);
}
<DeepExtract>
ContentValues cvR = new ContentValues();
String message;
if (actor != null && actor.length() > 0)
message = mService.getString(true ? R.string.muc_banned_by : R.string.muc_kicked_by, actor, reason);
else
message = mService.getString(true ? R.string.muc_banned : R.string.muc_kicked, reason);
cvR.put(RosterProvider.RosterConstants.STATUS_MESSAGE, message);
cvR.put(RosterProvider.RosterConstants.STATUS_MODE, StatusMode.offline.ordinal());
upsertRoster(cvR, room);
</DeepExtract>
} | yaxim | positive | 3,578 |
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.pref_general_tax);
mSharedPreferences = android.preference.PreferenceManager.getDefaultSharedPreferences(getActivity());
if ("pref_tax".equals("pref_discount")) {
Preference preference = findPreference("pref_tax");
EditTextPreference editTextPreference = (EditTextPreference) preference;
editTextPreference.setSummary(mSharedPreferences.getString("pref_tax", String.valueOf(editTextPreference.getSummary())));
}
} | @Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.pref_general_tax);
mSharedPreferences = android.preference.PreferenceManager.getDefaultSharedPreferences(getActivity());
<DeepExtract>
if ("pref_tax".equals("pref_discount")) {
Preference preference = findPreference("pref_tax");
EditTextPreference editTextPreference = (EditTextPreference) preference;
editTextPreference.setSummary(mSharedPreferences.getString("pref_tax", String.valueOf(editTextPreference.getSummary())));
}
</DeepExtract>
} | stockita-point-of-sale | positive | 3,580 |
public void writeCharacters(String text) throws XMLStreamException {
object.append(text);
} | public void writeCharacters(String text) throws XMLStreamException {
<DeepExtract>
object.append(text);
</DeepExtract>
} | jettison | positive | 3,582 |
public synchronized static void resetBitmapCache(int size) {
bitmapCacheSize = size;
if (null != bitmapMemoryCache) {
bitmapMemoryCache.removeAll();
bitmapMemoryCache = null;
}
} | public synchronized static void resetBitmapCache(int size) {
bitmapCacheSize = size;
<DeepExtract>
if (null != bitmapMemoryCache) {
bitmapMemoryCache.removeAll();
bitmapMemoryCache = null;
}
</DeepExtract>
} | bigapple | positive | 3,583 |
public Criteria andLicensePlateLessThanOrEqualTo(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "licensePlate" + " cannot be null");
}
criteria.add(new Criterion("license_plate <=", value));
return (Criteria) this;
} | public Criteria andLicensePlateLessThanOrEqualTo(String value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "licensePlate" + " cannot be null");
}
criteria.add(new Criterion("license_plate <=", value));
</DeepExtract>
return (Criteria) this;
} | spring-boot-learning-examples | positive | 3,584 |
public void exchange(Table table, int index) {
JettyLaunchConfigEntry entryA = entries.remove(index);
JettyLaunchConfigEntry entryB = entries.remove(index);
entryA.deleteItem(table);
entryB.deleteItem(table);
entries.add(entryA);
entryA.updateItem(index, listener, entries.size() - 1, false);
entries.add(entryB);
entryB.updateItem(index, listener, entries.size() - 1, false);
entryB.createItem(table, listener, index);
entryA.createItem(table, listener, index + 1);
} | public void exchange(Table table, int index) {
JettyLaunchConfigEntry entryA = entries.remove(index);
JettyLaunchConfigEntry entryB = entries.remove(index);
entryA.deleteItem(table);
entryB.deleteItem(table);
entries.add(entryA);
entryA.updateItem(index, listener, entries.size() - 1, false);
<DeepExtract>
entries.add(entryB);
entryB.updateItem(index, listener, entries.size() - 1, false);
</DeepExtract>
entryB.createItem(table, listener, index);
entryA.createItem(table, listener, index + 1);
} | eclipse-jetty-plugin | positive | 3,585 |
@Override
public List<CloudServiceInstance> getServiceInstancesByMetadataLabelSelector(String labelSelector) {
IntFunction<ListServiceInstancesRequest> pageRequestSupplier = page -> ListServiceInstancesRequest.builder().labelSelector(labelSelector).spaceId(getTargetSpaceGuid().toString()).page(page).build();
return fetchFluxWithAuxiliaryContent(() -> getServiceInstanceResources(pageRequestSupplier), this::zipWithAuxiliaryServiceInstanceContent).collectList().block();
} | @Override
public List<CloudServiceInstance> getServiceInstancesByMetadataLabelSelector(String labelSelector) {
IntFunction<ListServiceInstancesRequest> pageRequestSupplier = page -> ListServiceInstancesRequest.builder().labelSelector(labelSelector).spaceId(getTargetSpaceGuid().toString()).page(page).build();
<DeepExtract>
return fetchFluxWithAuxiliaryContent(() -> getServiceInstanceResources(pageRequestSupplier), this::zipWithAuxiliaryServiceInstanceContent).collectList().block();
</DeepExtract>
} | cf-java-client-sap | positive | 3,586 |
private static String inputStreamToString(InputStream in) throws IOException {
try {
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
int count;
while ((count = new InputStreamReader(in, UTF_8).read(buffer)) != -1) {
writer.write(buffer, 0, count);
}
return writer.toString();
} finally {
new InputStreamReader(in, UTF_8).close();
}
} | private static String inputStreamToString(InputStream in) throws IOException {
<DeepExtract>
try {
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
int count;
while ((count = new InputStreamReader(in, UTF_8).read(buffer)) != -1) {
writer.write(buffer, 0, count);
}
return writer.toString();
} finally {
new InputStreamReader(in, UTF_8).close();
}
</DeepExtract>
} | AndroidDemos | positive | 3,587 |
public Criteria andPwdNotLike(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "pwd" + " cannot be null");
}
criteria.add(new Criterion("pwd not like", value));
return (Criteria) this;
} | public Criteria andPwdNotLike(String value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "pwd" + " cannot be null");
}
criteria.add(new Criterion("pwd not like", value));
</DeepExtract>
return (Criteria) this;
} | Hospital | positive | 3,588 |
public void onClick(View v) {
if (D)
Log.d(TAG, "doDiscovery()");
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
mBtAdapter.startDiscovery();
v.setVisibility(View.GONE);
} | public void onClick(View v) {
<DeepExtract>
if (D)
Log.d(TAG, "doDiscovery()");
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
mBtAdapter.startDiscovery();
</DeepExtract>
v.setVisibility(View.GONE);
} | BallCraft | positive | 3,589 |
public ActionScriptProjectData getProjectDataForSourceFile(Path path) {
String configFileName = null;
for (ActionScriptProjectData projectData : allProjectData) {
if (projectData.config == null) {
continue;
}
Path configFilePath = projectData.config.getConfigFilePath();
if (configFilePath == null) {
continue;
}
configFileName = configFilePath.getFileName().toString();
break;
}
if (configFileName == null) {
return;
}
Path fallbackProjectRoot = null;
WorkspaceFolder fallbackFolder = null;
for (ActionScriptProjectData projectData : allProjectData) {
if (projectData.config == null) {
continue;
}
if (projectData.folder == null) {
continue;
}
Path workspaceFolderPath = LanguageServerCompilerUtils.getPathFromLanguageServerURI(projectData.folder.getUri());
if (workspaceFolderPath == null) {
continue;
}
if (!path.startsWith(workspaceFolderPath)) {
continue;
}
Path currentPath = path.getParent();
do {
Path configFilePath = currentPath.resolve(configFileName);
if (configFilePath.toFile().exists()) {
if (configFilePath.equals(projectData.config.getConfigFilePath())) {
return;
}
fallbackProjectRoot = currentPath;
fallbackFolder = projectData.folder;
}
currentPath = currentPath.getParent();
} while (currentPath != null && currentPath.startsWith(workspaceFolderPath));
}
if (fallbackProjectRoot == null || fallbackFolder == null) {
return;
}
addProject(fallbackProjectRoot, fallbackFolder);
ActionScriptProjectData bestMatch = null;
ActionScriptProjectData fallback = null;
for (ActionScriptProjectData projectData : allProjectData) {
ILspProject project = projectData.project;
if (project == null) {
continue;
}
Path projectRoot = projectData.projectRoot;
if (projectRoot == null) {
continue;
}
if (bestMatch != null && bestMatch.projectDepth >= projectData.projectDepth) {
continue;
}
if (SourcePathUtils.isInProjectSourcePath(path, project, projectData.configurator)) {
if (path.startsWith(projectRoot)) {
bestMatch = projectData;
continue;
}
if (fallback == null) {
fallback = projectData;
continue;
}
}
}
if (bestMatch != null) {
return bestMatch;
}
if (fallback != null) {
return fallback;
}
for (ActionScriptProjectData projectData : allProjectData) {
ILspProject project = projectData.project;
if (project != null) {
continue;
}
Path projectRoot = projectData.projectRoot;
if (projectRoot == null) {
continue;
}
if (path.startsWith(projectRoot)) {
return projectData;
}
}
return fallbackProjectData;
} | public ActionScriptProjectData getProjectDataForSourceFile(Path path) {
<DeepExtract>
String configFileName = null;
for (ActionScriptProjectData projectData : allProjectData) {
if (projectData.config == null) {
continue;
}
Path configFilePath = projectData.config.getConfigFilePath();
if (configFilePath == null) {
continue;
}
configFileName = configFilePath.getFileName().toString();
break;
}
if (configFileName == null) {
return;
}
Path fallbackProjectRoot = null;
WorkspaceFolder fallbackFolder = null;
for (ActionScriptProjectData projectData : allProjectData) {
if (projectData.config == null) {
continue;
}
if (projectData.folder == null) {
continue;
}
Path workspaceFolderPath = LanguageServerCompilerUtils.getPathFromLanguageServerURI(projectData.folder.getUri());
if (workspaceFolderPath == null) {
continue;
}
if (!path.startsWith(workspaceFolderPath)) {
continue;
}
Path currentPath = path.getParent();
do {
Path configFilePath = currentPath.resolve(configFileName);
if (configFilePath.toFile().exists()) {
if (configFilePath.equals(projectData.config.getConfigFilePath())) {
return;
}
fallbackProjectRoot = currentPath;
fallbackFolder = projectData.folder;
}
currentPath = currentPath.getParent();
} while (currentPath != null && currentPath.startsWith(workspaceFolderPath));
}
if (fallbackProjectRoot == null || fallbackFolder == null) {
return;
}
addProject(fallbackProjectRoot, fallbackFolder);
</DeepExtract>
ActionScriptProjectData bestMatch = null;
ActionScriptProjectData fallback = null;
for (ActionScriptProjectData projectData : allProjectData) {
ILspProject project = projectData.project;
if (project == null) {
continue;
}
Path projectRoot = projectData.projectRoot;
if (projectRoot == null) {
continue;
}
if (bestMatch != null && bestMatch.projectDepth >= projectData.projectDepth) {
continue;
}
if (SourcePathUtils.isInProjectSourcePath(path, project, projectData.configurator)) {
if (path.startsWith(projectRoot)) {
bestMatch = projectData;
continue;
}
if (fallback == null) {
fallback = projectData;
continue;
}
}
}
if (bestMatch != null) {
return bestMatch;
}
if (fallback != null) {
return fallback;
}
for (ActionScriptProjectData projectData : allProjectData) {
ILspProject project = projectData.project;
if (project != null) {
continue;
}
Path projectRoot = projectData.projectRoot;
if (projectRoot == null) {
continue;
}
if (path.startsWith(projectRoot)) {
return projectData;
}
}
return fallbackProjectData;
} | vscode-as3mxml | positive | 3,590 |
public S thenReturn(double... values) {
trainingContext().then(InterceptorUtils.constant(ArrayUtils.clone(values)));
return self();
@SuppressWarnings("unchecked")
final S self = (S) this;
return self;
} | public S thenReturn(double... values) {
trainingContext().then(InterceptorUtils.constant(ArrayUtils.clone(values)));
return self();
<DeepExtract>
@SuppressWarnings("unchecked")
final S self = (S) this;
return self;
</DeepExtract>
} | commons-proxy | positive | 3,591 |
@Test
public void testUpgrade() throws Exception {
hiveServer.createTable("CREATE TABLE " + hiveTableDesc.getTableName() + " (t1 TINYINT, s1 SMALLINT, i1 INT, l1 BIGINT, " + " f1 FLOAT, d1 DOUBLE) " + " ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'");
HiveOutputDescription outputDesc = new HiveOutputDescription();
outputDesc.setTableDesc(hiveTableDesc);
HiveInputDescription inputDesc = new HiveInputDescription();
inputDesc.setTableDesc(hiveTableDesc);
HiveTableSchema schema = HiveTableSchemas.lookup(hiveServer.getClient(), null, hiveTableDesc);
List<HiveWritableRecord> writeRecords = Lists.newArrayList();
HiveWritableRecord r1 = HiveRecordFactory.newWritableRecord(schema);
writeRecords.add(r1);
r1.set(1, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getShort(1));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(1, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getShort(1));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(2, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getInt(2));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(2, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getInt(2));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(2, 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getInt(2));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(3, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getLong(3));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(3, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getLong(3));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(3, 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getLong(3));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(3, 4L);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getLong(3));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, 4L);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, 4.2f);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4.2, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, 4);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, 4L);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, 4.2f);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4.2, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, 4.2d);
HiveOutput.writeTable(outputDesc, writeRecords);
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
assertEquals(4.2, readRecord.getDouble(5), DELTA);
} | @Test
public void testUpgrade() throws Exception {
hiveServer.createTable("CREATE TABLE " + hiveTableDesc.getTableName() + " (t1 TINYINT, s1 SMALLINT, i1 INT, l1 BIGINT, " + " f1 FLOAT, d1 DOUBLE) " + " ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'");
HiveOutputDescription outputDesc = new HiveOutputDescription();
outputDesc.setTableDesc(hiveTableDesc);
HiveInputDescription inputDesc = new HiveInputDescription();
inputDesc.setTableDesc(hiveTableDesc);
HiveTableSchema schema = HiveTableSchemas.lookup(hiveServer.getClient(), null, hiveTableDesc);
List<HiveWritableRecord> writeRecords = Lists.newArrayList();
HiveWritableRecord r1 = HiveRecordFactory.newWritableRecord(schema);
writeRecords.add(r1);
r1.set(1, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getShort(1));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(1, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getShort(1));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(2, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getInt(2));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(2, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getInt(2));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(2, 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getInt(2));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(3, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getLong(3));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(3, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getLong(3));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(3, 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getLong(3));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(3, 4L);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getLong(3));
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, 4L);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(4, 4.2f);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4.2, readRecord.getFloat(4), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, (byte) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, (short) 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, 4);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, 4L);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, 4.2f);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4.2, readRecord.getDouble(5), DELTA);
hiveServer.dropTable(hiveTableDesc.getTableName());
createTestTable();
r1.set(5, 4.2d);
HiveOutput.writeTable(outputDesc, writeRecords);
<DeepExtract>
Iterator<HiveReadableRecord> iter = HiveInput.readTable(inputDesc).iterator();
assertTrue(iter.hasNext());
HiveReadableRecord record = iter.next();
assertFalse(iter.hasNext());
return record;
</DeepExtract>
assertEquals(4.2, readRecord.getDouble(5), DELTA);
} | hive-io-experimental | positive | 3,592 |
public Chunk generateChunk() {
System.out.println("---------- Generate chunk: " + _x + ", " + _z);
SmartRandom random = new SmartRandom(new Random(generateSeedForChunk(_worldSeed, _x, _z)));
Chunk chunk = _chunkManager.getChunk(_x, _z, true, false, false);
chunk.setGenerated(true);
chunk.setLoading(true);
_heightMap = new int[Chunk.CHUNK_SIZE_HORIZONTAL][Chunk.CHUNK_SIZE_HORIZONTAL];
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; ++x) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; ++z) {
_heightMap[x][z] = _worldProvider.getHeightAt(x + chunk.getAbsoluteX(), z + chunk.getAbsoluteZ());
}
}
_temperatureMap = new int[Chunk.CHUNK_SIZE_HORIZONTAL][Chunk.CHUNK_SIZE_HORIZONTAL];
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; ++x) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; ++z) {
_temperatureMap[x][z] = _worldProvider.getTemperatureAt(x + chunk.getAbsoluteX(), z + chunk.getAbsoluteZ());
}
}
_humidityMap = new int[Chunk.CHUNK_SIZE_HORIZONTAL][Chunk.CHUNK_SIZE_HORIZONTAL];
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; ++x) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; ++z) {
_humidityMap[x][z] = _worldProvider.getHumidityAt(x + chunk.getAbsoluteX(), z + chunk.getAbsoluteZ());
}
}
float[][][] densityMap = new float[Chunk.CHUNK_SIZE_HORIZONTAL + 1][Chunk.CHUNK_SIZE_VERTICAL + 1][Chunk.CHUNK_SIZE_HORIZONTAL + 1];
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL + 1; x += SAMPLE_RATE_HORIZONTAL_DENSITY) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL + 1; z += SAMPLE_RATE_HORIZONTAL_DENSITY) {
for (int y = 0; y < Chunk.CHUNK_SIZE_VERTICAL + 1; y += SAMPLE_RATE_VERTICAL_DENSITY) {
densityMap[x][y][z] = generateDensity(random, x, y, z);
}
}
}
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; x++) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; z++) {
for (int y = 0; y < _heightMap[x][z]; y++) {
if (!(x % SAMPLE_RATE_HORIZONTAL_DENSITY == 0 && y % SAMPLE_RATE_VERTICAL_DENSITY == 0 && z % SAMPLE_RATE_HORIZONTAL_DENSITY == 0)) {
int offsetX = (x / SAMPLE_RATE_HORIZONTAL_DENSITY) * SAMPLE_RATE_HORIZONTAL_DENSITY;
int offsetY = (y / SAMPLE_RATE_VERTICAL_DENSITY) * SAMPLE_RATE_VERTICAL_DENSITY;
int offsetZ = (z / SAMPLE_RATE_HORIZONTAL_DENSITY) * SAMPLE_RATE_HORIZONTAL_DENSITY;
densityMap[x][y][z] = MathHelper.triLerp(x, y, z, densityMap[offsetX][offsetY][offsetZ], densityMap[offsetX][SAMPLE_RATE_VERTICAL_DENSITY + offsetY][offsetZ], densityMap[offsetX][offsetY][offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY], densityMap[offsetX][offsetY + SAMPLE_RATE_VERTICAL_DENSITY][offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY], densityMap[SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX][offsetY][offsetZ], densityMap[SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX][offsetY + SAMPLE_RATE_VERTICAL_DENSITY][offsetZ], densityMap[SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX][offsetY][offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY], densityMap[SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX][offsetY + SAMPLE_RATE_VERTICAL_DENSITY][offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY], offsetX, SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX, offsetY, SAMPLE_RATE_VERTICAL_DENSITY + offsetY, offsetZ, offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY);
}
}
}
}
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; x++) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; z++) {
int baseLevel = _heightMap[x][z];
Biome topBiome = _worldProvider.calculateBiome(_worldProvider.calculateTemperature(_temperatureMap[x][z], baseLevel), _worldProvider.getHumidityAt(x + chunk.getAbsoluteX(), baseLevel, z + chunk.getAbsoluteZ()));
for (int y = 0; y < Chunk.CHUNK_SIZE_VERTICAL && y <= baseLevel; y++) {
if (y < 4) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("bedrock"), (byte) 0, true, false, false);
continue;
}
int depth = baseLevel - y;
if (topBiome == Biome.DESERT && y >= baseLevel - 3) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("sand"), (byte) 0, true, false, false);
} else if (topBiome == Biome.SNOW && y == baseLevel) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("snow"), (byte) 0, true, false, false);
} else if ((topBiome == Biome.FOREST || topBiome == Biome.FIELDS) && y == baseLevel) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("grass"), (byte) 0, true, false, false);
} else {
float density = densityMap[x][y][z];
if (density < 7.3f && depth > 8) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("gravel"), (byte) 0, true, false, false);
} else if (density < 6.3f) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("dirt"), (byte) 0, true, false, false);
} else if (density < 9.0f) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("stone"), (byte) 0, true, false, false);
} else if (density < 9.5f && depth > 5) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("coal_ore"), (byte) 0, true, false, false);
} else if (density < 10.0f && depth > 10) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("iron_ore"), (byte) 0, true, false, false);
} else if (y < 16 && density < 13.0f) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("redstone_ore"), (byte) 0, true, false, false);
} else {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("stone"), (byte) 0, true, false, false);
}
}
}
}
}
{
int treeCount = MathHelper.round((1.0f - random.exponentialRandom(1.0f, 3)) * 12.0f);
TreeGenerator gen = new TreeGenerator(random.randomLong());
trees: for (int i = 0; i < treeCount; ++i) {
int x = chunk.getAbsoluteX() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL);
int z = chunk.getAbsoluteZ() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL);
for (TreeDefinition treeDef : _worldProvider.getTrees()) {
float xDiff = x - treeDef.x;
float zDiff = z - treeDef.z;
float distSq = xDiff * xDiff + zDiff * zDiff;
if (distSq < 60) {
continue trees;
}
}
int type = -1;
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()];
{
Biome biome = _worldProvider.getBiomeAt(x, y, z);
if (biome == Biome.FIELDS) {
continue;
}
if (biome == Biome.FOREST) {
gen.generateNiceBroadLeavedTree(chunk, x, y, z);
type = 0;
} else if (biome == Biome.DESERT) {
if (random.randomBoolean()) {
gen.generateCactus(chunk, x, y + 1, z);
type = 1;
}
} else if (biome == Biome.SNOW) {
gen.generatePinophyta(chunk, x, y, z);
type = 2;
}
if (type != -1) {
_worldProvider.getTrees().add(new TreeDefinition(x, y, z, type));
}
}
}
}
{
int grassCount = random.randomInt(5, 10);
for (int i = 0; i < grassCount; ++i) {
int x = chunk.getAbsoluteX() + random.randomInt(0, Chunk.CHUNK_SIZE_HORIZONTAL);
int z = chunk.getAbsoluteZ() + random.randomInt(0, Chunk.CHUNK_SIZE_HORIZONTAL);
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()];
Biome biome = _worldProvider.getBiomeAt(x, y, z);
if (biome == Biome.FIELDS || biome == Biome.FOREST) {
if (chunk.getBlockTypeAbsolute(x, y + 1, z, false, false, false) == 0) {
chunk.setSpecialBlockAbsolute(x, y + 1, z, BlockConstructor.construct(x, y + 1, z, chunk, _blockManager.blockID("tallgrass"), (byte) random.randomInt(6)), false, false, false);
}
}
}
}
{
int flowerCount = random.randomInt(5, 10);
for (int i = 0; i < flowerCount; ++i) {
int x = chunk.getAbsoluteX() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL);
int z = chunk.getAbsoluteZ() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL);
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()];
Biome biome = _worldProvider.getBiomeAt(x, y, z);
if (biome == Biome.FIELDS || biome == Biome.FOREST) {
if (chunk.getBlockTypeAbsolute(x, y + 1, z, false, false, false) == 0) {
if (random.randomBoolean()) {
chunk.setSpecialBlockAbsolute(x, y + 1, z, BlockConstructor.construct(x, y + 1, z, chunk, _blockManager.blockID("redflower"), (byte) 0), false, false, false);
} else {
chunk.setSpecialBlockAbsolute(x, y + 1, z, BlockConstructor.construct(x, y + 1, z, chunk, _blockManager.blockID("yellowflower"), (byte) 0), false, false, false);
}
}
}
}
}
if (random.randomInt(35) == -1) {
FloatingIslandGenerator gen = new FloatingIslandGenerator(_worldProvider);
int x = chunk.getAbsoluteX() + random.randomInt(1);
int z = chunk.getAbsoluteZ() + random.randomInt(1);
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()];
gen.generateNiceFloatingIsland(chunk, x, y + random.randomInt(40, 80), z);
}
if (random.randomInt(10) == -1) {
BuildingGenerator gen = new BuildingGenerator();
int x = chunk.getAbsoluteX() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL / 2);
int z = chunk.getAbsoluteZ() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL / 2);
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()] + 1;
if (_worldProvider.getBiomeAt(x, y, z) == Biome.FIELDS) {
System.out.println("Generate building at (" + x + ", " + y + ", " + z + ")");
gen.generateHouseAt(chunk, x, y, z);
}
}
chunk.setLoading(false);
_chunkManager.assignNeighbors(chunk);
return chunk;
} | public Chunk generateChunk() {
System.out.println("---------- Generate chunk: " + _x + ", " + _z);
SmartRandom random = new SmartRandom(new Random(generateSeedForChunk(_worldSeed, _x, _z)));
Chunk chunk = _chunkManager.getChunk(_x, _z, true, false, false);
chunk.setGenerated(true);
chunk.setLoading(true);
_heightMap = new int[Chunk.CHUNK_SIZE_HORIZONTAL][Chunk.CHUNK_SIZE_HORIZONTAL];
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; ++x) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; ++z) {
_heightMap[x][z] = _worldProvider.getHeightAt(x + chunk.getAbsoluteX(), z + chunk.getAbsoluteZ());
}
}
_temperatureMap = new int[Chunk.CHUNK_SIZE_HORIZONTAL][Chunk.CHUNK_SIZE_HORIZONTAL];
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; ++x) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; ++z) {
_temperatureMap[x][z] = _worldProvider.getTemperatureAt(x + chunk.getAbsoluteX(), z + chunk.getAbsoluteZ());
}
}
_humidityMap = new int[Chunk.CHUNK_SIZE_HORIZONTAL][Chunk.CHUNK_SIZE_HORIZONTAL];
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; ++x) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; ++z) {
_humidityMap[x][z] = _worldProvider.getHumidityAt(x + chunk.getAbsoluteX(), z + chunk.getAbsoluteZ());
}
}
float[][][] densityMap = new float[Chunk.CHUNK_SIZE_HORIZONTAL + 1][Chunk.CHUNK_SIZE_VERTICAL + 1][Chunk.CHUNK_SIZE_HORIZONTAL + 1];
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL + 1; x += SAMPLE_RATE_HORIZONTAL_DENSITY) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL + 1; z += SAMPLE_RATE_HORIZONTAL_DENSITY) {
for (int y = 0; y < Chunk.CHUNK_SIZE_VERTICAL + 1; y += SAMPLE_RATE_VERTICAL_DENSITY) {
densityMap[x][y][z] = generateDensity(random, x, y, z);
}
}
}
<DeepExtract>
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; x++) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; z++) {
for (int y = 0; y < _heightMap[x][z]; y++) {
if (!(x % SAMPLE_RATE_HORIZONTAL_DENSITY == 0 && y % SAMPLE_RATE_VERTICAL_DENSITY == 0 && z % SAMPLE_RATE_HORIZONTAL_DENSITY == 0)) {
int offsetX = (x / SAMPLE_RATE_HORIZONTAL_DENSITY) * SAMPLE_RATE_HORIZONTAL_DENSITY;
int offsetY = (y / SAMPLE_RATE_VERTICAL_DENSITY) * SAMPLE_RATE_VERTICAL_DENSITY;
int offsetZ = (z / SAMPLE_RATE_HORIZONTAL_DENSITY) * SAMPLE_RATE_HORIZONTAL_DENSITY;
densityMap[x][y][z] = MathHelper.triLerp(x, y, z, densityMap[offsetX][offsetY][offsetZ], densityMap[offsetX][SAMPLE_RATE_VERTICAL_DENSITY + offsetY][offsetZ], densityMap[offsetX][offsetY][offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY], densityMap[offsetX][offsetY + SAMPLE_RATE_VERTICAL_DENSITY][offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY], densityMap[SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX][offsetY][offsetZ], densityMap[SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX][offsetY + SAMPLE_RATE_VERTICAL_DENSITY][offsetZ], densityMap[SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX][offsetY][offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY], densityMap[SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX][offsetY + SAMPLE_RATE_VERTICAL_DENSITY][offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY], offsetX, SAMPLE_RATE_HORIZONTAL_DENSITY + offsetX, offsetY, SAMPLE_RATE_VERTICAL_DENSITY + offsetY, offsetZ, offsetZ + SAMPLE_RATE_HORIZONTAL_DENSITY);
}
}
}
}
</DeepExtract>
for (int x = 0; x < Chunk.CHUNK_SIZE_HORIZONTAL; x++) {
for (int z = 0; z < Chunk.CHUNK_SIZE_HORIZONTAL; z++) {
int baseLevel = _heightMap[x][z];
Biome topBiome = _worldProvider.calculateBiome(_worldProvider.calculateTemperature(_temperatureMap[x][z], baseLevel), _worldProvider.getHumidityAt(x + chunk.getAbsoluteX(), baseLevel, z + chunk.getAbsoluteZ()));
for (int y = 0; y < Chunk.CHUNK_SIZE_VERTICAL && y <= baseLevel; y++) {
if (y < 4) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("bedrock"), (byte) 0, true, false, false);
continue;
}
int depth = baseLevel - y;
if (topBiome == Biome.DESERT && y >= baseLevel - 3) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("sand"), (byte) 0, true, false, false);
} else if (topBiome == Biome.SNOW && y == baseLevel) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("snow"), (byte) 0, true, false, false);
} else if ((topBiome == Biome.FOREST || topBiome == Biome.FIELDS) && y == baseLevel) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("grass"), (byte) 0, true, false, false);
} else {
float density = densityMap[x][y][z];
if (density < 7.3f && depth > 8) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("gravel"), (byte) 0, true, false, false);
} else if (density < 6.3f) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("dirt"), (byte) 0, true, false, false);
} else if (density < 9.0f) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("stone"), (byte) 0, true, false, false);
} else if (density < 9.5f && depth > 5) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("coal_ore"), (byte) 0, true, false, false);
} else if (density < 10.0f && depth > 10) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("iron_ore"), (byte) 0, true, false, false);
} else if (y < 16 && density < 13.0f) {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("redstone_ore"), (byte) 0, true, false, false);
} else {
chunk.setDefaultBlockRelative(x, y, z, BlockManager.getInstance().getBlockType("stone"), (byte) 0, true, false, false);
}
}
}
}
}
{
int treeCount = MathHelper.round((1.0f - random.exponentialRandom(1.0f, 3)) * 12.0f);
TreeGenerator gen = new TreeGenerator(random.randomLong());
trees: for (int i = 0; i < treeCount; ++i) {
int x = chunk.getAbsoluteX() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL);
int z = chunk.getAbsoluteZ() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL);
for (TreeDefinition treeDef : _worldProvider.getTrees()) {
float xDiff = x - treeDef.x;
float zDiff = z - treeDef.z;
float distSq = xDiff * xDiff + zDiff * zDiff;
if (distSq < 60) {
continue trees;
}
}
int type = -1;
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()];
{
Biome biome = _worldProvider.getBiomeAt(x, y, z);
if (biome == Biome.FIELDS) {
continue;
}
if (biome == Biome.FOREST) {
gen.generateNiceBroadLeavedTree(chunk, x, y, z);
type = 0;
} else if (biome == Biome.DESERT) {
if (random.randomBoolean()) {
gen.generateCactus(chunk, x, y + 1, z);
type = 1;
}
} else if (biome == Biome.SNOW) {
gen.generatePinophyta(chunk, x, y, z);
type = 2;
}
if (type != -1) {
_worldProvider.getTrees().add(new TreeDefinition(x, y, z, type));
}
}
}
}
{
int grassCount = random.randomInt(5, 10);
for (int i = 0; i < grassCount; ++i) {
int x = chunk.getAbsoluteX() + random.randomInt(0, Chunk.CHUNK_SIZE_HORIZONTAL);
int z = chunk.getAbsoluteZ() + random.randomInt(0, Chunk.CHUNK_SIZE_HORIZONTAL);
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()];
Biome biome = _worldProvider.getBiomeAt(x, y, z);
if (biome == Biome.FIELDS || biome == Biome.FOREST) {
if (chunk.getBlockTypeAbsolute(x, y + 1, z, false, false, false) == 0) {
chunk.setSpecialBlockAbsolute(x, y + 1, z, BlockConstructor.construct(x, y + 1, z, chunk, _blockManager.blockID("tallgrass"), (byte) random.randomInt(6)), false, false, false);
}
}
}
}
{
int flowerCount = random.randomInt(5, 10);
for (int i = 0; i < flowerCount; ++i) {
int x = chunk.getAbsoluteX() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL);
int z = chunk.getAbsoluteZ() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL);
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()];
Biome biome = _worldProvider.getBiomeAt(x, y, z);
if (biome == Biome.FIELDS || biome == Biome.FOREST) {
if (chunk.getBlockTypeAbsolute(x, y + 1, z, false, false, false) == 0) {
if (random.randomBoolean()) {
chunk.setSpecialBlockAbsolute(x, y + 1, z, BlockConstructor.construct(x, y + 1, z, chunk, _blockManager.blockID("redflower"), (byte) 0), false, false, false);
} else {
chunk.setSpecialBlockAbsolute(x, y + 1, z, BlockConstructor.construct(x, y + 1, z, chunk, _blockManager.blockID("yellowflower"), (byte) 0), false, false, false);
}
}
}
}
}
if (random.randomInt(35) == -1) {
FloatingIslandGenerator gen = new FloatingIslandGenerator(_worldProvider);
int x = chunk.getAbsoluteX() + random.randomInt(1);
int z = chunk.getAbsoluteZ() + random.randomInt(1);
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()];
gen.generateNiceFloatingIsland(chunk, x, y + random.randomInt(40, 80), z);
}
if (random.randomInt(10) == -1) {
BuildingGenerator gen = new BuildingGenerator();
int x = chunk.getAbsoluteX() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL / 2);
int z = chunk.getAbsoluteZ() + random.randomInt(Chunk.CHUNK_SIZE_HORIZONTAL / 2);
int y = _heightMap[x - chunk.getAbsoluteX()][z - chunk.getAbsoluteZ()] + 1;
if (_worldProvider.getBiomeAt(x, y, z) == Biome.FIELDS) {
System.out.println("Generate building at (" + x + ", " + y + ", " + z + ")");
gen.generateHouseAt(chunk, x, y, z);
}
}
chunk.setLoading(false);
_chunkManager.assignNeighbors(chunk);
return chunk;
} | CraftMania | positive | 3,593 |
@Override
public <T> int insert(T entity, IncludeType includeType) {
if (entity == null)
return -1;
getInterceptorChain().beforePasreEntity(entity, SuidType.INSERT);
String sql = getObjToSQLRich().toInsertSQL(entity, includeType);
if (entity == null)
return;
HoneyContext.regEntityClass(entity.getClass());
sql = doAfterCompleteSql(sql);
Logger.logSQL("insert SQL: ", sql);
int r = getBeeSql().modify(sql);
doBeforeReturn();
return r;
} | @Override
public <T> int insert(T entity, IncludeType includeType) {
if (entity == null)
return -1;
getInterceptorChain().beforePasreEntity(entity, SuidType.INSERT);
String sql = getObjToSQLRich().toInsertSQL(entity, includeType);
<DeepExtract>
if (entity == null)
return;
HoneyContext.regEntityClass(entity.getClass());
</DeepExtract>
sql = doAfterCompleteSql(sql);
Logger.logSQL("insert SQL: ", sql);
int r = getBeeSql().modify(sql);
doBeforeReturn();
return r;
} | honey | positive | 3,595 |
@Override
public void onError(int response, @Nonnull Exception e) {
Check.isTrue(Thread.holdsLock(mLock), "Must be synchronized");
countDown(1);
} | @Override
public void onError(int response, @Nonnull Exception e) {
<DeepExtract>
Check.isTrue(Thread.holdsLock(mLock), "Must be synchronized");
countDown(1);
</DeepExtract>
} | android-checkout | positive | 3,596 |
public long dateHeader(final String name, final long defaultValue) throws HttpRequestException {
try {
return closeOutput();
} catch (IOException e) {
throw new HttpRequestException(e);
}
return getConnection().getHeaderFieldDate(name, defaultValue);
} | public long dateHeader(final String name, final long defaultValue) throws HttpRequestException {
<DeepExtract>
try {
return closeOutput();
} catch (IOException e) {
throw new HttpRequestException(e);
}
</DeepExtract>
return getConnection().getHeaderFieldDate(name, defaultValue);
} | crud-rest-gen | positive | 3,597 |
@Override
public void onCreate() {
super.onCreate();
app = this;
P2PSpecial.getInstance().init(app, APPID, APPToken, APPVersion);
} | @Override
public void onCreate() {
super.onCreate();
app = this;
<DeepExtract>
P2PSpecial.getInstance().init(app, APPID, APPToken, APPVersion);
</DeepExtract>
} | GwellDemo | positive | 3,598 |
public void setStrokeWidth(float strokeWidth) {
mStrokeWidth = strokeWidth;
mPaint.setStrokeWidth(strokeWidth);
mCallback.invalidateDrawable(null);
} | public void setStrokeWidth(float strokeWidth) {
mStrokeWidth = strokeWidth;
mPaint.setStrokeWidth(strokeWidth);
<DeepExtract>
mCallback.invalidateDrawable(null);
</DeepExtract>
} | TencentNews | positive | 3,599 |
public CommandLine setToggleBooleanFlags(boolean newValue) {
this.toggleBooleanFlags = newValue;
return this;
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setToggleBooleanFlags(newValue);
}
return this;
} | public CommandLine setToggleBooleanFlags(boolean newValue) {
<DeepExtract>
this.toggleBooleanFlags = newValue;
return this;
</DeepExtract>
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setToggleBooleanFlags(newValue);
}
return this;
} | eclipstyle | positive | 3,600 |
@Test
public void getSubscriptions_forScreenName() {
mockServer.expect(requestTo("https://api.twitter.com/1.1/lists/subscriptions.json?screen_name=habuma")).andExpect(method(GET)).andRespond(withSuccess(jsonResource("list-of-lists"), APPLICATION_JSON));
assertEquals(2, twitter.listOperations().getSubscriptions("habuma").size());
UserList list1 = twitter.listOperations().getSubscriptions("habuma").get(0);
assertEquals(40842137, list1.getId());
assertEquals("forFun2", list1.getName());
assertEquals("@habuma/forfun2", list1.getFullName());
assertEquals("forfun2", list1.getSlug());
assertEquals("Just for fun, too", list1.getDescription());
assertEquals(3, list1.getMemberCount());
assertEquals(0, list1.getSubscriberCount());
assertEquals("/habuma/forfun2", list1.getUriPath());
assertTrue(list1.isPublic());
UserList list2 = twitter.listOperations().getSubscriptions("habuma").get(1);
assertEquals(40841803, list2.getId());
assertEquals("forFun", list2.getName());
assertEquals("@habuma/forfun", list2.getFullName());
assertEquals("forfun", list2.getSlug());
assertEquals("Just for fun", list2.getDescription());
assertEquals(22, list2.getMemberCount());
assertEquals(100, list2.getSubscriberCount());
assertEquals("/habuma/forfun", list2.getUriPath());
assertFalse(list2.isPublic());
} | @Test
public void getSubscriptions_forScreenName() {
mockServer.expect(requestTo("https://api.twitter.com/1.1/lists/subscriptions.json?screen_name=habuma")).andExpect(method(GET)).andRespond(withSuccess(jsonResource("list-of-lists"), APPLICATION_JSON));
<DeepExtract>
assertEquals(2, twitter.listOperations().getSubscriptions("habuma").size());
UserList list1 = twitter.listOperations().getSubscriptions("habuma").get(0);
assertEquals(40842137, list1.getId());
assertEquals("forFun2", list1.getName());
assertEquals("@habuma/forfun2", list1.getFullName());
assertEquals("forfun2", list1.getSlug());
assertEquals("Just for fun, too", list1.getDescription());
assertEquals(3, list1.getMemberCount());
assertEquals(0, list1.getSubscriberCount());
assertEquals("/habuma/forfun2", list1.getUriPath());
assertTrue(list1.isPublic());
UserList list2 = twitter.listOperations().getSubscriptions("habuma").get(1);
assertEquals(40841803, list2.getId());
assertEquals("forFun", list2.getName());
assertEquals("@habuma/forfun", list2.getFullName());
assertEquals("forfun", list2.getSlug());
assertEquals("Just for fun", list2.getDescription());
assertEquals(22, list2.getMemberCount());
assertEquals(100, list2.getSubscriberCount());
assertEquals("/habuma/forfun", list2.getUriPath());
assertFalse(list2.isPublic());
</DeepExtract>
} | spring-social-twitter | positive | 3,601 |
public static double JaccardIndexIDImages(Element e1, Element e2, boolean split) {
Hashtable<String, Integer> hash1 = getLinksOrImage(e1, split, "img", "ID");
Hashtable<String, Integer> hash2 = getLinksOrImage(e2, split, "img", "ID");
int nbCommon = 0;
for (String s : hash1.keySet()) {
if (hash2.containsKey(s)) {
++nbCommon;
}
}
int a = (hash1.size() + hash2.size() - nbCommon);
if (a == 0) {
return 0;
}
return ((double) nbCommon) / a;
} | public static double JaccardIndexIDImages(Element e1, Element e2, boolean split) {
<DeepExtract>
Hashtable<String, Integer> hash1 = getLinksOrImage(e1, split, "img", "ID");
Hashtable<String, Integer> hash2 = getLinksOrImage(e2, split, "img", "ID");
int nbCommon = 0;
for (String s : hash1.keySet()) {
if (hash2.containsKey(s)) {
++nbCommon;
}
}
int a = (hash1.size() + hash2.size() - nbCommon);
if (a == 0) {
return 0;
}
return ((double) nbCommon) / a;
</DeepExtract>
} | pagelyzer | positive | 3,602 |
public Settings build() {
String overridesFiles = System.getProperty(OVERRIDES_FILE_SYSTEM_PROPERTY);
if (!Strings.isNullOrEmpty(overridesFiles)) {
String[] files = overridesFiles.split(",");
for (String file : files) {
if (!Strings.isNullOrEmpty(file)) {
file = file.trim();
log.info(String.format("loading overrides from %s", file));
loadFromFile(file);
}
}
} else {
log.info("no overrides file specified (use -Dsettings to provide one)");
}
Properties p = new Properties();
p.putAll(System.getProperties());
substituteVariables(p);
for (Map.Entry<Object, Object> entry : p.entrySet()) {
Object current = properties.get(entry.getKey());
if (current != null) {
log.info(String.format("override setting '%s' with value '%s' from system properties (previous value was '%s')", entry.getKey(), entry.getValue(), current));
properties.put(entry.getKey(), entry.getValue());
}
}
return settings;
} | public Settings build() {
<DeepExtract>
String overridesFiles = System.getProperty(OVERRIDES_FILE_SYSTEM_PROPERTY);
if (!Strings.isNullOrEmpty(overridesFiles)) {
String[] files = overridesFiles.split(",");
for (String file : files) {
if (!Strings.isNullOrEmpty(file)) {
file = file.trim();
log.info(String.format("loading overrides from %s", file));
loadFromFile(file);
}
}
} else {
log.info("no overrides file specified (use -Dsettings to provide one)");
}
Properties p = new Properties();
p.putAll(System.getProperties());
substituteVariables(p);
for (Map.Entry<Object, Object> entry : p.entrySet()) {
Object current = properties.get(entry.getKey());
if (current != null) {
log.info(String.format("override setting '%s' with value '%s' from system properties (previous value was '%s')", entry.getKey(), entry.getValue(), current));
properties.put(entry.getKey(), entry.getValue());
}
}
</DeepExtract>
return settings;
} | commons | positive | 3,604 |
public static Date plusMonths(Date date, long amountToAdd) {
Objects.requireNonNull(date, "temporal");
return date.plus(amountToAdd, ChronoUnit.MONTHS);
} | public static Date plusMonths(Date date, long amountToAdd) {
<DeepExtract>
Objects.requireNonNull(date, "temporal");
return date.plus(amountToAdd, ChronoUnit.MONTHS);
</DeepExtract>
} | jstarcraft-nlp | positive | 3,605 |
public Table getVerboseTable(String name) throws JSONException, IOException {
String url = tableMap.get(name);
if (true)
url += "?v=true";
JSONObject jsonObject = Helper.getJSONObject(url);
Table newTable = new Table(name, jsonObject, true);
return newTable;
} | public Table getVerboseTable(String name) throws JSONException, IOException {
<DeepExtract>
String url = tableMap.get(name);
if (true)
url += "?v=true";
JSONObject jsonObject = Helper.getJSONObject(url);
Table newTable = new Table(name, jsonObject, true);
return newTable;
</DeepExtract>
} | resthub | positive | 3,606 |
public void editImage(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, IMAGE_PICKER_REQUEST);
}
} | public void editImage(View view) {
<DeepExtract>
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, IMAGE_PICKER_REQUEST);
}
</DeepExtract>
} | artcodes-android | positive | 3,607 |
public void uploadAction(String str) throws org.apache.thrift.TException {
uploadAction_args args = new uploadAction_args();
args.setStr(str);
sendBase("uploadAction", args);
uploadAction_result result = new uploadAction_result();
receiveBase(result, "uploadAction");
return;
} | public void uploadAction(String str) throws org.apache.thrift.TException {
uploadAction_args args = new uploadAction_args();
args.setStr(str);
sendBase("uploadAction", args);
<DeepExtract>
uploadAction_result result = new uploadAction_result();
receiveBase(result, "uploadAction");
return;
</DeepExtract>
} | netty-thrift | positive | 3,608 |
public static Entity executeQueryCount(Connection conn, String sql) throws SQLException {
Entity entity = new Entity();
this.sql = sql;
long start = System.currentTimeMillis();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
entity.setQueryTime(System.currentTimeMillis() - start);
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 0; i < columns; ++i) {
rs.getObject(i + 1);
}
}
} finally {
JDBCUtils.close(rs, stmt);
}
this.deserializeTime = System.currentTimeMillis() - start - entity.getQueryTime();
return entity;
} | public static Entity executeQueryCount(Connection conn, String sql) throws SQLException {
Entity entity = new Entity();
this.sql = sql;
long start = System.currentTimeMillis();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
entity.setQueryTime(System.currentTimeMillis() - start);
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 0; i < columns; ++i) {
rs.getObject(i + 1);
}
}
} finally {
JDBCUtils.close(rs, stmt);
}
<DeepExtract>
this.deserializeTime = System.currentTimeMillis() - start - entity.getQueryTime();
</DeepExtract>
return entity;
} | teiid-embedded-examples | positive | 3,609 |
@Test
public void doCreate__servletContextIsNotYetAvailableViaSrpingUtils_vaadinApplicationConfigurationHasSpringPropertiesPrefixedByVaadin() {
Mockito.when(webAppContext.getServletContext()).thenReturn(servletContext);
Mockito.when(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).thenReturn(null);
new SpringApplicationContextInit().setApplicationContext(webAppContext);
String prefix = "foo_";
SpringServlet.PROPERTY_NAMES.stream().forEach(name -> Mockito.when(env.getProperty("vaadin." + name)).thenReturn(prefix + name));
Map<String, String> props = new HashMap<>();
ApplicationConfiguration config = factory.doCreate(context, null, props);
for (String prop : SpringServlet.PROPERTY_NAMES) {
Assert.assertEquals("'" + prop + "' property is not available via " + ApplicationConfiguration.class, prefix + prop, config.getStringProperty(prop, null));
Assert.assertEquals("'" + prop + "' property is not set in the properties map passed to the " + ApplicationConfiguration.class.getSimpleName() + " CTOR", prefix + prop, props.get(prop));
}
Assert.assertEquals(SpringServlet.PROPERTY_NAMES.size(), props.size());
} | @Test
public void doCreate__servletContextIsNotYetAvailableViaSrpingUtils_vaadinApplicationConfigurationHasSpringPropertiesPrefixedByVaadin() {
Mockito.when(webAppContext.getServletContext()).thenReturn(servletContext);
Mockito.when(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).thenReturn(null);
new SpringApplicationContextInit().setApplicationContext(webAppContext);
<DeepExtract>
String prefix = "foo_";
SpringServlet.PROPERTY_NAMES.stream().forEach(name -> Mockito.when(env.getProperty("vaadin." + name)).thenReturn(prefix + name));
Map<String, String> props = new HashMap<>();
ApplicationConfiguration config = factory.doCreate(context, null, props);
for (String prop : SpringServlet.PROPERTY_NAMES) {
Assert.assertEquals("'" + prop + "' property is not available via " + ApplicationConfiguration.class, prefix + prop, config.getStringProperty(prop, null));
Assert.assertEquals("'" + prop + "' property is not set in the properties map passed to the " + ApplicationConfiguration.class.getSimpleName() + " CTOR", prefix + prop, props.get(prop));
}
Assert.assertEquals(SpringServlet.PROPERTY_NAMES.size(), props.size());
</DeepExtract>
} | spring | positive | 3,610 |
public int validate(String realm, String returnTo, boolean compatibility, boolean enforceRpId) {
if (DEBUG)
_log.debug("Verifying realm: " + realm + " on return URL: " + returnTo);
URL realmUrl;
try {
realmUrl = new URL(realm);
} catch (MalformedURLException e) {
_log.error("Invalid realm URL: " + realm, e);
result = MALFORMED_REALM;
}
String realmDomain = realmUrl.getHost();
if (isDeniedRealmDomain(realmDomain)) {
_log.warn("Blacklisted realm domain: " + realmDomain);
result = DENIED_REALM;
}
URL returnToUrl;
try {
returnToUrl = new URL(returnTo);
} catch (MalformedURLException e) {
_log.error("Invalid return URL: " + returnTo);
result = MALFORMED_RETURN_TO_URL;
}
if (realmUrl.getRef() != null) {
if (DEBUG)
_log.debug("Realm verification failed: " + "URL fragments are not allowed.");
result = FRAGMENT_NOT_ALLOWED;
}
if (!realmUrl.getProtocol().equalsIgnoreCase(returnToUrl.getProtocol())) {
if (DEBUG)
_log.debug("Realm verification failed: " + "protocol mismatch.");
result = PROTOCOL_MISMATCH;
}
if (!domainMatch(realmDomain, returnToUrl.getHost())) {
if (DEBUG)
_log.debug("Realm verification failed: " + "domain mismatch.");
result = DOMAIN_MISMATCH;
}
if (!portMatch(realmUrl, returnToUrl)) {
if (DEBUG)
_log.debug("Realm verification failed: " + "port mismatch.");
result = PORT_MISMATCH;
}
if (!pathMatch(realmUrl, returnToUrl)) {
if (DEBUG)
_log.debug("Realm verification failed: " + "path mismatch.");
result = PATH_MISMATCH;
}
_log.info("Return URL: " + returnTo + " matches realm: " + realm);
return OK;
if (OK != result) {
_log.error("Return URL: " + returnTo + " does not match realm: " + realm);
return result;
}
if (!compatibility && enforceRpId) {
result = validateRpId(realm, returnTo);
if (OK != result)
_log.error("Failed to validate return URL: " + returnTo + " against endpoints discovered from the RP's realm.");
} else if (!compatibility && !enforceRpId && _isOP) {
_log.warn("RP discovery / realm validation disabled; " + "this option SHOULD be enabled for OPs");
}
return result;
} | public int validate(String realm, String returnTo, boolean compatibility, boolean enforceRpId) {
<DeepExtract>
if (DEBUG)
_log.debug("Verifying realm: " + realm + " on return URL: " + returnTo);
URL realmUrl;
try {
realmUrl = new URL(realm);
} catch (MalformedURLException e) {
_log.error("Invalid realm URL: " + realm, e);
result = MALFORMED_REALM;
}
String realmDomain = realmUrl.getHost();
if (isDeniedRealmDomain(realmDomain)) {
_log.warn("Blacklisted realm domain: " + realmDomain);
result = DENIED_REALM;
}
URL returnToUrl;
try {
returnToUrl = new URL(returnTo);
} catch (MalformedURLException e) {
_log.error("Invalid return URL: " + returnTo);
result = MALFORMED_RETURN_TO_URL;
}
if (realmUrl.getRef() != null) {
if (DEBUG)
_log.debug("Realm verification failed: " + "URL fragments are not allowed.");
result = FRAGMENT_NOT_ALLOWED;
}
if (!realmUrl.getProtocol().equalsIgnoreCase(returnToUrl.getProtocol())) {
if (DEBUG)
_log.debug("Realm verification failed: " + "protocol mismatch.");
result = PROTOCOL_MISMATCH;
}
if (!domainMatch(realmDomain, returnToUrl.getHost())) {
if (DEBUG)
_log.debug("Realm verification failed: " + "domain mismatch.");
result = DOMAIN_MISMATCH;
}
if (!portMatch(realmUrl, returnToUrl)) {
if (DEBUG)
_log.debug("Realm verification failed: " + "port mismatch.");
result = PORT_MISMATCH;
}
if (!pathMatch(realmUrl, returnToUrl)) {
if (DEBUG)
_log.debug("Realm verification failed: " + "path mismatch.");
result = PATH_MISMATCH;
}
_log.info("Return URL: " + returnTo + " matches realm: " + realm);
return OK;
</DeepExtract>
if (OK != result) {
_log.error("Return URL: " + returnTo + " does not match realm: " + realm);
return result;
}
if (!compatibility && enforceRpId) {
result = validateRpId(realm, returnTo);
if (OK != result)
_log.error("Failed to validate return URL: " + returnTo + " against endpoints discovered from the RP's realm.");
} else if (!compatibility && !enforceRpId && _isOP) {
_log.warn("RP discovery / realm validation disabled; " + "this option SHOULD be enabled for OPs");
}
return result;
} | openid4java | positive | 3,611 |
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteRows(modelTable);
} | public void actionPerformed(java.awt.event.ActionEvent evt) {
<DeepExtract>
deleteRows(modelTable);
</DeepExtract>
} | fuelphp-netbeans | positive | 3,612 |
public void widgetSelected(final SelectionEvent e) {
final SourceSelection selection = getSelection();
final Object[] objects = list.getListeners();
for (final Object object : objects) {
final ITextSourceListener listener = (ITextSourceListener) object;
listener.selectionChanged(selection);
}
} | public void widgetSelected(final SelectionEvent e) {
<DeepExtract>
final SourceSelection selection = getSelection();
final Object[] objects = list.getListeners();
for (final Object object : objects) {
final ITextSourceListener listener = (ITextSourceListener) object;
listener.selectionChanged(selection);
}
</DeepExtract>
} | glance | positive | 3,613 |
public RecvMessage receive(String xml) {
XmlReaders readers = XmlReaders.create(xml);
RecvMessage msg = parse2RecvMessage(readers);
RecvMessageType type = RecvMessageType.from(msg.getMsgType());
if (RecvMessageType.EVENT == type) {
return parse2RecvEvent(readers, msg);
} else {
return parse2RecvMsg(readers, msg);
}
} | public RecvMessage receive(String xml) {
XmlReaders readers = XmlReaders.create(xml);
<DeepExtract>
RecvMessage msg = parse2RecvMessage(readers);
RecvMessageType type = RecvMessageType.from(msg.getMsgType());
if (RecvMessageType.EVENT == type) {
return parse2RecvEvent(readers, msg);
} else {
return parse2RecvMsg(readers, msg);
}
</DeepExtract>
} | wechat | positive | 3,614 |
public void run() {
PImage shape = RainbowStudio.pApplet.loadImage("images/spin-disc-k=1.png");
PImage shape2 = RainbowStudio.pApplet.createImage(shape.width, shape.width, RGB);
shape.loadPixels();
shape2.loadPixels();
for (int x = 0; x < shape.width; x++) {
for (int y = 0; y < shape.width; y++) {
shape2.pixels[x + shape.width * y] = shape.pixels[(shape.width - 1 - x) + shape.width * y];
}
}
shape2.updatePixels();
Random rnd = new Random();
PImage palette = RainbowStudio.pApplet.loadImage("images/lab-square-lookup.png");
palette.loadPixels();
for (int i = 0; i < BALL_COUNT; i++) {
PImage img = RainbowStudio.pApplet.createImage(shape.width, shape.width, RGB);
img.loadPixels();
int x = rnd.nextInt(palette.width);
int y = rnd.nextInt(palette.width);
int c = palette.pixels[x * palette.width + y];
for (int p = 0; p < img.pixels.length; p++) {
img.pixels[p] = c;
}
img.mask(i % 2 == 0 ? shape : shape2);
synchronized (textures) {
textures[i] = img;
}
}
} | public void run() {
<DeepExtract>
PImage shape = RainbowStudio.pApplet.loadImage("images/spin-disc-k=1.png");
PImage shape2 = RainbowStudio.pApplet.createImage(shape.width, shape.width, RGB);
shape.loadPixels();
shape2.loadPixels();
for (int x = 0; x < shape.width; x++) {
for (int y = 0; y < shape.width; y++) {
shape2.pixels[x + shape.width * y] = shape.pixels[(shape.width - 1 - x) + shape.width * y];
}
}
shape2.updatePixels();
Random rnd = new Random();
PImage palette = RainbowStudio.pApplet.loadImage("images/lab-square-lookup.png");
palette.loadPixels();
for (int i = 0; i < BALL_COUNT; i++) {
PImage img = RainbowStudio.pApplet.createImage(shape.width, shape.width, RGB);
img.loadPixels();
int x = rnd.nextInt(palette.width);
int y = rnd.nextInt(palette.width);
int c = palette.pixels[x * palette.width + y];
for (int p = 0; p < img.pixels.length; p++) {
img.pixels[p] = c;
}
img.mask(i % 2 == 0 ? shape : shape2);
synchronized (textures) {
textures[i] = img;
}
}
</DeepExtract>
} | RainbowStudio | positive | 3,615 |
public final <U> Ix<U> ofType(final Class<U> token) {
if (Interactive.ofType(it, token) instanceof Ix) {
return (Ix<T>) Interactive.ofType(it, token);
}
return new Ix<T>(Interactive.ofType(it, token));
} | public final <U> Ix<U> ofType(final Class<U> token) {
<DeepExtract>
if (Interactive.ofType(it, token) instanceof Ix) {
return (Ix<T>) Interactive.ofType(it, token);
}
return new Ix<T>(Interactive.ofType(it, token));
</DeepExtract>
} | ixjava | positive | 3,616 |
@CodeTranslate
public void invokeMethodWithIntReturn() {
MethodExpressionTest.count();
return 1;
} | @CodeTranslate
public void invokeMethodWithIntReturn() {
<DeepExtract>
MethodExpressionTest.count();
return 1;
</DeepExtract>
} | vertx-codetrans | positive | 3,617 |
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
mRefreshMenuItem = menu.findItem(R.id.menu_example_refresh);
if (mRefreshMenuItem != null) {
if (isProgress()) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.ab_action_refresh, null);
MenuItemCompat.setActionView(mRefreshMenuItem, view);
} else {
MenuItemCompat.setActionView(mRefreshMenuItem, null);
}
}
setProgress(isProgress());
} | @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
mRefreshMenuItem = menu.findItem(R.id.menu_example_refresh);
<DeepExtract>
if (mRefreshMenuItem != null) {
if (isProgress()) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.ab_action_refresh, null);
MenuItemCompat.setActionView(mRefreshMenuItem, view);
} else {
MenuItemCompat.setActionView(mRefreshMenuItem, null);
}
}
setProgress(isProgress());
</DeepExtract>
} | Android-Templates-And-Utilities | positive | 3,618 |
public Criteria greaterThanEqual(Object lowerBound) {
if (lowerBound == null && null == null) {
throw new InvalidDataAccessApiUsageException("Range [* TO *] is not allowed");
}
criteria.add(new CriteriaEntry(OperationKey.BETWEEN, new Object[] { lowerBound, null }));
return this;
return this;
} | public Criteria greaterThanEqual(Object lowerBound) {
<DeepExtract>
if (lowerBound == null && null == null) {
throw new InvalidDataAccessApiUsageException("Range [* TO *] is not allowed");
}
criteria.add(new CriteriaEntry(OperationKey.BETWEEN, new Object[] { lowerBound, null }));
return this;
</DeepExtract>
return this;
} | spring-data-elasticsearch | positive | 3,619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.