auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void processException(Exception e, String operation) throws RemoteFileChangedException { if (e instanceof AmazonServiceException) { AmazonServiceException serviceException = (AmazonServiceException) e; <START> if (serviceException.getStatusCode() == 412) { <END> versionMismatches.incrementAndGet(); throw new RemoteFileChangedException(uri, operation, String.format( RemoteFileChangedException.PRECONDITIONS_NOT_MET + " on %s." + " Version %s was unavailable", getSource(), getRevisionId()), serviceException); } } }</code><technical_language>Please do magic number - actually, http error codes for this a constant</technical_language>

Target:
public void processException(Exception e, String operation) throws RemoteFileChangedException { if (e instanceof AmazonServiceException) { AmazonServiceException serviceException = (AmazonServiceException) e; if (serviceException.getStatusCode() == SC_PRECONDITION_FAILED) { versionMismatches.incrementAndGet(); throw new RemoteFileChangedException(uri, operation, String.format( RemoteFileChangedException.PRECONDITIONS_FAILED + " on %s." + " Version %s was unavailable", getSource(), getRevisionId()), serviceException); } } }
Source:
<code>public void train() throws IOException { List<String> commands = buildCommands(); ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(new File("./")); LOGGER.info("Start trainning sub process. Commands {}", commands.toString()); <START> Process p = pb.start(); <END> }</code><technical_language>python console log re-directed? is redirect console log Java console shifu.log</technical_language>

Target:
public void train() throws IOException { List<String> commands = buildCommands(); ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(new File("./")); LOGGER.info("Start trainning sub process. Commands {}", commands.toString()); Process p = pb.start(); StreamCollector sc = new StreamCollector(p.getInputStream()); sc.start(); try { p.waitFor(); sc.close(); } catch (InterruptedException e) { throw new RuntimeException(e); } }
Source:
<code>@Override public ExecuteResult prepareAndExecute(StatementHandle h, String sql, long maxRowCount, int maxRowsInFirstFrame, PrepareCallback callback) throws NoSuchStatementException { final CalcitePrepare.CalciteSignature<Object> signature; try { final int updateCount; synchronized (callback.getMonitor()) { callback.clear(); final CalciteConnectionImpl calciteConnection = getConnection(); final CalciteServerStatement statement = calciteConnection.server.getStatement(h); final Context context = statement.createPrepareContext(); final CalcitePrepare.Query<Object> query = toQuery(context, sql); signature = calciteConnection.parseQuery(query, context, maxRowCount); statement.setSignature(signature); switch (signature.statementType) { case CREATE: case DROP: case ALTER: case OTHER_DDL: updateCount = 0; break; default: updateCount = -1; break; } callback.assign(signature, null, updateCount); } callback.execute(); final MetaResultSet metaResultSet = <START> new MetaResultSetImpl(h.connectionId, h.id, false, signature, null, updateCount); <END> return new ExecuteResult(ImmutableList.of(metaResultSet)); } catch (SQLException e) { throw new RuntimeException(e); } }</code><technical_language>I prefer updating Avatica add another MetaResultSet.create updateCount parameter, instead of adding a subclass</technical_language>

Target:
@Override public ExecuteResult prepareAndExecute(StatementHandle h, String sql, long maxRowCount, int maxRowsInFirstFrame, PrepareCallback callback) throws NoSuchStatementException { final CalcitePrepare.CalciteSignature<Object> signature; try { final int updateCount; synchronized (callback.getMonitor()) { callback.clear(); final CalciteConnectionImpl calciteConnection = getConnection(); final CalciteServerStatement statement = calciteConnection.server.getStatement(h); final Context context = statement.createPrepareContext(); final CalcitePrepare.Query<Object> query = toQuery(context, sql); signature = calciteConnection.parseQuery(query, context, maxRowCount); statement.setSignature(signature); switch (signature.statementType) { case CREATE: case DROP: case ALTER: case OTHER_DDL: updateCount = 0; break; default: updateCount = -1; break; } callback.assign(signature, null, updateCount); } callback.execute(); final MetaResultSet metaResultSet = MetaResultSet.create(h.connectionId, h.id, false, signature, null, updateCount); return new ExecuteResult(ImmutableList.of(metaResultSet)); } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
<code>private InputStream generateStream() { final Ds3ObjectList objects = new Ds3ObjectList(); objects.setObjects(this.ds3Objects); objects.setPriority(this.priority); objects.setWriteOptimization(this.writeOptimization); objects.setChunkClientProcessingOrderGuarantee(this.chunkOrdering); final StringBuilder xmlOutputBuilder = new StringBuilder(); <START> if (this.getCommand() == BulkCommand.GET) { <END> xmlOutputBuilder.append(XmlOutput.toXml(objects, true)); } else { xmlOutputBuilder.append(XmlOutput.toXml(objects, false)); } final byte[] stringBytes = xmlOutputBuilder.toString().getBytes(); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }</code><technical_language>Is this right logic? care bulk PUT. want add filter for request besides bulk put. invert this logic</technical_language>

Target:
private InputStream generateStream() { final Ds3ObjectList objects = new Ds3ObjectList(); objects.setObjects(this.ds3Objects); objects.setPriority(this.priority); objects.setWriteOptimization(this.writeOptimization); objects.setChunkClientProcessingOrderGuarantee(this.chunkOrdering); final StringBuilder xmlOutputBuilder = new StringBuilder(); if (this.getCommand() == BulkCommand.PUT) { xmlOutputBuilder.append(XmlOutput.toXml(objects, true)); } else { xmlOutputBuilder.append(XmlOutput.toXml(objects, false)); } final byte[] stringBytes = xmlOutputBuilder.toString().getBytes(); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }
Source:
<code>public static long parseBytes(String input, ConfigOrigin originForException, String pathForException) { String s = ConfigImplUtil.unicodeTrim(input); String unitString = getUnits(s); String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() - unitString.length())); if (numberString.length() == 0) throw new ConfigException.BadValue(originForException, pathForException, "No number in size-in-bytes value '" + input + "'"); MemoryUnit units = MemoryUnit.parseUnit(unitString); if (units == null) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes unit '" + unitString + "' (try k, K, kB, KiB, kilobytes, kibibytes)"); } try { BigInteger result; if (numberString.matches("[0-9]+")) { result = units.bytes.multiply(new BigInteger(numberString)); } else { BigDecimal resultDecimal = (new BigDecimal(units.bytes)).multiply(new BigDecimal(numberString)); result = resultDecimal.toBigInteger(); } if (result.bitLength() < 64) return result.longValue(); else throw new ConfigException.BadValue(originForException, pathForException, <START> "size-in-bytes value is out of range for a 64-bit long: '" + input + "'"); <END> } catch (NumberFormatException e) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes number '" + numberString + "'"); } }</code><technical_language>this is ConfigMemorySize.toBytes throw for out of range</technical_language>

