auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public byte[] getCacheKey() { <START> try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { <END> baos.write(StringUtils.toUtf8(getClass().getCanonicalName())); baos.write(0xFF); baos.write(StringUtils.toUtf8(getLookup())); baos.write(0xFF); baos.write(ensureDelegate().getCacheKey()); return baos.toByteArray(); } catch (IOException e) { throw Throwables.propagate(e); } }</code><technical_language>allocate a bytebuffer right size avoid catch IOException</technical_language>

Target:
public byte[] getCacheKey() { final byte[] keyPrefix = StringUtils.toUtf8(getClass().getCanonicalName()); final byte[] lookupName = StringUtils.toUtf8(getLookup()); final byte[] delegateKey = ensureDelegate().getCacheKey(); return ByteBuffer .allocate(keyPrefix.length + 1 + lookupName.length + 1 + delegateKey.length) .put(keyPrefix).put((byte) 0xFF) .put(lookupName).put((byte) 0xFF) .put(delegateKey) .array(); }
Source:
<code>public static RMInitialState getRMInitialState(long counter) { try { long startTime = System.currentTimeMillis(); <START> final RMInitialState state = rmProxy.getRMInitialState(counter); <END> long time = System.currentTimeMillis() - startTime; logger.debug(String.format("Updated RM initial state in %d ms", time)); return state; } catch (Exception e) { logger.error("Exception occurrend while updating RM state cache, connection reset", e); throw e; } }</code><technical_language>do need pass object reference instead of active object</technical_language>

Target:
public static RMInitialState getRMInitialState(long counter) { try { long startTime = System.currentTimeMillis(); final RMInitialState state = PAFuture.getFutureValue(rm.getRMInitialState(counter)); long time = System.currentTimeMillis() - startTime; logger.debug(String.format("Updated RM initial state in %d ms", time)); return state; } catch (Exception e) { logger.error("Exception occurrend while updating RM state cache, connection reset", e); throw e; } }
Source:
<code>public PluggableFacade(PluggableDefinition def, IPipeHolder holder, EnumFacing side, NBTTagCompound nbt) { super(def, holder, side); this.states = FacadeInstance.readFromNbt(nbt, "states"); activeState = MathUtil.clamp(nbt.getInteger("activeState"), 0, states.phasedStates.length - 1); <START> isSideSolid = states.areAllStatesSolid(side) && !states.phasedStates[activeState].isHollow(); <END> }</code><technical_language>activeState change *any* time. Depending sense. Honestly allowing phasing hollow non-hollow facades. fully implemented this up, I guess this needs fixing well</technical_language>

Target:
public PluggableFacade(PluggableDefinition def, IPipeHolder holder, EnumFacing side, NBTTagCompound nbt) { super(def, holder, side); this.states = FacadeInstance.readFromNbt(nbt, "states"); activeState = MathUtil.clamp(nbt.getInteger("activeState"), 0, states.phasedStates.length - 1); isSideSolid = states.areAllStatesSolid(side); blockFaceShape = states.getBlockFaceShape(side); }
Source:
<code>public void createClientWithJWKS_generatedKid() throws Exception { OIDCClientRepresentation clientRep = createRep(); clientRep.setGrantTypes(Collections.singletonList(OAuth2Constants.CLIENT_CREDENTIALS)); clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.PRIVATE_KEY_JWT); TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints(); <START> Map<String, String> generatedKeys = oidcClientEndpointsResource.generateKeys(null); <END> JSONWebKeySet keySet = oidcClientEndpointsResource.getJwks(); clientRep.setJwks(keySet); OIDCClientRepresentation response = reg.oidc().create(clientRep); Assert.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod()); Assert.assertNull(response.getClientSecret()); Assert.assertNull(response.getClientSecretExpiresAt()); assertAuthenticateClientSuccess(generatedKeys, response, KEEP_GENERATED_KID); }</code><technical_language>Add oidcClientEndpointsResource.generateKeys() null here</technical_language>

