auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { debug(String.format("Thread %s is starting new connection", getName())); Session prevSession; while(!closed()) { prevSession = session; session = server.getNextSession(session); if (session == null) close(); if (closed()) break; if (session != prevSession) { initializeForSession(); } try { long timeStart = System.currentTimeMillis(); switch (session.state) { case Session.INIT: sessionInitialState(); if (session == null) break; case Session.ATTEXC: case Session.SECACC: case Session.CHKSEC: long currentTimeSlice; do { try { processCommands(); } catch (DRDASocketTimeoutException ste) { } currentTimeSlice = getTimeSlice(); } while ((currentTimeSlice <= 0) || (System.currentTimeMillis() - timeStart < currentTimeSlice)); break; default: agentError("Session in invalid state:" + session.state); } } catch (Exception e) { if (e instanceof DRDAProtocolException && ((DRDAProtocolException)e).isDisconnectException()) { debug("client went away"); closeSession(); } else { handleException(e); } } catch (Error error) { try { debug("encountered error " + error.getMessage()); error.printStackTrace(server.logWriter); closeSession(); } catch (Throwable t) { try { session.clientSocket.close(); } catch (IOException ioe) { } } finally { throw error; } } } debug(String.format("Ending connection thread %s", getName())); server.removeThread(this); }

Target:
public void run() { if(LOG.isDebugEnabled()) { LOG.debug(String.format("Thread %s is starting new connection", getName())); } Session prevSession; while(!closed()) { prevSession = session; session = server.getNextSession(session); if (session == null) close(); if (closed()) break; if (session != prevSession) { initializeForSession(); } try { long timeStart = System.currentTimeMillis(); switch (session.state) { case Session.INIT: sessionInitialState(); if (session == null) break; case Session.ATTEXC: case Session.SECACC: case Session.CHKSEC: long currentTimeSlice; do { try { processCommands(); } catch (DRDASocketTimeoutException ste) { } currentTimeSlice = getTimeSlice(); } while ((currentTimeSlice <= 0) || (System.currentTimeMillis() - timeStart < currentTimeSlice)); break; default: agentError("Session in invalid state:" + session.state); } } catch (Exception e) { if (e instanceof DRDAProtocolException && ((DRDAProtocolException)e).isDisconnectException()) { if(LOG.isDebugEnabled()) { LOG.debug("client went away"); } closeSession(); } else { handleException(e); } } catch (Error error) { try { if(LOG.isDebugEnabled()) { LOG.debug("encountered error", error); } error.printStackTrace(server.logWriter); closeSession(); } catch (Throwable t) { try { session.clientSocket.close(); } catch (IOException ioe) { } } finally { throw error; } } } if(LOG.isDebugEnabled()) { LOG.debug(String.format("Ending connection thread %s", getName())); } server.removeThread(this); }
Source:
public LockFactory createLockFactory(File indexDir, Properties dirConfiguration) { String defaultStrategy = indexDir == null ? "single" : "native"; String lockFactoryName = dirConfiguration.getProperty( Environment.LOCKING_STRATEGY, defaultStrategy ); if ( "simple".equals( lockFactoryName ) ) { if ( indexDir == null ) { throw new SearchException( "To use \"simple\" as a LockFactory strategy an indexBase path must be set" ); } return new SimpleFSLockFactory( indexDir ); } else if ( "native".equals( lockFactoryName ) ) { if ( indexDir == null ) { throw new SearchException( "To use \"native\" as a LockFactory strategy an indexBase path must be set" ); } return new NativeFSLockFactory( indexDir ); } else if ( "single".equals( lockFactoryName ) ) { return new SingleInstanceLockFactory(); } else if ( "none".equals( lockFactoryName ) ) { return NoLockFactory.getNoLockFactory(); } else { LockFactoryProvider lockFactoryFactory = ClassLoaderHelper.instanceFromName( LockFactoryProvider.class, lockFactoryName, Environment.LOCKING_STRATEGY, serviceManager ); return lockFactoryFactory.createLockFactory( indexDir, dirConfiguration ); } }

Target:
public LockFactory createLockFactory(File indexDir, Properties dirConfiguration) { String defaultStrategy = indexDir == null ? "single" : "native"; String lockFactoryName = dirConfiguration.getProperty( Environment.LOCKING_STRATEGY, defaultStrategy ); if ( "simple".equals( lockFactoryName ) ) { if ( indexDir == null ) { throw LOG.indexBasePathRequiredForLockingStrategy( "simple" ); } return new SimpleFSLockFactory( indexDir ); } else if ( "native".equals( lockFactoryName ) ) { if ( indexDir == null ) { throw LOG.indexBasePathRequiredForLockingStrategy( "native" ); } return new NativeFSLockFactory( indexDir ); } else if ( "single".equals( lockFactoryName ) ) { return new SingleInstanceLockFactory(); } else if ( "none".equals( lockFactoryName ) ) { return NoLockFactory.getNoLockFactory(); } else { LockFactoryProvider lockFactoryFactory = ClassLoaderHelper.instanceFromName( LockFactoryProvider.class, lockFactoryName, Environment.LOCKING_STRATEGY, serviceManager ); return lockFactoryFactory.createLockFactory( indexDir, dirConfiguration ); } }
Source:
private String buildMessage(int from, int to, int total) { if (total > 0) { return messages.fromIndexToIndexOfTotalCount(from, to, total); } else { return messages.fromIndexToIndex(from, to); } }

Target:
private String buildMessage(int from, int to, int total) { if (total > 0) { return messages.fromIndexToIndexOfTotalCount(from, to, total); } return messages.fromIndexToIndex(from, to); }
Source:
public void handle(PodEvent event) { final String podName = event.getPodName(); try { for (Entry<String, KubernetesMachineImpl> entry : machines.getMachines(getContext().getIdentity()).entrySet()) { final KubernetesMachineImpl machine = entry.getValue(); if (podName.startsWith(machine.getPodName())) { eventPublisher.sendMachineLogEnvent( entry.getKey(), event.getMessage(), event.getCreationTimeStamp(), getContext().getIdentity()); return; } } } catch (InfrastructureException e) { LOG.error("Error while machine fetching for logs publishing. Cause: {}", e.getMessage()); } }