Target:
public static BigInteger parseBytes(String input, ConfigOrigin originForException, String pathForException) { String s = ConfigImplUtil.unicodeTrim(input); String unitString = getUnits(s); String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() - unitString.length())); if (numberString.length() == 0) throw new ConfigException.BadValue(originForException, pathForException, "No number in size-in-bytes value '" + input + "'"); MemoryUnit units = MemoryUnit.parseUnit(unitString); if (units == null) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes unit '" + unitString + "' (try k, K, kB, KiB, kilobytes, kibibytes)"); } try { BigInteger result; if (numberString.matches("[0-9]+")) { result = units.bytes.multiply(new BigInteger(numberString)); } else { BigDecimal resultDecimal = (new BigDecimal(units.bytes)).multiply(new BigDecimal(numberString)); result = resultDecimal.toBigInteger(); } return result; } catch (NumberFormatException e) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes number '" + numberString + "'"); } }
Source:
<code><START> public AbstractFFmpegStreamBuilder() { <END> this.parent = null; }</code><technical_language>constructor public</technical_language>

Target:
protected AbstractFFmpegStreamBuilder() { this.parent = null; }
Source:
<code>protected void processStream(String documentId, InputStream contentStream) throws IOException, InterruptedException { currentProgress++; <START> if (currentProgress > 0 && currentProgress % progresLogInterval == 0) { <END> log.info("metadata extaction progress: " + currentProgress + ", time taken to process " + progresLogInterval + " elements: " + ((System.currentTimeMillis() - intervalTime) / 1000) + " secs"); intervalTime = System.currentTimeMillis(); } if (excludedIds.contains(documentId)) { log.info("skipping processing for excluded id " + documentId); return; } log.info("starting processing for id: " + documentId); long startTime = System.currentTimeMillis(); try { ContentExtractor extractor = new ContentExtractor(interruptionTimeoutSecs); extractor.setPDF(contentStream); try { handleContent(extractor, documentId); } catch (Exception e) { log.error((e.getCause() instanceof InvalidPdfException) ? "Invalid PDF file" : "got unexpected exception, just logging", e); handleException(e, documentId); return; } handleProcessingTime(System.currentTimeMillis() - startTime, documentId); } catch (AnalysisException e) { mos.close(); throw new RuntimeException(e); } }</code><technical_language>currentProgress is >0. condition removed</technical_language>

Target:
protected void processStream(String documentId, InputStream contentStream) throws IOException, InterruptedException { currentProgress++; if (currentProgress % progresLogInterval == 0) { log.info("metadata extaction progress: " + currentProgress + ", time taken to process " + progresLogInterval + " elements: " + ((System.currentTimeMillis() - intervalTime) / 1000) + " secs"); intervalTime = System.currentTimeMillis(); } if (excludedIds.contains(documentId)) { log.info("skipping processing for excluded id " + documentId); return; } log.info("starting processing for id: " + documentId); long startTime = System.currentTimeMillis(); try { ContentExtractor extractor = new ContentExtractor(interruptionTimeoutSecs); extractor.setPDF(contentStream); try { handleContent(extractor, documentId); } catch (Exception e) { log.error((e.getCause() instanceof InvalidPdfException) ? "Invalid PDF file" : "got unexpected exception, just logging", e); handleException(e, documentId); return; } handleProcessingTime(System.currentTimeMillis() - startTime, documentId); } catch (AnalysisException e) { mos.close(); throw new RuntimeException(e); } }
Source:
<code>public void testGetStrippedVdsUniqueIdWithoutValidChars() { RegisterVdsParameters paramsMock = getQueryParameters(); when(paramsMock.getVdsUniqueId()).thenReturn("^%^"); String result = getQuery().getStrippedVdsUniqueId(); <START> assertEquals("", result); <END> }</code><technical_language>Please add assertion message asserEquals() call</technical_language>

Target:
public void testGetStrippedVdsUniqueIdWithoutValidChars() { RegisterVdsParameters paramsMock = getQueryParameters(); when(paramsMock.getVdsUniqueId()).thenReturn("^%^"); String result = getQuery().getStrippedVdsUniqueId(); assertEquals("Vds id is not empty as expected", result, ""); }
Source:
<code>public JSONObject printBoxBarcodes(HttpSession session, JSONObject json) { <START> return ControllerHelperServiceUtils.printBarcodes(securityManager, printManager, json, new BarcodePrintAssister<Box>() { <END> @Override public Box fetch(long id) throws IOException { return requestManager.getBoxById(id); } @Override public void store(Box item, User user) throws IOException { item.setLastModifier(user); requestManager.saveBox(item); } @Override public String groupName() { return "boxes"; } @Override public String idName() { return "boxId"; } @Override public Iterable<Box> fetchAll(long projectId) throws IOException { return Collections.emptySet(); } }); }</code><technical_language>BarcodePrintAssister private final member instead of new anonymous class request. in other ControllerHelperServices</technical_language>

