auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public GDPRSymmetricKey() throws Exception { algorithm = OzoneConsts.GDPR_ALGORITHM_NAME; secret = RandomStringUtils .randomAlphabetic(OzoneConsts.GDPR_RANDOM_SECRET_LENGTH); this.secretKey = new SecretKeySpec( <START> secret.substring(0, OzoneConsts.GDPR_RANDOM_SECRET_LENGTH) <END> .getBytes(OzoneConsts.GDPR_CHARSET), algorithm); this.cipher = Cipher.getInstance(algorithm); }</code><technical_language>is secret.substring(0, OzoneConsts.GDPR_RANDOM_SECRET_LENGTH)? a direct secret, generating secret length 32. this.secretKey = new SecretKeySpec( secret.getBytes(OzoneConsts.GDPR_CHARSET), algorithm);</technical_language>

Target:
public GDPRSymmetricKey() throws Exception { algorithm = OzoneConsts.GDPR_ALGORITHM_NAME; secret = RandomStringUtils .randomAlphabetic(OzoneConsts.GDPR_RANDOM_SECRET_LENGTH); this.secretKey = new SecretKeySpec( secret.getBytes(OzoneConsts.GDPR_CHARSET), algorithm); this.cipher = Cipher.getInstance(algorithm); }
Source:
<code>public VdsIdVDSCommandBase(P parameters, boolean newHost) { super(parameters); if (!newHost) { <START> _vdsManager = Injector.get(ResourceManager.class).getVdsManager(parameters.getVdsId()); <END> } }</code><technical_language>get rid this injection moving initialization of _vdsManager c'tor executeVDSCommand() method. newHost a member executeVDSCommand() referring initialized ResourceManager obtain vdsManager host</technical_language>

Target:
public VdsIdVDSCommandBase(P parameters, boolean newHost) { super(parameters); this.newHost = newHost; }
Source:
<code>public void onInitialize(MatchingFrame frame, ISearchContext context) throws LocalSearchException { call = helper.createCall(context); <START> Set<Object> seedsToEvaluate = <END> Sets.newLinkedHashSet(); seedsToEvaluate.add(frame.get(seedPosition)); Set<Object> seedsEvaluated = Sets.newHashSet(); do { Object currentValue = seedsToEvaluate.iterator().next(); seedsToEvaluate.remove(currentValue); seedsEvaluated.add(currentValue); final Object[] mappedFrame = calculateCallFrame(currentValue); for (Tuple match : call.getAllMatches(mappedFrame)) { Object foundTarget = getTargets(match); if (!seedsEvaluated.contains(foundTarget)) { seedsToEvaluate.add(foundTarget); } } } while (!seedsToEvaluate.isEmpty()); it = seedsEvaluated.iterator(); }</code><technical_language>This more readable a queue a condition-first loop. Also, add remove operations more efficient a linkedlist a linkedHashSet. Do a reason a Set? Duplicates checked seedsEvaluated</technical_language>