Target:
public void createClientWithJWKS_generatedKid() throws Exception { OIDCClientRepresentation clientRep = createRep(); clientRep.setGrantTypes(Collections.singletonList(OAuth2Constants.CLIENT_CREDENTIALS)); clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.PRIVATE_KEY_JWT); TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints(); Map<String, String> generatedKeys = oidcClientEndpointsResource.generateKeys("RS256"); JSONWebKeySet keySet = oidcClientEndpointsResource.getJwks(); clientRep.setJwks(keySet); OIDCClientRepresentation response = reg.oidc().create(clientRep); Assert.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod()); Assert.assertNull(response.getClientSecret()); Assert.assertNull(response.getClientSecretExpiresAt()); assertAuthenticateClientSuccess(generatedKeys, response, KEEP_GENERATED_KID); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final String token = tokenExtractor.getToken(httpRequest); if (isNullOrEmpty(token)) { chain.doFilter(request, response); return; } try { final Jws<Claims> jwt = <START> Jwts.parser().setSigningKeyResolver(workspaceSigningKeyResolver).parseClaimsJws(token); <END> final Claims claims = jwt.getBody(); try { final String userId = claims.get(USER_ID_CLAIM, String.class); final String userName = userManager.getById(userId).getName(); final Subject authorizedSubject = new AuthorizedSubject( new SubjectImpl(userName, userId, token, false), permissionChecker); EnvironmentContext.getCurrent().setSubject(authorizedSubject); chain.doFilter(addUserInRequest(httpRequest, authorizedSubject), response); } catch (NotFoundException ex) { sendErr( response, SC_UNAUTHORIZED, "Authentication with machine token failed because user for this token no longer exist."); } catch (ServerException ex) { sendErr( response, SC_UNAUTHORIZED, format("Authentication with machine token failed cause: %s", ex.getMessage())); } finally { EnvironmentContext.reset(); } } catch (JwtException ex) { chain.doFilter(request, response); } }</code><technical_language>extract field Jwts.parser().setSigningKeyResolver(workspaceSigningKeyResolver)</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final String token = tokenExtractor.getToken(httpRequest); if (isNullOrEmpty(token)) { chain.doFilter(request, response); return; } try { final Claims claims = jwtParser.parseClaimsJws(token).getBody(); try { final String userId = claims.get(USER_ID_CLAIM, String.class); final String userName = userManager.getById(userId).getName(); final Subject authorizedSubject = new AuthorizedSubject( new SubjectImpl(userName, userId, token, false), permissionChecker); EnvironmentContext.getCurrent().setSubject(authorizedSubject); chain.doFilter(addUserInRequest(httpRequest, authorizedSubject), response); } catch (NotFoundException ex) { sendErr( response, SC_UNAUTHORIZED, "Authentication with machine token failed because user for this token no longer exist."); } finally { EnvironmentContext.reset(); } } catch (NotMachineTokenJwtException ex) { chain.doFilter(request, response); } catch (ServerException | JwtException e) { sendErr( response, SC_UNAUTHORIZED, format("Authentication with machine token failed cause: %s", e.getMessage())); } }
Source:
<code>public void reload() { prepareConfigFile(); <START> if(process.getClass().getName().equals("java.lang.UNIXProcess")) { <END> try { Request.Post("http://localhost:8088/v1-catalog/templates?action=refresh").execute(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }</code><technical_language>This needed anymore</technical_language>

Target:
public void reload() { try { prepareConfigFile(); Request.Post("http://localhost:8088/v1-catalog/templates?action=refresh").execute(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public boolean canMatchTrace(ITmfTrace trace) { if (!(trace instanceof IKernelTrace)) { return false; } IKernelAnalysisEventLayout layout = ((IKernelTrace) trace).getKernelEventLayout(); TRACE_LAYOUTS.put(trace, layout); <START> Set<String> events = REQUIRED_EVENTS.computeIfAbsent(layout, k -> { <END> Set<String> eventsSet = new HashSet<>(); eventsSet.addAll(k.eventsNetworkSend()); eventsSet.addAll(k.eventsNetworkReceive()); return eventsSet; }); if (!(trace instanceof ITmfTraceWithPreDefinedEvents)) { return true; } ITmfTraceWithPreDefinedEvents ktrace = (ITmfTraceWithPreDefinedEvents) trace; Set<String> traceEvents = TmfEventTypeCollectionHelper.getEventNames(ktrace.getContainedEventTypes()); traceEvents.retainAll(events); return !traceEvents.isEmpty(); }</code><technical_language>more K</technical_language>

Target:
public boolean canMatchTrace(ITmfTrace trace) { if (!(trace instanceof IKernelTrace)) { return false; } IKernelAnalysisEventLayout layout = ((IKernelTrace) trace).getKernelEventLayout(); TRACE_LAYOUTS.put(trace, layout); Set<String> events = REQUIRED_EVENTS.computeIfAbsent(layout, eventLayout -> { Set<String> eventsSet = new HashSet<>(); eventsSet.addAll(eventLayout.eventsNetworkSend()); eventsSet.addAll(eventLayout.eventsNetworkReceive()); return eventsSet; }); if (!(trace instanceof ITmfTraceWithPreDefinedEvents)) { return true; } ITmfTraceWithPreDefinedEvents ktrace = (ITmfTraceWithPreDefinedEvents) trace; Set<String> traceEvents = TmfEventTypeCollectionHelper.getEventNames(ktrace.getContainedEventTypes()); traceEvents.retainAll(events); return !traceEvents.isEmpty(); }
Source:
<code>public StringFieldEditor(String name, String labelText, int width, int strategy, Composite parent) { <START> init(name, labelText); <END> widthInChars = width; setValidateStrategy(strategy); isValid = false; errorMessage = JFaceResources .getString("StringFieldEditor.errorMessage"); createControl(parent); }</code><technical_language>I suggest invoke this(name, labelText, wight, 1, strategy, parent) here</technical_language>

Target:
public StringFieldEditor(String name, String labelText, int width, int strategy, Composite parent) { this(name, labelText, width, 1, strategy, parent); }
Source:
<code>public void testStopSyncthingServiceBackground() { PreferenceManager.getDefaultSharedPreferences(mContext) .edit() .putBoolean(SyncthingService.PREF_ALWAYS_RUN_IN_BACKGROUND, true) .commit(); Intent intent = new Intent(new Intent(mContext, AppConfigReceiver.class)); intent.setAction(AppConfigReceiver.ACTION_STOP); try { mReceiver.onReceive(mContext, intent); <START> Assert.fail("Stop SyncthingService Background (1) - didn't fail to create the notification"); <END> } catch (NullPointerException e) { } }</code><technical_language>This message wrong, fail failed create notification, right? Also, need messages. If a test fails, get test case line logged, problem finding it. I a problem either. I include name of test case, duplicated info</technical_language>

Target:
public void testStopSyncthingServiceBackground() { PreferenceManager.getDefaultSharedPreferences(mContext) .edit() .putBoolean(SyncthingService.PREF_ALWAYS_RUN_IN_BACKGROUND, true) .commit(); Intent intent = new Intent(new Intent(mContext, AppConfigReceiver.class)); intent.setAction(AppConfigReceiver.ACTION_STOP); mReceiver.onReceive(mContext, intent); assertEquals("Stop SyncthingService Background", 0, mContext.getStopServiceIntents().size()); }
Source:
<code>public Object get(String column) { TupleOperation result = currentState.get( column ); if ( result == null ) { return snapshot.get( column ); } else if ( result.getType() == PUT_NULL || result.getType() == REMOVE ) { <START> return result; <END> } else { return result.getValue(); } }</code><technical_language>this return null ? If not, I this API return "Object" a meaning :)</technical_language>

Target:
public Object get(String column) { TupleOperation result = currentState.get( column ); if ( result == null ) { return snapshot.get( column ); } else if ( result.getType() == PUT_NULL || result.getType() == REMOVE ) { return null; } else { return result.getValue(); } }
Source:
<code>public void onConstruct(String enumName, int ordinal, int idIn, String nameIn, String suffixIn, Class <? extends WorldProvider > clazzIn, CallbackInfo ci) { <START> this.sanitizedId = this.getName().toLowerCase().replaceAll(" ", "_").replace("[^A-Za-z0-9_]", ""); <END> this.config = new SpongeConfig<>(SpongeConfig.Type.DIMENSION, SpongeImpl.getSpongeConfigDir().resolve("worlds").resolve(dimensionType$getId ()).resolve("dimension.conf"), SpongeImpl.ECOSYSTEM_ID); this.context = new Context(Context.DIMENSION_KEY, this.sanitizedId); }</code><technical_language>Single char replacements .replace(' ', '_'), I regex replace is working replace literal replacements, replaceAll is method supports regular expressions</technical_language>

Target:
public void onConstruct(String enumName, int ordinal, int idIn, String nameIn, String suffixIn, Class <? extends WorldProvider > clazzIn, CallbackInfo ci) { this.sanitizedId = this.getName().toLowerCase().replace(" ", "_").replaceAll("[^A-Za-z0-9_]", ""); this.config = new SpongeConfig<>(SpongeConfig.Type.DIMENSION, SpongeImpl.getSpongeConfigDir().resolve("worlds").resolve(dimensionType$getId ()).resolve("dimension.conf"), SpongeImpl.ECOSYSTEM_ID); this.context = new Context(Context.DIMENSION_KEY, this.sanitizedId); }
Source:
<code>private HystrixConcurrencyStrategy detectRegisteredConcurrencyStrategy() { HystrixConcurrencyStrategy registeredStrategy = HystrixPlugins.getInstance() .getConcurrencyStrategy(); if (existingConcurrencyStrategy == null) { return registeredStrategy; } if (registeredStrategy instanceof HystrixConcurrencyStrategyDefault){ return existingConcurrencyStrategy; } <START> if (!existingConcurrencyStrategy.equals(registeredStrategy)){ <END> throw new IllegalStateException("Multiple HystrixConcurrencyStrategy detected."); } return existingConcurrencyStrategy; }</code><technical_language>throw exception in this case? I fine return existingConcurrencyStrategy</technical_language>

Target:
private HystrixConcurrencyStrategy detectRegisteredConcurrencyStrategy() { HystrixConcurrencyStrategy registeredStrategy = HystrixPlugins.getInstance() .getConcurrencyStrategy(); if (existingConcurrencyStrategy == null) { return registeredStrategy; } if (registeredStrategy instanceof HystrixConcurrencyStrategyDefault){ return existingConcurrencyStrategy; } if (!existingConcurrencyStrategy.equals(registeredStrategy)){ LOGGER.warn("Multiple HystrixConcurrencyStrategy detected. Bean of HystrixConcurrencyStrategy was used."); } return existingConcurrencyStrategy; }
Source:
<code>String value() { String s = value; if ( s == null ) { synchronized ( this ) { s = value; if ( s == null ) { <START> s = value = new String( bytes, offset, length, StandardCharsets.UTF_8 ); <END> } } } return s; }</code><technical_language>I typically write = s = ... - matters, order more another volatile load</technical_language>

Target:
String value() { String s = value; if ( s == null ) { synchronized ( this ) { s = value; if ( s == null ) { value = s = new String( bytes, offset, byteLength, StandardCharsets.UTF_8 ); } } } return s; }
Source:
<code>protected Node getSequencedNode( Node parentNode, String relativePath, int waitTimeSeconds) throws Exception { String parentNodePath = parentNode.getPath(); String expectedPath = parentNodePath.endsWith( "/") ? parentNodePath + relativePath : parentNodePath + "/" + relativePath; if (!sequencedNodes.containsKey(expectedPath)) { <START> if (!waitingLatches.containsKey(expectedPath)) { <END> createWaitingLatch(expectedPath); } logger.debug("Waiting for sequenced node at: " + expectedPath); waitingLatches.get(expectedPath).await(waitTimeSeconds, TimeUnit.SECONDS); } waitingLatches.remove(expectedPath); return sequencedNodes.remove(expectedPath); }</code><technical_language>This if check is necessary, createWaitingLatch(...) create latch if is there</technical_language>

Target:
protected Node getSequencedNode( Node parentNode, String relativePath, int waitTimeSeconds) throws Exception { String parentNodePath = parentNode.getPath(); String expectedPath = parentNodePath.endsWith( "/") ? parentNodePath + relativePath : parentNodePath + "/" + relativePath; if (!sequencedNodes.containsKey(expectedPath)) { createWaitingLatchIfNecessary(expectedPath); logger.debug("Waiting for sequenced node at: " + expectedPath); waitingLatches.get(expectedPath).await(waitTimeSeconds, TimeUnit.SECONDS); } waitingLatches.remove(expectedPath); return sequencedNodes.remove(expectedPath); }
Source:
<code>private Set<IContainer> getIgnoredReferencePointParents( Set<IReferencePoint> referencePoints, Set<IContainer> referencePointParents) { Set<IContainer> referencePointDelegates = referencePoints.stream().map(ResourceConverter::getDelegate).collect(Collectors.toSet()); List<IContainer> sortedReferencePointParents = new ArrayList<>(referencePointParents); <START> sortedReferencePointParents.sort( (c1, c2) -> { IPath path1 = c1.getFullPath(); IPath path2 = c2.getFullPath(); return -1 * Integer.compare(path1.segmentCount(), path2.segmentCount()); }); <END> Set<IContainer> containersWithoutSharableChildren = new HashSet<>(); Set<IContainer> containersWithSharableChildren = new HashSet<>(); for (IContainer referencePointParent : sortedReferencePointParents) { IResource[] children; try { children = referencePointParent.members(); } catch (CoreException e) { log.error("Could not obtain members of container " + referencePointParent, e); continue; } boolean hasSharableChildren = false; for (IResource child : children) { if (!(child instanceof IContainer)) { continue; } if (containersWithSharableChildren.contains(child) || (!referencePointParents.contains(child) && !referencePointDelegates.contains(child))) { hasSharableChildren = true; break; } } if (hasSharableChildren) { containersWithSharableChildren.add(referencePointParent); } else { containersWithoutSharableChildren.add(referencePointParent); } } return containersWithoutSharableChildren; }</code><technical_language>suggestion: suggestion sortedReferencePointParents.sort( Comparator.comparingInt((IContainer c) -> c.getFullPath().segmentCount()).reversed());</technical_language>

Target:
private Set<IContainer> getIgnoredReferencePointParents( Set<IReferencePoint> referencePoints, Set<IContainer> referencePointParents) { Set<IContainer> referencePointDelegates = referencePoints.stream().map(ResourceConverter::getDelegate).collect(Collectors.toSet()); List<IContainer> sortedReferencePointParents = new ArrayList<>(referencePointParents); sortedReferencePointParents.sort( Comparator.comparingInt((IContainer c) -> c.getFullPath().segmentCount()).reversed()); Set<IContainer> containersWithoutSharableChildren = new HashSet<>(); Set<IContainer> containersWithSharableChildren = new HashSet<>(); for (IContainer referencePointParent : sortedReferencePointParents) { IResource[] children; try { children = referencePointParent.members(); } catch (CoreException e) { log.error("Could not obtain members of container " + referencePointParent, e); continue; } boolean hasSharableChildren = false; for (IResource child : children) { if (!(child instanceof IContainer)) { continue; } if (containersWithSharableChildren.contains(child) || (!referencePointParents.contains(child) && !referencePointDelegates.contains(child))) { hasSharableChildren = true; break; } } if (hasSharableChildren) { containersWithSharableChildren.add(referencePointParent); } else { containersWithoutSharableChildren.add(referencePointParent); } } return containersWithoutSharableChildren; }
Source:
<code>private Mono<CosmosPermissionResponse> readInternal(CosmosPermissionRequestOptions options, Context context) { String spanName = "readPermission." + cosmosUser.getId(); Mono<CosmosPermissionResponse> responseMono = readInternal(options); return cosmosUser.getDatabase().getClient().getTracerProvider().traceEnabledCosmosResponsePublisher(responseMono, context, <START> spanName, <END> cosmosUser.getDatabase().getId(), cosmosUser.getDatabase().getClient().getServiceEndpoint()); }</code><technical_language>Readability is concern here, lets is</technical_language>

Target:
private Mono<CosmosPermissionResponse> readInternal(CosmosPermissionRequestOptions options, Context context) { String spanName = "readPermission." + cosmosUser.getId(); Mono<CosmosPermissionResponse> responseMono = cosmosUser.getDatabase() .getDocClientWrapper() .readPermission(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosPermissionResponse(response)) .single(); return cosmosUser.getDatabase().getClient().getTracerProvider().traceEnabledCosmosResponsePublisher(responseMono, context, spanName, cosmosUser.getDatabase().getId(), cosmosUser.getDatabase().getClient().getServiceEndpoint()); }
Source:
<code>private void updateCustomizedStates(String instanceName, String customizedStateType, Map<String, CustomizedState> customizedStates, CustomizedStateOutput customizedStateOutput, Map<String, Resource> resourceMap) { for (CustomizedState customizedState : customizedStates.values()) { String resourceName = customizedState.getResourceName(); Resource resource = resourceMap.get(resourceName); if (resource == null) { continue; } Map<String, String> partitionStateMap = customizedState .getPartitionStateMap(CustomizedState.CustomizedStateProperty.CURRENT_STATE); for (String partitionName : partitionStateMap.keySet()) { Partition partition = resource.getPartition(partitionName); if (partition != null) { customizedStateOutput .setCustomizedState(customizedStateType, resourceName, partition, instanceName, customizedState.getState(partitionName)); <START> customizedStateOutput <END> .setStartTime(customizedStateType, resourceName, partition, instanceName, String.valueOf(customizedState.getStartTime(partitionName))); } } } }</code><technical_language>simpler if set start time setCustomizedState()? other cases want update state touch start time? This reduce duplicate code</technical_language>

Target:
private void updateCustomizedStates(String instanceName, String customizedStateType, Map<String, CustomizedState> customizedStates, CustomizedStateOutput customizedStateOutput, Map<String, Resource> resourceMap) { for (CustomizedState customizedState : customizedStates.values()) { String resourceName = customizedState.getResourceName(); Resource resource = resourceMap.get(resourceName); if (resource == null) { continue; } Map<String, String> partitionStateMap = customizedState .getPartitionStateMap(CustomizedState.CustomizedStateProperty.CURRENT_STATE); for (String partitionName : partitionStateMap.keySet()) { Partition partition = resource.getPartition(partitionName); if (partition != null) { customizedStateOutput .setCustomizedState(customizedStateType, resourceName, partition, instanceName, customizedState.getState(partitionName), customizedState.getStartTime(partitionName)); } } } }
Source:
<code>static <E> TList<E> createList(E... elements) { if (elements == null || elements.length == 0) { return TCollections.emptyList(); } <START> final TList<E> list = new TArrayList<>(); <END> for (E element : elements) { list.add(requireNonNull(element, "element")); } return TCollections.unmodifiableList(list); }</code><technical_language>I this approach: 1. objects created instead of (i.e. ArrayList UnmodifiableList) 2. create a temporary array for passing varargs, if original List.of varargs 3. rely ArrayList allocate extra space in order improve add performance, is required in immutable list</technical_language>

Target:
static <E> TList<E> createList(E... elements) { if (elements.length == 0) { return TCollections.emptyList(); } for (E element : elements) { requireNonNull(element, "element"); } return new ImmutableArrayList<>(elements); }
Source:
<code>public void should_not_loose_InnerClasses_attribute() throws Exception { final ClassWriter cw = new ClassWriter(0); final ClassReader cr = new ClassReader(Java9Support.downgradeIfRequired( TargetLoader.getClassDataAsBytes(Inner.class))); cr.accept(new ClassVisitor(InstrSupport.ASM_API_VERSION, cw) { @Override public void visitEnd() { final MethodVisitor mv = cv.visitMethod(0, "m", "()V", null, null); mv.visitCode(); addCauseOfResizeInstructions(mv); mv.visitMaxs(2, 1); mv.visitEnd(); super.visitEnd(); } }, 0); final byte[] bytes = instrumenter.instrument(cw.toByteArray(), ""); final TargetLoader targetLoader = new TargetLoader(); <START> final Class outer = targetLoader.add(ResizeInstructionsTest.class, <END> TargetLoader.getClassDataAsBytes(ResizeInstructionsTest.class)); final Class inner = targetLoader.add(Inner.class, bytes); assertNotSame(outer, inner.getEnclosingClass()); assertNull(inner.getEnclosingClass()); assertNotSame(outer, inner.getDeclaringClass()); assertNull(inner.getDeclaringClass()); }</code><technical_language>@Godin Raw Class types give a compiler warning, Class<?> fixes issue</technical_language>

Target:
public void should_not_loose_InnerClasses_attribute() throws Exception { final ClassWriter cw = new ClassWriter(0); final ClassReader cr = new ClassReader(Java9Support.downgradeIfRequired( TargetLoader.getClassDataAsBytes(Inner.class))); cr.accept(new ClassVisitor(InstrSupport.ASM_API_VERSION, cw) { @Override public void visitEnd() { final MethodVisitor mv = cv.visitMethod(0, "m", "()V", null, null); mv.visitCode(); addCauseOfResizeInstructions(mv); mv.visitMaxs(2, 1); mv.visitEnd(); super.visitEnd(); } }, 0); final byte[] bytes = instrumenter.instrument(cw.toByteArray(), ""); final TargetLoader targetLoader = new TargetLoader(); final Class<?> outer = targetLoader.add(ResizeInstructionsTest.class, TargetLoader.getClassDataAsBytes(ResizeInstructionsTest.class)); final Class<?> inner = targetLoader.add(Inner.class, bytes); assertNotSame(outer, inner.getEnclosingClass()); assertNull(inner.getEnclosingClass()); assertNotSame(outer, inner.getDeclaringClass()); assertNull(inner.getDeclaringClass()); }
Source:
<code>private void restoreRoots(File buRoot, Set<File> unrestorable) { File[] children = buRoot.listFiles(); if (children == null) { unrestorable.add(buRoot); return; } for (File <START> children1 : <END> children) { String name = children1.getName(); String rName = name; String prefix = ""; while (rName.startsWith(ROOTCHAR)) { prefix += File.separator; rName = rName.substring(1); } if (prefix.length() < 1) { rName = rName + ":" + File.separator; } else rName = prefix + rName; File bu = new File(buRoot, name); File target = new File(rName); if (!bu.isDirectory()) { unrestorable.add(bu); continue; } if (!(target.exists() && target.isDirectory())) { unrestorable.add(bu); continue; } restore(target, bu, unrestorable); } restoreRenamedFiles(unrestorable); }</code><technical_language>child</technical_language>

Target:
private void restoreRoots(File buRoot, Set<File> unrestorable) { File[] children = buRoot.listFiles(); if (children == null) { unrestorable.add(buRoot); return; } for (File child : children) { String name = child.getName(); String rName = name; String prefix = ""; while (rName.startsWith(ROOTCHAR)) { prefix += File.separator; rName = rName.substring(1); } if (prefix.length() < 1) { rName = rName + ":" + File.separator; } else rName = prefix + rName; File bu = new File(buRoot, name); File target = new File(rName); if (!bu.isDirectory()) { unrestorable.add(bu); continue; } if (!(target.exists() && target.isDirectory())) { unrestorable.add(bu); continue; } restore(target, bu, unrestorable); } restoreRenamedFiles(unrestorable); }
Source:
<code>public void addUmiObservation(String observedUmi, String inferredUmi) { observedUmis.increment(observedUmi); inferredUmis.increment(inferredUmi); observedUmiBases += observedUmi.length(); totalObservedUmis++; <START> <END> }</code><technical_language>white space</technical_language>

Target:
public void addUmiObservation(String observedUmi, String inferredUmi) { observedUmis.increment(observedUmi); inferredUmis.increment(inferredUmi); observedUmiBases += observedUmi.length(); totalObservedUmisWithoutNs++; }
Source:
<code>public void execute() { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow window = workbench .getActiveWorkbenchWindow(); <START> if (window == null) { <END> return; } IWorkbenchPage activePage = window.getActivePage(); if (activePage != null) { activePage.setPerspective(descriptor); } else { try { window.openPage(descriptor.getId(), ((Workbench) workbench) .getDefaultPageInput()); } catch (WorkbenchException e) { IStatus errorStatus = WorkbenchPlugin.newError(NLS.bind( WorkbenchMessages.Workbench_showPerspectiveError, descriptor.getLabel()), e); StatusManager.getManager().handle(errorStatus, StatusManager.SHOW); } } }</code><technical_language>I Assert.isNotNull(window) here</technical_language>

Target:
public void execute() { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow window = workbench .getActiveWorkbenchWindow(); Assert.isNotNull(window); IWorkbenchPage activePage = window.getActivePage(); if (activePage != null) { activePage.setPerspective(descriptor); } else { try { window.openPage(descriptor.getId(), ((Workbench) workbench) .getDefaultPageInput()); } catch (WorkbenchException e) { IStatus errorStatus = WorkbenchPlugin.newError(NLS.bind( WorkbenchMessages.Workbench_showPerspectiveError, descriptor.getLabel()), e); StatusManager.getManager().handle(errorStatus, StatusManager.SHOW); } } }
Source:
<code>public String getTaskIdFromTaskUrl(String url) { if (url == null) { return null; } int index = url.indexOf(CHANGE_PREFIX_OLD); if (index > 0) { return url.substring(index + CHANGE_PREFIX_OLD.length()); } <START> index = url.indexOf(CHANGE_PREFIX_NEW); <END> if (index > 0) { Matcher matcher = CHANGE_ID_PATTERN.matcher(url.substring(index)); if (matcher.find()) { return matcher.group(1); } } return null; }</code><technical_language>change pattern "(/#change,|/#/c/)(\\d+)" group(2) eliminate 4 lines of code above</technical_language>

Target:
public String getTaskIdFromTaskUrl(String url) { if (url == null) { return null; } Matcher matcher = CHANGE_ID_PATTERN.matcher(url); if (matcher.find()) { return matcher.group(2); } return null; }
Source:
<code>public Page buildDictionaryPage(int[] indices, PageBuilder sourcePageBuilder) { int[] outputChannels = new int[probeOutputChannels.size()]; for (int i = 0; i < outputChannels.length; i++) { <START> outputChannels[i] = probeOutputChannels.get(i); <END> } return internalBuildDictionaryPage(indices, outputChannels, sourcePageBuilder); }</code><technical_language>copy list array with: int[] outputChannels = probeOutputChannels.stream() .mapToInt(i -> i) .toArray(); (if pass probeOutputChannels reference, ensuring immutability in ctor first)</technical_language>

Target:
public Page buildDictionaryPage(int[] indices, PageBuilder sourcePageBuilder) { return internalBuildDictionaryPage(indices, probeOutputChannels.stream().mapToInt(i -> i).toArray(), sourcePageBuilder); }
Source:
<code>public InstrumentationContext<List<ValidationError>> beginValidation(InstrumentationValidationParameters parameters) { return whenCompleted((errors, throwable) -> { if ((errors != null && errors.size() > 0) || throwable != null) { return; } QueryTraversal queryTraversal = newQueryTraversal(parameters); int depth = queryTraversal.reducePreOrder((env, acc) -> Math.max(getPathLength(env.getParentEnvironment()), acc), 0); log.debug("Query depth: {}", depth); if (depth > maxDepth) { if (abortExecution) { throw mkAbortException(depth, maxDepth); } else { log.warn("Maximum query depth exceeded > {}", depth, maxDepth); } } }); <START> } <END></code><technical_language>thinking more this. logging if want do some other action a Function<Boolean,ComplexityInfo returns true if abort exception throw say. of a function allow people do do other log call statsd react in some other manner. ComplexityInfo is a builder built object contains complexity count. Passing int means add more "parameters" a time prefer wrapper objects builders</technical_language>

Target:
public InstrumentationContext<List<ValidationError>> beginValidation(InstrumentationValidationParameters parameters) { return whenCompleted((errors, throwable) -> { if ((errors != null && errors.size() > 0) || throwable != null) { return; } QueryTraversal queryTraversal = newQueryTraversal(parameters); int depth = queryTraversal.reducePreOrder((env, acc) -> Math.max(getPathLength(env.getParentEnvironment()), acc), 0); log.debug("Query depth info: {}", depth); if (depth > maxDepth) { QueryDepthInfo queryDepthInfo = QueryDepthInfo.newQueryDepthInfo() .depth(depth) .build(); boolean throwAbortException = maxQueryDepthExceededFunction.apply(queryDepthInfo); if (throwAbortException) { throw mkAbortException(depth, maxDepth); } } }); }
Source:
<code>public void handleMessageLog(TelemetryMessageLogDTO messageLog) { LOG.debug("Received telemetry messages", messageLog.getMessages().size()); for (TelemetryMessageDTO eachMessage : messageLog.getMessages()) { LOG.debug("Parse log message {}", eachMessage); <START> final NetflowPackage flowPackage = new NetflowPackage(eachMessage.getBytes()); <END> if (flowPackage.getVersion() != NetflowPackage.VERSION) { LOG.warn("Invalid Version. Expected {}, received {}. Skipping flow package.", NetflowPackage.VERSION, flowPackage.getVersion()); continue; } if (flowPackage.getHeader().getCount() == 0) { LOG.warn("Received Package has no content. Skipping flow package."); continue; } if (!flowPackage.isValid()) { LOG.warn("Received Package is not valid. Skipping flow package."); continue; } LOG.debug("FlowPackage received: {}", flowPackage); } }</code><technical_language>Package Packet</technical_language>

Target:
public void handleMessageLog(TelemetryMessageLogDTO messageLog) { LOG.debug("Received telemetry messages", messageLog.getMessages().size()); for (TelemetryMessageDTO eachMessage : messageLog.getMessages()) { LOG.debug("Parse log message {}", eachMessage); try { final NetflowPacket flowPacket = new NetflowPacket(eachMessage.getBytes()); if (flowPacket.getVersion() != NetflowPacket.VERSION) { LOG.warn("Invalid Version. Expected {}, received {}. Skipping flow packet.", NetflowPacket.VERSION, flowPacket.getVersion()); continue; } if (flowPacket.getCount() == 0) { LOG.warn("Received packet has no content. Skipping flow packet."); continue; } if (!flowPacket.isValid()) { LOG.warn("Received packet is not valid. Skipping flow packet."); continue; } LOG.debug("Flow packet received: {}", flowPacket); } catch (Exception e) { LOG.error("Received packet cannot be read.", e); } } }
Source:
<code><START> for (WeaponType type : WeaponType.values()) { <END> ELF_ARSENAL.put(type, new ElfWeapon(type)); }</code><technical_language>Java 11 local variable type inference (var)</technical_language>

Target:
for (WeaponType type : WeaponType.values()) { ELFARSENAL.put(type, new ElfWeapon(type)); }
Source:
<code>public Map<Class<?>, Object> build(KieServicesConfiguration configuration, ClassLoader classLoader) { <START> final Map<Class<?>, Object> services = new HashMap<>(); <END> services.put(TaskAssigningRuntimeClient.class, new TaskAssigningRuntimeClientImpl(configuration, classLoader)); return services; }</code><technical_language>I Collections.singletonMap()</technical_language>

Target:
public Map<Class<?>, Object> build(KieServicesConfiguration configuration, ClassLoader classLoader) { return Collections.singletonMap(TaskAssigningRuntimeClient.class, new TaskAssigningRuntimeClientImpl(configuration, classLoader)); }
Source:
<code>pathname -> pathname.isFile() && pathname.getName().startsWith(RESERVE_FILE_PREFIX); private static final FileFilter FILE_SIZE_DIR_FILTER = pathname -> pathname.isDirectory() && getFileSizeForDirName(pathname.getName()) != null; private final File reserveDir; private final long requiredSwapSegmentsPerSize; private final StorageManagerMetrics metrics; private ReserveFileMap reserveFiles; private PoolState poolState = PoolState.NOT_INVENTORIED; DiskSpaceAllocator(File reserveDir, long requiredSwapSegmentsPerSize, StorageManagerMetrics metrics) { this.reserveDir = reserveDir; this.requiredSwapSegmentsPerSize = requiredSwapSegmentsPerSize; this.metrics = metrics; try { if (reserveDir.isDirectory()) { reserveFiles = inventoryExistingReserveFiles(); poolState = PoolState.INVENTORIED; } } catch (Exception e) { <START> logger.error("Could not inventory preexisting reserve directory", e); <END> } }</code><technical_language>this exception swallow</technical_language>

Target:
pathname -> pathname.isFile() && pathname.getName().startsWith(RESERVE_FILE_PREFIX); private static final FileFilter FILE_SIZE_DIR_FILTER = pathname -> pathname.isDirectory() && getFileSizeForDirName(pathname.getName()) != null; private final boolean enablePooling; private final File reserveDir; private final long requiredSwapSegmentsPerSize; private final StorageManagerMetrics metrics; private final ReserveFileMap reserveFiles = new ReserveFileMap(); private PoolState poolState = PoolState.NOT_INVENTORIED; private Exception inventoryException = null; DiskSpaceAllocator(boolean enablePooling, File reserveDir, long requiredSwapSegmentsPerSize, StorageManagerMetrics metrics) { this.enablePooling = enablePooling; this.reserveDir = reserveDir; this.requiredSwapSegmentsPerSize = requiredSwapSegmentsPerSize; this.metrics = metrics; try { if (enablePooling) { prepareDirectory(reserveDir); inventoryExistingReserveFiles(); poolState = PoolState.INVENTORIED; } } catch (Exception e) { inventoryException = e; logger.error("Could not inventory preexisting reserve directory", e); } }
Source:
<code>public Map getActivityChristmasInvestAmountAndCount(){ List<InvestModel> investModels = investMapper.countSuccessInvestByInvestTime(null, activityChristmasStartTime, activityChristmasEndTime); Map<String,Object> param = Maps.newConcurrentMap(); long amount = 0l; long count = 0l; <START> Map<String,String> userMap = Maps.newConcurrentMap(); <END> for(InvestModel investModel : investModels){ LoanDetailsModel loanDetailsModel = loanDetailsMapper.getByLoanId(investModel.getLoanId()); if(loanDetailsModel != null && loanDetailsModel.isActivity() && loanDetailsModel.getActivityDesc().equals("圣诞专享")){ amount += investModel.getAmount(); if(userMap.get(investModel.getLoginName()) == null){ userMap.put(investModel.getLoginName(),investModel.getLoginName()); count ++; } } } param.put("investAmount",amount); param.put("investCount",count); return param; }</code><technical_language>set</technical_language>

Target:
public Map getActivityChristmasInvestAmountAndCount(){ List<InvestModel> investModels = investMapper.countSuccessInvestByInvestTime(null, activityChristmasStartTime, activityChristmasEndTime); Map<String,Object> param = Maps.newConcurrentMap(); long amount = 0l; Set userSet = new HashSet(); for(InvestModel investModel : investModels){ LoanDetailsModel loanDetailsModel = loanDetailsMapper.getByLoanId(investModel.getLoanId()); if(loanDetailsModel != null && loanDetailsModel.isActivity() && loanDetailsModel.getActivityDesc().equals("圣诞专享")){ amount += investModel.getAmount(); userSet.add(investModel.getLoginName()); } } param.put("investAmount",amount); param.put("investCount",userSet.size()); return param; }
Source:
<code>public void testSnapshotDroplet() { int powerOffEvent = api.getDropletApi().powerOff(droplet.getId()); assertTrue(powerOffEvent > 0, "The event id should not be null"); waitForEvent(powerOffEvent); int event = api.getDropletApi().snapshot(droplet.getId(), "testsnapshot"); assertTrue(event > 0, "The event id should not be null"); waitForEvent(event); Optional<Image> snapshot = tryFind(api.getImageApi().list(), new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getName().equals("testsnapshot"); } }); assertTrue(snapshot.isPresent(), "The created snapshot should exist in the image list"); <START> api.getImageApi().delete(snapshot.get().getId()); <END> }</code><technical_language>Guess want this happen test succeeds fails? Put in AfterClass block</technical_language>

Target:
public void testSnapshotDroplet() { int powerOffEvent = api.getDropletApi().powerOff(droplet.getId()); assertTrue(powerOffEvent > 0, "The event id should be > 0"); waitForEvent(powerOffEvent); int event = api.getDropletApi().snapshot(droplet.getId(), "testsnapshot"); assertTrue(event > 0, "The event id should be > 0"); waitForEvent(event); Optional<Image> snapshot = tryFind(api.getImageApi().list(), new Predicate<Image>() { @Override public boolean apply(Image input) { return input.getName().equals("testsnapshot"); } }); assertTrue(snapshot.isPresent(), "The created snapshot should exist in the image list"); this.snapshot = snapshot.get(); }
Source:
<code>public boolean commitRequired() { <START> return !dirtyChunks.isEmpty() || !positions.isEmpty(); <END> }</code><technical_language>forget include enabled in this check, others -- in case</technical_language>

Target:
public boolean commitRequired() { return enabled || postEditSimulation; }
Source:
<code>protected boolean isUserAuthorizedToRunAction() { <START> log.debug("IsUserAutorizedToRunAction: login on behalf - no permission check"); <END> return true; }</code><technical_language>start 'isUse...' (lower i)</technical_language>

Target:
protected boolean isUserAuthorizedToRunAction() { log.debug("isUserAuthorizedToRunAction: login on behalf - no permission check"); return true; }
Source:
<code>public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && isSheetShowing()) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null) { state.startTracking(event, this); } return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null) { state.handleUpEvent(event); } if (event.isTracking() && !event.isCanceled()) { if (isSheetShowing()) { if (getState() == BottomSheetLayout.State.EXPANDED) { <START> peekSheet(); <END> } else { dismissSheet(); } } return true; } } } return super.onKeyPreIme(keyCode, event); }</code><technical_language>I do want bring this again. In case bottom sheet for sharing. If press want completely cancel share (what default share sheet lollipop does). If this is hard-coded peek instead of dismiss, vary hard change</technical_language>

