before
stringlengths 12
3.76M
| after
stringlengths 37
3.84M
| repo
stringlengths 1
56
| type
stringclasses 1
value |
|---|---|---|---|
@Override
public Reader getCharacterStream(int i) throws SQLException {
if (closed) {
throw new SQLException("ResultSet is closed");
}
return null;
}
|
<DeepExtract>
if (closed) {
throw new SQLException("ResultSet is closed");
}
</DeepExtract>
|
rodriguez
|
positive
|
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
super.onExecuteWrite(device, requestId, execute);
if (mBluetoothGattServer != null) {
mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, new byte[] {});
}
Log.i("ADV-CB", "executeWriteStorages : " + execute);
for (int i = mWriteList.size() - 1; i >= 0; i--) {
WriteStorage storage = mWriteList.get(i);
if (storage != null && storage.getDeviceAddress().equalsIgnoreCase(device.getAddress())) {
if (execute) {
if (storage.isCharacter()) {
onCharacterWrite(storage.getDeviceAddress(), storage.getUUID(), storage.getFullData());
}
}
mWriteList.remove(storage);
storage.clearData();
}
}
}
|
<DeepExtract>
Log.i("ADV-CB", "executeWriteStorages : " + execute);
for (int i = mWriteList.size() - 1; i >= 0; i--) {
WriteStorage storage = mWriteList.get(i);
if (storage != null && storage.getDeviceAddress().equalsIgnoreCase(device.getAddress())) {
if (execute) {
if (storage.isCharacter()) {
onCharacterWrite(storage.getDeviceAddress(), storage.getUUID(), storage.getFullData());
}
}
mWriteList.remove(storage);
storage.clearData();
}
}
</DeepExtract>
|
BLETestStuff
|
positive
|
public static String addSecond(String date, int hourAmount) {
String dateString = null;
DateStyle dateStyle = getDateStyle(date);
if (dateStyle != null) {
Date myDate = StringToDate(date, dateStyle);
myDate = addInteger(myDate, Calendar.SECOND, hourAmount);
dateString = DateToString(myDate, dateStyle);
}
return dateString;
}
|
<DeepExtract>
String dateString = null;
DateStyle dateStyle = getDateStyle(date);
if (dateStyle != null) {
Date myDate = StringToDate(date, dateStyle);
myDate = addInteger(myDate, Calendar.SECOND, hourAmount);
dateString = DateToString(myDate, dateStyle);
}
return dateString;
</DeepExtract>
|
SuperNote
|
positive
|
@Test
public void testAsyncOperation(TestContext context) {
Async async = context.async();
vertx.setTimer(10, l -> list -> {
assertThat(list, hasItems("a", "b", "c"));
async.complete();
}.handle(Arrays.asList("a", "b", "c")));
}
|
<DeepExtract>
vertx.setTimer(10, l -> list -> {
assertThat(list, hasItems("a", "b", "c"));
async.complete();
}.handle(Arrays.asList("a", "b", "c")));
</DeepExtract>
|
vertx-examples
|
positive
|
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
if (e.getMessage() != null) {
Log.e(TAG, e.toString());
}
String errMsg = "Facebook error: " + e.getMessage();
int errorCode = INVALID_ERROR_CODE;
if (e instanceof FacebookOperationCanceledException) {
errMsg = "User cancelled dialog";
errorCode = 4201;
} else if (e instanceof FacebookDialogException) {
errMsg = "Dialog error: " + e.getMessage();
}
if (showDialogContext != null) {
showDialogContext.error(getErrorResponse(e, errMsg, errorCode));
} else {
Log.e(TAG, "Error already sent so no context, msg: " + errMsg + ", code: " + errorCode);
}
}
|
<DeepExtract>
if (e.getMessage() != null) {
Log.e(TAG, e.toString());
}
String errMsg = "Facebook error: " + e.getMessage();
int errorCode = INVALID_ERROR_CODE;
if (e instanceof FacebookOperationCanceledException) {
errMsg = "User cancelled dialog";
errorCode = 4201;
} else if (e instanceof FacebookDialogException) {
errMsg = "Dialog error: " + e.getMessage();
}
if (showDialogContext != null) {
showDialogContext.error(getErrorResponse(e, errMsg, errorCode));
} else {
Log.e(TAG, "Error already sent so no context, msg: " + errMsg + ", code: " + errorCode);
}
</DeepExtract>
|
newschool-frontend
|
positive
|
@Override
public void map(CaseConfig caseConfig) {
super.mapTo(this);
Map<String, String> client = config.getMapProperty("xclient");
if (client != null) {
for (Map.Entry<String, String> pair : client.entrySet()) {
((XclientSession) this).getXclient().put(pair.getKey(), pair.getValue());
}
}
}
|
<DeepExtract>
super.mapTo(this);
Map<String, String> client = config.getMapProperty("xclient");
if (client != null) {
for (Map.Entry<String, String> pair : client.entrySet()) {
((XclientSession) this).getXclient().put(pair.getKey(), pair.getValue());
}
}
</DeepExtract>
|
robin
|
positive
|
public ValveWriter close() throws IOException {
this.indentation--;
this.writeIndentation().write(CLOSE_TAG + ValveWriter.LINE_BREAK);
return this;
}
|
<DeepExtract>
this.writeIndentation().write(CLOSE_TAG + ValveWriter.LINE_BREAK);
</DeepExtract>
|
sourcecraft
|
positive
|
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ArrayList<String> password = new ArrayList<>();
int arraySize;
int randomIndex;
Random random = new SecureRandom();
int length = Integer.parseInt(passwordLength.getText().toString());
if (!checkBoxLowerCase.isChecked() && !checkBoxUpperCase.isChecked() && !checkBoxNumbers.isChecked() && !checkBoxSpecialChars.isChecked()) {
generatedPassword = "";
passwordDisplay.setText("");
return;
}
while (password.size() < length) {
if (checkBoxLowerCase.isChecked()) {
arraySize = lowerCase.length;
randomIndex = random.nextInt(arraySize);
password.add(lowerCase[randomIndex]);
}
if (checkBoxUpperCase.isChecked()) {
arraySize = upperCase.length;
randomIndex = random.nextInt(arraySize);
password.add(upperCase[randomIndex]);
}
if (checkBoxNumbers.isChecked()) {
arraySize = numbers.length;
randomIndex = random.nextInt(arraySize);
password.add(numbers[randomIndex]);
}
if (checkBoxSpecialChars.isChecked()) {
arraySize = specialChars.length;
randomIndex = random.nextInt(arraySize);
password.add(specialChars[randomIndex]);
}
}
Collections.shuffle(password);
while (password.size() > length) {
password.remove(0);
}
generatedPassword = TextUtils.join("", password);
passwordDisplay.setText(generatedPassword);
}
|
<DeepExtract>
ArrayList<String> password = new ArrayList<>();
int arraySize;
int randomIndex;
Random random = new SecureRandom();
int length = Integer.parseInt(passwordLength.getText().toString());
if (!checkBoxLowerCase.isChecked() && !checkBoxUpperCase.isChecked() && !checkBoxNumbers.isChecked() && !checkBoxSpecialChars.isChecked()) {
generatedPassword = "";
passwordDisplay.setText("");
return;
}
while (password.size() < length) {
if (checkBoxLowerCase.isChecked()) {
arraySize = lowerCase.length;
randomIndex = random.nextInt(arraySize);
password.add(lowerCase[randomIndex]);
}
if (checkBoxUpperCase.isChecked()) {
arraySize = upperCase.length;
randomIndex = random.nextInt(arraySize);
password.add(upperCase[randomIndex]);
}
if (checkBoxNumbers.isChecked()) {
arraySize = numbers.length;
randomIndex = random.nextInt(arraySize);
password.add(numbers[randomIndex]);
}
if (checkBoxSpecialChars.isChecked()) {
arraySize = specialChars.length;
randomIndex = random.nextInt(arraySize);
password.add(specialChars[randomIndex]);
}
}
Collections.shuffle(password);
while (password.size() > length) {
password.remove(0);
}
generatedPassword = TextUtils.join("", password);
passwordDisplay.setText(generatedPassword);
</DeepExtract>
|
rcloneExplorer
|
positive
|
public static void main(String[] args) {
BenchmarkSettings.loadSettings(args);
BenchmarkSettings.printSettings();
SparkUpfront s = new SparkUpfront();
cfg = new ConfUtils(BenchmarkSettings.conf);
SparkConf sconf = new SparkConf().setMaster(cfg.getSPARK_MASTER()).setAppName("Spark App").setSparkHome(cfg.getSPARK_HOME()).setJars(new String[] { cfg.getSPARK_APPLICATION_JAR() }).set("spark.hadoop.cloneConf", "false").set("spark.executor.memory", cfg.getSPARK_EXECUTOR_MEMORY()).set("spark.driver.memory", cfg.getSPARK_DRIVER_MEMORY()).set("spark.task.cpus", "1");
try {
sconf.registerKryoClasses(new Class<?>[] { Class.forName("org.apache.hadoop.io.LongWritable"), Class.forName("org.apache.hadoop.io.Text") });
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ctx = new JavaSparkContext(sconf);
ctx.hadoopConfiguration().setBoolean(FileInputFormat.INPUT_DIR_RECURSIVE, true);
ctx.hadoopConfiguration().set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
sqlContext = new SQLContext(ctx);
sqlContext.sql(createTpch);
TPCHWorkload w = new TPCHWorkload();
w.setUp();
for (int i = 0; i < w.supportedQueries.length; i++) {
Query q = w.getQuery(w.supportedQueries[i]);
long start = System.currentTimeMillis();
String query = q.createQueryString();
System.out.println("Query:" + query);
DataFrame df = sqlContext.sql(query);
long result = df.count();
long end = System.currentTimeMillis();
System.out.println("RES: Query: " + w.supportedQueries[i] + ";Time Taken: " + (end - start) + "; Result: " + result);
}
}
|
<DeepExtract>
cfg = new ConfUtils(BenchmarkSettings.conf);
SparkConf sconf = new SparkConf().setMaster(cfg.getSPARK_MASTER()).setAppName("Spark App").setSparkHome(cfg.getSPARK_HOME()).setJars(new String[] { cfg.getSPARK_APPLICATION_JAR() }).set("spark.hadoop.cloneConf", "false").set("spark.executor.memory", cfg.getSPARK_EXECUTOR_MEMORY()).set("spark.driver.memory", cfg.getSPARK_DRIVER_MEMORY()).set("spark.task.cpus", "1");
try {
sconf.registerKryoClasses(new Class<?>[] { Class.forName("org.apache.hadoop.io.LongWritable"), Class.forName("org.apache.hadoop.io.Text") });
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ctx = new JavaSparkContext(sconf);
ctx.hadoopConfiguration().setBoolean(FileInputFormat.INPUT_DIR_RECURSIVE, true);
ctx.hadoopConfiguration().set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
sqlContext = new SQLContext(ctx);
sqlContext.sql(createTpch);
</DeepExtract>
<DeepExtract>
TPCHWorkload w = new TPCHWorkload();
w.setUp();
for (int i = 0; i < w.supportedQueries.length; i++) {
Query q = w.getQuery(w.supportedQueries[i]);
long start = System.currentTimeMillis();
String query = q.createQueryString();
System.out.println("Query:" + query);
DataFrame df = sqlContext.sql(query);
long result = df.count();
long end = System.currentTimeMillis();
System.out.println("RES: Query: " + w.supportedQueries[i] + ";Time Taken: " + (end - start) + "; Result: " + result);
}
</DeepExtract>
|
amoeba
|
positive
|
public static Result lbfgs(double[] x, Function proc_evaluate, ProgressCallback proc_progress, Params param) {
int n = x.length;
Result ret = new Result(null);
double[] step = new double[] { 0 };
final int m = param.m;
double[] d, w, pf = null;
double[] fx = new double[] { 0 };
double rate = 0;
line_search_proc linesearch = new line_search_backtracking();
callback_data_t cd = new callback_data_t();
cd.n = n;
cd.proc_evaluate = proc_evaluate;
cd.proc_progress = proc_progress;
if (n <= 0) {
return new Result(Status.LBFGSERR_INVALID_N);
}
if (param.epsilon < 0.) {
return new Result(Status.LBFGSERR_INVALID_EPSILON);
}
if (param.past < 0) {
return new Result(Status.LBFGSERR_INVALID_TESTPERIOD);
}
if (param.delta < 0.) {
return new Result(Status.LBFGSERR_INVALID_DELTA);
}
if (param.min_step < 0.) {
return new Result(Status.LBFGSERR_INVALID_MINSTEP);
}
if (param.max_step < param.min_step) {
return new Result(Status.LBFGSERR_INVALID_MAXSTEP);
}
if (param.ftol < 0.) {
return new Result(Status.LBFGSERR_INVALID_FTOL);
}
if (param.linesearch == LinesearchAlgorithm.LBFGS_LINESEARCH_BACKTRACKING_WOLFE || param.linesearch == LinesearchAlgorithm.LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE) {
if (param.wolfe <= param.ftol || 1. <= param.wolfe) {
return new Result(Status.LBFGSERR_INVALID_WOLFE);
}
}
if (param.gtol < 0.) {
return new Result(Status.LBFGSERR_INVALID_GTOL);
}
if (param.xtol < 0.) {
return new Result(Status.LBFGSERR_INVALID_XTOL);
}
if (param.max_linesearch <= 0) {
return new Result(Status.LBFGSERR_INVALID_MAXLINESEARCH);
}
if (param.orthantwise_c < 0.) {
return new Result(Status.LBFGSERR_INVALID_ORTHANTWISE);
}
if (param.orthantwise_start < 0 || n < param.orthantwise_start) {
return new Result(Status.LBFGSERR_INVALID_ORTHANTWISE_START);
}
if (param.orthantwise_end < 0) {
param.orthantwise_end = n;
}
if (n < param.orthantwise_end) {
return new Result(Status.LBFGSERR_INVALID_ORTHANTWISE_END);
}
if (param.orthantwise_c != 0.) {
linesearch = new line_search_backtracking_owlqn();
} else {
switch(param.linesearch) {
case LBFGS_LINESEARCH_MORETHUENTE:
linesearch = new line_search_morethuente();
break;
case LBFGS_LINESEARCH_BACKTRACKING_ARMIJO:
case LBFGS_LINESEARCH_BACKTRACKING_WOLFE:
case LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE:
linesearch = new line_search_backtracking();
break;
default:
return new Result(Status.LBFGSERR_INVALID_LINESEARCH);
}
}
xp = new double[n];
g = new double[n];
gp = new double[n];
d = new double[n];
w = new double[n];
if (param.orthantwise_c != 0) {
pg = new double[n];
} else {
pg = new double[0];
}
lm = new iteration_data_t[m];
for (i = 0; i < m; ++i) {
lm[i] = new iteration_data_t();
it = lm[i];
it.alpha = 0;
it.ys = 0;
it.s = new double[n];
it.y = new double[n];
}
if (0 < param.past) {
pf = new double[param.past];
}
double sqloss = 0;
Arr.fill(g, 0);
for (int i = 0; i < cd.n; i++) {
double pred = Arr.innerProduct(x, X[i]);
double resid = pred - Y[i];
sqloss += Math.pow(resid, 2);
for (int j = 0; j < Nfeat; j++) {
g[j] += X[i][j] * resid;
}
}
return sqloss;
if (0. != param.orthantwise_c) {
xnorm = owlqn_x1norm(x, param.orthantwise_start, param.orthantwise_end);
fx[0] += xnorm * param.orthantwise_c;
owlqn_pseudo_gradient(pg, x, g, n, param.orthantwise_c, param.orthantwise_start, param.orthantwise_end);
}
if (pf != null) {
pf[0] = fx[0];
}
if (param.orthantwise_c == 0.) {
vecncpy(d, g, n);
} else {
vecncpy(d, pg, n);
}
double s = vecdot(x, x, n);
return Math.sqrt(s);
if (param.orthantwise_c == 0.) {
gnorm = vec2norm(g, n);
} else {
gnorm = vec2norm(pg, n);
}
if (xnorm < 1.0)
xnorm = 1.0;
if (gnorm / xnorm <= param.epsilon) {
return new Result(Status.LBFGS_ALREADY_MINIMIZED);
}
double s = vec2norm(d, n);
return 1.0 / s;
k = 1;
end = 0;
for (; ; ) {
veccpy(xp, x, n);
veccpy(gp, g, n);
if (param.orthantwise_c == 0.) {
ls = linesearch.go(n, x, fx, g, d, step, xp, gp, w, cd, param);
} else {
ls = linesearch.go(n, x, fx, g, d, step, xp, pg, w, cd, param);
owlqn_pseudo_gradient(pg, x, g, n, param.orthantwise_c, param.orthantwise_start, param.orthantwise_end);
}
if (ls != null && ls.isError()) {
veccpy(x, xp, n);
veccpy(g, gp, n);
ret.status = ls;
ret.objective = fx[0];
return ret;
}
xnorm = vec2norm(x, n);
if (param.orthantwise_c == 0.) {
gnorm = vec2norm(g, n);
} else {
gnorm = vec2norm(pg, n);
}
if (cd.proc_progress != null) {
int stopEarly = cd.proc_progress.apply(x, g, fx[0], xnorm, gnorm, step[0], cd.n, k, ls);
if (stopEarly != 0) {
ret.status = Status.LBFGS_STOP;
ret.additionalStatus = stopEarly;
ret.objective = fx[0];
return ret;
}
}
if (xnorm < 1.0)
xnorm = 1.0;
if (gnorm / xnorm <= param.epsilon) {
ret.status = Status.LBFGS_SUCCESS;
break;
}
if (pf != null) {
if (param.past <= k) {
rate = (pf[k % param.past] - fx[0]) / fx[0];
if (rate < param.delta) {
ret.status = Status.LBFGS_STOP;
break;
}
}
pf[k % param.past] = fx[0];
}
if (param.max_iterations != 0 && param.max_iterations < k + 1) {
ret.status = Status.LBFGSERR_MAXIMUMITERATION;
break;
}
it = lm[end];
vecdiff(it.s, x, xp, n);
vecdiff(it.y, g, gp, n);
ys = vecdot(it.y, it.s, n);
yy = vecdot(it.y, it.y, n);
it.ys = ys;
bound = (m <= k) ? m : k;
++k;
end = (end + 1) % m;
if (param.orthantwise_c == 0.) {
vecncpy(d, g, n);
} else {
vecncpy(d, pg, n);
}
j = end;
for (i = 0; i < bound; ++i) {
j = (j + m - 1) % m;
it = lm[j];
it.alpha = vecdot(it.s, d, n);
it.alpha /= it.ys;
vecadd(d, it.y, -it.alpha, n);
}
vecscale(d, ys / yy, n);
for (i = 0; i < bound; ++i) {
it = lm[j];
beta = vecdot(it.y, d, n);
beta /= it.ys;
vecadd(d, it.s, it.alpha - beta, n);
j = (j + 1) % m;
}
if (param.orthantwise_c != 0.) {
for (i = param.orthantwise_start; i < param.orthantwise_end; ++i) {
if (d[i] * pg[i] >= 0) {
d[i] = 0;
}
}
}
step[0] = 1.0;
}
ret.objective = fx[0];
return ret;
}
|
<DeepExtract>
double sqloss = 0;
Arr.fill(g, 0);
for (int i = 0; i < cd.n; i++) {
double pred = Arr.innerProduct(x, X[i]);
double resid = pred - Y[i];
sqloss += Math.pow(resid, 2);
for (int j = 0; j < Nfeat; j++) {
g[j] += X[i][j] * resid;
}
}
return sqloss;
</DeepExtract>
<DeepExtract>
double s = vecdot(x, x, n);
return Math.sqrt(s);
</DeepExtract>
<DeepExtract>
double s = vec2norm(d, n);
return 1.0 / s;
</DeepExtract>
|
myutil
|
positive
|
@Override
public void run() {
if (mBoardRelease != null) {
showReleasesInfo(false, null, false);
} else {
if (mDeviceInfoData != null) {
boolean hasDFUService = mFirmwareUpdater.hasCurrentConnectedDeviceDFUService();
if (hasDFUService) {
showReleasesInfo(false, null, false);
} else {
showReleasesInfo(true, getString(R.string.connectedsettings_dfunotfound), false);
mCustomFirmwareButton.setVisibility(View.GONE);
mCustomBootloaderButton.setVisibility(View.GONE);
}
} else {
showReleasesInfo(true, getString(R.string.connectedsettings_retrievinginfo), true);
}
}
}
|
<DeepExtract>
if (mBoardRelease != null) {
showReleasesInfo(false, null, false);
} else {
if (mDeviceInfoData != null) {
boolean hasDFUService = mFirmwareUpdater.hasCurrentConnectedDeviceDFUService();
if (hasDFUService) {
showReleasesInfo(false, null, false);
} else {
showReleasesInfo(true, getString(R.string.connectedsettings_dfunotfound), false);
mCustomFirmwareButton.setVisibility(View.GONE);
mCustomBootloaderButton.setVisibility(View.GONE);
}
} else {
showReleasesInfo(true, getString(R.string.connectedsettings_retrievinginfo), true);
}
}
</DeepExtract>
|
Bluefruit_LE_Connect_Android
|
positive
|
public static void main(String[] args) {
int overflow = 0;
ListNode result = new ListNode(0);
ListNode p = new ListNode(5), q = new ListNode(5), curr = result;
while (p != null || q != null) {
int pval = p == null ? 0 : p.val;
int qval = q == null ? 0 : q.val;
int value = pval + qval + overflow;
overflow = 0;
if (value >= 10)
overflow++;
curr.next = new ListNode(value % 10);
curr = curr.next;
if (p != null)
p = p.next;
if (q != null)
q = q.next;
}
if (overflow > 0) {
curr.next = new ListNode(overflow);
}
return result.next;
}
|
<DeepExtract>
int overflow = 0;
ListNode result = new ListNode(0);
ListNode p = new ListNode(5), q = new ListNode(5), curr = result;
while (p != null || q != null) {
int pval = p == null ? 0 : p.val;
int qval = q == null ? 0 : q.val;
int value = pval + qval + overflow;
overflow = 0;
if (value >= 10)
overflow++;
curr.next = new ListNode(value % 10);
curr = curr.next;
if (p != null)
p = p.next;
if (q != null)
q = q.next;
}
if (overflow > 0) {
curr.next = new ListNode(overflow);
}
return result.next;
</DeepExtract>
|
JavaZone
|
positive
|
@VisibleForTesting
int retrieveFirstNumberOfSubjects() {
return numberOfSubjects;
}
|
<DeepExtract>
return numberOfSubjects;
</DeepExtract>
|
groningen
|
positive
|
@CodeTranslate
public void memberExpressionAccessedByMethod() throws Exception {
VariableTest.o = member;
}
|
<DeepExtract>
VariableTest.o = member;
</DeepExtract>
|
vertx-codetrans
|
positive
|
@Override
public boolean onCreate() {
if (getContext() == null) {
init(getApplicationByReflect());
return;
}
init((Application) getContext().getApplicationContext());
return true;
}
|
<DeepExtract>
if (getContext() == null) {
init(getApplicationByReflect());
return;
}
init((Application) getContext().getApplicationContext());
</DeepExtract>
|
MVPFramework
|
positive
|
public boolean more() throws JSONException {
int c;
if (this.usePrevious) {
this.usePrevious = false;
c = this.previous;
} else {
try {
c = this.reader.read();
} catch (IOException exception) {
throw new JSONException(exception);
}
if (c <= 0) {
this.eof = true;
c = 0;
}
}
this.index += 1;
if (this.previous == '\r') {
this.line += 1;
this.character = c == '\n' ? 0 : 1;
} else if (c == '\n') {
this.line += 1;
this.character = 0;
} else {
this.character += 1;
}
this.previous = (char) c;
return this.previous;
if (this.end()) {
return false;
}
if (this.usePrevious || this.index <= 0) {
throw new JSONException("Stepping back two steps is not supported");
}
this.index -= 1;
this.character -= 1;
this.usePrevious = true;
this.eof = false;
return true;
}
|
<DeepExtract>
int c;
if (this.usePrevious) {
this.usePrevious = false;
c = this.previous;
} else {
try {
c = this.reader.read();
} catch (IOException exception) {
throw new JSONException(exception);
}
if (c <= 0) {
this.eof = true;
c = 0;
}
}
this.index += 1;
if (this.previous == '\r') {
this.line += 1;
this.character = c == '\n' ? 0 : 1;
} else if (c == '\n') {
this.line += 1;
this.character = 0;
} else {
this.character += 1;
}
this.previous = (char) c;
return this.previous;
</DeepExtract>
<DeepExtract>
if (this.usePrevious || this.index <= 0) {
throw new JSONException("Stepping back two steps is not supported");
}
this.index -= 1;
this.character -= 1;
this.usePrevious = true;
this.eof = false;
</DeepExtract>
|
renren-api2-sdk-java
|
positive
|
@Override
public void run() {
if (stack.size() <= 0)
return;
contentFrameLayout.setLayoutTransition(null);
View showView = wrapper.getView();
View preView = stack.peek().getView();
stack.push(wrapper);
contentFrameLayout.addView(showView);
pushOutAnimator.setTarget(preView);
pushOutAnimator.start();
pushInAnimator.setTarget(showView);
pushInAnimator.setFloatValues(contentFrameLayout.getWidth(), 0);
pushInAnimator.start();
refreshTitle();
refreshOptionsMenu();
}
|
<DeepExtract>
if (stack.size() <= 0)
return;
contentFrameLayout.setLayoutTransition(null);
View showView = wrapper.getView();
View preView = stack.peek().getView();
stack.push(wrapper);
contentFrameLayout.addView(showView);
pushOutAnimator.setTarget(preView);
pushOutAnimator.start();
pushInAnimator.setTarget(showView);
pushInAnimator.setFloatValues(contentFrameLayout.getWidth(), 0);
pushInAnimator.start();
refreshTitle();
refreshOptionsMenu();
</DeepExtract>
|
flyapp
|
positive
|
@Override
public void addComment(XmlElement xmlElement) {
Map<String, Object> map = new HashMap<>();
map.put("mgb", MergeConstants.NEW_ELEMENT_TAG);
map.put("xmlElement", xmlElement);
if (this.suppressAllComments) {
return;
}
String[] comments = getComments(map, EnumNode.ADD_COMMENT);
if (comments != null) {
if (comments.length == 1 && !StringUtility.stringHasValue(comments[0])) {
return;
}
for (String comment : comments) {
xmlElement.addElement(new TextElement(comment));
}
}
}
|
<DeepExtract>
if (this.suppressAllComments) {
return;
}
String[] comments = getComments(map, EnumNode.ADD_COMMENT);
if (comments != null) {
if (comments.length == 1 && !StringUtility.stringHasValue(comments[0])) {
return;
}
for (String comment : comments) {
xmlElement.addElement(new TextElement(comment));
}
}
</DeepExtract>
|
mybatis-generator-plugin
|
positive
|
public void setDeviceName(java.lang.String deviceName) throws IOException {
try {
if (wrtr != null) {
wrtr.close();
wrtr = null;
}
if (rdr != null) {
rdr.close();
rdr = null;
}
} catch (IOException e) {
e.printStackTrace();
}
this.deviceName = deviceName;
wrtr = new RandomAccessFile(deviceName, "rw");
rdr = wrtr;
long result = -1;
Field dscrField;
FileDescriptor dscr;
try {
dscr = wrtr.getFD();
try {
dscrField = FileDescriptor.class.getDeclaredField("handle");
} catch (NoSuchFieldException ex) {
dscrField = FileDescriptor.class.getDeclaredField("fd");
}
dscrField.setAccessible(true);
result = dscrField.getLong(dscr);
} catch (Exception ex) {
log.log(Level.SEVERE, "getFD", ex);
}
return result;
SerialExt.serialPortDescriptor = (int) serialDeviceDescriptor;
}
|
<DeepExtract>
try {
if (wrtr != null) {
wrtr.close();
wrtr = null;
}
if (rdr != null) {
rdr.close();
rdr = null;
}
} catch (IOException e) {
e.printStackTrace();
}
</DeepExtract>
<DeepExtract>
long result = -1;
Field dscrField;
FileDescriptor dscr;
try {
dscr = wrtr.getFD();
try {
dscrField = FileDescriptor.class.getDeclaredField("handle");
} catch (NoSuchFieldException ex) {
dscrField = FileDescriptor.class.getDeclaredField("fd");
}
dscrField.setAccessible(true);
result = dscrField.getLong(dscr);
} catch (Exception ex) {
log.log(Level.SEVERE, "getFD", ex);
}
return result;
</DeepExtract>
|
AndrOBD
|
positive
|
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
String stringValue = PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(), "").toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
} else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
preference.setSummary(null);
} else {
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
preference.setSummary(stringValue);
}
return true;
}
|
<DeepExtract>
String stringValue = PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(), "").toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
} else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
preference.setSummary(null);
} else {
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
preference.setSummary(stringValue);
}
return true;
</DeepExtract>
|
EverExample
|
positive
|
@Nullable
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
return superState;
}
final SavedState myState = new SavedState(superState);
return mChecked;
return myState;
}
|
<DeepExtract>
return mChecked;
</DeepExtract>
|
SamsungOneUi
|
positive
|
public static Builder newBuilder(net.osrg.namazu.InspectorMessage.InspectorMsgReq prototype) {
if (prototype instanceof net.osrg.namazu.InspectorMessage.InspectorMsgReq_Event_FuncCall) {
return mergeFrom((net.osrg.namazu.InspectorMessage.InspectorMsgReq_Event_FuncCall) prototype);
} else {
super.mergeFrom(prototype);
return this;
}
}
|
<DeepExtract>
if (prototype instanceof net.osrg.namazu.InspectorMessage.InspectorMsgReq_Event_FuncCall) {
return mergeFrom((net.osrg.namazu.InspectorMessage.InspectorMsgReq_Event_FuncCall) prototype);
} else {
super.mergeFrom(prototype);
return this;
}
</DeepExtract>
|
namazu
|
positive
|
@Override
public int execute(Config config) throws IOException {
var log = Log.create(name(), config.getOrThrow("pro", ProConf.class).loglevel());
var frozerConf = config.getOrThrow(name(), FrozerConf.class);
log.debug(config, conf -> "config " + frozerConf);
String rootModuleName = frozerConf.rootModule().orElseThrow(() -> new IllegalArgumentException("no root module specified"));
ModuleFinder finder = ModuleFinder.of(frozerConf.modulePath().toArray(Path[]::new));
var rootModule = finder.find(rootModuleName).orElseThrow(() -> new IllegalStateException("no root module " + rootModuleName + " not found"));
var dependencies = new LinkedHashSet<String>();
var requires = new LinkedHashSet<String>();
ModuleHelper.resolveOnlyRequires(finder, List.of(rootModuleName), new ResolverListener() {
@Override
public void module(String moduleName) {
dependencies.add(moduleName);
}
@Override
public void dependencyNotFound(String moduleName, String dependencyChain) {
requires.add(moduleName);
}
});
dependencies.removeAll(requires);
var packages = dependencies.stream().filter(not(rootModuleName::equals)).flatMap(name -> finder.find(name).stream()).map(ModuleReference::descriptor).flatMap(descriptor -> Stream.<String>concat(descriptor.exports().stream().map(Exports::source), descriptor.packages().stream())).collect(toUnmodifiableSet());
var rootModuleName = rootModule.descriptor().name();
var internalRootModuleName = rootModuleName.replace('.', '/');
var internalPackageNameMap = packages.stream().map(name -> name.replace('.', '/')).collect(toUnmodifiableMap(name -> name, name -> internalRootModuleName + '/' + name));
var newPackages = new HashSet<String>();
Path path = frozerConf.moduleFrozenArtifactSourcePath().resolve(rootModuleName + ".jar");
Files.createDirectories(path.getParent());
try (var output = Files.newOutputStream(path);
var outputStream = new JarOutputStream(output)) {
var entryNames = new HashSet<>();
for (var dependency : dependencies) {
var reference = finder.find(dependency).orElseThrow();
try (var reader = reference.open()) {
for (String filename : (Iterable<String>) reader.list()::iterator) {
if (filename.equals("module-info.class") || filename.endsWith("/") || filename.startsWith("META-INF")) {
continue;
}
if (!entryNames.add(filename)) {
System.out.println("duplicate entry " + filename + " skip it !");
continue;
}
try (var inputStream = reader.open(filename).orElseThrow(() -> new IOException("can not read " + filename))) {
if (!filename.endsWith(".class")) {
getPackage(filename).ifPresent(newPackages::add);
outputStream.putNextEntry(new JarEntry(filename));
inputStream.transferTo(outputStream);
continue;
}
var newFilename = interpolateInternalName(internalPackageNameMap, filename);
getPackage(newFilename).ifPresent(newPackages::add);
outputStream.putNextEntry(new JarEntry(newFilename));
outputStream.write(rewriteBytecode(internalPackageNameMap, inputStream.readAllBytes()));
}
}
}
}
outputStream.putNextEntry(new JarEntry("module-info.class"));
var builder = ModuleDescriptor.newOpenModule(rootModuleName);
var rootModuleDescriptor = rootModule.descriptor();
rootModuleDescriptor.version().ifPresent(builder::version);
requires.forEach(builder::requires);
rootModuleDescriptor.exports().forEach(builder::exports);
rootModuleDescriptor.opens().forEach(builder::opens);
builder.packages(rootModuleDescriptor.packages());
dependencies.stream().flatMap(name -> finder.find(name).stream()).map(ModuleReference::descriptor).forEach(descriptor -> {
descriptor.provides().forEach(provides -> {
builder.provides(interpolateClassName(internalPackageNameMap, provides.service()), provides.providers().stream().map(provider -> interpolateClassName(internalPackageNameMap, provider)).collect(toUnmodifiableList()));
});
descriptor.uses().forEach(uses -> builder.uses(interpolateClassName(internalPackageNameMap, uses)));
});
builder.packages(newPackages);
var moduleDescriptor = builder.build();
outputStream.write(ModuleHelper.moduleDescriptorToBinary(moduleDescriptor));
}
return 0;
}
|
<DeepExtract>
var rootModuleName = rootModule.descriptor().name();
var internalRootModuleName = rootModuleName.replace('.', '/');
var internalPackageNameMap = packages.stream().map(name -> name.replace('.', '/')).collect(toUnmodifiableMap(name -> name, name -> internalRootModuleName + '/' + name));
var newPackages = new HashSet<String>();
Path path = frozerConf.moduleFrozenArtifactSourcePath().resolve(rootModuleName + ".jar");
Files.createDirectories(path.getParent());
try (var output = Files.newOutputStream(path);
var outputStream = new JarOutputStream(output)) {
var entryNames = new HashSet<>();
for (var dependency : dependencies) {
var reference = finder.find(dependency).orElseThrow();
try (var reader = reference.open()) {
for (String filename : (Iterable<String>) reader.list()::iterator) {
if (filename.equals("module-info.class") || filename.endsWith("/") || filename.startsWith("META-INF")) {
continue;
}
if (!entryNames.add(filename)) {
System.out.println("duplicate entry " + filename + " skip it !");
continue;
}
try (var inputStream = reader.open(filename).orElseThrow(() -> new IOException("can not read " + filename))) {
if (!filename.endsWith(".class")) {
getPackage(filename).ifPresent(newPackages::add);
outputStream.putNextEntry(new JarEntry(filename));
inputStream.transferTo(outputStream);
continue;
}
var newFilename = interpolateInternalName(internalPackageNameMap, filename);
getPackage(newFilename).ifPresent(newPackages::add);
outputStream.putNextEntry(new JarEntry(newFilename));
outputStream.write(rewriteBytecode(internalPackageNameMap, inputStream.readAllBytes()));
}
}
}
}
outputStream.putNextEntry(new JarEntry("module-info.class"));
var builder = ModuleDescriptor.newOpenModule(rootModuleName);
var rootModuleDescriptor = rootModule.descriptor();
rootModuleDescriptor.version().ifPresent(builder::version);
requires.forEach(builder::requires);
rootModuleDescriptor.exports().forEach(builder::exports);
rootModuleDescriptor.opens().forEach(builder::opens);
builder.packages(rootModuleDescriptor.packages());
dependencies.stream().flatMap(name -> finder.find(name).stream()).map(ModuleReference::descriptor).forEach(descriptor -> {
descriptor.provides().forEach(provides -> {
builder.provides(interpolateClassName(internalPackageNameMap, provides.service()), provides.providers().stream().map(provider -> interpolateClassName(internalPackageNameMap, provider)).collect(toUnmodifiableList()));
});
descriptor.uses().forEach(uses -> builder.uses(interpolateClassName(internalPackageNameMap, uses)));
});
builder.packages(newPackages);
var moduleDescriptor = builder.build();
outputStream.write(ModuleHelper.moduleDescriptorToBinary(moduleDescriptor));
}
</DeepExtract>
|
pro
|
positive
|
public void seekToTimeUs(long timeUs) {
if (render == null) {
setUpSuccess = false;
render = new LSOStickerPlayerRender(getContext());
render.setBackGroundColor(padBGRed, padBGGreen, padBGBlue, padBGAlpha);
render.setOnErrorListener(new OnLanSongSDKErrorListener() {
@Override
public void onLanSongSDKError(int errorCode) {
setUpSuccess = false;
if (userErrorListener != null) {
userErrorListener.onLanSongSDKError(errorCode);
}
}
});
}
if (render != null) {
render.seekToTimeUs(timeUs);
}
}
|
<DeepExtract>
if (render == null) {
setUpSuccess = false;
render = new LSOStickerPlayerRender(getContext());
render.setBackGroundColor(padBGRed, padBGGreen, padBGBlue, padBGAlpha);
render.setOnErrorListener(new OnLanSongSDKErrorListener() {
@Override
public void onLanSongSDKError(int errorCode) {
setUpSuccess = false;
if (userErrorListener != null) {
userErrorListener.onLanSongSDKError(errorCode);
}
}
});
}
</DeepExtract>
|
LanSoEditor_advance
|
positive
|
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields;
switch(fieldId) {
default:
fields = null;
}
if (fields == null)
throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
|
<DeepExtract>
_Fields fields;
switch(fieldId) {
default:
fields = null;
}
</DeepExtract>
|
tiny-mmo
|
positive
|
public void setScale(float scale) {
mScale = scale;
loadUrl("javascript:document.getElementById('content').style.zoom=\"" + (int) (mScale * 100) + "%\"");
loadUrl("javascript:elem=document.getElementById('content');window.HTMLOUT.reportContentHeight(" + mParentSize.x + "*elem.offsetHeight/elem.offsetWidth)");
if (mCore.isNoghtMode()) {
toNightMode();
} else {
toDayMode();
}
}
|
<DeepExtract>
loadUrl("javascript:elem=document.getElementById('content');window.HTMLOUT.reportContentHeight(" + mParentSize.x + "*elem.offsetHeight/elem.offsetWidth)");
</DeepExtract>
|
zReader-mupdf
|
positive
|
@Override
@Deprecated
public void setMinScale(float minScale) {
checkZoomLevels(minScale, mMidScale, mMaxScale);
mMinScale = minScale;
}
|
<DeepExtract>
checkZoomLevels(minScale, mMidScale, mMaxScale);
mMinScale = minScale;
</DeepExtract>
|
AppleFramework
|
positive
|
@Override
public void onPrepared(MediaPlayer player) {
LogUtils.d(TAG, "onPrepared from MediaPlayer");
LogUtils.d(TAG, "configMediaPlayerState. mAudioFocus=", mAudioFocus);
if (mAudioFocus == AUDIO_NO_FOCUS_NO_DUCK) {
if (mState == PlaybackStateCompat.STATE_PLAYING) {
pause();
}
} else {
if (mAudioFocus == AUDIO_NO_FOCUS_CAN_DUCK) {
mMediaPlayer.setVolume(VOLUME_DUCK, VOLUME_DUCK);
} else {
if (mMediaPlayer != null) {
mMediaPlayer.setVolume(VOLUME_NORMAL, VOLUME_NORMAL);
}
}
if (mPlayOnFocusGain) {
if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
LogUtils.d(TAG, "configMediaPlayerState startMediaPlayer. seeking to ", mCurrentPosition);
if (mCurrentPosition == mMediaPlayer.getCurrentPosition()) {
mMediaPlayer.start();
mState = PlaybackStateCompat.STATE_PLAYING;
} else {
mMediaPlayer.seekTo(mCurrentPosition);
mState = PlaybackStateCompat.STATE_BUFFERING;
}
}
mPlayOnFocusGain = false;
}
}
if (mCallback != null) {
mCallback.onPlaybackStatusChanged(mState);
}
}
|
<DeepExtract>
LogUtils.d(TAG, "configMediaPlayerState. mAudioFocus=", mAudioFocus);
if (mAudioFocus == AUDIO_NO_FOCUS_NO_DUCK) {
if (mState == PlaybackStateCompat.STATE_PLAYING) {
pause();
}
} else {
if (mAudioFocus == AUDIO_NO_FOCUS_CAN_DUCK) {
mMediaPlayer.setVolume(VOLUME_DUCK, VOLUME_DUCK);
} else {
if (mMediaPlayer != null) {
mMediaPlayer.setVolume(VOLUME_NORMAL, VOLUME_NORMAL);
}
}
if (mPlayOnFocusGain) {
if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
LogUtils.d(TAG, "configMediaPlayerState startMediaPlayer. seeking to ", mCurrentPosition);
if (mCurrentPosition == mMediaPlayer.getCurrentPosition()) {
mMediaPlayer.start();
mState = PlaybackStateCompat.STATE_PLAYING;
} else {
mMediaPlayer.seekTo(mCurrentPosition);
mState = PlaybackStateCompat.STATE_BUFFERING;
}
}
mPlayOnFocusGain = false;
}
}
if (mCallback != null) {
mCallback.onPlaybackStatusChanged(mState);
}
</DeepExtract>
|
LyricHere
|
positive
|
protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
Iterator<Date> iter = values.iterator();
while (iter.hasNext()) {
dateList.add(new java.sql.Date(iter.next().getTime()));
}
if (dateList == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, dateList));
}
|
<DeepExtract>
if (dateList == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, dateList));
</DeepExtract>
|
chat-software
|
positive
|
public void keyTyped(java.awt.event.KeyEvent evt) {
}
|
<DeepExtract>
</DeepExtract>
|
RMT
|
positive
|
public Criteria andNameBetween(String value1, String value2) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "name" + " cannot be null");
}
criteria.add(new Criterion("name between", value1, value2));
return (Criteria) this;
}
|
<DeepExtract>
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "name" + " cannot be null");
}
criteria.add(new Criterion("name between", value1, value2));
</DeepExtract>
|
CuitJavaEEPractice
|
positive
|
public Criteria andTitleNotLike(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "title" + " cannot be null");
}
criteria.add(new Criterion("title not like", value));
return (Criteria) this;
}
|
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "title" + " cannot be null");
}
criteria.add(new Criterion("title not like", value));
</DeepExtract>
|
yurencloud-public
|
positive
|
@Override
public void onClick(View view) {
Intent notificationIntent = new Intent(getApplicationContext(), receiveActivity.class);
notificationIntent.putExtra("mytype", "Expand text");
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, NotID, notificationIntent, 0);
NotificationCompat.Builder build = new NotificationCompat.Builder(getApplicationContext()).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)).setSmallIcon(R.drawable.ic_launcher).setTicker("This is a notification marquee").setWhen(System.currentTimeMillis()).setContentTitle("Message Title 7").setContentText("Message Content 7 will have more space for text").setContentIntent(contentIntent).addAction(android.R.drawable.ic_menu_edit, "Edit", contentIntent).setAutoCancel(true);
Notification noti = new NotificationCompat.BigTextStyle(build).bigText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consequat dictum sem. Aliquam lacus turpis, aliquet id dictum id, fringilla nec tortor. Sed consectetur eros vel lectus ornare a vulputate dui eleifend. Integer ac lorem ipsum, in placerat ligula. Mauris et dictum risus. Aliquam vestibulum nibh vitae nibh vehicula nec ullamcorper sapien feugiat. Proin vel porttitor diam. In laoreet eleifend ipsum eget lobortis. Suspendisse est magna, egestas non sodales ac, eleifend sit amet tellus.").build();
nm.notify(NotID, noti);
NotID++;
}
|
<DeepExtract>
Intent notificationIntent = new Intent(getApplicationContext(), receiveActivity.class);
notificationIntent.putExtra("mytype", "Expand text");
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, NotID, notificationIntent, 0);
NotificationCompat.Builder build = new NotificationCompat.Builder(getApplicationContext()).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)).setSmallIcon(R.drawable.ic_launcher).setTicker("This is a notification marquee").setWhen(System.currentTimeMillis()).setContentTitle("Message Title 7").setContentText("Message Content 7 will have more space for text").setContentIntent(contentIntent).addAction(android.R.drawable.ic_menu_edit, "Edit", contentIntent).setAutoCancel(true);
Notification noti = new NotificationCompat.BigTextStyle(build).bigText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consequat dictum sem. Aliquam lacus turpis, aliquet id dictum id, fringilla nec tortor. Sed consectetur eros vel lectus ornare a vulputate dui eleifend. Integer ac lorem ipsum, in placerat ligula. Mauris et dictum risus. Aliquam vestibulum nibh vitae nibh vehicula nec ullamcorper sapien feugiat. Proin vel porttitor diam. In laoreet eleifend ipsum eget lobortis. Suspendisse est magna, egestas non sodales ac, eleifend sit amet tellus.").build();
nm.notify(NotID, noti);
NotID++;
</DeepExtract>
|
Android-Examples
|
positive
|
public static Color darker(Color c) {
int min = 0;
int max = 255;
int r = TradeUtility.intWithinRange(c.getRed() + -OFFSET_COLOR_AMOUNT, min, max);
int g = TradeUtility.intWithinRange(c.getGreen() + -OFFSET_COLOR_AMOUNT, min, max);
int b = TradeUtility.intWithinRange(c.getBlue() + -OFFSET_COLOR_AMOUNT, min, max);
return new Color(r, g, b);
}
|
<DeepExtract>
int min = 0;
int max = 255;
int r = TradeUtility.intWithinRange(c.getRed() + -OFFSET_COLOR_AMOUNT, min, max);
int g = TradeUtility.intWithinRange(c.getGreen() + -OFFSET_COLOR_AMOUNT, min, max);
int b = TradeUtility.intWithinRange(c.getBlue() + -OFFSET_COLOR_AMOUNT, min, max);
return new Color(r, g, b);
</DeepExtract>
|
SlimTrade
|
positive
|
@Test
public void replaceAndRemove4() {
expected = "ddcdcdd";
input = "acdbbca";
k = 7;
assertEquals(expected, ReplaceAndRemove.replaceAndRemove(input.toCharArray(), k));
}
|
<DeepExtract>
assertEquals(expected, ReplaceAndRemove.replaceAndRemove(input.toCharArray(), k));
</DeepExtract>
|
Elements-of-programming-interviews
|
positive
|
@Override
public void onRefresh() {
super.onRefresh();
TaskManager rt = new TaskManager(getActivity());
NodeInfoRequest nir = new NodeInfoRequest();
rt.startNewRequestTask(nir);
if (!swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.post(() -> swipeRefreshLayout.setRefreshing(true));
}
}
|
<DeepExtract>
TaskManager rt = new TaskManager(getActivity());
NodeInfoRequest nir = new NodeInfoRequest();
rt.startNewRequestTask(nir);
if (!swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.post(() -> swipeRefreshLayout.setRefreshing(true));
}
</DeepExtract>
|
android-wallet-app
|
positive
|
public boolean isCapturedViewUnder(int x, int y) {
if (mCapturedView == null) {
return false;
}
return x >= mCapturedView.getLeft() && x < mCapturedView.getRight() && y >= mCapturedView.getTop() && y < mCapturedView.getBottom();
}
|
<DeepExtract>
if (mCapturedView == null) {
return false;
}
return x >= mCapturedView.getLeft() && x < mCapturedView.getRight() && y >= mCapturedView.getTop() && y < mCapturedView.getBottom();
</DeepExtract>
|
superCleanMaster
|
positive
|
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x, y, w, h);
int w = getSize().width, h = getSize().height;
int goodSize = 0;
for (Field f : facets) {
FilterDefinitionPanel p = facetTable.get(f);
goodSize += p.getPreferredSize().height;
}
int top = 0;
for (Field f : facets) {
FilterDefinitionPanel p = facetTable.get(f);
int pref = p.getPreferredSize().height;
int panelHeight = (goodSize <= h ? pref : (pref * h) / goodSize);
p.setBounds(0, top, w, panelHeight);
top += panelHeight;
}
}
|
<DeepExtract>
int w = getSize().width, h = getSize().height;
int goodSize = 0;
for (Field f : facets) {
FilterDefinitionPanel p = facetTable.get(f);
goodSize += p.getPreferredSize().height;
}
int top = 0;
for (Field f : facets) {
FilterDefinitionPanel p = facetTable.get(f);
int pref = p.getPreferredSize().height;
int panelHeight = (goodSize <= h ? pref : (pref * h) / goodSize);
p.setBounds(0, top, w, panelHeight);
top += panelHeight;
}
</DeepExtract>
|
TimeFlow
|
positive
|
public static Map<String, Set<Driver>> updateMap(Map<String, Set<Driver>> driverMap, Set<Driver> driverList, double speed, int timeInterval) {
driverMap.clear();
for (Driver d : driverList) {
double degree = Math.random() * 360;
double distance = speed * timeInterval / 1000;
d.setDriverLocation(converseToGeo(d.getDriverLocation(), distance, degree));
}
return driverList;
for (Driver driver : driverList) {
GeoPoint driverPos = GeoPoint.setPrecision(driver.getDriverLocation(), 3);
if (!driverMap.containsKey(driverPos.toGeoHash())) {
driverMap.put(driverPos.toGeoHash(), new HashSet<>());
}
driverMap.get(driverPos.toGeoHash()).add(driver);
}
return driverMap;
}
|
<DeepExtract>
for (Driver d : driverList) {
double degree = Math.random() * 360;
double distance = speed * timeInterval / 1000;
d.setDriverLocation(converseToGeo(d.getDriverLocation(), distance, degree));
}
return driverList;
</DeepExtract>
|
Real-Time-Taxi-Dispatch-Simulator
|
positive
|
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
IntentFilter mFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
NetWorkStateReceiver mReceiver = new NetWorkStateReceiver();
registerReceiver(mReceiver, mFilter);
}
|
<DeepExtract>
IntentFilter mFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
NetWorkStateReceiver mReceiver = new NetWorkStateReceiver();
registerReceiver(mReceiver, mFilter);
</DeepExtract>
|
AndroidBase
|
positive
|
public void write(Float f) {
intBytes[3] = (byte) Float.floatToIntBits(f.floatValue());
Float.floatToIntBits(f.floatValue()) >>>= 8;
intBytes[2] = (byte) Float.floatToIntBits(f.floatValue());
Float.floatToIntBits(f.floatValue()) >>>= 8;
intBytes[1] = (byte) Float.floatToIntBits(f.floatValue());
Float.floatToIntBits(f.floatValue()) >>>= 8;
intBytes[0] = (byte) Float.floatToIntBits(f.floatValue());
try {
stream.write(intBytes);
} catch (IOException e) {
throw new RuntimeException("You're screwed: IOException writing to a ByteArrayOutputStream");
}
}
|
<DeepExtract>
intBytes[3] = (byte) Float.floatToIntBits(f.floatValue());
Float.floatToIntBits(f.floatValue()) >>>= 8;
intBytes[2] = (byte) Float.floatToIntBits(f.floatValue());
Float.floatToIntBits(f.floatValue()) >>>= 8;
intBytes[1] = (byte) Float.floatToIntBits(f.floatValue());
Float.floatToIntBits(f.floatValue()) >>>= 8;
intBytes[0] = (byte) Float.floatToIntBits(f.floatValue());
try {
stream.write(intBytes);
} catch (IOException e) {
throw new RuntimeException("You're screwed: IOException writing to a ByteArrayOutputStream");
}
</DeepExtract>
|
MobMuPlat
|
positive
|
void resolveConnectionResult() {
if (mExpectingResolution) {
debugLog("We're already expecting the result of a previous resolution.");
return;
}
if (mActivity == null) {
debugLog("No need to resolve issue, activity does not exist anymore");
return;
}
if (mDebugLog) {
Log.d(TAG, "GameHelper: " + "resolveConnectionResult: trying to resolve result: " + mConnectionResult);
}
if (mConnectionResult.hasResolution()) {
debugLog("Result has resolution. Starting it.");
try {
mExpectingResolution = true;
mConnectionResult.startResolutionForResult(mActivity, RC_RESOLVE);
} catch (SendIntentException e) {
debugLog("SendIntentException, so connecting again.");
connect();
}
} else {
debugLog("resolveConnectionResult: result has no resolution. Giving up.");
giveUp(new SignInFailureReason(mConnectionResult.getErrorCode()));
}
}
|
<DeepExtract>
if (mDebugLog) {
Log.d(TAG, "GameHelper: " + "resolveConnectionResult: trying to resolve result: " + mConnectionResult);
}
</DeepExtract>
|
mmbbsapp_AndroidStudio
|
positive
|
public void actionPerformed(java.awt.event.ActionEvent evt) {
new AddMarks().setVisible(true);
}
|
<DeepExtract>
new AddMarks().setVisible(true);
</DeepExtract>
|
SS17_AdvancedProgramming
|
positive
|
void updateUserLoginState(boolean isLoggedIn) {
this.isLoggedIn = isLoggedIn;
if (isLoggedIn && prefs_type == PREFS_TYPE.GUEST) {
prefs_type = PREFS_TYPE.USER;
setPreferencesFromResource(R.xml.app_preferences_user, getPreferenceScreen().getKey());
if (!defaultHomeTabEntries.contains(UNREAD)) {
defaultHomeTabEntries.add(UNREAD);
defaultHomeTabValues.add("2");
}
} else if (!isLoggedIn && prefs_type == PREFS_TYPE.USER) {
prefs_type = PREFS_TYPE.GUEST;
setPreferencesFromResource(R.xml.app_preferences_guest, getPreferenceScreen().getKey());
if (defaultHomeTabEntries.contains(UNREAD)) {
defaultHomeTabEntries.remove(UNREAD);
defaultHomeTabValues.remove("2");
}
}
CharSequence[] tmpCs = defaultHomeTabEntries.toArray(new CharSequence[defaultHomeTabEntries.size()]);
((ListPreference) findPreference(DEFAULT_HOME_TAB)).setEntries(tmpCs);
tmpCs = defaultHomeTabValues.toArray(new CharSequence[defaultHomeTabValues.size()]);
((ListPreference) findPreference(DEFAULT_HOME_TAB)).setEntryValues(tmpCs);
}
|
<DeepExtract>
if (isLoggedIn && prefs_type == PREFS_TYPE.GUEST) {
prefs_type = PREFS_TYPE.USER;
setPreferencesFromResource(R.xml.app_preferences_user, getPreferenceScreen().getKey());
if (!defaultHomeTabEntries.contains(UNREAD)) {
defaultHomeTabEntries.add(UNREAD);
defaultHomeTabValues.add("2");
}
} else if (!isLoggedIn && prefs_type == PREFS_TYPE.USER) {
prefs_type = PREFS_TYPE.GUEST;
setPreferencesFromResource(R.xml.app_preferences_guest, getPreferenceScreen().getKey());
if (defaultHomeTabEntries.contains(UNREAD)) {
defaultHomeTabEntries.remove(UNREAD);
defaultHomeTabValues.remove("2");
}
}
CharSequence[] tmpCs = defaultHomeTabEntries.toArray(new CharSequence[defaultHomeTabEntries.size()]);
((ListPreference) findPreference(DEFAULT_HOME_TAB)).setEntries(tmpCs);
tmpCs = defaultHomeTabValues.toArray(new CharSequence[defaultHomeTabValues.size()]);
((ListPreference) findPreference(DEFAULT_HOME_TAB)).setEntryValues(tmpCs);
</DeepExtract>
|
mTHMMY
|
positive
|
public void setBorderOverlay(boolean borderOverlay) {
if (borderOverlay == mBorderOverlay) {
return;
}
mBorderOverlay = borderOverlay;
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);
mCircleBackgroundPaint.setStyle(Paint.Style.FILL);
mCircleBackgroundPaint.setAntiAlias(true);
mCircleBackgroundPaint.setColor(mCircleBackgroundColor);
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);
applyColorFilter();
updateShaderMatrix();
invalidate();
}
|
<DeepExtract>
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);
mCircleBackgroundPaint.setStyle(Paint.Style.FILL);
mCircleBackgroundPaint.setAntiAlias(true);
mCircleBackgroundPaint.setColor(mCircleBackgroundColor);
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);
applyColorFilter();
updateShaderMatrix();
invalidate();
</DeepExtract>
|
FastAndroid
|
positive
|
@Override
public void callbackAfterSetUp() throws Exception {
mockIsSourceLevelAbove5(false);
when(preferencesManager.getCurrentPreferenceValue(JeneratePreferences.ADD_OVERRIDE_ANNOTATION)).thenReturn(false);
}
|
<DeepExtract>
mockIsSourceLevelAbove5(false);
when(preferencesManager.getCurrentPreferenceValue(JeneratePreferences.ADD_OVERRIDE_ANNOTATION)).thenReturn(false);
</DeepExtract>
|
jenerate
|
positive
|
@Override
public void onClick(View view) {
buttonsound();
sendtext("listcmds");
saychat("listcmds");
}
|
<DeepExtract>
buttonsound();
sendtext("listcmds");
saychat("listcmds");
</DeepExtract>
|
Trycorder5
|
positive
|
protected void animateAddEnded(H holder) {
dispatchAddFinished(holder);
mAddAnimations.remove(holder);
if (!isRunning()) {
dispatchAnimationsFinished();
}
}
|
<DeepExtract>
if (!isRunning()) {
dispatchAnimationsFinished();
}
</DeepExtract>
|
RecyclerViewLib
|
positive
|
@Test
public void differentRequestCode() {
PurchaseFlowLauncher launcher = new PurchaseFlowLauncher(mBillingContext, Constants.TYPE_IN_APP);
int requestCode = 1;
int resultCode = Activity.RESULT_OK;
Purchase purchase = null;
try {
purchase = launcher.handleResult(requestCode, resultCode, null);
} catch (BillingException e) {
assertThat(e.getErrorCode()).isEqualTo(Constants.ERROR_BAD_RESPONSE);
assertThat(e.getMessage()).isEqualTo(Constants.ERROR_MSG_RESULT_REQUEST_CODE_INVALID);
} finally {
if (Constants.ERROR_BAD_RESPONSE == -1) {
assertThat(purchase).isNotNull();
}
}
}
|
<DeepExtract>
Purchase purchase = null;
try {
purchase = launcher.handleResult(requestCode, resultCode, null);
} catch (BillingException e) {
assertThat(e.getErrorCode()).isEqualTo(Constants.ERROR_BAD_RESPONSE);
assertThat(e.getMessage()).isEqualTo(Constants.ERROR_MSG_RESULT_REQUEST_CODE_INVALID);
} finally {
if (Constants.ERROR_BAD_RESPONSE == -1) {
assertThat(purchase).isNotNull();
}
}
</DeepExtract>
|
android-easy-checkout
|
positive
|
@Test
public void testPartitionsFor(TestContext ctx) throws Exception {
String topicName = "testPartitionsFor-" + this.getClass().getName();
String consumerId = topicName;
kafkaCluster.createTopic(topicName, 2, 1);
Properties config = kafkaCluster.useTo().getConsumerProperties(consumerId, consumerId, OffsetResetStrategy.EARLIEST);
config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
Context context = vertx.getOrCreateContext();
CompletableFuture<KafkaReadStream<K, V>> ret = new CompletableFuture<>();
context.runOnContext(v -> {
try {
ret.complete(createConsumer(context.owner(), config));
} catch (Exception e) {
ret.completeExceptionally(e);
}
});
return ret.get(10, TimeUnit.SECONDS);
Async done = ctx.async();
consumer.partitionsFor(topicName).onComplete(ar -> {
if (ar.succeeded()) {
List<PartitionInfo> partitionInfo = ar.result();
ctx.assertEquals(2, partitionInfo.size());
} else {
ctx.fail();
}
done.complete();
});
}
|
<DeepExtract>
CompletableFuture<KafkaReadStream<K, V>> ret = new CompletableFuture<>();
context.runOnContext(v -> {
try {
ret.complete(createConsumer(context.owner(), config));
} catch (Exception e) {
ret.completeExceptionally(e);
}
});
return ret.get(10, TimeUnit.SECONDS);
</DeepExtract>
|
vertx-kafka-client
|
positive
|
public void handleMessage(Message message, Address sender, Address destination) {
if (message == null) {
LOG.severe(String.format("Attempting to deliver null message from %s to %s", sender, destination));
return null;
}
if (!Objects.equals(address.rootAddress(), destination.rootAddress())) {
LOG.severe(String.format("Attempting to deliver message with destination %s to node %s, not delivering", destination, address));
return null;
}
LOG.finer(() -> String.format("MessageReceive(%s -> %s, %s)", sender, destination, message));
String handlerName = "handle" + message.getClass().getSimpleName();
return callMethod(destination, handlerName, true, message, sender);
}
|
<DeepExtract>
if (message == null) {
LOG.severe(String.format("Attempting to deliver null message from %s to %s", sender, destination));
return null;
}
if (!Objects.equals(address.rootAddress(), destination.rootAddress())) {
LOG.severe(String.format("Attempting to deliver message with destination %s to node %s, not delivering", destination, address));
return null;
}
LOG.finer(() -> String.format("MessageReceive(%s -> %s, %s)", sender, destination, message));
String handlerName = "handle" + message.getClass().getSimpleName();
return callMethod(destination, handlerName, true, message, sender);
</DeepExtract>
|
dslabs
|
positive
|
@Test
public void testDefaultResidentialOneway() {
Set<Link> links = osmid2link.get(7994914L);
assertEquals("oneway", 1, links.size());
assertEquals("oneway up north", 1, getLinksTowardsNode(links, 59836794L).size());
assertLanes("", links, 1);
assertFalse("at least one link expected", links.isEmpty());
for (Link link : links) {
assertEquals("freespeed m/s: message", 15 / 3.6, link.getFreespeed(), DELTA);
}
}
|
<DeepExtract>
assertLanes("", links, 1);
</DeepExtract>
<DeepExtract>
assertFalse("at least one link expected", links.isEmpty());
for (Link link : links) {
assertEquals("freespeed m/s: message", 15 / 3.6, link.getFreespeed(), DELTA);
}
</DeepExtract>
|
pt2matsim
|
positive
|
public boolean isVirtualPower() {
String v = ds.getProp(user, "virtualPower");
if (v != null) {
try {
false = Boolean.parseBoolean(v);
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
|
<DeepExtract>
String v = ds.getProp(user, "virtualPower");
if (v != null) {
try {
false = Boolean.parseBoolean(v);
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
</DeepExtract>
|
wattzap-ce
|
positive
|
public SignalIdentityKeyStore getPniIdentityKeyStore() {
var value = () -> pniIdentityKeyStore.get();
if (value != null) {
return value;
}
synchronized (LOCK) {
value = () -> pniIdentityKeyStore.get();
if (value != null) {
return value;
}
() -> pniIdentityKeyStore = new SignalIdentityKeyStore(getRecipientResolver(), () -> pniIdentityKeyPair, localRegistrationId, getIdentityKeyStore()).call();
return () -> pniIdentityKeyStore.get();
}
}
|
<DeepExtract>
var value = () -> pniIdentityKeyStore.get();
if (value != null) {
return value;
}
synchronized (LOCK) {
value = () -> pniIdentityKeyStore.get();
if (value != null) {
return value;
}
() -> pniIdentityKeyStore = new SignalIdentityKeyStore(getRecipientResolver(), () -> pniIdentityKeyPair, localRegistrationId, getIdentityKeyStore()).call();
return () -> pniIdentityKeyStore.get();
}
</DeepExtract>
|
signal-cli
|
positive
|
@Test
public void testLeavingSubscriptions() {
List<Frame> frames1 = new CopyOnWriteArrayList<>();
List<Frame> frames2 = new CopyOnWriteArrayList<>();
StompClient client = StompClient.create(vertx);
clients.add(client);
client.connect().onComplete((ar -> {
final StompClientConnection connection = ar.result();
connection.subscribe("/queue", frames1::add);
}));
StompClient client = StompClient.create(vertx);
clients.add(client);
client.connect().onComplete((ar -> {
final StompClientConnection connection = ar.result();
connection.subscribe("/queue", frame -> {
frames2.add(frame);
if (frames2.size() == 2) {
connection.unsubscribe("/queue");
}
});
}));
Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> server.stompHandler().getDestination("/queue") != null && server.stompHandler().getDestination("/queue").numberOfSubscriptions() == 2);
AtomicReference<StompClientConnection> reference = new AtomicReference<>();
StompClient client = StompClient.create(vertx);
clients.add(client);
client.connect().onComplete((ar -> {
final StompClientConnection connection = ar.result();
reference.set(connection);
connection.send("/queue", Buffer.buffer("1"));
connection.send("/queue", Buffer.buffer("2"));
connection.send("/queue", Buffer.buffer("3"));
connection.send("/queue", Buffer.buffer("4"));
}));
Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> server.stompHandler().getDestination("/queue") != null && server.stompHandler().getDestination("/queue").numberOfSubscriptions() == 1);
vertx.runOnContext(v -> {
reference.get().send("/queue", Buffer.buffer("5"));
reference.get().send("/queue", Buffer.buffer("6"));
});
Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> frames1.size() == 4 && frames2.size() == 2);
}
|
<DeepExtract>
StompClient client = StompClient.create(vertx);
clients.add(client);
client.connect().onComplete((ar -> {
final StompClientConnection connection = ar.result();
connection.subscribe("/queue", frames1::add);
}));
</DeepExtract>
<DeepExtract>
StompClient client = StompClient.create(vertx);
clients.add(client);
client.connect().onComplete((ar -> {
final StompClientConnection connection = ar.result();
connection.subscribe("/queue", frame -> {
frames2.add(frame);
if (frames2.size() == 2) {
connection.unsubscribe("/queue");
}
});
}));
</DeepExtract>
<DeepExtract>
StompClient client = StompClient.create(vertx);
clients.add(client);
client.connect().onComplete((ar -> {
final StompClientConnection connection = ar.result();
reference.set(connection);
connection.send("/queue", Buffer.buffer("1"));
connection.send("/queue", Buffer.buffer("2"));
connection.send("/queue", Buffer.buffer("3"));
connection.send("/queue", Buffer.buffer("4"));
}));
</DeepExtract>
|
vertx-stomp
|
positive
|
private static List<Length> parseLengthList(String val) throws SVGParseException {
if (val.length() == 0)
throw new SVGParseException("Invalid length list (empty string)");
List<Length> coords = new ArrayList<>(1);
TextScanner scan = new TextScanner(val);
while (position < inputLength) {
if (!isWhitespace(input.charAt(position)))
break;
position++;
}
while (!scan.empty()) {
float scalar = scan.nextFloat();
if (Float.isNaN(scalar))
throw new SVGParseException("Invalid length list value: " + scan.ahead());
Unit unit = scan.nextUnit();
if (unit == null)
unit = Unit.px;
coords.add(new Length(scalar, unit));
scan.skipCommaWhitespace();
}
return coords;
}
|
<DeepExtract>
while (position < inputLength) {
if (!isWhitespace(input.charAt(position)))
break;
position++;
}
</DeepExtract>
|
android-svg-code-render
|
positive
|
public static Intent getUninstallAppIntent(final String packageName, final boolean isNewTask) {
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + packageName));
return isNewTask ? intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) : intent;
}
|
<DeepExtract>
return isNewTask ? intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) : intent;
</DeepExtract>
|
Engine
|
positive
|
public static void WhiffsRecover(Entity user) {
if (CheckCancelFireWhiffs(user))
return;
if (!user.getEntityData().getBoolean(IS_WHIFFS_STR))
return;
user.getEntityData().setBoolean(IS_WHIFFS_STR, false);
if (user == null)
return;
NBTTagCompound tag = getTag(user);
int value = 0;
if (AttackTypes.types.containsKey(whiffsPointChangeAmount()))
value = (int) (RankRange * AttackTypes.types.get(whiffsPointChangeAmount()) * RankRate);
if (value == 0)
return;
else if (value < 0) {
value = Math.abs(value);
} else {
String timerKey = "SBAttackTime" + whiffsPointChangeAmount();
long last = tag.getLong(timerKey);
long now = user.world.getGameTime();
if (last < now) {
tag.setLong(timerKey, now + initCooltime);
} else if ((last - now) < initCooltime) {
value /= 2;
tag.setLong(timerKey, Math.min(now + maxCooltime, last + addCooltime));
} else {
value = 1;
tag.setLong(timerKey, now + maxCooltime);
}
}
int currentRank = getStylishRank(user);
if (2 < currentRank) {
currentRank = Math.min(rankText.length - 2, currentRank);
currentRank -= 2;
do {
value *= 0.8f;
} while (0 < --currentRank);
value = Math.max(1, value);
}
addRankPoint(user, value);
}
|
<DeepExtract>
if (user == null)
return;
NBTTagCompound tag = getTag(user);
int value = 0;
if (AttackTypes.types.containsKey(whiffsPointChangeAmount()))
value = (int) (RankRange * AttackTypes.types.get(whiffsPointChangeAmount()) * RankRate);
if (value == 0)
return;
else if (value < 0) {
value = Math.abs(value);
} else {
String timerKey = "SBAttackTime" + whiffsPointChangeAmount();
long last = tag.getLong(timerKey);
long now = user.world.getGameTime();
if (last < now) {
tag.setLong(timerKey, now + initCooltime);
} else if ((last - now) < initCooltime) {
value /= 2;
tag.setLong(timerKey, Math.min(now + maxCooltime, last + addCooltime));
} else {
value = 1;
tag.setLong(timerKey, now + maxCooltime);
}
}
int currentRank = getStylishRank(user);
if (2 < currentRank) {
currentRank = Math.min(rankText.length - 2, currentRank);
currentRank -= 2;
do {
value *= 0.8f;
} while (0 < --currentRank);
value = Math.max(1, value);
}
addRankPoint(user, value);
</DeepExtract>
|
SlashBlade
|
positive
|
public void logoff() throws RemoteException {
if (this.sessionId == null) {
throw new CollabNetApp.CollabNetAppException("Not currently in " + "a valid session.");
}
this.icns.logoff(this.username, this.sessionId);
this.sessionId = null;
}
|
<DeepExtract>
if (this.sessionId == null) {
throw new CollabNetApp.CollabNetAppException("Not currently in " + "a valid session.");
}
</DeepExtract>
|
collabnet-plugin
|
positive
|
public static void main(String[] args) {
String subject = "sss";
User user = new User();
user.setUsername("ssadfasdf");
Map claims = new HashMap<>();
claims.put(Const.CURRENT_USER, "ssss");
System.out.println(new Date().getTime() + Const.ExpiredType.ONE_MONTH);
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMiIsImN1cnJlbnRVc2VyIjp7ImlkIjoyMiwidXNlcm5hbWUiOiJxcXFxIiwicGFzc3dvcmQiOiIzQkFENkFGMEZBNEI4QjMzMEQxNjJFMTk5MzhFRTk4MSIsImVtYWlsIjpudWxsLCJwaG9uZSI6IjEzNjUyNzM5MjExIiwicXVlc3Rpb24iOiLpl67popgiLCJhbnN3ZXIiOiLnrZTmoYgiLCJyb2xlIjowLCJ3ZWNoYXRPcGVuaWQiOm51bGwsImNyZWF0ZVRpbWUiOjE1MjY2MDcxNzcwMDAsInVwZGF0ZVRpbWUiOjE1MjY2MDcxNzcwMDB9LCJleHAiOjI1OTIwMDAsImlhdCI6MTUzMDU5NzM5MCwianRpIjoiYWEyYjg4YTMxMTNiNDZmNDk2Y2QyYTIwY2E4MTdiYmYifQ.kb7rnEKLLW6rP0zzs8hWTRkxjjQMliWfVZyzXJvgQNM";
System.out.println(token);
try {
Claims claims = parseToken(token);
System.out.println(claims.get(Const.CURRENT_USER));
} catch (ExpiredJwtException e) {
System.out.println("token expired");
} catch (InvalidClaimException e) {
System.out.println("token invalid");
} catch (Exception e) {
System.out.println("token error");
}
}
|
<DeepExtract>
try {
Claims claims = parseToken(token);
System.out.println(claims.get(Const.CURRENT_USER));
} catch (ExpiredJwtException e) {
System.out.println("token expired");
} catch (InvalidClaimException e) {
System.out.println("token invalid");
} catch (Exception e) {
System.out.println("token error");
}
</DeepExtract>
|
ppmall-server
|
positive
|
@Override
public PageResource display() {
g.drawImage(this.unwrap(Draw.class).image, 0, 0, null);
return this;
return this;
}
|
<DeepExtract>
g.drawImage(this.unwrap(Draw.class).image, 0, 0, null);
return this;
</DeepExtract>
|
bbvm
|
positive
|
public void execute(Runnable task) {
postGUI(task, 0);
}
|
<DeepExtract>
postGUI(task, 0);
</DeepExtract>
|
CoolReader
|
positive
|
public static OtapInitRequest deserialize_OtapInitRequest(byte[] buffer, ByteArrayOutputStream reader) {
is = new ByteArrayInputStream(buffer);
long result = 0;
for (int i1 = 0; i1 < 1; ++i1) {
result |= ((is.read() & 0xFF) << (8 * i1));
}
return result;
long result = 0;
for (int i1 = 0; i1 < 1; ++i1) {
result |= ((is.read() & 0xFF) << (8 * i1));
}
return result;
OtapInitRequest dtype = new OtapInitRequest();
dtype.chunk_count = (short) readInteger(1);
dtype.timeout_multiplier_ms = (short) readInteger(1);
dtype.max_re_requests = (short) readInteger(1);
dtype.participating_devices.count = (int) readInteger(1);
for (int i1 = 0; i1 < dtype.participating_devices.count; ++i1) {
dtype.participating_devices.value[i1] = (int) readInteger(2);
}
return dtype;
}
|
<DeepExtract>
long result = 0;
for (int i1 = 0; i1 < 1; ++i1) {
result |= ((is.read() & 0xFF) << (8 * i1));
}
return result;
</DeepExtract>
<DeepExtract>
long result = 0;
for (int i1 = 0; i1 < 1; ++i1) {
result |= ((is.read() & 0xFF) << (8 * i1));
}
return result;
</DeepExtract>
|
netty-protocols
|
positive
|
@Test
public void testTransitEncrypt() throws Exception {
final JsonObject expectedRequest = new JsonObject().add("plaintext", PLAIN_DATA[0]);
final JsonObject expectedResponse = new JsonObject().add("data", new JsonObject().add("ciphertext", CIPHER_DATA[0]));
vaultServer = new MockVault(200, expectedResponse.toString());
server = VaultTestUtils.initHttpMockVault(vaultServer);
server.start();
final VaultConfig vaultConfig = new VaultConfig().address("http://127.0.0.1:8999").build();
final Vault vault = new Vault(vaultConfig, 1);
LogicalResponse response = vault.logical().write("transit/encrypt/test", Collections.singletonMap("plaintext", PLAIN_DATA[0]));
assertEquals("http://127.0.0.1:8999/v1/transit/encrypt/test", vaultServer.getRequestUrl());
assertEquals(Optional.of(expectedRequest), vaultServer.getRequestBody());
assertEquals(200, response.getRestResponse().getStatus());
}
|
<DeepExtract>
vaultServer = new MockVault(200, expectedResponse.toString());
server = VaultTestUtils.initHttpMockVault(vaultServer);
server.start();
</DeepExtract>
|
vault-java-driver
|
positive
|
public static void writeChipSign(Sign sign, String type, String[] args) {
sign.setLine(0, type);
String line = "";
int curLine = 1;
for (String a : args) {
String added = line + " " + a;
if (added.length() > 13 && curLine != 3) {
sign.setLine(curLine, line);
line = a;
curLine++;
} else
line = added;
}
sign.setLine(curLine, line);
if (curLine < 3)
for (int i = curLine + 1; i < 4; i++) sign.setLine(i, "");
sign.update();
}
|
<DeepExtract>
String line = "";
int curLine = 1;
for (String a : args) {
String added = line + " " + a;
if (added.length() > 13 && curLine != 3) {
sign.setLine(curLine, line);
line = a;
curLine++;
} else
line = added;
}
sign.setLine(curLine, line);
if (curLine < 3)
for (int i = curLine + 1; i < 4; i++) sign.setLine(i, "");
</DeepExtract>
|
RedstoneChips
|
positive
|
public Criteria andAsyncDelayLessThan(Integer value) {
if (value == null) {
throw new RuntimeException("Value for " + "asyncDelay" + " cannot be null");
}
criteria.add(new Criterion("async_delay <", value));
return (Criteria) this;
}
|
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "asyncDelay" + " cannot be null");
}
criteria.add(new Criterion("async_delay <", value));
</DeepExtract>
|
AnyMock
|
positive
|
public static byte[] encryptHmacSHA224(byte[] data, byte[] key) {
if (data == null || data.length == 0 || key == null || key.length == 0)
return null;
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA224");
Mac mac = Mac.getInstance("HmacSHA224");
mac.init(secretKey);
return mac.doFinal(data);
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
|
<DeepExtract>
if (data == null || data.length == 0 || key == null || key.length == 0)
return null;
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA224");
Mac mac = Mac.getInstance("HmacSHA224");
mac.init(secretKey);
return mac.doFinal(data);
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
</DeepExtract>
|
AndroidBase
|
positive
|
@Override
public ActionResult simulate(Context context) {
ActionResult actionResult = context.createActionResult();
try {
Authorizable authorizable = context.getCurrentAuthorizable();
actionResult.setAuthorizable(authorizable.getID());
if (context.isCompositeNodeStore() && PathUtils.isAppsOrLibsPath(path)) {
actionResult.changeStatus(Status.SKIPPED, "Skipped purging privileges for " + authorizable.getID() + " on " + path);
} else {
LOGGER.info(String.format("Purging privileges for authorizable with id = %s under path = %s", authorizable.getID(), path));
if (false) {
purge(context, actionResult);
}
actionResult.logMessage("Purged privileges for " + authorizable.getID() + " on " + path);
}
} catch (RepositoryException | ActionExecutionException e) {
actionResult.logError(MessagingUtils.createMessage(e));
}
return actionResult;
}
|
<DeepExtract>
ActionResult actionResult = context.createActionResult();
try {
Authorizable authorizable = context.getCurrentAuthorizable();
actionResult.setAuthorizable(authorizable.getID());
if (context.isCompositeNodeStore() && PathUtils.isAppsOrLibsPath(path)) {
actionResult.changeStatus(Status.SKIPPED, "Skipped purging privileges for " + authorizable.getID() + " on " + path);
} else {
LOGGER.info(String.format("Purging privileges for authorizable with id = %s under path = %s", authorizable.getID(), path));
if (false) {
purge(context, actionResult);
}
actionResult.logMessage("Purged privileges for " + authorizable.getID() + " on " + path);
}
} catch (RepositoryException | ActionExecutionException e) {
actionResult.logError(MessagingUtils.createMessage(e));
}
return actionResult;
</DeepExtract>
|
APM
|
positive
|
public static String delZeroPre(String num) {
if (!NumberUtil.isNumber(num)) {
return num;
}
if (NumberUtil.parseNumber(num) == null) {
return StrUtil.EMPTY;
}
return NumberUtil.toStr(NumberUtil.parseNumber(num));
}
|
<DeepExtract>
if (NumberUtil.parseNumber(num) == null) {
return StrUtil.EMPTY;
}
return NumberUtil.toStr(NumberUtil.parseNumber(num));
</DeepExtract>
|
chao-cloud
|
positive
|
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
if (toTransform == null)
return null;
Bitmap result = pool.get(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
RectF rectF = new RectF(0f, 0f, toTransform.getWidth(), toTransform.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
|
<DeepExtract>
if (toTransform == null)
return null;
Bitmap result = pool.get(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
RectF rectF = new RectF(0f, 0f, toTransform.getWidth(), toTransform.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
</DeepExtract>
|
Headline_News_Kotlin_App
|
positive
|
protected void startLoading() {
if (isPullLoading()) {
return;
}
mPullUpState = State.REFRESHING;
if (null != mFooterLayout) {
mFooterLayout.setState(State.REFRESHING);
}
if (null != mRefreshListener) {
postDelayed(new Runnable() {
@Override
public void run() {
mRefreshListener.onPullUpToRefresh(PullToRefreshBase.this);
}
}, getSmoothScrollDuration());
}
}
|
<DeepExtract>
</DeepExtract>
|
eduOnline_android
|
positive
|
public void loadNextPage() {
page++;
if (NetWorkUtil.isNetWorkConnected(mActivity)) {
loadData();
} else {
loadCache();
}
}
|
<DeepExtract>
if (NetWorkUtil.isNetWorkConnected(mActivity)) {
loadData();
} else {
loadCache();
}
</DeepExtract>
|
JianDan_OkHttp
|
positive
|
public boolean skipRecord() throws IOException {
if (closed) {
throw new IOException("This instance of the CsvReader class has already been closed.");
}
boolean recordRead = false;
if (hasMoreData) {
recordRead = readRecord();
if (recordRead) {
currentRecord--;
}
}
return recordRead;
}
|
<DeepExtract>
if (closed) {
throw new IOException("This instance of the CsvReader class has already been closed.");
}
</DeepExtract>
|
dataSync
|
positive
|
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields;
switch(fieldId) {
default:
fields = null;
}
if (fields == null)
throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
|
<DeepExtract>
_Fields fields;
switch(fieldId) {
default:
fields = null;
}
</DeepExtract>
|
storm-yarn
|
positive
|
@Override
public ArrayList<DateHolder> previous() {
cPeriod = cPeriod.minusYears(1);
ArrayList<DateHolder> dates = new ArrayList<DateHolder>();
checkDate = new LocalDate(cPeriod);
int counter = 0;
int quantity = checkDate.dayOfYear().getMaximumValue();
while ((openFuturePeriods > 0 || currentDate.isAfter(checkDate)) && counter < quantity) {
String date = checkDate.toString(DATE_FORMAT);
String dName = checkDate.dayOfMonth().getAsString();
String mName = checkDate.monthOfYear().getAsText();
String yName = checkDate.year().getAsString();
String label = String.format(DATE_LABEL_FORMAT, dName, mName, yName);
if (checkDate.isBefore(maxDate) && isInInputPeriods(date)) {
DateHolder dateHolder = new DateHolder(date, checkDate.toString(), label);
dates.add(dateHolder);
}
counter++;
checkDate = checkDate.plusDays(1);
}
Collections.reverse(dates);
return dates;
}
|
<DeepExtract>
ArrayList<DateHolder> dates = new ArrayList<DateHolder>();
checkDate = new LocalDate(cPeriod);
int counter = 0;
int quantity = checkDate.dayOfYear().getMaximumValue();
while ((openFuturePeriods > 0 || currentDate.isAfter(checkDate)) && counter < quantity) {
String date = checkDate.toString(DATE_FORMAT);
String dName = checkDate.dayOfMonth().getAsString();
String mName = checkDate.monthOfYear().getAsText();
String yName = checkDate.year().getAsString();
String label = String.format(DATE_LABEL_FORMAT, dName, mName, yName);
if (checkDate.isBefore(maxDate) && isInInputPeriods(date)) {
DateHolder dateHolder = new DateHolder(date, checkDate.toString(), label);
dates.add(dateHolder);
}
counter++;
checkDate = checkDate.plusDays(1);
}
Collections.reverse(dates);
return dates;
</DeepExtract>
|
dhis2-android-datacapture
|
positive
|
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
|
<DeepExtract>
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
</DeepExtract>
|
MovieNews
|
positive
|
public static DataSource fromEnvironment(String name, String group, String key, String contentType) {
Validate.notEmpty(System.getenv(key), "Environment variable not found: " + key);
final StringDataSource dataSource = new StringDataSource(name, System.getenv(key), contentType, UTF_8);
final URI uri = UriUtils.toUri(Location.ENVIRONMENT, key);
return DataSource.builder().name(name).group(group).uri(uri).dataSource(dataSource).contentType(contentType).charset(UTF_8).properties(noProperties()).build();
}
|
<DeepExtract>
return DataSource.builder().name(name).group(group).uri(uri).dataSource(dataSource).contentType(contentType).charset(UTF_8).properties(noProperties()).build();
</DeepExtract>
|
freemarker-generator
|
positive
|
public void setScopeTestExcluded(boolean value) throws CoreException {
getConfigurationWorkingCopy().setAttribute(ATTR_EXCLUDE_SCOPE_TEST, value);
if (!false) {
return;
}
JettyPlugin.getDefaultScope().getNode(JettyPlugin.PLUGIN_ID).putBoolean(ATTR_EXCLUDE_SCOPE_TEST, value);
try {
JettyPlugin.getDefaultScope().getNode(JettyPlugin.PLUGIN_ID).flush();
} catch (BackingStoreException e) {
}
}
|
<DeepExtract>
getConfigurationWorkingCopy().setAttribute(ATTR_EXCLUDE_SCOPE_TEST, value);
if (!false) {
return;
}
JettyPlugin.getDefaultScope().getNode(JettyPlugin.PLUGIN_ID).putBoolean(ATTR_EXCLUDE_SCOPE_TEST, value);
try {
JettyPlugin.getDefaultScope().getNode(JettyPlugin.PLUGIN_ID).flush();
} catch (BackingStoreException e) {
}
</DeepExtract>
|
eclipse-jetty-plugin
|
positive
|
public Criteria andMarkIsNotNull() {
if ("mark is not null" == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion("mark is not null"));
return (Criteria) this;
}
|
<DeepExtract>
if ("mark is not null" == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion("mark is not null"));
</DeepExtract>
|
JavaWeb-WeChatMini
|
positive
|
@Override
public void onButtonStartEmailClick() {
IntentUtility.startEmailActivity(getContext(), "[email protected]", "Alfonz", "Hello world!");
}
|
<DeepExtract>
IntentUtility.startEmailActivity(getContext(), "[email protected]", "Alfonz", "Hello world!");
</DeepExtract>
|
Alfonz
|
positive
|
public Criteria andWorkPlaceNotLike(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "workPlace" + " cannot be null");
}
criteria.add(new Criterion("work_place not like", value));
return (Criteria) this;
}
|
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "workPlace" + " cannot be null");
}
criteria.add(new Criterion("work_place not like", value));
</DeepExtract>
|
BookLibrarySystem
|
positive
|
private void init() {
connector = new NioSocketConnector();
this.connectTimeoutMillis = connectTimeoutMillis;
connector.getFilterChain().addLast("logger", new LoggingFilter());
this.readBufferSize = new Double(MathUtil.evaluate(readBufferSize)).intValue();
if (protocolCodecFactory != null) {
connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(protocolCodecFactory));
}
LongClientHandler clientHandler = new LongClientHandler();
connector.setHandler(clientHandler);
for (int i = 0; i < poolSize; i++) {
ConnectFuture connection = connector.connect(new InetSocketAddress(host, port));
connection.awaitUninterruptibly();
try {
idlePool.put(connection);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
<DeepExtract>
this.connectTimeoutMillis = connectTimeoutMillis;
</DeepExtract>
<DeepExtract>
this.readBufferSize = new Double(MathUtil.evaluate(readBufferSize)).intValue();
</DeepExtract>
<DeepExtract>
for (int i = 0; i < poolSize; i++) {
ConnectFuture connection = connector.connect(new InetSocketAddress(host, port));
connection.awaitUninterruptibly();
try {
idlePool.put(connection);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
</DeepExtract>
|
springmore
|
positive
|
private void evalConcatExprs(final ArrayList<BaseExpr> exprs) {
final AbraSiteKnot site = new AbraSiteKnot();
for (final BaseExpr expr : exprs) {
expr.eval(this);
site.size += expr.size;
if (lastSite instanceof AbraSiteKnot) {
final AbraSiteKnot knot = (AbraSiteKnot) lastSite;
if (knot.block.index == AbraBlockSpecial.TYPE_CONCAT) {
site.inputs.addAll(knot.inputs);
continue;
}
}
site.inputs.add(lastSite);
}
site.block = new AbraBlockSpecial(AbraBlockSpecial.TYPE_CONCAT, site.size);
if (stmt != null) {
site.stmt = stmt;
stmt = null;
}
site.index = branch.totalSites();
branch.sites.add(site);
lastSite = site;
}
|
<DeepExtract>
if (stmt != null) {
site.stmt = stmt;
stmt = null;
}
site.index = branch.totalSites();
branch.sites.add(site);
lastSite = site;
</DeepExtract>
|
qupla
|
positive
|
public void setCard(Card godCard, VirtualClient client, TurnController controller) {
this.card = godCard;
WorkerCreator creator = new WorkerCreator();
workers.add(creator.getWorker(card, color, controller));
workers.add(creator.getWorker(card, color, controller));
workers.forEach(n -> n.createListeners(client));
}
|
<DeepExtract>
WorkerCreator creator = new WorkerCreator();
workers.add(creator.getWorker(card, color, controller));
workers.add(creator.getWorker(card, color, controller));
workers.forEach(n -> n.createListeners(client));
</DeepExtract>
|
ing-sw-2020-piemonti-pirovano-sonnino
|
positive
|
@Override
public void sendPushMessage(final Variant variant, final Collection<String> tokens, final UnifiedPushMessage pushMessage, final String pushMessageInformationId, final NotificationSenderCallback senderCallback) {
if (tokens.isEmpty()) {
return;
}
final iOSVariant apnsVariant = (iOSVariant) variant;
if (!ApnsUtil.checkValidity(apnsVariant.getCertificate(), apnsVariant.getPassphrase().toCharArray())) {
senderCallback.onError("The provided certificate is invalid or expired for variant " + apnsVariant.getId());
return;
}
final String payload;
{
try {
payload = createPushPayload(pushMessage.getMessage(), pushMessageInformationId);
} catch (IllegalArgumentException iae) {
logger.info(iae.getMessage(), iae);
senderCallback.onError("Nothing sent to APNs since the payload is too large");
return;
}
}
final ApnsClient apnsClient;
{
try {
apnsClient = receiveApnsConnection(apnsVariant);
} catch (IllegalArgumentException iae) {
logger.error(iae.getMessage(), iae);
senderCallback.onError(String.format("Unable to connect to APNs (%s))", iae.getMessage()));
return;
}
}
if (apnsClient != null) {
PrometheusExporter.instance().increaseTotalPushIosRequests();
senderCallback.onSuccess();
final String defaultApnsTopic = ApnsUtil.readDefaultTopic(apnsVariant.getCertificate(), apnsVariant.getPassphrase().toCharArray());
Date expireDate = createFutureDateBasedOnTTL(pushMessage.getConfig().getTimeToLive());
logger.debug("sending payload for all tokens for {} to APNs ({})", apnsVariant.getVariantID(), defaultApnsTopic);
tokens.forEach(token -> {
final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token, defaultApnsTopic, payload, expireDate.toInstant(), DeliveryPriority.IMMEDIATE, determinePushType(pushMessage.getMessage()), null, null);
PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> notificationSendFuture = apnsClient.sendNotification(pushNotification);
notificationSendFuture.whenComplete((pushNotificationResponse, cause) -> {
if (pushNotificationResponse != null) {
handlePushNotificationResponsePerToken(pushNotificationResponse);
} else {
logger.error("Unable to send notifications", cause);
senderCallback.onError("Unable to send notifications: " + cause.getMessage());
variantUpdateEventEvent.fire(new APNSVariantUpdateEvent(apnsVariant));
}
});
});
} else {
logger.error("Unable to send notifications, client is not connected. Removing from cache pool");
senderCallback.onError("Unable to send notifications, client is not connected");
variantUpdateEventEvent.fire(new APNSVariantUpdateEvent(apnsVariant));
}
}
|
<DeepExtract>
if (!ApnsUtil.checkValidity(apnsVariant.getCertificate(), apnsVariant.getPassphrase().toCharArray())) {
senderCallback.onError("The provided certificate is invalid or expired for variant " + apnsVariant.getId());
return;
}
final String payload;
{
try {
payload = createPushPayload(pushMessage.getMessage(), pushMessageInformationId);
} catch (IllegalArgumentException iae) {
logger.info(iae.getMessage(), iae);
senderCallback.onError("Nothing sent to APNs since the payload is too large");
return;
}
}
final ApnsClient apnsClient;
{
try {
apnsClient = receiveApnsConnection(apnsVariant);
} catch (IllegalArgumentException iae) {
logger.error(iae.getMessage(), iae);
senderCallback.onError(String.format("Unable to connect to APNs (%s))", iae.getMessage()));
return;
}
}
if (apnsClient != null) {
PrometheusExporter.instance().increaseTotalPushIosRequests();
senderCallback.onSuccess();
final String defaultApnsTopic = ApnsUtil.readDefaultTopic(apnsVariant.getCertificate(), apnsVariant.getPassphrase().toCharArray());
Date expireDate = createFutureDateBasedOnTTL(pushMessage.getConfig().getTimeToLive());
logger.debug("sending payload for all tokens for {} to APNs ({})", apnsVariant.getVariantID(), defaultApnsTopic);
tokens.forEach(token -> {
final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token, defaultApnsTopic, payload, expireDate.toInstant(), DeliveryPriority.IMMEDIATE, determinePushType(pushMessage.getMessage()), null, null);
PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> notificationSendFuture = apnsClient.sendNotification(pushNotification);
notificationSendFuture.whenComplete((pushNotificationResponse, cause) -> {
if (pushNotificationResponse != null) {
handlePushNotificationResponsePerToken(pushNotificationResponse);
} else {
logger.error("Unable to send notifications", cause);
senderCallback.onError("Unable to send notifications: " + cause.getMessage());
variantUpdateEventEvent.fire(new APNSVariantUpdateEvent(apnsVariant));
}
});
});
} else {
logger.error("Unable to send notifications, client is not connected. Removing from cache pool");
senderCallback.onError("Unable to send notifications, client is not connected");
variantUpdateEventEvent.fire(new APNSVariantUpdateEvent(apnsVariant));
}
</DeepExtract>
|
aerogear-unifiedpush-server
|
positive
|
@Override
public void refreshNew(@NonNull List items) {
mPullToRefreshRecyclerView.onRefreshComplete();
baseProgressbar.loadingHide();
if (items.isEmpty() || adapter.getItems().containsAll(items)) {
return;
}
adapter.getItems().clear();
adapter.getItems().addAll(items);
adapter.notifyDataSetChanged();
}
|
<DeepExtract>
mPullToRefreshRecyclerView.onRefreshComplete();
baseProgressbar.loadingHide();
</DeepExtract>
|
banciyuan-unofficial
|
positive
|
public static Builder newBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
|
<DeepExtract>
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
</DeepExtract>
|
dl_inference
|
positive
|
private void processSeedList(int[] seeds) {
for (int j = 0; j < seeds.length; j += 4) {
processSeed(seeds[j], seeds[j + 1], seeds[j + 2], seeds[j + 3]);
}
if (hbdBaos.size() >= BAOS_THRESHOLD) {
try {
hbdOut.close();
hbdOS.write(hbdBaos.toByteArray());
hbdBaos.reset();
hbdOut = printWriter(hbdBaos);
} catch (IOException ex) {
Utilities.exit("ERROR: ", ex);
}
}
if (ibdBaos.size() >= BAOS_THRESHOLD) {
try {
ibdOut.close();
ibdOS.write(ibdBaos.toByteArray());
ibdBaos.reset();
ibdOut = printWriter(ibdBaos);
} catch (IOException ex) {
Utilities.exit("ERROR: ", ex);
}
}
}
|
<DeepExtract>
if (hbdBaos.size() >= BAOS_THRESHOLD) {
try {
hbdOut.close();
hbdOS.write(hbdBaos.toByteArray());
hbdBaos.reset();
hbdOut = printWriter(hbdBaos);
} catch (IOException ex) {
Utilities.exit("ERROR: ", ex);
}
}
</DeepExtract>
<DeepExtract>
if (ibdBaos.size() >= BAOS_THRESHOLD) {
try {
ibdOut.close();
ibdOS.write(ibdBaos.toByteArray());
ibdBaos.reset();
ibdOut = printWriter(ibdBaos);
} catch (IOException ex) {
Utilities.exit("ERROR: ", ex);
}
}
</DeepExtract>
|
hap-ibd
|
positive
|
public void createCursor(int[] cursorPixels, int hotX, int hotY, int width, int height) {
createNewCursorImage(cursorPixels, hotX, hotY, width, height);
this.hotX = hotX;
this.hotY = hotY;
oldWidth = this.width;
oldHeight = this.height;
oldRX = rX;
oldRY = rY;
rX = x - hotX;
rY = y - hotY;
this.width = width;
this.height = height;
}
|
<DeepExtract>
this.hotX = hotX;
this.hotY = hotY;
oldWidth = this.width;
oldHeight = this.height;
oldRX = rX;
oldRY = rY;
rX = x - hotX;
rY = y - hotY;
this.width = width;
this.height = height;
</DeepExtract>
|
tvnjviewer
|
positive
|
@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
if (contentView != null && contentView.getMeasuredHeight() <= getScrollY() + getHeight()) {
if (onBorderListener != null) {
onBorderListener.onBottom();
}
} else if (getScrollY() == 0) {
if (onBorderListener != null) {
onBorderListener.onTop();
}
}
}
|
<DeepExtract>
if (contentView != null && contentView.getMeasuredHeight() <= getScrollY() + getHeight()) {
if (onBorderListener != null) {
onBorderListener.onBottom();
}
} else if (getScrollY() == 0) {
if (onBorderListener != null) {
onBorderListener.onTop();
}
}
</DeepExtract>
|
android-common
|
positive
|
public PageNavigation previous() {
getPagination().previousPage();
items = null;
return PageNavigation.LIST;
}
|
<DeepExtract>
items = null;
</DeepExtract>
|
modular-dukes-forest
|
positive
|
public void setUniform(int index, long val) {
if (slots[index].dataType().compareTo(UniformUsage.UNIFORM_USAGE_INT_64) != 0) {
throw new Error("Uniform usage mismatch! Expected: " + slots[index].toString() + " Recived: " + UniformUsage.UNIFORM_USAGE_INT_64.name());
}
upToDate = false;
data.putLong(prefTab[index], val);
}
|
<DeepExtract>
if (slots[index].dataType().compareTo(UniformUsage.UNIFORM_USAGE_INT_64) != 0) {
throw new Error("Uniform usage mismatch! Expected: " + slots[index].toString() + " Recived: " + UniformUsage.UNIFORM_USAGE_INT_64.name());
}
upToDate = false;
</DeepExtract>
|
SFE-Engine
|
positive
|
public void setRenderer(GLTextureView.Renderer renderer) {
if (mGLThread != null) {
throw new IllegalStateException("setRenderer has already been called for this instance.");
}
if (mEGLConfigChooser == null) {
mEGLConfigChooser = new SimpleEGLConfigChooser(true);
}
if (mEGLContextFactory == null) {
mEGLContextFactory = new DefaultContextFactory();
}
if (mEGLWindowSurfaceFactory == null) {
mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
}
mRenderer = renderer;
mGLThread = new GLThread(mThisWeakRef);
if (LOG_EGL) {
Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId());
}
mEgl = (EGL10) EGLContext.getEGL();
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
throw new RuntimeException("eglGetDisplay failed");
}
int[] version = new int[2];
if (!mEgl.eglInitialize(mEglDisplay, version)) {
throw new RuntimeException("eglInitialize failed");
}
GLTextureView view = mGLSurfaceViewWeakRef.get();
if (view == null) {
mEglConfig = null;
mEglContext = null;
} else {
mEglConfig = view.mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
mEglContext = view.mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
}
if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
mEglContext = null;
throwEglException("createContext");
}
if (LOG_EGL) {
Log.w("EglHelper", "createContext " + mEglContext + " tid=" + Thread.currentThread().getId());
}
mEglSurface = null;
}
|
<DeepExtract>
if (mGLThread != null) {
throw new IllegalStateException("setRenderer has already been called for this instance.");
}
</DeepExtract>
<DeepExtract>
if (LOG_EGL) {
Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId());
}
mEgl = (EGL10) EGLContext.getEGL();
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
throw new RuntimeException("eglGetDisplay failed");
}
int[] version = new int[2];
if (!mEgl.eglInitialize(mEglDisplay, version)) {
throw new RuntimeException("eglInitialize failed");
}
GLTextureView view = mGLSurfaceViewWeakRef.get();
if (view == null) {
mEglConfig = null;
mEglContext = null;
} else {
mEglConfig = view.mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
mEglContext = view.mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig);
}
if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
mEglContext = null;
throwEglException("createContext");
}
if (LOG_EGL) {
Log.w("EglHelper", "createContext " + mEglContext + " tid=" + Thread.currentThread().getId());
}
mEglSurface = null;
</DeepExtract>
|
PhotoMovie
|
positive
|
public Criteria andBz119NotBetween(String value1, String value2) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "bz119" + " cannot be null");
}
criteria.add(new Criterion("`bz119` not between", value1, value2));
return (Criteria) this;
}
|
<DeepExtract>
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "bz119" + " cannot be null");
}
criteria.add(new Criterion("`bz119` not between", value1, value2));
</DeepExtract>
|
blockhealth
|
positive
|
public static void index(byte[] source, UUID picture_id, IndexWriterConfig conf) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(source);
BufferedImage image = ImageIO.read(in);
log.debug("Is Lucene configured? " + (conf == null));
if (conf == null) {
conf = new IndexWriterConfig(LuceneUtils.LUCENE_VERSION, new WhitespaceAnalyzer(LuceneUtils.LUCENE_VERSION));
conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
}
File path = getPath(FeatureEnumerate.AutoColorCorrelogram.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getAutoColorCorrelogramDocumentBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
File path = getPath(FeatureEnumerate.CEDD.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getCEDDDocumentBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
File path = getPath(FeatureEnumerate.ColorLayout.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getColorLayoutBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
File path = getPath(FeatureEnumerate.EdgeHistogram.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getEdgeHistogramBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
File path = getPath(FeatureEnumerate.ColorHistogram.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getColorHistogramDocumentBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
File path = getPath(FeatureEnumerate.PHOG.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getPHOGDocumentBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
}
|
<DeepExtract>
File path = getPath(FeatureEnumerate.AutoColorCorrelogram.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getAutoColorCorrelogramDocumentBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
</DeepExtract>
<DeepExtract>
File path = getPath(FeatureEnumerate.CEDD.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getCEDDDocumentBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
</DeepExtract>
<DeepExtract>
File path = getPath(FeatureEnumerate.ColorLayout.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getColorLayoutBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
</DeepExtract>
<DeepExtract>
File path = getPath(FeatureEnumerate.EdgeHistogram.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getEdgeHistogramBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
</DeepExtract>
<DeepExtract>
File path = getPath(FeatureEnumerate.ColorHistogram.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getColorHistogramDocumentBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
</DeepExtract>
<DeepExtract>
File path = getPath(FeatureEnumerate.PHOG.getText());
log.debug("creating indexed path " + path.getAbsolutePath());
IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf);
try {
Document document = DocumentBuilderFactory.getPHOGDocumentBuilder().createDocument(image, picture_id.toString());
iw.addDocument(document);
} catch (Exception e) {
System.err.println("Error reading image or indexing it.");
e.printStackTrace();
}
iw.close();
</DeepExtract>
|
flipper-reverse-image-search
|
positive
|
public boolean equalString(String str, int len) {
String other = str.length() == len ? str : str.substring(0, len);
return (other instanceof AbstractSymbol) && ((AbstractSymbol) other).index == this.index;
}
|
<DeepExtract>
return (other instanceof AbstractSymbol) && ((AbstractSymbol) other).index == this.index;
</DeepExtract>
|
Compiler
|
positive
|
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mEditText.setError("");
}
|
<DeepExtract>
mEditText.setError("");
</DeepExtract>
|
igniter
|
positive
|
public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) {
if (useFieldNames && fieldName != null) {
buffer.append(fieldName);
buffer.append(fieldNameValueSeparator);
}
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldSeparator(buffer);
}
|
<DeepExtract>
if (useFieldNames && fieldName != null) {
buffer.append(fieldName);
buffer.append(fieldNameValueSeparator);
}
</DeepExtract>
<DeepExtract>
appendFieldSeparator(buffer);
</DeepExtract>
|
xposed-art
|
positive
|
@PostConstruct
public void init() {
connectionManagerFactory = new DefaultApacheHttpClientConnectionManagerFactory();
return connectionManagerFactory.newConnectionManager(false, 200, 20, -1, TimeUnit.MILLISECONDS, null);
httpClientFactory = new DefaultApacheHttpClientFactory(HttpClientBuilder.create());
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(-1).setSocketTimeout(10000).setConnectTimeout(2000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
return httpClientFactory.createBuilder().setDefaultRequestConfig(requestConfig).setConnectionManager(this.connectionManager).disableRedirectHandling().build();
}
|
<DeepExtract>
return connectionManagerFactory.newConnectionManager(false, 200, 20, -1, TimeUnit.MILLISECONDS, null);
</DeepExtract>
<DeepExtract>
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(-1).setSocketTimeout(10000).setConnectTimeout(2000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
return httpClientFactory.createBuilder().setDefaultRequestConfig(requestConfig).setConnectionManager(this.connectionManager).disableRedirectHandling().build();
</DeepExtract>
|
springcloud-vip-2
|
positive
|
@Override
public LineStringBuilder pointLatLon(double latitude, double longitude) {
shapes.add(ShapeFactoryImpl.this.pointLatLon(latitude, longitude));
return this;
return this;
}
|
<DeepExtract>
shapes.add(ShapeFactoryImpl.this.pointLatLon(latitude, longitude));
return this;
</DeepExtract>
|
spatial4j
|
positive
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.