Target:
public void onInitialize(MatchingFrame frame, ISearchContext context) throws LocalSearchException { call = helper.createCall(context); Queue<Object> seedsToEvaluate = new LinkedList<>(); seedsToEvaluate.add(frame.get(seedPosition)); Set<Object> seedsEvaluated = new HashSet<>(); while(!seedsToEvaluate.isEmpty()) { Object currentValue = seedsToEvaluate.poll(); seedsEvaluated.add(currentValue); final Object[] mappedFrame = calculateCallFrame(currentValue); for (Tuple match : call.getAllMatches(mappedFrame)) { Object foundTarget = getTarget(match); if (!seedsEvaluated.contains(foundTarget)) { seedsToEvaluate.add(foundTarget); } } } it = seedsEvaluated.iterator(); }
Source:
<code>public void checkNameProjectTest() throws Exception { driver.navigate().to(swaggerUrl); try { assertTrue(swagger.getWsNamesFromWorkspacePage().contains(workspace.getName())); } catch (IllegalStateException ex) { Assert.fail("Known issue <LINK_0>"); <START> } catch (StaleElementReferenceException ex) { <END> Assert.fail("Known issue <LINK_0>"); } }</code><technical_language>combine IllegalStateException StaleElementReferenceException catch() section: } catch (IllegalStateException | StaleElementReferenceException ex) { // remove try-catch block issue resolved Assert.fail("Known issue <LINK_0>"); }</technical_language>

Target:
public void checkNameProjectTest() throws Exception { driver.navigate().to(swaggerUrl); try { assertTrue(swagger.getWsNamesFromWorkspacePage().contains(workspace.getName())); } catch (IllegalStateException | StaleElementReferenceException ex) { fail("Known issue <LINK_0>"); } }
Source:
<code>public void inject() { final Type[] types = Type.getArgumentTypes(this.method.desc); InsnList inject = new InsnList(); Label l0 = new Label(); inject.add(new LabelNode(l0)); int offset = 0; <START> if (args != null && args.length > 0) { <END> for (int arg : args) { if (Modifier.isStatic(method.access)) { int loadOpcode = ASMUtils.getLoadOpcode(types[arg] .getDescriptor()); inject.add(new VarInsnNode(loadOpcode, arg + offset)); if (loadOpcode == Opcodes.LLOAD) { offset++; } } else { inject.add(new VarInsnNode(ASMUtils.getLoadOpcode(types[arg] .getDescriptor()), arg + 1)); } } } inject.add(new MethodInsnNode(INVOKESTATIC, this.invokeClass, this.invokeMethod, this.desc)); if (this.conditional) { LabelNode ln = new LabelNode(new Label()); inject.add(new JumpInsnNode(IFEQ, ln)); if (Type.getReturnType(method.desc).equals(Type.BOOLEAN_TYPE)) { inject.add(new InsnNode(ICONST_1)); inject.add(new InsnNode(IRETURN)); } else { inject.add(new InsnNode(RETURN)); } inject.add(ln); } if (method.name.startsWith("<") && !Modifier.isStatic(method.access)) { AbstractInsnNode target = null; for (AbstractInsnNode node : this.method.instructions.toArray()) { if (node.getOpcode() == Opcodes.INVOKESPECIAL) { target = node; break; } } if (target != null) { this.method.instructions.insert(target, inject); } } else { this.method.instructions.insert(inject); } }</code><technical_language>args.length check required right</technical_language>

Target:
public void inject() { final Type[] types = Type.getArgumentTypes(this.method.desc); InsnList inject = new InsnList(); Label l0 = new Label(); inject.add(new LabelNode(l0)); int offset = 0; if (args != null) { for (int arg : args) { if (Modifier.isStatic(method.access)) { int loadOpcode = ASMUtils.getLoadOpcode(types[arg] .getDescriptor()); inject.add(new VarInsnNode(loadOpcode, arg + offset)); if (loadOpcode == Opcodes.LLOAD) { offset++; } } else { inject.add(new VarInsnNode(ASMUtils.getLoadOpcode(types[arg] .getDescriptor()), arg + 1)); } } } inject.add(new MethodInsnNode(INVOKESTATIC, this.invokeClass, this.invokeMethod, this.desc)); if (this.conditional) { LabelNode ln = new LabelNode(new Label()); inject.add(new JumpInsnNode(IFEQ, ln)); if (Type.getReturnType(method.desc).equals(Type.BOOLEAN_TYPE)) { inject.add(new InsnNode(ICONST_1)); inject.add(new InsnNode(IRETURN)); } else { inject.add(new InsnNode(RETURN)); } inject.add(ln); } if (method.name.startsWith("<") && !Modifier.isStatic(method.access)) { AbstractInsnNode target = null; for (AbstractInsnNode node : this.method.instructions.toArray()) { if (node.getOpcode() == Opcodes.INVOKESPECIAL) { target = node; break; } } if (target != null) { this.method.instructions.insert(target, inject); } } else { this.method.instructions.insert(inject); } }
Source:
<code>public static VectorGenerator gauss(Vector means, Vector variances, Long seed) { <START> A.notEmpty(means.asArray(), "mean.size() != 0"); <END> A.ensure(means.size() == variances.size(), "mean.size() == variances.size()"); RandomProducer[] producers = new RandomProducer[means.size()]; for (int i = 0; i < producers.length; i++) producers[i] = new GaussRandomProducer(means.get(i), variances.get(i), seed >>= 2); return RandomProducer.vectorize(producers); }</code><technical_language>Do need convert vector array check empty</technical_language>

Target:
public static VectorGenerator gauss(Vector means, Vector variances, Long seed) { A.notEmpty(means.asArray(), "mean.size() != 0"); A.ensure(means.size() == variances.size(), "mean.size() == variances.size()"); RandomProducer[] producers = new RandomProducer[means.size()]; for (int i = 0; i < producers.length; i++) producers[i] = new GaussRandomProducer(means.get(i), variances.get(i), seed *= 2); return RandomProducer.vectorize(producers); }
Source:
<code>private void uploadModel(String modelInputPath) throws IOException { FileReader fr = new FileReader(modelInputPath); NaiveBayesModelReader reader = new PlainTextNaiveBayesModelReader(new BufferedReader(fr)); reader.checkModelType(); NaiveBayesModel initialModel = (NaiveBayesModel) reader.constructModel(); fr.close(); Object[] data = initialModel.getDataStructures(); <START> Context[] params = (Context[]) data[0]; <END> Map<String, Context> pmap = (Map<String, Context>) data[1]; String[] outcomeNames = (String[]) data[2]; this.setMasterOutcomeLabels(Arrays.asList(outcomeNames)); this.setMasterPredLabels(new ArrayList<>(pmap.keySet())); List<MutableContext> paramsList = new ArrayList<>(); for (String pred : masterPredLabels) { Context context = pmap.get(pred); MutableContext mutableContext = new MutableContext(context.getOutcomes(), context.getParameters()); paramsList.add(mutableContext); } this.setParameters(paramsList); }</code><technical_language>this appears unused</technical_language>

Target:
private void uploadModel(String modelInputPath) throws IOException { NaiveBayesModel initialModel; try (FileReader fr = new FileReader(modelInputPath)) { NaiveBayesModelReader reader = new PlainTextNaiveBayesModelReader(new BufferedReader(fr)); reader.checkModelType(); initialModel = (NaiveBayesModel) reader.constructModel(); } Object[] data = initialModel.getDataStructures(); Map<String, Context> pmap = (Map<String, Context>) data[1]; String[] outcomeNames = (String[]) data[2]; this.setMasterOutcomeLabels(Arrays.asList(outcomeNames)); this.setMasterPredLabels(new ArrayList<>(pmap.keySet())); List<MutableContext> paramsList = new ArrayList<>(); for (String pred : masterPredLabels) { Context context = pmap.get(pred); MutableContext mutableContext = new MutableContext(context.getOutcomes(), context.getParameters()); paramsList.add(mutableContext); } this.setParameters(paramsList); }
Source:
<code>public void testModuleGroups() throws Exception { Map<String, String> results = new HashMap<>(); results.put(CDH580Spark2Constant.SPARK_MODULE_GROUP.getModuleName(), "(SPARK_LOCAL_MODE=='false')"); results.put(CDH580Spark2Constant.HDFS_MODULE_GROUP.getModuleName(), "(SPARK_LOCAL_MODE=='false')"); results.put(CDH580Spark2Constant.MAPREDUCE_MODULE_GROUP.getModuleName(), "(SPARK_LOCAL_MODE=='false')"); results.put(CDH580Spark2Constant.SPARK_MRREQUIRED_MODULE_GROUP.getModuleName(), "(SPARK_LOCAL_MODE=='false')"); results.put(CDH580Spark2Constant.TALEND_CLOUDERA_CDH_5_5_NAVIGATOR.getModuleName(), "(USE_CLOUDERA_NAVIGATOR=='true')"); Set<DistributionModuleGroup> moduleGroups = CDH580Spark2SparkStreamingModuleGroup.getModuleGroups(); <START> assertEquals(3, moduleGroups.size()); <END> moduleGroups.iterator(); for (DistributionModuleGroup module : moduleGroups) { assertTrue("Should contain module " + module.getModuleName(), results.containsKey(module.getModuleName())); if (results.get(module.getModuleName()) == null) { assertTrue("The condition of the module " + module.getModuleName() + " is not null.", results.get(module.getModuleName()) == null); } else { assertTrue("The condition of the module " + module.getModuleName() + " is null, but it should be " + results.get(module.getModuleName()) + ".", results.get(module.getModuleName()) != null); assertEquals(results.get(module.getModuleName()), module.getRequiredIf().getConditionString()); } } }</code><technical_language>"5" ? Else do assertEquals(results.size(), moduleGroups.size())</technical_language>

Target:
public void testModuleGroups() throws Exception { Map<String, String> results = new HashMap<>(); results.put(CDH580Spark2Constant.SPARK_MODULE_GROUP.getModuleName(), "(SPARK_LOCAL_MODE=='false')"); results.put(CDH580Spark2Constant.HDFS_MODULE_GROUP.getModuleName(), "(SPARK_LOCAL_MODE=='false')"); results.put(CDH580Spark2Constant.MAPREDUCE_MODULE_GROUP.getModuleName(), "(SPARK_LOCAL_MODE=='false')"); Set<DistributionModuleGroup> moduleGroups = CDH580Spark2SparkStreamingModuleGroup.getModuleGroups(); assertEquals(results.size(), moduleGroups.size()); moduleGroups.iterator(); for (DistributionModuleGroup module : moduleGroups) { assertTrue("Should contain module " + module.getModuleName(), results.containsKey(module.getModuleName())); if (results.get(module.getModuleName()) == null) { assertTrue("The condition of the module " + module.getModuleName() + " is not null.", results.get(module.getModuleName()) == null); } else { assertTrue("The condition of the module " + module.getModuleName() + " is null, but it should be " + results.get(module.getModuleName()) + ".", results.get(module.getModuleName()) != null); assertEquals(results.get(module.getModuleName()), module.getRequiredIf().getConditionString()); } } }
Source:
<code>private void addWrapper(ProxyWhitelist pwl){ <START> lock.writeLock().lock(); <END> wrappers.put(pwl, null); lock.writeLock().unlock(); }</code><technical_language>get a deadlock in some cases? #reset holds a lock for outer ProxyWhitelist, this is called acquire lock for delegate ProxyWhitelist. Do locks acquired in order? I surprised if cyclic references instances of ProxyWhitelist, guess is fine, good for confirm</technical_language>

Target:
private void addWrapper(ProxyWhitelist pwl){ lock.writeLock().lock(); try { wrappers.put(pwl, null); } finally { lock.writeLock().unlock(); } }
Source:
<code><START> public JiraSite(String url){ <END> URL mainURL = toURL(url); if (mainURL == null) throw new AssertionError("URL cannot be null"); this.url = mainURL; }</code><technical_language>toUrl method throw AssetionError itself, need null check</technical_language>

Target:
public JiraSite(String url){ URL mainURL = toURL(url); if (mainURL == null) throw new AssertionError("URL cannot be empty"); this.url = mainURL; }
Source:
<code>public long getVirtualOffsetForSeek(final long uncompressedOffset) { if (uncompressedOffset == 0) { return BlockCompressedFilePointerUtil.makeFilePointer(0, 0); } final IndexEntry indexEntry = entries.stream() <START> .filter(entry -> entry.getUncompressedOffset() >= uncompressedOffset) <END> .findFirst().orElse(FIRST_MAPPING); final int blockOffset = Math.toIntExact(indexEntry.getUncompressedOffset() - uncompressedOffset); return BlockCompressedFilePointerUtil.makeFilePointer(indexEntry.getCompressedOffset(), blockOffset); }</code><technical_language>confused this. this is finding block offset for. want find block offset for? I confused? want implement this a binary search potentially entries in a large gzipped file</technical_language>

Target:
public long getVirtualOffsetForSeek(final long uncompressedOffset) { try { if (uncompressedOffset == 0) { return BlockCompressedFilePointerUtil.makeFilePointer(0, 0); } final int pos = Collections.binarySearch(entries, new IndexEntry(0, uncompressedOffset), Comparator.comparingLong(IndexEntry::getUncompressedOffset)); if (pos >= 0) { return BlockCompressedFilePointerUtil.makeFilePointer( entries.get(pos).getCompressedOffset(), 0); } final int entryPos = -pos - 2; if (entryPos == -1) { return BlockCompressedFilePointerUtil.makeFilePointer(0, Math.toIntExact(uncompressedOffset)); } final IndexEntry indexEntry = entries.get(entryPos); final int blockOffset = Math.toIntExact(uncompressedOffset - indexEntry.getUncompressedOffset()); return BlockCompressedFilePointerUtil.makeFilePointer(indexEntry.getCompressedOffset(), blockOffset); } catch (ArithmeticException e) { throw new IllegalArgumentException("Cannot handle offsets within blocks larger than " + Integer.MAX_VALUE, e); } }
Source:
<code>private AmazonEC2 getEC2Service() { eurekaConfig = EurekaServerConfigurationManager.getInstance() .getConfiguration(); <START> AmazonEC2 ec2Service = new AmazonEC2Client( <END> AWSCredentialsManager.getInstance().getCredentials()); String region = DiscoveryManager.getInstance().getEurekaClientConfig() .getRegion(); region = region.trim().toLowerCase(); ec2Service.setEndpoint("ec2." + region + ".amazonaws.com"); return ec2Service; }</code><technical_language>I is a problem this approach, specifically pulling credentials out of On-Instance Provider, credentials expire 12 hours default. net result is this AmazonEC2 object self-destruct 12 hours, unintended consequences road. I applaud incorporation of On-Instance providers; however, I provider needs funneled Amazon Objects in order for safe. Thanks, Jay</technical_language>

Target:
private AmazonEC2 getEC2Service() { eurekaConfig = EurekaServerConfigurationManager.getInstance() .getConfiguration(); String aWSAccessId = eurekaConfig.getAWSAccessId(); String aWSSecretKey = eurekaConfig.getAWSSecretKey(); AmazonEC2 ec2Service; if (null != aWSAccessId && !"".equals(aWSAccessId) && null != aWSSecretKey && !"".equals(aWSSecretKey)) { ec2Service = new AmazonEC2Client(new BasicAWSCredentials( aWSAccessId, aWSSecretKey)); } else { ec2Service = new AmazonEC2Client( new InstanceProfileCredentialsProvider()); } String region = DiscoveryManager.getInstance().getEurekaClientConfig() .getRegion(); region = region.trim().toLowerCase(); ec2Service.setEndpoint("ec2." + region + ".amazonaws.com"); return ec2Service; }
Source:
<code>public Method getOnErrorMethod(Object webSocketEndpoint) { <START> Method[] methods = webSocketEndpoint.getClass().getMethods(); <END> for (Method method : methods) { if (method.isAnnotationPresent(OnError.class)) { return method; } } return null; }</code><technical_language>above, for loop throw a NPE if methods variable null</technical_language>

Target:
public Method getOnErrorMethod(Object webSocketEndpoint) { Method[] methods = webSocketEndpoint.getClass().getMethods(); if (methods == null) { return null; } for (Method method : methods) { if (method.isAnnotationPresent(OnError.class)) { return method; } } return null; }
Source:
<code>public static MessageTransformers createMessageTransformer(String className, SecorConfig config) throws Exception { <START> Class<?> clazz = Class.forName(className); <END> if(!MessageTransformers.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.", className, MessageTransformers.class.getName())); } return (MessageTransformers) clazz.getConstructor(SecorConfig.class).newInstance(config); }</code><technical_language>spaces instead of tabs</technical_language>

Target:
public static MessageTransformer createMessageTransformer( String className, SecorConfig config) throws Exception { Class<?> clazz = Class.forName(className); if (!MessageTransformer.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format( "The class '%s' is not assignable to '%s'.", className, MessageTransformer.class.getName())); } return (MessageTransformer) clazz.getConstructor(SecorConfig.class) .newInstance(config); }
Source:
<code>public TextFieldTableCell<S, T> call(TableColumn<S, T> param) { return new TextFieldTableCell<>(stringConverter) { List<Subscription> subscriptions = new ArrayList<>(); @Override public void startEdit() { super.startEdit(); lookupTextField().ifPresent(textField -> Platform.runLater(() -> { textField.requestFocus(); textField.selectAll(); })); } private Optional<TextField> lookupTextField() { if (getGraphic() instanceof TextField) { return Optional.of((TextField) getGraphic()); } else { if (getGraphic() instanceof HBox) { HBox hbox = (HBox) getGraphic(); if ((hbox.getChildren().size() > 1) && hbox.getChildren().get(1) instanceof TextField) { return Optional.of((TextField) hbox.getChildren().get(1)); } } return Optional.empty(); } } @Override public void updateItem(T item, boolean empty) { super.updateItem(item, empty); subscriptions.forEach(Subscription::unsubscribe); subscriptions.clear(); S viewModel = getTableRow().getItem(); if (empty || (viewModel == null)) { setText(null); setGraphic(null); setOnMouseClicked(null); setTooltip(null); setStyle(""); } else { if (validationStatusProperty != null) { validationStatusProperty.apply(viewModel).getHighestMessage().ifPresent(message -> { setTooltip(new Tooltip(message.getMessage())); <START> subscriptions.add(BindingsHelper.includePseudoClassWhen(this, INVALID_PSEUDO_CLASS, <END> validationStatusProperty.apply(viewModel).validProperty().not())); }); } } } }; }</code><technical_language>This line of isPresent block want subscribe validProperty in case</technical_language>

Target:
public TextFieldTableCell<S, T> call(TableColumn<S, T> param) { return new TextFieldTableCell<>(stringConverter) { final List<Subscription> subscriptions = new ArrayList<>(); @Override public void startEdit() { super.startEdit(); lookupTextField().ifPresent(textField -> Platform.runLater(() -> { textField.requestFocus(); textField.selectAll(); })); } private Optional<TextField> lookupTextField() { if (getGraphic() instanceof TextField) { return Optional.of((TextField) getGraphic()); } else { if (getGraphic() instanceof HBox) { HBox hbox = (HBox) getGraphic(); if ((hbox.getChildren().size() > 1) && hbox.getChildren().get(1) instanceof TextField) { return Optional.of((TextField) hbox.getChildren().get(1)); } } return Optional.empty(); } } @Override public void updateItem(T item, boolean empty) { super.updateItem(item, empty); subscriptions.forEach(Subscription::unsubscribe); subscriptions.clear(); if (empty || getTableRow() == null || getTableRow().getItem() == null) { setText(null); setGraphic(null); setOnMouseClicked(null); setTooltip(null); pseudoClassStateChanged(INVALID_PSEUDO_CLASS, false); } else { S viewModel = getTableRow().getItem(); if (validationStatusProperty != null) { validationStatusProperty.apply(viewModel) .getHighestMessage() .ifPresent(message -> setTooltip(new Tooltip(message.getMessage()))); subscriptions.add(BindingsHelper.includePseudoClassWhen( this, INVALID_PSEUDO_CLASS, validationStatusProperty.apply(viewModel).validProperty().not())); } } } }; }
Source:
<code>private boolean canConnectToConsole() { final VM vm = getVm(); machineHasReconnectFlag = vm.getAllowConsoleReconnect(); if (machineHasReconnectFlag) { return true; } userHasReconnectPermission = checkUserAuthorization(ActionGroup.RECONNECT_TO_VM, MultiLevelAdministrationHandler.SYSTEM_OBJECT_ID, VdcObjectType.System); if (userHasReconnectPermission) { return true; <START> } <END> final String currentName = getCurrentUser().getUserName(); final NGuid currentId = getCurrentUser().getUserId(); final String previousName = vm.getConsoleUserName(); final NGuid previousId = vm.getConsoleUserId(); if (previousId != null && !previousId.equals(currentId)) { log.warnFormat("User \"{0}\" is trying to set a ticket for virtual machine \"{1}\" but the machine is already in use by \"{2}\".", currentName, vm.getvm_name(), previousName); log.warnFormat("The id of user \"{0}\" is \"{1}\".", currentName, currentId); log.warnFormat("The id of user \"{0}\" is \"{1}\".", previousName, previousId); log.warnFormat("The id of virtual machine \"{0}\" is \"{1}\".", vm.getvm_name(), vm.getvm_guid()); log.warnFormat("The ticket will not be set."); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_IN_USE_BY_OTHER_USER); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__SET); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_TICKET); return false; } return true; }</code><technical_language>I consistent rest of engine architecture this authorization check part of 'IsUserAutorizedToRunAction' method. I override IsUserAutorizedToRunAction method call super beginning of implementation invoke canConnectToConsole part of authentication mechanism (instead of invoked part of canDoAction logic). idea that, in addition for general architecture, is want give user info validating user perform action. In this context user get a message - VM in status illegal user is authorized perform action</technical_language>