Target:
public void handle(PodEvent event) { final String podName = event.getPodName(); try { for (Entry<String, KubernetesMachineImpl> entry : machines.getMachines(getContext().getIdentity()).entrySet()) { final KubernetesMachineImpl machine = entry.getValue(); if (machine.getPodName().equals(podName)) { eventPublisher.sendMachineLogEnvent( entry.getKey(), event.getMessage(), event.getCreationTimeStamp(), getContext().getIdentity()); return; } } } catch (InfrastructureException e) { LOG.error("Error while machine fetching for logs publishing. Cause: {}", e.getMessage()); } }
Source:
private void thawVm() { if (!shouldFreezeOrThawVm()) { return; } VDSReturnValue returnValue = null; boolean allowInconsistent = Config.<Boolean>getValue(ConfigValues.LiveSnapshotAllowInconsistent); try { returnValue = runVdsCommand(VDSCommandType.Thaw, new VdsAndVmIDVDSParametersBase( getVds().getId(), getVmId())); } catch (EngineException e) { if (!allowInconsistent) { handleThawVmFailure(e); return; } } if (returnValue != null && !returnValue.getSucceeded() && allowInconsistent) { handleThawVmFailure(new EngineException(EngineError.thawErr)); } }

Target:
private void thawVm() { if (!shouldFreezeOrThawVm()) { return; } VDSReturnValue returnValue = null; boolean allowInconsistent = Config.<Boolean>getValue(ConfigValues.LiveSnapshotAllowInconsistent); try { returnValue = runVdsCommand(VDSCommandType.Thaw, new VdsAndVmIDVDSParametersBase( getVds().getId(), getVmId())); } catch (EngineException e) { if (!allowInconsistent) { handleThawVmFailure(e); return; } } if (returnValue != null && !returnValue.getSucceeded() && !allowInconsistent) { handleThawVmFailure(new EngineException(EngineError.thawErr)); } }
Source:
private void waitMasterHandover(final Entity oldMaster, final Entity newMaster) { boolean masterChanged = Repeater.create() .backoff(Duration.millis(500), 1.2, Duration.FIVE_SECONDS) .limitTimeTo(Duration.ONE_MINUTE) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Entity master = getMasterNode(); return master != oldMaster && master != null; } }) .run(); if (!masterChanged) { LOG.warn("Timeout waiting for node to become master: " + newMaster + "."); } }

Target:
private void waitMasterHandover(final Entity oldMaster, final Entity newMaster) { boolean masterChanged = Repeater.create() .backoff(Duration.millis(50), 1.5, Duration.FIVE_SECONDS) .limitTimeTo(Duration.ONE_MINUTE) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Entity master = getMasterNode(); return !Objects.equal(master, oldMaster) && master != null; } }) .run(); if (!masterChanged) { LOG.warn("Timeout waiting for node to become master: " + newMaster + "."); } }
Source:
public void removeViewInLayout(@NonNull View view) { if (view.getAnimation() != null || (mTransitioningFragmentViews != null && mTransitioningFragmentViews.contains(view))) { addDisappearingFragmentView(view); } super.removeViewInLayout(view); }

Target:
public void removeViewInLayout(@NonNull View view) { if (view != mHoldView) { addDisappearingFragmentView(view); super.removeViewInLayout(view); } }
Source:
public <T> T setupClient(BiFunction<String, String, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(azureStorageConnectionString) || ImplUtils.isNullOrEmpty(azureStorageFileEndpoint)) { logger.asWarning().log("Connection string and endpoint must be set to build the testing client"); fail(); return null; } return clientBuilder.apply(azureStorageConnectionString, azureStorageFileEndpoint); }

Target:
public <T> T setupClient(BiFunction<String, String, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(azureStorageConnectionString) && ImplUtils.isNullOrEmpty(azureStorageFileEndpoint)) { logger.asWarning().log("Connection string and endpoint must be set to build the testing client"); fail(); return null; } return clientBuilder.apply(azureStorageConnectionString, azureStorageFileEndpoint); }
Source:
public boolean validateSource() { if (backlink.getAnnotation(Required.class) != null) { Utils.error(String.format( "The @LinkingObjects field \"%s.%s\" cannot be @Required.", targetClass, targetField)); } if ((sourceField == null) || sourceField.equals("")) { Utils.error(String.format( "The @LinkingObjects annotation for the field \"%s.%s\" must have a parameter identifying the link target.", targetClass, targetField)); return false; } if (sourceField.contains(".")) { Utils.error(String.format( "The parameter to the @LinkingObjects annotation for the field \"%s.%s\" contains a '.'. The use of '.' to specify fields in referenced classes is not supported.", targetClass, targetField)); return false; } if (!Utils.isRealmResults(backlink)) { Utils.error(String.format( "The field \"%s.%s\" is a \"%s\". Fields annotated with @LinkingObjects must be RealmResults.", targetClass, targetField, backlink.asType())); return false; } if (sourceClass == null) { Utils.error(String.format( "\"The field \"%s.%s\", annotated with @LinkingObjects, must specify a generic type.", targetClass, targetField)); return false; } return true; }

Target:
public boolean validateSource() { if (backlink.getAnnotation(Required.class) != null) { Utils.error(String.format( "The @LinkingObjects field \"%s.%s\" cannot be @Required.", targetClass, targetField)); return false; } if ((sourceField == null) || sourceField.equals("")) { Utils.error(String.format( "The @LinkingObjects annotation for the field \"%s.%s\" must have a parameter identifying the link target.", targetClass, targetField)); return false; } if (sourceField.contains(".")) { Utils.error(String.format( "The parameter to the @LinkingObjects annotation for the field \"%s.%s\" contains a '.'. The use of '.' to specify fields in referenced classes is not supported.", targetClass, targetField)); return false; } if (!Utils.isRealmResults(backlink)) { Utils.error(String.format( "The field \"%s.%s\" is a \"%s\". Fields annotated with @LinkingObjects must be RealmResults.", targetClass, targetField, backlink.asType())); return false; } if (sourceClass == null) { Utils.error(String.format( "\"The field \"%s.%s\", annotated with @LinkingObjects, must specify a generic type.", targetClass, targetField)); return false; } if (!backlink.getModifiers().contains(Modifier.FINAL)) { Utils.error(String.format( "A @LinkingObjects field \"%s.%s\" must be final.", targetClass, targetField)); return false; } return true; }
Source:
public Query createQuery() { final int nbrOfClauses = clauses.size(); if ( nbrOfClauses == 0 ) { return new MatchAllDocsQuery(); } else if ( nbrOfClauses == 1 ) { final BooleanClause uniqueClause = clauses.get( 0 ); if ( uniqueClause.getOccur().equals( BooleanClause.Occur.MUST_NOT ) ) { should( new MatchAllDocsQuery() ); } else { return queryCustomizer.setWrappedQuery( uniqueClause.getQuery() ).createQuery(); } } BooleanQuery query = new BooleanQuery(); for ( BooleanClause clause : clauses ) { query.add( clause ); } return queryCustomizer.setWrappedQuery( query ).createQuery(); }