Target:
public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && isSheetShowing()) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null) { state.startTracking(event, this); } return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { KeyEvent.DispatcherState dispatcherState = getKeyDispatcherState(); if (dispatcherState != null) { dispatcherState.handleUpEvent(event); } if (isSheetShowing() && event.isTracking() && !event.isCanceled()) { if (state == State.EXPANDED && dismissMode == State.PEEKED) { peekSheet(); } else { dismissSheet(); } return true; } } } return super.onKeyPreIme(keyCode, event); }
Source:
<code>private boolean checkCurrentNetworkAsCaptivePortal() { String captivePortalURL = "<LINK_0>"; CommCareNetworkService commCareNetworkService = CommCareNetworkServiceGenerator.createNoAuthCommCareNetworkService(); try { Response<ResponseBody> response = commCareNetworkService.makeGetRequest(captivePortalURL, new HashMap<>(), new HashMap<>()).execute(); <START> Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Detecting captive portal, Response Code: " <END> + response.code() + " and Response Body: " + response.body()); return response.code() == 200 && !"success".equals(response.body().string()); } catch (IOException e) { Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Detecting captive portal failed with exception" + e.getMessage()); return false; } }</code><technical_language>I remove log catchers of CaptivePortalRedirectException log in individual processes</technical_language>

Target:
private boolean checkCurrentNetworkAsCaptivePortal() { String captivePortalURL = "<LINK_0>"; CommCareNetworkService commCareNetworkService = CommCareNetworkServiceGenerator.createNoAuthCommCareNetworkService(); try { Response<ResponseBody> response = commCareNetworkService.makeGetRequest(captivePortalURL, new HashMap<>(), new HashMap<>()).execute(); return response.code() == 200 && !"success".equals(response.body().string()); } catch (IOException e) { Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Detecting captive portal failed with exception" + e.getMessage()); return false; } }
Source:
<code><START> public LRUCache(int cacheSize) { <END> this.cacheSize = cacheSize; }</code><technical_language>This constructor insertion order, instead of access order. for cache entries queried entries get ejected if inserted long time ago, cache capacity is full. I curious, trade decide insertion order, instead of access order? improvement is in ResponseCache.get, a cache hit, remove entry re-put entry, queried order date</technical_language>

Target:
LRUCache(int cacheSize) { super(cacheSize/4); this.cacheSize = cacheSize; }
Source:
<code>public DFUFileDetailInfo getFileDetails(String logicalname, String clustername) throws Exception { try { DFUInfoResponse resp = this.getFileInfo(logicalname, clustername); if (resp == null) { throw new FileNotFoundException(logicalname + " does not exist"); } this.handleException(resp.getExceptions()); DFUFileDetailInfo info = new DFUFileDetailInfo(resp.getFileDetail()); try { <START> info.setFirstline(this.getFirstRow(logicalname, clustername)); <END> } catch (Exception e) { info.setFirstline(""); } if (info.getFilename() != null) { try { info.setColumns(getFileMetaData(logicalname, clustername)); } catch (ArrayOfEspException e) { if (e.getException().length > 0 && e.getException(0).getMessage() != null && e.getException(0).getMessage().contains("not available in service WsDfu")) { info.setColumns(this.getFileDataColumns(logicalname, clustername)); } } } if ((info.getEcl() == null || info.getEcl().isEmpty()) && info.getIsSuperfile() && info.getSubfiles() != null && info.getSubfiles().length != 0) { DFUFileDetailInfo subfile = this.getFileDetails(info.getSubfiles()[0], info.getCluster()); if (subfile != null) { info.setEcl(subfile.getEcl()); } } return info; } catch (ArrayOfEspException e) { if (e != null) { for (EspException espexception : e.getException()) { Utils.println(System.out, "Error retrieving file type for file" + logicalname + ": " + espexception.getSource() + espexception.getMessage(), false, true); } } throw e; } }</code><technical_language>stored in "first line"</technical_language>

Target:
public DFUFileDetailInfo getFileDetails(String logicalname, String clustername) throws Exception { try { DFUInfoResponse resp = this.getFileInfo(logicalname, clustername); if (resp == null) { throw new FileNotFoundException(logicalname + " does not exist"); } this.handleException(resp.getExceptions()); DFUFileDetailInfo info = new DFUFileDetailInfo(resp.getFileDetail()); try { info.setFirstline(this.getFirstRow(logicalname, clustername)); } catch (Exception e) { info.setFirstline(""); } if (info.getFilename() != null) { try { info.setColumns(getFileMetaData(logicalname, clustername)); } catch (ArrayOfEspException e) { if (e.getException().length > 0 && e.getException(0).getMessage() != null && e.getException(0).getMessage().contains("not available in service WsDfu")) { info.setColumns(this.getFileDataColumns(logicalname, clustername)); } } } if ((info.getEcl() == null || info.getEcl().isEmpty()) && info.getIsSuperfile() && info.getSubfiles() != null && info.getSubfiles().length != 0) { DFUFileDetailInfo subfile = this.getFileDetails(info.getSubfiles()[0], info.getCluster()); if (subfile != null) { info.setEcl(subfile.getEcl()); info.setColumns(subfile.getColumns()); info.setContentType(subfile.getContentType()); info.setFormat(subfile.getFormat()); } } return info; } catch (ArrayOfEspException e) { if (e != null) { for (EspException espexception : e.getException()) { Utils.println(System.out, "Error retrieving file type for file" + logicalname + ": " + espexception.getSource() + espexception.getMessage(), false, true); } } throw e; } }