Target:
private boolean canConnectToConsole() { final VM vm = getVm(); if (vm.getAllowConsoleReconnect()) { return true; } final String currentName = getCurrentUser().getUserName(); final NGuid currentId = getCurrentUser().getUserId(); final String previousName = vm.getConsoleUserName(); final NGuid previousId = vm.getConsoleUserId(); if (previousId != null && !previousId.equals(currentId)) { log.warnFormat("User \"{0}\" is trying to set a ticket for virtual machine \"{1}\" but the machine is already in use by \"{2}\".", currentName, vm.getvm_name(), previousName); log.warnFormat("The id of user \"{0}\" is \"{1}\".", currentName, currentId); log.warnFormat("The id of user \"{0}\" is \"{1}\".", previousName, previousId); log.warnFormat("The id of virtual machine \"{0}\" is \"{1}\".", vm.getvm_name(), vm.getvm_guid()); log.warnFormat("The ticket will not be set."); addCanDoActionMessage(VdcBllMessages.USER_NOT_AUTHORIZED_TO_PERFORM_ACTION); return false; } return true; }
Source:
<code>private static void setWallpaper(Context context, Bitmap bitmap) { WallpaperManager wallpaperManager = WallpaperManager.getInstance(context); try { wallpaperManager.setBitmap(bitmap); ViewUtil.showLongToast(context, context.getString(R.string.wallpaper_set_successfully)); <START> if (progressDialog.isShowing() && progressDialog != null) { <END> progressDialog.dismiss(); } } catch (IOException e) { Timber.e(e, "Error setting wallpaper"); ViewUtil.showLongToast(context, context.getString(R.string.wallpaper_set_unsuccessfully)); if (progressDialog != null) { progressDialog.cancel(); } } }</code><technical_language>flip conditions, null check done</technical_language>