Target:
public JSONObject printBoxBarcodes(HttpSession session, JSONObject json) { return ControllerHelperServiceUtils.printBarcodes(printerService, json, new BarcodePrintAssister<Box>() { @Override public Box fetch(long id) throws IOException { return requestManager.getBoxById(id); } @Override public void store(Box item) throws IOException { requestManager.saveBox(item); } @Override public String getGroupName() { return "boxes"; } @Override public String getIdName() { return "boxId"; } @Override public Iterable<Box> fetchAll(long projectId) throws IOException { throw new UnsupportedOperationException(); } }); }
Source:
<code>private void evict() { int evictionIndex = heads.getEvictionIndex(); if (evictionIndex < 0) { <START> StringBuilder sb = new StringBuilder("Storage Engine and Eviction Failed - Everything Pinned (" + getSize() + " mappings) \n"); <END> sb.append("Storage Engine : ").append(chainStorage); throw new OversizeMappingException(sb.toString()); } else { heads.evict(evictionIndex, false); } }</code><technical_language>This winds allocating (2) StringBuilder instances -- append instead of concatenation</technical_language>

Target:
private void evict() { int evictionIndex = heads.getEvictionIndex(); if (evictionIndex < 0) { StringBuilder sb = new StringBuilder("Storage Engine and Eviction Failed - Everything Pinned ("); sb.append(getSize()).append(" mappings) \n").append("Storage Engine : ").append(chainStorage); throw new OversizeMappingException(sb.toString()); } else { heads.evict(evictionIndex, false); } }
Source:
<code>public HiveOrcAggregatedMemoryContext() { <START> this.delegate = newSimpleAggregatedMemoryContext(); <END> }</code><technical_language>this(this.delegate = newSimpleAggregatedMemoryContext());</technical_language>

Target:
public HiveOrcAggregatedMemoryContext() { this(newSimpleAggregatedMemoryContext()); }
Source:
<code>public static void withCategories(final BlockingSphereClient client, final List<Supplier<? extends CategoryDraft>> creator, final Consumer<List<Category>> user) { List<Category> categories = creator.stream().map(singleCreator -> { final CategoryDraft categoryDraft = singleCreator.get(); final String slug = englishSlugOf(categoryDraft); final PagedQueryResult<Category> pagedQueryResult = client.executeBlocking(CategoryQuery.of().bySlug(Locale.ENGLISH, slug)); pagedQueryResult.head().ifPresent( category -> client.executeBlocking(CategoryDeleteCommand.of(category)) ); final Category category = client.executeBlocking(CategoryCreateCommand.of(categoryDraft)); LOGGER.debug(() -> "created category " + category.getSlug() + " id: " + category.getId()); return category; }).collect(Collectors.toList()); try { user.accept(categories); } finally { categories.forEach(category -> { <START> final PagedQueryResult<Category> res = client.executeBlocking(CategoryQuery.of().byId(category.getId())); <END> client.executeBlocking(CategoryDeleteCommand.of(res.head().get())); LOGGER.debug(() -> "deleted category " + category.getId()); }); } }</code><technical_language>CategoryDeleteCommand I code copied a category ;-)</technical_language>

Target:
public static void withCategories(final BlockingSphereClient client, final List<Supplier<? extends CategoryDraft>> creator, final Consumer<List<Category>> user) { List<Category> categories = creator.stream().map(singleCreator -> { final CategoryDraft categoryDraft = singleCreator.get(); final String slug = englishSlugOf(categoryDraft); final PagedQueryResult<Category> pagedQueryResult = client.executeBlocking(CategoryQuery.of().bySlug(Locale.ENGLISH, slug)); pagedQueryResult.head().ifPresent( category -> client.executeBlocking(CategoryDeleteCommand.of(category)) ); final Category category = client.executeBlocking(CategoryCreateCommand.of(categoryDraft)); return category; }).collect(Collectors.toList()); try { user.accept(categories); } finally { categories.forEach(category -> { client.executeBlocking(CategoryDeleteCommand.of(category)); }); } }
Source:
<code>public Object[] getChildren(Object parent) { ArrayList<UMLRTProtocolMessage> protocolMsgs = new ArrayList<>(); EList<UMLRTProtocol> allProtocols = new UniqueEList<>(); for (UMLRTProtocol protocol : protocols) { allProtocols.addAll(ProtocolUtils.getAllProtocols(protocol)); } for (UMLRTProtocol protocol : allProtocols) { if (ProtocolUtils.isCommonProtocol(protocols, protocol)) { addProtocolMsgs(protocolMsgs, protocol); } } return protocolMsgs.stream() .sorted(UMLRTInheritanceKind.facadeComparator()) <START> .map(new Function<UMLRTProtocolMessage, Event>() { <END> @Override public Event apply(UMLRTProtocolMessage msg) { return msg.toReceiveEvent(); } }) .toArray(); }</code><technical_language>a method reference, here: .map(UMLTProtocolMessage::toReceiveEvent) a bit easier read but, compiler is clever, saves creating a .class file for function. :-)</technical_language>

Target:
public Object[] getChildren(Object parent) { ArrayList<UMLRTProtocolMessage> protocolMsgs = new ArrayList<>(); EList<UMLRTProtocol> allProtocols = new UniqueEList<>(); for (UMLRTProtocol protocol : protocols) { allProtocols.addAll(ProtocolUtils.getAllProtocols(protocol)); } for (UMLRTProtocol protocol : allProtocols) { if (ProtocolUtils.isCommonProtocol(protocols, protocol)) { addProtocolMsgs(protocolMsgs, protocol); } } return protocolMsgs.stream() .sorted(UMLRTInheritanceKind.facadeComparator()) .map(UMLRTProtocolMessage::toReceiveEvent) .toArray(); }
Source:
<code>public String getName() { return <START> "Lambda vars"; <END> }</code><technical_language>this in variables view I name "Lambda", details of object showing lambda name etc</technical_language>

