before
stringlengths
33
3.21M
after
stringlengths
63
3.21M
repo
stringlengths
1
56
type
stringclasses
1 value
__index_level_0__
int64
0
442k
private void setFragment(Fragment fragment) { if (mFragManager.getBackStackEntryCount() > 0) { mFragManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); onSearchExpanded(false); } FragmentTransaction ft = mFragManager.beginTransaction().replace(R.id.container, fragment, mFragmentTag); try { ft.commit(); } catch (Exception e) { ft.commitAllowingStateLoss(); } Menu menu = mNavigationView.getMenu(); menu.getItem(mPosition).setChecked(true); mToolbarTitle.setText(menu.getItem(mPosition).getTitle()); }
private void setFragment(Fragment fragment) { <DeepExtract> if (mFragManager.getBackStackEntryCount() > 0) { mFragManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); onSearchExpanded(false); } </DeepExtract> FragmentTransaction ft = mFragManager.beginTransaction().replace(R.id.container, fragment, mFragmentTag); try { ft.commit(); } catch (Exception e) { ft.commitAllowingStateLoss(); } Menu menu = mNavigationView.getMenu(); menu.getItem(mPosition).setChecked(true); mToolbarTitle.setText(menu.getItem(mPosition).getTitle()); }
candybar-library
positive
439,096
void write() { writePackage(); writeImports(); writer.append(AT_GENERATED).eol(); writer.append(diAnnotation()).eol(); writer.append("public class ").append(shortName).append("$Route implements Routing.Service {").eol().eol(); String controllerName = "controller"; String controllerType = shortName; if (isRequestScoped()) { controllerName = "factory"; controllerType += Constants.FACTORY_SUFFIX; } writer.append(" private final %s %s;", controllerType, controllerName).eol(); if (reader.isIncludeValidator()) { writer.append(" private final Validator validator;").eol(); } writer.eol(); writer.append(" public %s$Route(%s %s", shortName, controllerType, controllerName); if (reader.isIncludeValidator()) { writer.append(", Validator validator"); } writer.append(") {").eol(); writer.append(" this.%s = %s;", controllerName, controllerName).eol(); if (reader.isIncludeValidator()) { writer.append(" this.validator = validator;").eol(); } writer.append(" }").eol().eol(); writer.append(" @Override").eol(); writer.append(" public void add(Routing routing) {").eol().eol(); for (MethodReader method : reader.methods()) { if (method.isWebMethod()) { writeForMethod(method); } } writer.append(" }").eol().eol(); writeClassEnd(); }
void write() { writePackage(); writeImports(); writer.append(AT_GENERATED).eol(); writer.append(diAnnotation()).eol(); writer.append("public class ").append(shortName).append("$Route implements Routing.Service {").eol().eol(); String controllerName = "controller"; String controllerType = shortName; if (isRequestScoped()) { controllerName = "factory"; controllerType += Constants.FACTORY_SUFFIX; } writer.append(" private final %s %s;", controllerType, controllerName).eol(); if (reader.isIncludeValidator()) { writer.append(" private final Validator validator;").eol(); } writer.eol(); writer.append(" public %s$Route(%s %s", shortName, controllerType, controllerName); if (reader.isIncludeValidator()) { writer.append(", Validator validator"); } writer.append(") {").eol(); writer.append(" this.%s = %s;", controllerName, controllerName).eol(); if (reader.isIncludeValidator()) { writer.append(" this.validator = validator;").eol(); } writer.append(" }").eol().eol(); <DeepExtract> writer.append(" @Override").eol(); writer.append(" public void add(Routing routing) {").eol().eol(); for (MethodReader method : reader.methods()) { if (method.isWebMethod()) { writeForMethod(method); } } writer.append(" }").eol().eol(); </DeepExtract> writeClassEnd(); }
avaje-http
positive
439,097
public MonthPlan parse(int year, int month) { this.url = (ParserUtils.getUrl(URL_PLAN, year, String.format("%02d", month))); this.year = year; this.month = month; MonthPlan monthPlan = new MonthPlan(year, month); Element tbody = ParserUtils.getDoc(url).getElementsByTag("tbody").get(0); Elements items = tbody.getElementsByClass("textL"); Element[] itemsArray = items.toArray(new Element[items.size()]); for (int i = 1; i < itemsArray.length; i++) { Element planElement = itemsArray[i]; String dayStr = planElement.getElementsByTag("em").get(0).text(); if (dayStr.equals("") || dayStr.length() == 0) continue; int day = Integer.valueOf(dayStr); Elements plans = itemsArray[i].getElementsByTag("strong"); JSONArray plansJsonArray = new JSONArray(); for (Element plan : plans) plansJsonArray.add(plan.text()); Plan plan = new Plan(day, plansJsonArray); monthPlan.addPlan(plan); } try { DataBase.getInstance().execute(monthPlan); } catch (SQLException e) { e.printStackTrace(); } return monthPlan; }
public MonthPlan parse(int year, int month) { this.url = (ParserUtils.getUrl(URL_PLAN, year, String.format("%02d", month))); this.year = year; this.month = month; <DeepExtract> MonthPlan monthPlan = new MonthPlan(year, month); Element tbody = ParserUtils.getDoc(url).getElementsByTag("tbody").get(0); Elements items = tbody.getElementsByClass("textL"); Element[] itemsArray = items.toArray(new Element[items.size()]); for (int i = 1; i < itemsArray.length; i++) { Element planElement = itemsArray[i]; String dayStr = planElement.getElementsByTag("em").get(0).text(); if (dayStr.equals("") || dayStr.length() == 0) continue; int day = Integer.valueOf(dayStr); Elements plans = itemsArray[i].getElementsByTag("strong"); JSONArray plansJsonArray = new JSONArray(); for (Element plan : plans) plansJsonArray.add(plan.text()); Plan plan = new Plan(day, plansJsonArray); monthPlan.addPlan(plan); } try { DataBase.getInstance().execute(monthPlan); } catch (SQLException e) { e.printStackTrace(); } return monthPlan; </DeepExtract> }
DMS
positive
439,098
public void postOnlyDelayedWork(final int what, final long delay) { if (hasMessages(what)) { removeMessages(what); } sendMessageDelayed(obtainMessage(what), delay); }
public void postOnlyDelayedWork(final int what, final long delay) { if (hasMessages(what)) { removeMessages(what); } <DeepExtract> sendMessageDelayed(obtainMessage(what), delay); </DeepExtract> }
InteractiveChart
positive
439,101
final public Node RDFLiteral() throws ParseException { String lex = null; Token t; String lex; switch((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case STRING_LITERAL1: t = jj_consume_token(STRING_LITERAL1); lex = stripQuotes(t.image); break; case STRING_LITERAL2: t = jj_consume_token(STRING_LITERAL2); lex = stripQuotes(t.image); break; case STRING_LITERAL_LONG1: t = jj_consume_token(STRING_LITERAL_LONG1); lex = stripQuotes3(t.image); break; case STRING_LITERAL_LONG2: t = jj_consume_token(STRING_LITERAL_LONG2); lex = stripQuotes3(t.image); break; default: jj_la1[163] = jj_gen; jj_consume_token(-1); throw new ParseException(); } lex = unescapeStr(lex, t.beginLine, t.beginColumn); { if (true) lex = lex; } throw new Error("Missing return statement in function"); String lang = null; String uri = null; switch((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case LANGTAG: case DATATYPE: switch((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case LANGTAG: t = jj_consume_token(LANGTAG); lang = stripChars(t.image, 1); break; case DATATYPE: jj_consume_token(DATATYPE); uri = iri(); break; default: jj_la1[156] = jj_gen; jj_consume_token(-1); throw new ParseException(); } break; default: jj_la1[157] = jj_gen; ; } { if (true) return createLiteral(lex, lang, uri); } throw new Error("Missing return statement in function"); }
final public Node RDFLiteral() throws ParseException { String lex = null; <DeepExtract> Token t; String lex; switch((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case STRING_LITERAL1: t = jj_consume_token(STRING_LITERAL1); lex = stripQuotes(t.image); break; case STRING_LITERAL2: t = jj_consume_token(STRING_LITERAL2); lex = stripQuotes(t.image); break; case STRING_LITERAL_LONG1: t = jj_consume_token(STRING_LITERAL_LONG1); lex = stripQuotes3(t.image); break; case STRING_LITERAL_LONG2: t = jj_consume_token(STRING_LITERAL_LONG2); lex = stripQuotes3(t.image); break; default: jj_la1[163] = jj_gen; jj_consume_token(-1); throw new ParseException(); } lex = unescapeStr(lex, t.beginLine, t.beginColumn); { if (true) lex = lex; } throw new Error("Missing return statement in function"); </DeepExtract> String lang = null; String uri = null; switch((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case LANGTAG: case DATATYPE: switch((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case LANGTAG: t = jj_consume_token(LANGTAG); lang = stripChars(t.image, 1); break; case DATATYPE: jj_consume_token(DATATYPE); uri = iri(); break; default: jj_la1[156] = jj_gen; jj_consume_token(-1); throw new ParseException(); } break; default: jj_la1[157] = jj_gen; ; } { if (true) return createLiteral(lex, lang, uri); } throw new Error("Missing return statement in function"); }
RDFstarTools
positive
439,102
private void textFieldChangeHandler() { int value = TextFieldUtil.parseInteger(textFieldBatchSize); AIFacade.setTrainBatchSize(value); int value = TextFieldUtil.parseInteger(textFieldEpoch); AIFacade.setTrainEpoch(value); int value = TextFieldUtil.parseInteger(textFieldListeningPeriod); AIFacade.setListeningPeriod(value); }
private void textFieldChangeHandler() { int value = TextFieldUtil.parseInteger(textFieldBatchSize); AIFacade.setTrainBatchSize(value); int value = TextFieldUtil.parseInteger(textFieldEpoch); AIFacade.setTrainEpoch(value); <DeepExtract> int value = TextFieldUtil.parseInteger(textFieldListeningPeriod); AIFacade.setListeningPeriod(value); </DeepExtract> }
Dluid
positive
439,103
public void setCommandsCaseType(@NotNull ConcordionCommandsCaseType commandsCaseType) { this.commandsCaseType = commandsCaseType; for (WeakReference<ConcordionSettingsListener> listener : listeners) { ConcordionSettingsListener listenerRef = listener.get(); if (listenerRef != null) { listenerRef.settingsChanged(this); } } }
public void setCommandsCaseType(@NotNull ConcordionCommandsCaseType commandsCaseType) { this.commandsCaseType = commandsCaseType; <DeepExtract> for (WeakReference<ConcordionSettingsListener> listener : listeners) { ConcordionSettingsListener listenerRef = listener.get(); if (listenerRef != null) { listenerRef.settingsChanged(this); } } </DeepExtract> }
idea-concordion-support
positive
439,104
public void reg(String name, MinecraftClient mc, CommandDispatcher<FabricClientCommandSource> cd) { MinecraftClient mc = CodeUtilities.MC; reg("previewactionbar", mc, literal(name).then(argument("message", StringArgumentType.greedyString()).executes(ctx -> { Text msg = new LiteralText(ctx.getArgument("message", String.class).replace("&", "§")); mc.player.sendMessage(msg, true); return 1; })).executes(ctx -> { mc.player.sendMessage(mc.player.getMainHandStack().getName(), true); return 1; })); reg("actionbarpreview", mc, literal(name).then(argument("message", StringArgumentType.greedyString()).executes(ctx -> { Text msg = new LiteralText(ctx.getArgument("message", String.class).replace("&", "§")); mc.player.sendMessage(msg, true); return 1; })).executes(ctx -> { mc.player.sendMessage(mc.player.getMainHandStack().getName(), true); return 1; })); }
public void reg(String name, MinecraftClient mc, CommandDispatcher<FabricClientCommandSource> cd) { <DeepExtract> MinecraftClient mc = CodeUtilities.MC; reg("previewactionbar", mc, literal(name).then(argument("message", StringArgumentType.greedyString()).executes(ctx -> { Text msg = new LiteralText(ctx.getArgument("message", String.class).replace("&", "§")); mc.player.sendMessage(msg, true); return 1; })).executes(ctx -> { mc.player.sendMessage(mc.player.getMainHandStack().getName(), true); return 1; })); reg("actionbarpreview", mc, literal(name).then(argument("message", StringArgumentType.greedyString()).executes(ctx -> { Text msg = new LiteralText(ctx.getArgument("message", String.class).replace("&", "§")); mc.player.sendMessage(msg, true); return 1; })).executes(ctx -> { mc.player.sendMessage(mc.player.getMainHandStack().getName(), true); return 1; })); </DeepExtract> }
CodeUtilities
positive
439,105
public void analyze() { PartiallyBalancedTabulationSolver<BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> solver = PartiallyBalancedTabulationSolver.createPartiallyBalancedTabulationSolver(new TaintProblem(), null); TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> result = null; try { result = solver.solve(); } catch (CancelException e) { assert false; } return result; System.out.println("#find taint: " + isTainted); }
public void analyze() { <DeepExtract> PartiallyBalancedTabulationSolver<BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> solver = PartiallyBalancedTabulationSolver.createPartiallyBalancedTabulationSolver(new TaintProblem(), null); TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, Pair<CGNode, Integer>> result = null; try { result = solver.solve(); } catch (CancelException e) { assert false; } return result; </DeepExtract> System.out.println("#find taint: " + isTainted); }
HybriDroid
positive
439,106
@Test public void successOutputCheckWithAntiCsrfWithCookieDomain() throws Exception { String[] args = { "../" }; Utils.setValueInConfig("cookie_domain", "localhost"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; JsonObject userDataInJWT = new JsonObject(); userDataInJWT.addProperty("key", "value"); JsonObject userDataInDatabase = new JsonObject(); userDataInDatabase.addProperty("key", "value"); JsonObject request = new JsonObject(); request.addProperty("userId", userId); request.add("userDataInJWT", userDataInJWT); request.add("userDataInDatabase", userDataInDatabase); request.addProperty("enableAntiCsrf", true); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/recipe/session", request, 1000, 1000, null, Utils.getCdiVersion2_7ForTests(), "session"); assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); assertEquals(response.get("session").getAsJsonObject().get("userId").getAsString(), userId); assertEquals(response.get("session").getAsJsonObject().get("userDataInJWT").getAsJsonObject().toString(), userDataInJWT.toString()); assertEquals(response.get("session").getAsJsonObject().entrySet().size(), 3); assertTrue(response.get("accessToken").getAsJsonObject().has("token")); assertTrue(response.get("accessToken").getAsJsonObject().has("expiry")); assertTrue(response.get("accessToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("accessToken").getAsJsonObject().entrySet().size(), 3); assertTrue(response.get("refreshToken").getAsJsonObject().has("token")); assertTrue(response.get("refreshToken").getAsJsonObject().has("expiry")); assertTrue(response.get("refreshToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("refreshToken").getAsJsonObject().entrySet().size(), 3); assertTrue(response.get("idRefreshToken").getAsJsonObject().has("token")); assertTrue(response.get("idRefreshToken").getAsJsonObject().has("expiry")); assertTrue(response.get("idRefreshToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("idRefreshToken").getAsJsonObject().entrySet().size(), 3); assertTrue(response.has("jwtSigningPublicKey")); assertTrue(response.has("jwtSigningPublicKeyExpiryTime")); assertTrue(response.has("antiCsrfToken")); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); }
@Test public void successOutputCheckWithAntiCsrfWithCookieDomain() throws Exception { String[] args = { "../" }; Utils.setValueInConfig("cookie_domain", "localhost"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; JsonObject userDataInJWT = new JsonObject(); userDataInJWT.addProperty("key", "value"); JsonObject userDataInDatabase = new JsonObject(); userDataInDatabase.addProperty("key", "value"); JsonObject request = new JsonObject(); request.addProperty("userId", userId); request.add("userDataInJWT", userDataInJWT); request.add("userDataInDatabase", userDataInDatabase); request.addProperty("enableAntiCsrf", true); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/recipe/session", request, 1000, 1000, null, Utils.getCdiVersion2_7ForTests(), "session"); <DeepExtract> assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); assertEquals(response.get("session").getAsJsonObject().get("userId").getAsString(), userId); assertEquals(response.get("session").getAsJsonObject().get("userDataInJWT").getAsJsonObject().toString(), userDataInJWT.toString()); assertEquals(response.get("session").getAsJsonObject().entrySet().size(), 3); assertTrue(response.get("accessToken").getAsJsonObject().has("token")); assertTrue(response.get("accessToken").getAsJsonObject().has("expiry")); assertTrue(response.get("accessToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("accessToken").getAsJsonObject().entrySet().size(), 3); assertTrue(response.get("refreshToken").getAsJsonObject().has("token")); assertTrue(response.get("refreshToken").getAsJsonObject().has("expiry")); assertTrue(response.get("refreshToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("refreshToken").getAsJsonObject().entrySet().size(), 3); assertTrue(response.get("idRefreshToken").getAsJsonObject().has("token")); assertTrue(response.get("idRefreshToken").getAsJsonObject().has("expiry")); assertTrue(response.get("idRefreshToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("idRefreshToken").getAsJsonObject().entrySet().size(), 3); assertTrue(response.has("jwtSigningPublicKey")); assertTrue(response.has("jwtSigningPublicKeyExpiryTime")); </DeepExtract> assertTrue(response.has("antiCsrfToken")); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); }
supertokens-core
positive
439,107
public void addTextureVEnd(double amt) { if (this.autoUV) { this.textureV += amt; } this.textureVEnd += amt; if (autoUV) { if (snapUV) { Sized scale = getVoxel2PixelScale(); textureU = (int) Math.round(textureU * scale.W) / scale.W; textureV = (int) Math.round((textureV * scale.H)) / scale.H; double width = cuboid.getFaceDimension(side).getWidth(); double height = cuboid.getFaceDimension(side).getHeight(); if (rotation == 0 || rotation == 2) { textureUEnd = textureU + Math.max(1 / scale.W, Math.floor(width * scale.W + 0.000001) / scale.W); textureVEnd = textureV + Math.max(1 / scale.H, Math.floor(height * scale.H + 0.000001) / scale.H); } else { textureUEnd = textureU + Math.max(1 / scale.H, Math.floor(height * scale.W + 0.000001) / scale.W); textureVEnd = textureV + Math.max(1 / scale.W, Math.floor(width * scale.H + 0.000001) / scale.H); } } else { if (rotation == 0 || rotation == 2) { textureUEnd = textureU + cuboid.getFaceDimension(side).getWidth(); textureVEnd = textureV + cuboid.getFaceDimension(side).getHeight(); } else { textureUEnd = textureU + cuboid.getFaceDimension(side).getHeight(); textureVEnd = textureV + cuboid.getFaceDimension(side).getWidth(); } } } if (amt != 0) ModelCreator.DidModify(); }
public void addTextureVEnd(double amt) { if (this.autoUV) { this.textureV += amt; } this.textureVEnd += amt; <DeepExtract> if (autoUV) { if (snapUV) { Sized scale = getVoxel2PixelScale(); textureU = (int) Math.round(textureU * scale.W) / scale.W; textureV = (int) Math.round((textureV * scale.H)) / scale.H; double width = cuboid.getFaceDimension(side).getWidth(); double height = cuboid.getFaceDimension(side).getHeight(); if (rotation == 0 || rotation == 2) { textureUEnd = textureU + Math.max(1 / scale.W, Math.floor(width * scale.W + 0.000001) / scale.W); textureVEnd = textureV + Math.max(1 / scale.H, Math.floor(height * scale.H + 0.000001) / scale.H); } else { textureUEnd = textureU + Math.max(1 / scale.H, Math.floor(height * scale.W + 0.000001) / scale.W); textureVEnd = textureV + Math.max(1 / scale.W, Math.floor(width * scale.H + 0.000001) / scale.H); } } else { if (rotation == 0 || rotation == 2) { textureUEnd = textureU + cuboid.getFaceDimension(side).getWidth(); textureVEnd = textureV + cuboid.getFaceDimension(side).getHeight(); } else { textureUEnd = textureU + cuboid.getFaceDimension(side).getHeight(); textureVEnd = textureV + cuboid.getFaceDimension(side).getWidth(); } } } </DeepExtract> if (amt != 0) ModelCreator.DidModify(); }
vsmodelcreator
positive
439,108
protected String resultText(Set<DefaultVertex> result) { markedEdges.clear(); userSelectedVertices.clear(); highlightedVertices.clear(); colourMap.clear(); redraw(); if (result == null) { return "Computation aborted"; } else { if (result.isEmpty()) { return "Graph is threshold"; } highlightedVertices.addAll(result); redraw(); return "Threshold obstruction highlighted"; } }
protected String resultText(Set<DefaultVertex> result) { <DeepExtract> markedEdges.clear(); userSelectedVertices.clear(); highlightedVertices.clear(); colourMap.clear(); redraw(); </DeepExtract> if (result == null) { return "Computation aborted"; } else { if (result.isEmpty()) { return "Graph is threshold"; } highlightedVertices.addAll(result); redraw(); return "Threshold obstruction highlighted"; } }
Grapher
positive
439,110
protected HttpClient constructHttpClient() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient httpClient = new HttpClient(connectionManager); HttpClientParams params = httpClient.getParams(); params.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true); params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true); if (socketTimeout != null) { params.setSoTimeout(socketTimeout); } HttpConnectionManagerParams connectionManagerParams = httpClient.getHttpConnectionManager().getParams(); this.maxTotalConnections = maxTotalConnections; connectionManagerParams.setDefaultMaxConnectionsPerHost(maxHostConnections); this.connectionTimeout = connectionTimeout; return httpClient; }
protected HttpClient constructHttpClient() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient httpClient = new HttpClient(connectionManager); HttpClientParams params = httpClient.getParams(); params.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true); params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true); if (socketTimeout != null) { params.setSoTimeout(socketTimeout); } HttpConnectionManagerParams connectionManagerParams = httpClient.getHttpConnectionManager().getParams(); this.maxTotalConnections = maxTotalConnections; connectionManagerParams.setDefaultMaxConnectionsPerHost(maxHostConnections); <DeepExtract> this.connectionTimeout = connectionTimeout; </DeepExtract> return httpClient; }
alfresco-core
positive
439,111
@Override public synchronized RenderingState draw(AbsDisplayer displayer) { if (clearRetainerFlag) { mRenderer.clearRetainer(); clearRetainerFlag = false; } if (danmakuList != null) { Canvas canvas = (Canvas) displayer.getExtraData(); DrawHelper.clearCanvas(canvas); if (mIsHidden && !mRequestRender) { return mRenderingState; } mRequestRender = false; RenderingState renderingState = mRenderingState; long beginMills = mTimer.currMillisecond - mContext.mDanmakuFactory.MAX_DANMAKU_DURATION - 100; long endMills = mTimer.currMillisecond + mContext.mDanmakuFactory.MAX_DANMAKU_DURATION; IDanmakus screenDanmakus = danmakus; if (mLastBeginMills > beginMills || mTimer.currMillisecond > mLastEndMills) { screenDanmakus = danmakuList.sub(beginMills, endMills); if (screenDanmakus != null) { danmakus = screenDanmakus; } mLastBeginMills = beginMills; mLastEndMills = endMills; } else { beginMills = mLastBeginMills; endMills = mLastEndMills; } IDanmakus runningDanmakus = mRunningDanmakus; beginTracing(renderingState, runningDanmakus, screenDanmakus); if (runningDanmakus != null && !runningDanmakus.isEmpty()) { mRenderingState.isRunningDanmakus = true; mRenderer.draw(displayer, runningDanmakus, 0, mRenderingState); } mRenderingState.isRunningDanmakus = false; if (screenDanmakus != null && !screenDanmakus.isEmpty()) { mRenderer.draw(mDisp, screenDanmakus, mStartRenderTime, renderingState); endTracing(renderingState); if (renderingState.nothingRendered) { if (mLastDanmaku != null && mLastDanmaku.isTimeOut()) { mLastDanmaku = null; if (mTaskListener != null) { mTaskListener.onDanmakusDrawingFinished(); } } if (renderingState.beginTime == RenderingState.UNKNOWN_TIME) { renderingState.beginTime = beginMills; } if (renderingState.endTime == RenderingState.UNKNOWN_TIME) { renderingState.endTime = endMills; } } return renderingState; } else { renderingState.nothingRendered = true; renderingState.beginTime = beginMills; renderingState.endTime = endMills; return renderingState; } } return null; }
@Override public synchronized RenderingState draw(AbsDisplayer displayer) { <DeepExtract> if (clearRetainerFlag) { mRenderer.clearRetainer(); clearRetainerFlag = false; } if (danmakuList != null) { Canvas canvas = (Canvas) displayer.getExtraData(); DrawHelper.clearCanvas(canvas); if (mIsHidden && !mRequestRender) { return mRenderingState; } mRequestRender = false; RenderingState renderingState = mRenderingState; long beginMills = mTimer.currMillisecond - mContext.mDanmakuFactory.MAX_DANMAKU_DURATION - 100; long endMills = mTimer.currMillisecond + mContext.mDanmakuFactory.MAX_DANMAKU_DURATION; IDanmakus screenDanmakus = danmakus; if (mLastBeginMills > beginMills || mTimer.currMillisecond > mLastEndMills) { screenDanmakus = danmakuList.sub(beginMills, endMills); if (screenDanmakus != null) { danmakus = screenDanmakus; } mLastBeginMills = beginMills; mLastEndMills = endMills; } else { beginMills = mLastBeginMills; endMills = mLastEndMills; } IDanmakus runningDanmakus = mRunningDanmakus; beginTracing(renderingState, runningDanmakus, screenDanmakus); if (runningDanmakus != null && !runningDanmakus.isEmpty()) { mRenderingState.isRunningDanmakus = true; mRenderer.draw(displayer, runningDanmakus, 0, mRenderingState); } mRenderingState.isRunningDanmakus = false; if (screenDanmakus != null && !screenDanmakus.isEmpty()) { mRenderer.draw(mDisp, screenDanmakus, mStartRenderTime, renderingState); endTracing(renderingState); if (renderingState.nothingRendered) { if (mLastDanmaku != null && mLastDanmaku.isTimeOut()) { mLastDanmaku = null; if (mTaskListener != null) { mTaskListener.onDanmakusDrawingFinished(); } } if (renderingState.beginTime == RenderingState.UNKNOWN_TIME) { renderingState.beginTime = beginMills; } if (renderingState.endTime == RenderingState.UNKNOWN_TIME) { renderingState.endTime = endMills; } } return renderingState; } else { renderingState.nothingRendered = true; renderingState.beginTime = beginMills; renderingState.endTime = endMills; return renderingState; } } return null; </DeepExtract> }
DanmakuFlameMaster
positive
439,114
public void setDefaultImageBitmap(Bitmap bitmap) { mImageSource = IMAGE_SOURCE_BITMAP; mDefaultBitmap = bitmap; if (mBitmap == null) { switch(mImageSource) { case IMAGE_SOURCE_BITMAP: setImageBitmap(mDefaultBitmap); break; case IMAGE_SOURCE_DRAWABLE: setImageDrawable(mDefaultDrawable); break; case IMAGE_SOURCE_RESOURCE: setImageResource(mDefaultResId); break; default: setImageDrawable(null); break; } } }
public void setDefaultImageBitmap(Bitmap bitmap) { mImageSource = IMAGE_SOURCE_BITMAP; mDefaultBitmap = bitmap; <DeepExtract> if (mBitmap == null) { switch(mImageSource) { case IMAGE_SOURCE_BITMAP: setImageBitmap(mDefaultBitmap); break; case IMAGE_SOURCE_DRAWABLE: setImageDrawable(mDefaultDrawable); break; case IMAGE_SOURCE_RESOURCE: setImageResource(mDefaultResId); break; default: setImageDrawable(null); break; } } </DeepExtract> }
GreenDroid
positive
439,115
@Override public void close() { SCUtils.removeScenicViewComponents(target); if (targetScene != null) { targetScene.removeEventFilter(MouseEvent.MOUSE_MOVED, sceneHoverListener); targetScene.removeEventFilter(MouseEvent.MOUSE_MOVED, mousePosListener); targetScene.removeEventFilter(MouseEvent.MOUSE_PRESSED, scenePressListener); } if (targetWindow != null) { targetWindow.xProperty().removeListener(targetWindowPropListener); targetWindow.yProperty().removeListener(targetWindowPropListener); targetWindow.widthProperty().removeListener(targetWindowPropListener); targetWindow.heightProperty().removeListener(targetWindowPropListener); targetWindow.focusedProperty().removeListener(targetWindowPropListener); targetWindow.sceneProperty().removeListener(targetWindowSceneListener); } targetWindow = null; if (targetWindow != null) { targetWindow.xProperty().addListener(targetWindowPropListener); targetWindow.yProperty().addListener(targetWindowPropListener); targetWindow.widthProperty().addListener(targetWindowPropListener); targetWindow.heightProperty().addListener(targetWindowPropListener); targetWindow.focusedProperty().addListener(targetWindowPropListener); targetWindow.sceneProperty().addListener(targetWindowSceneListener); if (targetWindow instanceof Stage) stageID.setName(((Stage) targetWindow).getTitle()); } updateWindowDetails(); if (false) { if (SCUtils.isNormalNode(target)) { target.visibleProperty().removeListener(visibilityInvalidationListener); target.visibleProperty().addListener(visibilityInvalidationListener); propertyTracker(target, true); target.removeEventFilter(Event.ANY, traceEventHandler); if (configuration.isEventLogEnabled()) target.addEventFilter(Event.ANY, traceEventHandler); ObservableList<Node> children = ChildrenGetter.getChildren(target); children.removeListener(structureInvalidationListener); children.addListener(structureInvalidationListener); for (int i = 0; i < children.size(); i++) { updateListeners(children.get(i), false, true); } } } else { ObservableList<Node> children = ChildrenGetter.getChildren(target); for (int i = 0; i < children.size(); i++) { updateListeners(children.get(i), false, true); } children.removeListener(structureInvalidationListener); if (target != null && true) { target.visibleProperty().removeListener(visibilityInvalidationListener); propertyTracker(target, false); target.removeEventFilter(Event.ANY, traceEventHandler); } } if (refresher != null) { refresher.finish(); } if (windowChecker != null) { windowChecker.finish(); } dispatcher = null; }
@Override public void close() { SCUtils.removeScenicViewComponents(target); if (targetScene != null) { targetScene.removeEventFilter(MouseEvent.MOUSE_MOVED, sceneHoverListener); targetScene.removeEventFilter(MouseEvent.MOUSE_MOVED, mousePosListener); targetScene.removeEventFilter(MouseEvent.MOUSE_PRESSED, scenePressListener); } if (targetWindow != null) { targetWindow.xProperty().removeListener(targetWindowPropListener); targetWindow.yProperty().removeListener(targetWindowPropListener); targetWindow.widthProperty().removeListener(targetWindowPropListener); targetWindow.heightProperty().removeListener(targetWindowPropListener); targetWindow.focusedProperty().removeListener(targetWindowPropListener); targetWindow.sceneProperty().removeListener(targetWindowSceneListener); } targetWindow = null; if (targetWindow != null) { targetWindow.xProperty().addListener(targetWindowPropListener); targetWindow.yProperty().addListener(targetWindowPropListener); targetWindow.widthProperty().addListener(targetWindowPropListener); targetWindow.heightProperty().addListener(targetWindowPropListener); targetWindow.focusedProperty().addListener(targetWindowPropListener); targetWindow.sceneProperty().addListener(targetWindowSceneListener); if (targetWindow instanceof Stage) stageID.setName(((Stage) targetWindow).getTitle()); } updateWindowDetails(); <DeepExtract> if (false) { if (SCUtils.isNormalNode(target)) { target.visibleProperty().removeListener(visibilityInvalidationListener); target.visibleProperty().addListener(visibilityInvalidationListener); propertyTracker(target, true); target.removeEventFilter(Event.ANY, traceEventHandler); if (configuration.isEventLogEnabled()) target.addEventFilter(Event.ANY, traceEventHandler); ObservableList<Node> children = ChildrenGetter.getChildren(target); children.removeListener(structureInvalidationListener); children.addListener(structureInvalidationListener); for (int i = 0; i < children.size(); i++) { updateListeners(children.get(i), false, true); } } } else { ObservableList<Node> children = ChildrenGetter.getChildren(target); for (int i = 0; i < children.size(); i++) { updateListeners(children.get(i), false, true); } children.removeListener(structureInvalidationListener); if (target != null && true) { target.visibleProperty().removeListener(visibilityInvalidationListener); propertyTracker(target, false); target.removeEventFilter(Event.ANY, traceEventHandler); } } </DeepExtract> if (refresher != null) { refresher.finish(); } if (windowChecker != null) { windowChecker.finish(); } dispatcher = null; }
scenic-view
positive
439,116
public Criteria andIntervalcountBetween(Integer value1, Integer value2) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "intervalcount" + " cannot be null"); } criteria.add(new Criterion("intervalCount between", value1, value2)); return (Criteria) this; }
public Criteria andIntervalcountBetween(Integer value1, Integer value2) { <DeepExtract> if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "intervalcount" + " cannot be null"); } criteria.add(new Criterion("intervalCount between", value1, value2)); </DeepExtract> return (Criteria) this; }
emotional_analysis
positive
439,117
@Override public boolean output(SyncData[] data) { for (SyncData syncData : data) { if (syncData == null) { continue; } if (coldStartingRepo.equals(syncData.getRepo()) && coldStartingEntity.equals(syncData.getEntity())) { hold.put(syncData); } } return consumerSource.input(data); }
@Override public boolean output(SyncData[] data) { <DeepExtract> for (SyncData syncData : data) { if (syncData == null) { continue; } if (coldStartingRepo.equals(syncData.getRepo()) && coldStartingEntity.equals(syncData.getEntity())) { hold.put(syncData); } } </DeepExtract> return consumerSource.input(data); }
syncer
positive
439,118
public Criteria andAuditStatusNotBetween(Short value1, Short value2) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "auditStatus" + " cannot be null"); } criteria.add(new Criterion("AUDIT_STATUS not between", value1, value2)); return (Criteria) this; }
public Criteria andAuditStatusNotBetween(Short value1, Short value2) { <DeepExtract> if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "auditStatus" + " cannot be null"); } criteria.add(new Criterion("AUDIT_STATUS not between", value1, value2)); </DeepExtract> return (Criteria) this; }
ECPS
positive
439,120
@BeforeClass(alwaysRun = true) public void init() throws Exception { super.init(userMode); genericRestClient = new GenericRestClient(); headerMap = new HashMap<>(); resourcePath = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "GREG" + File.separator; publisherUrl = publisherContext.getContextUrls().getSecureServiceUrl().replace("services", "publisher/apis"); assertTrue(addNewRxtConfiguration("event_lc.rxt", "event_lc.rxt"), "Adding new custom event_lc.rxt failure encountered "); JSONObject objSessionPublisher = new JSONObject(authenticate(publisherUrl, genericRestClient, automationContext.getSuperTenant().getTenantAdmin().getUserName(), automationContext.getSuperTenant().getTenantAdmin().getPassword()).getEntity(String.class)); jSessionId = objSessionPublisher.getJSONObject("data").getString("sessionId"); cookieHeader = "JSESSIONID=" + jSessionId; refreshPublisherLandingPage(publisherUrl, genericRestClient, cookieHeader); assertNotNull(jSessionId, "Invalid JSessionID received"); }
@BeforeClass(alwaysRun = true) public void init() throws Exception { super.init(userMode); genericRestClient = new GenericRestClient(); headerMap = new HashMap<>(); resourcePath = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "GREG" + File.separator; publisherUrl = publisherContext.getContextUrls().getSecureServiceUrl().replace("services", "publisher/apis"); <DeepExtract> assertTrue(addNewRxtConfiguration("event_lc.rxt", "event_lc.rxt"), "Adding new custom event_lc.rxt failure encountered "); JSONObject objSessionPublisher = new JSONObject(authenticate(publisherUrl, genericRestClient, automationContext.getSuperTenant().getTenantAdmin().getUserName(), automationContext.getSuperTenant().getTenantAdmin().getPassword()).getEntity(String.class)); jSessionId = objSessionPublisher.getJSONObject("data").getString("sessionId"); cookieHeader = "JSESSIONID=" + jSessionId; refreshPublisherLandingPage(publisherUrl, genericRestClient, cookieHeader); assertNotNull(jSessionId, "Invalid JSessionID received"); </DeepExtract> }
product-es
positive
439,121
private void removeValues(int index) { if (!values_.isModifiable()) { values_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(values_); } values_.remove(index); }
private void removeValues(int index) { <DeepExtract> if (!values_.isModifiable()) { values_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(values_); } </DeepExtract> values_.remove(index); }
carma-cloud
positive
439,122
@GetMapping(GROUP_USERS_REQUEST_PATH) @ResponseBody public ResponseEntity<SecurityUserReferenceCollection> getGroupUsers(@PathVariable(VARIABLE_GROUP_ID) String groupId) { ServiceResponse<SecurityUserReferenceCollection> response = groupMembershipService.getGroupUsers(groupId); switch(response.getStatus()) { case NOT_FOUND: return (ResponseEntity<T>) ResponseEntity.notFound().build(); case UNAUTHORIZED: return (ResponseEntity<T>) ResponseEntity.status(HttpStatus.FORBIDDEN).build(); case DELETED: return (ResponseEntity<T>) ResponseEntity.status(HttpStatus.GONE).build(); } return ResponseEntity.ok(response.getObj()); }
@GetMapping(GROUP_USERS_REQUEST_PATH) @ResponseBody public ResponseEntity<SecurityUserReferenceCollection> getGroupUsers(@PathVariable(VARIABLE_GROUP_ID) String groupId) { ServiceResponse<SecurityUserReferenceCollection> response = groupMembershipService.getGroupUsers(groupId); <DeepExtract> switch(response.getStatus()) { case NOT_FOUND: return (ResponseEntity<T>) ResponseEntity.notFound().build(); case UNAUTHORIZED: return (ResponseEntity<T>) ResponseEntity.status(HttpStatus.FORBIDDEN).build(); case DELETED: return (ResponseEntity<T>) ResponseEntity.status(HttpStatus.GONE).build(); } return ResponseEntity.ok(response.getObj()); </DeepExtract> }
elucidate-server
positive
439,124
private void init(Context context) { int w = PixelUtil.dp2px(60); int h = PixelUtil.dp2px(84); margins = new ArrayList<>(); margins.add(new Point(0, 0)); margins.add(new Point(0, h)); margins.add(new Point(0, h * 2)); margins.add(new Point(w, 0)); margins.add(new Point(w, h)); margins.add(new Point(w, h * 2)); margins.add(new Point(w * 2, 0)); margins.add(new Point(w * 2, h)); margins.add(new Point(w * 2, h * 2)); margins.add(new Point(w * 3, 0)); margins.add(new Point(w * 3, h)); margins.add(new Point(w * 3, h * 2)); this.context = context; LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); bgView = new ImageView(context); bgView.setImageResource(R.drawable.search_radar); bgView.setLayoutParams(params); scanView = new ImageView(context); scanView.setImageResource(R.drawable.search_radar_green); scanView.setLayoutParams(params); addView(bgView); addView(scanView); scanView.setVisibility(GONE); }
private void init(Context context) { <DeepExtract> int w = PixelUtil.dp2px(60); int h = PixelUtil.dp2px(84); margins = new ArrayList<>(); margins.add(new Point(0, 0)); margins.add(new Point(0, h)); margins.add(new Point(0, h * 2)); margins.add(new Point(w, 0)); margins.add(new Point(w, h)); margins.add(new Point(w, h * 2)); margins.add(new Point(w * 2, 0)); margins.add(new Point(w * 2, h)); margins.add(new Point(w * 2, h * 2)); margins.add(new Point(w * 3, 0)); margins.add(new Point(w * 3, h)); margins.add(new Point(w * 3, h * 2)); </DeepExtract> this.context = context; LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); bgView = new ImageView(context); bgView.setImageResource(R.drawable.search_radar); bgView.setLayoutParams(params); scanView = new ImageView(context); scanView.setImageResource(R.drawable.search_radar_green); scanView.setLayoutParams(params); addView(bgView); addView(scanView); scanView.setVisibility(GONE); }
FlyWoo
positive
439,127
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); Utils.themeInit(this); setContentView(R.layout.activity_translators_list); getActionBar().setDisplayHomeAsUpEnabled(true); String[] languagesArray; assMan = getAssets(); String[] languagesArray = { "All" }; String[] decodedLanguagesArray = { "All" }; try { InputStream in = assMan.open("languages"); InputStreamReader is = new InputStreamReader(in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while (read != null) { sb.append(read + "_"); read = br.readLine(); } String languages = sb.toString(); String ianaDecodedLanguages = ianaDecode(languages); languagesArray = languages.split("_"); decodedLanguagesArray = ianaDecodedLanguages.split("_"); } catch (IOException e) { Log.e(DEBUG_TAG, e.getMessage()); } if (false) { languagesArray = decodedLanguagesArray; } else { languagesArray = languagesArray; } String[] decodedLanguagesArray; assMan = getAssets(); String[] languagesArray = { "All" }; String[] decodedLanguagesArray = { "All" }; try { InputStream in = assMan.open("languages"); InputStreamReader is = new InputStreamReader(in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while (read != null) { sb.append(read + "_"); read = br.readLine(); } String languages = sb.toString(); String ianaDecodedLanguages = ianaDecode(languages); languagesArray = languages.split("_"); decodedLanguagesArray = ianaDecodedLanguages.split("_"); } catch (IOException e) { Log.e(DEBUG_TAG, e.getMessage()); } if (true) { decodedLanguagesArray = decodedLanguagesArray; } else { decodedLanguagesArray = languagesArray; } for (int i = 0; i < languagesArray.length; i++) { String[] list = getTranslatorsNames(languagesArray[i]); adapter.addSection(decodedLanguagesArray[i], new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list)); } setListAdapter(adapter); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); Utils.themeInit(this); setContentView(R.layout.activity_translators_list); getActionBar().setDisplayHomeAsUpEnabled(true); String[] languagesArray; assMan = getAssets(); String[] languagesArray = { "All" }; String[] decodedLanguagesArray = { "All" }; try { InputStream in = assMan.open("languages"); InputStreamReader is = new InputStreamReader(in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while (read != null) { sb.append(read + "_"); read = br.readLine(); } String languages = sb.toString(); String ianaDecodedLanguages = ianaDecode(languages); languagesArray = languages.split("_"); decodedLanguagesArray = ianaDecodedLanguages.split("_"); } catch (IOException e) { Log.e(DEBUG_TAG, e.getMessage()); } if (false) { languagesArray = decodedLanguagesArray; } else { languagesArray = languagesArray; } <DeepExtract> String[] decodedLanguagesArray; assMan = getAssets(); String[] languagesArray = { "All" }; String[] decodedLanguagesArray = { "All" }; try { InputStream in = assMan.open("languages"); InputStreamReader is = new InputStreamReader(in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while (read != null) { sb.append(read + "_"); read = br.readLine(); } String languages = sb.toString(); String ianaDecodedLanguages = ianaDecode(languages); languagesArray = languages.split("_"); decodedLanguagesArray = ianaDecodedLanguages.split("_"); } catch (IOException e) { Log.e(DEBUG_TAG, e.getMessage()); } if (true) { decodedLanguagesArray = decodedLanguagesArray; } else { decodedLanguagesArray = languagesArray; } </DeepExtract> for (int i = 0; i < languagesArray.length; i++) { String[] list = getTranslatorsNames(languagesArray[i]); adapter.addSection(decodedLanguagesArray[i], new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list)); } setListAdapter(adapter); }
ytdownloader-2
positive
439,128
@Override public void remove(AttributeKey key) { AttributeEntityMapper mapper = session.getMapper(AttributeEntityMapper.class); AttributeEntity attribute = new AttributeEntity(key.getKey(), key.getScope(), ""); mapper.delete(attribute); Map<AttributeKey, Object> newAttributes = Maps.newHashMap(); AttributeEntityMapper mapper = session.getMapper(AttributeEntityMapper.class); try { for (AttributeEntity entity : mapper.selectAll()) { newAttributes.put(new AttributeKey(entity.getfKEY(), entity.getfSCOPE()), entity.getfVALUE()); } container.reset(newAttributes); } catch (Exception e) { log.error("Could not set new attributes", e); } }
@Override public void remove(AttributeKey key) { AttributeEntityMapper mapper = session.getMapper(AttributeEntityMapper.class); AttributeEntity attribute = new AttributeEntity(key.getKey(), key.getScope(), ""); mapper.delete(attribute); <DeepExtract> Map<AttributeKey, Object> newAttributes = Maps.newHashMap(); AttributeEntityMapper mapper = session.getMapper(AttributeEntityMapper.class); try { for (AttributeEntity entity : mapper.selectAll()) { newAttributes.put(new AttributeKey(entity.getfKEY(), entity.getfSCOPE()), entity.getfVALUE()); } container.reset(newAttributes); } catch (Exception e) { log.error("Could not set new attributes", e); } </DeepExtract> }
soabase
positive
439,129
private void showActionDefault(Action action) throws IOException { Set<Tile> actionTiles = action instanceof PlayerAction ? ((PlayerAction) action).getTiles() : null; PlayerLocation location = action instanceof PlayerAction ? ((PlayerAction) action).getLocation() : null; if (location == null) { cliView.printSplitLine(getDefaultActionStr(action.getType(), actionTiles).toString(), POSITION_WIDTH * 4); } else { PlayerLocation.Relation relation = contextView.getMyLocation().getRelationOf(location); int position = 1 + POSITION_WIDTH * relation.ordinal(); StringBuilder showStr = new StringBuilder(); IntStream.range(0, position).forEach(i -> showStr.append(' ')); showStr.append(str(contextView.getTableView().getPlayerName(location))); showStr.append(' '); showStr.append(getDefaultActionStr(action.getType(), actionTiles)); cliView.printMessage(showStr.toString()); } updateTileLine(); }
private void showActionDefault(Action action) throws IOException { Set<Tile> actionTiles = action instanceof PlayerAction ? ((PlayerAction) action).getTiles() : null; PlayerLocation location = action instanceof PlayerAction ? ((PlayerAction) action).getLocation() : null; <DeepExtract> if (location == null) { cliView.printSplitLine(getDefaultActionStr(action.getType(), actionTiles).toString(), POSITION_WIDTH * 4); } else { PlayerLocation.Relation relation = contextView.getMyLocation().getRelationOf(location); int position = 1 + POSITION_WIDTH * relation.ordinal(); StringBuilder showStr = new StringBuilder(); IntStream.range(0, position).forEach(i -> showStr.append(' ')); showStr.append(str(contextView.getTableView().getPlayerName(location))); showStr.append(' '); showStr.append(getDefaultActionStr(action.getType(), actionTiles)); cliView.printMessage(showStr.toString()); } updateTileLine(); </DeepExtract> }
mahjong
positive
439,130
@Override public void componentResized(ComponentEvent e) { if (frame.isVisible()) { referencePanel.getBounds(bounds); bounds.setLocation(referencePanel.getLocationOnScreen()); window.setBounds(bounds); } }
@Override public void componentResized(ComponentEvent e) { <DeepExtract> if (frame.isVisible()) { referencePanel.getBounds(bounds); bounds.setLocation(referencePanel.getLocationOnScreen()); window.setBounds(bounds); } </DeepExtract> }
vlcj-examples
positive
439,132
@Test public void shouldSearchTrajStationMdMx() throws Exception { ObjTrajectory traj = new ObjTrajectory(); traj.setUid("traj-search"); String query = traj.getXMLString("1.4.1.1"); ObjTrajectorys trajectorysQuery = WitsmlMarshal.deserialize(query, ObjTrajectorys.class); ObjTrajectory singularTrajectoryQuery = trajectorysQuery.getTrajectory().get(0); singularTrajectoryQuery.setName("traj-search"); com.hashmapinc.tempus.WitsmlObjects.v1411.MeasuredDepthCoord mDMnMeasuredDepth = new com.hashmapinc.tempus.WitsmlObjects.v1411.MeasuredDepthCoord(); com.hashmapinc.tempus.WitsmlObjects.v1411.MeasuredDepthCoord mDMxmeasuredDepth = new com.hashmapinc.tempus.WitsmlObjects.v1411.MeasuredDepthCoord(); mDMnMeasuredDepth.setValue(null); singularTrajectoryQuery.setMdMn(mDMnMeasuredDepth); mDMxmeasuredDepth.setValue(500.0); singularTrajectoryQuery.setMdMx(mDMxmeasuredDepth); List<AbstractWitsmlObject> wmlObjectsQuery = new ArrayList<>(); wmlObjectsQuery.add(singularTrajectoryQuery); QueryContext qc = new QueryContext("1.4.1.1", "trajectory", null, query, wmlObjectsQuery, "goodUsername", "goodPassword", "shouldSearchTrajectoryCaseB"); assertEquals(true, this.valve.trajHasSearchQueryArgs(qc)); }
@Test public void shouldSearchTrajStationMdMx() throws Exception { ObjTrajectory traj = new ObjTrajectory(); traj.setUid("traj-search"); String query = traj.getXMLString("1.4.1.1"); ObjTrajectorys trajectorysQuery = WitsmlMarshal.deserialize(query, ObjTrajectorys.class); ObjTrajectory singularTrajectoryQuery = trajectorysQuery.getTrajectory().get(0); singularTrajectoryQuery.setName("traj-search"); <DeepExtract> com.hashmapinc.tempus.WitsmlObjects.v1411.MeasuredDepthCoord mDMnMeasuredDepth = new com.hashmapinc.tempus.WitsmlObjects.v1411.MeasuredDepthCoord(); com.hashmapinc.tempus.WitsmlObjects.v1411.MeasuredDepthCoord mDMxmeasuredDepth = new com.hashmapinc.tempus.WitsmlObjects.v1411.MeasuredDepthCoord(); mDMnMeasuredDepth.setValue(null); singularTrajectoryQuery.setMdMn(mDMnMeasuredDepth); mDMxmeasuredDepth.setValue(500.0); singularTrajectoryQuery.setMdMx(mDMxmeasuredDepth); List<AbstractWitsmlObject> wmlObjectsQuery = new ArrayList<>(); wmlObjectsQuery.add(singularTrajectoryQuery); QueryContext qc = new QueryContext("1.4.1.1", "trajectory", null, query, wmlObjectsQuery, "goodUsername", "goodPassword", "shouldSearchTrajectoryCaseB"); assertEquals(true, this.valve.trajHasSearchQueryArgs(qc)); </DeepExtract> }
Drillflow
positive
439,134
@Override public void onAnimationFinished(BaseAnimation baseAnimation) { planetController.collectArtifact(artifactObject); App.TUTORIAL_CONTROLLER.onArtifactCollected(); }
@Override public void onAnimationFinished(BaseAnimation baseAnimation) { <DeepExtract> planetController.collectArtifact(artifactObject); App.TUTORIAL_CONTROLLER.onArtifactCollected(); </DeepExtract> }
Alien-Ark
positive
439,135
public static int updateEntitiesCount(String table, String setClause, String whereClause) throws SQLException { if (open) return; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } connection = DriverManager.getConnection(Constants.DATABASE_CONNECTION, Constants.DATABASE_USER, Constants.DATABASE_PASSWORD); statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); open = true; String expression = "UPDATE " + table + " SET " + setClause + " WHERE " + whereClause; System.out.println("S-a apelat expresia SQL \'" + expression + "\'"); statement.execute(expression); return statement.getUpdateCount(); }
public static int updateEntitiesCount(String table, String setClause, String whereClause) throws SQLException { <DeepExtract> if (open) return; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } connection = DriverManager.getConnection(Constants.DATABASE_CONNECTION, Constants.DATABASE_USER, Constants.DATABASE_PASSWORD); statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); open = true; </DeepExtract> String expression = "UPDATE " + table + " SET " + setClause + " WHERE " + whereClause; System.out.println("S-a apelat expresia SQL \'" + expression + "\'"); statement.execute(expression); return statement.getUpdateCount(); }
University-Management-System
positive
439,136
public static void startActivityWithData(Activity context, Class<?> activity, String... data) { IntentBuilder build = new IntentBuilder(activity); for (int i = 0; i < data.length; i++) { build.putExtra(data[i], i); } if (context != null) { context.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getContext().startActivity(context); } }
public static void startActivityWithData(Activity context, Class<?> activity, String... data) { IntentBuilder build = new IntentBuilder(activity); for (int i = 0; i < data.length; i++) { build.putExtra(data[i], i); } <DeepExtract> if (context != null) { context.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getContext().startActivity(context); } </DeepExtract> }
Utils-Everywhere
positive
439,137
private void writeTablesWithIncrementingColumnNames(List<Table> tables, LineWriter out) throws IOException { out.writeln("<li>"); out.writeln("<b>Tables with incrementing column names, potentially indicating denormalization:</b>"); if (!tables.isEmpty()) { out.writeln("<table class='dataTable' border='1' rules='groups'>"); out.writeln("<thead align='left'>"); out.writeln("<tr>"); out.writeln(" <th>Table</th>"); out.writeln("</tr>"); out.writeln("</thead>"); out.writeln("<tbody>"); for (Table table : tables) { out.writeln(" <tr>"); out.write(" <td class='detail'>"); out.write("<a href='tables/"); out.write(encodeHref(table.getName())); out.write(".html'>"); out.write(table.getName()); out.write("</a>"); out.writeln("</td>"); out.writeln(" </tr>"); } out.writeln("</tbody>"); out.writeln("</table>"); } switch(tables.size()) { case 0: out.write("<br>Anomaly not detected"); break; case 1: out.write("1 instance of anomaly detected"); break; default: out.write(tables.size() + " instances of anomaly detected"); } out.writeln("<p></li>"); }
private void writeTablesWithIncrementingColumnNames(List<Table> tables, LineWriter out) throws IOException { out.writeln("<li>"); out.writeln("<b>Tables with incrementing column names, potentially indicating denormalization:</b>"); if (!tables.isEmpty()) { out.writeln("<table class='dataTable' border='1' rules='groups'>"); out.writeln("<thead align='left'>"); out.writeln("<tr>"); out.writeln(" <th>Table</th>"); out.writeln("</tr>"); out.writeln("</thead>"); out.writeln("<tbody>"); for (Table table : tables) { out.writeln(" <tr>"); out.write(" <td class='detail'>"); out.write("<a href='tables/"); out.write(encodeHref(table.getName())); out.write(".html'>"); out.write(table.getName()); out.write("</a>"); out.writeln("</td>"); out.writeln(" </tr>"); } out.writeln("</tbody>"); out.writeln("</table>"); } <DeepExtract> switch(tables.size()) { case 0: out.write("<br>Anomaly not detected"); break; case 1: out.write("1 instance of anomaly detected"); break; default: out.write(tables.size() + " instances of anomaly detected"); } </DeepExtract> out.writeln("<p></li>"); }
maven-schemaspy-plugin
positive
439,139
public static void shutdown_error() { Client.runReplayCloseHook = true; if (input == null) return; try { if (retained_timestamp != TIMESTAMP_EOF && retained_bytes != null) { try { ByteBuffer buffer = ByteBuffer.allocate(retained_bread + 8); buffer.putInt(retained_timestamp); buffer.putInt(retained_bread); buffer.put(retained_bytes, retained_off, retained_bread); input_checksum.update(buffer.array()); input.write(buffer.array()); input.flush(); } catch (Exception e) { e.printStackTrace(); shutdown_error(); } } ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(TIMESTAMP_EOF); input_checksum.update(buffer.array()); input.write(buffer.array()); output_checksum.update(buffer.array()); output.write(buffer.array()); input.write(input_checksum.digest()); output.write(output_checksum.digest()); Logger.Debug("Generating metadata"); try { metadata.writeInt(retained_timestamp); metadata.writeLong(System.currentTimeMillis()); if (ipAddressMetadata.length == 4) { metadata.writeInt(0); metadata.writeInt(0); metadata.writeInt(0xFFFF); } for (int i = 0; i < ipAddressMetadata.length; i++) { metadata.writeByte(ipAddressMetadata[i]); } metadata.writeByte(0); int userSettings = 0; if (!Client.members) { userSettings |= 1 << 31; } metadata.writeInt(userSettings); metadata.flush(); metadata.close(); } catch (IOException e) { Logger.Error("Couldn't write metadata.bin!"); } output.close(); input.close(); keys.close(); if (started_record_kb_mouse) { keyboard.write(buffer.array()); mouse.write(buffer.array()); keyboard.close(); mouse.close(); } output = null; input = null; keys = null; keyboard = null; mouse = null; output_checksum = null; input_checksum = null; retained_timestamp = TIMESTAMP_EOF; retained_bytes = null; Logger.Info("Replay recording stopped"); } catch (Exception e) { output = null; input = null; keys = null; keyboard = null; mouse = null; Logger.Error("Unable to close replay files"); return; } isRecording = false; if (Client.state == Client.STATE_GAME) { Client.displayMessage("Recording has been stopped because of an error", Client.CHAT_QUEST); Client.displayMessage("Please log back in to start recording again", Client.CHAT_QUEST); } }
public static void shutdown_error() { Client.runReplayCloseHook = true; <DeepExtract> if (input == null) return; try { if (retained_timestamp != TIMESTAMP_EOF && retained_bytes != null) { try { ByteBuffer buffer = ByteBuffer.allocate(retained_bread + 8); buffer.putInt(retained_timestamp); buffer.putInt(retained_bread); buffer.put(retained_bytes, retained_off, retained_bread); input_checksum.update(buffer.array()); input.write(buffer.array()); input.flush(); } catch (Exception e) { e.printStackTrace(); shutdown_error(); } } ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(TIMESTAMP_EOF); input_checksum.update(buffer.array()); input.write(buffer.array()); output_checksum.update(buffer.array()); output.write(buffer.array()); input.write(input_checksum.digest()); output.write(output_checksum.digest()); Logger.Debug("Generating metadata"); try { metadata.writeInt(retained_timestamp); metadata.writeLong(System.currentTimeMillis()); if (ipAddressMetadata.length == 4) { metadata.writeInt(0); metadata.writeInt(0); metadata.writeInt(0xFFFF); } for (int i = 0; i < ipAddressMetadata.length; i++) { metadata.writeByte(ipAddressMetadata[i]); } metadata.writeByte(0); int userSettings = 0; if (!Client.members) { userSettings |= 1 << 31; } metadata.writeInt(userSettings); metadata.flush(); metadata.close(); } catch (IOException e) { Logger.Error("Couldn't write metadata.bin!"); } output.close(); input.close(); keys.close(); if (started_record_kb_mouse) { keyboard.write(buffer.array()); mouse.write(buffer.array()); keyboard.close(); mouse.close(); } output = null; input = null; keys = null; keyboard = null; mouse = null; output_checksum = null; input_checksum = null; retained_timestamp = TIMESTAMP_EOF; retained_bytes = null; Logger.Info("Replay recording stopped"); } catch (Exception e) { output = null; input = null; keys = null; keyboard = null; mouse = null; Logger.Error("Unable to close replay files"); return; } isRecording = false; </DeepExtract> if (Client.state == Client.STATE_GAME) { Client.displayMessage("Recording has been stopped because of an error", Client.CHAT_QUEST); Client.displayMessage("Please log back in to start recording again", Client.CHAT_QUEST); } }
rscplus
positive
439,141
@Override @Transactional(rollbackFor = Exception.class) public UserRole grantRole(String userId, String roleId) { User user; User user = (User) RedisCacheUtils.get("user:" + userId); if (user != null) { user = user; } else { user = userDao.selectById(userId); if (user != null) { RedisCacheUtils.set("user:" + userId, user, 1800); } user = user; } Role role; User user = (User) RedisCacheUtils.get("user:" + roleId); if (user != null) { role = user; } else { user = userDao.selectById(roleId); if (user != null) { RedisCacheUtils.set("user:" + roleId, user, 1800); } role = user; } if (user == null || role == null) { return null; } UserRole userRole = new UserRole(); userRole.setRoleId(roleId); userRole.setUserId(userId); userRole.setSalt(PasswordUtils.getSalt()); userRole.setPassword(PasswordUtils.encryptPassword(userRole.getSalt(), userRole.getPassword())); userDao.insert(userRole); RedisCacheUtils.set("user:" + userRole.getId(), userRole, 1800); return userDao.selectById(userRole.getId()); return userRole; }
@Override @Transactional(rollbackFor = Exception.class) public UserRole grantRole(String userId, String roleId) { User user; User user = (User) RedisCacheUtils.get("user:" + userId); if (user != null) { user = user; } else { user = userDao.selectById(userId); if (user != null) { RedisCacheUtils.set("user:" + userId, user, 1800); } user = user; } Role role; User user = (User) RedisCacheUtils.get("user:" + roleId); if (user != null) { role = user; } else { user = userDao.selectById(roleId); if (user != null) { RedisCacheUtils.set("user:" + roleId, user, 1800); } role = user; } if (user == null || role == null) { return null; } UserRole userRole = new UserRole(); userRole.setRoleId(roleId); userRole.setUserId(userId); <DeepExtract> userRole.setSalt(PasswordUtils.getSalt()); userRole.setPassword(PasswordUtils.encryptPassword(userRole.getSalt(), userRole.getPassword())); userDao.insert(userRole); RedisCacheUtils.set("user:" + userRole.getId(), userRole, 1800); return userDao.selectById(userRole.getId()); </DeepExtract> return userRole; }
blog-springboot
positive
439,142
protected JUTClassesAndPackages initPackages(IPackageFragment pack) throws CoreException, JUTWarning { List<IPackageFragmentRoot> baseSrcFolders = new ArrayList<IPackageFragmentRoot>(); IPackageFragmentRoot testSrcFolder = null; JUTClassesAndPackages jutClassesAndPackages = new JUTClassesAndPackages(); List<IPackageFragment> basePackages = new ArrayList<IPackageFragment>(); IPackageFragment basePackage = null; IPackageFragment testPackage = null; String testPackagePostfix = JUTPreferences.getTestPackagePostfix(); String baseProjectName = ""; String basePackageName = ""; String testProjectName = ""; String testPackageName = ""; if (projects.isBaseProjectSelected()) { baseProjectName = projects.getBaseProject().getElementName(); basePackage = pack; basePackages.add(basePackage); basePackageName = pack.getElementName(); testProjectName = null; if (projects.getTestProject() != null) { testProjectName = projects.getTestProject().getElementName(); if (testPackagePostfix.equals("")) { testPackageName = basePackageName; } else if ("".equals(basePackageName)) { testPackageName = testPackagePostfix; } else if (basePackageName.startsWith(baseProjectName)) { testPackageName = basePackageName.replace(baseProjectName, testProjectName); testPackageName += testPackagePostfix; } else { testPackageName = basePackageName + "." + testPackagePostfix; } testSrcFolder = getTestSourceFolder(projects.getTestProject(), basePackage); testPackage = JDTUtils.getPackage(projects.getTestProject(), testSrcFolder, testPackageName, false); } } else { testPackage = pack; baseProjectName = projects.getBaseProject().getElementName(); testProjectName = projects.getTestProject().getElementName(); testPackageName = testPackage.getElementName(); if (testPackagePostfix.equals("")) { basePackageName = testPackageName; } else if (testPackagePostfix.equals(testPackageName)) { basePackageName = ""; } else { int lastIndexOf = testPackageName.lastIndexOf(testPackagePostfix); if (lastIndexOf > -1) { basePackageName = testPackageName.substring(0, lastIndexOf); } else { throw new JUTWarning("The base package could not be found! Test-package-name: " + testPackageName); } } baseSrcFolders = getBaseSourceFolders(projects.getBaseProject(), testPackage); for (IPackageFragmentRoot root : baseSrcFolders) { basePackage = JDTUtils.getPackage(projects.getBaseProject(), root, basePackageName, false); if (basePackage != null && basePackage.exists()) { basePackages.add(basePackage); } } } if (basePackages.size() == 0) { throw new JUTWarning("The base package could not be found! The base-class was moved manually or the preferences are not correct."); } this.testPackageName = testPackageName; this.basePackages = basePackages; this.baseSrcFolders = baseSrcFolders; this.testPackage = testPackage; this.testSrcFolder = testSrcFolder; this.classesAndPackages = jutClassesAndPackages; return jutClassesAndPackages; }
protected JUTClassesAndPackages initPackages(IPackageFragment pack) throws CoreException, JUTWarning { List<IPackageFragmentRoot> baseSrcFolders = new ArrayList<IPackageFragmentRoot>(); IPackageFragmentRoot testSrcFolder = null; JUTClassesAndPackages jutClassesAndPackages = new JUTClassesAndPackages(); List<IPackageFragment> basePackages = new ArrayList<IPackageFragment>(); IPackageFragment basePackage = null; IPackageFragment testPackage = null; String testPackagePostfix = JUTPreferences.getTestPackagePostfix(); String baseProjectName = ""; String basePackageName = ""; String testProjectName = ""; String testPackageName = ""; if (projects.isBaseProjectSelected()) { baseProjectName = projects.getBaseProject().getElementName(); basePackage = pack; basePackages.add(basePackage); basePackageName = pack.getElementName(); testProjectName = null; if (projects.getTestProject() != null) { testProjectName = projects.getTestProject().getElementName(); if (testPackagePostfix.equals("")) { testPackageName = basePackageName; } else if ("".equals(basePackageName)) { testPackageName = testPackagePostfix; } else if (basePackageName.startsWith(baseProjectName)) { testPackageName = basePackageName.replace(baseProjectName, testProjectName); testPackageName += testPackagePostfix; } else { testPackageName = basePackageName + "." + testPackagePostfix; } testSrcFolder = getTestSourceFolder(projects.getTestProject(), basePackage); testPackage = JDTUtils.getPackage(projects.getTestProject(), testSrcFolder, testPackageName, false); } } else { testPackage = pack; baseProjectName = projects.getBaseProject().getElementName(); testProjectName = projects.getTestProject().getElementName(); testPackageName = testPackage.getElementName(); if (testPackagePostfix.equals("")) { basePackageName = testPackageName; } else if (testPackagePostfix.equals(testPackageName)) { basePackageName = ""; } else { int lastIndexOf = testPackageName.lastIndexOf(testPackagePostfix); if (lastIndexOf > -1) { basePackageName = testPackageName.substring(0, lastIndexOf); } else { throw new JUTWarning("The base package could not be found! Test-package-name: " + testPackageName); } } baseSrcFolders = getBaseSourceFolders(projects.getBaseProject(), testPackage); for (IPackageFragmentRoot root : baseSrcFolders) { basePackage = JDTUtils.getPackage(projects.getBaseProject(), root, basePackageName, false); if (basePackage != null && basePackage.exists()) { basePackages.add(basePackage); } } } if (basePackages.size() == 0) { throw new JUTWarning("The base package could not be found! The base-class was moved manually or the preferences are not correct."); } this.testPackageName = testPackageName; this.basePackages = basePackages; this.baseSrcFolders = baseSrcFolders; this.testPackage = testPackage; this.testSrcFolder = testSrcFolder; <DeepExtract> this.classesAndPackages = jutClassesAndPackages; </DeepExtract> return jutClassesAndPackages; }
junit-tools
positive
439,144
public static LogitTreeNode buildTree(final BaseFeatureSet featureSet, final LinearFunction linFunc, final int maxDepth) { final List<AspatialFeature> aspatialFeatures = new ArrayList<AspatialFeature>(featureSet.aspatialFeatures().length); for (final AspatialFeature aspatial : featureSet.aspatialFeatures()) { aspatialFeatures.add(aspatial); } final List<SpatialFeature> spatialFeatures = new ArrayList<SpatialFeature>(featureSet.spatialFeatures().length); for (final SpatialFeature spatial : featureSet.spatialFeatures()) { spatialFeatures.add(spatial); } final FVector allWeights = linFunc.effectiveParams().allWeights(); final TFloatArrayList aspatialWeights = new TFloatArrayList(aspatialFeatures.size()); final TFloatArrayList spatialWeights = new TFloatArrayList(spatialFeatures.size()); for (int i = 0; i < allWeights.dim(); ++i) { if (i < aspatialFeatures.size()) aspatialWeights.add(allWeights.get(i)); else spatialWeights.add(allWeights.get(i)); } float accumInterceptWeight = 0.f; for (int i = aspatialFeatures.size() - 1; i >= 0; --i) { if (aspatialFeatures.get(i) instanceof InterceptFeature) { accumInterceptWeight += aspatialWeights.removeAt(i); aspatialFeatures.remove(i); } } for (int i = aspatialFeatures.size() - 1; i >= 0; --i) { if (aspatialWeights.getQuick(i) == 0.f) { ListUtils.removeSwap(aspatialWeights, i); ListUtils.removeSwap(aspatialFeatures, i); } } for (int i = spatialFeatures.size() - 1; i >= 0; --i) { if (spatialWeights.getQuick(i) == 0.f) { ListUtils.removeSwap(spatialWeights, i); ListUtils.removeSwap(spatialFeatures, i); } } if (aspatialFeatures.isEmpty() && spatialFeatures.isEmpty()) { return new LogitModelNode(new Feature[] { InterceptFeature.instance() }, new float[] { accumInterceptWeight }); } if (maxDepth == 0) { final int numModelFeatures = aspatialFeatures.size() + spatialFeatures.size() + 1; final Feature[] featuresArray = new Feature[numModelFeatures]; final float[] weightsArray = new float[numModelFeatures]; int nextIdx = 0; featuresArray[nextIdx] = InterceptFeature.instance(); weightsArray[nextIdx++] = accumInterceptWeight; for (int i = 0; i < aspatialFeatures.size(); ++i) { featuresArray[nextIdx] = aspatialFeatures.get(i); weightsArray[nextIdx++] = aspatialWeights.getQuick(i); } for (int i = 0; i < spatialFeatures.size(); ++i) { featuresArray[nextIdx] = spatialFeatures.get(i); weightsArray[nextIdx++] = spatialWeights.getQuick(i); } return new LogitModelNode(featuresArray, weightsArray); } float lowestScore = Float.POSITIVE_INFINITY; int bestIdx = -1; boolean bestFeatureIsAspatial = true; float sumAllAbsWeights = 0.f; for (int i = 0; i < aspatialWeights.size(); ++i) { sumAllAbsWeights += Math.abs(aspatialWeights.getQuick(i)); } for (int i = 0; i < spatialWeights.size(); ++i) { sumAllAbsWeights += Math.abs(spatialWeights.getQuick(i)); } for (int i = 0; i < aspatialFeatures.size(); ++i) { final float absFeatureWeight = Math.abs(aspatialWeights.getQuick(i)); float falseScore = sumAllAbsWeights - absFeatureWeight; float trueScore = sumAllAbsWeights - absFeatureWeight; for (int j = 0; j < spatialWeights.size(); ++j) { trueScore -= Math.abs(spatialWeights.getQuick(j)); } final float splitScore = (falseScore + trueScore) / 2.f; if (splitScore < lowestScore) { lowestScore = splitScore; bestIdx = i; } } for (int i = 0; i < spatialFeatures.size(); ++i) { final SpatialFeature spatial = spatialFeatures.get(i); final float absFeatureWeight = Math.abs(spatialWeights.getQuick(i)); float falseScore = sumAllAbsWeights - absFeatureWeight; float trueScore = sumAllAbsWeights - absFeatureWeight; for (int j = 0; j < aspatialWeights.size(); ++j) { trueScore -= Math.abs(aspatialWeights.getQuick(j)); } for (int j = 0; j < spatialFeatures.size(); ++j) { if (i == j) continue; final SpatialFeature otherFeature = spatialFeatures.get(j); if (otherFeature.generalises(spatial)) { final float otherAbsWeight = Math.abs(spatialWeights.getQuick(j)); trueScore -= otherAbsWeight; } if (spatial.generalises(otherFeature)) { final float otherAbsWeight = Math.abs(spatialWeights.getQuick(j)); falseScore -= otherAbsWeight; } } final float splitScore = (falseScore + trueScore) / 2.f; if (splitScore < lowestScore) { lowestScore = splitScore; bestIdx = i; bestFeatureIsAspatial = false; } } final Feature splittingFeature; if (bestFeatureIsAspatial) splittingFeature = aspatialFeatures.get(bestIdx); else splittingFeature = spatialFeatures.get(bestIdx); final LogitTreeNode trueBranch; { final List<AspatialFeature> remainingAspatialsWhenTrue; final TFloatArrayList remainingAspatialWeightsWhenTrue; final List<SpatialFeature> remainingSpatialsWhenTrue; final TFloatArrayList remainingSpatialWeightsWhenTrue; float accumInterceptWhenTrue = accumInterceptWeight; if (bestFeatureIsAspatial) { remainingAspatialsWhenTrue = new ArrayList<AspatialFeature>(aspatialFeatures); remainingAspatialWeightsWhenTrue = new TFloatArrayList(aspatialWeights); ListUtils.removeSwap(remainingAspatialsWhenTrue, bestIdx); accumInterceptWhenTrue += remainingAspatialWeightsWhenTrue.getQuick(bestIdx); ListUtils.removeSwap(remainingAspatialWeightsWhenTrue, bestIdx); remainingSpatialsWhenTrue = new ArrayList<SpatialFeature>(); remainingSpatialWeightsWhenTrue = new TFloatArrayList(); } else { remainingAspatialsWhenTrue = new ArrayList<AspatialFeature>(); remainingAspatialWeightsWhenTrue = new TFloatArrayList(); remainingSpatialsWhenTrue = new ArrayList<SpatialFeature>(spatialFeatures); remainingSpatialWeightsWhenTrue = new TFloatArrayList(spatialWeights); for (int i = remainingSpatialsWhenTrue.size() - 1; i >= 0; --i) { if (i == bestIdx) { ListUtils.removeSwap(remainingSpatialsWhenTrue, i); accumInterceptWhenTrue += remainingSpatialWeightsWhenTrue.getQuick(i); ListUtils.removeSwap(remainingSpatialWeightsWhenTrue, i); } else { final SpatialFeature other = remainingSpatialsWhenTrue.get(i); if (other.generalises((SpatialFeature) splittingFeature)) { ListUtils.removeSwap(remainingSpatialsWhenTrue, i); accumInterceptWhenTrue += remainingSpatialWeightsWhenTrue.getQuick(i); ListUtils.removeSwap(remainingSpatialWeightsWhenTrue, i); } } } } trueBranch = buildNode(remainingAspatialsWhenTrue, remainingAspatialWeightsWhenTrue, remainingSpatialsWhenTrue, remainingSpatialWeightsWhenTrue, accumInterceptWhenTrue, maxDepth - 1); } final LogitTreeNode falseBranch; { final List<AspatialFeature> remainingAspatialsWhenFalse; final TFloatArrayList remainingAspatialWeightsWhenFalse; final List<SpatialFeature> remainingSpatialsWhenFalse; final TFloatArrayList remainingSpatialWeightsWhenFalse; float accumInterceptWhenFalse = accumInterceptWeight; if (bestFeatureIsAspatial) { remainingAspatialsWhenFalse = new ArrayList<AspatialFeature>(aspatialFeatures); remainingAspatialWeightsWhenFalse = new TFloatArrayList(aspatialWeights); ListUtils.removeSwap(remainingAspatialsWhenFalse, bestIdx); ListUtils.removeSwap(remainingAspatialWeightsWhenFalse, bestIdx); remainingSpatialsWhenFalse = new ArrayList<SpatialFeature>(spatialFeatures); remainingSpatialWeightsWhenFalse = new TFloatArrayList(spatialWeights); } else { remainingAspatialsWhenFalse = new ArrayList<AspatialFeature>(aspatialFeatures); remainingAspatialWeightsWhenFalse = new TFloatArrayList(aspatialWeights); remainingSpatialsWhenFalse = new ArrayList<SpatialFeature>(spatialFeatures); remainingSpatialWeightsWhenFalse = new TFloatArrayList(spatialWeights); for (int i = remainingSpatialsWhenFalse.size() - 1; i >= 0; --i) { if (i == bestIdx) { ListUtils.removeSwap(remainingSpatialsWhenFalse, i); ListUtils.removeSwap(remainingSpatialWeightsWhenFalse, i); } else { final SpatialFeature other = remainingSpatialsWhenFalse.get(i); if (((SpatialFeature) splittingFeature).generalises(other)) { ListUtils.removeSwap(remainingSpatialsWhenFalse, i); ListUtils.removeSwap(remainingSpatialWeightsWhenFalse, i); } } } } falseBranch = buildNode(remainingAspatialsWhenFalse, remainingAspatialWeightsWhenFalse, remainingSpatialsWhenFalse, remainingSpatialWeightsWhenFalse, accumInterceptWhenFalse, maxDepth - 1); } return new LogitDecisionNode(splittingFeature, trueBranch, falseBranch); }
public static LogitTreeNode buildTree(final BaseFeatureSet featureSet, final LinearFunction linFunc, final int maxDepth) { final List<AspatialFeature> aspatialFeatures = new ArrayList<AspatialFeature>(featureSet.aspatialFeatures().length); for (final AspatialFeature aspatial : featureSet.aspatialFeatures()) { aspatialFeatures.add(aspatial); } final List<SpatialFeature> spatialFeatures = new ArrayList<SpatialFeature>(featureSet.spatialFeatures().length); for (final SpatialFeature spatial : featureSet.spatialFeatures()) { spatialFeatures.add(spatial); } final FVector allWeights = linFunc.effectiveParams().allWeights(); final TFloatArrayList aspatialWeights = new TFloatArrayList(aspatialFeatures.size()); final TFloatArrayList spatialWeights = new TFloatArrayList(spatialFeatures.size()); for (int i = 0; i < allWeights.dim(); ++i) { if (i < aspatialFeatures.size()) aspatialWeights.add(allWeights.get(i)); else spatialWeights.add(allWeights.get(i)); } float accumInterceptWeight = 0.f; for (int i = aspatialFeatures.size() - 1; i >= 0; --i) { if (aspatialFeatures.get(i) instanceof InterceptFeature) { accumInterceptWeight += aspatialWeights.removeAt(i); aspatialFeatures.remove(i); } } for (int i = aspatialFeatures.size() - 1; i >= 0; --i) { if (aspatialWeights.getQuick(i) == 0.f) { ListUtils.removeSwap(aspatialWeights, i); ListUtils.removeSwap(aspatialFeatures, i); } } for (int i = spatialFeatures.size() - 1; i >= 0; --i) { if (spatialWeights.getQuick(i) == 0.f) { ListUtils.removeSwap(spatialWeights, i); ListUtils.removeSwap(spatialFeatures, i); } } <DeepExtract> if (aspatialFeatures.isEmpty() && spatialFeatures.isEmpty()) { return new LogitModelNode(new Feature[] { InterceptFeature.instance() }, new float[] { accumInterceptWeight }); } if (maxDepth == 0) { final int numModelFeatures = aspatialFeatures.size() + spatialFeatures.size() + 1; final Feature[] featuresArray = new Feature[numModelFeatures]; final float[] weightsArray = new float[numModelFeatures]; int nextIdx = 0; featuresArray[nextIdx] = InterceptFeature.instance(); weightsArray[nextIdx++] = accumInterceptWeight; for (int i = 0; i < aspatialFeatures.size(); ++i) { featuresArray[nextIdx] = aspatialFeatures.get(i); weightsArray[nextIdx++] = aspatialWeights.getQuick(i); } for (int i = 0; i < spatialFeatures.size(); ++i) { featuresArray[nextIdx] = spatialFeatures.get(i); weightsArray[nextIdx++] = spatialWeights.getQuick(i); } return new LogitModelNode(featuresArray, weightsArray); } float lowestScore = Float.POSITIVE_INFINITY; int bestIdx = -1; boolean bestFeatureIsAspatial = true; float sumAllAbsWeights = 0.f; for (int i = 0; i < aspatialWeights.size(); ++i) { sumAllAbsWeights += Math.abs(aspatialWeights.getQuick(i)); } for (int i = 0; i < spatialWeights.size(); ++i) { sumAllAbsWeights += Math.abs(spatialWeights.getQuick(i)); } for (int i = 0; i < aspatialFeatures.size(); ++i) { final float absFeatureWeight = Math.abs(aspatialWeights.getQuick(i)); float falseScore = sumAllAbsWeights - absFeatureWeight; float trueScore = sumAllAbsWeights - absFeatureWeight; for (int j = 0; j < spatialWeights.size(); ++j) { trueScore -= Math.abs(spatialWeights.getQuick(j)); } final float splitScore = (falseScore + trueScore) / 2.f; if (splitScore < lowestScore) { lowestScore = splitScore; bestIdx = i; } } for (int i = 0; i < spatialFeatures.size(); ++i) { final SpatialFeature spatial = spatialFeatures.get(i); final float absFeatureWeight = Math.abs(spatialWeights.getQuick(i)); float falseScore = sumAllAbsWeights - absFeatureWeight; float trueScore = sumAllAbsWeights - absFeatureWeight; for (int j = 0; j < aspatialWeights.size(); ++j) { trueScore -= Math.abs(aspatialWeights.getQuick(j)); } for (int j = 0; j < spatialFeatures.size(); ++j) { if (i == j) continue; final SpatialFeature otherFeature = spatialFeatures.get(j); if (otherFeature.generalises(spatial)) { final float otherAbsWeight = Math.abs(spatialWeights.getQuick(j)); trueScore -= otherAbsWeight; } if (spatial.generalises(otherFeature)) { final float otherAbsWeight = Math.abs(spatialWeights.getQuick(j)); falseScore -= otherAbsWeight; } } final float splitScore = (falseScore + trueScore) / 2.f; if (splitScore < lowestScore) { lowestScore = splitScore; bestIdx = i; bestFeatureIsAspatial = false; } } final Feature splittingFeature; if (bestFeatureIsAspatial) splittingFeature = aspatialFeatures.get(bestIdx); else splittingFeature = spatialFeatures.get(bestIdx); final LogitTreeNode trueBranch; { final List<AspatialFeature> remainingAspatialsWhenTrue; final TFloatArrayList remainingAspatialWeightsWhenTrue; final List<SpatialFeature> remainingSpatialsWhenTrue; final TFloatArrayList remainingSpatialWeightsWhenTrue; float accumInterceptWhenTrue = accumInterceptWeight; if (bestFeatureIsAspatial) { remainingAspatialsWhenTrue = new ArrayList<AspatialFeature>(aspatialFeatures); remainingAspatialWeightsWhenTrue = new TFloatArrayList(aspatialWeights); ListUtils.removeSwap(remainingAspatialsWhenTrue, bestIdx); accumInterceptWhenTrue += remainingAspatialWeightsWhenTrue.getQuick(bestIdx); ListUtils.removeSwap(remainingAspatialWeightsWhenTrue, bestIdx); remainingSpatialsWhenTrue = new ArrayList<SpatialFeature>(); remainingSpatialWeightsWhenTrue = new TFloatArrayList(); } else { remainingAspatialsWhenTrue = new ArrayList<AspatialFeature>(); remainingAspatialWeightsWhenTrue = new TFloatArrayList(); remainingSpatialsWhenTrue = new ArrayList<SpatialFeature>(spatialFeatures); remainingSpatialWeightsWhenTrue = new TFloatArrayList(spatialWeights); for (int i = remainingSpatialsWhenTrue.size() - 1; i >= 0; --i) { if (i == bestIdx) { ListUtils.removeSwap(remainingSpatialsWhenTrue, i); accumInterceptWhenTrue += remainingSpatialWeightsWhenTrue.getQuick(i); ListUtils.removeSwap(remainingSpatialWeightsWhenTrue, i); } else { final SpatialFeature other = remainingSpatialsWhenTrue.get(i); if (other.generalises((SpatialFeature) splittingFeature)) { ListUtils.removeSwap(remainingSpatialsWhenTrue, i); accumInterceptWhenTrue += remainingSpatialWeightsWhenTrue.getQuick(i); ListUtils.removeSwap(remainingSpatialWeightsWhenTrue, i); } } } } trueBranch = buildNode(remainingAspatialsWhenTrue, remainingAspatialWeightsWhenTrue, remainingSpatialsWhenTrue, remainingSpatialWeightsWhenTrue, accumInterceptWhenTrue, maxDepth - 1); } final LogitTreeNode falseBranch; { final List<AspatialFeature> remainingAspatialsWhenFalse; final TFloatArrayList remainingAspatialWeightsWhenFalse; final List<SpatialFeature> remainingSpatialsWhenFalse; final TFloatArrayList remainingSpatialWeightsWhenFalse; float accumInterceptWhenFalse = accumInterceptWeight; if (bestFeatureIsAspatial) { remainingAspatialsWhenFalse = new ArrayList<AspatialFeature>(aspatialFeatures); remainingAspatialWeightsWhenFalse = new TFloatArrayList(aspatialWeights); ListUtils.removeSwap(remainingAspatialsWhenFalse, bestIdx); ListUtils.removeSwap(remainingAspatialWeightsWhenFalse, bestIdx); remainingSpatialsWhenFalse = new ArrayList<SpatialFeature>(spatialFeatures); remainingSpatialWeightsWhenFalse = new TFloatArrayList(spatialWeights); } else { remainingAspatialsWhenFalse = new ArrayList<AspatialFeature>(aspatialFeatures); remainingAspatialWeightsWhenFalse = new TFloatArrayList(aspatialWeights); remainingSpatialsWhenFalse = new ArrayList<SpatialFeature>(spatialFeatures); remainingSpatialWeightsWhenFalse = new TFloatArrayList(spatialWeights); for (int i = remainingSpatialsWhenFalse.size() - 1; i >= 0; --i) { if (i == bestIdx) { ListUtils.removeSwap(remainingSpatialsWhenFalse, i); ListUtils.removeSwap(remainingSpatialWeightsWhenFalse, i); } else { final SpatialFeature other = remainingSpatialsWhenFalse.get(i); if (((SpatialFeature) splittingFeature).generalises(other)) { ListUtils.removeSwap(remainingSpatialsWhenFalse, i); ListUtils.removeSwap(remainingSpatialWeightsWhenFalse, i); } } } } falseBranch = buildNode(remainingAspatialsWhenFalse, remainingAspatialWeightsWhenFalse, remainingSpatialsWhenFalse, remainingSpatialWeightsWhenFalse, accumInterceptWhenFalse, maxDepth - 1); } return new LogitDecisionNode(splittingFeature, trueBranch, falseBranch); </DeepExtract> }
LudiiAI
positive
439,145
public static DagRequest build(File project, File profile, Map<String, String> params, List<String> goals) { DagRequest dagRequest = new DagRequest(); dagRequest.dag = new Dag(); if (params == null) { params = new HashMap<>(); } AnalyticsBoard analyticsBoard = null; File ananas = Paths.get(project.getAbsolutePath(), "ananas.yml").toFile(); if (!ananas.exists()) { ananas = Paths.get(project.getAbsolutePath(), "ananas.yaml").toFile(); if (!ananas.exists()) { throw new RuntimeException("Can't find ananas.yml file in our project"); } } try { analyticsBoard = openYAML(ananas.getAbsolutePath(), AnalyticsBoard.class); } catch (Exception e) { throw new RuntimeException("Failed to parse analytics board file: " + e.getLocalizedMessage(), e); } Profile profileObj = new Profile(); try { if (profile.exists()) { profileObj = openYAML(profile.getAbsolutePath(), Profile.class); } else { LOG.error(String.format("Profile %s not found, fallback to default Local Flink Engine\n", profile.getAbsolutePath())); } } catch (Exception e) { LOG.warn("Failed to parse profile file: " + e.getLocalizedMessage()); LOG.warn("Fallback to default Local Flink Engine"); Arrays.stream(e.getStackTrace()).map(StackTraceElement::toString).forEach(LOG::error); } if (profileObj.engine == null) { profileObj.engine = new Engine(); profileObj.engine.name = "Local Engine"; profileObj.engine.type = "flink"; profileObj.engine.properties = new HashMap<>(); profileObj.engine.properties.put("database_type", "derby"); } dagRequest.dag.connections = analyticsBoard.dag.connections; dagRequest.dag.steps = Sets.newHashSet(analyticsBoard.steps.values()); dagRequest.engine = profileObj.engine; dagRequest.goals = new HashSet<>(goals); dagRequest.params = analyticsBoard.variables.stream().collect(Collectors.toMap(v -> v.name, v -> v)); profileObj.params.forEach((k, v) -> { if (dagRequest.params.containsKey(k)) { dagRequest.params.get(k).value = v; } }); params.forEach((k, v) -> { if (dagRequest.params.containsKey(k)) { dagRequest.params.get(k).value = v; } }); dagRequest.params.put("EXECUTE_TIME", new Variable("EXECUTE_TIME", "date", "", "runtime", "" + System.currentTimeMillis())); dagRequest.params.put("PROJECT_PATH", new Variable("PROJECT_PATH", "string", "", "runtime", project.getAbsolutePath())); return dagRequest; }
public static DagRequest build(File project, File profile, Map<String, String> params, List<String> goals) { DagRequest dagRequest = new DagRequest(); dagRequest.dag = new Dag(); if (params == null) { params = new HashMap<>(); } AnalyticsBoard analyticsBoard = null; File ananas = Paths.get(project.getAbsolutePath(), "ananas.yml").toFile(); if (!ananas.exists()) { ananas = Paths.get(project.getAbsolutePath(), "ananas.yaml").toFile(); if (!ananas.exists()) { throw new RuntimeException("Can't find ananas.yml file in our project"); } } try { analyticsBoard = openYAML(ananas.getAbsolutePath(), AnalyticsBoard.class); } catch (Exception e) { throw new RuntimeException("Failed to parse analytics board file: " + e.getLocalizedMessage(), e); } Profile profileObj = new Profile(); try { if (profile.exists()) { profileObj = openYAML(profile.getAbsolutePath(), Profile.class); } else { LOG.error(String.format("Profile %s not found, fallback to default Local Flink Engine\n", profile.getAbsolutePath())); } } catch (Exception e) { LOG.warn("Failed to parse profile file: " + e.getLocalizedMessage()); LOG.warn("Fallback to default Local Flink Engine"); Arrays.stream(e.getStackTrace()).map(StackTraceElement::toString).forEach(LOG::error); } if (profileObj.engine == null) { profileObj.engine = new Engine(); profileObj.engine.name = "Local Engine"; profileObj.engine.type = "flink"; profileObj.engine.properties = new HashMap<>(); profileObj.engine.properties.put("database_type", "derby"); } dagRequest.dag.connections = analyticsBoard.dag.connections; dagRequest.dag.steps = Sets.newHashSet(analyticsBoard.steps.values()); dagRequest.engine = profileObj.engine; dagRequest.goals = new HashSet<>(goals); dagRequest.params = analyticsBoard.variables.stream().collect(Collectors.toMap(v -> v.name, v -> v)); profileObj.params.forEach((k, v) -> { if (dagRequest.params.containsKey(k)) { dagRequest.params.get(k).value = v; } }); params.forEach((k, v) -> { if (dagRequest.params.containsKey(k)) { dagRequest.params.get(k).value = v; } }); <DeepExtract> dagRequest.params.put("EXECUTE_TIME", new Variable("EXECUTE_TIME", "date", "", "runtime", "" + System.currentTimeMillis())); dagRequest.params.put("PROJECT_PATH", new Variable("PROJECT_PATH", "string", "", "runtime", project.getAbsolutePath())); </DeepExtract> return dagRequest; }
ananas-desktop
positive
439,146
public int borderHover() { if (borderHover == null) { LogHelper.error("StyleHandler: Attempt to retrieve un-defined boderHover prop for " + baseProp); return 0; } return value; }
public int borderHover() { if (borderHover == null) { LogHelper.error("StyleHandler: Attempt to retrieve un-defined boderHover prop for " + baseProp); return 0; } <DeepExtract> return value; </DeepExtract> }
ProjectIntelligence
positive
439,148
@Override public void run() { Toast.makeText(getActivity(), "Programming Successful", Toast.LENGTH_SHORT).show(); if (deviceData.programmableData.identificationString != null) textView_IdString.setText(String.valueOf(deviceData.programmableData.identificationString)); if (deviceData.programmableData.PIN != null) textView_PIN.setText(String.valueOf(deviceData.programmableData.PIN)); if (deviceData.programmableData.latitude != null) textView_Latitude.setText(String.valueOf(deviceData.programmableData.latitude.setScale(5, BigDecimal.ROUND_HALF_UP))); if (deviceData.programmableData.longitude != null) textView_Longitude.setText(String.valueOf(deviceData.programmableData.longitude.setScale(5, BigDecimal.ROUND_HALF_UP))); if (deviceData.programmableData.hintString != null) textView_HintString.setText(String.valueOf(deviceData.programmableData.hintString)); if (deviceData.programmableData.lastVisitTimestamp != null) { DateFormat df = DateFormat.getDateTimeInstance(); df.setTimeZone(TimeZone.getTimeZone("UTC")); textView_LastVisit.setText(df.format(deviceData.programmableData.lastVisitTimestamp.getTime())); } if (deviceData.programmableData.numberOfVisits != null) textView_NumVisits.setText(String.valueOf(deviceData.programmableData.numberOfVisits)); textView_HardwareVer.setText(String.valueOf(deviceData.hardwareRevision)); textView_ManfID.setText(String.valueOf(deviceData.manufacturerID)); textView_ModelNum.setText(String.valueOf(deviceData.modelNumber)); textView_SoftwareVer.setText(String.valueOf(deviceData.softwareRevision)); textView_SerialNum.setText(String.valueOf(deviceData.serialNumber)); textView_BatteryVoltage.setText(String.valueOf(deviceData.batteryVoltage)); textView_BatteryStatus.setText(deviceData.batteryStatus.toString()); textView_OperatingTime.setText(String.valueOf(deviceData.cumulativeOperatingTime)); textView_OperatingTimeResolution.setText(String.valueOf(deviceData.cumulativeOperatingTimeResolution)); }
@Override public void run() { Toast.makeText(getActivity(), "Programming Successful", Toast.LENGTH_SHORT).show(); <DeepExtract> if (deviceData.programmableData.identificationString != null) textView_IdString.setText(String.valueOf(deviceData.programmableData.identificationString)); if (deviceData.programmableData.PIN != null) textView_PIN.setText(String.valueOf(deviceData.programmableData.PIN)); if (deviceData.programmableData.latitude != null) textView_Latitude.setText(String.valueOf(deviceData.programmableData.latitude.setScale(5, BigDecimal.ROUND_HALF_UP))); if (deviceData.programmableData.longitude != null) textView_Longitude.setText(String.valueOf(deviceData.programmableData.longitude.setScale(5, BigDecimal.ROUND_HALF_UP))); if (deviceData.programmableData.hintString != null) textView_HintString.setText(String.valueOf(deviceData.programmableData.hintString)); if (deviceData.programmableData.lastVisitTimestamp != null) { DateFormat df = DateFormat.getDateTimeInstance(); df.setTimeZone(TimeZone.getTimeZone("UTC")); textView_LastVisit.setText(df.format(deviceData.programmableData.lastVisitTimestamp.getTime())); } if (deviceData.programmableData.numberOfVisits != null) textView_NumVisits.setText(String.valueOf(deviceData.programmableData.numberOfVisits)); textView_HardwareVer.setText(String.valueOf(deviceData.hardwareRevision)); textView_ManfID.setText(String.valueOf(deviceData.manufacturerID)); textView_ModelNum.setText(String.valueOf(deviceData.modelNumber)); textView_SoftwareVer.setText(String.valueOf(deviceData.softwareRevision)); textView_SerialNum.setText(String.valueOf(deviceData.serialNumber)); textView_BatteryVoltage.setText(String.valueOf(deviceData.batteryVoltage)); textView_BatteryStatus.setText(deviceData.batteryStatus.toString()); textView_OperatingTime.setText(String.valueOf(deviceData.cumulativeOperatingTime)); textView_OperatingTimeResolution.setText(String.valueOf(deviceData.cumulativeOperatingTimeResolution)); </DeepExtract> }
ANT-Android-SDKs
positive
439,149
public void parse(IPacketParser parser) throws IOException { this.parseAddress(parser); this.parseOption(parser); int size = (IIntInputStream) parser.read("ZNet RX IO Sample Size"); if (size != 1) { throw new XBeeParseException("Sample size is not supported if > 1 for ZNet I/O"); } this.setDigitalChannelMaskMsb((IIntInputStream) parser.read("ZNet RX IO Sample Digital Mask 1")); this.setDigitalChannelMaskLsb((IIntInputStream) parser.read("ZNet RX IO Sample Digital Mask 2")); this.setAnalogChannelMask((IIntInputStream) parser.read("ZNet RX IO Sample Analog Channel Mask")); this.analogChannelMask = this.analogChannelMask & 0x8f; this.digitalChannelMaskMsb = this.digitalChannelMaskMsb & 0x1c; if (this.containsDigital()) { log.info("response contains digital data"); this.setDioMsb((IIntInputStream) parser.read("ZNet RX IO DIO MSB")); this.setDioLsb((IIntInputStream) parser.read("ZNet RX IO DIO LSB")); } else { log.info("response does not contain digital data"); } int enabledCount = 0; for (int i = 0; i < 4; i++) { if (this.isAnalogEnabled(i)) { log.info("response contains analog[" + i + "]"); analog[i] = ByteUtils.parse10BitAnalog((IIntInputStream) parser, enabledCount); enabledCount++; } } if (this.isSupplyVoltageEnabled()) { analog[SUPPLY_VOLTAGE_INDEX] = ByteUtils.parse10BitAnalog((IIntInputStream) parser, enabledCount); enabledCount++; } log.debug("There are " + analog + " analog inputs in this packet"); }
public void parse(IPacketParser parser) throws IOException { this.parseAddress(parser); this.parseOption(parser); <DeepExtract> int size = (IIntInputStream) parser.read("ZNet RX IO Sample Size"); if (size != 1) { throw new XBeeParseException("Sample size is not supported if > 1 for ZNet I/O"); } this.setDigitalChannelMaskMsb((IIntInputStream) parser.read("ZNet RX IO Sample Digital Mask 1")); this.setDigitalChannelMaskLsb((IIntInputStream) parser.read("ZNet RX IO Sample Digital Mask 2")); this.setAnalogChannelMask((IIntInputStream) parser.read("ZNet RX IO Sample Analog Channel Mask")); this.analogChannelMask = this.analogChannelMask & 0x8f; this.digitalChannelMaskMsb = this.digitalChannelMaskMsb & 0x1c; if (this.containsDigital()) { log.info("response contains digital data"); this.setDioMsb((IIntInputStream) parser.read("ZNet RX IO DIO MSB")); this.setDioLsb((IIntInputStream) parser.read("ZNet RX IO DIO LSB")); } else { log.info("response does not contain digital data"); } int enabledCount = 0; for (int i = 0; i < 4; i++) { if (this.isAnalogEnabled(i)) { log.info("response contains analog[" + i + "]"); analog[i] = ByteUtils.parse10BitAnalog((IIntInputStream) parser, enabledCount); enabledCount++; } } if (this.isSupplyVoltageEnabled()) { analog[SUPPLY_VOLTAGE_INDEX] = ByteUtils.parse10BitAnalog((IIntInputStream) parser, enabledCount); enabledCount++; } log.debug("There are " + analog + " analog inputs in this packet"); </DeepExtract> }
xbee-api
positive
439,150
@Override public void onClick(View v) { switch(VIEW_TYPE_SPINNER) { case VIEW_TYPE_SPINNER: if (mCurrentViewType != VIEW_TYPE_SPINNER) { switch(mMode) { case DATE_MODE_START: if (mIsLunar) { mDatePickerSpinner.updateDate(mLunarStartYear, mLunarStartMonth, mLunarStartDay); } else { mDatePickerSpinner.updateDate(mStartDate.get(Calendar.YEAR), mStartDate.get(Calendar.MONTH), mStartDate.get(Calendar.DAY_OF_MONTH)); } mViewAnimator.setDisplayedChild(0); mPickerView.setEnabled(true); mPickerView.setVisibility(View.VISIBLE); mCalendarViewLayout.setVisibility(View.GONE); mCurrentViewType = VIEW_TYPE_SPINNER; Message textValueSetMsg = mHandler.obtainMessage(); textValueSetMsg.what = MESSAGE_CALENDAR_HEADER_TEXT_VALUE_SET; mHandler.sendMessage(textValueSetMsg); break; case DATE_MODE_END: if (mIsLunar) { mDatePickerSpinner.updateDate(mLunarEndYear, mLunarEndMonth, mLunarEndDay); } else { mDatePickerSpinner.updateDate(mEndDate.get(Calendar.YEAR), mEndDate.get(Calendar.MONTH), mEndDate.get(Calendar.DAY_OF_MONTH)); } mViewAnimator.setDisplayedChild(0); mPickerView.setEnabled(true); mPickerView.setVisibility(View.VISIBLE); mCalendarViewLayout.setVisibility(View.GONE); mCurrentViewType = VIEW_TYPE_SPINNER; Message textValueSetMsg2 = mHandler.obtainMessage(); textValueSetMsg2.what = MESSAGE_CALENDAR_HEADER_TEXT_VALUE_SET; mHandler.sendMessage(textValueSetMsg2); break; default: if (mIsLunar) { mDatePickerSpinner.updateDate(mLunarCurrentYear, mLunarCurrentMonth, mLunarCurrentDay); } else { mDatePickerSpinner.updateDate(mCurrentDate.get(Calendar.YEAR), mCurrentDate.get(Calendar.MONTH), mCurrentDate.get(Calendar.DAY_OF_MONTH)); } mViewAnimator.setDisplayedChild(0); mPickerView.setEnabled(true); mPickerView.setVisibility(View.VISIBLE); mCalendarViewLayout.setVisibility(View.GONE); mCurrentViewType = VIEW_TYPE_SPINNER; Message textValueSetMsg3 = mHandler.obtainMessage(); textValueSetMsg3.what = MESSAGE_CALENDAR_HEADER_TEXT_VALUE_SET; mHandler.sendMessage(textValueSetMsg3); break; } } if (mOnViewTypeChangedListener != null) { mOnViewTypeChangedListener.onViewTypeChanged(this); } Message monthButtonSetMsg = mHandler.obtainMessage(); monthButtonSetMsg.what = MESSAGE_CALENDAR_HEADER_MONTH_BUTTON_SET; mHandler.sendMessage(monthButtonSetMsg); break; case VIEW_TYPE_CALENDAR: boolean typeChanged = false; if (mCurrentViewType != VIEW_TYPE_SPINNER) { mCalendarPagerAdapter.notifyDataSetChanged(); mViewAnimator.setDisplayedChild(1); mPickerView.setEnabled(false); mPickerView.setVisibility(View.GONE); mCalendarViewLayout.setEnabled(true); mCalendarViewLayout.setVisibility(View.VISIBLE); mCurrentViewType = VIEW_TYPE_SPINNER; Message textValueSetMsg = mHandler.obtainMessage(); textValueSetMsg.what = MESSAGE_CALENDAR_HEADER_TEXT_VALUE_SET; mHandler.sendMessage(textValueSetMsg); typeChanged = true; } if (mOnViewTypeChangedListener != null && typeChanged) { mOnViewTypeChangedListener.onViewTypeChanged(this); } Message monthButtonSetMsg2 = mHandler.obtainMessage(); monthButtonSetMsg2.what = MESSAGE_CALENDAR_HEADER_MONTH_BUTTON_SET; mHandler.sendMessage(monthButtonSetMsg2); break; } }
@Override public void onClick(View v) { <DeepExtract> switch(VIEW_TYPE_SPINNER) { case VIEW_TYPE_SPINNER: if (mCurrentViewType != VIEW_TYPE_SPINNER) { switch(mMode) { case DATE_MODE_START: if (mIsLunar) { mDatePickerSpinner.updateDate(mLunarStartYear, mLunarStartMonth, mLunarStartDay); } else { mDatePickerSpinner.updateDate(mStartDate.get(Calendar.YEAR), mStartDate.get(Calendar.MONTH), mStartDate.get(Calendar.DAY_OF_MONTH)); } mViewAnimator.setDisplayedChild(0); mPickerView.setEnabled(true); mPickerView.setVisibility(View.VISIBLE); mCalendarViewLayout.setVisibility(View.GONE); mCurrentViewType = VIEW_TYPE_SPINNER; Message textValueSetMsg = mHandler.obtainMessage(); textValueSetMsg.what = MESSAGE_CALENDAR_HEADER_TEXT_VALUE_SET; mHandler.sendMessage(textValueSetMsg); break; case DATE_MODE_END: if (mIsLunar) { mDatePickerSpinner.updateDate(mLunarEndYear, mLunarEndMonth, mLunarEndDay); } else { mDatePickerSpinner.updateDate(mEndDate.get(Calendar.YEAR), mEndDate.get(Calendar.MONTH), mEndDate.get(Calendar.DAY_OF_MONTH)); } mViewAnimator.setDisplayedChild(0); mPickerView.setEnabled(true); mPickerView.setVisibility(View.VISIBLE); mCalendarViewLayout.setVisibility(View.GONE); mCurrentViewType = VIEW_TYPE_SPINNER; Message textValueSetMsg2 = mHandler.obtainMessage(); textValueSetMsg2.what = MESSAGE_CALENDAR_HEADER_TEXT_VALUE_SET; mHandler.sendMessage(textValueSetMsg2); break; default: if (mIsLunar) { mDatePickerSpinner.updateDate(mLunarCurrentYear, mLunarCurrentMonth, mLunarCurrentDay); } else { mDatePickerSpinner.updateDate(mCurrentDate.get(Calendar.YEAR), mCurrentDate.get(Calendar.MONTH), mCurrentDate.get(Calendar.DAY_OF_MONTH)); } mViewAnimator.setDisplayedChild(0); mPickerView.setEnabled(true); mPickerView.setVisibility(View.VISIBLE); mCalendarViewLayout.setVisibility(View.GONE); mCurrentViewType = VIEW_TYPE_SPINNER; Message textValueSetMsg3 = mHandler.obtainMessage(); textValueSetMsg3.what = MESSAGE_CALENDAR_HEADER_TEXT_VALUE_SET; mHandler.sendMessage(textValueSetMsg3); break; } } if (mOnViewTypeChangedListener != null) { mOnViewTypeChangedListener.onViewTypeChanged(this); } Message monthButtonSetMsg = mHandler.obtainMessage(); monthButtonSetMsg.what = MESSAGE_CALENDAR_HEADER_MONTH_BUTTON_SET; mHandler.sendMessage(monthButtonSetMsg); break; case VIEW_TYPE_CALENDAR: boolean typeChanged = false; if (mCurrentViewType != VIEW_TYPE_SPINNER) { mCalendarPagerAdapter.notifyDataSetChanged(); mViewAnimator.setDisplayedChild(1); mPickerView.setEnabled(false); mPickerView.setVisibility(View.GONE); mCalendarViewLayout.setEnabled(true); mCalendarViewLayout.setVisibility(View.VISIBLE); mCurrentViewType = VIEW_TYPE_SPINNER; Message textValueSetMsg = mHandler.obtainMessage(); textValueSetMsg.what = MESSAGE_CALENDAR_HEADER_TEXT_VALUE_SET; mHandler.sendMessage(textValueSetMsg); typeChanged = true; } if (mOnViewTypeChangedListener != null && typeChanged) { mOnViewTypeChangedListener.onViewTypeChanged(this); } Message monthButtonSetMsg2 = mHandler.obtainMessage(); monthButtonSetMsg2.what = MESSAGE_CALENDAR_HEADER_MONTH_BUTTON_SET; mHandler.sendMessage(monthButtonSetMsg2); break; } </DeepExtract> }
SamsungOneUi
positive
439,151
public void isTelegramEnabled(Boolean enabled) { Editor editor = settings.edit(); editor.putString("TELEGRAM_ENABLED", enabled); editor.commit(); }
public void isTelegramEnabled(Boolean enabled) { <DeepExtract> Editor editor = settings.edit(); editor.putString("TELEGRAM_ENABLED", enabled); editor.commit(); </DeepExtract> }
curiosus
positive
439,152
@Override public Object getProxy() { final AopProxy aopProxy = this.createAopProxy(); if (this.ctorArguments != null && this.ctorArgumentTypes != null) { try { final Method ctorArgSetter = aopProxy.getClass().getMethod("setConstructorArguments", Object[].class, Class[].class); ctorArgSetter.invoke(aopProxy, this.ctorArguments, this.ctorArgumentTypes); } catch (final NoSuchMethodException nsme) { LOGGER.info("Proxy does not provide setConstructorArguments method - likely Cglib is not available", nsme); } catch (final InvocationTargetException ite) { LOGGER.error("Error setting constructor arguments", ite); } catch (final IllegalAccessException iae) { LOGGER.error("Error setting constructor arguments", iae); } } final Object proxy = aopProxy.getProxy(); return proxy; }
@Override public Object getProxy() { final AopProxy aopProxy = this.createAopProxy(); <DeepExtract> if (this.ctorArguments != null && this.ctorArgumentTypes != null) { try { final Method ctorArgSetter = aopProxy.getClass().getMethod("setConstructorArguments", Object[].class, Class[].class); ctorArgSetter.invoke(aopProxy, this.ctorArguments, this.ctorArgumentTypes); } catch (final NoSuchMethodException nsme) { LOGGER.info("Proxy does not provide setConstructorArguments method - likely Cglib is not available", nsme); } catch (final InvocationTargetException ite) { LOGGER.error("Error setting constructor arguments", ite); } catch (final IllegalAccessException iae) { LOGGER.error("Error setting constructor arguments", iae); } } </DeepExtract> final Object proxy = aopProxy.getProxy(); return proxy; }
alfresco-enhanced-script-environment
positive
439,153
@Test void onlyWriteUrl() { Mockito.doAnswer(invocation -> { final PgConnection connection = invocation.getArgument(0, PgConnection.class); return "host-1".equals(connection.getHost().getName()); }).when(primaryHostDeterminer).isPrimary(any(PgConnection.class)); final HighAvailabilityPgConnection haPgConnection = connectionFactory.ofUrl("jdbc:postgresql://host-1:6432,host-2:6432/db_name?ssl=true&sslmode=require", "postgres", "postgres"); assertThat(haPgConnection).isNotNull().satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()).hasSize(2).isUnmodifiable()); assertThat(haPgConnection.getConnectionToPrimary()).isNotNull().satisfies(c -> verify(primaryHostDeterminer).isPrimary(c)); for (final PgConnection connection : haPgConnection.getConnectionsToAllHostsInCluster()) { if (primaryHostDeterminer.isPrimary(connection)) { assertThat(connection).isSameAs(haPgConnection.getConnectionToPrimary()); } } }
@Test void onlyWriteUrl() { Mockito.doAnswer(invocation -> { final PgConnection connection = invocation.getArgument(0, PgConnection.class); return "host-1".equals(connection.getHost().getName()); }).when(primaryHostDeterminer).isPrimary(any(PgConnection.class)); final HighAvailabilityPgConnection haPgConnection = connectionFactory.ofUrl("jdbc:postgresql://host-1:6432,host-2:6432/db_name?ssl=true&sslmode=require", "postgres", "postgres"); assertThat(haPgConnection).isNotNull().satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()).hasSize(2).isUnmodifiable()); <DeepExtract> assertThat(haPgConnection.getConnectionToPrimary()).isNotNull().satisfies(c -> verify(primaryHostDeterminer).isPrimary(c)); for (final PgConnection connection : haPgConnection.getConnectionsToAllHostsInCluster()) { if (primaryHostDeterminer.isPrimary(connection)) { assertThat(connection).isSameAs(haPgConnection.getConnectionToPrimary()); } } </DeepExtract> }
pg-index-health
positive
439,154
ContentValues toContentValues() { ContentValues contentValues = new ContentValues(); contentValues.put(JobStorage.COLUMN_ID, mId); contentValues.put(JobStorage.COLUMN_TAG, mTag); contentValues.put(JobStorage.COLUMN_START_MS, mStartMs); contentValues.put(JobStorage.COLUMN_END_MS, mEndMs); contentValues.put(JobStorage.COLUMN_BACKOFF_MS, mBackoffMs); contentValues.put(JobStorage.COLUMN_BACKOFF_POLICY, mBackoffPolicy.toString()); contentValues.put(JobStorage.COLUMN_INTERVAL_MS, mIntervalMs); contentValues.put(JobStorage.COLUMN_FLEX_MS, mFlexMs); contentValues.put(JobStorage.COLUMN_REQUIREMENTS_ENFORCED, mRequirementsEnforced); contentValues.put(JobStorage.COLUMN_REQUIRES_CHARGING, mRequiresCharging); contentValues.put(JobStorage.COLUMN_REQUIRES_DEVICE_IDLE, mRequiresDeviceIdle); contentValues.put(JobStorage.COLUMN_REQUIRES_BATTERY_NOT_LOW, mRequiresBatteryNotLow); contentValues.put(JobStorage.COLUMN_REQUIRES_STORAGE_NOT_LOW, mRequiresStorageNotLow); contentValues.put(JobStorage.COLUMN_EXACT, mExact); contentValues.put(JobStorage.COLUMN_NETWORK_TYPE, mNetworkType.toString()); if (mExtras != null) { contentValues.put(JobStorage.COLUMN_EXTRAS, mExtras.saveToXml()); } else if (!TextUtils.isEmpty(mExtrasXml)) { contentValues.put(JobStorage.COLUMN_EXTRAS, mExtrasXml); } contentValues.put(JobStorage.COLUMN_TRANSIENT, mTransient); contentValues.put(JobStorage.COLUMN_NUM_FAILURES, mFailureCount); contentValues.put(JobStorage.COLUMN_SCHEDULED_AT, mScheduledAt); contentValues.put(JobStorage.COLUMN_STARTED, mStarted); contentValues.put(JobStorage.COLUMN_FLEX_SUPPORT, mFlexSupport); contentValues.put(JobStorage.COLUMN_LAST_RUN, mLastRun); return contentValues; }
ContentValues toContentValues() { ContentValues contentValues = new ContentValues(); <DeepExtract> contentValues.put(JobStorage.COLUMN_ID, mId); contentValues.put(JobStorage.COLUMN_TAG, mTag); contentValues.put(JobStorage.COLUMN_START_MS, mStartMs); contentValues.put(JobStorage.COLUMN_END_MS, mEndMs); contentValues.put(JobStorage.COLUMN_BACKOFF_MS, mBackoffMs); contentValues.put(JobStorage.COLUMN_BACKOFF_POLICY, mBackoffPolicy.toString()); contentValues.put(JobStorage.COLUMN_INTERVAL_MS, mIntervalMs); contentValues.put(JobStorage.COLUMN_FLEX_MS, mFlexMs); contentValues.put(JobStorage.COLUMN_REQUIREMENTS_ENFORCED, mRequirementsEnforced); contentValues.put(JobStorage.COLUMN_REQUIRES_CHARGING, mRequiresCharging); contentValues.put(JobStorage.COLUMN_REQUIRES_DEVICE_IDLE, mRequiresDeviceIdle); contentValues.put(JobStorage.COLUMN_REQUIRES_BATTERY_NOT_LOW, mRequiresBatteryNotLow); contentValues.put(JobStorage.COLUMN_REQUIRES_STORAGE_NOT_LOW, mRequiresStorageNotLow); contentValues.put(JobStorage.COLUMN_EXACT, mExact); contentValues.put(JobStorage.COLUMN_NETWORK_TYPE, mNetworkType.toString()); if (mExtras != null) { contentValues.put(JobStorage.COLUMN_EXTRAS, mExtras.saveToXml()); } else if (!TextUtils.isEmpty(mExtrasXml)) { contentValues.put(JobStorage.COLUMN_EXTRAS, mExtrasXml); } contentValues.put(JobStorage.COLUMN_TRANSIENT, mTransient); </DeepExtract> contentValues.put(JobStorage.COLUMN_NUM_FAILURES, mFailureCount); contentValues.put(JobStorage.COLUMN_SCHEDULED_AT, mScheduledAt); contentValues.put(JobStorage.COLUMN_STARTED, mStarted); contentValues.put(JobStorage.COLUMN_FLEX_SUPPORT, mFlexSupport); contentValues.put(JobStorage.COLUMN_LAST_RUN, mLastRun); return contentValues; }
android-job
positive
439,155
public static void configureObjectMapperForPosting(ObjectMapper om, Class clazz) { om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); om.registerModule(new JackanModule()); om.setSerializationInclusion(Include.NON_NULL); om.addMixInAnnotations(CkanResource.class, CkanResourceForPosting.class); om.addMixInAnnotations(CkanDataset.class, CkanDatasetForPosting.class); om.addMixInAnnotations(CkanOrganization.class, CkanGroupOrgForPosting.class); if (CkanDatasetBase.class.isAssignableFrom(clazz)) { om.addMixInAnnotations(CkanGroup.class, GroupForDatasetPosting.class); } else { om.addMixInAnnotations(CkanGroup.class, CkanGroupOrgForPosting.class); } om.addMixInAnnotations(CkanUser.class, CkanUserForPosting.class); om.addMixInAnnotations(CkanTag.class, CkanTagForPosting.class); }
public static void configureObjectMapperForPosting(ObjectMapper om, Class clazz) { <DeepExtract> om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); om.registerModule(new JackanModule()); </DeepExtract> om.setSerializationInclusion(Include.NON_NULL); om.addMixInAnnotations(CkanResource.class, CkanResourceForPosting.class); om.addMixInAnnotations(CkanDataset.class, CkanDatasetForPosting.class); om.addMixInAnnotations(CkanOrganization.class, CkanGroupOrgForPosting.class); if (CkanDatasetBase.class.isAssignableFrom(clazz)) { om.addMixInAnnotations(CkanGroup.class, GroupForDatasetPosting.class); } else { om.addMixInAnnotations(CkanGroup.class, CkanGroupOrgForPosting.class); } om.addMixInAnnotations(CkanUser.class, CkanUserForPosting.class); om.addMixInAnnotations(CkanTag.class, CkanTagForPosting.class); }
jackan
positive
439,156
public Builder addWordsBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); if (!((bitField0_ & 0x00000001) == 0x00000001)) { words_ = new com.google.protobuf.LazyStringArrayList(words_); bitField0_ |= 0x00000001; } words_.add(value); onChanged(); return this; }
public Builder addWordsBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); <DeepExtract> if (!((bitField0_ & 0x00000001) == 0x00000001)) { words_ = new com.google.protobuf.LazyStringArrayList(words_); bitField0_ |= 0x00000001; } </DeepExtract> words_.add(value); onChanged(); return this; }
cellery-security
positive
439,158
@Override public void onCreate() { super.onCreate(); mApp = this; if (BuildConfig.DEBUG) { LogUtils.e(TAG, "Device Info: model=" + Build.MODEL); LogUtils.e(TAG, "Device Info: brand=" + Build.BRAND); LogUtils.e(TAG, "Device Info: device=" + Build.DEVICE); LogUtils.e(TAG, "Device Info: board=" + Build.BOARD); LogUtils.e(TAG, "Device Info: product=" + Build.PRODUCT); LogUtils.e(TAG, "Device Info: manufacturer=" + Build.MANUFACTURER); LogUtils.e(TAG, "Device Info: fingerprint=" + Build.FINGERPRINT); LogUtils.enable(); } else { LogUtils.disable(); } Fresco.initialize(this); mRequestQueue = Volley.newRequestQueue(RanDianApplication.getApp()); mGson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create(); mAccountController = new AccountController(getApp()); }
@Override public void onCreate() { super.onCreate(); mApp = this; if (BuildConfig.DEBUG) { LogUtils.e(TAG, "Device Info: model=" + Build.MODEL); LogUtils.e(TAG, "Device Info: brand=" + Build.BRAND); LogUtils.e(TAG, "Device Info: device=" + Build.DEVICE); LogUtils.e(TAG, "Device Info: board=" + Build.BOARD); LogUtils.e(TAG, "Device Info: product=" + Build.PRODUCT); LogUtils.e(TAG, "Device Info: manufacturer=" + Build.MANUFACTURER); LogUtils.e(TAG, "Device Info: fingerprint=" + Build.FINGERPRINT); LogUtils.enable(); } else { LogUtils.disable(); } Fresco.initialize(this); mRequestQueue = Volley.newRequestQueue(RanDianApplication.getApp()); mGson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create(); <DeepExtract> mAccountController = new AccountController(getApp()); </DeepExtract> }
AppKit
positive
439,161
public static void main(String[] args) { if (args.length != 2) { LOG.error("Usage: MovingAverageCalculationServiceDemo <url> <accesstoken>"); System.exit(1); } final String url = args[0]; final String accessToken = args[1]; HistoricMarketDataProvider<String> historicMarketDataProvider = new OandaHistoricMarketDataProvider(url, accessToken); MovingAverageCalculationService<String> movingAverageCalcService = new MovingAverageCalculationService<String>(historicMarketDataProvider); TradeableInstrument<String> eurnzd = new TradeableInstrument<String>("EUR_NZD"); final int countIntervals = 30; ImmutablePair<Double, Double> eurnzdSmaAndWma = movingAverageCalcService.calculateSMAandWMAasPair(eurnzd, countIntervals, CandleStickGranularity.H1); LOG.info(String.format("SMA=%2.5f,WMA=%2.5f for instrument=%s,granularity=%s for the last %d intervals", eurnzdSmaAndWma.left, eurnzdSmaAndWma.right, eurnzd.getInstrument(), CandleStickGranularity.H1, countIntervals)); DateTime from = new DateTime(1444003200000L); DateTime to = new DateTime(1453075200000L); TradeableInstrument<String> gbpchf = new TradeableInstrument<String>("GBP_CHF"); ImmutablePair<Double, Double> gbpchfSmaAndWma = movingAverageCalcService.calculateSMAandWMAasPair(gbpchf, from, to, CandleStickGranularity.W); LOG.info(String.format("SMA=%2.5f,WMA=%2.5f for instrument=%s,granularity=%s from %s to %s", gbpchfSmaAndWma.left, gbpchfSmaAndWma.right, gbpchf.getInstrument(), CandleStickGranularity.W, from, to)); }
public static void main(String[] args) { <DeepExtract> if (args.length != 2) { LOG.error("Usage: MovingAverageCalculationServiceDemo <url> <accesstoken>"); System.exit(1); } </DeepExtract> final String url = args[0]; final String accessToken = args[1]; HistoricMarketDataProvider<String> historicMarketDataProvider = new OandaHistoricMarketDataProvider(url, accessToken); MovingAverageCalculationService<String> movingAverageCalcService = new MovingAverageCalculationService<String>(historicMarketDataProvider); TradeableInstrument<String> eurnzd = new TradeableInstrument<String>("EUR_NZD"); final int countIntervals = 30; ImmutablePair<Double, Double> eurnzdSmaAndWma = movingAverageCalcService.calculateSMAandWMAasPair(eurnzd, countIntervals, CandleStickGranularity.H1); LOG.info(String.format("SMA=%2.5f,WMA=%2.5f for instrument=%s,granularity=%s for the last %d intervals", eurnzdSmaAndWma.left, eurnzdSmaAndWma.right, eurnzd.getInstrument(), CandleStickGranularity.H1, countIntervals)); DateTime from = new DateTime(1444003200000L); DateTime to = new DateTime(1453075200000L); TradeableInstrument<String> gbpchf = new TradeableInstrument<String>("GBP_CHF"); ImmutablePair<Double, Double> gbpchfSmaAndWma = movingAverageCalcService.calculateSMAandWMAasPair(gbpchf, from, to, CandleStickGranularity.W); LOG.info(String.format("SMA=%2.5f,WMA=%2.5f for instrument=%s,granularity=%s from %s to %s", gbpchfSmaAndWma.left, gbpchfSmaAndWma.right, gbpchf.getInstrument(), CandleStickGranularity.W, from, to)); }
book-code
positive
439,162
public void disconnect() { if (mConnectionState == STATE_DISCONNECTED) return; mConnectionState = STATE_DISCONNECTED; if (STATE_DISCONNECTED == TapchatService.STATE_DISCONNECTED) { synchronized (mConnections) { for (Connection connection : mConnections.values()) { connection.serviceDisconnected(); } } } mBus.post(new ServiceStateChangedEvent(this)); mConnections.clear(); if (mHeartbeatTimer != null) { mHeartbeatTimer.cancel(); mHeartbeatTimer = null; } if (mBouncerConnection != null) { mBouncerConnection.stop(); mBouncerConnection = null; } }
public void disconnect() { if (mConnectionState == STATE_DISCONNECTED) return; <DeepExtract> mConnectionState = STATE_DISCONNECTED; if (STATE_DISCONNECTED == TapchatService.STATE_DISCONNECTED) { synchronized (mConnections) { for (Connection connection : mConnections.values()) { connection.serviceDisconnected(); } } } mBus.post(new ServiceStateChangedEvent(this)); </DeepExtract> mConnections.clear(); if (mHeartbeatTimer != null) { mHeartbeatTimer.cancel(); mHeartbeatTimer = null; } if (mBouncerConnection != null) { mBouncerConnection.stop(); mBouncerConnection = null; } }
tapchat-android
positive
439,165
public void setWithParamString(String qs, String sep) { String[] qa = qs.split(sep); for (int i = 0; i < qa.length; i++) { String[] nv = qa[i].split("="); try { String name = URLDecoder.decode(nv[0], "UTF-8"); String val = URLDecoder.decode(nv[1], "UTF-8"); if (params.containsKey(name)) { Parameter p = (Parameter) this.get(name); if (p.getType() == 'i') { continue; } p.setValueFromString(val); continue; } newParameter(name, null, val, 'r'); } catch (UnsupportedEncodingException e) { } } options = (OptionsSet) getValue("mo"); }
public void setWithParamString(String qs, String sep) { String[] qa = qs.split(sep); for (int i = 0; i < qa.length; i++) { String[] nv = qa[i].split("="); try { String name = URLDecoder.decode(nv[0], "UTF-8"); String val = URLDecoder.decode(nv[1], "UTF-8"); if (params.containsKey(name)) { Parameter p = (Parameter) this.get(name); if (p.getType() == 'i') { continue; } p.setValueFromString(val); continue; } newParameter(name, null, val, 'r'); } catch (UnsupportedEncodingException e) { } } <DeepExtract> options = (OptionsSet) getValue("mo"); </DeepExtract> }
digilib
positive
439,166
public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(EnvConfig.class); Properties properties = new Properties(); properties.put("spring.profiles.active", "product"); PropertiesPropertySource propertySource = new PropertiesPropertySource("my", properties); ctx.getEnvironment().getPropertySources().addFirst(propertySource); ctx.refresh(); Map<String, String> beanMap = ctx.getBeansOfType(String.class); beanMap.forEach((name, bean) -> System.out.println(name + ":" + bean)); }
public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(EnvConfig.class); <DeepExtract> Properties properties = new Properties(); properties.put("spring.profiles.active", "product"); PropertiesPropertySource propertySource = new PropertiesPropertySource("my", properties); ctx.getEnvironment().getPropertySources().addFirst(propertySource); </DeepExtract> ctx.refresh(); Map<String, String> beanMap = ctx.getBeansOfType(String.class); beanMap.forEach((name, bean) -> System.out.println(name + ":" + bean)); }
enumdemo
positive
439,169
public static void editedPost(Post post, User user) { JsonObject object = new JsonObject(); object.addProperty("type", "postEdited"); object.addProperty("post", post.getExternalId()); object.add("postName", post.getName().json()); object.addProperty("postSlug", post.getSlug()); object.addProperty("user", user.getUsername()); object.addProperty("userName", user.getProfile().getDisplayName()); SiteActivity activity = new SiteActivity(post.getSite()); activity.setEventDate(new DateTime()); activity.setContent(object); post.getSite().pushActivity(activity); }
public static void editedPost(Post post, User user) { JsonObject object = new JsonObject(); object.addProperty("type", "postEdited"); object.addProperty("post", post.getExternalId()); object.add("postName", post.getName().json()); object.addProperty("postSlug", post.getSlug()); object.addProperty("user", user.getUsername()); object.addProperty("userName", user.getProfile().getDisplayName()); <DeepExtract> SiteActivity activity = new SiteActivity(post.getSite()); activity.setEventDate(new DateTime()); activity.setContent(object); post.getSite().pushActivity(activity); </DeepExtract> }
fenixedu-cms
positive
439,170
@Test public void testLsHttpNoPassword() throws Exception { File authData = new File(testFileLocation + "httpNoUsernamePassword.txt"); if (!authData.exists()) return; Scanner scanner = new Scanner(authData); String ignoreURL = scanner.next(); String username = scanner.next(); String password = scanner.next(); UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password); TransportCommand command = Git.lsRemoteRepository().setRemote(GITHUB_REMOTE_URL); RepoHelper helper = new RepoHelper(""); helper.wrapAuthentication(command, credentials); command.call(); }
@Test public void testLsHttpNoPassword() throws Exception { <DeepExtract> File authData = new File(testFileLocation + "httpNoUsernamePassword.txt"); if (!authData.exists()) return; Scanner scanner = new Scanner(authData); String ignoreURL = scanner.next(); String username = scanner.next(); String password = scanner.next(); UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password); TransportCommand command = Git.lsRemoteRepository().setRemote(GITHUB_REMOTE_URL); RepoHelper helper = new RepoHelper(""); helper.wrapAuthentication(command, credentials); command.call(); </DeepExtract> }
Elegit
positive
439,171
public Criteria andSubtotalLessThanOrEqualTo(Double value) { if (value == null) { throw new RuntimeException("Value for " + "subtotal" + " cannot be null"); } criteria.add(new Criterion("subtotal <=", value)); return (Criteria) this; }
public Criteria andSubtotalLessThanOrEqualTo(Double value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "subtotal" + " cannot be null"); } criteria.add(new Criterion("subtotal <=", value)); </DeepExtract> return (Criteria) this; }
ssmxiaomi
positive
439,172
@Nullable @Override default String getName() { return buildParameter.getBuildUrl(); }
@Nullable @Override default String getName() { <DeepExtract> return buildParameter.getBuildUrl(); </DeepExtract> }
jenkins-control-plugin
positive
439,174
@Override public void run() { filterItem.setVersions(versionNames.toArray(new String[versionNames.size()])); versionCombo.setItems(filterItem.getVersions()); versionCombo.select(0); versionCombo.setVisible(true); filterItem.setSelectedVersion(versionCombo.getText()); for (PackageFilterChangedListener listener : listeners) { listener.filterChanged(filterItem); } }
@Override public void run() { filterItem.setVersions(versionNames.toArray(new String[versionNames.size()])); <DeepExtract> versionCombo.setItems(filterItem.getVersions()); versionCombo.select(0); versionCombo.setVisible(true); filterItem.setSelectedVersion(versionCombo.getText()); for (PackageFilterChangedListener listener : listeners) { listener.filterChanged(filterItem); } </DeepExtract> }
Composer-Eclipse-Plugin
positive
439,175
@Override public double get() { ensureEnabled(); ultrasonic.ping(); while (!ultrasonic.isRangeValid()) { Timer.delay(0.02); } return ultrasonic.getRangeInches(); }
@Override public double get() { ensureEnabled(); <DeepExtract> ultrasonic.ping(); while (!ultrasonic.isRangeValid()) { Timer.delay(0.02); } </DeepExtract> return ultrasonic.getRangeInches(); }
atalibj
positive
439,177
public void addBlock(int xCoord, int yCoord, int zCoord) { if (corner1.equals(new Coord(0, 0, 0)) && corner2.equals(new Coord(0, 0, 0))) { corner1 = new Coord(xCoord, yCoord, zCoord); corner2 = new Coord(xCoord, yCoord, zCoord); } List<Coord> iter = Coord.between(new Coord(corner1.x, corner1.y, corner2.z + 1), new Coord(corner2.x, corner2.y, corner2.z + 1)); if (tryExpandSide(iter)) corner2.z++; iter = Coord.between(new Coord(corner1.x, corner1.y, corner1.z - 1), new Coord(corner2.x, corner2.y, corner1.z - 1)); if (tryExpandSide(iter)) corner1.z--; List<Coord> iter = Coord.between(new Coord(corner1.x, corner2.y + 1, corner1.z), new Coord(corner2.x, corner2.y + 1, corner2.z)); if (tryExpandSide(iter)) corner2.y++; iter = Coord.between(new Coord(corner1.x, corner1.y - 1, corner1.z), new Coord(corner2.x, corner1.y - 1, corner2.z)); if (tryExpandSide(iter)) corner1.y--; List<Coord> iter = Coord.between(new Coord(corner2.x + 1, corner1.y, corner1.z), new Coord(corner2.x + 1, corner2.y, corner2.z)); if (tryExpandSide(iter)) corner2.x++; iter = Coord.between(new Coord(corner1.x - 1, corner1.y, corner1.z), new Coord(corner1.x - 1, corner2.y, corner2.z)); if (tryExpandSide(iter)) corner1.x--; }
public void addBlock(int xCoord, int yCoord, int zCoord) { if (corner1.equals(new Coord(0, 0, 0)) && corner2.equals(new Coord(0, 0, 0))) { corner1 = new Coord(xCoord, yCoord, zCoord); corner2 = new Coord(xCoord, yCoord, zCoord); } List<Coord> iter = Coord.between(new Coord(corner1.x, corner1.y, corner2.z + 1), new Coord(corner2.x, corner2.y, corner2.z + 1)); if (tryExpandSide(iter)) corner2.z++; iter = Coord.between(new Coord(corner1.x, corner1.y, corner1.z - 1), new Coord(corner2.x, corner2.y, corner1.z - 1)); if (tryExpandSide(iter)) corner1.z--; List<Coord> iter = Coord.between(new Coord(corner1.x, corner2.y + 1, corner1.z), new Coord(corner2.x, corner2.y + 1, corner2.z)); if (tryExpandSide(iter)) corner2.y++; iter = Coord.between(new Coord(corner1.x, corner1.y - 1, corner1.z), new Coord(corner2.x, corner1.y - 1, corner2.z)); if (tryExpandSide(iter)) corner1.y--; <DeepExtract> List<Coord> iter = Coord.between(new Coord(corner2.x + 1, corner1.y, corner1.z), new Coord(corner2.x + 1, corner2.y, corner2.z)); if (tryExpandSide(iter)) corner2.x++; iter = Coord.between(new Coord(corner1.x - 1, corner1.y, corner1.z), new Coord(corner1.x - 1, corner2.y, corner2.z)); if (tryExpandSide(iter)) corner1.x--; </DeepExtract> }
Metallurgy3
positive
439,178
private void enterSuperStepBarrier(String barrierName, int superStep) { LOG.debug("p{} creating barrier {}", getPartitionID(), barrierName + Integer.toString(superStep)); Barrier barrier = null; synchronized (leaderGroupMembers) { LOG.debug("{} will wait for {} partitions", barrierName + Integer.toString(superStep), leaderGroupMembers.size()); barrier = new OrbFastBarrier(getOrbConf(), jobInProgressPath + "/" + barrierName + Integer.toString(superStep), leaderGroupMembers.size(), Integer.toString(getPartitionID()), zk); } try { barrier.enter(); LOG.debug("p{} entered {}", getPartitionID(), barrierName + Integer.toString(superStep)); } catch (OrbZKFailure e) { LOG.error("p{} failed to complete barrier {}: " + e.getMessage(), getPartitionID(), barrierName + Integer.toString(superStep)); e.printStackTrace(); } }
private void enterSuperStepBarrier(String barrierName, int superStep) { <DeepExtract> LOG.debug("p{} creating barrier {}", getPartitionID(), barrierName + Integer.toString(superStep)); Barrier barrier = null; synchronized (leaderGroupMembers) { LOG.debug("{} will wait for {} partitions", barrierName + Integer.toString(superStep), leaderGroupMembers.size()); barrier = new OrbFastBarrier(getOrbConf(), jobInProgressPath + "/" + barrierName + Integer.toString(superStep), leaderGroupMembers.size(), Integer.toString(getPartitionID()), zk); } try { barrier.enter(); LOG.debug("p{} entered {}", getPartitionID(), barrierName + Integer.toString(superStep)); } catch (OrbZKFailure e) { LOG.error("p{} failed to complete barrier {}: " + e.getMessage(), getPartitionID(), barrierName + Integer.toString(superStep)); e.printStackTrace(); } </DeepExtract> }
goldenorb
positive
439,183
public static void exportAllDatabases(Context ctx) { if (!Util.checkExternalPermission(ctx)) { Util.myNotify(ctx, ctx.getResources().getString(R.string.warning), ctx.getResources().getString(R.string.permission_external_storage), 81234, new Intent(ctx, PermissionsActivity.class)); return; } File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File data = Environment.getDataDirectory(); FileChannel source = null; FileChannel destination = null; String currentDBPath = "/data/" + ctx.getPackageName() + "/databases/" + ScrobblesDatabase.DATABASE_NAME; String backupDBPath = "simple.last.fm.scrobbler.db"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); try { source = new FileInputStream(currentDB).getChannel(); destination = new FileOutputStream(backupDB).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); Util.myNotify(ctx, "Database Exported", backupDB.toString(), 57109, new Intent(ctx, SettingsActivity.class)); } catch (IOException e) { e.printStackTrace(); } }
public static void exportAllDatabases(Context ctx) { <DeepExtract> if (!Util.checkExternalPermission(ctx)) { Util.myNotify(ctx, ctx.getResources().getString(R.string.warning), ctx.getResources().getString(R.string.permission_external_storage), 81234, new Intent(ctx, PermissionsActivity.class)); return; } File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File data = Environment.getDataDirectory(); FileChannel source = null; FileChannel destination = null; String currentDBPath = "/data/" + ctx.getPackageName() + "/databases/" + ScrobblesDatabase.DATABASE_NAME; String backupDBPath = "simple.last.fm.scrobbler.db"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); try { source = new FileInputStream(currentDB).getChannel(); destination = new FileOutputStream(backupDB).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); Util.myNotify(ctx, "Database Exported", backupDB.toString(), 57109, new Intent(ctx, SettingsActivity.class)); } catch (IOException e) { e.printStackTrace(); } </DeepExtract> }
sls
positive
439,184
public void quickInitialization() { long start = System.nanoTime(); systemThreadGroup = newInstance(getSystemDictionary().getJavaLangThreadGroup(), "()V"); mainThreadGroup = newInstance(getSystemDictionary().getJavaLangThreadGroup(), "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V", systemThreadGroup, getString("main")); JavaUninitialized unit = new JavaUninitialized(getSystemDictionary().getJavaLangThread(), getSystemDictionary().getJavaLangThread().internalGetType().getInternalName()); unit.initializedValue().setMetadata("oop", ThreadOop.forCurrentThread()); unit.initializedValue().setField("priority", "I", JavaWrapper.createInteger(this, 5)); unit.initializedValue().setField("status", "I", JavaWrapper.createInteger(this, 1)); JavaWrapper instance = JavaWrapper.wrap(unit); ThreadOop.forCurrentThread().setThread(instance); ClassNode node = getSystemDictionary().getJavaLangThread().getClassNode(); initialize(getSystemDictionary().getJavaLangThread()); MethodNode init = ASMHelper.findMethod(node, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V"); if (init != null) { internalExecute(node, init, instance, new JavaWrapper[] { mainThreadGroup, getString("main") }, null); } else { throw new ExecutionException("Unknown ctor init " + "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V"); } return instance; long end = System.nanoTime(); System.out.println("Initialization of VM took " + TimeUnit.NANOSECONDS.toMillis(end - start) + "ms"); }
public void quickInitialization() { long start = System.nanoTime(); systemThreadGroup = newInstance(getSystemDictionary().getJavaLangThreadGroup(), "()V"); mainThreadGroup = newInstance(getSystemDictionary().getJavaLangThreadGroup(), "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V", systemThreadGroup, getString("main")); <DeepExtract> JavaUninitialized unit = new JavaUninitialized(getSystemDictionary().getJavaLangThread(), getSystemDictionary().getJavaLangThread().internalGetType().getInternalName()); unit.initializedValue().setMetadata("oop", ThreadOop.forCurrentThread()); unit.initializedValue().setField("priority", "I", JavaWrapper.createInteger(this, 5)); unit.initializedValue().setField("status", "I", JavaWrapper.createInteger(this, 1)); JavaWrapper instance = JavaWrapper.wrap(unit); ThreadOop.forCurrentThread().setThread(instance); ClassNode node = getSystemDictionary().getJavaLangThread().getClassNode(); initialize(getSystemDictionary().getJavaLangThread()); MethodNode init = ASMHelper.findMethod(node, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V"); if (init != null) { internalExecute(node, init, instance, new JavaWrapper[] { mainThreadGroup, getString("main") }, null); } else { throw new ExecutionException("Unknown ctor init " + "(Ljava/lang/ThreadGroup;Ljava/lang/String;)V"); } return instance; </DeepExtract> long end = System.nanoTime(); System.out.println("Initialization of VM took " + TimeUnit.NANOSECONDS.toMillis(end - start) + "ms"); }
javavm
positive
439,185
@Override public void resume() { mGetDrinkListInteractor.execute(new DrinkListSubscriber()); }
@Override public void resume() { <DeepExtract> mGetDrinkListInteractor.execute(new DrinkListSubscriber()); </DeepExtract> }
CleanFit
positive
439,186
public static String getJSON(String apiInterface, String method) throws WebApiException { String protocol = secure ? "https" : "http"; String url = String.format("%s://api.steampowered.com/%s/%s/v%04d/?", protocol, apiInterface, method, 1); if (null == null) { null = new HashMap<>(); } null.put("format", "json"); if (apiKey != null) { null.put("key", apiKey); } boolean first = true; for (Map.Entry<String, Object> param : null.entrySet()) { if (first) { first = false; } else { url += '&'; } url += String.format("%s=%s", param.getKey(), param.getValue()); } if (LOG.isInfoEnabled()) { String debugUrl = (apiKey == null) ? url : url.replace(apiKey, "SECRET"); LOG.info("Querying Steam Web API: " + debugUrl); } String data; try { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); Integer statusCode = response.getStatusLine().getStatusCode(); if (!statusCode.toString().startsWith("20")) { if (statusCode == 401) { throw new WebApiException(WebApiException.Cause.UNAUTHORIZED); } throw new WebApiException(WebApiException.Cause.HTTP_ERROR, statusCode, response.getStatusLine().getReasonPhrase()); } data = EntityUtils.toString(response.getEntity()); } catch (WebApiException e) { throw e; } catch (Exception e) { throw new WebApiException("Could not communicate with the Web API.", e); } return data; }
public static String getJSON(String apiInterface, String method) throws WebApiException { <DeepExtract> String protocol = secure ? "https" : "http"; String url = String.format("%s://api.steampowered.com/%s/%s/v%04d/?", protocol, apiInterface, method, 1); if (null == null) { null = new HashMap<>(); } null.put("format", "json"); if (apiKey != null) { null.put("key", apiKey); } boolean first = true; for (Map.Entry<String, Object> param : null.entrySet()) { if (first) { first = false; } else { url += '&'; } url += String.format("%s=%s", param.getKey(), param.getValue()); } if (LOG.isInfoEnabled()) { String debugUrl = (apiKey == null) ? url : url.replace(apiKey, "SECRET"); LOG.info("Querying Steam Web API: " + debugUrl); } String data; try { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); Integer statusCode = response.getStatusLine().getStatusCode(); if (!statusCode.toString().startsWith("20")) { if (statusCode == 401) { throw new WebApiException(WebApiException.Cause.UNAUTHORIZED); } throw new WebApiException(WebApiException.Cause.HTTP_ERROR, statusCode, response.getStatusLine().getReasonPhrase()); } data = EntityUtils.toString(response.getEntity()); } catch (WebApiException e) { throw e; } catch (Exception e) { throw new WebApiException("Could not communicate with the Web API.", e); } return data; </DeepExtract> }
steam-condenser-java
positive
439,187
@Override public void recordAuthToken(String userName, String clientId, GrantType type) { Map<String, String> tags = new HashMap<>(8); tags.put("user", userName); tags.put("client", clientId); tags.put("type", type.name()); log.info("TBD: please use time-based data base (such as openTSDB) to record event, event name=" + "auth.token"); }
@Override public void recordAuthToken(String userName, String clientId, GrantType type) { Map<String, String> tags = new HashMap<>(8); tags.put("user", userName); tags.put("client", clientId); tags.put("type", type.name()); <DeepExtract> log.info("TBD: please use time-based data base (such as openTSDB) to record event, event name=" + "auth.token"); </DeepExtract> }
simple-oauth2
positive
439,188
public static long deriveKeyLong(IPRF prf, byte[] seed, byte[] input) { byte[] key = prf.apply(seed, input); byte[] out = new byte[8]; System.arraycopy(key, 0, out, 0, out.length); for (int i = out.length; i < key.length; i++) { out[i - out.length] ^= key[i]; } ByteBuffer buffer = ByteBuffer.allocate(out.length); buffer.put(out); buffer.flip(); return buffer.getLong(); }
public static long deriveKeyLong(IPRF prf, byte[] seed, byte[] input) { byte[] key = prf.apply(seed, input); byte[] out = new byte[8]; System.arraycopy(key, 0, out, 0, out.length); for (int i = out.length; i < key.length; i++) { out[i - out.length] ^= key[i]; } <DeepExtract> ByteBuffer buffer = ByteBuffer.allocate(out.length); buffer.put(out); buffer.flip(); return buffer.getLong(); </DeepExtract> }
timecrypt
positive
439,189
@Test public void testDimensionsValidator() { int errors = 0; DimensionsValidator validator = new DimensionsValidator(100, 100, 1000, 1000); final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(assetFile.getAbsolutePath()), 1000, 500, false); try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; Assert.assertEquals(0, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, false); try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; Assert.assertEquals(0, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 1000, 1000, false); try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; Assert.assertEquals(0, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 50, 500, false); try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; Assert.assertEquals(1, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 50, 500, false); try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; Assert.assertEquals(2, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, false); try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; Assert.assertEquals(3, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 1500, 500, false); try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; Assert.assertEquals(4, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 500, 1500, false); try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; Assert.assertEquals(5, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 1500, 1500, false); try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; Assert.assertEquals(6, errors); }
@Test public void testDimensionsValidator() { int errors = 0; DimensionsValidator validator = new DimensionsValidator(100, 100, 1000, 1000); final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(assetFile.getAbsolutePath()), 1000, 500, false); <DeepExtract> try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; </DeepExtract> Assert.assertEquals(0, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, false); <DeepExtract> try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; </DeepExtract> Assert.assertEquals(0, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 1000, 1000, false); <DeepExtract> try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; </DeepExtract> Assert.assertEquals(0, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 50, 500, false); <DeepExtract> try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; </DeepExtract> Assert.assertEquals(1, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 50, 500, false); <DeepExtract> try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; </DeepExtract> Assert.assertEquals(2, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, false); <DeepExtract> try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; </DeepExtract> Assert.assertEquals(3, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 1500, 500, false); <DeepExtract> try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; </DeepExtract> Assert.assertEquals(4, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 500, 1500, false); <DeepExtract> try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; </DeepExtract> Assert.assertEquals(5, errors); bitmap = Bitmap.createScaledBitmap(bitmap, 1500, 1500, false); <DeepExtract> try { validator.execute(context, bitmap); } catch (ValidationException e) { errors = 1; } return 0; </DeepExtract> Assert.assertEquals(6, errors); }
cloudinary_android
positive
439,190
public void addSymlink(String symlinkName, int permissions, String symlinkDestination) throws ArchiverException { if ((logger != null) && logger.isDebugEnabled()) { logger.debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } }
public void addSymlink(String symlinkName, int permissions, String symlinkDestination) throws ArchiverException { <DeepExtract> if ((logger != null) && logger.isDebugEnabled()) { logger.debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } </DeepExtract> }
plexus-archiver
positive
439,191
public static String sendOpeningReceipt(Context context, final Attachment attachment) throws DigipostClientException, DigipostApiException, DigipostAuthenticationException { if (apiAccess == null) { apiAccess = new ApiAccess(); } return apiAccess.postput(context, ApiAccess.POST, attachment.getOpeningReceiptUri(), null); }
public static String sendOpeningReceipt(Context context, final Attachment attachment) throws DigipostClientException, DigipostApiException, DigipostAuthenticationException { <DeepExtract> if (apiAccess == null) { apiAccess = new ApiAccess(); } </DeepExtract> return apiAccess.postput(context, ApiAccess.POST, attachment.getOpeningReceiptUri(), null); }
android
positive
439,193
@Override protected void initView() { helper = SharedPrefHelper.getInstance(); mTitleBarTitle.setText("个人资料"); mTitleBarBack.setImageDrawable(getResources().getDrawable(R.mipmap.icon_back)); mBottomBarLeft.setVisibility(View.GONE); mBottomBarTv2.setText("编辑个人资料"); }
@Override protected void initView() { helper = SharedPrefHelper.getInstance(); <DeepExtract> mTitleBarTitle.setText("个人资料"); mTitleBarBack.setImageDrawable(getResources().getDrawable(R.mipmap.icon_back)); mBottomBarLeft.setVisibility(View.GONE); mBottomBarTv2.setText("编辑个人资料"); </DeepExtract> }
Android-IM
positive
439,194
public static BaseText s(Object text, String carpetStyle) { s(text).formatted(carpetStyle); return s(text); }
public static BaseText s(Object text, String carpetStyle) { <DeepExtract> s(text).formatted(carpetStyle); return s(text); </DeepExtract> }
Carpet-TIS-Addition
positive
439,195
@Test public void testFindByCargoId() { final TrackingId trackingId = new TrackingId("ABC123"); final Cargo cargo = cargoRepository.find(trackingId); assertThat(cargo).isNotNull(); assertThat(cargo.origin()).isEqualTo(HONGKONG); assertThat(cargo.routeSpecification().origin()).isEqualTo(HONGKONG); assertThat(cargo.routeSpecification().destination()).isEqualTo(HELSINKI); assertThat(cargo.delivery()).isNotNull(); final List<HandlingEvent> events = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime(); assertThat(events).hasSize(3); HandlingEvent firstEvent = events.get(0); assertThat(firstEvent.type()).isEqualTo(RECEIVE); assertThat(firstEvent.location()).isEqualTo(HONGKONG); assertThat(firstEvent.completionTime()).isEqualTo(toDate("2009-03-01")); assertThat(firstEvent.registrationTime()).isEqualToIgnoringSeconds(new Date()); assertThat(firstEvent.voyage().voyageNumber()).isEqualTo(Voyage.NONE.voyageNumber()); assertThat(firstEvent.cargo()).isEqualTo(cargo); HandlingEvent secondEvent = events.get(1); assertThat(secondEvent.type()).isEqualTo(LOAD); assertThat(secondEvent.location()).isEqualTo(HONGKONG); assertThat(secondEvent.completionTime()).isEqualTo(toDate("2009-03-02")); assertThat(secondEvent.registrationTime()).isEqualToIgnoringSeconds(new Date()); assertThat(secondEvent.voyage().voyageNumber()).isEqualTo(new VoyageNumber("0100S")); assertThat(secondEvent.cargo()).isEqualTo(cargo); List<Leg> legs = cargo.itinerary().legs(); assertThat(legs).hasSize(3).extracting("voyage.voyageNumber", "loadLocation", "unloadLocation").containsExactly(Tuple.tuple(null, HONGKONG, NEWYORK), Tuple.tuple("0200T", NEWYORK, DALLAS), Tuple.tuple("0300A", DALLAS, HELSINKI)); }
@Test public void testFindByCargoId() { final TrackingId trackingId = new TrackingId("ABC123"); final Cargo cargo = cargoRepository.find(trackingId); assertThat(cargo).isNotNull(); assertThat(cargo.origin()).isEqualTo(HONGKONG); assertThat(cargo.routeSpecification().origin()).isEqualTo(HONGKONG); assertThat(cargo.routeSpecification().destination()).isEqualTo(HELSINKI); assertThat(cargo.delivery()).isNotNull(); final List<HandlingEvent> events = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime(); assertThat(events).hasSize(3); HandlingEvent firstEvent = events.get(0); assertThat(firstEvent.type()).isEqualTo(RECEIVE); assertThat(firstEvent.location()).isEqualTo(HONGKONG); assertThat(firstEvent.completionTime()).isEqualTo(toDate("2009-03-01")); assertThat(firstEvent.registrationTime()).isEqualToIgnoringSeconds(new Date()); assertThat(firstEvent.voyage().voyageNumber()).isEqualTo(Voyage.NONE.voyageNumber()); assertThat(firstEvent.cargo()).isEqualTo(cargo); HandlingEvent secondEvent = events.get(1); <DeepExtract> assertThat(secondEvent.type()).isEqualTo(LOAD); assertThat(secondEvent.location()).isEqualTo(HONGKONG); assertThat(secondEvent.completionTime()).isEqualTo(toDate("2009-03-02")); assertThat(secondEvent.registrationTime()).isEqualToIgnoringSeconds(new Date()); assertThat(secondEvent.voyage().voyageNumber()).isEqualTo(new VoyageNumber("0100S")); assertThat(secondEvent.cargo()).isEqualTo(cargo); </DeepExtract> List<Leg> legs = cargo.itinerary().legs(); assertThat(legs).hasSize(3).extracting("voyage.voyageNumber", "loadLocation", "unloadLocation").containsExactly(Tuple.tuple(null, HONGKONG, NEWYORK), Tuple.tuple("0200T", NEWYORK, DALLAS), Tuple.tuple("0300A", DALLAS, HELSINKI)); }
dddsample-core
positive
439,196
public SmartMotorBuilder copy() { var builder = new SmartMotorBuilder(); if (type != null) builder.type(this.type); if (portSet) builder.port(this.port); if (enableBrakeModeSet) builder.enableBrakeMode(this.enableBrakeMode); this.statusFrameRatesMillis = this.statusFrameRatesMillis; return this; }
public SmartMotorBuilder copy() { var builder = new SmartMotorBuilder(); if (type != null) builder.type(this.type); if (portSet) builder.port(this.port); if (enableBrakeModeSet) builder.enableBrakeMode(this.enableBrakeMode); <DeepExtract> this.statusFrameRatesMillis = this.statusFrameRatesMillis; return this; </DeepExtract> }
449-central-repo
positive
439,197
public void onNewHead(final FlowNode flowNode) { if (!autoBuildsRegex.trim().isEmpty()) { tryToDefineStartAndStopNodeIds(flowNode); } if (finalResultSent) { return; } pipelineLogger.debug("Checking for issue keys for this build ... "); if (issueKeyExtractor.extractIssueKeys(this.build, pipelineLogger).isEmpty()) { pipelineLogger.debug("No issue keys could be extracted from this build yet, not sending build event to Jira (yet)."); return; } pipelineLogger.debug("Found issue keys for this build! Deciding whether to send information to Jira now."); if (autoBuildsRegex.trim().isEmpty()) { pipelineLogger.debug("Pipeline step regex for builds is empty!"); if (false) { pipelineLogger.debug("Sending final build event (isOnCompleted == true))"); finalResultSent = true; sendBuildStatusToJira(Optional.empty()); } else if (!inProgressSent) { pipelineLogger.debug("Sending in-progress build event (isOnCompleted == false, inProgressSent == false))"); inProgressSent = true; sendBuildStatusToJira(Optional.empty()); } else { pipelineLogger.debug("Not sending any build event (isOnCompleted == false, inProgressSent == true))"); } } else { pipelineLogger.debug(String.format("Pipeline step regex for builds is set to '%s'", autoBuildsRegex)); if (false) { pipelineLogger.debug("Sending final build event (isOnCompleted == true))"); finalResultSent = true; sendBuildStatusToJira(Optional.empty()); } else if (canDetermineFinalResultOfEndNode()) { pipelineLogger.debug("Sending final build event (isOnCompleted == false, canDetermineFinalResultOfEndNode() == true))"); finalResultSent = true; sendBuildStatusToJira(Optional.of(endFlowNodeId)); } else if (!startFlowNodeId.isEmpty() && !inProgressSent) { pipelineLogger.debug("Sending in-progress build event (isOnCompleted == false, canDetermineFinalResultOfEndNode() == false, inProgressSent == false))"); inProgressSent = true; sendBuildStatusToJira(Optional.empty()); } else { pipelineLogger.debug("Not sending any build event (isOnCompleted == false, canDetermineFinalResultOfEndNode() == false, inProgressSent == true)))"); } } }
public void onNewHead(final FlowNode flowNode) { if (!autoBuildsRegex.trim().isEmpty()) { tryToDefineStartAndStopNodeIds(flowNode); } <DeepExtract> if (finalResultSent) { return; } pipelineLogger.debug("Checking for issue keys for this build ... "); if (issueKeyExtractor.extractIssueKeys(this.build, pipelineLogger).isEmpty()) { pipelineLogger.debug("No issue keys could be extracted from this build yet, not sending build event to Jira (yet)."); return; } pipelineLogger.debug("Found issue keys for this build! Deciding whether to send information to Jira now."); if (autoBuildsRegex.trim().isEmpty()) { pipelineLogger.debug("Pipeline step regex for builds is empty!"); if (false) { pipelineLogger.debug("Sending final build event (isOnCompleted == true))"); finalResultSent = true; sendBuildStatusToJira(Optional.empty()); } else if (!inProgressSent) { pipelineLogger.debug("Sending in-progress build event (isOnCompleted == false, inProgressSent == false))"); inProgressSent = true; sendBuildStatusToJira(Optional.empty()); } else { pipelineLogger.debug("Not sending any build event (isOnCompleted == false, inProgressSent == true))"); } } else { pipelineLogger.debug(String.format("Pipeline step regex for builds is set to '%s'", autoBuildsRegex)); if (false) { pipelineLogger.debug("Sending final build event (isOnCompleted == true))"); finalResultSent = true; sendBuildStatusToJira(Optional.empty()); } else if (canDetermineFinalResultOfEndNode()) { pipelineLogger.debug("Sending final build event (isOnCompleted == false, canDetermineFinalResultOfEndNode() == true))"); finalResultSent = true; sendBuildStatusToJira(Optional.of(endFlowNodeId)); } else if (!startFlowNodeId.isEmpty() && !inProgressSent) { pipelineLogger.debug("Sending in-progress build event (isOnCompleted == false, canDetermineFinalResultOfEndNode() == false, inProgressSent == false))"); inProgressSent = true; sendBuildStatusToJira(Optional.empty()); } else { pipelineLogger.debug("Not sending any build event (isOnCompleted == false, canDetermineFinalResultOfEndNode() == false, inProgressSent == true)))"); } } </DeepExtract> }
atlassian-jira-software-cloud-plugin
positive
439,198
public void actionPerformed(java.awt.event.ActionEvent evt) { end_effect_len.setText(""); end_effect_comp.setText(""); mcalcs.use_angle(new Double(Er_tf.getText()), new Double(pcb_height_tf.getText()), new Double(freq_ghz_tf.getText()), new Double(Zo_tf.getText()), new Double(angle_tf.getText())); W_tf.setText(String.format("%3.1f", mcalcs.W)); L_tf.setText(String.format("%3.1f", mcalcs.length)); equiv_comp_val_tf.setText(String.format("%3.2f", mcalcs.comp_val)); Xlc_tf.setText(String.format("%3.1f", mcalcs.Xlc)); warnings.setText(mcalcs.warnings); if (Zo_combo.getSelectedIndex() == 1) { end_effect_comp.setText(String.format(" comp x 1.05: %3.1f", mcalcs.comp_val * 1.05)); } }
public void actionPerformed(java.awt.event.ActionEvent evt) { <DeepExtract> end_effect_len.setText(""); end_effect_comp.setText(""); mcalcs.use_angle(new Double(Er_tf.getText()), new Double(pcb_height_tf.getText()), new Double(freq_ghz_tf.getText()), new Double(Zo_tf.getText()), new Double(angle_tf.getText())); W_tf.setText(String.format("%3.1f", mcalcs.W)); L_tf.setText(String.format("%3.1f", mcalcs.length)); equiv_comp_val_tf.setText(String.format("%3.2f", mcalcs.comp_val)); Xlc_tf.setText(String.format("%3.1f", mcalcs.Xlc)); warnings.setText(mcalcs.warnings); if (Zo_combo.getSelectedIndex() == 1) { end_effect_comp.setText(String.format(" comp x 1.05: %3.1f", mcalcs.comp_val * 1.05)); } </DeepExtract> }
jPCBSim
positive
439,201
public static String xssEncode(String s) { if (s == null || "".equals(s)) { return s; } StringBuilder sb = new StringBuilder(s.length() + 16); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch(c) { case '>': sb.append('>'); break; case '<': sb.append('<'); break; case '\'': sb.append('‘'); break; case '&': sb.append('&'); break; case '#': sb.append('#'); break; default: sb.append(c); break; } } return sb.toString(); }
public static String xssEncode(String s) { <DeepExtract> if (s == null || "".equals(s)) { return s; } StringBuilder sb = new StringBuilder(s.length() + 16); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch(c) { case '>': sb.append('>'); break; case '<': sb.append('<'); break; case '\'': sb.append('‘'); break; case '&': sb.append('&'); break; case '#': sb.append('#'); break; default: sb.append(c); break; } } return sb.toString(); </DeepExtract> }
springboard-cloud
positive
439,202
@Test public void receivePrintStream() throws Exception { handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { response.setStatus(HTTP_OK); try { response.getWriter().print("content"); } catch (IOException e) { fail(); } } }; ByteArrayOutputStream output = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(output, true, CHARSET_UTF8); assertTrue(post(url).receive(stream).ok()); throw closeCause; assertEquals("content", output.toString(CHARSET_UTF8)); }
@Test public void receivePrintStream() throws Exception { handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { response.setStatus(HTTP_OK); try { response.getWriter().print("content"); } catch (IOException e) { fail(); } } }; ByteArrayOutputStream output = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(output, true, CHARSET_UTF8); assertTrue(post(url).receive(stream).ok()); <DeepExtract> throw closeCause; </DeepExtract> assertEquals("content", output.toString(CHARSET_UTF8)); }
NiuBi
positive
439,203
private Territory getWeakestNeighbor() { Territory t = null; Territory weakest = null; double soldierCount = 1000000000; if (myTerritory.getNeighbors() != null && !myTerritory.getNeighbors().isEmpty()) { for (int i = 0; i < myTerritory.getNeighbors().numObjs; i++) { t = (Territory) myTerritory.getNeighbors().get(i); if ((!(t == null)) && (t.getSoldiers() < soldierCount)) { soldierCount = t.getSoldiers(); weakest = t; } } } return weakest; }
private Territory getWeakestNeighbor() { <DeepExtract> Territory t = null; Territory weakest = null; double soldierCount = 1000000000; if (myTerritory.getNeighbors() != null && !myTerritory.getNeighbors().isEmpty()) { for (int i = 0; i < myTerritory.getNeighbors().numObjs; i++) { t = (Territory) myTerritory.getNeighbors().get(i); if ((!(t == null)) && (t.getSoldiers() < soldierCount)) { soldierCount = t.getSoldiers(); weakest = t; } } } return weakest; </DeepExtract> }
CSS605-Fall2011
positive
439,204
void addCurrentAttributeAndEmitToken() { try { if (currentAttributeName != null) { String curAttrName = currentAttributeName.toLowerCase(); if (attributes.containsKey(curAttrName)) { tokenHandler.emitParseError(); } else { attributes.put(new AttributeNode(curAttrName, currentAttributeName.containsUpperCase ? currentAttributeName.asString() : curAttrName, currentAttributeValue.asString(), currentAttributeQuoteType)); } } } catch (NullPointerException npe) { tokenHandler.emitParseError(); } finally { currentAttributeName = null; currentAttributeValue = null; } if (!isEndTagToken) { lastEmittedStartTagName = tagName; } if (selfClosing && isEndTagToken) { tokenHandler.emitParseError(); } if (!isEndTagToken) { tokenHandler.emitStartTagToken(tagName, attributes, selfClosing); } else { tokenHandler.emitEndTagToken(tagName); } }
void addCurrentAttributeAndEmitToken() { try { if (currentAttributeName != null) { String curAttrName = currentAttributeName.toLowerCase(); if (attributes.containsKey(curAttrName)) { tokenHandler.emitParseError(); } else { attributes.put(new AttributeNode(curAttrName, currentAttributeName.containsUpperCase ? currentAttributeName.asString() : curAttrName, currentAttributeValue.asString(), currentAttributeQuoteType)); } } } catch (NullPointerException npe) { tokenHandler.emitParseError(); } finally { currentAttributeName = null; currentAttributeValue = null; } if (!isEndTagToken) { lastEmittedStartTagName = tagName; } <DeepExtract> if (selfClosing && isEndTagToken) { tokenHandler.emitParseError(); } if (!isEndTagToken) { tokenHandler.emitStartTagToken(tagName, attributes, selfClosing); } else { tokenHandler.emitEndTagToken(tagName); } </DeepExtract> }
jfiveparse
positive
439,205
@Override public void endElement(final String uri, final String localName, final String qName) throws SAXException { Tag t; try { t = Tag.valueOf(qName.toUpperCase()); } catch (final IllegalArgumentException e) { throw new SAXException("Unknown tag <" + qName.toUpperCase() + ">"); } if (t == Tag.BR) { return; } if (t == Tag.B) { fontStyle &= ~SWT.BOLD; } else if (t == Tag.I) { fontStyle &= ~SWT.ITALIC; } else if (t == Tag.U) { underline = false; } else if (t == Tag.S) { strikeout = false; } else if (t == Tag.SUB) subscript = false; else if (t == Tag.SUP) { superscript = false; } else if (t == Tag.STYLE) { foreground = null; background = null; fontHeight = 0; fontName = null; } else if (t == Tag.A) { foreground = lastForeground; underline = lastUnderline; strikeout = lastStrikeout; link = null; } tagStack.remove(tagStack.size() - 1); }
@Override public void endElement(final String uri, final String localName, final String qName) throws SAXException { <DeepExtract> Tag t; try { t = Tag.valueOf(qName.toUpperCase()); } catch (final IllegalArgumentException e) { throw new SAXException("Unknown tag <" + qName.toUpperCase() + ">"); } </DeepExtract> if (t == Tag.BR) { return; } if (t == Tag.B) { fontStyle &= ~SWT.BOLD; } else if (t == Tag.I) { fontStyle &= ~SWT.ITALIC; } else if (t == Tag.U) { underline = false; } else if (t == Tag.S) { strikeout = false; } else if (t == Tag.SUB) subscript = false; else if (t == Tag.SUP) { superscript = false; } else if (t == Tag.STYLE) { foreground = null; background = null; fontHeight = 0; fontName = null; } else if (t == Tag.A) { foreground = lastForeground; underline = lastUnderline; strikeout = lastStrikeout; link = null; } tagStack.remove(tagStack.size() - 1); }
greip
positive
439,206
@Override public ProcessorBuilder<T, R> filter(Predicate<? super R> predicate) { return new ProcessorBuilderImpl<>(new Stages.Filter(predicate), this); }
@Override public ProcessorBuilder<T, R> filter(Predicate<? super R> predicate) { <DeepExtract> return new ProcessorBuilderImpl<>(new Stages.Filter(predicate), this); </DeepExtract> }
microprofile-reactive-streams-operators
positive
439,207
public void forceDismiss(int position) { mLastScrollIndex = vList.getFirstVisiblePosition(); View v = vList.getChildAt(0); mLastScrollTop = (v == null) ? 0 : v.getTop(); vSwipeDismissList.forceDismiss(position); }
public void forceDismiss(int position) { <DeepExtract> mLastScrollIndex = vList.getFirstVisiblePosition(); View v = vList.getChildAt(0); mLastScrollTop = (v == null) ? 0 : v.getTop(); </DeepExtract> vSwipeDismissList.forceDismiss(position); }
sms-ticket
positive
439,209
@Override public void initView() { mVpActMainShow = (ViewPager) findViewById(R.id.vp_act_main_show); mLinActMainBottom = (LinearLayout) findViewById(R.id.lin_act_main_bottom); mTvActMainHomeimg = (TextView) findViewById(R.id.tv_act_main_homeimg); mTvActMainHometext = (TextView) findViewById(R.id.tv_act_main_hometext); mTvActMainVedioimg = (TextView) findViewById(R.id.tv_act_main_vedioimg); mTvActMainVediotext = (TextView) findViewById(R.id.tv_act_main_vediotext); mTvActMainCollimg = (TextView) findViewById(R.id.tv_act_main_collimg); mTvActMainColltext = (TextView) findViewById(R.id.tv_act_main_colltext); mTvActMainMeimg = (TextView) findViewById(R.id.tv_act_main_meimg); mTvActMainMetext = (TextView) findViewById(R.id.tv_act_main_metext); mFragments = new ArrayList<>(); mCollectFragment = CollectFragment.newInstance(); mMeFragment = MeFragment.newInstance(); mHomeFragment = HomeFragment.newInstance(); mVedioFragment = VedioFragment.newInstance(); mFragments.add(mHomeFragment); mFragments.add(mVedioFragment); mFragments.add(mCollectFragment); mFragments.add(mMeFragment); FragmentManager manager = getSupportFragmentManager(); mVPAdapter = new VPAdapter(manager, mFragments); mVpActMainShow.setAdapter(mVPAdapter); mVpActMainShow.setPageTransformer(true, new RotateUpTransformer()); mVpActMainShow.addOnPageChangeListener(this); mTvActMainHomeimg.setOnClickListener(this); mTvActMainMeimg.setOnClickListener(this); mTvActMainVedioimg.setOnClickListener(this); mTvActMainCollimg.setOnClickListener(this); }
@Override public void initView() { mVpActMainShow = (ViewPager) findViewById(R.id.vp_act_main_show); mLinActMainBottom = (LinearLayout) findViewById(R.id.lin_act_main_bottom); mTvActMainHomeimg = (TextView) findViewById(R.id.tv_act_main_homeimg); mTvActMainHometext = (TextView) findViewById(R.id.tv_act_main_hometext); mTvActMainVedioimg = (TextView) findViewById(R.id.tv_act_main_vedioimg); mTvActMainVediotext = (TextView) findViewById(R.id.tv_act_main_vediotext); mTvActMainCollimg = (TextView) findViewById(R.id.tv_act_main_collimg); mTvActMainColltext = (TextView) findViewById(R.id.tv_act_main_colltext); mTvActMainMeimg = (TextView) findViewById(R.id.tv_act_main_meimg); mTvActMainMetext = (TextView) findViewById(R.id.tv_act_main_metext); mFragments = new ArrayList<>(); mCollectFragment = CollectFragment.newInstance(); mMeFragment = MeFragment.newInstance(); mHomeFragment = HomeFragment.newInstance(); mVedioFragment = VedioFragment.newInstance(); mFragments.add(mHomeFragment); mFragments.add(mVedioFragment); mFragments.add(mCollectFragment); mFragments.add(mMeFragment); FragmentManager manager = getSupportFragmentManager(); mVPAdapter = new VPAdapter(manager, mFragments); mVpActMainShow.setAdapter(mVPAdapter); mVpActMainShow.setPageTransformer(true, new RotateUpTransformer()); mVpActMainShow.addOnPageChangeListener(this); <DeepExtract> mTvActMainHomeimg.setOnClickListener(this); mTvActMainMeimg.setOnClickListener(this); mTvActMainVedioimg.setOnClickListener(this); mTvActMainCollimg.setOnClickListener(this); </DeepExtract> }
ChildrenEduction
positive
439,210
@Override public void callback(String url, WebPage wp, AjaxStatus status) { AQUtility.debug("web cb"); if (wp != null) { setHtmlCheckMobile(wv, wp); } if (ready == null || !wp.getOriginal().equals(ready.getTag(AQuery.TAG_URL))) { return; } try { } catch (Exception e) { AQUtility.report(e); } }
@Override public void callback(String url, WebPage wp, AjaxStatus status) { AQUtility.debug("web cb"); if (wp != null) { setHtmlCheckMobile(wv, wp); } <DeepExtract> if (ready == null || !wp.getOriginal().equals(ready.getTag(AQuery.TAG_URL))) { return; } try { } catch (Exception e) { AQUtility.report(e); } </DeepExtract> }
simplefacebook
positive
439,211
@Override public void release() { if (stopped) { return; } stopped = true; ThreadUtils.get().runOnFX(consoleStage::hide); stdoutThread.interrupt(); stderrThread.interrupt(); System.setOut(originalStdout); System.setErr(originalStderr); Logger.info("restored stdout/stderr"); }
@Override public void release() { <DeepExtract> if (stopped) { return; } stopped = true; ThreadUtils.get().runOnFX(consoleStage::hide); stdoutThread.interrupt(); stderrThread.interrupt(); System.setOut(originalStdout); System.setErr(originalStderr); Logger.info("restored stdout/stderr"); </DeepExtract> }
Chara
positive
439,212
public BDB setInputType(int inputType) { this.inputType = inputType; this.flags |= BDialog.FLAG_INPUT; return this; }
public BDB setInputType(int inputType) { this.inputType = inputType; <DeepExtract> this.flags |= BDialog.FLAG_INPUT; return this; </DeepExtract> }
BaldPhone
positive
439,213
@Override public void onResponse(ArrayList<User> users) { mUsers.clear(); mUsers.addAll(users); mAdapter.notifyDataSetChanged(); if (users.size() > 0) showList(); else hideList(); mShouldRequest = true; }
@Override public void onResponse(ArrayList<User> users) { <DeepExtract> mUsers.clear(); mUsers.addAll(users); mAdapter.notifyDataSetChanged(); if (users.size() > 0) showList(); else hideList(); mShouldRequest = true; </DeepExtract> }
watershed
positive
439,215
@Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { logger.info("closing outbound channel"); if (inboundChannel.isConnected()) { inboundChannel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }
@Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { logger.info("closing outbound channel"); <DeepExtract> if (inboundChannel.isConnected()) { inboundChannel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } </DeepExtract> }
flazr
positive
439,218
@Test public void testInheritedBatchDelete() { Child lc0 = new Child(); lc0.foo = "bar"; lc0.bar = "order"; lc0.fee = "123"; lc0.save(); Child lc1 = new Child(); lc1.foo = "foo"; lc1.bar = "order"; lc1.fee = "123"; lc1.save(); Child.q("bar", "order").delete(); assertTrue(Event.count("foobar", OnBatchDelete.class) == 0); assertTrue(Event.count("foobar", BatchDeleted.class) == 0); assertTrue(Event.count("456", OnBatchDelete.class) == 2); assertTrue(Event.count("456", BatchDeleted.class) == 2); }
@Test public void testInheritedBatchDelete() { Child lc0 = new Child(); lc0.foo = "bar"; lc0.bar = "order"; lc0.fee = "123"; lc0.save(); Child lc1 = new Child(); lc1.foo = "foo"; lc1.bar = "order"; lc1.fee = "123"; lc1.save(); Child.q("bar", "order").delete(); assertTrue(Event.count("foobar", OnBatchDelete.class) == 0); assertTrue(Event.count("foobar", BatchDeleted.class) == 0); assertTrue(Event.count("456", OnBatchDelete.class) == 2); <DeepExtract> assertTrue(Event.count("456", BatchDeleted.class) == 2); </DeepExtract> }
play-morphia
positive
439,219
public ViewTransitionBuilder delayHeight(@IntRange(from = 0) final int targetHeight) { process[HEIGHT] = targetHeight; return this; }
public ViewTransitionBuilder delayHeight(@IntRange(from = 0) final int targetHeight) { process[HEIGHT] = targetHeight; <DeepExtract> return this; </DeepExtract> }
android-transition
positive
439,220
private void EventSetsPanel_RemoveEventSetButtonActionPerformed(java.awt.event.ActionEvent evt) { SelectedEventDriverList = JGAAP_API.getEventDrivers(); JGAAP_API.removeEventDriver(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex())); EventSetsPanel_ParametersPanel.removeAll(); EventSetsPanel_ParametersPanel.updateUI(); UpdateSelectedEventSetListBox(); }
private void EventSetsPanel_RemoveEventSetButtonActionPerformed(java.awt.event.ActionEvent evt) { <DeepExtract> SelectedEventDriverList = JGAAP_API.getEventDrivers(); JGAAP_API.removeEventDriver(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex())); EventSetsPanel_ParametersPanel.removeAll(); EventSetsPanel_ParametersPanel.updateUI(); UpdateSelectedEventSetListBox(); </DeepExtract> }
JGAAP
positive
439,221
public void start(I iface, notifyWithoutOneway_args args, AsyncMethodCallback<Void> resultHandler) throws TException { checkReady(); notifyWithoutOneway_call method_call = new notifyWithoutOneway_call(args.id, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); }
public void start(I iface, notifyWithoutOneway_args args, AsyncMethodCallback<Void> resultHandler) throws TException { <DeepExtract> checkReady(); notifyWithoutOneway_call method_call = new notifyWithoutOneway_call(args.id, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); </DeepExtract> }
Firefly
positive
439,224
public void nodeLeaving(Id nodeId) { Node node = registry.getNode(nodeId); boolean before = registry.isClusterHealthy(); registry.leave(nodeId); boolean after = registry.isClusterHealthy(); interest.nodeLeft(node, after); clusterApplication.informNodeLeftCluster(node.id(), after); informAllLiveNodes(after); if (before != after) { clusterApplication.informClusterIsHealthy(after); interest.informClusterIsHealthy(after); } }
public void nodeLeaving(Id nodeId) { <DeepExtract> Node node = registry.getNode(nodeId); boolean before = registry.isClusterHealthy(); registry.leave(nodeId); boolean after = registry.isClusterHealthy(); interest.nodeLeft(node, after); clusterApplication.informNodeLeftCluster(node.id(), after); informAllLiveNodes(after); if (before != after) { clusterApplication.informClusterIsHealthy(after); interest.informClusterIsHealthy(after); } </DeepExtract> }
xoom-cluster
positive
439,225
@Override public JComponent getComponent(Lookup masterLookup) { if (panel == null) { panel = new FoldersPanel(this); } return panel; }
@Override public JComponent getComponent(Lookup masterLookup) { <DeepExtract> if (panel == null) { panel = new FoldersPanel(this); } return panel; </DeepExtract> }
Kayak
positive
439,227
@Override public TinyMap<K, V> build() { compact(); Preconditions.checkArgument(buildKeys().size() == size(), "Must have same size"); return TinyMap.createUnsafe(buildKeys(), Arrays.copyOf(values, buildKeys().size())); }
@Override public TinyMap<K, V> build() { <DeepExtract> compact(); Preconditions.checkArgument(buildKeys().size() == size(), "Must have same size"); return TinyMap.createUnsafe(buildKeys(), Arrays.copyOf(values, buildKeys().size())); </DeepExtract> }
tinymap
positive
439,228
private void initRanking() { getSupportActionBar().setTitle(getString(R.string.text_ranking)); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); if (rankingFragment == null) { rankingFragment = new RankingFragment(); transaction.add(R.id.main_frame_layout, rankingFragment); } if (homePageFragment != null) { transaction.hide(homePageFragment); } if (categoryFragment != null) { transaction.hide(categoryFragment); } if (rankingFragment != null) { transaction.hide(rankingFragment); } if (wallpaperFragment != null) { transaction.hide(wallpaperFragment); } if (recommendFragment != null) { transaction.hide(recommendFragment); } if (weatherFragment != null) { transaction.hide(weatherFragment); } if (albumFragment != null) { transaction.hide(albumFragment); } transaction.show(rankingFragment); transaction.commit(); }
private void initRanking() { getSupportActionBar().setTitle(getString(R.string.text_ranking)); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); if (rankingFragment == null) { rankingFragment = new RankingFragment(); transaction.add(R.id.main_frame_layout, rankingFragment); } <DeepExtract> if (homePageFragment != null) { transaction.hide(homePageFragment); } if (categoryFragment != null) { transaction.hide(categoryFragment); } if (rankingFragment != null) { transaction.hide(rankingFragment); } if (wallpaperFragment != null) { transaction.hide(wallpaperFragment); } if (recommendFragment != null) { transaction.hide(recommendFragment); } if (weatherFragment != null) { transaction.hide(weatherFragment); } if (albumFragment != null) { transaction.hide(albumFragment); } </DeepExtract> transaction.show(rankingFragment); transaction.commit(); }
LoveWallpaper
positive
439,229
@Override public HashCode hashLong(long input) { munch(); buffer.flip(); if (buffer.remaining() > 0) { processRemaining(buffer); } return makeHash(); }
@Override public HashCode hashLong(long input) { <DeepExtract> munch(); buffer.flip(); if (buffer.remaining() > 0) { processRemaining(buffer); } return makeHash(); </DeepExtract> }
pancake-smarts
positive
439,230
public ByteBuffer getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); lookup_result result = new lookup_result(); receiveBase(result, "lookup"); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "lookup failed: unknown result"); }
public ByteBuffer getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); <DeepExtract> lookup_result result = new lookup_result(); receiveBase(result, "lookup"); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "lookup failed: unknown result"); </DeepExtract> }
Pistachio
positive
439,232
@Override public void onReceive(Context context, Intent intent) { if (DroidConfig.DEBUG) { final NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); final String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); final boolean failover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false); Log.i(TAG, "Network info: " + " otherNetworkInfo = " + (otherNetworkInfo == null ? "[none]" : otherNetworkInfo) + ", failover=" + failover + ", reason=" + reason); } if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) { notifyConnectionGone(context); return; } final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { notifyConnectionActive(context, netInfo.getType()); } else { notifyConnectionGone(context); } }
@Override public void onReceive(Context context, Intent intent) { <DeepExtract> if (DroidConfig.DEBUG) { final NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); final String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); final boolean failover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false); Log.i(TAG, "Network info: " + " otherNetworkInfo = " + (otherNetworkInfo == null ? "[none]" : otherNetworkInfo) + ", failover=" + failover + ", reason=" + reason); } </DeepExtract> if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) { notifyConnectionGone(context); return; } final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { notifyConnectionActive(context, netInfo.getType()); } else { notifyConnectionGone(context); } }
kraken
positive
439,233
public static <T> T randChoice(List<T> elems, Random rand) { int index = rand.nextInt(elems.size()); return elems.get(index + start); }
public static <T> T randChoice(List<T> elems, Random rand) { int index = rand.nextInt(elems.size()); <DeepExtract> return elems.get(index + start); </DeepExtract> }
nlp-utils
positive
439,235