before
stringlengths
33
3.21M
after
stringlengths
63
3.21M
repo
stringlengths
1
56
type
stringclasses
1 value
__index_level_0__
int64
0
442k
public Attachment getAttachment(int slotIndex, String name) { if (slotIndex < 0) throw new IllegalArgumentException("slotIndex must be >= 0."); if (name == null) throw new IllegalArgumentException("name cannot be null."); this.slotIndex = slotIndex; this.name = name; hashCode = 31 * (31 + name.hashCode()) + slotIndex; return attachments.get(lookup); }
public Attachment getAttachment(int slotIndex, String name) { if (slotIndex < 0) throw new IllegalArgumentException("slotIndex must be >= 0."); <DeepExtract> if (name == null) throw new IllegalArgumentException("name cannot be null."); this.slotIndex = slotIndex; this.name = name; hashCode = 31 * (31 + name.hashCode()) + slotIndex; </DeepExtract> return attachments.get(lookup); }
libgdxjam
positive
2,901
@Override public boolean removeTransactionWithIndex(long index) { if (index < 0) { throw new NegativeIndexException(); } else if (index == 0) { throw new ZeroIndexException(); } if (data.containsKey(index)) { HttpTransaction deletedTransaction = data.get(index); data.remove(index); sendDataChangeEvent(Event.DELETED, deletedTransaction); return true; } return false; }
@Override public boolean removeTransactionWithIndex(long index) { <DeepExtract> if (index < 0) { throw new NegativeIndexException(); } else if (index == 0) { throw new ZeroIndexException(); } </DeepExtract> if (data.containsKey(index)) { HttpTransaction deletedTransaction = data.get(index); data.remove(index); sendDataChangeEvent(Event.DELETED, deletedTransaction); return true; } return false; }
Gander
positive
2,903
@Test public void testTransferTransaction() { ECKey sourcePrivateKey = new BrainKey(BILTHON_7_BRAIN_KEY, 0).getPrivateKey(); PublicKey to1 = new PublicKey(ECKey.fromPublicOnly(new BrainKey(BILTHON_5_BRAIN_KEY, 0).getPublicKey())); PublicKey to2 = new PublicKey(ECKey.fromPublicOnly(new BrainKey(BILTHON_16_BRAIN_KEY, 0).getPublicKey())); BigInteger nonce = BigInteger.ONE; byte[] encryptedMessage = Memo.encryptMessage(sourcePrivateKey, to1, nonce, "another message"); Memo memo = new Memo(new Address(ECKey.fromPublicOnly(sourcePrivateKey.getPubKey())), new Address(to1.getKey()), nonce, encryptedMessage); TransferOperation transferOperation1 = new TransferOperationBuilder().setTransferAmount(new AssetAmount(UnsignedLong.valueOf(1), CORE_ASSET)).setSource(bilthon_7).setDestination(bilthon_5).setFee(new AssetAmount(UnsignedLong.valueOf(FEE_AMOUNT), CORE_ASSET)).setMemo(memo).build(); TransferOperation transferOperation2 = new TransferOperationBuilder().setTransferAmount(new AssetAmount(UnsignedLong.valueOf(1), CORE_ASSET)).setSource(bilthon_7).setDestination(bilthon_16).setFee(new AssetAmount(UnsignedLong.valueOf(FEE_AMOUNT), CORE_ASSET)).setMemo(memo).build(); ArrayList<BaseOperation> operationList = new ArrayList<>(); operationList.add(transferOperation1); operationList.add(transferOperation2); try { Transaction transaction = new Transaction(sourcePrivateKey, null, operationList); SSLContext context = null; context = NaiveSSLContext.getInstance("TLS"); WebSocketFactory factory = new WebSocketFactory(); factory.setSSLContext(context); WebSocket mWebSocket = factory.createSocket(NODE_URL); mWebSocket.addListener(new TransactionBroadcastSequence(transaction, CORE_ASSET, listener)); mWebSocket.connect(); if (null != null) { synchronized (null) { null.wait(); } } else { synchronized (listener) { listener.wait(); } } Assert.assertNotNull(baseResponse); Assert.assertNull(baseResponse.error); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgoritmException. Msg: " + e.getMessage()); } catch (InterruptedException e) { System.out.println("InterruptedException. Msg: " + e.getMessage()); } catch (IOException e) { System.out.println("IOException. Msg: " + e.getMessage()); } catch (WebSocketException e) { System.out.println("WebSocketException. Msg: " + e.getMessage()); } }
@Test public void testTransferTransaction() { ECKey sourcePrivateKey = new BrainKey(BILTHON_7_BRAIN_KEY, 0).getPrivateKey(); PublicKey to1 = new PublicKey(ECKey.fromPublicOnly(new BrainKey(BILTHON_5_BRAIN_KEY, 0).getPublicKey())); PublicKey to2 = new PublicKey(ECKey.fromPublicOnly(new BrainKey(BILTHON_16_BRAIN_KEY, 0).getPublicKey())); BigInteger nonce = BigInteger.ONE; byte[] encryptedMessage = Memo.encryptMessage(sourcePrivateKey, to1, nonce, "another message"); Memo memo = new Memo(new Address(ECKey.fromPublicOnly(sourcePrivateKey.getPubKey())), new Address(to1.getKey()), nonce, encryptedMessage); TransferOperation transferOperation1 = new TransferOperationBuilder().setTransferAmount(new AssetAmount(UnsignedLong.valueOf(1), CORE_ASSET)).setSource(bilthon_7).setDestination(bilthon_5).setFee(new AssetAmount(UnsignedLong.valueOf(FEE_AMOUNT), CORE_ASSET)).setMemo(memo).build(); TransferOperation transferOperation2 = new TransferOperationBuilder().setTransferAmount(new AssetAmount(UnsignedLong.valueOf(1), CORE_ASSET)).setSource(bilthon_7).setDestination(bilthon_16).setFee(new AssetAmount(UnsignedLong.valueOf(FEE_AMOUNT), CORE_ASSET)).setMemo(memo).build(); ArrayList<BaseOperation> operationList = new ArrayList<>(); operationList.add(transferOperation1); operationList.add(transferOperation2); <DeepExtract> try { Transaction transaction = new Transaction(sourcePrivateKey, null, operationList); SSLContext context = null; context = NaiveSSLContext.getInstance("TLS"); WebSocketFactory factory = new WebSocketFactory(); factory.setSSLContext(context); WebSocket mWebSocket = factory.createSocket(NODE_URL); mWebSocket.addListener(new TransactionBroadcastSequence(transaction, CORE_ASSET, listener)); mWebSocket.connect(); if (null != null) { synchronized (null) { null.wait(); } } else { synchronized (listener) { listener.wait(); } } Assert.assertNotNull(baseResponse); Assert.assertNull(baseResponse.error); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgoritmException. Msg: " + e.getMessage()); } catch (InterruptedException e) { System.out.println("InterruptedException. Msg: " + e.getMessage()); } catch (IOException e) { System.out.println("IOException. Msg: " + e.getMessage()); } catch (WebSocketException e) { System.out.println("WebSocketException. Msg: " + e.getMessage()); } </DeepExtract> }
graphenej
positive
2,904
public Vector3 sub(Vector3 vec) { x -= vec.x; y -= vec.y; z -= vec.z; return this; }
public Vector3 sub(Vector3 vec) { <DeepExtract> x -= vec.x; y -= vec.y; z -= vec.z; return this; </DeepExtract> }
CoFHTweaks
positive
2,905
public int getGLLightIdentifier() { int retID = -1; switch(this.lightNumber) { case 0: retID = GLLightingFunc.GL_LIGHT0; break; case 1: retID = GLLightingFunc.GL_LIGHT1; break; case 2: retID = GLLightingFunc.GL_LIGHT2; break; case 3: retID = GLLightingFunc.GL_LIGHT3; break; case 4: retID = GLLightingFunc.GL_LIGHT4; break; case 5: retID = GLLightingFunc.GL_LIGHT5; break; case 6: retID = GLLightingFunc.GL_LIGHT6; break; case 7: retID = GLLightingFunc.GL_LIGHT7; break; default: throw new LightingException("tried to determine ID of a number not on [0,7]"); } return retID; }
public int getGLLightIdentifier() { <DeepExtract> int retID = -1; switch(this.lightNumber) { case 0: retID = GLLightingFunc.GL_LIGHT0; break; case 1: retID = GLLightingFunc.GL_LIGHT1; break; case 2: retID = GLLightingFunc.GL_LIGHT2; break; case 3: retID = GLLightingFunc.GL_LIGHT3; break; case 4: retID = GLLightingFunc.GL_LIGHT4; break; case 5: retID = GLLightingFunc.GL_LIGHT5; break; case 6: retID = GLLightingFunc.GL_LIGHT6; break; case 7: retID = GLLightingFunc.GL_LIGHT7; break; default: throw new LightingException("tried to determine ID of a number not on [0,7]"); } return retID; </DeepExtract> }
jogl-utils
positive
2,906
public synchronized void keyReleased(int j) { int k = getGameAction(j); int l; if ((l = j - 48) >= 0 && l < 10) m_LaZ[l] = false; else if (k >= 0 && k < 7) m_aeaZ[k] = false; _xavV(); }
public synchronized void keyReleased(int j) { <DeepExtract> int k = getGameAction(j); int l; if ((l = j - 48) >= 0 && l < 10) m_LaZ[l] = false; else if (k >= 0 && k < 7) m_aeaZ[k] = false; _xavV(); </DeepExtract> }
gravitydefied
positive
2,907
public Criteria andMaxpriceEqualTo(String value) { if (value == null) { throw new RuntimeException("Value for " + "maxprice" + " cannot be null"); } criteria.add(new Criterion("maxprice =", value)); return (Criteria) this; }
public Criteria andMaxpriceEqualTo(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "maxprice" + " cannot be null"); } criteria.add(new Criterion("maxprice =", value)); </DeepExtract> return (Criteria) this; }
Whome
positive
2,908
public void mouseDragged(MouseEvent ev) { switch(new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())).type) { case DOWN: Optional<Entry> oe = doc.getByPoint(new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())).pt); if (oe.isPresent()) { System.out.println("classic dragging " + oe.get().id); oDragging = Optional.of(new Dragging(new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())), oe.get())); move = new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())).pt; } break; case MOVE: move = new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())).pt; updateMove(); break; case UP: oDragging = Optional.empty(); break; } }
public void mouseDragged(MouseEvent ev) { <DeepExtract> switch(new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())).type) { case DOWN: Optional<Entry> oe = doc.getByPoint(new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())).pt); if (oe.isPresent()) { System.out.println("classic dragging " + oe.get().id); oDragging = Optional.of(new Dragging(new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())), oe.get())); move = new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())).pt; } break; case MOVE: move = new MouseEvt(Type.MOVE, new Point(ev.getX(), ev.getY())).pt; updateMove(); break; case UP: oDragging = Optional.empty(); break; } </DeepExtract> }
sodium
positive
2,909
public Criteria andParm2NotIn(List<String> values) { if (values == null) { throw new RuntimeException("Value for " + "parm2" + " cannot be null"); } criteria.add(new Criterion("PARM2 not in", values)); return (Criteria) this; }
public Criteria andParm2NotIn(List<String> values) { <DeepExtract> if (values == null) { throw new RuntimeException("Value for " + "parm2" + " cannot be null"); } criteria.add(new Criterion("PARM2 not in", values)); </DeepExtract> return (Criteria) this; }
console
positive
2,911
@Override public void stateChanged(ChangeEvent e) { String text = in.getText(); float fontsize = ((Number) size.getValue()).floatValue(); int style = Font.PLAIN; if (italic.isSelected()) { style |= Font.ITALIC; } if (bold.isSelected()) { style |= Font.BOLD; } out.removeAll(); for (Font font : GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()) { if (font.canDisplayUpTo(text) == -1) { out.add(new JLabel(font.getFontName())); JLabel sample = new JLabel(text); sample.setFont(font.deriveFont(style, fontsize)); out.add(sample); } } validate(); }
@Override public void stateChanged(ChangeEvent e) { <DeepExtract> String text = in.getText(); float fontsize = ((Number) size.getValue()).floatValue(); int style = Font.PLAIN; if (italic.isSelected()) { style |= Font.ITALIC; } if (bold.isSelected()) { style |= Font.BOLD; } out.removeAll(); for (Font font : GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()) { if (font.canDisplayUpTo(text) == -1) { out.add(new JLabel(font.getFontName())); JLabel sample = new JLabel(text); sample.setFont(font.deriveFont(style, fontsize)); out.add(sample); } } validate(); </DeepExtract> }
MathOCR
positive
2,913
public Criteria andIdBetween(String value1, String value2) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "id" + " cannot be null"); } criteria.add(new Criterion("id between", value1, value2)); return (Criteria) this; }
public Criteria andIdBetween(String value1, String value2) { <DeepExtract> if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "id" + " cannot be null"); } criteria.add(new Criterion("id between", value1, value2)); </DeepExtract> return (Criteria) this; }
sihai-maven-ssm-alipay
positive
2,914
public Criteria andGmtModifiedIsNotNull() { if ("GMT_MODIFIED is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("GMT_MODIFIED is not null")); return (Criteria) this; }
public Criteria andGmtModifiedIsNotNull() { <DeepExtract> if ("GMT_MODIFIED is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("GMT_MODIFIED is not null")); </DeepExtract> return (Criteria) this; }
communitycode
positive
2,915
public static boolean createDefaultTable() { String sql = "CREATE TABLE %s (" + "player VARCHAR(50), " + "data LONGTEXT)DEFAULT CHARSET=UTF8;"; sql = String.format(sql, tableName); MySqlConnection connection = MySqlConnection.getConnection(); if (!connection.isValid()) { RealSurvival.logger().severe(I18N.tr("log.severe.mysql.not-valid")); return false; } try { return connection.execute(sql).execute(); } catch (SQLException e) { e.printStackTrace(); } finally { connection.free(null, null); } return false; }
public static boolean createDefaultTable() { String sql = "CREATE TABLE %s (" + "player VARCHAR(50), " + "data LONGTEXT)DEFAULT CHARSET=UTF8;"; sql = String.format(sql, tableName); <DeepExtract> MySqlConnection connection = MySqlConnection.getConnection(); if (!connection.isValid()) { RealSurvival.logger().severe(I18N.tr("log.severe.mysql.not-valid")); return false; } try { return connection.execute(sql).execute(); } catch (SQLException e) { e.printStackTrace(); } finally { connection.free(null, null); } return false; </DeepExtract> }
RealSurvival
positive
2,916
@Test public void findNearest2() throws Exception { list = Arrays.asList("Mark", "Steve", "Mason", "Joan", "Jordan", "Greg", "Mark", "Garth", "Joan", "Daisy", "Garth", "Marcus"); expected = 3; assertEquals(expected, NearestRepeated.findNearest(list)); }
@Test public void findNearest2() throws Exception { list = Arrays.asList("Mark", "Steve", "Mason", "Joan", "Jordan", "Greg", "Mark", "Garth", "Joan", "Daisy", "Garth", "Marcus"); expected = 3; <DeepExtract> assertEquals(expected, NearestRepeated.findNearest(list)); </DeepExtract> }
Elements-of-programming-interviews
positive
2,917
@Test public void castPrimitiveIntegerExceptionWithLogging() { PoijiOptions options = PoijiOptionsBuilder.settings().sheetName(sheetName).build(); String value = "not an int"; Integer expectedDefault = 0; Integer testVal = (Integer) casting.castValue(int.class, value, options); assertEquals(expectedDefault, testVal); assertEquals(casting.getErrors().size(), 1); assertCastingErrorEquals(casting.getErrors().get(0), sheetName, value, expectedDefault, NumberFormatException.class); }
@Test public void castPrimitiveIntegerExceptionWithLogging() { PoijiOptions options = PoijiOptionsBuilder.settings().sheetName(sheetName).build(); String value = "not an int"; Integer expectedDefault = 0; Integer testVal = (Integer) casting.castValue(int.class, value, options); assertEquals(expectedDefault, testVal); <DeepExtract> assertEquals(casting.getErrors().size(), 1); assertCastingErrorEquals(casting.getErrors().get(0), sheetName, value, expectedDefault, NumberFormatException.class); </DeepExtract> }
poiji
positive
2,918
@Override public void sendPing(byte[] payload) { sendMessage(new TextMessage(new Ping(payload))); }
@Override public void sendPing(byte[] payload) { <DeepExtract> sendMessage(new TextMessage(new Ping(payload))); </DeepExtract> }
autobahn-java
positive
2,919
public final void testIllegalElementName() throws Exception { renderer.openDocument(); renderer.openTag(":svg", ImmutableList.<String>of()); renderer.openTag("svg:", ImmutableList.<String>of()); renderer.openTag("-1", ImmutableList.<String>of()); renderer.openTag("svg::svg", ImmutableList.<String>of()); renderer.openTag("a@b", ImmutableList.<String>of()); renderer.closeDocument(); String output = rendered.toString(); assertFalse(output, output.contains("<")); assertEquals(Joiner.on('\n').join("Invalid element name : :svg", "Invalid element name : svg:", "Invalid element name : -1", "Invalid element name : svg::svg", "Invalid element name : a@b"), Joiner.on('\n').join(errors)); errors.clear(); }
public final void testIllegalElementName() throws Exception { renderer.openDocument(); renderer.openTag(":svg", ImmutableList.<String>of()); renderer.openTag("svg:", ImmutableList.<String>of()); renderer.openTag("-1", ImmutableList.<String>of()); renderer.openTag("svg::svg", ImmutableList.<String>of()); renderer.openTag("a@b", ImmutableList.<String>of()); <DeepExtract> renderer.closeDocument(); </DeepExtract> String output = rendered.toString(); assertFalse(output, output.contains("<")); assertEquals(Joiner.on('\n').join("Invalid element name : :svg", "Invalid element name : svg:", "Invalid element name : -1", "Invalid element name : svg::svg", "Invalid element name : a@b"), Joiner.on('\n').join(errors)); errors.clear(); }
java-html-sanitizer
positive
2,920
private void closeImpl() { TmcSwingUtilities.ensureEdt(new Runnable() { @Override public void run() { TmcEventBus.getDefault().post(new InvokedEvent("spyware_unloaded")); textInsertEventSource.close(); TmcEventBus.getDefault().unsubscribe(tmcEventBusSource); ProjectActionCaptor.removeListener(projectActionSource); } }); if (instance != null) { instance.closeImpl(); instance = null; } if (instance != null) { instance.closeImpl(); instance = null; } if (instance != null) { instance.closeImpl(); instance = null; } }
private void closeImpl() { TmcSwingUtilities.ensureEdt(new Runnable() { @Override public void run() { TmcEventBus.getDefault().post(new InvokedEvent("spyware_unloaded")); textInsertEventSource.close(); TmcEventBus.getDefault().unsubscribe(tmcEventBusSource); ProjectActionCaptor.removeListener(projectActionSource); } }); <DeepExtract> if (instance != null) { instance.closeImpl(); instance = null; } </DeepExtract> if (instance != null) { instance.closeImpl(); instance = null; } <DeepExtract> if (instance != null) { instance.closeImpl(); instance = null; } </DeepExtract> }
tmc-netbeans
positive
2,921
@Override public <T> List<T> getExtractByInterClassOfMain(Class<T> interfaceClass) { if (interfaceClass == null) { return Collections.emptyList(); } List<ExtractWrapper> extracts = new ArrayList<>(); Map<ExtractCoordinate, ExtractWrapper> extractCoordinateObjectMap = extractMap.get(MAIN_EXTRACT_KEY); if (extractCoordinateObjectMap == null || extractCoordinateObjectMap.isEmpty()) { return Collections.emptyList(); } for (ExtractWrapper wrapper : extractCoordinateObjectMap.values()) { Object object = wrapper.getObject(); Set<Class<?>> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(object.getClass()); if (allInterfacesForClassAsSet.contains(interfaceClass)) { extracts.add(wrapper); } } return sort(extracts); }
@Override public <T> List<T> getExtractByInterClassOfMain(Class<T> interfaceClass) { <DeepExtract> if (interfaceClass == null) { return Collections.emptyList(); } List<ExtractWrapper> extracts = new ArrayList<>(); Map<ExtractCoordinate, ExtractWrapper> extractCoordinateObjectMap = extractMap.get(MAIN_EXTRACT_KEY); if (extractCoordinateObjectMap == null || extractCoordinateObjectMap.isEmpty()) { return Collections.emptyList(); } for (ExtractWrapper wrapper : extractCoordinateObjectMap.values()) { Object object = wrapper.getObject(); Set<Class<?>> allInterfacesForClassAsSet = ClassUtils.getAllInterfacesForClassAsSet(object.getClass()); if (allInterfacesForClassAsSet.contains(interfaceClass)) { extracts.add(wrapper); } } return sort(extracts); </DeepExtract> }
springboot-plugin-framework-parent
positive
2,922
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); Utils.themeInit(this); setContentView(R.layout.activity_credits_show); getActionBar().setDisplayHomeAsUpEnabled(true); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); Utils.themeInit(this); setContentView(R.layout.activity_credits_show); <DeepExtract> getActionBar().setDisplayHomeAsUpEnabled(true); </DeepExtract> }
ytdownloader-2
positive
2,923
@Test public void testAllOf() { MyAssertions.assertThat((s1, s2) -> allOf(s1, s2).apply(numberSchema(), intSchema()).toJson()).extractingKey("allOf").containsItemSatisfying(i -> MyAssertions.assertThatJson(i).containsEntry("type", "number")).containsItemSatisfying(i -> MyAssertions.assertThatJson(i).containsEntry("type", "integer")); }
@Test public void testAllOf() { <DeepExtract> MyAssertions.assertThat((s1, s2) -> allOf(s1, s2).apply(numberSchema(), intSchema()).toJson()).extractingKey("allOf").containsItemSatisfying(i -> MyAssertions.assertThatJson(i).containsEntry("type", "number")).containsItemSatisfying(i -> MyAssertions.assertThatJson(i).containsEntry("type", "integer")); </DeepExtract> }
vertx-json-schema
positive
2,924
private void generateTrunk() { int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(this.slopeChance); int zPreference = this.randGenerator.nextInt(this.slopeChance); int xDirection = 1; if (this.randGenerator.nextInt(100) < 50) { xDirection = -1; } int zDirection = 1; if (this.randGenerator.nextInt(100) < 50) { zDirection = -1; } int height = this.randGenerator.nextInt(this.heightMaximum - this.heightMinimum + 1) + this.heightMinimum; int twistChance = 5; for (int p = 0; p < height; p++) { if (p > 3) { if (this.randGenerator.nextInt(100) <= twistChance) { xDirection *= -1; } if (this.randGenerator.nextInt(100) <= twistChance) { zDirection *= -1; } if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += xDirection; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += zDirection; } } this.createTrunk(); this.blockPositionY += 1; } int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(60) + 20; int zPreference = this.randGenerator.nextInt(60) + 20; for (int r = 0; r < this.branchLength; r++) { if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += 1; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += 1; } if (Math.abs(r % 2) == 1) { this.blockPositionY += this.randGenerator.nextInt(2); } if (!Tag.LOGS.isTagged(getBlockType(this.blockPositionX, this.blockPositionY, this.blockPositionZ))) { this.undo.put(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ).setType(this.woodType, false); this.branchBlocks.add(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } this.blockPositionX = originX; this.blockPositionY = originY; this.blockPositionZ = originZ; int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(60) + 20; int zPreference = this.randGenerator.nextInt(60) + 20; for (int r = 0; r < this.branchLength; r++) { if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += -1; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += 1; } if (Math.abs(r % 2) == 1) { this.blockPositionY += this.randGenerator.nextInt(2); } if (!Tag.LOGS.isTagged(getBlockType(this.blockPositionX, this.blockPositionY, this.blockPositionZ))) { this.undo.put(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ).setType(this.woodType, false); this.branchBlocks.add(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } this.blockPositionX = originX; this.blockPositionY = originY; this.blockPositionZ = originZ; int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(60) + 20; int zPreference = this.randGenerator.nextInt(60) + 20; for (int r = 0; r < this.branchLength; r++) { if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += 1; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += -1; } if (Math.abs(r % 2) == 1) { this.blockPositionY += this.randGenerator.nextInt(2); } if (!Tag.LOGS.isTagged(getBlockType(this.blockPositionX, this.blockPositionY, this.blockPositionZ))) { this.undo.put(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ).setType(this.woodType, false); this.branchBlocks.add(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } this.blockPositionX = originX; this.blockPositionY = originY; this.blockPositionZ = originZ; int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(60) + 20; int zPreference = this.randGenerator.nextInt(60) + 20; for (int r = 0; r < this.branchLength; r++) { if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += -1; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += -1; } if (Math.abs(r % 2) == 1) { this.blockPositionY += this.randGenerator.nextInt(2); } if (!Tag.LOGS.isTagged(getBlockType(this.blockPositionX, this.blockPositionY, this.blockPositionZ))) { this.undo.put(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ).setType(this.woodType, false); this.branchBlocks.add(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } this.blockPositionX = originX; this.blockPositionY = originY; this.blockPositionZ = originZ; this.blockPositionX = originX; this.blockPositionY = originY + 4; this.blockPositionZ = originZ; int nextXPreference = this.randGenerator.nextInt(this.slopeChance); int nextZPreference = this.randGenerator.nextInt(this.slopeChance); int nextXDirection = 1; if (this.randGenerator.nextInt(100) < 50) { nextXDirection = -1; } int nextZDirection = 1; if (this.randGenerator.nextInt(100) < 50) { nextZDirection = -1; } int nextHeight = this.randGenerator.nextInt(this.heightMaximum - this.heightMinimum + 1) + this.heightMinimum; if (nextHeight > 4) { for (int p = 0; p < nextHeight; p++) { if (this.randGenerator.nextInt(100) <= twistChance) { nextXDirection *= -1; } if (this.randGenerator.nextInt(100) <= twistChance) { nextZDirection *= -1; } if (this.randGenerator.nextInt(100) < nextXPreference) { this.blockPositionX += nextXDirection; } if (this.randGenerator.nextInt(100) < nextZPreference) { this.blockPositionZ += nextZDirection; } this.createTrunk(); this.blockPositionY += 1; } createBranch(1, 1); createBranch(-1, 1); createBranch(1, -1); createBranch(-1, -1); } }
private void generateTrunk() { int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(this.slopeChance); int zPreference = this.randGenerator.nextInt(this.slopeChance); int xDirection = 1; if (this.randGenerator.nextInt(100) < 50) { xDirection = -1; } int zDirection = 1; if (this.randGenerator.nextInt(100) < 50) { zDirection = -1; } int height = this.randGenerator.nextInt(this.heightMaximum - this.heightMinimum + 1) + this.heightMinimum; int twistChance = 5; for (int p = 0; p < height; p++) { if (p > 3) { if (this.randGenerator.nextInt(100) <= twistChance) { xDirection *= -1; } if (this.randGenerator.nextInt(100) <= twistChance) { zDirection *= -1; } if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += xDirection; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += zDirection; } } this.createTrunk(); this.blockPositionY += 1; } int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(60) + 20; int zPreference = this.randGenerator.nextInt(60) + 20; for (int r = 0; r < this.branchLength; r++) { if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += 1; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += 1; } if (Math.abs(r % 2) == 1) { this.blockPositionY += this.randGenerator.nextInt(2); } if (!Tag.LOGS.isTagged(getBlockType(this.blockPositionX, this.blockPositionY, this.blockPositionZ))) { this.undo.put(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ).setType(this.woodType, false); this.branchBlocks.add(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } this.blockPositionX = originX; this.blockPositionY = originY; this.blockPositionZ = originZ; int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(60) + 20; int zPreference = this.randGenerator.nextInt(60) + 20; for (int r = 0; r < this.branchLength; r++) { if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += -1; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += 1; } if (Math.abs(r % 2) == 1) { this.blockPositionY += this.randGenerator.nextInt(2); } if (!Tag.LOGS.isTagged(getBlockType(this.blockPositionX, this.blockPositionY, this.blockPositionZ))) { this.undo.put(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ).setType(this.woodType, false); this.branchBlocks.add(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } this.blockPositionX = originX; this.blockPositionY = originY; this.blockPositionZ = originZ; int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(60) + 20; int zPreference = this.randGenerator.nextInt(60) + 20; for (int r = 0; r < this.branchLength; r++) { if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += 1; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += -1; } if (Math.abs(r % 2) == 1) { this.blockPositionY += this.randGenerator.nextInt(2); } if (!Tag.LOGS.isTagged(getBlockType(this.blockPositionX, this.blockPositionY, this.blockPositionZ))) { this.undo.put(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ).setType(this.woodType, false); this.branchBlocks.add(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } this.blockPositionX = originX; this.blockPositionY = originY; this.blockPositionZ = originZ; <DeepExtract> int originX = this.blockPositionX; int originY = this.blockPositionY; int originZ = this.blockPositionZ; int xPreference = this.randGenerator.nextInt(60) + 20; int zPreference = this.randGenerator.nextInt(60) + 20; for (int r = 0; r < this.branchLength; r++) { if (this.randGenerator.nextInt(100) < xPreference) { this.blockPositionX += -1; } if (this.randGenerator.nextInt(100) < zPreference) { this.blockPositionZ += -1; } if (Math.abs(r % 2) == 1) { this.blockPositionY += this.randGenerator.nextInt(2); } if (!Tag.LOGS.isTagged(getBlockType(this.blockPositionX, this.blockPositionY, this.blockPositionZ))) { this.undo.put(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ).setType(this.woodType, false); this.branchBlocks.add(clampY(this.blockPositionX, this.blockPositionY, this.blockPositionZ)); } this.blockPositionX = originX; this.blockPositionY = originY; this.blockPositionZ = originZ; </DeepExtract> this.blockPositionX = originX; this.blockPositionY = originY + 4; this.blockPositionZ = originZ; int nextXPreference = this.randGenerator.nextInt(this.slopeChance); int nextZPreference = this.randGenerator.nextInt(this.slopeChance); int nextXDirection = 1; if (this.randGenerator.nextInt(100) < 50) { nextXDirection = -1; } int nextZDirection = 1; if (this.randGenerator.nextInt(100) < 50) { nextZDirection = -1; } int nextHeight = this.randGenerator.nextInt(this.heightMaximum - this.heightMinimum + 1) + this.heightMinimum; if (nextHeight > 4) { for (int p = 0; p < nextHeight; p++) { if (this.randGenerator.nextInt(100) <= twistChance) { nextXDirection *= -1; } if (this.randGenerator.nextInt(100) <= twistChance) { nextZDirection *= -1; } if (this.randGenerator.nextInt(100) < nextXPreference) { this.blockPositionX += nextXDirection; } if (this.randGenerator.nextInt(100) < nextZPreference) { this.blockPositionZ += nextZDirection; } this.createTrunk(); this.blockPositionY += 1; } createBranch(1, 1); createBranch(-1, 1); createBranch(1, -1); createBranch(-1, -1); } }
FastAsyncVoxelSniper
positive
2,928
private void display() { assert isInitialized() : controlId; assert !isEnabled() : controlId; getElement().setVisible(true); if (!isInitialized()) { this.startEnabled = true; return; } if (true && !isEnabled()) { display(); } else if (!true && isEnabled()) { hide(); } }
private void display() { assert isInitialized() : controlId; assert !isEnabled() : controlId; getElement().setVisible(true); <DeepExtract> if (!isInitialized()) { this.startEnabled = true; return; } if (true && !isEnabled()) { display(); } else if (!true && isEnabled()) { hide(); } </DeepExtract> }
jme3-utilities
positive
2,929
@Override public void onCreate() { super.onCreate(); DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build(); ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(getApplicationContext()).defaultDisplayImageOptions(defaultOptions).build(); ImageLoader.getInstance().init(configuration); Douban.init(getApplicationContext()); instance = this; }
@Override public void onCreate() { super.onCreate(); <DeepExtract> DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build(); ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(getApplicationContext()).defaultDisplayImageOptions(defaultOptions).build(); ImageLoader.getInstance().init(configuration); </DeepExtract> Douban.init(getApplicationContext()); instance = this; }
Douban-FM-sdk
positive
2,931
@Test public void shouldParseConfigWithMissingArtifactAndListOfValidatedArtifacts() { initAppContext("/TestBomDependencyNotFoundFilterParser-missingArtifactWithListOfValidated.xml"); assertNumberOfBeansWithType(ExceptionFilter.class, 2); List<BomDependencyNotFoundExceptionFilter> filters = getAllMatchingBeans(BomDependencyNotFoundExceptionFilter.class); assertFalse("No filters with specified type found!", filters.isEmpty()); for (DependencyNotFoundExceptionFilter filter : filters) { if ("org.kie:kie-parent:pom:.*" == null) { if ("org.drools:drools-core:jar:.*".equals(filter.getMissingArtifactRegex()) && filter.getValidatedArtifactRegex() == null) { return; } } else { if ("org.drools:drools-core:jar:.*".equals(filter.getMissingArtifactRegex()) && "org.kie:kie-parent:pom:.*".equals(filter.getValidatedArtifactRegex())) { return; } } } fail("Filter with missing-artifact='" + "org.drools:drools-core:jar:.*" + "' and validated-artifact='" + "org.kie:kie-parent:pom:.*" + "' not found!"); for (DependencyNotFoundExceptionFilter filter : filters) { if ("org.acme:acme-parent:pom:.*" == null) { if ("org.drools:drools-core:jar:.*".equals(filter.getMissingArtifactRegex()) && filter.getValidatedArtifactRegex() == null) { return; } } else { if ("org.drools:drools-core:jar:.*".equals(filter.getMissingArtifactRegex()) && "org.acme:acme-parent:pom:.*".equals(filter.getValidatedArtifactRegex())) { return; } } } fail("Filter with missing-artifact='" + "org.drools:drools-core:jar:.*" + "' and validated-artifact='" + "org.acme:acme-parent:pom:.*" + "' not found!"); }
@Test public void shouldParseConfigWithMissingArtifactAndListOfValidatedArtifacts() { initAppContext("/TestBomDependencyNotFoundFilterParser-missingArtifactWithListOfValidated.xml"); assertNumberOfBeansWithType(ExceptionFilter.class, 2); List<BomDependencyNotFoundExceptionFilter> filters = getAllMatchingBeans(BomDependencyNotFoundExceptionFilter.class); assertFalse("No filters with specified type found!", filters.isEmpty()); for (DependencyNotFoundExceptionFilter filter : filters) { if ("org.kie:kie-parent:pom:.*" == null) { if ("org.drools:drools-core:jar:.*".equals(filter.getMissingArtifactRegex()) && filter.getValidatedArtifactRegex() == null) { return; } } else { if ("org.drools:drools-core:jar:.*".equals(filter.getMissingArtifactRegex()) && "org.kie:kie-parent:pom:.*".equals(filter.getValidatedArtifactRegex())) { return; } } } fail("Filter with missing-artifact='" + "org.drools:drools-core:jar:.*" + "' and validated-artifact='" + "org.kie:kie-parent:pom:.*" + "' not found!"); <DeepExtract> for (DependencyNotFoundExceptionFilter filter : filters) { if ("org.acme:acme-parent:pom:.*" == null) { if ("org.drools:drools-core:jar:.*".equals(filter.getMissingArtifactRegex()) && filter.getValidatedArtifactRegex() == null) { return; } } else { if ("org.drools:drools-core:jar:.*".equals(filter.getMissingArtifactRegex()) && "org.acme:acme-parent:pom:.*".equals(filter.getValidatedArtifactRegex())) { return; } } } fail("Filter with missing-artifact='" + "org.drools:drools-core:jar:.*" + "' and validated-artifact='" + "org.acme:acme-parent:pom:.*" + "' not found!"); </DeepExtract> }
redhat-repository-validator
positive
2,932
private JSONWriter end(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != mode) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; }
private JSONWriter end(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } <DeepExtract> if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != mode) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; </DeepExtract> try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; }
TTMS
positive
2,933
public BySelector desc(Pattern contentDescription) { if (contentDescription == null) { throw new NullPointerException("contentDescription cannot be null"); } return contentDescription; if (mDesc != null) { throw new IllegalStateException("Description selector is already defined"); } mDesc = contentDescription; return this; }
public BySelector desc(Pattern contentDescription) { <DeepExtract> if (contentDescription == null) { throw new NullPointerException("contentDescription cannot be null"); } return contentDescription; </DeepExtract> if (mDesc != null) { throw new IllegalStateException("Description selector is already defined"); } mDesc = contentDescription; return this; }
za-Farmer
positive
2,935
public Criteria andCollegeidLessThan(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "collegeid" + " cannot be null"); } criteria.add(new Criterion("collegeID <", value)); return (Criteria) this; }
public Criteria andCollegeidLessThan(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "collegeid" + " cannot be null"); } criteria.add(new Criterion("collegeID <", value)); </DeepExtract> return (Criteria) this; }
Examination_System
positive
2,939
public static void clear(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } editor.commit(); }
public static void clear(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); <DeepExtract> try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } editor.commit(); </DeepExtract> }
shop-front-android
positive
2,941
public boolean asBoolean(ExpressionContext context) throws ExpressionEvaluationException { Object o; try { o = MVEL.executeExpression(compiledExpression, context.asMap()); } catch (Exception e) { throw new ExpressionEvaluationException("Error evaluating exception on line: " + line + ", column: " + col + ", expression: " + expression, e); } if (o instanceof Boolean) { return (Boolean) o; } if (o instanceof Number) { return ((Number) o).intValue() != 0; } return o instanceof String && !"".equals(o); }
public boolean asBoolean(ExpressionContext context) throws ExpressionEvaluationException { <DeepExtract> Object o; try { o = MVEL.executeExpression(compiledExpression, context.asMap()); } catch (Exception e) { throw new ExpressionEvaluationException("Error evaluating exception on line: " + line + ", column: " + col + ", expression: " + expression, e); } </DeepExtract> if (o instanceof Boolean) { return (Boolean) o; } if (o instanceof Number) { return ((Number) o).intValue() != 0; } return o instanceof String && !"".equals(o); }
Cambridge
positive
2,942
@Benchmark public RTree<Object, Point> defaultRTreeInsertOneEntryIntoGreekDataEntriesMaxChildren128() { if (precision == Precision.DOUBLE) { return defaultTreeM128.add(new Object(), Geometries.point(Math.random() * 1000, Math.random() * 1000)); } else { return defaultTreeM128.add(new Object(), Geometries.point((float) Math.random() * 1000, (float) Math.random() * 1000)); } }
@Benchmark public RTree<Object, Point> defaultRTreeInsertOneEntryIntoGreekDataEntriesMaxChildren128() { <DeepExtract> if (precision == Precision.DOUBLE) { return defaultTreeM128.add(new Object(), Geometries.point(Math.random() * 1000, Math.random() * 1000)); } else { return defaultTreeM128.add(new Object(), Geometries.point((float) Math.random() * 1000, (float) Math.random() * 1000)); } </DeepExtract> }
rtree
positive
2,943
default PubSubSubscription listenForCheerEvents(OAuth2Credential credential, String channelId) { PubSubRequest request = new PubSubRequest(); request.setType(PubSubType.LISTEN); request.setNonce(CryptoUtils.generateNonce(30)); request.getData().put("auth_token", credential != null ? credential.getAccessToken() : ""); request.getData().put("topics", "channel-bits-events-v2." + channelId); return listenOnTopic(request); }
default PubSubSubscription listenForCheerEvents(OAuth2Credential credential, String channelId) { <DeepExtract> PubSubRequest request = new PubSubRequest(); request.setType(PubSubType.LISTEN); request.setNonce(CryptoUtils.generateNonce(30)); request.getData().put("auth_token", credential != null ? credential.getAccessToken() : ""); request.getData().put("topics", "channel-bits-events-v2." + channelId); return listenOnTopic(request); </DeepExtract> }
twitch4j
positive
2,944
public JSONWriter value(Object object) throws JSONException { if (JSONObject.valueToString(object) == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(JSONObject.valueToString(object)); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
public JSONWriter value(Object object) throws JSONException { <DeepExtract> if (JSONObject.valueToString(object) == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(JSONObject.valueToString(object)); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); </DeepExtract> }
Longan
positive
2,945
@Override public void run() { if (mScanning) { mScanning = false; if (isEnable() && mBluetoothAdapter != null && mLeScanCallback != null) { mBluetoothAdapter.stopLeScan(mLeScanCallback); } } }
@Override public void run() { <DeepExtract> if (mScanning) { mScanning = false; if (isEnable() && mBluetoothAdapter != null && mLeScanCallback != null) { mBluetoothAdapter.stopLeScan(mLeScanCallback); } } </DeepExtract> }
BaseLibrary
positive
2,946
private void showToolbar() { float headerTranslationY = ViewHelper.getTranslationY(mHeaderView); if (headerTranslationY != 0) { ViewPropertyAnimator.animate(mHeaderView).cancel(); ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start(); } int toolbarHeight = mToolbarView.getHeight(); mPagerAdapter.setScrollY(true ? 0 : toolbarHeight); for (int i = 0; i < mPagerAdapter.getCount(); i++) { if (i == mPager.getCurrentItem()) { continue; } Fragment f = mPagerAdapter.getItemAt(i); if (f == null) { continue; } View view = f.getView(); if (view == null) { continue; } ObservableScrollView scrollView = (ObservableScrollView) view.findViewById(R.id.scroll); if (true) { if (0 < scrollView.getCurrentScrollY()) { scrollView.scrollTo(0, 0); } } else { if (scrollView.getCurrentScrollY() < toolbarHeight) { scrollView.scrollTo(0, toolbarHeight); } } } }
private void showToolbar() { float headerTranslationY = ViewHelper.getTranslationY(mHeaderView); if (headerTranslationY != 0) { ViewPropertyAnimator.animate(mHeaderView).cancel(); ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start(); } <DeepExtract> int toolbarHeight = mToolbarView.getHeight(); mPagerAdapter.setScrollY(true ? 0 : toolbarHeight); for (int i = 0; i < mPagerAdapter.getCount(); i++) { if (i == mPager.getCurrentItem()) { continue; } Fragment f = mPagerAdapter.getItemAt(i); if (f == null) { continue; } View view = f.getView(); if (view == null) { continue; } ObservableScrollView scrollView = (ObservableScrollView) view.findViewById(R.id.scroll); if (true) { if (0 < scrollView.getCurrentScrollY()) { scrollView.scrollTo(0, 0); } } else { if (scrollView.getCurrentScrollY() < toolbarHeight) { scrollView.scrollTo(0, toolbarHeight); } } } </DeepExtract> }
Android-ObservableScrollView
positive
2,947
public Boolean visit(final EndsWithFilter filter, final JsonNode object) throws ScimException { Iterable<JsonNode> nodes = getCandidateNodes(filter.getAttributePath(), object); for (JsonNode node : nodes) { if (node.isTextual() && filter.getComparisonValue().isTextual()) { AttributeDefinition attributeDefinition = getAttributeDefinition(filter.getAttributePath()); String nodeValue = node.textValue(); String comparisonValue = filter.getComparisonValue().textValue(); if (attributeDefinition == null || !attributeDefinition.isCaseExact()) { nodeValue = StaticUtils.toLowerCase(nodeValue); comparisonValue = StaticUtils.toLowerCase(comparisonValue); } switch(filter.getFilterType()) { case CONTAINS: if (nodeValue.contains(comparisonValue)) { return true; } break; case STARTS_WITH: if (nodeValue.startsWith(comparisonValue)) { return true; } break; case ENDS_WITH: if (nodeValue.endsWith(comparisonValue)) { return true; } break; } } else if (node.equals(filter.getComparisonValue())) { return true; } } return false; }
public Boolean visit(final EndsWithFilter filter, final JsonNode object) throws ScimException { <DeepExtract> Iterable<JsonNode> nodes = getCandidateNodes(filter.getAttributePath(), object); for (JsonNode node : nodes) { if (node.isTextual() && filter.getComparisonValue().isTextual()) { AttributeDefinition attributeDefinition = getAttributeDefinition(filter.getAttributePath()); String nodeValue = node.textValue(); String comparisonValue = filter.getComparisonValue().textValue(); if (attributeDefinition == null || !attributeDefinition.isCaseExact()) { nodeValue = StaticUtils.toLowerCase(nodeValue); comparisonValue = StaticUtils.toLowerCase(comparisonValue); } switch(filter.getFilterType()) { case CONTAINS: if (nodeValue.contains(comparisonValue)) { return true; } break; case STARTS_WITH: if (nodeValue.startsWith(comparisonValue)) { return true; } break; case ENDS_WITH: if (nodeValue.endsWith(comparisonValue)) { return true; } break; } } else if (node.equals(filter.getComparisonValue())) { return true; } } return false; </DeepExtract> }
scim2
positive
2,948
@ParameterizedTest @MethodSource("fromDtoToModelTestCases") @DisplayName("fromDtoToModel: when the given dto is not null then the equivalent model is returned") public void fromDtoToModel_whenGivenDtoIsNotNull_thenEquivalentModelIsReturned(OrderDto dtoToConvert) { Order equivalentModel = converter.fromDtoToModel(dtoToConvert); assertNotNull(equivalentModel); assertNotNull(dtoToConvert); assertEquals(equivalentModel.getId(), dtoToConvert.getId()); assertEquals(equivalentModel.getCode(), dtoToConvert.getCode()); if (null != equivalentModel.getCreated()) { assertEquals(equivalentModel.getCreated().getTime(), dtoToConvert.getCreated().getTime()); } }
@ParameterizedTest @MethodSource("fromDtoToModelTestCases") @DisplayName("fromDtoToModel: when the given dto is not null then the equivalent model is returned") public void fromDtoToModel_whenGivenDtoIsNotNull_thenEquivalentModelIsReturned(OrderDto dtoToConvert) { Order equivalentModel = converter.fromDtoToModel(dtoToConvert); <DeepExtract> assertNotNull(equivalentModel); assertNotNull(dtoToConvert); assertEquals(equivalentModel.getId(), dtoToConvert.getId()); assertEquals(equivalentModel.getCode(), dtoToConvert.getCode()); if (null != equivalentModel.getCreated()) { assertEquals(equivalentModel.getCreated().getTime(), dtoToConvert.getCreated().getTime()); } </DeepExtract> }
Spring5Microservices
positive
2,950
private excepthandlerType astForExceptClause(Node exc, Node body) { try { assert (exc.dfaType == DFAType.except_clause); } catch (PyExceptions e) { throw new PyExceptions(ErrorType.AST_ERROR, "AST Error", exc); } try { assert (body.dfaType == DFAType.suite); } catch (PyExceptions e) { throw new PyExceptions(ErrorType.AST_ERROR, "AST Error", body); } if (exc.nChild() == 1) { java.util.List<stmtType> suiteSeq = astForSuite(body); return new ExceptHandler(null, null, suiteSeq, exc.lineNo, exc.colOffset); } else if (exc.nChild() == 2) { exprType expression = astForExpr(exc.getChild(1)); java.util.List<stmtType> suiteSeq = astForSuite(body); return new ExceptHandler(expression, null, suiteSeq, exc.lineNo, exc.colOffset); } else if (exc.nChild() == 4) { String e = newIdentifier(exc.getChild(3)); forbiddenName(e, exc.getChild(3), false); exprType expression = astForExpr(exc.getChild(1)); java.util.List<stmtType> suiteSeq = astForSuite(body); return new ExceptHandler(expression, e, suiteSeq, exc.lineNo, exc.colOffset); } throw new PyExceptions(ErrorType.AST_ERROR, "wrong number of children for 'except' clause: " + exc.nChild(), exc); }
private excepthandlerType astForExceptClause(Node exc, Node body) { try { assert (exc.dfaType == DFAType.except_clause); } catch (PyExceptions e) { throw new PyExceptions(ErrorType.AST_ERROR, "AST Error", exc); } <DeepExtract> try { assert (body.dfaType == DFAType.suite); } catch (PyExceptions e) { throw new PyExceptions(ErrorType.AST_ERROR, "AST Error", body); } </DeepExtract> if (exc.nChild() == 1) { java.util.List<stmtType> suiteSeq = astForSuite(body); return new ExceptHandler(null, null, suiteSeq, exc.lineNo, exc.colOffset); } else if (exc.nChild() == 2) { exprType expression = astForExpr(exc.getChild(1)); java.util.List<stmtType> suiteSeq = astForSuite(body); return new ExceptHandler(expression, null, suiteSeq, exc.lineNo, exc.colOffset); } else if (exc.nChild() == 4) { String e = newIdentifier(exc.getChild(3)); forbiddenName(e, exc.getChild(3), false); exprType expression = astForExpr(exc.getChild(1)); java.util.List<stmtType> suiteSeq = astForSuite(body); return new ExceptHandler(expression, e, suiteSeq, exc.lineNo, exc.colOffset); } throw new PyExceptions(ErrorType.AST_ERROR, "wrong number of children for 'except' clause: " + exc.nChild(), exc); }
JPython
positive
2,952
public Criteria andNameLike(String value) { if (value == null) { throw new RuntimeException("Value for " + "name" + " cannot be null"); } criteria.add(new Criterion("name like", value)); return (Criteria) this; }
public Criteria andNameLike(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "name" + " cannot be null"); } criteria.add(new Criterion("name like", value)); </DeepExtract> return (Criteria) this; }
Online_Study_System
positive
2,953
@Override public void onUIRefreshComplete() { mReleasePos = getCurrentPosY(); if (isUnderTouch()) { mReleasePercent = mCurrentDragPercent; } else { if (mReleasePercent <= 0) { mReleasePercent = 1.0f * getCurrentPosY() / getOffsetToKeepHeaderWhileLoading(); } mReleasePercent = mReleasePercent * getCurrentPosY() / mReleasePos; } }
@Override public void onUIRefreshComplete() { mReleasePos = getCurrentPosY(); <DeepExtract> if (isUnderTouch()) { mReleasePercent = mCurrentDragPercent; } else { if (mReleasePercent <= 0) { mReleasePercent = 1.0f * getCurrentPosY() / getOffsetToKeepHeaderWhileLoading(); } mReleasePercent = mReleasePercent * getCurrentPosY() / mReleasePos; } </DeepExtract> }
cygmodule
positive
2,954
@Test public void shouldBuildPythonFunctionWithDependenciesWithDocker() { GenericContainer genericContainer = startAndGetContainer(greengrassITShared.getLifxDeploymentCommand(Optional.empty())); waitForContainerToFinish(genericContainer); System.out.println(genericContainer.getLogs()); MatcherAssert.assertThat(genericContainer.getCurrentContainerInfo().getState().getExitCode(), is(EXIT_CODE_IS_ZERO)); return genericContainer; }
@Test public void shouldBuildPythonFunctionWithDependenciesWithDocker() { <DeepExtract> GenericContainer genericContainer = startAndGetContainer(greengrassITShared.getLifxDeploymentCommand(Optional.empty())); waitForContainerToFinish(genericContainer); System.out.println(genericContainer.getLogs()); MatcherAssert.assertThat(genericContainer.getCurrentContainerInfo().getState().getExitCode(), is(EXIT_CODE_IS_ZERO)); return genericContainer; </DeepExtract> }
aws-greengrass-provisioner
positive
2,955
@Test(description = "Test for empty form submission") public void emptyFormTest() { firstNameField.clear(); lastNameField.clear(); emailField.clear(); userNameField.clear(); firstNameField.sendKeys(""); lastNameField.sendKeys(""); emailField.sendKeys(""); userNameField.sendKeys(""); addUserButton.click(); WebElement alert = driver.findElement(By.xpath(uiElementMapper.getElement("iot.admin.addUser.formError.xpath"))); if (!alert.isDisplayed()) { Assert.assertTrue(false, "Alert for empty form not is displayed."); } Assert.assertEquals(alert.getText(), "Username is a required field. It cannot be empty."); }
@Test(description = "Test for empty form submission") public void emptyFormTest() { <DeepExtract> firstNameField.clear(); lastNameField.clear(); emailField.clear(); userNameField.clear(); </DeepExtract> firstNameField.sendKeys(""); lastNameField.sendKeys(""); emailField.sendKeys(""); userNameField.sendKeys(""); addUserButton.click(); WebElement alert = driver.findElement(By.xpath(uiElementMapper.getElement("iot.admin.addUser.formError.xpath"))); if (!alert.isDisplayed()) { Assert.assertTrue(false, "Alert for empty form not is displayed."); } Assert.assertEquals(alert.getText(), "Username is a required field. It cannot be empty."); }
product-iots
positive
2,956
@Test public void testParse_PHP() throws ParseException { final DateFormat dateFormat = new CompositeDateFormat(); final double delta = date.getTime() - dateFormat.parse("Thu March 07 21:26:05 GMT-05:00 2013").getTime(); final String msg = "expected=" + date + " actual=" + dateFormat.parse("Thu March 07 21:26:05 GMT-05:00 2013") + " delta=" + delta; Assert.assertTrue(msg, Math.abs(delta) < 1000); final double delta = date.getTime() - dateFormat.parse("Fri March 08 02:26:05 GMT 2013").getTime(); final String msg = "expected=" + date + " actual=" + dateFormat.parse("Fri March 08 02:26:05 GMT 2013") + " delta=" + delta; Assert.assertTrue(msg, Math.abs(delta) < 1000); }
@Test public void testParse_PHP() throws ParseException { final DateFormat dateFormat = new CompositeDateFormat(); final double delta = date.getTime() - dateFormat.parse("Thu March 07 21:26:05 GMT-05:00 2013").getTime(); final String msg = "expected=" + date + " actual=" + dateFormat.parse("Thu March 07 21:26:05 GMT-05:00 2013") + " delta=" + delta; Assert.assertTrue(msg, Math.abs(delta) < 1000); <DeepExtract> final double delta = date.getTime() - dateFormat.parse("Fri March 08 02:26:05 GMT 2013").getTime(); final String msg = "expected=" + date + " actual=" + dateFormat.parse("Fri March 08 02:26:05 GMT 2013") + " delta=" + delta; Assert.assertTrue(msg, Math.abs(delta) < 1000); </DeepExtract> }
jesque
positive
2,958
public Criteria andXmGreaterThanOrEqualTo(String value) { if (value == null) { throw new RuntimeException("Value for " + "xm" + " cannot be null"); } criteria.add(new Criterion("xm >=", value)); return (Criteria) this; }
public Criteria andXmGreaterThanOrEqualTo(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "xm" + " cannot be null"); } criteria.add(new Criterion("xm >=", value)); </DeepExtract> return (Criteria) this; }
PetStore
positive
2,959
public Criteria andApprovalEqualTo(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "approval" + " cannot be null"); } criteria.add(new Criterion("approval =", value)); return (Criteria) this; }
public Criteria andApprovalEqualTo(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "approval" + " cannot be null"); } criteria.add(new Criterion("approval =", value)); </DeepExtract> return (Criteria) this; }
webim
positive
2,960
@NotNull @Override public String getText() { return "Reverse arrow"; }
@NotNull @Override public String getText() { <DeepExtract> return "Reverse arrow"; </DeepExtract> }
plantuml4idea
positive
2,962
private File[] getFiles(File dir, String extension) { ArrayList<File> files = new ArrayList<>(); if (dir.isDirectory()) { System.out.println(" ~ searching dir: " + dir); for (File subfile : dir.listFiles()) { getFilesEmbedded(subfile, files, extension); } } if (dir.isFile() && dir.getPath().toLowerCase().endsWith(extension)) { files.add(dir); } File[] filearray = new File[files.size()]; for (int i = 0; i < files.size(); i++) { filearray[i] = files.get(i); } return filearray; }
private File[] getFiles(File dir, String extension) { ArrayList<File> files = new ArrayList<>(); <DeepExtract> if (dir.isDirectory()) { System.out.println(" ~ searching dir: " + dir); for (File subfile : dir.listFiles()) { getFilesEmbedded(subfile, files, extension); } } if (dir.isFile() && dir.getPath().toLowerCase().endsWith(extension)) { files.add(dir); } </DeepExtract> File[] filearray = new File[files.size()]; for (int i = 0; i < files.size(); i++) { filearray[i] = files.get(i); } return filearray; }
Jasmin
positive
2,963
public void changeItems(Collection<E> resources, int start, int before, int count) { items.clear(); items.addAll(resources); if (before == 0) { if (start == 0) { notifyDataSetChanged(); } else { notifyItemRangeInserted(start, count); } } else { if (before < count) { notifyItemRangeInserted(start + before, count - before); } if (before > count) { notifyItemRangeRemoved(start + count, before - count); } notifyItemRangeChanged(start, Math.min(before, count)); } }
public void changeItems(Collection<E> resources, int start, int before, int count) { items.clear(); items.addAll(resources); <DeepExtract> if (before == 0) { if (start == 0) { notifyDataSetChanged(); } else { notifyItemRangeInserted(start, count); } } else { if (before < count) { notifyItemRangeInserted(start + before, count - before); } if (before > count) { notifyItemRangeRemoved(start + count, before - count); } notifyItemRangeChanged(start, Math.min(before, count)); } </DeepExtract> }
Pioneer
positive
2,965
@Override public void onCreate() { super.onCreate(); App.instance = this; database = AppDatabase.getInstance(this); sharedPreferences = getSharedPreferences(Constants.APP_PREFERENCES, MODE_PRIVATE); File cacheFolder = new File(App.getInstance().getCacheDir(), "media"); int cacheSize = sharedPreferences.getInt(Constants.PREFERENCE_CACHE_SIZE, 250); LeastRecentlyUsedCacheEvictor cacheEvictor = new LeastRecentlyUsedCacheEvictor(cacheSize * 1000000); return new SimpleCache(cacheFolder, cacheEvictor); cachingTasksManager = new CachingTasksManager(); }
@Override public void onCreate() { super.onCreate(); App.instance = this; database = AppDatabase.getInstance(this); sharedPreferences = getSharedPreferences(Constants.APP_PREFERENCES, MODE_PRIVATE); <DeepExtract> File cacheFolder = new File(App.getInstance().getCacheDir(), "media"); int cacheSize = sharedPreferences.getInt(Constants.PREFERENCE_CACHE_SIZE, 250); LeastRecentlyUsedCacheEvictor cacheEvictor = new LeastRecentlyUsedCacheEvictor(cacheSize * 1000000); return new SimpleCache(cacheFolder, cacheEvictor); </DeepExtract> cachingTasksManager = new CachingTasksManager(); }
youtube-audio-player
positive
2,967
public StateListBuilder<V, T> multiline(V value) { states.add(android.R.attr.state_multiline); values.add(value); return this; }
public StateListBuilder<V, T> multiline(V value) { <DeepExtract> states.add(android.R.attr.state_multiline); values.add(value); return this; </DeepExtract> }
relight
positive
2,969
private void resetMatrix() { mSuppMatrix.reset(); ImageView imageView = getImageView(); if (null != imageView) { checkImageViewScaleType(); imageView.setImageMatrix(getDrawMatrix()); if (null != mMatrixChangeListener) { RectF displayRect = getDisplayRect(getDrawMatrix()); if (null != displayRect) { mMatrixChangeListener.onMatrixChanged(displayRect); } } } final ImageView imageView = getImageView(); if (null == imageView) { return false; } final RectF rect = getDisplayRect(getDrawMatrix()); if (null == rect) { return false; } final float height = rect.height(), width = rect.width(); float deltaX = 0, deltaY = 0; final int viewHeight = getImageViewHeight(imageView); if (height <= viewHeight) { switch(mScaleType) { case FIT_START: deltaY = -rect.top; break; case FIT_END: deltaY = viewHeight - height - rect.top; break; default: deltaY = (viewHeight - height) / 2 - rect.top; break; } } else if (rect.top > 0) { deltaY = -rect.top; } else if (rect.bottom < viewHeight) { deltaY = viewHeight - rect.bottom; } final int viewWidth = getImageViewWidth(imageView); if (width <= viewWidth) { switch(mScaleType) { case FIT_START: deltaX = -rect.left; break; case FIT_END: deltaX = viewWidth - width - rect.left; break; default: deltaX = (viewWidth - width) / 2 - rect.left; break; } mScrollEdge = EDGE_BOTH; } else if (rect.left > 0) { mScrollEdge = EDGE_LEFT; deltaX = -rect.left; } else if (rect.right < viewWidth) { deltaX = viewWidth - rect.right; mScrollEdge = EDGE_RIGHT; } else { mScrollEdge = EDGE_NONE; } mSuppMatrix.postTranslate(deltaX, deltaY); return true; }
private void resetMatrix() { mSuppMatrix.reset(); ImageView imageView = getImageView(); if (null != imageView) { checkImageViewScaleType(); imageView.setImageMatrix(getDrawMatrix()); if (null != mMatrixChangeListener) { RectF displayRect = getDisplayRect(getDrawMatrix()); if (null != displayRect) { mMatrixChangeListener.onMatrixChanged(displayRect); } } } <DeepExtract> final ImageView imageView = getImageView(); if (null == imageView) { return false; } final RectF rect = getDisplayRect(getDrawMatrix()); if (null == rect) { return false; } final float height = rect.height(), width = rect.width(); float deltaX = 0, deltaY = 0; final int viewHeight = getImageViewHeight(imageView); if (height <= viewHeight) { switch(mScaleType) { case FIT_START: deltaY = -rect.top; break; case FIT_END: deltaY = viewHeight - height - rect.top; break; default: deltaY = (viewHeight - height) / 2 - rect.top; break; } } else if (rect.top > 0) { deltaY = -rect.top; } else if (rect.bottom < viewHeight) { deltaY = viewHeight - rect.bottom; } final int viewWidth = getImageViewWidth(imageView); if (width <= viewWidth) { switch(mScaleType) { case FIT_START: deltaX = -rect.left; break; case FIT_END: deltaX = viewWidth - width - rect.left; break; default: deltaX = (viewWidth - width) / 2 - rect.left; break; } mScrollEdge = EDGE_BOTH; } else if (rect.left > 0) { mScrollEdge = EDGE_LEFT; deltaX = -rect.left; } else if (rect.right < viewWidth) { deltaX = viewWidth - rect.right; mScrollEdge = EDGE_RIGHT; } else { mScrollEdge = EDGE_NONE; } mSuppMatrix.postTranslate(deltaX, deltaY); return true; </DeepExtract> }
AppleFramework
positive
2,971
@Override public void onAnimationEnd(@NonNull final Animator animation) { mActiveDismissCount--; if (mActiveDismissCount == 0 && getActiveSwipeCount() == 0) { restoreViewPresentations(mDismissedViews); notifyCallback(mDismissedPositions); mDismissedViews.clear(); mDismissedPositions.clear(); } }
@Override public void onAnimationEnd(@NonNull final Animator animation) { mActiveDismissCount--; <DeepExtract> if (mActiveDismissCount == 0 && getActiveSwipeCount() == 0) { restoreViewPresentations(mDismissedViews); notifyCallback(mDismissedPositions); mDismissedViews.clear(); mDismissedPositions.clear(); } </DeepExtract> }
ListViewAnimations
positive
2,972
private View addViewBelow(View theView, int position) { int belowPosition = position + 1; DebugUtil.i("addViewBelow:" + position); View view = obtainView(belowPosition, mIsScrap); int edgeOfNewChild = theView.getBottom() + mDividerHeight; final boolean isSelected = false && shouldShowSelector(); final boolean updateChildSelected = isSelected != view.isSelected(); final int mode = mTouchMode; final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL && mMotionPosition == belowPosition; final boolean updateChildPressed = isPressed != view.isPressed(); final boolean needToMeasure = !mIsScrap[0] || updateChildSelected || view.isLayoutRequested(); PLA_AbsListView.LayoutParams p = (PLA_AbsListView.LayoutParams) view.getLayoutParams(); if (p == null) { p = new PLA_AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); } p.viewType = mAdapter.getItemViewType(belowPosition); p.scrappedFromPosition = belowPosition; if ((mIsScrap[0] && !p.forceAdd) || (p.recycledHeaderFooter && p.viewType == PLA_AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) { attachViewToParent(view, true ? -1 : 0, p); } else { p.forceAdd = false; if (p.viewType == PLA_AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) { p.recycledHeaderFooter = true; } addViewInLayout(view, true ? -1 : 0, p, true); } if (updateChildSelected) { view.setSelected(isSelected); } if (updateChildPressed) { view.setPressed(isPressed); } if (needToMeasure) { int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec, mListPadding.left + mListPadding.right, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } onMeasureChild(view, belowPosition, childWidthSpec, childHeightSpec); } else { cleanupLayoutState(view); } final int w = view.getMeasuredWidth(); final int h = view.getMeasuredHeight(); final int childTop = true ? edgeOfNewChild : edgeOfNewChild - h; if (needToMeasure) { final int childRight = mListPadding.left + w; final int childBottom = childTop + h; onLayoutChild(view, belowPosition, mListPadding.left, childTop, childRight, childBottom); } else { final int offsetLeft = mListPadding.left - view.getLeft(); final int offsetTop = childTop - view.getTop(); onOffsetChild(view, belowPosition, offsetLeft, offsetTop); } if (mCachingStarted && !view.isDrawingCacheEnabled()) { view.setDrawingCacheEnabled(true); } return view; }
private View addViewBelow(View theView, int position) { int belowPosition = position + 1; DebugUtil.i("addViewBelow:" + position); View view = obtainView(belowPosition, mIsScrap); int edgeOfNewChild = theView.getBottom() + mDividerHeight; <DeepExtract> final boolean isSelected = false && shouldShowSelector(); final boolean updateChildSelected = isSelected != view.isSelected(); final int mode = mTouchMode; final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL && mMotionPosition == belowPosition; final boolean updateChildPressed = isPressed != view.isPressed(); final boolean needToMeasure = !mIsScrap[0] || updateChildSelected || view.isLayoutRequested(); PLA_AbsListView.LayoutParams p = (PLA_AbsListView.LayoutParams) view.getLayoutParams(); if (p == null) { p = new PLA_AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); } p.viewType = mAdapter.getItemViewType(belowPosition); p.scrappedFromPosition = belowPosition; if ((mIsScrap[0] && !p.forceAdd) || (p.recycledHeaderFooter && p.viewType == PLA_AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) { attachViewToParent(view, true ? -1 : 0, p); } else { p.forceAdd = false; if (p.viewType == PLA_AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) { p.recycledHeaderFooter = true; } addViewInLayout(view, true ? -1 : 0, p, true); } if (updateChildSelected) { view.setSelected(isSelected); } if (updateChildPressed) { view.setPressed(isPressed); } if (needToMeasure) { int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec, mListPadding.left + mListPadding.right, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } onMeasureChild(view, belowPosition, childWidthSpec, childHeightSpec); } else { cleanupLayoutState(view); } final int w = view.getMeasuredWidth(); final int h = view.getMeasuredHeight(); final int childTop = true ? edgeOfNewChild : edgeOfNewChild - h; if (needToMeasure) { final int childRight = mListPadding.left + w; final int childBottom = childTop + h; onLayoutChild(view, belowPosition, mListPadding.left, childTop, childRight, childBottom); } else { final int offsetLeft = mListPadding.left - view.getLeft(); final int offsetTop = childTop - view.getTop(); onOffsetChild(view, belowPosition, offsetLeft, offsetTop); } if (mCachingStarted && !view.isDrawingCacheEnabled()) { view.setDrawingCacheEnabled(true); } </DeepExtract> return view; }
MoGuJie
positive
2,973
@Override protected void doStop() throws Exception { if (startConsumerCallable != null) { startConsumerCallable.stop(); } for (RabbitConsumer consumer : this.consumers) { try { consumer.stop(); } catch (TimeoutException e) { log.warn("Timeout occurred while stopping consumer. This exception is ignored", e); } } this.consumers.clear(); if (conn != null) { log.debug("Closing connection: {} with timeout: {} ms.", conn, closeTimeout); conn.close(closeTimeout); conn = null; } if (executor != null) { if (endpoint != null && endpoint.getCamelContext() != null) { endpoint.getCamelContext().getExecutorServiceManager().shutdownNow(executor); } else { executor.shutdownNow(); } executor = null; } }
@Override protected void doStop() throws Exception { <DeepExtract> if (startConsumerCallable != null) { startConsumerCallable.stop(); } for (RabbitConsumer consumer : this.consumers) { try { consumer.stop(); } catch (TimeoutException e) { log.warn("Timeout occurred while stopping consumer. This exception is ignored", e); } } this.consumers.clear(); if (conn != null) { log.debug("Closing connection: {} with timeout: {} ms.", conn, closeTimeout); conn.close(closeTimeout); conn = null; } </DeepExtract> if (executor != null) { if (endpoint != null && endpoint.getCamelContext() != null) { endpoint.getCamelContext().getExecutorServiceManager().shutdownNow(executor); } else { executor.shutdownNow(); } executor = null; } }
apibusinesshub-integration-recipes
positive
2,974
private int jjMoveStringLiteralDfa5_3(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_3(3, old0, 0L, 0L); try { curChar = input_stream.readChar(); } catch (java.io.IOException e) { jjStopStringLiteralDfa_3(4, active0, 0L, 0L); return 5; } switch(curChar) { case 99: return jjMoveStringLiteralDfa6_3(active0, 0x80000L); case 100: return jjMoveStringLiteralDfa6_3(active0, 0x400L); case 101: return jjMoveStringLiteralDfa6_3(active0, 0x800L); case 105: return jjMoveStringLiteralDfa6_3(active0, 0x200L); case 109: return jjMoveStringLiteralDfa6_3(active0, 0x1000L); case 111: return jjMoveStringLiteralDfa6_3(active0, 0x4000L); case 116: if ((active0 & 0x20000L) != 0L) return jjStopAtPos(5, 17); break; case 117: return jjMoveStringLiteralDfa6_3(active0, 0x8000L); default: break; } return jjMoveNfa_3(jjStopStringLiteralDfa_3(4, active0, 0L, 0L), 4 + 1); }
private int jjMoveStringLiteralDfa5_3(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_3(3, old0, 0L, 0L); try { curChar = input_stream.readChar(); } catch (java.io.IOException e) { jjStopStringLiteralDfa_3(4, active0, 0L, 0L); return 5; } switch(curChar) { case 99: return jjMoveStringLiteralDfa6_3(active0, 0x80000L); case 100: return jjMoveStringLiteralDfa6_3(active0, 0x400L); case 101: return jjMoveStringLiteralDfa6_3(active0, 0x800L); case 105: return jjMoveStringLiteralDfa6_3(active0, 0x200L); case 109: return jjMoveStringLiteralDfa6_3(active0, 0x1000L); case 111: return jjMoveStringLiteralDfa6_3(active0, 0x4000L); case 116: if ((active0 & 0x20000L) != 0L) return jjStopAtPos(5, 17); break; case 117: return jjMoveStringLiteralDfa6_3(active0, 0x8000L); default: break; } <DeepExtract> return jjMoveNfa_3(jjStopStringLiteralDfa_3(4, active0, 0L, 0L), 4 + 1); </DeepExtract> }
OXPath
positive
2,975
public String serialize(TreeNode root) { if (root == null) return ""; List<String> list = new ArrayList<>(); if (root != null) { list.add(String.valueOf(root.val)); preOrder(root.left, list); preOrder(root.right, list); } return String.join(",", list); }
public String serialize(TreeNode root) { if (root == null) return ""; List<String> list = new ArrayList<>(); <DeepExtract> if (root != null) { list.add(String.valueOf(root.val)); preOrder(root.left, list); preOrder(root.right, list); } </DeepExtract> return String.join(",", list); }
AlgoCS
positive
2,976
@Test public void testStaticRunTestOnContext() throws Exception { Result result; try { result = new JUnitCore().run(new VertxUnitRunner(StaticUseRunOnContextRule.class)); } catch (InitializationError initializationError) { throw new AssertionError(initializationError); } assertEquals(2, result.getRunCount()); assertEquals(0, result.getFailureCount()); for (String name : Arrays.asList("testMethod1", "testMethod2")) { Context methodCtx = StaticUseRunOnContextRule.method.get(name); Context beforeCtx = StaticUseRunOnContextRule.before.get(name); Context afterCtx = StaticUseRunOnContextRule.after.get(name); assertNotNull(methodCtx); assertSame(methodCtx, beforeCtx); assertSame(methodCtx, afterCtx); } assertSame(StaticUseRunOnContextRule.method.get("testMethod1"), StaticUseRunOnContextRule.method.get("testMethod2")); assertSame(StaticUseRunOnContextRule.beforeClass, StaticUseRunOnContextRule.method.get("testMethod1")); assertSame(StaticUseRunOnContextRule.afterClass, StaticUseRunOnContextRule.method.get("testMethod1")); }
@Test public void testStaticRunTestOnContext() throws Exception { <DeepExtract> Result result; try { result = new JUnitCore().run(new VertxUnitRunner(StaticUseRunOnContextRule.class)); } catch (InitializationError initializationError) { throw new AssertionError(initializationError); } </DeepExtract> assertEquals(2, result.getRunCount()); assertEquals(0, result.getFailureCount()); for (String name : Arrays.asList("testMethod1", "testMethod2")) { Context methodCtx = StaticUseRunOnContextRule.method.get(name); Context beforeCtx = StaticUseRunOnContextRule.before.get(name); Context afterCtx = StaticUseRunOnContextRule.after.get(name); assertNotNull(methodCtx); assertSame(methodCtx, beforeCtx); assertSame(methodCtx, afterCtx); } assertSame(StaticUseRunOnContextRule.method.get("testMethod1"), StaticUseRunOnContextRule.method.get("testMethod2")); assertSame(StaticUseRunOnContextRule.beforeClass, StaticUseRunOnContextRule.method.get("testMethod1")); assertSame(StaticUseRunOnContextRule.afterClass, StaticUseRunOnContextRule.method.get("testMethod1")); }
vertx-unit
positive
2,977
public Criteria andN_priorityLessThanOrEqualTo(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "n_priority" + " cannot be null"); } criteria.add(new Criterion("n_priority <=", value)); return (Criteria) this; }
public Criteria andN_priorityLessThanOrEqualTo(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "n_priority" + " cannot be null"); } criteria.add(new Criterion("n_priority <=", value)); </DeepExtract> return (Criteria) this; }
BaiChengNews
positive
2,978
public Criteria andMethodDescLessThan(String value) { if (value == null) { throw new RuntimeException("Value for " + "methodDesc" + " cannot be null"); } criteria.add(new Criterion("method_desc <", value)); return (Criteria) this; }
public Criteria andMethodDescLessThan(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "methodDesc" + " cannot be null"); } criteria.add(new Criterion("method_desc <", value)); </DeepExtract> return (Criteria) this; }
data-manage-parent
positive
2,979
public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo) { if (mVacantCache != null) { mVacantCache.clearVacantCells(); mVacantCache = null; } }
public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo) { <DeepExtract> if (mVacantCache != null) { mVacantCache.clearVacantCells(); mVacantCache = null; } </DeepExtract> }
Open-Launcher-for-GTV
positive
2,980
public int getTimePoint(double tTarget, int pStart) { int p, interval = pStart; if (timePoints == null) { timePoints = new double[timePointsList.size()]; for (int i = 0; i < timePointsList.size(); i++) { timePoints[i] = (double) (timePointsList.get(i)); } } return timePoints; int interval; if (pStart < 0) interval = 0; else if (pStart > numPoints - 2) interval = numPoints - 2; else interval = pStart; if (isAscending) { while ((interval >= 0) && (interval <= numPoints - 2)) { if (tTarget >= timePoints[interval + 1]) interval++; else if (tTarget < timePoints[interval]) interval--; else break; } } else { while ((interval >= 0) && (interval <= numPoints - 2)) { if (tTarget >= timePoints[interval]) interval--; else if (tTarget < timePoints[interval + 1]) interval++; else break; } } return interval; if (interval < 0) p = 0; else if (interval > numPoints - 2) { p = numPoints - 1; } else { p = interval; if (isAscending) { if ((tTarget - timePoints[interval]) > (timePoints[interval + 1] - tTarget)) p = interval + 1; } else { if ((tTarget - timePoints[interval + 1]) < (timePoints[interval] - tTarget)) p = interval + 1; } } return p; }
public int getTimePoint(double tTarget, int pStart) { int p, interval = pStart; if (timePoints == null) { timePoints = new double[timePointsList.size()]; for (int i = 0; i < timePointsList.size(); i++) { timePoints[i] = (double) (timePointsList.get(i)); } } return timePoints; <DeepExtract> int interval; if (pStart < 0) interval = 0; else if (pStart > numPoints - 2) interval = numPoints - 2; else interval = pStart; if (isAscending) { while ((interval >= 0) && (interval <= numPoints - 2)) { if (tTarget >= timePoints[interval + 1]) interval++; else if (tTarget < timePoints[interval]) interval--; else break; } } else { while ((interval >= 0) && (interval <= numPoints - 2)) { if (tTarget >= timePoints[interval]) interval--; else if (tTarget < timePoints[interval + 1]) interval++; else break; } } return interval; </DeepExtract> if (interval < 0) p = 0; else if (interval > numPoints - 2) { p = numPoints - 1; } else { p = interval; if (isAscending) { if ((tTarget - timePoints[interval]) > (timePoints[interval + 1] - tTarget)) p = interval + 1; } else { if ((tTarget - timePoints[interval + 1]) < (timePoints[interval] - tTarget)) p = interval + 1; } } return p; }
PhyDyn
positive
2,982
public Criteria andIdIn(List<Integer> values) { if (values == null) { throw new RuntimeException("Value for " + "id" + " cannot be null"); } criteria.add(new Criterion("id in", values)); return (Criteria) this; }
public Criteria andIdIn(List<Integer> values) { <DeepExtract> if (values == null) { throw new RuntimeException("Value for " + "id" + " cannot be null"); } criteria.add(new Criterion("id in", values)); </DeepExtract> return (Criteria) this; }
dubbo-mock
positive
2,983
private static void mergeSort1(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); int midIndex = array.length / 2; int[] tempArray = new int[array.length]; int i = 0, j = midIndex + 1, k = 0; int i = 0, j = midIndex + 1, k = 0; int i = 0, j = midIndex + 1, k = 0; while (i <= midIndex && j < array.length) { if (array[i] <= array[j]) { tempArray[k] = array[i]; i++; k++; } else { tempArray[k] = array[j]; j++; k++; } } while (i <= midIndex) { tempArray[k] = array[i]; i++; k++; } while (j < array.length) { tempArray[k] = array[j]; j++; k++; } for (int i = 0; i < tempArray.length; i++) { System.out.print(tempArray[i] + " "); } System.out.println(); }
private static void mergeSort1(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); int midIndex = array.length / 2; int[] tempArray = new int[array.length]; int i = 0, j = midIndex + 1, k = 0; int i = 0, j = midIndex + 1, k = 0; int i = 0, j = midIndex + 1, k = 0; while (i <= midIndex && j < array.length) { if (array[i] <= array[j]) { tempArray[k] = array[i]; i++; k++; } else { tempArray[k] = array[j]; j++; k++; } } while (i <= midIndex) { tempArray[k] = array[i]; i++; k++; } while (j < array.length) { tempArray[k] = array[j]; j++; k++; } <DeepExtract> for (int i = 0; i < tempArray.length; i++) { System.out.print(tempArray[i] + " "); } System.out.println(); </DeepExtract> }
ProjectStudy
positive
2,984
protected ch.qos.logback.core.Appender getLogbackDailyAndSizeRollingFileAppender(String productName, String file, String encoding, String size, String datePattern, int maxBackupIndex) { RollingFileAppender appender = new RollingFileAppender(); appender.setContext(LogbackLoggerContextUtil.getLoggerContext()); appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender"); appender.setAppend(true); appender.setFile(LoggerHelper.getLogFile(productName, file)); TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy(); rolling.setParent(appender); if (maxBackupIndex >= 0) { rolling.setMaxHistory(maxBackupIndex); } rolling.setFileNamePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}.%i"); rolling.setContext(LogbackLoggerContextUtil.getLoggerContext()); SizeAndTimeBasedFNATP fnatp = new SizeAndTimeBasedFNATP(); try { try { Method setMaxFileSizeMethod = fnatp.getClass().getDeclaredMethod("setMaxFileSize", String.class); setMaxFileSizeMethod.invoke(fnatp, size); } catch (NoSuchMethodException e) { Method setMaxFileSizeMethod = fnatp.getClass().getDeclaredMethod("setMaxFileSize", FileSize.class); setMaxFileSizeMethod.invoke(fnatp, FileSize.valueOf(size)); } } catch (Throwable t) { throw new RuntimeException("Failed to setMaxFileSize", t); } fnatp.setTimeBasedRollingPolicy(rolling); rolling.setTimeBasedFileNamingAndTriggeringPolicy(fnatp); rolling.start(); appender.setRollingPolicy(rolling); PatternLayout layout = new PatternLayout(); layout.setPattern(LoggerHelper.getPattern(productName)); layout.setContext(LogbackLoggerContextUtil.getLoggerContext()); layout.start(); appender.setLayout(layout); appender.start(); return appender; }
protected ch.qos.logback.core.Appender getLogbackDailyAndSizeRollingFileAppender(String productName, String file, String encoding, String size, String datePattern, int maxBackupIndex) { RollingFileAppender appender = new RollingFileAppender(); appender.setContext(LogbackLoggerContextUtil.getLoggerContext()); appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender"); appender.setAppend(true); appender.setFile(LoggerHelper.getLogFile(productName, file)); TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy(); rolling.setParent(appender); if (maxBackupIndex >= 0) { rolling.setMaxHistory(maxBackupIndex); } rolling.setFileNamePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}.%i"); rolling.setContext(LogbackLoggerContextUtil.getLoggerContext()); SizeAndTimeBasedFNATP fnatp = new SizeAndTimeBasedFNATP(); <DeepExtract> try { try { Method setMaxFileSizeMethod = fnatp.getClass().getDeclaredMethod("setMaxFileSize", String.class); setMaxFileSizeMethod.invoke(fnatp, size); } catch (NoSuchMethodException e) { Method setMaxFileSizeMethod = fnatp.getClass().getDeclaredMethod("setMaxFileSize", FileSize.class); setMaxFileSizeMethod.invoke(fnatp, FileSize.valueOf(size)); } } catch (Throwable t) { throw new RuntimeException("Failed to setMaxFileSize", t); } </DeepExtract> fnatp.setTimeBasedRollingPolicy(rolling); rolling.setTimeBasedFileNamingAndTriggeringPolicy(fnatp); rolling.start(); appender.setRollingPolicy(rolling); PatternLayout layout = new PatternLayout(); layout.setPattern(LoggerHelper.getPattern(productName)); layout.setContext(LogbackLoggerContextUtil.getLoggerContext()); layout.start(); appender.setLayout(layout); appender.start(); return appender; }
logger.api
positive
2,985
public void itemStateChanged(ItemEvent evt) { if (evt.getStateChange() == ItemEvent.SELECTED == autoReloadEnabled) return; autoReloadEnabled = evt.getStateChange() == ItemEvent.SELECTED; if (evt.getStateChange() == ItemEvent.SELECTED) { initFileWatcher(); } else { if (fw != null) { sm.remove(fw); fw = null; } } }
public void itemStateChanged(ItemEvent evt) { <DeepExtract> if (evt.getStateChange() == ItemEvent.SELECTED == autoReloadEnabled) return; autoReloadEnabled = evt.getStateChange() == ItemEvent.SELECTED; if (evt.getStateChange() == ItemEvent.SELECTED) { initFileWatcher(); } else { if (fw != null) { sm.remove(fw); fw = null; } } </DeepExtract> }
TMCMG
positive
2,986
@Override public void setComponent(EntityId entityId, EntityComponent component) { EntityComponent lastComp = getComponent(entityId, component.getClass()); super.setComponent(entityId, component); Platform.runLater(() -> { if (component.getClass() == Parenting.class) { handleParentingChange(entityId, (Parenting) lastComp, (Parenting) component); } else if (component.getClass() == Naming.class) { handleNamingChange(entityId, (Naming) lastComp, (Naming) component); } EntityNode node = findOrCreateNode(entityId); if (lastComp != null && component == null) { node.componentListProperty().remove(lastComp); } else if (lastComp != null && component != null) { int index = node.componentListProperty().indexOf(lastComp); if (index == -1) { LogUtil.warning("Something went wrong with the known issue #16. We need to replace a component in an entity node, but the old component can't be found in the entity node's comp list."); LogUtil.warning(" Component class : " + component.getClass().getSimpleName()); LogUtil.warning(" last component : " + lastComp); LogUtil.warning(" new component : " + component); Naming naming = getComponent(entityId, Naming.class); LogUtil.warning(" entity : " + entityId + (naming != null ? naming.getName() : "unamed.")); LogUtil.warning(" please give info about that test case to https://github.com/brainless-studios/alchemist/issues/16"); } else node.componentListProperty().set(index, component); } else if (lastComp == null && component != null) { node.componentListProperty().add(component); } }); }
@Override public void setComponent(EntityId entityId, EntityComponent component) { EntityComponent lastComp = getComponent(entityId, component.getClass()); super.setComponent(entityId, component); <DeepExtract> Platform.runLater(() -> { if (component.getClass() == Parenting.class) { handleParentingChange(entityId, (Parenting) lastComp, (Parenting) component); } else if (component.getClass() == Naming.class) { handleNamingChange(entityId, (Naming) lastComp, (Naming) component); } EntityNode node = findOrCreateNode(entityId); if (lastComp != null && component == null) { node.componentListProperty().remove(lastComp); } else if (lastComp != null && component != null) { int index = node.componentListProperty().indexOf(lastComp); if (index == -1) { LogUtil.warning("Something went wrong with the known issue #16. We need to replace a component in an entity node, but the old component can't be found in the entity node's comp list."); LogUtil.warning(" Component class : " + component.getClass().getSimpleName()); LogUtil.warning(" last component : " + lastComp); LogUtil.warning(" new component : " + component); Naming naming = getComponent(entityId, Naming.class); LogUtil.warning(" entity : " + entityId + (naming != null ? naming.getName() : "unamed.")); LogUtil.warning(" please give info about that test case to https://github.com/brainless-studios/alchemist/issues/16"); } else node.componentListProperty().set(index, component); } else if (lastComp == null && component != null) { node.componentListProperty().add(component); } }); </DeepExtract> }
alchemist
positive
2,987
private String indent(ITree t) { StringBuilder b = new StringBuilder(); for (int i = 0; i < t.getDepth(); i++) b.append("\t"); System.err.println("This terminal should currently not be used (please use toShortString())"); return toShortString(); }
private String indent(ITree t) { StringBuilder b = new StringBuilder(); for (int i = 0; i < t.getDepth(); i++) b.append("\t"); <DeepExtract> System.err.println("This terminal should currently not be used (please use toShortString())"); return toShortString(); </DeepExtract> }
IntelliMerge
positive
2,988
public View getView(int position, View view, ViewGroup parent) { if (view == null) { LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = vi.inflate(R.layout.base_restaurant_cell, parent, false); holder = new RestaurantViewHolder(view); view.setTag(holder); } else { holder = (RestaurantViewHolder) view.getTag(); } Restaurant restaurant = getItem(position); Drawable defaultThumbnail = new IconDrawable(context, IoniconsIcons.ion_android_restaurant).colorRes(R.color.dark_gray); if (!restaurant.getImageUrl().isEmpty()) { Picasso.get().load(restaurant.getImageUrl()).error(defaultThumbnail).fit().centerCrop().into(thumbnail); } else { thumbnail.setImageDrawable(defaultThumbnail); } name.setText(restaurant.getName()); address.setText(restaurant.getAddress()); if (restaurant.getCategoriesListText().isEmpty()) { categories.setVisibility(View.GONE); } else { categories.setText(restaurant.getCategoriesListText()); categories.setVisibility(View.VISIBLE); } return view; }
public View getView(int position, View view, ViewGroup parent) { if (view == null) { LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = vi.inflate(R.layout.base_restaurant_cell, parent, false); holder = new RestaurantViewHolder(view); view.setTag(holder); } else { holder = (RestaurantViewHolder) view.getTag(); } <DeepExtract> Restaurant restaurant = getItem(position); Drawable defaultThumbnail = new IconDrawable(context, IoniconsIcons.ion_android_restaurant).colorRes(R.color.dark_gray); if (!restaurant.getImageUrl().isEmpty()) { Picasso.get().load(restaurant.getImageUrl()).error(defaultThumbnail).fit().centerCrop().into(thumbnail); } else { thumbnail.setImageDrawable(defaultThumbnail); } name.setText(restaurant.getName()); address.setText(restaurant.getAddress()); if (restaurant.getCategoriesListText().isEmpty()) { categories.setVisibility(View.GONE); } else { categories.setText(restaurant.getCategoriesListText()); categories.setVisibility(View.VISIBLE); } </DeepExtract> return view; }
Food-Diary
positive
2,989
public void handleEvent(Event event) { int n = 0; for (TableItem item : testRequirementsViewer.getTable().getItems()) { item.setImage(1, null); if (n % 2 == 0) item.setBackground(Colors.WHITE); else item.setBackground(Colors.GREY); testRequirementsViewer.getTable().getItem(n).setText(0, Integer.toString(n + 1)); n++; } if (event.detail == SWT.CHECK) { Iterator<AbstractPath<Integer>> iterator = Activator.getDefault().getTestRequirementController().getTestRequirements().iterator(); for (TableItem item : testRequirementsViewer.getTable().getItems()) { AbstractPath<Integer> selected = iterator.next(); if (item == event.item) { if (item.getChecked()) Activator.getDefault().getTestRequirementController().enableInfeasible(selected); else Activator.getDefault().getTestRequirementController().disableInfeasible(selected); break; } } } else if (event.detail == SWT.NONE) { Iterator<AbstractPath<Integer>> iterator = Activator.getDefault().getTestRequirementController().getTestRequirements().iterator(); for (TableItem item : testRequirementsViewer.getTable().getItems()) { AbstractPath<Integer> selected = iterator.next(); if (item == event.item) { Activator.getDefault().getTestRequirementController().selectTestRequirement(selected); break; } } } }
public void handleEvent(Event event) { <DeepExtract> int n = 0; for (TableItem item : testRequirementsViewer.getTable().getItems()) { item.setImage(1, null); if (n % 2 == 0) item.setBackground(Colors.WHITE); else item.setBackground(Colors.GREY); testRequirementsViewer.getTable().getItem(n).setText(0, Integer.toString(n + 1)); n++; } </DeepExtract> if (event.detail == SWT.CHECK) { Iterator<AbstractPath<Integer>> iterator = Activator.getDefault().getTestRequirementController().getTestRequirements().iterator(); for (TableItem item : testRequirementsViewer.getTable().getItems()) { AbstractPath<Integer> selected = iterator.next(); if (item == event.item) { if (item.getChecked()) Activator.getDefault().getTestRequirementController().enableInfeasible(selected); else Activator.getDefault().getTestRequirementController().disableInfeasible(selected); break; } } } else if (event.detail == SWT.NONE) { Iterator<AbstractPath<Integer>> iterator = Activator.getDefault().getTestRequirementController().getTestRequirements().iterator(); for (TableItem item : testRequirementsViewer.getTable().getItems()) { AbstractPath<Integer> selected = iterator.next(); if (item == event.item) { Activator.getDefault().getTestRequirementController().selectTestRequirement(selected); break; } } } }
PESTT
positive
2,990
@Override public void init() { jobBuilders = new HashMap<String, IJobBuilder>(); FileJobBuilder fileJobBuilder = new FileJobBuilder(); fileJobBuilder.init(); jobBuilders.put("file", fileJobBuilder); this.config = config; if (log.isInfoEnabled()) { log.info("mixJobBuilder init complete."); } }
@Override public void init() { jobBuilders = new HashMap<String, IJobBuilder>(); FileJobBuilder fileJobBuilder = new FileJobBuilder(); fileJobBuilder.init(); jobBuilders.put("file", fileJobBuilder); <DeepExtract> this.config = config; </DeepExtract> if (log.isInfoEnabled()) { log.info("mixJobBuilder init complete."); } }
beatles
positive
2,991
@Override public void onDownloadJson(int handle, String... emojiNames) { categorizedEmojies.clear(); if (keyboardViewManager == null) return; final String category = currentCategory; currentCategory = null; changeCategory(category, keyboardViewManager.getCurrentPage()); }
@Override public void onDownloadJson(int handle, String... emojiNames) { <DeepExtract> categorizedEmojies.clear(); if (keyboardViewManager == null) return; final String category = currentCategory; currentCategory = null; changeCategory(category, keyboardViewManager.getCurrentPage()); </DeepExtract> }
emojidex-android
positive
2,992
public void assertSelectedIds(String selectLocator, String pattern) throws java.lang.Exception { if (selectLocator instanceof String && getSelectedIds(pattern) instanceof String) { assertEquals((String) selectLocator, (String) getSelectedIds(pattern)); } else if (selectLocator instanceof String && getSelectedIds(pattern) instanceof String[]) { assertEquals((String) selectLocator, (String[]) getSelectedIds(pattern)); } else if (selectLocator instanceof String && getSelectedIds(pattern) instanceof Number) { assertEquals((String) selectLocator, ((Number) getSelectedIds(pattern)).toString()); } else { if (selectLocator instanceof String[] && getSelectedIds(pattern) instanceof String[]) { String[] sa1 = (String[]) selectLocator; String[] sa2 = (String[]) getSelectedIds(pattern); if (sa1.length != sa2.length) { throw new AssertionFailedError("Expected " + sa1 + " but saw " + sa2); } for (int j = 0; j < sa1.length; j++) { Assert.assertEquals(sa1[j], sa2[j]); } } } }
public void assertSelectedIds(String selectLocator, String pattern) throws java.lang.Exception { <DeepExtract> if (selectLocator instanceof String && getSelectedIds(pattern) instanceof String) { assertEquals((String) selectLocator, (String) getSelectedIds(pattern)); } else if (selectLocator instanceof String && getSelectedIds(pattern) instanceof String[]) { assertEquals((String) selectLocator, (String[]) getSelectedIds(pattern)); } else if (selectLocator instanceof String && getSelectedIds(pattern) instanceof Number) { assertEquals((String) selectLocator, ((Number) getSelectedIds(pattern)).toString()); } else { if (selectLocator instanceof String[] && getSelectedIds(pattern) instanceof String[]) { String[] sa1 = (String[]) selectLocator; String[] sa2 = (String[]) getSelectedIds(pattern); if (sa1.length != sa2.length) { throw new AssertionFailedError("Expected " + sa1 + " but saw " + sa2); } for (int j = 0; j < sa1.length; j++) { Assert.assertEquals(sa1[j], sa2[j]); } } } </DeepExtract> }
selenium-client-factory
positive
2,993
public void saveExecutionMillTime(String method, int exeTime) { Statistics st = executionMillTime.get(method); if (st == null) { st = new Statistics((int) Math.ceil((exeTime + 1) * 1.5), statisticSum); Statistics old = executionMillTime.putIfAbsent(method, st); if (old != null) { st = old; } } int index = history[0]++; final int LENGTH = history.length - 1; if (index == LENGTH) { history[0] = 1; } history[index] = exeTime; if (index != indexOfMax) { if (exeTime > max) { indexOfMax = index; max = exeTime; } } else if (history[LENGTH] > 0) { if (exeTime < max) { int imax = 1; for (int i = 2; i < history.length; i++) { if (history[i] > history[imax]) { imax = i; } } indexOfMax = imax; max = history[imax]; } else { max = exeTime; } } }
public void saveExecutionMillTime(String method, int exeTime) { Statistics st = executionMillTime.get(method); if (st == null) { st = new Statistics((int) Math.ceil((exeTime + 1) * 1.5), statisticSum); Statistics old = executionMillTime.putIfAbsent(method, st); if (old != null) { st = old; } } <DeepExtract> int index = history[0]++; final int LENGTH = history.length - 1; if (index == LENGTH) { history[0] = 1; } history[index] = exeTime; if (index != indexOfMax) { if (exeTime > max) { indexOfMax = index; max = exeTime; } } else if (history[LENGTH] > 0) { if (exeTime < max) { int imax = 1; for (int i = 2; i < history.length; i++) { if (history[i] > history[imax]) { imax = i; } } indexOfMax = imax; max = history[imax]; } else { max = exeTime; } } </DeepExtract> }
netty-thrift
positive
2,994
private void startShadow() { mPolygonShapeSpec.setHasShadow(true); mBorderPaint.setShadowLayer(mPolygonShapeSpec.getShadowRadius(), mPolygonShapeSpec.getShadowXOffset(), mPolygonShapeSpec.getShadowYOffset(), mPolygonShapeSpec.getShadowColor()); updatePolygonSize(getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom()); invalidate(); }
private void startShadow() { mPolygonShapeSpec.setHasShadow(true); mBorderPaint.setShadowLayer(mPolygonShapeSpec.getShadowRadius(), mPolygonShapeSpec.getShadowXOffset(), mPolygonShapeSpec.getShadowYOffset(), mPolygonShapeSpec.getShadowColor()); <DeepExtract> updatePolygonSize(getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom()); </DeepExtract> invalidate(); }
BaseMyProject
positive
2,995
public Criteria andAvatarIsNull() { if ("avatar is null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("avatar is null")); return (Criteria) this; }
public Criteria andAvatarIsNull() { <DeepExtract> if ("avatar is null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("avatar is null")); </DeepExtract> return (Criteria) this; }
oauth4j
positive
2,996
public void preShow() { if (root == null) { throw new IllegalStateException("setContentView called with a view to display"); } if (background == null) { mWindow.setBackgroundDrawable(new BitmapDrawable()); } else { mWindow.setBackgroundDrawable(background); } mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); mWindow.setTouchable(true); mWindow.setFocusable(true); mWindow.setOutsideTouchable(true); this.root = root; mWindow.setContentView(root); }
public void preShow() { if (root == null) { throw new IllegalStateException("setContentView called with a view to display"); } if (background == null) { mWindow.setBackgroundDrawable(new BitmapDrawable()); } else { mWindow.setBackgroundDrawable(background); } mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); mWindow.setTouchable(true); mWindow.setFocusable(true); mWindow.setOutsideTouchable(true); <DeepExtract> this.root = root; mWindow.setContentView(root); </DeepExtract> }
owncloud-android
positive
2,997
public void setTypeface(Typeface typeface, int style) { this.tabTypeface = typeface; this.tabTypefaceStyle = style; for (int i = 0; i < tabCount; i++) { View v = tabsContainer.getChildAt(i); v.setBackgroundResource(tabBackgroundResId); if (v instanceof TextView) { TextView tab = (TextView) v; tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize); tab.setTypeface(tabTypeface, tabTypefaceStyle); tab.setTextColor(tabTextColor); if (textAllCaps) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { tab.setAllCaps(true); } else { tab.setText(tab.getText().toString().toUpperCase(locale)); } } if (i == selectedPosition) { tab.setTextColor(selectedTabTextColor); } } } }
public void setTypeface(Typeface typeface, int style) { this.tabTypeface = typeface; this.tabTypefaceStyle = style; <DeepExtract> for (int i = 0; i < tabCount; i++) { View v = tabsContainer.getChildAt(i); v.setBackgroundResource(tabBackgroundResId); if (v instanceof TextView) { TextView tab = (TextView) v; tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize); tab.setTypeface(tabTypeface, tabTypefaceStyle); tab.setTextColor(tabTextColor); if (textAllCaps) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { tab.setAllCaps(true); } else { tab.setText(tab.getText().toString().toUpperCase(locale)); } } if (i == selectedPosition) { tab.setTextColor(selectedTabTextColor); } } } </DeepExtract> }
WeCenterMobile-Android
positive
2,998
public OnBoardTest getExhaustGasRecirculationSystemTest() { if (getIgnitionType().equals(IgnitionType.Compression)) { return OnBoardTest.NotAvailable; } if (!isOn("C7")) { return OnBoardTest.NotAvailable; } if (isOn("D7")) { return OnBoardTest.AvailableIncomplete; } return OnBoardTest.AvailableComplete; }
public OnBoardTest getExhaustGasRecirculationSystemTest() { if (getIgnitionType().equals(IgnitionType.Compression)) { return OnBoardTest.NotAvailable; } <DeepExtract> if (!isOn("C7")) { return OnBoardTest.NotAvailable; } if (isOn("D7")) { return OnBoardTest.AvailableIncomplete; } return OnBoardTest.AvailableComplete; </DeepExtract> }
OBD2
positive
2,999
public static <T> Component<T> newComponentCustom(String name, ComponentFactory<T> factory) { if (listener != null) { listener.onComponentAdd(components.addDefinition(factory.create(components.nextId(), name)), true); } return components.addDefinition(factory.create(components.nextId(), name)); }
public static <T> Component<T> newComponentCustom(String name, ComponentFactory<T> factory) { <DeepExtract> if (listener != null) { listener.onComponentAdd(components.addDefinition(factory.create(components.nextId(), name)), true); } return components.addDefinition(factory.create(components.nextId(), name)); </DeepExtract> }
Ents
positive
3,000
@Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (fling != null) { fling.cancelFling(); } fling = new Fling((int) velocityX, (int) velocityY); if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) { postOnAnimation(fling); } else { postDelayed(fling, 1000 / 60); } return super.onFling(e1, e2, velocityX, velocityY); }
@Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (fling != null) { fling.cancelFling(); } fling = new Fling((int) velocityX, (int) velocityY); <DeepExtract> if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) { postOnAnimation(fling); } else { postDelayed(fling, 1000 / 60); } </DeepExtract> return super.onFling(e1, e2, velocityX, velocityY); }
catnut
positive
3,001
public static String[][] getListValues(List list) { Store store = (Store) list.get(0); if (this.size() == 0) { col = new String[0]; } String[] keys = new String[this.size()]; this.keySet().toArray(keys); return keys; values = new String[list.size() + 1][col.length]; for (int i = 0; i < list.size(); i++) { store = (Store) list.get(i); values[i] = store.getStrValues(); } return values; }
public static String[][] getListValues(List list) { Store store = (Store) list.get(0); <DeepExtract> if (this.size() == 0) { col = new String[0]; } String[] keys = new String[this.size()]; this.keySet().toArray(keys); return keys; </DeepExtract> values = new String[list.size() + 1][col.length]; for (int i = 0; i < list.size(); i++) { store = (Store) list.get(i); values[i] = store.getStrValues(); } return values; }
Uni
positive
3,002
@Test public void testParameterizedConstructorSingleResolved() { Operation<Object, Params, Event> operation = Operations.constructorOf(this::parameterizedConstructorSingle); Assert.assertTrue(ParameterizedConstructorHandlerSingle.class.isAssignableFrom(((OperationHandlerOperation) operation).handler().getClass())); }
@Test public void testParameterizedConstructorSingleResolved() { Operation<Object, Params, Event> operation = Operations.constructorOf(this::parameterizedConstructorSingle); <DeepExtract> Assert.assertTrue(ParameterizedConstructorHandlerSingle.class.isAssignableFrom(((OperationHandlerOperation) operation).handler().getClass())); </DeepExtract> }
sourcerer
positive
3,003
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); if (0 == N - 1) { if (1 != 0 && 1 % 3 == 0) { ans++; } return; } for (int i = 0; i < 3; i++) { 1 *= 10; 1 += i; combination(0 + 1, 1); 1 -= i; 1 /= 10; } if (0 == N - 1) { if (2 != 0 && 2 % 3 == 0) { ans++; } return; } for (int i = 0; i < 3; i++) { 2 *= 10; 2 += i; combination(0 + 1, 2); 2 -= i; 2 /= 10; } System.out.println(ans); }
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); if (0 == N - 1) { if (1 != 0 && 1 % 3 == 0) { ans++; } return; } for (int i = 0; i < 3; i++) { 1 *= 10; 1 += i; combination(0 + 1, 1); 1 -= i; 1 /= 10; } <DeepExtract> if (0 == N - 1) { if (2 != 0 && 2 % 3 == 0) { ans++; } return; } for (int i = 0; i < 3; i++) { 2 *= 10; 2 += i; combination(0 + 1, 2); 2 -= i; 2 /= 10; } </DeepExtract> System.out.println(ans); }
BOJ
positive
3,004
private static String removeDuplicateSlashes(String string) { StringBuffer buffer = new StringBuffer(); boolean lastWasSlash = false; for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '/') { if (!lastWasSlash) { buffer.append(c); lastWasSlash = true; } } else { buffer.append(c); lastWasSlash = false; } } return string; }
private static String removeDuplicateSlashes(String string) { StringBuffer buffer = new StringBuffer(); boolean lastWasSlash = false; for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '/') { if (!lastWasSlash) { buffer.append(c); lastWasSlash = true; } } else { buffer.append(c); lastWasSlash = false; } } <DeepExtract> return string; </DeepExtract> }
unix-maven-plugin
positive
3,005
public ByteTreeBasic reply(final LargeInteger integerChallenge) { if (!(0 <= integerChallenge.compareTo(LargeInteger.ZERO) && integerChallenge.bitLength() <= vbitlen)) { throw new ProtocolError("Malformed challenge!"); } this.v = pField.toElement(integerChallenge); final PRingElement a = r.innerProduct(ipe); final PRingElement c = r.sum(); final PRingElement f = s.innerProduct(e); k_A = a.mulAdd(v, alpha); k_B = b.mulAdd(v, beta); k_C = c.mulAdd(v, gamma); k_D = d.mulAdd(v, delta); k_E = (PFieldElementArray) ipe.mulAdd(v, epsilon); k_F = f.mulAdd(v, phi); final ByteTreeContainer reply = new ByteTreeContainer(k_A.toByteTree(), k_B.toByteTree(), k_C.toByteTree(), k_D.toByteTree(), k_E.toByteTree(), k_F.toByteTree()); return reply; }
public ByteTreeBasic reply(final LargeInteger integerChallenge) { <DeepExtract> if (!(0 <= integerChallenge.compareTo(LargeInteger.ZERO) && integerChallenge.bitLength() <= vbitlen)) { throw new ProtocolError("Malformed challenge!"); } this.v = pField.toElement(integerChallenge); </DeepExtract> final PRingElement a = r.innerProduct(ipe); final PRingElement c = r.sum(); final PRingElement f = s.innerProduct(e); k_A = a.mulAdd(v, alpha); k_B = b.mulAdd(v, beta); k_C = c.mulAdd(v, gamma); k_D = d.mulAdd(v, delta); k_E = (PFieldElementArray) ipe.mulAdd(v, epsilon); k_F = f.mulAdd(v, phi); final ByteTreeContainer reply = new ByteTreeContainer(k_A.toByteTree(), k_B.toByteTree(), k_C.toByteTree(), k_D.toByteTree(), k_E.toByteTree(), k_F.toByteTree()); return reply; }
verificatum-vmn
positive
3,006
private void processNeedCommand(String argument) { int p1 = argument.indexOf('\''); int p2 = argument.indexOf('\'', p1 + 1); String needed = argument.substring(p1 + 1, p2); String extra = argument.split(":", 2)[1]; String status = "ok"; switch(needed) { case "PROTECTFD": FileDescriptor fdtoprotect = mFDList.pollFirst(); protectFileDescriptor(fdtoprotect); break; case "DNSSERVER": case "DNS6SERVER": mOpenVPNService.addDNS(extra); break; case "DNSDOMAIN": mOpenVPNService.setDomain(extra); break; case "ROUTE": { String[] routeparts = extra.split(" "); if (routeparts.length == 5) { mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], routeparts[4]); } else if (routeparts.length >= 3) { mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], null); } else { VpnStatus.logError("Unrecognized ROUTE cmd:" + Arrays.toString(routeparts) + " | " + argument); } break; } case "ROUTE6": { String[] routeparts = extra.split(" "); mOpenVPNService.addRoutev6(routeparts[0], routeparts[1]); break; } case "IFCONFIG": String[] ifconfigparts = extra.split(" "); int mtu = Integer.parseInt(ifconfigparts[2]); mOpenVPNService.setLocalIP(ifconfigparts[0], ifconfigparts[1], mtu, ifconfigparts[3]); break; case "IFCONFIG6": String[] ifconfig6parts = extra.split(" "); mtu = Integer.parseInt(ifconfig6parts[1]); mOpenVPNService.setMtu(mtu); mOpenVPNService.setLocalIPv6(ifconfig6parts[0]); break; case "PERSIST_TUN_ACTION": status = mOpenVPNService.getTunReopenStatus(); break; case "OPENTUN": if (sendTunFD(needed, extra)) return; else status = "cancel"; break; case "HTTPPROXY": String[] httpproxy = extra.split(" "); if (httpproxy.length == 2) { mOpenVPNService.addHttpProxy(httpproxy[0], Integer.parseInt(httpproxy[1])); } else { VpnStatus.logError("Unrecognized HTTPPROXY cmd: " + Arrays.toString(httpproxy) + " | " + argument); } break; default: Log.e(TAG, "Unknown needok command " + argument); return; } String cmd = String.format("needok '%s' %s\n", needed, status); try { if (mSocket != null && mSocket.getOutputStream() != null) { mSocket.getOutputStream().write(cmd.getBytes()); mSocket.getOutputStream().flush(); return true; } } catch (IOException e) { } return false; }
private void processNeedCommand(String argument) { int p1 = argument.indexOf('\''); int p2 = argument.indexOf('\'', p1 + 1); String needed = argument.substring(p1 + 1, p2); String extra = argument.split(":", 2)[1]; String status = "ok"; switch(needed) { case "PROTECTFD": FileDescriptor fdtoprotect = mFDList.pollFirst(); protectFileDescriptor(fdtoprotect); break; case "DNSSERVER": case "DNS6SERVER": mOpenVPNService.addDNS(extra); break; case "DNSDOMAIN": mOpenVPNService.setDomain(extra); break; case "ROUTE": { String[] routeparts = extra.split(" "); if (routeparts.length == 5) { mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], routeparts[4]); } else if (routeparts.length >= 3) { mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], null); } else { VpnStatus.logError("Unrecognized ROUTE cmd:" + Arrays.toString(routeparts) + " | " + argument); } break; } case "ROUTE6": { String[] routeparts = extra.split(" "); mOpenVPNService.addRoutev6(routeparts[0], routeparts[1]); break; } case "IFCONFIG": String[] ifconfigparts = extra.split(" "); int mtu = Integer.parseInt(ifconfigparts[2]); mOpenVPNService.setLocalIP(ifconfigparts[0], ifconfigparts[1], mtu, ifconfigparts[3]); break; case "IFCONFIG6": String[] ifconfig6parts = extra.split(" "); mtu = Integer.parseInt(ifconfig6parts[1]); mOpenVPNService.setMtu(mtu); mOpenVPNService.setLocalIPv6(ifconfig6parts[0]); break; case "PERSIST_TUN_ACTION": status = mOpenVPNService.getTunReopenStatus(); break; case "OPENTUN": if (sendTunFD(needed, extra)) return; else status = "cancel"; break; case "HTTPPROXY": String[] httpproxy = extra.split(" "); if (httpproxy.length == 2) { mOpenVPNService.addHttpProxy(httpproxy[0], Integer.parseInt(httpproxy[1])); } else { VpnStatus.logError("Unrecognized HTTPPROXY cmd: " + Arrays.toString(httpproxy) + " | " + argument); } break; default: Log.e(TAG, "Unknown needok command " + argument); return; } String cmd = String.format("needok '%s' %s\n", needed, status); <DeepExtract> try { if (mSocket != null && mSocket.getOutputStream() != null) { mSocket.getOutputStream().write(cmd.getBytes()); mSocket.getOutputStream().flush(); return true; } } catch (IOException e) { } return false; </DeepExtract> }
Gear-VPN
positive
3,007
public synchronized void aICreateEnrouteATCAircraft(String containerTitle, String tailNumber, int flightNumber, String flightPlanPath, double flightPlanPosition, boolean touchAndGo, int dataRequestID) throws IOException { writeBuffer.clear(); writeBuffer.position(16); if (containerTitle == null) { containerTitle = ""; } byte[] b = containerTitle.getBytes(); writeBuffer.put(b, 0, Math.min(b.length, 256)); if (b.length < 256) { for (int i = 0; i < (256 - b.length); i++) { writeBuffer.put((byte) 0); } } if (tailNumber == null) { tailNumber = ""; } byte[] b = tailNumber.getBytes(); writeBuffer.put(b, 0, Math.min(b.length, 12)); if (b.length < 12) { for (int i = 0; i < (12 - b.length); i++) { writeBuffer.put((byte) 0); } } writeBuffer.putInt(flightNumber); if (flightPlanPath == null) { flightPlanPath = ""; } byte[] b = flightPlanPath.getBytes(); writeBuffer.put(b, 0, Math.min(b.length, 260)); if (b.length < 260) { for (int i = 0; i < (260 - b.length); i++) { writeBuffer.put((byte) 0); } } writeBuffer.putDouble(flightPlanPosition); writeBuffer.putInt(touchAndGo ? 1 : 0); writeBuffer.putInt(dataRequestID); int packetSize = writeBuffer.position(); writeBuffer.putInt(0, packetSize); writeBuffer.putInt(4, ourProtocol); writeBuffer.putInt(8, 0xF0000000 | 0x28); writeBuffer.putInt(12, currentIndex++); writeBuffer.flip(); sc.write(writeBuffer); packetsSent++; bytesSent += packetSize; }
public synchronized void aICreateEnrouteATCAircraft(String containerTitle, String tailNumber, int flightNumber, String flightPlanPath, double flightPlanPosition, boolean touchAndGo, int dataRequestID) throws IOException { writeBuffer.clear(); writeBuffer.position(16); if (containerTitle == null) { containerTitle = ""; } byte[] b = containerTitle.getBytes(); writeBuffer.put(b, 0, Math.min(b.length, 256)); if (b.length < 256) { for (int i = 0; i < (256 - b.length); i++) { writeBuffer.put((byte) 0); } } if (tailNumber == null) { tailNumber = ""; } byte[] b = tailNumber.getBytes(); writeBuffer.put(b, 0, Math.min(b.length, 12)); if (b.length < 12) { for (int i = 0; i < (12 - b.length); i++) { writeBuffer.put((byte) 0); } } writeBuffer.putInt(flightNumber); if (flightPlanPath == null) { flightPlanPath = ""; } byte[] b = flightPlanPath.getBytes(); writeBuffer.put(b, 0, Math.min(b.length, 260)); if (b.length < 260) { for (int i = 0; i < (260 - b.length); i++) { writeBuffer.put((byte) 0); } } writeBuffer.putDouble(flightPlanPosition); writeBuffer.putInt(touchAndGo ? 1 : 0); writeBuffer.putInt(dataRequestID); <DeepExtract> int packetSize = writeBuffer.position(); writeBuffer.putInt(0, packetSize); writeBuffer.putInt(4, ourProtocol); writeBuffer.putInt(8, 0xF0000000 | 0x28); writeBuffer.putInt(12, currentIndex++); writeBuffer.flip(); sc.write(writeBuffer); packetsSent++; bytesSent += packetSize; </DeepExtract> }
jsimconnect
positive
3,008
public AssemblyResult parse(String text) { AssemblyResult result = new AssemblyResult(config); String[] lines = text.split("\n"); LogManager.LOGGER.info("Assembly job started: " + lines.length + " lines to parse."); ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int currentLine = 0; currentLine < lines.length; currentLine++) { try { checkForORGInstruction(lines[currentLine], result, currentLine); } catch (PseudoInstructionException e) { break; } catch (AssemblyException e) { } } int currentOffset = 0; for (int currentLine = 0; currentLine < lines.length; currentLine++) { try { checkForLabel(lines[currentLine], result, (char) currentOffset); currentOffset += parseInstruction(lines[currentLine], currentLine, instructionSet).length / 2; if (currentOffset >= MEM_SIZE) { throw new OffsetOverflowException(currentOffset, MEM_SIZE, currentLine); } } catch (FatalAssemblyException e) { break; } catch (AssemblyException e1) { } } int currentOffset = 0; for (int currentLine = 0; currentLine < lines.length; currentLine++) { String line = lines[currentLine]; try { line = removeComment(line); line = removeLabel(line); if (isLineEmpty(line)) { throw new EmptyLineException(currentLine); } checkForSectionDeclaration(line, result, currentLine, currentOffset); checkForEQUInstruction(line, result.labels, currentLine); checkForORGInstruction(line, result, currentLine); byte[] bytes = parseInstruction(line, currentLine, result.labels, instructionSet); currentOffset += bytes.length / 2; if (currentOffset >= MEM_SIZE) { throw new OffsetOverflowException(currentOffset, MEM_SIZE, currentLine); } out.write(bytes); } catch (EmptyLineException | PseudoInstructionException e) { } catch (FatalAssemblyException asmE) { result.exceptions.add(asmE); break; } catch (AssemblyException asmE) { result.exceptions.add(asmE); } catch (IOException ioE) { ioE.printStackTrace(); } } boolean writeToMemory = true; for (Exception e : result.exceptions) { if (e instanceof OffsetOverflowException) { writeToMemory = false; break; } } if (writeToMemory) { result.bytes = out.toByteArray(); } else { result.bytes = new byte[0]; LogManager.LOGGER.fine("Skipping writing assembled bytes to memory. (OffsetOverflowException)"); } try { out.close(); } catch (IOException e) { e.printStackTrace(); } LogManager.LOGGER.info("Assembled " + result.bytes.length + " bytes (" + result.exceptions.size() + " errors)"); for (AssemblyException e : result.exceptions) { LogManager.LOGGER.severe(e.getMessage() + '@' + e.getLine()); } LogManager.LOGGER.info('\n' + Util.toHex(result.bytes)); return result; }
public AssemblyResult parse(String text) { AssemblyResult result = new AssemblyResult(config); String[] lines = text.split("\n"); LogManager.LOGGER.info("Assembly job started: " + lines.length + " lines to parse."); ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int currentLine = 0; currentLine < lines.length; currentLine++) { try { checkForORGInstruction(lines[currentLine], result, currentLine); } catch (PseudoInstructionException e) { break; } catch (AssemblyException e) { } } int currentOffset = 0; for (int currentLine = 0; currentLine < lines.length; currentLine++) { try { checkForLabel(lines[currentLine], result, (char) currentOffset); currentOffset += parseInstruction(lines[currentLine], currentLine, instructionSet).length / 2; if (currentOffset >= MEM_SIZE) { throw new OffsetOverflowException(currentOffset, MEM_SIZE, currentLine); } } catch (FatalAssemblyException e) { break; } catch (AssemblyException e1) { } } <DeepExtract> int currentOffset = 0; for (int currentLine = 0; currentLine < lines.length; currentLine++) { String line = lines[currentLine]; try { line = removeComment(line); line = removeLabel(line); if (isLineEmpty(line)) { throw new EmptyLineException(currentLine); } checkForSectionDeclaration(line, result, currentLine, currentOffset); checkForEQUInstruction(line, result.labels, currentLine); checkForORGInstruction(line, result, currentLine); byte[] bytes = parseInstruction(line, currentLine, result.labels, instructionSet); currentOffset += bytes.length / 2; if (currentOffset >= MEM_SIZE) { throw new OffsetOverflowException(currentOffset, MEM_SIZE, currentLine); } out.write(bytes); } catch (EmptyLineException | PseudoInstructionException e) { } catch (FatalAssemblyException asmE) { result.exceptions.add(asmE); break; } catch (AssemblyException asmE) { result.exceptions.add(asmE); } catch (IOException ioE) { ioE.printStackTrace(); } } </DeepExtract> boolean writeToMemory = true; for (Exception e : result.exceptions) { if (e instanceof OffsetOverflowException) { writeToMemory = false; break; } } if (writeToMemory) { result.bytes = out.toByteArray(); } else { result.bytes = new byte[0]; LogManager.LOGGER.fine("Skipping writing assembled bytes to memory. (OffsetOverflowException)"); } try { out.close(); } catch (IOException e) { e.printStackTrace(); } LogManager.LOGGER.info("Assembled " + result.bytes.length + " bytes (" + result.exceptions.size() + " errors)"); for (AssemblyException e : result.exceptions) { LogManager.LOGGER.severe(e.getMessage() + '@' + e.getLine()); } LogManager.LOGGER.info('\n' + Util.toHex(result.bytes)); return result; }
Much-Assembly-Required
positive
3,009
public SliceSeqExpand duplicate() { SliceSeqExpand newSlice = new SliceSeqExpand(); copyAllocationInfoFrom((SliceSeqExpand) this); return newSlice; }
public SliceSeqExpand duplicate() { SliceSeqExpand newSlice = new SliceSeqExpand(); <DeepExtract> copyAllocationInfoFrom((SliceSeqExpand) this); </DeepExtract> return newSlice; }
Oak
positive
3,010
@Test public void findUserIdsConnectedTo() { return createExistingSocialUserConnection("1", "facebook", "9", 1L, null, null, null, "234567890", null, "345678901", System.currentTimeMillis() + 3600000); return createExistingSocialUserConnection("2", "facebook", "11", 2L, null, null, null, "456789012", null, "56789012", System.currentTimeMillis() + 3600000); Set<String> localUserIds = usersConnectionRepository.findUserIdsConnectedTo("facebook", new HashSet<>(Arrays.asList("9", "11"))); assertEquals(2, localUserIds.size()); assertTrue(localUserIds.contains("1")); assertTrue(localUserIds.contains("2")); }
@Test public void findUserIdsConnectedTo() { return createExistingSocialUserConnection("1", "facebook", "9", 1L, null, null, null, "234567890", null, "345678901", System.currentTimeMillis() + 3600000); <DeepExtract> return createExistingSocialUserConnection("2", "facebook", "11", 2L, null, null, null, "456789012", null, "56789012", System.currentTimeMillis() + 3600000); </DeepExtract> Set<String> localUserIds = usersConnectionRepository.findUserIdsConnectedTo("facebook", new HashSet<>(Arrays.asList("9", "11"))); assertEquals(2, localUserIds.size()); assertTrue(localUserIds.contains("1")); assertTrue(localUserIds.contains("2")); }
rfb-loyalty
positive
3,011
private void sendDeliveryReceipt(SmppSession session, Address mtDestinationAddress, Address mtSourceAddress, byte dataCoding) { DeliverSm deliver = new DeliverSm(); deliver.setEsmClass(SmppConstants.ESM_CLASS_MT_SMSC_DELIVERY_RECEIPT); deliver.setSourceAddress(mtDestinationAddress); deliver.setDestAddress(mtSourceAddress); deliver.setDataCoding(dataCoding); try { WindowFuture<Integer, PduRequest, PduResponse> future = session.sendRequestPdu(deliver, 10000, false); if (!future.await()) { logger.error("Failed to receive deliver_sm_resp within specified time"); } else if (future.isSuccess()) { DeliverSmResp deliverSmResp = (DeliverSmResp) future.getResponse(); logger.info("deliver_sm_resp: commandStatus [" + deliverSmResp.getCommandStatus() + "=" + deliverSmResp.getResultMessage() + "]"); } else { logger.error("Failed to properly receive deliver_sm_resp: " + future.getCause()); } } catch (Exception e) { } }
private void sendDeliveryReceipt(SmppSession session, Address mtDestinationAddress, Address mtSourceAddress, byte dataCoding) { DeliverSm deliver = new DeliverSm(); deliver.setEsmClass(SmppConstants.ESM_CLASS_MT_SMSC_DELIVERY_RECEIPT); deliver.setSourceAddress(mtDestinationAddress); deliver.setDestAddress(mtSourceAddress); deliver.setDataCoding(dataCoding); <DeepExtract> try { WindowFuture<Integer, PduRequest, PduResponse> future = session.sendRequestPdu(deliver, 10000, false); if (!future.await()) { logger.error("Failed to receive deliver_sm_resp within specified time"); } else if (future.isSuccess()) { DeliverSmResp deliverSmResp = (DeliverSmResp) future.getResponse(); logger.info("deliver_sm_resp: commandStatus [" + deliverSmResp.getCommandStatus() + "=" + deliverSmResp.getResultMessage() + "]"); } else { logger.error("Failed to properly receive deliver_sm_resp: " + future.getCause()); } } catch (Exception e) { } </DeepExtract> }
cloudhopper-smpp
positive
3,012
@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); swipeRefreshLayout = view.findViewById(R.id.swiperefreshlayout); swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { reload(); } }); adapter = new ImportAdapter(); recyclerView.setAdapter(adapter); adapter.setItemClickListener(new ImportAdapter.OnItemClickListener() { @Override public void onItemClick(RestoreModel model) { showRestore(model); } }); mPresenter = new ConfigPresenter(getContext().getApplicationContext(), this); adapter.showData(mPresenter.getRestoreFiles()); swipeRefreshLayout.setRefreshing(false); }
@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); swipeRefreshLayout = view.findViewById(R.id.swiperefreshlayout); swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { reload(); } }); adapter = new ImportAdapter(); recyclerView.setAdapter(adapter); adapter.setItemClickListener(new ImportAdapter.OnItemClickListener() { @Override public void onItemClick(RestoreModel model) { showRestore(model); } }); mPresenter = new ConfigPresenter(getContext().getApplicationContext(), this); <DeepExtract> adapter.showData(mPresenter.getRestoreFiles()); swipeRefreshLayout.setRefreshing(false); </DeepExtract> }
AppOpsX
positive
3,013
public Model create(File repoDir, String jarPath) { try { File pomFile = toPomFile(repoDir, model); FileUtils.touch(pomFile); FileOutputStream s = new FileOutputStream(pomFile); new MavenXpp3Writer().write(s, model); s.flush(); s.close(); if (!StringUtils.equals(model.getPackaging(), "pom")) { File srcFile = new File(jarPath); File destFile = toArtifactFile(repoDir, model); FileUtils.copyFile(srcFile, destFile); createChecksums(destFile); } if (originalText != null && demagedText != null) { String pomText = FileUtils.readFileToString(pomFile); pomText = pomText.replace(originalText, demagedText); FileUtils.writeStringToFile(pomFile, pomText); } createChecksums(pomFile); } catch (Exception e) { throw new RuntimeException(e); } return model; }
public Model create(File repoDir, String jarPath) { <DeepExtract> try { File pomFile = toPomFile(repoDir, model); FileUtils.touch(pomFile); FileOutputStream s = new FileOutputStream(pomFile); new MavenXpp3Writer().write(s, model); s.flush(); s.close(); if (!StringUtils.equals(model.getPackaging(), "pom")) { File srcFile = new File(jarPath); File destFile = toArtifactFile(repoDir, model); FileUtils.copyFile(srcFile, destFile); createChecksums(destFile); } if (originalText != null && demagedText != null) { String pomText = FileUtils.readFileToString(pomFile); pomText = pomText.replace(originalText, demagedText); FileUtils.writeStringToFile(pomFile, pomText); } createChecksums(pomFile); } catch (Exception e) { throw new RuntimeException(e); } </DeepExtract> return model; }
redhat-repository-validator
positive
3,014
private boolean parseCloseRawBlock(PsiBuilder builder) { PsiBuilder.Marker closeRawBlockMarker = builder.mark(); if (!parseLeafToken(builder, END_RAW_BLOCK)) { closeRawBlockMarker.drop(); return false; } PsiBuilder.Marker mustacheNameMark = builder.mark(); PsiBuilder.Marker pathMarker = builder.mark(); if (parsePathSegments(builder)) { pathMarker.done(PATH); return true; } pathMarker.rollbackTo(); return false; mustacheNameMark.done(HbTokenTypes.MUSTACHE_NAME); if (builder.getTokenType() != CLOSE_RAW_BLOCK) { PsiBuilder.Marker unexpectedTokensMarker = builder.mark(); while (!builder.eof() && builder.getTokenType() != CLOSE_RAW_BLOCK && !RECOVERY_SET.contains(builder.getTokenType())) { builder.advanceLexer(); } recordLeafTokenError(CLOSE_RAW_BLOCK, unexpectedTokensMarker); } if (!builder.eof() && builder.getTokenType() == CLOSE_RAW_BLOCK) { parseLeafToken(builder, CLOSE_RAW_BLOCK); } closeRawBlockMarker.done(CLOSE_BLOCK_STACHE); return true; }
private boolean parseCloseRawBlock(PsiBuilder builder) { PsiBuilder.Marker closeRawBlockMarker = builder.mark(); if (!parseLeafToken(builder, END_RAW_BLOCK)) { closeRawBlockMarker.drop(); return false; } PsiBuilder.Marker mustacheNameMark = builder.mark(); PsiBuilder.Marker pathMarker = builder.mark(); if (parsePathSegments(builder)) { pathMarker.done(PATH); return true; } pathMarker.rollbackTo(); return false; mustacheNameMark.done(HbTokenTypes.MUSTACHE_NAME); <DeepExtract> if (builder.getTokenType() != CLOSE_RAW_BLOCK) { PsiBuilder.Marker unexpectedTokensMarker = builder.mark(); while (!builder.eof() && builder.getTokenType() != CLOSE_RAW_BLOCK && !RECOVERY_SET.contains(builder.getTokenType())) { builder.advanceLexer(); } recordLeafTokenError(CLOSE_RAW_BLOCK, unexpectedTokensMarker); } if (!builder.eof() && builder.getTokenType() == CLOSE_RAW_BLOCK) { parseLeafToken(builder, CLOSE_RAW_BLOCK); } </DeepExtract> closeRawBlockMarker.done(CLOSE_BLOCK_STACHE); return true; }
idea-handlebars
positive
3,015
public static <T> void createNoUserForbiddenTestPut(TestRestTemplate client, URI url, T object) { ParameterizedTypeReference<String> responseType = new ParameterizedTypeReference<>() { }; ResponseEntity<String> result = client.exchange(RequestEntity.put(url).body(object), responseType); assertThat(result.getStatusCode(), is(equalTo(HttpStatus.FORBIDDEN))); }
public static <T> void createNoUserForbiddenTestPut(TestRestTemplate client, URI url, T object) { <DeepExtract> ParameterizedTypeReference<String> responseType = new ParameterizedTypeReference<>() { }; ResponseEntity<String> result = client.exchange(RequestEntity.put(url).body(object), responseType); assertThat(result.getStatusCode(), is(equalTo(HttpStatus.FORBIDDEN))); </DeepExtract> }
FAIRDataPoint
positive
3,016
@NonNull @Override protected View makeCenterView() { dayLabels = activity.getResources().getStringArray(R.array.day_labels); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int maxDays = DateUtils.calculateDaysInMonth(year, month); days.clear(); boolean includeToday = driverHour <= 24; switch(preDays) { case 1: if (includeToday) { days.add(dayLabels[0]); } break; case 2: if (includeToday) { days.add(dayLabels[0]); days.add(dayLabels[1]); } else { days.add(dayLabels[1]); } break; case 3: if (includeToday) { days.add(dayLabels[0]); days.add(dayLabels[1]); days.add(dayLabels[2]); } else { days.add(dayLabels[1]); days.add(dayLabels[2]); } break; default: if (includeToday) { days.add(dayLabels[0]); days.add(dayLabels[1]); days.add(dayLabels[2]); } else { days.add(dayLabels[1]); days.add(dayLabels[2]); preDays = preDays - 1; } for (int i = preDays; i <= maxDays; i++) { days.add(dealDayLabel(DateUtils.fillZero(i))); } break; } if (hours.size() == 0) { LogUtils.verbose(this, "init hours before make view"); initHourData(); } if (minutes.size() == 0) { LogUtils.verbose(this, "init minutes before make view"); changeMinuteData(DateUtils.trimZero(selectedHour)); } LinearLayout layout = new LinearLayout(activity); layout.setOrientation(LinearLayout.HORIZONTAL); layout.setGravity(Gravity.CENTER); layout.setWeightSum(3); if (weightEnable) { wheelViewParams = new LinearLayout.LayoutParams(0, WRAP_CONTENT); wheelViewParams.weight = 1.0f; } else { wheelViewParams = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); } labelViewParams = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); final WheelView dayView = new WheelView(activity); final WheelView hourView = new WheelView(activity); final WheelView minuteView = new WheelView(activity); dayView.setCanLoop(canLoop); dayView.setTextSize(textSize); dayView.setSelectedTextColor(textColorFocus); dayView.setUnSelectedTextColor(textColorNormal); dayView.setAdapter(new ArrayWheelAdapter<>(days)); dayView.setCurrentItem(selectedDayIndex); dayView.setLineConfig(lineConfig); dayView.setDividerType(lineConfig.getDividerType()); dayView.setLayoutParams(wheelViewParams); dayView.setOnItemPickListener(new OnItemPickListener<String>() { @Override public void onItemPicked(int index, String item) { selectedDayIndex = index; if (onWheelListener != null) { onWheelListener.onDayWheeled(index, item); } } }); layout.addView(dayView); if (!TextUtils.isEmpty(dayLabel)) { if (isOuterLabelEnable()) { TextView labelView = new TextView(activity); labelView.setLayoutParams(labelViewParams); labelView.setTextColor(textColorFocus); labelView.setTextSize(textSize); labelView.setText(dayLabel); layout.addView(labelView); } else { dayView.setLabel(dayLabel); } } hourView.setCanLoop(canLoop); hourView.setTextSize(textSize); hourView.setSelectedTextColor(textColorFocus); hourView.setUnSelectedTextColor(textColorNormal); hourView.setDividerType(lineConfig.getDividerType()); hourView.setAdapter(new ArrayWheelAdapter<>(hours)); hourView.setCurrentItem(selectedHourIndex); hourView.setLineConfig(lineConfig); hourView.setLayoutParams(wheelViewParams); hourView.setOnItemPickListener(new OnItemPickListener<String>() { @Override public void onItemPicked(int index, String item) { selectedHourIndex = index; selectedMinuteIndex = 0; selectedHour = item; if (onWheelListener != null) { onWheelListener.onHourWheeled(index, item); } if (!canLinkage) { return; } changeMinuteData(DateUtils.trimZero(item)); minuteView.setAdapter(new ArrayWheelAdapter<>(minutes)); minuteView.setCurrentItem(selectedMinuteIndex); } }); layout.addView(hourView); if (!TextUtils.isEmpty(hourLabel)) { if (isOuterLabelEnable()) { TextView labelView = new TextView(activity); labelView.setLayoutParams(labelViewParams); labelView.setTextColor(textColorFocus); labelView.setTextSize(textSize); labelView.setText(hourLabel); layout.addView(labelView); } else { hourView.setLabel(hourLabel); } } minuteView.setCanLoop(canLoop); minuteView.setTextSize(textSize); minuteView.setSelectedTextColor(textColorFocus); minuteView.setUnSelectedTextColor(textColorNormal); minuteView.setAdapter(new ArrayWheelAdapter<>(minutes)); minuteView.setCurrentItem(selectedMinuteIndex); minuteView.setDividerType(lineConfig.getDividerType()); minuteView.setLineConfig(lineConfig); minuteView.setLayoutParams(wheelViewParams); layout.addView(minuteView); minuteView.setOnItemPickListener(new OnItemPickListener<String>() { @Override public void onItemPicked(int index, String item) { selectedMinuteIndex = index; selectedMinute = item; if (onWheelListener != null) { onWheelListener.onMinuteWheeled(index, item); } } }); if (!TextUtils.isEmpty(minuteLabel)) { if (isOuterLabelEnable()) { TextView labelView = new TextView(activity); labelView.setLayoutParams(labelViewParams); labelView.setTextColor(textColorFocus); labelView.setTextSize(textSize); labelView.setText(minuteLabel); layout.addView(labelView); } else { minuteView.setLabel(minuteLabel); } } return layout; }
@NonNull @Override protected View makeCenterView() { dayLabels = activity.getResources().getStringArray(R.array.day_labels); <DeepExtract> int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int maxDays = DateUtils.calculateDaysInMonth(year, month); days.clear(); boolean includeToday = driverHour <= 24; switch(preDays) { case 1: if (includeToday) { days.add(dayLabels[0]); } break; case 2: if (includeToday) { days.add(dayLabels[0]); days.add(dayLabels[1]); } else { days.add(dayLabels[1]); } break; case 3: if (includeToday) { days.add(dayLabels[0]); days.add(dayLabels[1]); days.add(dayLabels[2]); } else { days.add(dayLabels[1]); days.add(dayLabels[2]); } break; default: if (includeToday) { days.add(dayLabels[0]); days.add(dayLabels[1]); days.add(dayLabels[2]); } else { days.add(dayLabels[1]); days.add(dayLabels[2]); preDays = preDays - 1; } for (int i = preDays; i <= maxDays; i++) { days.add(dealDayLabel(DateUtils.fillZero(i))); } break; } </DeepExtract> if (hours.size() == 0) { LogUtils.verbose(this, "init hours before make view"); initHourData(); } if (minutes.size() == 0) { LogUtils.verbose(this, "init minutes before make view"); changeMinuteData(DateUtils.trimZero(selectedHour)); } LinearLayout layout = new LinearLayout(activity); layout.setOrientation(LinearLayout.HORIZONTAL); layout.setGravity(Gravity.CENTER); layout.setWeightSum(3); if (weightEnable) { wheelViewParams = new LinearLayout.LayoutParams(0, WRAP_CONTENT); wheelViewParams.weight = 1.0f; } else { wheelViewParams = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); } labelViewParams = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); final WheelView dayView = new WheelView(activity); final WheelView hourView = new WheelView(activity); final WheelView minuteView = new WheelView(activity); dayView.setCanLoop(canLoop); dayView.setTextSize(textSize); dayView.setSelectedTextColor(textColorFocus); dayView.setUnSelectedTextColor(textColorNormal); dayView.setAdapter(new ArrayWheelAdapter<>(days)); dayView.setCurrentItem(selectedDayIndex); dayView.setLineConfig(lineConfig); dayView.setDividerType(lineConfig.getDividerType()); dayView.setLayoutParams(wheelViewParams); dayView.setOnItemPickListener(new OnItemPickListener<String>() { @Override public void onItemPicked(int index, String item) { selectedDayIndex = index; if (onWheelListener != null) { onWheelListener.onDayWheeled(index, item); } } }); layout.addView(dayView); if (!TextUtils.isEmpty(dayLabel)) { if (isOuterLabelEnable()) { TextView labelView = new TextView(activity); labelView.setLayoutParams(labelViewParams); labelView.setTextColor(textColorFocus); labelView.setTextSize(textSize); labelView.setText(dayLabel); layout.addView(labelView); } else { dayView.setLabel(dayLabel); } } hourView.setCanLoop(canLoop); hourView.setTextSize(textSize); hourView.setSelectedTextColor(textColorFocus); hourView.setUnSelectedTextColor(textColorNormal); hourView.setDividerType(lineConfig.getDividerType()); hourView.setAdapter(new ArrayWheelAdapter<>(hours)); hourView.setCurrentItem(selectedHourIndex); hourView.setLineConfig(lineConfig); hourView.setLayoutParams(wheelViewParams); hourView.setOnItemPickListener(new OnItemPickListener<String>() { @Override public void onItemPicked(int index, String item) { selectedHourIndex = index; selectedMinuteIndex = 0; selectedHour = item; if (onWheelListener != null) { onWheelListener.onHourWheeled(index, item); } if (!canLinkage) { return; } changeMinuteData(DateUtils.trimZero(item)); minuteView.setAdapter(new ArrayWheelAdapter<>(minutes)); minuteView.setCurrentItem(selectedMinuteIndex); } }); layout.addView(hourView); if (!TextUtils.isEmpty(hourLabel)) { if (isOuterLabelEnable()) { TextView labelView = new TextView(activity); labelView.setLayoutParams(labelViewParams); labelView.setTextColor(textColorFocus); labelView.setTextSize(textSize); labelView.setText(hourLabel); layout.addView(labelView); } else { hourView.setLabel(hourLabel); } } minuteView.setCanLoop(canLoop); minuteView.setTextSize(textSize); minuteView.setSelectedTextColor(textColorFocus); minuteView.setUnSelectedTextColor(textColorNormal); minuteView.setAdapter(new ArrayWheelAdapter<>(minutes)); minuteView.setCurrentItem(selectedMinuteIndex); minuteView.setDividerType(lineConfig.getDividerType()); minuteView.setLineConfig(lineConfig); minuteView.setLayoutParams(wheelViewParams); layout.addView(minuteView); minuteView.setOnItemPickListener(new OnItemPickListener<String>() { @Override public void onItemPicked(int index, String item) { selectedMinuteIndex = index; selectedMinute = item; if (onWheelListener != null) { onWheelListener.onMinuteWheeled(index, item); } } }); if (!TextUtils.isEmpty(minuteLabel)) { if (isOuterLabelEnable()) { TextView labelView = new TextView(activity); labelView.setLayoutParams(labelViewParams); labelView.setTextColor(textColorFocus); labelView.setTextSize(textSize); labelView.setText(minuteLabel); layout.addView(labelView); } else { minuteView.setLabel(minuteLabel); } } return layout; }
android-pickers
positive
3,018
void complete(long maxIdleTimeMillis, long maxCacheTimeMillis) { this.maxIdleTime = SecondsOrMillis.fromMillisToInternal(maxIdleTimeMillis); this.maxCacheTime = SecondsOrMillis.fromMillisToInternal(maxCacheTimeMillis); flags |= STATE_COMPLETE; inputDate = SecondsOrMillis.fromMillisToInternal(currentTimeMillisEstimate() - Cache.baseTimeMillis); lastAccess = SecondsOrMillis.fromMillisToInternal(currentTimeMillisEstimate() - Cache.baseTimeMillis); }
void complete(long maxIdleTimeMillis, long maxCacheTimeMillis) { this.maxIdleTime = SecondsOrMillis.fromMillisToInternal(maxIdleTimeMillis); this.maxCacheTime = SecondsOrMillis.fromMillisToInternal(maxCacheTimeMillis); flags |= STATE_COMPLETE; inputDate = SecondsOrMillis.fromMillisToInternal(currentTimeMillisEstimate() - Cache.baseTimeMillis); <DeepExtract> lastAccess = SecondsOrMillis.fromMillisToInternal(currentTimeMillisEstimate() - Cache.baseTimeMillis); </DeepExtract> }
triava
positive
3,019
private static boolean isRYM(String arg, Entity e) { boolean inverted = isInverted(arg); double mult = Double.parseDouble(arg.split("=")[1]); return (e.getLocation().getPitch() < mult) != inverted; }
private static boolean isRYM(String arg, Entity e) { <DeepExtract> boolean inverted = isInverted(arg); double mult = Double.parseDouble(arg.split("=")[1]); return (e.getLocation().getPitch() < mult) != inverted; </DeepExtract> }
advanced-achievements
positive
3,020
public void testEmptyToNullCoercionForPrimitives() throws Exception { final String EMPTY = "\"\""; ObjectReader intR = MAPPER.readerFor(int.class); assertEquals(Integer.valueOf(0), intR.readValue(EMPTY)); try { intR.with(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).readValue("\"\""); fail("Should not have passed"); } catch (JsonMappingException e) { verifyException(e, "cannot coerce empty String"); } final String EMPTY = "\"\""; ObjectReader intR = MAPPER.readerFor(long.class); assertEquals(Long.valueOf(0), intR.readValue(EMPTY)); try { intR.with(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).readValue("\"\""); fail("Should not have passed"); } catch (JsonMappingException e) { verifyException(e, "cannot coerce empty String"); } final String EMPTY = "\"\""; ObjectReader intR = MAPPER.readerFor(double.class); assertEquals(Double.valueOf(0.0), intR.readValue(EMPTY)); try { intR.with(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).readValue("\"\""); fail("Should not have passed"); } catch (JsonMappingException e) { verifyException(e, "cannot coerce empty String"); } final String EMPTY = "\"\""; ObjectReader intR = MAPPER.readerFor(float.class); assertEquals(Float.valueOf(0.0f), intR.readValue(EMPTY)); try { intR.with(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).readValue("\"\""); fail("Should not have passed"); } catch (JsonMappingException e) { verifyException(e, "cannot coerce empty String"); } }
public void testEmptyToNullCoercionForPrimitives() throws Exception { final String EMPTY = "\"\""; ObjectReader intR = MAPPER.readerFor(int.class); assertEquals(Integer.valueOf(0), intR.readValue(EMPTY)); try { intR.with(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).readValue("\"\""); fail("Should not have passed"); } catch (JsonMappingException e) { verifyException(e, "cannot coerce empty String"); } final String EMPTY = "\"\""; ObjectReader intR = MAPPER.readerFor(long.class); assertEquals(Long.valueOf(0), intR.readValue(EMPTY)); try { intR.with(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).readValue("\"\""); fail("Should not have passed"); } catch (JsonMappingException e) { verifyException(e, "cannot coerce empty String"); } final String EMPTY = "\"\""; ObjectReader intR = MAPPER.readerFor(double.class); assertEquals(Double.valueOf(0.0), intR.readValue(EMPTY)); try { intR.with(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).readValue("\"\""); fail("Should not have passed"); } catch (JsonMappingException e) { verifyException(e, "cannot coerce empty String"); } <DeepExtract> final String EMPTY = "\"\""; ObjectReader intR = MAPPER.readerFor(float.class); assertEquals(Float.valueOf(0.0f), intR.readValue(EMPTY)); try { intR.with(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).readValue("\"\""); fail("Should not have passed"); } catch (JsonMappingException e) { verifyException(e, "cannot coerce empty String"); } </DeepExtract> }
jackson-blackbird
positive
3,021
private final void write128(byte[] out, int off) { out[off + 3] = (byte) ((s0 + mix128(s7, s4, s5, s6, 24) >> 24) & 0xff); out[off + 2] = (byte) ((s0 + mix128(s7, s4, s5, s6, 24) >> 16) & 0xff); out[off + 1] = (byte) ((s0 + mix128(s7, s4, s5, s6, 24) >> 8) & 0xff); out[off + 0] = (byte) (s0 + mix128(s7, s4, s5, s6, 24) & 0xff); out[off + 4 + 3] = (byte) ((s1 + mix128(s6, s7, s4, s5, 16) >> 24) & 0xff); out[off + 4 + 2] = (byte) ((s1 + mix128(s6, s7, s4, s5, 16) >> 16) & 0xff); out[off + 4 + 1] = (byte) ((s1 + mix128(s6, s7, s4, s5, 16) >> 8) & 0xff); out[off + 4 + 0] = (byte) (s1 + mix128(s6, s7, s4, s5, 16) & 0xff); out[off + 8 + 3] = (byte) ((s2 + mix128(s5, s6, s7, s4, 8) >> 24) & 0xff); out[off + 8 + 2] = (byte) ((s2 + mix128(s5, s6, s7, s4, 8) >> 16) & 0xff); out[off + 8 + 1] = (byte) ((s2 + mix128(s5, s6, s7, s4, 8) >> 8) & 0xff); out[off + 8 + 0] = (byte) (s2 + mix128(s5, s6, s7, s4, 8) & 0xff); out[off + 12 + 3] = (byte) ((s3 + mix128(s4, s5, s6, s7, 0) >> 24) & 0xff); out[off + 12 + 2] = (byte) ((s3 + mix128(s4, s5, s6, s7, 0) >> 16) & 0xff); out[off + 12 + 1] = (byte) ((s3 + mix128(s4, s5, s6, s7, 0) >> 8) & 0xff); out[off + 12 + 0] = (byte) (s3 + mix128(s4, s5, s6, s7, 0) & 0xff); }
private final void write128(byte[] out, int off) { out[off + 3] = (byte) ((s0 + mix128(s7, s4, s5, s6, 24) >> 24) & 0xff); out[off + 2] = (byte) ((s0 + mix128(s7, s4, s5, s6, 24) >> 16) & 0xff); out[off + 1] = (byte) ((s0 + mix128(s7, s4, s5, s6, 24) >> 8) & 0xff); out[off + 0] = (byte) (s0 + mix128(s7, s4, s5, s6, 24) & 0xff); out[off + 4 + 3] = (byte) ((s1 + mix128(s6, s7, s4, s5, 16) >> 24) & 0xff); out[off + 4 + 2] = (byte) ((s1 + mix128(s6, s7, s4, s5, 16) >> 16) & 0xff); out[off + 4 + 1] = (byte) ((s1 + mix128(s6, s7, s4, s5, 16) >> 8) & 0xff); out[off + 4 + 0] = (byte) (s1 + mix128(s6, s7, s4, s5, 16) & 0xff); out[off + 8 + 3] = (byte) ((s2 + mix128(s5, s6, s7, s4, 8) >> 24) & 0xff); out[off + 8 + 2] = (byte) ((s2 + mix128(s5, s6, s7, s4, 8) >> 16) & 0xff); out[off + 8 + 1] = (byte) ((s2 + mix128(s5, s6, s7, s4, 8) >> 8) & 0xff); out[off + 8 + 0] = (byte) (s2 + mix128(s5, s6, s7, s4, 8) & 0xff); <DeepExtract> out[off + 12 + 3] = (byte) ((s3 + mix128(s4, s5, s6, s7, 0) >> 24) & 0xff); out[off + 12 + 2] = (byte) ((s3 + mix128(s4, s5, s6, s7, 0) >> 16) & 0xff); out[off + 12 + 1] = (byte) ((s3 + mix128(s4, s5, s6, s7, 0) >> 8) & 0xff); out[off + 12 + 0] = (byte) (s3 + mix128(s4, s5, s6, s7, 0) & 0xff); </DeepExtract> }
burst-mining-system
positive
3,022