Target:
public String getName() { return "Lambda"; }
Source:
<code>public CoapEndpoint(Connector connector, NetworkConfig config) { this.config = config; this.connector = connector; if (connector.isTcp()) { this.matcher = new TcpMatcher(config); this.coapstack = new CoapTcpStack(config, new OutboxImpl()); this.serializer = new Serializer(new TcpDataSerializer()); this.parser = new TcpDataParser(); } else { <START> this.matcher = new TcpMatcher(config); <END> this.coapstack = new CoapUdpStack(config, new OutboxImpl()); this.serializer = new Serializer(new UdpDataSerializer()); this.parser = new UdpDataParser(); } this.connector.setRawDataReceiver(new InboxImpl()); }</code><technical_language>new UdpMatcher(config) ..</technical_language>

Target:
public CoapEndpoint(Connector connector, NetworkConfig config) { this.config = config; this.connector = connector; if (connector.isTcp()) { this.matcher = new TcpMatcher(config); this.coapstack = new CoapTcpStack(config, new OutboxImpl()); this.serializer = new Serializer(new TcpDataSerializer()); this.parser = new TcpDataParser(); } else { this.matcher = new UdpMatcher(config); this.coapstack = new CoapUdpStack(config, new OutboxImpl()); this.serializer = new Serializer(new UdpDataSerializer()); this.parser = new UdpDataParser(); } this.connector.setRawDataReceiver(new InboxImpl()); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bot); RecyclerView directions = Views.findById(this, R.id.bot_directions); directions.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); directions.setLayoutManager(layoutManager); RecyclerView.Adapter adapter = new DirectionAdapter(LayoutInflater.from(this), Collections.<Direction>emptyList()); directions.setAdapter(adapter); <START> ControllerView controllerView = Views.findById(this, R.id.bot_debug_controls); <END> controllerView.setControllerListener(controllerListener); handler = new Handler(); }</code><technical_language>Added a controller view send commands straight Arduino</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bot); RecyclerView directions = Views.findById(this, R.id.bot_directions); directions.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); directions.setLayoutManager(layoutManager); RecyclerView.Adapter adapter = new DirectionAdapter(LayoutInflater.from(this), Collections.<Direction>emptyList()); directions.setAdapter(adapter); ControllerView controllerView = Views.findById(this, R.id.bot_debug_controls); controllerView.setControllerListener(controllerListener); Handler handler = new Handler(); commandRepeater = new CommandRepeater(commandRepeatedListener, handler); }
Source:
<code>public String getEditorTitle() { <START> try { return String.format("Table Report - Merge View"); } catch (Exception ex) { } <END> return "Table Report - Merge View"; }</code><technical_language>Remove lines superfluous now, original method bizarre. Don? Ryan</technical_language>

Target:
public String getEditorTitle() { try { Branch branch = BranchManager.getBranch(sourceBranch); return String.format("Table Report - Merge View [%s]", branch.toStringWithId()); } catch (Exception ex) { } return "Table Report - Merge View"; }
Source:
<code>private void initMigrationMode() { ArrayList<EntityModel> migrationModes = new ArrayList<EntityModel>(); Constants constants = ConstantsManager.getInstance().getConstants(); migrationModes.add(new EntityModel(constants.autoAndManMigration(), MigrationSupport.MIGRATABLE)); migrationModes.add(new EntityModel(constants.manualMigrationOnly(), MigrationSupport.IMPLICITLY_NON_MIGRATABLE)); <START> migrationModes.add(new EntityModel(constants.noMigration(), MigrationSupport.PINNED_TO_HOST)); <END> getMigrationMode().setItems(migrationModes); getDisplayProtocol().getSelectedItemChangedEvent().addListener(this); }</code><technical_language>constant EntityModels</technical_language>

Target:
private void initMigrationMode() { ArrayList<EntityModel> migrationModes = new ArrayList<EntityModel>(); Constants constants = ConstantsManager.getInstance().getConstants(); MIGRATABLE_ENTITY.setTitle(constants.autoAndManMigration()); IMPLICITLY_NON_MIGRATABLE_ENTITY.setTitle(constants.manualMigrationOnly()); PINNED_TO_HOST_ENTITY.setTitle(constants.noMigration()); migrationModes.add(MIGRATABLE_ENTITY); migrationModes.add(IMPLICITLY_NON_MIGRATABLE_ENTITY); migrationModes.add(PINNED_TO_HOST_ENTITY); getMigrationMode().setItems(migrationModes); }
Source:
<code>public void setup() throws Exception { <START> System.out.println("Executing setup"); <END> StateStoreProperties.get().setProperty(FalconJPAService.URL, url); Configuration localConf = new Configuration(); fs.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); fs.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); falconJPAService.init(); this.dfsCluster = EmbeddedCluster.newCluster("testCluster"); this.conf = dfsCluster.getConf(); }</code><technical_language>required</technical_language>

Target:
public void setup() throws Exception{ StateStoreProperties.get().setProperty(FalconJPAService.URL, url); Configuration localConf = new Configuration(); fs.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); fs.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); falconJPAService.init(); this.dfsCluster = EmbeddedCluster.newCluster("testCluster"); this.conf = dfsCluster.getConf(); }
Source:
<code>public void onInitialize() { SkeletalMeshComponent skeletalMesh = actor().skeletalMesh(); if (getNode().play != null) { List<?> animationListToPlay = (List<?>) actor().getComponentField(getNode().play); if (animationListToPlay != null) { skeletalMesh.animation = (MeshAnimation) animationListToPlay.get( random.nextInt(animationListToPlay.size())); } else { skeletalMesh.animation = null; } } if (getNode().loop != null) { skeletalMesh.animationPool.clear(); List<?> animationListToLoop = (List<?>) actor().getComponentField(getNode().loop); if (animationListToLoop != null) { <START> skeletalMesh.animationPool.addAll(animationListToLoop.stream().map(object -> (MeshAnimation) object).collect(Collectors.toList())); <END> } } skeletalMesh.loop = true; actor().save(skeletalMesh); }</code><technical_language>I find this more difficult read prefer original version here</technical_language>