Target:
public Query createQuery() { final int nbrOfClauses = clauses.size(); if ( nbrOfClauses == 0 ) { throw log.booleanQueryWithoutClauses(); } else if ( nbrOfClauses == 1 ) { final BooleanClause uniqueClause = clauses.get( 0 ); if ( uniqueClause.getOccur().equals( BooleanClause.Occur.MUST_NOT ) ) { should( new MatchAllDocsQuery() ); } else { return queryCustomizer.setWrappedQuery( uniqueClause.getQuery() ).createQuery(); } } BooleanQuery query = new BooleanQuery(); for ( BooleanClause clause : clauses ) { query.add( clause ); } return queryCustomizer.setWrappedQuery( query ).createQuery(); }
Source:
public NewTmfViewAction(TmfView view) { super(MessageFormat.format(Messages.TmfView_NewTmfViewNameText, view.getTitle())); setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_NEW_VIEW)); fViewId = checkNotNull(view.getViewId()); }

Target:
public NewTmfViewAction(TmfView view) { super(MessageFormat.format(Messages.TmfView_NewTmfViewNameText, view.getTitle())); setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_NEW_VIEW)); fViewId = view.getViewId(); }
Source:
public void walkInnerClassesAndEnums(ObjectType type, String namespace, Set<String> provides) { for (String propName : getSortedPropertyNames(type)) { if (provides.contains(namespace + '.' + propName)) continue; JSType pType = type.getPropertyType(propName); if (pType.isEnumType()) { visitEnumType((EnumType) pType); } if (pType.isConstructor()) { visitClassAndInterface(propName, (FunctionType) pType); } } }

Target:
public void walkInnerClassesAndEnums(ObjectType type, String namespace, Set<String> provides) { for (String propName : getSortedPropertyNames(type)) { if (provides.contains(namespace + '.' + propName)) continue; JSType pType = type.getPropertyType(propName); if (pType.isEnumType()) { visitEnumType((EnumType) pType); } else if (pType.isConstructor()) { visitClassOrInterface(propName, (FunctionType) pType); } } }
Source:
public int loadTable(String namespace, String tablename, int numItems, int batchSize, int itemSize) { verifyNamespaceAndTablename(namespace, tablename); CorfuStore store = new CorfuStore(runtime); try { TableOptions.TableOptionsBuilder<Object, Object> optionsBuilder = TableOptions.builder(); if (diskPath != null) { optionsBuilder.persistentDataPath(Paths.get(diskPath)); } store.openTable(namespace, tablename, TableName.getDefaultInstance().getClass(), TableName.getDefaultInstance().getClass(), TableName.getDefaultInstance().getClass(), optionsBuilder.build()); byte[] array = new byte[itemSize]; new Random().nextBytes(array); TableName dummyVal = TableName.newBuilder().setNamespace(namespace+tablename) .setTableName(new String(array, StandardCharsets.UTF_16)).build(); log.info("Loading items of size in batchSized transactions into {}${}", numItems, itemSize, batchSize, namespace, tablename); int itemsRemaining = numItems; while (itemsRemaining > 0) { log.info("loadTable: Items left {}", itemsRemaining); TxBuilder tx = store.tx(namespace); for (int j = batchSize; j > 0 && itemsRemaining > 0; j--, itemsRemaining--) { TableName dummyKey = TableName.newBuilder() .setNamespace(Integer.toString(itemsRemaining)) .setTableName(Integer.toString(j)).build(); tx.update(tablename, dummyKey, dummyVal, dummyVal); } tx.commit(); } } catch (Exception e) { log.error("loadTable: failed.", namespace, tablename, numItems, batchSize, e); } return (int)(Math.ceil((double)numItems/batchSize)); }

Target:
public int loadTable(String namespace, String tablename, int numItems, int batchSize, int itemSize) { verifyNamespaceAndTablename(namespace, tablename); CorfuStore store = new CorfuStore(runtime); try { TableOptions.TableOptionsBuilder<Object, Object> optionsBuilder = TableOptions.builder(); if (diskPath != null) { optionsBuilder.persistentDataPath(Paths.get(diskPath)); } store.openTable(namespace, tablename, TableName.getDefaultInstance().getClass(), TableName.getDefaultInstance().getClass(), TableName.getDefaultInstance().getClass(), optionsBuilder.build()); byte[] array = new byte[itemSize]; new Random().nextBytes(array); TableName dummyVal = TableName.newBuilder().setNamespace(namespace+tablename) .setTableName(new String(array, StandardCharsets.UTF_16)).build(); log.info("WARNING: Loading items of size in batchSized transactions into {}${}", numItems, itemSize, batchSize, namespace, tablename); int itemsRemaining = numItems; while (itemsRemaining > 0) { log.info("loadTable: Items left {}", itemsRemaining); TxBuilder tx = store.tx(namespace); for (int j = batchSize; j > 0 && itemsRemaining > 0; j--, itemsRemaining--) { TableName dummyKey = TableName.newBuilder() .setNamespace(Integer.toString(itemsRemaining)) .setTableName(Integer.toString(j)).build(); tx.update(tablename, dummyKey, dummyVal, dummyVal); } tx.commit(); } } catch (Exception e) { log.error("loadTable: failed.", namespace, tablename, numItems, batchSize, e); } return (int)(Math.ceil((double)numItems/batchSize)); }
Source:
private void validateVolumeSize(VolumeTemplate value, VmType vmType, VolumeParameterType volumeParameterType, ValidationResult.ValidationResultBuilder validationBuilder, InstanceGroup instanceGroup) { if (vmType != null && needToCheckVolume(volumeParameterType, value.getVolumeCount())) { VolumeParameterConfig config = vmType.getVolumeParameterbyVolumeParameterType(volumeParameterType); if (config != null) { if (isIDBrokerInstanceGroup(instanceGroup)) { if (value.getVolumeSize() > 0) { value.setVolumeCount(0); value.setVolumeSize(0); } } else if (value.getVolumeSize() > config.maximumSize()) { validationBuilder.error(String.format("Max allowed volume size for '%s': %s", vmType.value(), config.maximumSize())); } else if (value.getVolumeSize() < config.minimumSize()) { validationBuilder.error(String.format("Min allowed volume size for '%s': %s", vmType.value(), config.minimumSize())); } } else { validationBuilder.error(String.format("The '%s' instance type does not support 'Ephemeral' volume type", vmType.value())); } } }