Target:
private static void setWallpaper(Context context, Bitmap bitmap) { WallpaperManager wallpaperManager = WallpaperManager.getInstance(context); try { wallpaperManager.setBitmap(bitmap); ViewUtil.showLongToast(context, context.getString(R.string.wallpaper_set_successfully)); if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } catch (IOException e) { Timber.e(e, "Error setting wallpaper"); ViewUtil.showLongToast(context, context.getString(R.string.wallpaper_set_unsuccessfully)); if (progressDialog != null) { progressDialog.cancel(); } } }
Source:
<code>protected void enableDiscoveryProtocol(JChannel c) { for (Protocol p : c.getProtocolStack().getProtocols()) { <START> if (p instanceof Discovery) { <END> try { log.tracef("About to start discovery: %s", p); p.start(); } catch (Exception e) { throw new RuntimeException(e); } } } }</code><technical_language>odd instanceof checks symmetric</technical_language>

Target:
protected void enableDiscoveryProtocol(JChannel c) { try { c.getProtocolStack().findProtocol(TEST_PING.class).start(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public void parseWithContinuation() throws Exception { String code = load("cpp_with_continuation.cpp"); Tokens tokens = parse(code); if (tokens.size() < 52) { printTokens(tokens); fail("Not enough tokens - probably parsing error. Tokens: " + tokens.size()); } assertEquals("static", findByLine(8, tokens).get(0).toString()); assertEquals("int", findByLine(8, tokens).get(1).toString()); <START> assertEquals("ab", findByLine(8, tokens).get(2).toString()); <END> assertEquals("int", findByLine(12, tokens).get(0).toString()); assertEquals("main", findByLine(12, tokens).get(1).toString()); assertEquals("(", findByLine(12, tokens).get(2).toString()); assertEquals(")", findByLine(12, tokens).get(3).toString()); assertEquals("{", findByLine(13, tokens).get(0).toString()); assertEquals("\"world!\\n\"", findByLine(16, tokens).get(0).toString()); assertEquals("}", findByLine(29, tokens).get(0).toString()); }</code><technical_language>add assert checking token's beingLine / endLine properly filled</technical_language>

Target:
public void parseWithContinuation() throws Exception { String code = load("cpp_with_continuation.cpp"); Tokens tokens = parse(code); if (tokens.size() < 52) { printTokens(tokens); fail("Not enough tokens - probably parsing error. Tokens: " + tokens.size()); } assertEquals("static", findByLine(8, tokens).get(0).toString()); assertEquals("int", findByLine(8, tokens).get(1).toString()); TokenEntry tokenEntry = findByLine(8, tokens).get(2); assertEquals("ab", tokenEntry.toString()); assertEquals("int", findByLine(12, tokens).get(0).toString()); assertEquals("main", findByLine(12, tokens).get(1).toString()); assertEquals("(", findByLine(12, tokens).get(2).toString()); assertEquals(")", findByLine(12, tokens).get(3).toString()); assertEquals("{", findByLine(13, tokens).get(0).toString()); assertEquals("\"world!\\n\"", findByLine(16, tokens).get(0).toString()); assertEquals("\"3 Hello, \\world!\\n\"", findByLine(22, tokens).get(4).toString()); assertEquals("}", findByLine(29, tokens).get(0).toString()); }
Source:
<code>public void testNonExistentProtocol() throws Exception { <START> fail("IGNITE-10245"); <END> protocols = new String[] { "SSLv3" }; startGrid(); checkClientStartFailure( null, new String[][] { new String[] { "SSLv3", "SSLvDoesNotExist" } }, GridClientException.class, "SSLvDoesNotExist" ); }</code><technical_language><LINK_0></technical_language>

Target:
public void testNonExistentProtocol() throws Exception { protocols = new String[] { "SSLv3" }; startGrid(); checkClientStartFailure( null, new String[] { "SSLv3", "SSLvDoesNotExist" }, "SSLvDoesNotExist" ); }
Source:
<code>public void testEndToEnd() throws IOException { final File tempFile = File.createTempFile("IntervalCodecTest.", ".interval_list"); tempFile.deleteOnExit(); final IntervalList expectedList = new IntervalList(this.dict); final IntervalList actualList = new IntervalList(this.dict); expectedList.add(new Interval("chr1", 50, 150)); expectedList.add(new Interval("chr1", 150, 250)); expectedList.add(new Interval("chr2", 50, 150)); expectedList.add(new Interval("chr3", 50, 150)); expectedList.add(new Interval("chr1", 50, 150, true, "number-5")); expectedList.add(new Interval("chr1", 150, 250, false, "number-6")); <START> try(final OutputStream outputStream = new FileOutputStream(tempFile)) { <END> final IntervalCodec writeCodec = new IntervalCodec(this.dict); writeCodec.setOutputStream(outputStream); for (final Interval interval : expectedList.getIntervals()) { writeCodec.encode(interval); } } final IntervalCodec readCodec = new IntervalCodec(this.dict); try(final InputStream inputStream = new FileInputStream(tempFile)) { readCodec.setInputStream(inputStream); while (true) { final Interval interval = readCodec.decode(); if (interval == null) { break; } else { actualList.add(interval); } } } Assert.assertEquals( actualList.getIntervals(), expectedList.getIntervals() ); }</code><technical_language>suggestion try (final OutputStream outputStream = new FileOutputStream(tempFile)) {</technical_language>

Target:
public void testEndToEnd() throws IOException { final File tempFile = File.createTempFile("IntervalCodecTest.", ".interval_list"); tempFile.deleteOnExit(); final IntervalList expectedList = new IntervalList(this.dict); final IntervalList actualList = new IntervalList(this.dict); expectedList.add(new Interval("chr1", 50, 150)); expectedList.add(new Interval("chr1", 150, 250)); expectedList.add(new Interval("chr2", 50, 150)); expectedList.add(new Interval("chr3", 50, 150)); expectedList.add(new Interval("chr1", 50, 150, true, "number-5")); expectedList.add(new Interval("chr1", 150, 250, false, "number-6")); try (final OutputStream outputStream = new FileOutputStream(tempFile)) { final IntervalCodec writeCodec = new IntervalCodec(this.dict); writeCodec.setOutputStream(outputStream); for (final Interval interval : expectedList.getIntervals()) { writeCodec.encode(interval); } } final IntervalCodec readCodec = new IntervalCodec(this.dict); try (final InputStream inputStream = new FileInputStream(tempFile)) { readCodec.setInputStream(inputStream); while (true) { final Interval interval = readCodec.decode(); if (interval == null) { break; } actualList.add(interval); } } Assert.assertEquals( actualList.getIntervals(), expectedList.getIntervals() ); }
Source:
<code>private static URI fixFileURL(URL u) { <START> if (!"file".equals(u.getProtocol())) throw new IllegalArgumentException(); <END> return new File(u.getFile()).toURI(); }</code><technical_language>Please a 2-space indent braces throws block</technical_language>

Target:
private static URI fixFileURL(URL u) { if (!"file".equals(u.getProtocol())) { throw new IllegalArgumentException(); } return new File(u.getFile()).toURI(); }
Source:
<code>private static @Nullable State getEventState(TimeEvent event) { if (event.hasValue()) { VirtualMachineViewEntry entry = (VirtualMachineViewEntry) event.getEntry(); int value = event.getValue(); if (entry.getType() == Type.VCPU) { <START> if ((value & VcpuStateValues.VCPU_PREEMPT) > 0) { return State.VCPU_PREEMPTED; } else if ((value & VcpuStateValues.VCPU_VMM) > 0) { return State.WAIT_VMM; } else if (value == 2) { return State.USERMODE; } else if (value == 1) { return State.IDLE; } else { return State.UNKNOWN; } <END> } else if (entry.getType() == Type.THREAD) { if (value == VcpuStateValues.VCPU_PREEMPT) { return null; } switch (value) { case StateValues.PROCESS_STATUS_RUN_USERMODE: return State.THREAD_USERMODE; case StateValues.PROCESS_STATUS_RUN_SYSCALL: return State.THREAD_SYSCALL; case StateValues.PROCESS_STATUS_WAIT_FOR_CPU: return State.THREAD_WAIT_FOR_CPU; case StateValues.PROCESS_STATUS_WAIT_BLOCKED: return State.THREAD_WAIT_BLOCKED; case StateValues.PROCESS_STATUS_INTERRUPTED: return State.THREAD_INTERRUPTED; case StateValues.PROCESS_STATUS_UNKNOWN: case StateValues.PROCESS_STATUS_WAIT_UNKNOWN: return State.THREAD_UNKNOWN; default: return null; } } } return null; }</code><technical_language>new method</technical_language>

Target:
private static @Nullable State getEventState(TimeEvent event) { if (event.hasValue()) { VirtualMachineViewEntry entry = (VirtualMachineViewEntry) event.getEntry(); int value = event.getValue(); if (entry.getType() == Type.VCPU) { return getStateForVcpu(value); } else if (entry.getType() == Type.THREAD) { return getStateForThread(value); } } return null; }
Source:
<code><START> private <T, U> Map<T, U> getGuestOsInto(){ <END> Map resultMap = map(); resultMap.put("kernel","2.6.32-642.el6.x86_64"); resultMap.put("type", "linux"); resultMap.put("version", "6.7"); resultMap.put("arch", "x86_64"); resultMap.put("codename", "Santiago"); resultMap.put("distribution", "Red Hat Enterprise Linux Server"); return resultMap; }</code><technical_language>VDSM schema this is Map<String, String>, please change</technical_language>

Target:
private Map<String, String> getGuestOsInto(){ Map<String, String> resultMap = map(); resultMap.put("kernel","2.6.32-642.el6.x86_64"); resultMap.put("type", "linux"); resultMap.put("version", "6.7"); resultMap.put("arch", "x86_64"); resultMap.put("codename", "Santiago"); resultMap.put("distribution", "Red Hat Enterprise Linux Server"); return resultMap; }
Source:
<code>public EnhancerFactoryData(Class generatedClass, Class[] primaryConstructorArgTypes, boolean classOnly) { this.generatedClass = generatedClass; try { setThreadCallbacks = getCallbacksSetter(generatedClass, SET_THREAD_CALLBACKS_NAME); <START> setThreadCallbacks.setAccessible(true); <END> if (classOnly) { this.primaryConstructorArgTypes = null; this.primaryConstructor = null; } else { this.primaryConstructorArgTypes = primaryConstructorArgTypes; this.primaryConstructor = generatedClass.getDeclaredConstructor(primaryConstructorArgTypes); primaryConstructor.setAccessible(true); } } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } }</code><technical_language>is this necessary? done before</technical_language>

Target:
public EnhancerFactoryData(Class generatedClass, Class[] primaryConstructorArgTypes, boolean classOnly) { this.generatedClass = generatedClass; try { setThreadCallbacks = getCallbacksSetter(generatedClass, SET_THREAD_CALLBACKS_NAME); if (classOnly) { this.primaryConstructorArgTypes = null; this.primaryConstructor = null; } else { this.primaryConstructorArgTypes = primaryConstructorArgTypes; this.primaryConstructor = ReflectUtils.getConstructor(generatedClass, primaryConstructorArgTypes); } } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } }
Source:
<code>public SyncUser retrieveUser(final String provider, final String providerId) throws ObjectServerError { if (Util.isEmptyString(provider)) { throw new IllegalArgumentException("Not-null 'provider' required."); } if (Util.isEmptyString(providerId)) { throw new IllegalArgumentException("None empty 'providerId' required."); } if (!isAdmin()) { <START> throw new IllegalStateException("User need to be admin in order to lookup ID."); <END> } AuthenticationServer authServer = SyncManager.getAuthServer(); LookupUserIdResponse response = authServer.retrieveUser(getSyncUser().getUserToken(), provider, providerId, getAuthenticationUrl()); if (!response.isValid()) { throw response.getError(); } else { SyncUser syncUser = SyncManager.getUserStore().get(response.getUserId()); if (syncUser != null) { return syncUser; } else { Token refreshToken = new Token(null, response.getUserId(), null, 0, null, response.isAdmin()); ObjectServerUser objectServerUser = new ObjectServerUser(refreshToken, getAuthenticationUrl()); objectServerUser.localLogout(); return new SyncUser(objectServerUser); } } }</code><technical_language>in order lookup other users</technical_language>

Target:
public SyncUser retrieveUser(final String provider, final String providerId) throws ObjectServerError { if (Util.isEmptyString(provider)) { throw new IllegalArgumentException("Not-null 'provider' required."); } if (Util.isEmptyString(providerId)) { throw new IllegalArgumentException("None empty 'providerId' required."); } if (!isAdmin()) { throw new IllegalArgumentException("SyncUser needs to be admin in order to lookup other users ID."); } AuthenticationServer authServer = SyncManager.getAuthServer(); LookupUserIdResponse response = authServer.retrieveUser(getSyncUser().getUserToken(), provider, providerId, getAuthenticationUrl()); if (!response.isValid()) { if (response.getError().getErrorCode() == ErrorCode.NOT_FOUND) { return null; } else { throw response.getError(); } } else { SyncUser syncUser = SyncManager.getUserStore().get(response.getUserId()); if (syncUser != null) { return syncUser; } else { Token refreshToken = new Token(null, response.getUserId(), null, 0, null, response.isAdmin()); ObjectServerUser objectServerUser = new ObjectServerUser(refreshToken, getAuthenticationUrl()); objectServerUser.localLogout(); return new SyncUser(objectServerUser); } } }
Source:
<code>public void updateStats(Binary min_value, Binary max_value) { <START> if (min.compareTo(min_value) > 0) { min = Binary.fromByteArray(min_value.getBytes()); } <END> if (max.compareTo(max_value) < 0) { max = Binary.fromByteArray(max_value.getBytes()); } }</code><technical_language>Binary.copy</technical_language>

Target:
public void updateStats(Binary min_value, Binary max_value) { if (min.compareTo(min_value) > 0) { min = min_value.copy(); } if (max.compareTo(max_value) < 0) { max = max_value.copy(); } }
Source:
<code>public Integer getNumberOpenedSocketsByUri(String uri) { Integer numberOpenedSocketForUri = 0; <START> if (socketsByUri.containsKey(uri)) { <END> numberOpenedSocketForUri = socketsByUri.get(uri).size(); } return numberOpenedSocketForUri; }</code><technical_language>concurrency issue</technical_language>

Target:
public Integer getNumberOpenedSocketsByUri(String uri) { Integer numberOpenedSocketForUri = 0; synchronized (this) { if (socketsByUri.containsKey(uri)) { numberOpenedSocketForUri = socketsByUri.get(uri).size(); } } return numberOpenedSocketForUri; }
Source:
<code>private void bindFrontendInfrastructure() { bind(Frontend.class).in(Singleton.class); requestStaticInjection(Frontend.InstanceHolder.class); <START> requestStaticInjection(AssetProvider.class); <END> bind(VdcOperationManager.class).in(Singleton.class); bind(OperationProcessor.class).in(Singleton.class); bind(CommunicationProvider.class).to(GWTRPCCommunicationProvider.class).in(Singleton.class); }</code><technical_language>Hm, this method meant GIN bindings for "frontend communication infra" classes, put AssetProvider binding elsewhere, e.g. end of bindCommonInfrastructure method</technical_language>

Target:
private void bindFrontendInfrastructure() { bind(Frontend.class).in(Singleton.class); requestStaticInjection(Frontend.InstanceHolder.class); bind(VdcOperationManager.class).in(Singleton.class); bind(OperationProcessor.class).in(Singleton.class); bind(CommunicationProvider.class).to(GWTRPCCommunicationProvider.class).in(Singleton.class); }
Source:
<code>public boolean isMap(final Object o) { <START> if (o instanceof Map) { <END> return true; } else { return o instanceof Group; } }</code><technical_language>(o instanceof Map) || (o instanceof Group)</technical_language>

Target:
public boolean isMap(final Object o) { return o instanceof Map || o instanceof Group; }
Source:
<code>public StateDescription getStateDescription(String itemName, Locale locale) { Set<ChannelUID> boundChannels = itemChannelLinkRegistry.getBoundChannels(itemName); if (!boundChannels.isEmpty()) { ChannelUID channelUID = boundChannels.iterator().next(); Channel channel = thingRegistry.getChannel(channelUID); if (channel != null) { ChannelType channelType = thingTypeRegistry.getChannelType(channel, locale); if (channelType != null) { StateDescription state = channelType.getState(); if ((channelType.getItemType() != null) && ((state == null) || (state.getPattern() == null))) { String pattern = null; if (channelType.getItemType().equalsIgnoreCase("String")) { pattern = "%s"; } else if (channelType.getItemType().equalsIgnoreCase("Number")) { pattern = "%.0f"; } if (pattern != null) { <START> logger.debug("Provide a default pattern for item {}", pattern, itemName); <END> if (state == null) { state = new StateDescription(null, null, null, pattern, false, null); } else { state = new StateDescription(state.getMinimum(), state.getMaximum(), state.getStep(), pattern, state.isReadOnly(), state.getOptions()); } } } return state; } else { return null; } } } return null; }</code><technical_language>please reduce trace level</technical_language>

Target:
public StateDescription getStateDescription(String itemName, Locale locale) { Set<ChannelUID> boundChannels = itemChannelLinkRegistry.getBoundChannels(itemName); if (!boundChannels.isEmpty()) { ChannelUID channelUID = boundChannels.iterator().next(); Channel channel = thingRegistry.getChannel(channelUID); if (channel != null) { ChannelType channelType = thingTypeRegistry.getChannelType(channel, locale); if (channelType != null) { StateDescription stateDescription = channelType.getState(); if ((channelType.getItemType() != null) && ((stateDescription == null) || (stateDescription.getPattern() == null))) { String pattern = null; if (channelType.getItemType().equalsIgnoreCase(CoreItemFactory.STRING)) { pattern = "%s"; } else if (channelType.getItemType().equalsIgnoreCase(CoreItemFactory.NUMBER)) { pattern = "%.0f"; } if (pattern != null) { logger.trace("Provide a default pattern for item {}", pattern, itemName); if (stateDescription == null) { stateDescription = new StateDescription(null, null, null, pattern, false, null); } else { stateDescription = new StateDescription(stateDescription.getMinimum(), stateDescription.getMaximum(), stateDescription.getStep(), pattern, stateDescription.isReadOnly(), stateDescription.getOptions()); } } } return stateDescription; } else { return null; } } } return null; }
Source:
<code>public Node transform(QueryVisitor queryVisitor) { NodeVisitorImpl nodeVisitor = new NodeVisitorImpl(queryVisitor, new QueryVisitorStub()); Map<Class<?>, Object> rootVars = new LinkedHashMap<>(); rootVars.put(QueryTraversalContext.class, new QueryTraversalContext(rootParentType, rootParentType, null, null)); Node root = roots.stream().findFirst() <START> .orElseThrow(() -> new IllegalArgumentException("Single root node is required for transformation.")); <END> TraverserVisitor<Node> nodeTraverserVisitor = new TraverserVisitor<Node>() { @Override public TraversalControl enter(TraverserContext<Node> context) { context.setVar(LeaveOrEnter.class, LeaveOrEnter.ENTER); return context.thisNode().accept(context, nodeVisitor); } @Override public TraversalControl leave(TraverserContext<Node> context) { context.setVar(LeaveOrEnter.class, LeaveOrEnter.LEAVE); return context.thisNode().accept(context, nodeVisitor); } }; return new TreeTransformer<>(AST_NODE_ADAPTER).transform(root, nodeTraverserVisitor, rootVars); }</code><technical_language>Assert class, please</technical_language>

Target:
public Node transform(QueryVisitor queryVisitor) { NodeVisitorImpl nodeVisitor = new NodeVisitorImpl(queryVisitor, new QueryVisitorStub()); Map<Class<?>, Object> rootVars = new LinkedHashMap<>(); rootVars.put(QueryTraversalContext.class, new QueryTraversalContext(rootParentType, rootParentType, null, null)); assertTrue(roots.size() == 1, "Single root node is required for transformation."); Node root = roots.stream().findFirst().get(); TraverserVisitor<Node> nodeTraverserVisitor = new TraverserVisitor<Node>() { @Override public TraversalControl enter(TraverserContext<Node> context) { context.setVar(LeaveOrEnter.class, LeaveOrEnter.ENTER); return context.thisNode().accept(context, nodeVisitor); } @Override public TraversalControl leave(TraverserContext<Node> context) { return TraversalControl.CONTINUE; } }; return new TreeTransformer<>(AST_NODE_ADAPTER).transform(root, nodeTraverserVisitor, rootVars); }
Source:
<code>private KafkaLogAppender(String topic, String name, Properties producerProperties, Properties consumerProperties) { this.topic = topic; this.name = name; this.producerProps = producerProperties; this.consumerProps = consumerProperties; this.producer = new KafkaProducer<>(this.producerProps); this.size = producer.partitionsFor(topic).size(); <START> log.debug(String.format("Created appender: %s on topic: %s with %d partitions", name, topic, size)); <END> }</code><technical_language>isInfoDebug</technical_language>

Target:
private KafkaLogAppender(String topic, String name, Properties producerProperties, Properties consumerProperties) { this.topic = topic; this.name = name; this.producerProps = producerProperties; this.consumerProps = consumerProperties; this.producer = new KafkaProducer<>(this.producerProps); this.size = producer.partitionsFor(topic).size(); if (log.isDebugEnabled()) { log.debug(String.format("Created appender: %s on topic: %s with %d partitions", name, topic, size)); } }
Source:
<code>private static void expectConsumerAssignmentPaused(final Consumer<byte[], byte[]> consumer) { final Set<TopicPartition> assignment = singleton(new TopicPartition("assignment", 0)); expect(consumer.assignment()).andReturn(assignment); consumer.pause(assignment); <START> expectLastCall(); <END> }</code><technical_language>prop: remove this line. need expectLastCall() if need do some expectation settings a call returns void, e.g., expectLastCall().times(3)</technical_language>

Target:
private static void expectConsumerAssignmentPaused(final Consumer<byte[], byte[]> consumer) { final Set<TopicPartition> assignment = singleton(new TopicPartition("assignment", 0)); expect(consumer.assignment()).andReturn(assignment); consumer.pause(assignment); }
Source:
<code>public void testGetWriteFlagsNone() { <START> assertEquals(EnumSet.noneOf(WriteFlag.class), WriteFlag.getWriteFlags(0)); <END> }</code><technical_language>give a meaningful name for 0</technical_language>

Target:
public void testGetWriteFlagsNone() { assertEquals(EnumSet.noneOf(WriteFlag.class), WriteFlag.getWriteFlags(NONE)); }