Target:
public void onInitialize() { SkeletalMeshComponent skeletalMesh = actor().skeletalMesh(); if (getNode().play != null) { List<?> animationListToPlay = (List<?>) actor().getComponentField(getNode().play); if (animationListToPlay != null) { skeletalMesh.animation = (MeshAnimation) animationListToPlay.get( random.nextInt(animationListToPlay.size())); } else { skeletalMesh.animation = null; } } if (getNode().loop != null) { skeletalMesh.animationPool.clear(); List<?> animationListToLoop = (List<?>) actor().getComponentField(getNode().loop); if (animationListToLoop != null) { for (Object object : animationListToLoop) { skeletalMesh.animationPool.add((MeshAnimation) object); } } } skeletalMesh.loop = true; actor().save(skeletalMesh); }
Source:
<code>public ResponseHandler write(ResponseCallback callback, boolean startTimeout) throws ConnectionException, BusyConnectionException { ResponseHandler handler = new ResponseHandler(this, callback); dispatcher.add(handler); <START> Message.Request request = callback.request().copy(); <END> request.setStreamId(handler.streamId); if (isDefunct.get()) { dispatcher.removeHandler(handler, true); throw new ConnectionException(address, "Write attempt on defunct connection"); } if (isClosed()) { dispatcher.removeHandler(handler, true); throw new ConnectionException(address, "Connection has been closed"); } logger.trace("{}, stream {}, writing request {}", this, request.getStreamId(), request); writer.incrementAndGet(); if (DISABLE_COALESCING) { channel.writeAndFlush(request).addListener(writeHandler(request, handler)); } else { flush(new FlushItem(channel, request, writeHandler(request, handler))); } if (startTimeout) handler.startTimeout(); return handler; }</code><technical_language>Is is optimization copy worth it</technical_language>

Target:
public ResponseHandler write(ResponseCallback callback, boolean startTimeout) throws ConnectionException, BusyConnectionException { ResponseHandler handler = new ResponseHandler(this, callback); dispatcher.add(handler); Message.Request request = callback.request().setStreamId(handler.streamId); if (isDefunct.get()) { dispatcher.removeHandler(handler, true); throw new ConnectionException(address, "Write attempt on defunct connection"); } if (isClosed()) { dispatcher.removeHandler(handler, true); throw new ConnectionException(address, "Connection has been closed"); } logger.trace("{}, stream {}, writing request {}", this, request.getStreamId(), request); writer.incrementAndGet(); if (DISABLE_COALESCING) { channel.writeAndFlush(request).addListener(writeHandler(request, handler)); } else { flush(new FlushItem(channel, request, writeHandler(request, handler))); } if (startTimeout) handler.startTimeout(); return handler; }
Source:
<code>public static TableDataManager getTableDataManager(@Nonnull TableDataManagerConfig tableDataManagerConfig, @Nonnull String instanceId, @Nonnull ZkHelixPropertyStore<ZNRecord> propertyStore, @Nonnull ServerMetrics serverMetrics, @Nonnull HelixManager helixManager) { TableDataManager tableDataManager; switch (TableType.valueOf(tableDataManagerConfig.getTableDataManagerType())) { case OFFLINE: if (tableDataManagerConfig.isDimTable()) { tableDataManager = DimensionTableDataManager.createInstanceByTableName(tableDataManagerConfig.getTableName()); break; } <START> tableDataManager = new OfflineTableDataManager(); <END> break; case REALTIME: tableDataManager = new RealtimeTableDataManager(_segmentBuildSemaphore); break; default: throw new IllegalStateException(); } tableDataManager.init(tableDataManagerConfig, instanceId, propertyStore, serverMetrics, helixManager); return tableDataManager; }</code><technical_language>nit: else clearer</technical_language>

Target:
public static TableDataManager getTableDataManager(@Nonnull TableDataManagerConfig tableDataManagerConfig, @Nonnull String instanceId, @Nonnull ZkHelixPropertyStore<ZNRecord> propertyStore, @Nonnull ServerMetrics serverMetrics, @Nonnull HelixManager helixManager) { TableDataManager tableDataManager; switch (TableType.valueOf(tableDataManagerConfig.getTableDataManagerType())) { case OFFLINE: if (tableDataManagerConfig.isDimTable()) { tableDataManager = DimensionTableDataManager.createInstanceByTableName(tableDataManagerConfig.getTableName()); } else { tableDataManager = new OfflineTableDataManager(); } break; case REALTIME: tableDataManager = new RealtimeTableDataManager(_segmentBuildSemaphore); break; default: throw new IllegalStateException(); } tableDataManager.init(tableDataManagerConfig, instanceId, propertyStore, serverMetrics, helixManager); return tableDataManager; }
Source:
<code>public static Response<AssetReportGetResponse> waitTillReady(PlaidClient client, String assetReportToken) throws Exception { Response<AssetReportGetResponse> response; do { AssetReportGetRequest assetReportGet = new AssetReportGetRequest(assetReportToken); response = client.service().assetReportGet(assetReportGet).execute(); } while ( !response.isSuccessful() && response.errorBody() != null && <START> client.parseError(response).getErrorCode().equals("PRODUCT_NOT_READY") <END> ); return response; }</code><technical_language>add upperbound (liek 20 ro somethign) throw exception if times</technical_language>