Target:
private void validateVolumeSize(VolumeTemplate value, VmType vmType, VolumeParameterType volumeParameterType, ValidationResult.ValidationResultBuilder validationBuilder, InstanceGroup instanceGroup) { if (vmType != null && needToCheckVolume(volumeParameterType, value.getVolumeCount())) { VolumeParameterConfig config = vmType.getVolumeParameterbyVolumeParameterType(volumeParameterType); if (config != null) { if (value.getVolumeSize() > config.maximumSize()) { validationBuilder.error(String.format("Max allowed volume size for '%s': %s", vmType.value(), config.maximumSize())); } else if (!isIDBrokerInstanceGroup(instanceGroup) && value.getVolumeSize() < config.minimumSize()) { validationBuilder.error(String.format("Min allowed volume size for '%s': %s", vmType.value(), config.minimumSize())); } } else { validationBuilder.error(String.format("The '%s' instance type does not support 'Ephemeral' volume type", vmType.value())); } } }
Source:
public GroupByQueryBrokerResource prepareResource(GroupByQuery query, boolean willMergeRunners) { if (!willMergeRunners) { final int requiredMergeBufferNum = countRequiredMergeBufferNum(query, 2, 1); if (requiredMergeBufferNum > mergeBufferPool.maxSize()) { throw new ResourceLimitExceededException( "Query needs " + requiredMergeBufferNum + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers are configured" ); } else if (requiredMergeBufferNum == 0) { return new GroupByQueryBrokerResource(); } else { final Number timeout = query.getContextValue(QueryContextKeys.TIMEOUT, JodaUtils.MAX_INSTANT); final ResourceHolder<List<ByteBuffer>> mergeBufferHolders; try { mergeBufferHolders = mergeBufferPool.drain(requiredMergeBufferNum, timeout.longValue()); if (mergeBufferHolders.get().size() < requiredMergeBufferNum) { mergeBufferHolders.close(); throw new TimeoutException("Cannot acquire enough merge buffers"); } else { return new GroupByQueryBrokerResource(mergeBufferHolders); } } catch (Exception e) { throw new QueryInterruptedException(e); } } } else { return new GroupByQueryBrokerResource(); } }

Target:
public GroupByQueryResource prepareResource(GroupByQuery query, boolean willMergeRunners) { if (!willMergeRunners) { final int requiredMergeBufferNum = countRequiredMergeBufferNum(query, 1); if (requiredMergeBufferNum > mergeBufferPool.maxSize()) { throw new ResourceLimitExceededException( "Query needs " + requiredMergeBufferNum + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers are configured" ); } else if (requiredMergeBufferNum == 0) { return new GroupByQueryResource(); } else { final Number timeout = query.getContextValue(QueryContextKeys.TIMEOUT, JodaUtils.MAX_INSTANT); final ResourceHolder<List<ByteBuffer>> mergeBufferHolders = mergeBufferPool.takeBatch( requiredMergeBufferNum, timeout.longValue() ); if (mergeBufferHolders == null) { throw new InsufficientResourcesException("Cannot acquire enough merge buffers"); } else { return new GroupByQueryResource(mergeBufferHolders); } } } else { return new GroupByQueryResource(); } }
Source:
public Manufacturer(final String code, final String name) { super(); this.code = code; this.name = name; }

Target:
public Manufacturer(final String code, final String name) { this.code = code; this.name = name; }
Source:
public void initialize(TransformContext context) throws Exception { super.initialize(context); FailureCollector failureCollector = context.getFailureCollector(); List<String> fieldsToFlatten = config.getFieldsToFlatten(); if (fieldsToFlatten == null || fieldsToFlatten.isEmpty()) { failureCollector.addFailure("No field(s) selected for flattening.", "Choose field(s) to flatten."); failureCollector.getOrThrowException(); } Schema inputSchema = context.getInputSchema(); if (inputSchema == null) { return; } List<OutputFieldInfo> inputOutputMapping = createOutputFieldsInfo(inputSchema, fieldsToFlatten, config.getLevelToLimitFlattening()); this.inputOutputMapping = handleDuplicateFieldName(inputOutputMapping, config.getPrefix()); this.outputSchema = generateOutputSchema(inputSchema, inputOutputMapping); }

Target:
public void initialize(TransformContext context) throws Exception { super.initialize(context); FailureCollector failureCollector = context.getFailureCollector(); List<String> fieldsToFlatten = config.getFieldsToFlatten(); if (fieldsToFlatten == null || fieldsToFlatten.isEmpty()) { failureCollector.addFailure("Atleast one field should be selected.", ""); failureCollector.getOrThrowException(); } Schema inputSchema = context.getInputSchema(); if (inputSchema == null) { return; } List<OutputFieldInfo> inputOutputMapping = createOutputFieldsInfo(inputSchema, fieldsToFlatten, config.getLevelToLimitFlattening()); this.inputOutputMapping = handleDuplicateFieldName(inputOutputMapping, config.getPrefix()); this.outputSchema = generateOutputSchema(inputSchema, inputOutputMapping); }
Source:
public Config getConfig() { if (coordinatorStreamConsumer == null) { throw new UnsupportedOperationException(String.format("CoordinatorStreamConsumer is not initialized in the CoordinatorStreamManager. ")); } return coordinatorStreamConsumer.getConfig(); }

Target:
public Config getConfig() { if (coordinatorStreamConsumer == null) { throw new IllegalStateException( String.format("CoordinatorStreamConsumer is not initialized in the CoordinatorStreamManager. ")); } return coordinatorStreamConsumer.getConfig(); }
Source:
public void setValue(ProjectAccess value) { if (editing && value.isOwnerOf(AccessSection.GLOBAL_CAPABILITIES) && value.getLocal(AccessSection.GLOBAL_CAPABILITIES) == null) { value.getLocal().add(0, new AccessSection(AccessSection.GLOBAL_CAPABILITIES)); } this.value = value; Project.NameKey parent = value.getInheritsFrom(); if (parent != null) { inheritsFrom.getStyle().setDisplay(Display.BLOCK); parentProject.setText(parent.get()); parentProject.setTargetHistoryToken( Dispatcher.toProjectAdmin(parent, ProjectScreen.ACCESS)); } else { inheritsFrom.getStyle().setDisplay(Display.NONE); } final GitwebLink c = Gerrit.getConfig().getGitwebLink(); if (value.isOwner() && c != null) { history.getStyle().setDisplay(Display.BLOCK); gitweb.setHref(c.toFileHistory(new Branch.NameKey( value.getInheritsFrom(), "refs/meta/config"), "project.config")); } else { history.getStyle().setDisplay(Display.NONE); } addSection.setVisible(value != null && editing && !value.getOwnerOf().isEmpty()); }

Target:
public void setValue(ProjectAccess value) { if (editing && value.isOwnerOf(AccessSection.GLOBAL_CAPABILITIES) && value.getLocal(AccessSection.GLOBAL_CAPABILITIES) == null) { value.getLocal().add(0, new AccessSection(AccessSection.GLOBAL_CAPABILITIES)); } this.value = value; Project.NameKey parent = value.getInheritsFrom(); if (parent != null) { inheritsFrom.getStyle().setDisplay(Display.BLOCK); parentProject.setText(parent.get()); parentProject.setTargetHistoryToken( Dispatcher.toProjectAdmin(parent, ProjectScreen.ACCESS)); } else { inheritsFrom.getStyle().setDisplay(Display.NONE); } final GitwebLink c = Gerrit.getConfig().getGitwebLink(); if (value.isConfigVisible() && c != null) { history.getStyle().setDisplay(Display.BLOCK); gitweb.setHref(c.toFileHistory(new Branch.NameKey(value.getProjectName(), "refs/meta/config"), "project.config")); } else { history.getStyle().setDisplay(Display.NONE); } addSection.setVisible(value != null && editing && !value.getOwnerOf().isEmpty()); }
Source:
public ArrayLiteralTreeImpl newArrayLiteralWithElidedElements(List<InternalSyntaxToken> commaTokens) { List<Tree> commas = Lists.newArrayList(); for (InternalSyntaxToken comma : commaTokens) { commas.add(comma); } return new ArrayLiteralTreeImpl(commas); }

Target:
public ArrayLiteralTreeImpl newArrayLiteralWithElidedElements(List<InternalSyntaxToken> commaTokens) { return new ArrayLiteralTreeImpl(new ArrayList<Tree>(commaTokens)); }
Source:
public boolean hasMuteReason(){ return !getMuteReason().equals(""); }

Target:
public boolean hasMuteReason(){ return muteReason != null; }
Source:
public static Function tryCreateSubscript(Symbol baseSymbol, List<String> path) { assert !path.isEmpty() : "Path must not be empty to create subscript function"; var baseType = baseSymbol.valueType(); switch (baseType.id()) { case ObjectType.ID: { List<Symbol> arguments = Lists2.mapTail(baseSymbol, path, Literal::of); DataType<?> returnType = ((ObjectType) baseType).resolveInnerType(path); return new Function( new FunctionInfo(new FunctionIdent(SubscriptObjectFunction.NAME, Symbols.typeView(arguments)), returnType), arguments ); } case RowType.ID: { String child = path.get(0); RowType rowType = (RowType) baseType; int idx = rowType.fieldNames().indexOf(child); if (idx < 0) { return null; } Function recordSubscript = new Function( new FunctionInfo( new FunctionIdent(SubscriptRecordFunction.NAME, List.of(baseType, DataTypes.STRING)), rowType.getFieldType(idx) ), List.of(baseSymbol, Literal.of(child)) ); if (path.size() > 1) { return tryCreateSubscript(recordSubscript, path.subList(1, path.size() - 1)); } return recordSubscript; } default: return null; } }

Target:
public static Function tryCreateSubscript(Symbol baseSymbol, List<String> path) { assert !path.isEmpty() : "Path must not be empty to create subscript function"; var baseType = baseSymbol.valueType(); switch (baseType.id()) { case ObjectType.ID: { List<Symbol> arguments = Lists2.mapTail(baseSymbol, path, Literal::of); DataType<?> returnType = ((ObjectType) baseType).resolveInnerType(path); return new Function( new FunctionInfo(new FunctionIdent(SubscriptObjectFunction.NAME, Symbols.typeView(arguments)), returnType), arguments ); } case RowType.ID: { String child = path.get(0); RowType rowType = (RowType) baseType; int idx = rowType.fieldNames().indexOf(child); if (idx < 0) { return null; } Function recordSubscript = new Function( new FunctionInfo( new FunctionIdent(SubscriptRecordFunction.NAME, List.of(baseType, DataTypes.STRING)), rowType.getFieldType(idx) ), List.of(baseSymbol, Literal.of(child)) ); if (path.size() > 1) { return tryCreateSubscript(recordSubscript, path.subList(1, path.size())); } return recordSubscript; } default: return null; } }
Source:
protected Iterable<String> getChoices(CommandSource source) { Set<Iterable<Entity>> worldEntities = Sponge.getServer().getWorlds().stream().map(World::getEntities).collect(Collectors.toSet()); List<String> prepend = Lists.newLinkedList(); if (source instanceof Player) { prepend.add(0, ((Player) source).getUniqueId().toString()); prepend.add(0, source.getName()); } prepend.addAll(Selector.complete("@")); return Iterables.concat(prepend, Iterables.concat(Iterables.transform(Iterables.concat(worldEntities), input -> { if (input == null || input == source) { return Collections.emptyList(); } if (input instanceof Player) { return Lists.newArrayList(((Player) input).getName(), input.getUniqueId().toString()); } return Collections.singleton(input.getUniqueId().toString()); }))); }

Target:
protected Iterable<String> getChoices(CommandSource source) { Stream<Entity> worldEntities = Sponge.getServer().getWorlds().stream().flatMap(world -> world.getEntities().stream()); Stream<String> prepend = Stream.empty(); if (source instanceof Player) { prepend = Stream.of( source.getName(), ((Player) source).getUniqueId().toString() ); } final Stream<String> selectors = Selector.complete("@").stream(); final Stream<String> stringEntities = worldEntities.flatMap( input -> { if (input == null || input == source) { return Stream.empty(); } else if (input instanceof Player) { return Stream.of( ((Player) input).getName(), input.getUniqueId().toString() ); } else { return Stream.of(input.getUniqueId().toString()); } } ); final Stream<String> out = Stream.of( prepend, selectors, stringEntities ).flatMap(Function.identity()); return out.collect(Collectors.toList()); }
Source:
private void bindServiceAndGetSignKeyId(final Intent data) { if (mServiceConnection != null) { getSignKeyId(data); return; } mServiceConnection = new OpenPgpServiceConnection( getContext().getApplicationContext(), mOpenPgpProvider, new OpenPgpServiceConnection.OnBound() { @Override public void onBound(IOpenPgpService2 service) { getSignKeyId(data); } @Override public void onError(Exception e) { Log.e(OpenPgpApi.TAG, "exception on binding!", e); } } ); mServiceConnection.bindToService(); }

Target:
private void bindServiceAndGetSignKeyId(final Intent data) { if (mServiceConnection != null && mServiceConnection.isBound()) { getSignKeyId(data); return; } mServiceConnection = new OpenPgpServiceConnection( getContext().getApplicationContext(), mOpenPgpProvider, new OpenPgpServiceConnection.OnBound() { @Override public void onBound(IOpenPgpService2 service) { getSignKeyId(data); } @Override public void onError(Exception e) { Log.e(OpenPgpApi.TAG, "exception on binding!", e); } } ); mServiceConnection.bindToService(); }
Source:
private void recordStepData(HadoopStepStats hdStepStats) { String jobID = hdStepStats.getJobID(); try { TwoNestedMap<String, String, Long> counters = Counters.getCounterMap(hdStepStats).get(jobID); try { addYarnPerformanceMetrics(hdStepStats, jobID, counters); } catch (Exception e) { LOG.info("Unable to add yarn performance stats", e); } persister.onCounters( jobID, counters ); recordTaskErrors(hdStepStats, jobID, false, counters); } catch (Exception e) { LOG.error("Failed to capture stats for step!", e); if (failOnCounterFetch) { throw new RuntimeException("Failed fetching stats for step", e); } } }

Target:
private void recordStepData(HadoopStepStats hdStepStats) { String jobID = hdStepStats.getJobID(); try { TwoNestedMap<String, String, Long> counters = Counters.getCounterMap(hdStepStats).get(jobID); try { addYarnPerformanceMetrics(hdStepStats, jobID, counters); } catch (Exception e) { LOG.error("Unable to add yarn performance stats", e); } persister.onCounters( jobID, counters ); recordTaskErrors(hdStepStats, jobID, false, counters); } catch (Exception e) { LOG.error("Failed to capture stats for step!", e); if (failOnCounterFetch) { throw new RuntimeException("Failed fetching stats for step", e); } } }
Source:
public void testRunQueryWithEnvProxy() throws Exception { List<FullHttpRequest> jobIssueRequests = Collections.synchronizedList(new ArrayList<>()); proxyServer = DefaultHttpProxyServer .bootstrap() .withPort(0) .withFiltersSource(new HttpFiltersSourceAdapter() { @Override public int getMaximumRequestBufferSizeInBytes() { return 1024 * 1024; } @Override public HttpFilters filterRequest(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext) { return new HttpFiltersAdapter(httpRequest) { @Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { assert httpObject instanceof FullHttpRequest; FullHttpRequest fullHttpRequest = (FullHttpRequest) httpObject; if (httpRequest.getUri().contains("/v3/job/issue")) { jobIssueRequests.add(fullHttpRequest.copy()); } return null; } }; } }).start(); copyResource("acceptance/td/td/td.dig", projectDir.resolve("workflow.dig")); copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql")); String proxyUrl = "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort(); runWorkflow(ImmutableMap.of("http_proxy", proxyUrl), ImmutableList.of("td.use_ssl=false")); assertThat(jobIssueRequests.size(), is(greaterThan(0))); }

Target:
public void testRunQueryWithEnvProxy() throws Exception { List<FullHttpRequest> requests = Collections.synchronizedList(new ArrayList<>()); proxyServer = startRequestTrackingProxy(requests); copyResource("acceptance/td/td/td.dig", projectDir.resolve("workflow.dig")); copyResource("acceptance/td/td/query.sql", projectDir.resolve("query.sql")); String proxyUrl = "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort(); runWorkflow(ImmutableMap.of("http_proxy", proxyUrl), ImmutableList.of("td.use_ssl=false")); assertThat(requests.stream().filter(req -> req.getUri().contains("/v3/job/issue")).count(), is(greaterThan(0L))); }
Source:
public void leaveNode(Tree tree) { if (tree.is(CONDITIONAL_EXPRS)) { ExpressionComplexity currentExpression = Iterables.getLast(statementLevel); currentExpression.decrementNestedExprLevel(); if (currentExpression.isOnFirstExprLevel()) { int complexity = currentExpression.getExprNumberOfOperator(); if (complexity > max) { String message = String.format(MESSAGE, complexity, max); getContext().addIssue(this, tree, message, complexity - max); } currentExpression.resetExprOperatorCounter(); } } else if (tree.is(SCOPES)) { statementLevel.remove(statementLevel.size() - 1); } }

Target:
public void leaveNode(Tree tree) { if (tree.is(CONDITIONAL_EXPRS)) { ExpressionComplexity currentExpression = Iterables.getLast(statementLevel); currentExpression.decrementNestedExprLevel(); if (currentExpression.isOnFirstExprLevel()) { int complexity = currentExpression.getExprNumberOfOperator(); if (complexity > max) { String message = String.format(MESSAGE, complexity, max); getContext().addIssue(this, tree, message, (double) (complexity - max)); } currentExpression.resetExprOperatorCounter(); } } else if (tree.is(SCOPES)) { statementLevel.remove(statementLevel.size() - 1); } }
Source:
public JdbcConnection(String propertiesFileName) throws IOException { BufferedReader propertiesFileReader = new BufferedReader(new FileReader(new File(propertiesFileName))); try { properties = new Properties(); properties.load(propertiesFileReader); }finally { propertiesFileReader.close(); } jdbcUrl = properties.getProperty(JDBC_URL); user = properties.getProperty(JDBC_USER); password = properties.getProperty(JDBC_PASSWORD); timeout = Integer.parseInt(properties.getProperty(JDBC_TIMEOUT, "600")); LOGGER.info("url {}", jdbcUrl); LOGGER.info("user {}", user); LOGGER.info("password {}", password); LOGGER.info("timeout {}", timeout); }

Target:
public JdbcConnection(String propertiesFileName) throws IOException { BufferedReader propertiesFileReader = new BufferedReader(new FileReader(new File(propertiesFileName))); try { properties = new Properties(); properties.load(propertiesFileReader); }finally { propertiesFileReader.close(); } jdbcUrl = properties.getProperty(JDBC_URL); user = properties.getProperty(JDBC_USER); password = properties.getProperty(JDBC_PASSWORD); timeout = Integer.parseInt(properties.getProperty(JDBC_TIMEOUT, "600")); LOGGER.info("url {}, user {}, password {}, timeout {}", jdbcUrl, user, password, timeout); }
Source:
public O loadClassFromJar(String jarPath, String classFqdn) throws ClassNotFoundException, MalformedURLException, InstantiationException, IllegalAccessException { ClassLoader classLoader; if (isClassLoadedFromParent(classFqdn)) { classLoader = parentClassLoader; } else { synchronized (cachedClassLoaders) { classLoader = findCachedClassLoader(jarPath); if (classLoader == null) { classLoader = getJarAddedClassLoader(jarPath); } } } O actualObject = initInstanceFromClassloader(classFqdn, classLoader); return createClassLoaderAwareProxyInstance(classLoader, actualObject); }

Target:
public O loadClassFromJar(String jarPath, String classFqdn) throws ClassNotFoundException, MalformedURLException, InstantiationException, IllegalAccessException { ClassLoader classLoader; if (isClassLoadedFromParent(classFqdn)) { classLoader = parentClassLoader; } else { classLoader = findCachedClassLoader(jarPath); if (classLoader == null) { classLoader = getJarAddedClassLoader(jarPath); } } O actualObject = initInstanceFromClassloader(classFqdn, classLoader); return createClassLoaderAwareProxyInstance(classLoader, actualObject); }
Source:
public String getErrorMessage() { return ""; }

Target:
public String getErrorMessage() { return mErrorMessage; }
Source:
public static void configureXStreamMappings(XStream toConfigure) { Map<String, Class> XSTREAM_MAPPINGS = new HashMap<String, Class>() { { put("ExpressionElement", ExpressionElement.class); put("ExpressionIdentifier", ExpressionIdentifier.class); put("FactIdentifier", FactIdentifier.class); put("FactMapping", FactMapping.class); put("FactMappingType", FactMappingType.class); put("FactMappingValue", FactMappingValue.class); put("Scenario", Scenario.class); put("ScenarioSimulationModel", ScenarioSimulationModel.class); put("Simulation", Simulation.class); put("SimulationDescriptor", SimulationDescriptor.class); put("Import", Import.class); } }; XSTREAM_MAPPINGS.forEach(toConfigure::alias); }

Target:
public static void configureXStreamMappings(XStream toConfigure) { toConfigure.alias("ExpressionElement", ExpressionElement.class); toConfigure.alias("ExpressionIdentifier", ExpressionIdentifier.class); toConfigure.alias("FactIdentifier", FactIdentifier.class); toConfigure.alias("FactMapping", FactMapping.class); toConfigure.alias("FactMappingType", FactMappingType.class); toConfigure.alias("FactMappingValue", FactMappingValue.class); toConfigure.alias("Scenario", Scenario.class); toConfigure.alias("ScenarioSimulationModel", ScenarioSimulationModel.class); toConfigure.alias("Simulation", Simulation.class); toConfigure.alias("SimulationDescriptor", SimulationDescriptor.class); toConfigure.alias("Import", Import.class); }
Source:
public JobResult removeSpace(final String jobId, final String spaceName) { JobResult result = new JobResult(); result.setJobId(jobId); if (spaceName == null) { result.setStatus(JobStatus.BAD_REQUEST); result.setResult("OrganizationalUnit name must be provided"); return result; } try { organizationalUnitService.removeOrganizationalUnit(spaceName); result.setStatus(JobStatus.SUCCESS); } catch (Exception e) { result.setStatus(JobStatus.FAIL); String errMsg = e.getClass().getSimpleName() + " thrown when trying to remove '" + spaceName + "': " + e.getMessage(); result.setResult(errMsg); logger.error(errMsg, e); } return result; }

Target:
public JobResult removeSpace(final String jobId, final String spaceName) { JobResult result = new JobResult(); result.setJobId(jobId); if (spaceName == null) { result.setStatus(JobStatus.BAD_REQUEST); result.setResult("Space name must be provided"); return result; } try { organizationalUnitService.removeOrganizationalUnit(spaceName); result.setStatus(JobStatus.SUCCESS); } catch (Exception e) { result.setStatus(JobStatus.FAIL); String errMsg = e.getClass().getSimpleName() + " thrown when trying to remove '" + spaceName + "': " + e.getMessage(); result.setResult(errMsg); logger.error(errMsg, e); } return result; }
Source:
public boolean hasNext() { boolean hasNext = source.hasNext(); if (!hasNext && prevTablet != null && prevTablet.getEndRow() != null) { Text defaultTabletRow = TabletsSection.getRow(prevTablet.getTableId(), null); if (range.contains(new Key(defaultTabletRow))) { throw new IllegalStateException( "Read all tablets but did not see default tablet. Last tablet seen : " + prevTablet.getExtent()); } } return hasNext; }

Target:
public boolean hasNext() { boolean hasNext = source.hasNext(); if (!hasNext && prevTablet != null && prevTablet.getEndRow() != null) { Text defaultTabletRow = TabletsSection.getRow(prevTablet.getTableId(), null); if (range.contains(new Key(defaultTabletRow))) { throw new IllegalStateException( "Scan range incudled default tablet, but did not see default tablet. Last tablet seen : " + prevTablet.getExtent()); } } return hasNext; }
Source:
private void handleFailingChecks(DomainRouterVO router, List<String> failingChecks) { if (failingChecks == null || failingChecks.size() == 0) { return; } String alertMessage = "Health checks failed: " + failingChecks.size() + " failing checks on router " + router.getUuid(); _alertMgr.sendAlert(AlertType.ALERT_TYPE_DOMAIN_ROUTER, router.getDataCenterId(), router.getPodIdToDeployIn(), alertMessage, alertMessage); s_logger.warn(alertMessage + ". Checking failed health checks to see if router needs reboot"); String checkFailsToRecreateVr = RouterHealthChecksFailuresToRecreateVr.valueIn(router.getDataCenterId()); StringBuilder failingChecksEvent = new StringBuilder("Router " + router.getUuid() + " has failing checks:"); boolean recreateRouter = false; for (String failedCheck : failingChecks) { failingChecksEvent.append(" ").append(failedCheck); if (StringUtils.isNotBlank(checkFailsToRecreateVr) && checkFailsToRecreateVr.contains(failedCheck)) { recreateRouter = true; } } ActionEventUtils.onActionEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, Domain.ROOT_DOMAIN, EventTypes.EVENT_ROUTER_HEALTH_CHECKS, failingChecksEvent.toString()); if (recreateRouter) { s_logger.warn("Health Check Alert: Found failing checks in " + RouterHealthChecksFailuresToRecreateVrCK + ", attempting recreating router."); recreateRouter(router.getId()); } }

Target:
private void handleFailingChecks(DomainRouterVO router, List<String> failingChecks) { if (failingChecks == null || failingChecks.size() == 0) { return; } String alertMessage = "Health checks failed: " + failingChecks.size() + " failing checks on router " + router.getUuid(); _alertMgr.sendAlert(AlertType.ALERT_TYPE_DOMAIN_ROUTER, router.getDataCenterId(), router.getPodIdToDeployIn(), alertMessage, alertMessage); s_logger.warn(alertMessage + ". Checking failed health checks to see if router needs recreate"); String checkFailsToRecreateVr = RouterHealthChecksFailuresToRecreateVr.valueIn(router.getDataCenterId()); StringBuilder failingChecksEvent = new StringBuilder(); boolean recreateRouter = false; for (int i = 0; i < failingChecks.size(); i++) { String failedCheck = failingChecks.get(i); if (i == 0) { failingChecksEvent.append("Router ") .append(router.getUuid()) .append(" has failing checks: "); } failingChecksEvent.append(failedCheck); if (i < failingChecks.size() - 1) { failingChecksEvent.append(", "); } if (StringUtils.isNotBlank(checkFailsToRecreateVr) && checkFailsToRecreateVr.contains(failedCheck)) { recreateRouter = true; } } ActionEventUtils.onActionEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, Domain.ROOT_DOMAIN, EventTypes.EVENT_ROUTER_HEALTH_CHECKS, failingChecksEvent.toString()); if (recreateRouter) { s_logger.warn("Health Check Alert: Found failing checks in " + RouterHealthChecksFailuresToRecreateVrCK + ", attempting recreating router."); recreateRouter(router.getId()); } }
Source:
private Document removeAllChildrenButOne(Document doc, int index) { try { Document clone = (Document) doc.clone(); Element remainingChild = null; ArrayList<Element> recordNodes = (ArrayList<Element>) srwRecordXPath.selectNodes(clone); for (int i = 0; i < recordNodes.size(); i++) { Element currentRecord = recordNodes.get(i); if (i != index) { currentRecord.detach(); } else { remainingChild = currentRecord; } } return remainingChild.getDocument(); } catch (JDOMException e) { e.printStackTrace(); logger.error("Unable to remove children from given document."); return null; } }

Target:
private Document removeAllChildrenButOne(Document doc, int index) { try { Document clone = (Document) doc.clone(); Element remainingChild = null; ArrayList<Element> recordNodes = (ArrayList<Element>) srwRecordXPath.selectNodes(clone); for (int i = 0; i < recordNodes.size(); i++) { Element currentRecord = recordNodes.get(i); if (i != index) { currentRecord.detach(); } else { remainingChild = currentRecord; } } if (Objects.equals(remainingChild, null)) { return clone; } return remainingChild.getDocument(); } catch (JDOMException e) { logger.error("Unable to remove children from given document."); return null; } }
Source:
public Props getJobOverrideProperty(final Project project, final Flow flow, final String jobName, final String source) throws ProjectManagerException { if (Double.compare(flow.getAzkabanFlowVersion(), Constants.AZKABAN_FLOW_VERSION_2_0) == 0) { final int flowVersion = this.projectLoader .getLatestFlowVersion(flow.getProjectId(), flow.getVersion(), source); return getPropertiesFromFlowFile(flow, jobName, source, flowVersion); } else { return this.projectLoader.fetchProjectProperty(project, jobName + ".jor"); } }

Target:
public Props getJobOverrideProperty(final Project project, final Flow flow, final String jobName, final String source) throws ProjectManagerException { if (FlowLoaderUtils.isAzkabanFlowVersion20(flow.getAzkabanFlowVersion())) { final int flowVersion = this.projectLoader .getLatestFlowVersion(flow.getProjectId(), flow.getVersion(), source); return getPropertiesFromFlowFile(flow, jobName, source, flowVersion); } else { return this.projectLoader .fetchProjectProperty(project, jobName + Constants.JOB_OVERRIDE_SUFFIX); } }