Target:
public static Response<AssetReportGetResponse> waitTillReady( PlaidClient client, String assetReportToken) throws Exception { int NUM_RETRIES = 20; int INTER_REQUEST_SLEEP = 1000; int attempt = 0; Response<AssetReportGetResponse> response; do { AssetReportGetRequest assetReportGet = new AssetReportGetRequest(assetReportToken); response = client.service().assetReportGet(assetReportGet).execute(); attempt++; Thread.sleep(INTER_REQUEST_SLEEP); } while ( !response.isSuccessful() && response.errorBody() != null && client.parseError(response).getErrorCode().equals(PRODUCT_NOT_READY) && attempt < NUM_RETRIES ); if (!response.isSuccessful()) { throw new Exception( String.format("Could not get asset report. Failed with %s", client.parseError(response).getErrorMessage() )); } return response; }
Source:
<code>public RuleResult validate(final PasswordData passwordData) { final RuleResult result = new RuleResult(true); <START> passwordRules.stream().map((rule) -> rule.validate(passwordData)).filter((rr) -> !rr.isValid()).forEach((rr) -> { <END> result.setValid(false); result.getDetails().addAll(rr.getDetails()); }); return result; }</code><technical_language>More compact clear</technical_language>

Target:
public RuleResult validate(final PasswordData passwordData) { final RuleResult result = new RuleResult(true); for (Rule rule : passwordRules) { final RuleResult rr = rule.validate(passwordData); if (!rr.isValid()) { result.setValid(false); result.getDetails().addAll(rr.getDetails()); } } return result; }
Source:
<code>private void processSuccess(LockWatchStateUpdate.Success success) { Preconditions.checkState(latestVersion.isPresent(), "Must have a known version to process successful updates"); Optional<LockWatchVersion> snapshotVersion = snapshot.getSnapshotVersion(); Preconditions.checkState(snapshotVersion.isPresent(), "Must have a snapshot before processing successful updates"); if (success.lastKnownVersion() < snapshotVersion.get().version()) { throw new TransactionLockWatchFailedException( "Cannot process events before the oldest event. The transaction should be retried, although this" + " should only happen very rarely."); } if (success.lastKnownVersion() > latestVersion.get().version()) { assertNoEventsAreMissing(success.events()); <START> latestVersion = Optional.of(LockWatchVersion.of(success.logId(), eventStore.putAll(success.events()))); <END> } }</code><technical_language>of change in tests change VersionedEventStore#putAll LockWatchEvents</technical_language>

Target:
private void processSuccess(LockWatchStateUpdate.Success success) { Preconditions.checkState(latestVersion.isPresent(), "Must have a known version to process successful updates"); Optional<LockWatchVersion> snapshotVersion = snapshot.getSnapshotVersion(); Preconditions.checkState(snapshotVersion.isPresent(), "Must have a snapshot before processing successful updates"); if (success.lastKnownVersion() < snapshotVersion.get().version()) { throw new TransactionLockWatchFailedException( "Cannot process events before the oldest event. The transaction should be retried, although this" + " should only happen very rarely."); } if (success.lastKnownVersion() > latestVersion.get().version()) { LockWatchEvents events = new LockWatchEvents.Builder() .addAllEvents(success.events()) .build(); assertNoEventsAreMissing(events); latestVersion = Optional.of(LockWatchVersion.of(success.logId(), eventStore.putAll(events))); } }
Source:
<code>public static Slice stGeometryType(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { GeometryType geometryType = deserializeType(input); String type; switch (geometryType) { case POINT: type = "ST_Point"; break; case MULTI_POINT: type = "ST_MultiPoint"; break; case LINE_STRING: type = "ST_LineString"; break; case MULTI_LINE_STRING: type = "ST_MultiLineString"; break; case POLYGON: type = "ST_Polygon"; break; case MULTI_POLYGON: type = "ST_MultiPolygon"; break; case GEOMETRY_COLLECTION: type = "ST_GeomCollection"; break; default: <START> throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Unexpected geometry type: " + geometryType); <END> } return utf8Slice(type); }</code><technical_language>@jwass @findepi @arhimondr GeometryType enum lists types for serialization. Envelope type is efficiently serialize trivial polygons enable optimizations preserving fact polygon is a rectangle aligned coordinate axes ser-de (see #10327). Andrii pointed out clearer rename GeometryType GeometrySerializationType . If do that, add getStandardName method enum return type name ST_GeometryType expects. This new serialization type is added, obvious standard name needs provided for it. ST_GeometryType return ST_Polygon for envelopes</technical_language>

Target:
public static Slice stGeometryType(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { return GeometrySerde.getGeometryType(input).standardName(); }
Source:
<code>public static boolean isDebugSessionAlive(IServer server) { Collection<DebugSessionTracker> trackers = getTrackers(); if (!trackers.isEmpty()) { <START> return trackers.stream().findFirst().get().isDebugSessionAlive(server); <END> } return false; }</code><technical_language>is alive debug sessions for session? one</technical_language>

Target:
public static boolean isDebugSessionAlive(IServer server) { Collection<DebugSessionTracker> trackers = getTrackers(); if (trackers.isEmpty()) { return false; } for (DebugSessionTracker tracker : trackers) { if (!tracker.isDebugSessionAlive(server)) { return false; } } return true; }
Source:
<code>public static Set<String> getPrefTags(SharedPreferences prefs, Context context) { Set<String> tags = getPrefTags(prefs); <START> if (tags.isEmpty()) { <END> TagsHandler tagsHandler = KissApplication.getApplication(context).getDataHandler().getTagsHandler(); Set<String> list = tagsHandler.getAllTagsAsSet(); for (String tag : list) { tags.add(tag); if (tags.size() >= 5) break; } } return tags; }</code><technical_language>tags null (default value)</technical_language>

Target:
public static Set<String> getPrefTags(SharedPreferences prefs, Context context) { Set<String> prefTags = getPrefTags(prefs); if (prefTags == null || prefTags.isEmpty()) { Set<String> tags = new HashSet<>(5); TagsHandler tagsHandler = KissApplication.getApplication(context).getDataHandler().getTagsHandler(); Set<String> list = tagsHandler.getAllTagsAsSet(); for (String tag : list) { tags.add(tag); if (tags.size() >= 5) break; } return tags; } return prefTags; }
Source:
<code>public static void writeObjectToConfAsBase64(String key, Object obj, Configuration conf) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); <START> ObjectOutputStream oos = new ObjectOutputStream(baos); <END> oos.writeObject(obj); oos.close(); conf.set(key, new String(Base64.encodeBase64(baos.toByteArray()), "UTF-8")); }</code><technical_language>compress it... introduce kryo / chill deps, churn for a low-level lib</technical_language>

Target:
public static void writeObjectToConfAsBase64(String key, Object obj, Configuration conf) throws IOException { ByteArrayOutputStream baos = null; GZIPOutputStream gos = null; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); gos = new GZIPOutputStream(baos); oos = new ObjectOutputStream(gos); oos.writeObject(obj); } finally { Closeables.close(oos); Closeables.close(gos); Closeables.close(baos); } conf.set(key, new String(Base64.encodeBase64(baos.toByteArray()), "UTF-8")); }
Source:
<code>public void shouldProperlyHandleEqualNames() throws Exception { final MockFolder folder = rule.createFolder("FOO"); final FreeStyleProject prj = folder.createProject(FreeStyleProject.class, "FOO"); assertsPath("/FOO/FOO", null, prj); <START> assertsPath("FOO/FOO", null, prj); <END> assertsPath("./FOO", folder, prj); assertsPath(".", folder, folder); assertsPath("../FOO", folder, folder); assertsPath("../FOO/FOO", folder, prj); assertsPath("./FOO", prj, prj); assertsPath(".", prj, folder); assertsPath("../FOO", prj, folder); assertsPath("../FOO/FOO", prj, prj); }</code><technical_language>This is missing tests for FOO folder project</technical_language>

Target:
public void shouldProperlyHandleEqualNames() throws Exception { final MockFolder folder = rule.createFolder("FOO"); final FreeStyleProject prj = folder.createProject(FreeStyleProject.class, "FOO"); assertsPath("/FOO/FOO", null, prj); assertsPath("FOO/FOO", null, prj); assertsPath("FOO", folder, prj); assertsPath("./FOO", folder, prj); assertsPath(".", folder, folder); assertsPath("../FOO", folder, folder); assertsPath("../FOO/FOO", folder, prj); assertsPath("FOO", prj, prj); assertsPath("./FOO", prj, prj); assertsPath(".", prj, folder); assertsPath("../FOO", prj, folder); assertsPath("../FOO/FOO", prj, prj); }
Source:
<code>public int fill(FluidStack resource, boolean doFill) { int k = 0; for (IFluidHandler handler : subHandlers) { <START> k += handler.fill(resource, doFill); <END> } return k; }</code><technical_language>this break horribly dupe bugs is subtracted resource</technical_language>

Target:
public int fill(FluidStack resource, boolean doFill) { if (resource == null || resource.amount <= 0) return 0; resource = resource.copy(); int totalFillAmount = 0; for (IFluidHandler handler : subHandlers) { int fillAmount = handler.fill(resource, doFill); totalFillAmount += fillAmount; resource.amount -= fillAmount; if (resource.amount <= 0) break; } return totalFillAmount; }
Source:
<code><START> public String getHelpDoc() { <END> return picard.analysis.CollectInsertSizeMetrics.USAGE_SUMMARY + "Creates output with \"" + String.join("\", \"", OUTPUT_EXTENSIONS) + "\" appended to OUTPUT."; }</code><technical_language>this is for (all?) subclasses. If USAGE_SUMMARY OUTPUT_EXTENSIONS constructor arguments abstract methods duplicate code removed</technical_language>

Target:
public String getHelpDoc() { return getSummary() + "Creates output with \"" + String.join(", ",getExtensions()) + "\" appended to OUTPUT."; }
Source:
<code>private boolean selectDefaultSubpicLanguage() { String defaultAudioLang = uiMgr.get("default_audio_language", "English"); MediaLangInfo mli = (MediaLangInfo) mediaLangMap.get(defaultAudioLang); SubpictureFormat subs = this.currFile.getFileFormat().getSubpictureFormats(); for(int i = 0; i < subs.length; i++) { if(subs[i].getForced()) { <START> if(subs[i].getLanguage().equalsIgnoreCase(mli.twoChar)) <END> { System.out.println("Setting forced subtitle to index: " + i); playbackControl(DVD_CONTROL_SUBTITLE_CHANGE, i, -1); return true; } for(int j = 0; j < mli.threeChar.length; j++) { if(subs[i].getLanguage().equalsIgnoreCase(mli.threeChar[j])) { System.out.println("Setting forced subtitle to index: " + i); playbackControl(DVD_CONTROL_SUBTITLE_CHANGE, i, -1); return true; } } } } String defaultLang = uiMgr.get("default_subpic_language", ""); if (defaultLang == null || defaultLang.length() == 0) return true; return performLanguageMatch(defaultLang, getDVDAvailableSubpictures(), DVD_CONTROL_SUBTITLE_CHANGE, getDVDSubpicture()); }</code><technical_language>need handle case mli is null</technical_language>

Target:
private boolean selectDefaultSubpicLanguage() { String defaultAudioLang = uiMgr.get("default_audio_language", "English"); String defaultLang = uiMgr.get("default_subpic_language", ""); if(defaultLang == null || defaultLang.length() == 0) { String subs = getDVDAvailableSubpictures(); String forcedSubs = new String[subs.length]; boolean hasForcedSub = false; for(int i = 0; i < subs.length; i++) { if(subs[i].toLowerCase().indexOf("[" + Sage.rez("forced") + "]") != -1) { forcedSubs[i] = subs[i]; hasForcedSub = true; } else { forcedSubs[i] = ""; } } if(hasForcedSub) { return performLanguageMatch(defaultAudioLang, forcedSubs, DVD_CONTROL_SUBTITLE_CHANGE, getDVDSubpicture()); } else { return true; } } return performLanguageMatch(defaultLang, getDVDAvailableSubpictures(), DVD_CONTROL_SUBTITLE_CHANGE, getDVDSubpicture()); }
Source:
<code>public Response<Void> stageBlockWithResponse(String base64BlockId, InputStream data, long length, byte[] contentMd5, String leaseId, Duration timeout, Context context) { Objects.requireNonNull(data); <START> data.mark(Integer.MAX_VALUE); <END> Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length, BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE); Mono<Response<Void>> response = client.stageBlockWithResponse(base64BlockId, fbb.subscribeOn(Schedulers.elastic()), length, contentMd5, leaseId, context); return blockWithOptionalTimeout(response, timeout); }</code><technical_language>do mark Integer.MAX_VALUE? If call reset this read position of stream Integer.MAX_VALUE</technical_language>

Target:
public Response<Void> stageBlockWithResponse(String base64BlockId, InputStream data, long length, byte[] contentMd5, String leaseId, Duration timeout, Context context) { Objects.requireNonNull(data); Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length, BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE); Mono<Response<Void>> response = client.stageBlockWithResponse(base64BlockId, fbb.subscribeOn(Schedulers.elastic()), length, contentMd5, leaseId, context); return blockWithOptionalTimeout(response, timeout); }
Source:
<code>synchronized void submit(long offset, BigInteger v) { if (!validateOffset((int) offset) || v == null || chceckpoints[(int) offset] != null) { <START> return; <END> } if (s == -1L && offset >= 0) { lag[idx(offset)] = c = s = offset; } if (offset > s) { s = offset; } chceckpoints[(int) offset] = v; }</code><technical_language>modify implemented in ENG-10264</technical_language>

Target:
synchronized void submit(long offset, BigInteger v) { if (!validateOffset((int) offset) || v == null || chceckpoints[(int) offset] != null) { return; } if (s == -1L && offset >= 0) { lag[idx(offset)] = c = s = offset; } if ((offset - c) >= lag.length) { offer = offset; try { wait(gapTrackerCheckMaxTimeMs); } catch (InterruptedException e) { rateLimitedLog(Level.WARN, e, "Gap tracker wait was interrupted." + m_config.getResourceID().toString()); } } if (offset > s) { s = offset; } chceckpoints[(int) offset] = v; }
Source:
<code><START> Optional<A> load(I id) { <END> final AggregateReadRequest<I> request = new AggregateReadRequest<>(id, snapshotTrigger); final Optional<AggregateStateRecord> eventsFromStorage = aggregateStorage().read(request); if (eventsFromStorage.isPresent()) { final A result = create(id); final AggregateStateRecord aggregateStateRecord = eventsFromStorage.get(); final AggregateTransaction tx = AggregateTransaction.start(result); result.play(aggregateStateRecord); tx.commit(); return Optional.of(result); } return Optional.absent(); }</code><technical_language>Considering implementation details, I this method package. discuss</technical_language>

Target:
private Optional<A> load(I id) { final Optional<AggregateStateRecord> eventsFromStorage = fetchHistory(id); if (eventsFromStorage.isPresent()) { final A result = play(id, eventsFromStorage.get()); return Optional.of(result); } return Optional.absent(); }
Source:
<code>private Drawable getPlaceholderDrawable() { if (placeholderResId != 0) { if (Build.VERSION.SDK_INT >= 21) { return picasso.context.getDrawable(placeholderResId); } else if (Build.VERSION.SDK_INT >= 16) { return picasso.context.getResources().getDrawable(placeholderResId); } else { final int resolvedId; <START> TypedValue sTempValue = new TypedValue(); <END> picasso.context.getResources().getValue(placeholderResId, sTempValue, true); resolvedId = sTempValue.resourceId; return picasso.context.getResources().getDrawable(resolvedId); } } else { return placeholderDrawable; } }</code><technical_language>call this</technical_language>

Target:
private Drawable getPlaceholderDrawable() { if (placeholderResId != 0) { if (Build.VERSION.SDK_INT >= 21) { return picasso.context.getDrawable(placeholderResId); } else if (Build.VERSION.SDK_INT >= 16) { return picasso.context.getResources().getDrawable(placeholderResId); } else { TypedValue value = new TypedValue(); picasso.context.getResources().getValue(placeholderResId, value, true); return picasso.context.getResources().getDrawable(value.resourceId); } } else { return placeholderDrawable; } }
Source:
<code><START> public CommonPathCapabilities() { <END> }</code><technical_language>This is a static non-instantiable class, change constructor visibility private</technical_language>

Target:
private CommonPathCapabilities() { }
Source:
<code>public FakeHttpServletRequest( Map<String, String> parameterMap, Cookie[] cookies, String workspace) { this.parameterMap = parameterMap; this.cookies = cookies; this.workspace = workspace; this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) <START> .map(atts -> atts.getRequest()); <END> }</code><technical_language>if notice, a method reference here: this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(ServletRequestAttributes::getRequest);</technical_language>

Target:
public FakeHttpServletRequest( Map<String, String> parameterMap, Cookie[] cookies, String workspace) { this.parameterMap = parameterMap; this.cookies = cookies; this.workspace = workspace; this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(ServletRequestAttributes::getRequest); }
Source:
<code>public static int randomAvailablePort() { int port; try { ServerSocket socket = new ServerSocket(0); port = socket.getLocalPort(); socket.close(); <START> } catch (IOException e) { <END> throw new RuntimeException(e); } return port; }</code><technical_language>bubble exception? in test setup I guess throw</technical_language>

Target:
public static int randomAvailablePort() { try { ServerSocket socket = new ServerSocket(0); int port = socket.getLocalPort(); socket.close(); return port; } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>public static File mkdirs(File dir) throws IOException { try { return Files.createDirectories(dir.toPath()).toFile(); <START> } catch (UnsupportedOperationException e) { <END> throw new IOException(e); } }</code><technical_language><LINK_0> . @dwnusbaum added a utility method for recently, replace dir.toPath() byt fileToPath(dir)</technical_language>

Target:
public static File mkdirs(File dir) throws IOException { try { return Files.createDirectories(fileToPath(dir)).toFile(); } catch (UnsupportedOperationException e) { throw new IOException(e); } }