auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public final void readURL(URLConnection url) throws IOException { DataInputStream in = new DataInputStream(url.getInputStream()); printHeader(url); try { while (true) { System.out.println((char) in.readUnsignedByte()); } } catch (EOFException e) { <START> LOGGER.error("EOF Exception while reading url : ",e); <END> } catch (IOException e) { LOGGER.error("IO Exception while reading url : ",e); } }</code><technical_language>put :, detail wrong this level (and include URL failed read). exception printed after</technical_language>

Target:
public final void readURL(URLConnection url) throws IOException { DataInputStream in = new DataInputStream(url.getInputStream()); printHeader(url); try { while (true) { System.out.println((char) in.readUnsignedByte()); } } catch (EOFException e) { LOGGER.error("EOF Exception while reading url, ", url.toString(), e); } catch (IOException e) { LOGGER.error("IO Exception while reading url, [{}]", url.toString(), e); } }
Source:
<code><START> public URL registerBlob (File blob) { <END> String key = blob.getName(); blobs.put(key, blob); URL url = null; try { url = new URL(protocol, host, port, path + "/" + key); } catch (Exception exception) { log.error("Can't generate URL for blob \"" + blob.getAbsolutePath() + "\".", exception); url = null; } if (url != null) { log.info("Registered URL \"" + url + "\" for blob \"" + blob.getAbsolutePath() + "\"."); } return url; }</code><technical_language>Based implementation of this file, BlobRegistry ServletUtils send file method I file path sanitized prevent directory traversal. I assume this is file path is coming a trusted source</technical_language>

Target:
public URL registerBlob (File blob) { String key = blob.getName(); blobs.put(key, blob); URL url = null; try { url = new URL(protocol, host, port, path + "/" + key); } catch (Exception exception) { log.error("Can't generate URL for blob \"" + blob.getAbsolutePath() + "\".", exception); url = null; } return url; }
Source:
<code>private void addHeaders(final HttpRequest httpRequest) throws IOException, SignatureException { final String date = DateFormatter.dateToRfc882(); httpRequest.addHeader(HOST, NetUtils.buildHostField(NetworkClientImpl.this.connectionDetails)); httpRequest.addHeader(DATE, date); httpRequest.addHeader(CONTENT_TYPE, this.ds3Request.getContentType().toString()); for(final Map.Entry<String, String> header: this.ds3Request.getHeaders().entrySet()) { httpRequest.addHeader(header.getKey(), header.getValue()); } <START> if (this.hash != "") { <END> httpRequest.addHeader("Content-MD5", this.hash); } httpRequest.addHeader(AUTHORIZATION, this.getSignature(new SignatureDetails( this.ds3Request.getVerb(), this.hash, this.ds3Request.getContentType().toString(), date, "", this.ds3Request.getPath(), NetworkClientImpl.this.connectionDetails.getCredentials() ))); }</code><technical_language>This evaluate true. comparing references instead of a string comparison. this.hash.equals("") preferably this.hash.isEmpty()</technical_language>

Target:
private void addHeaders(final HttpRequest httpRequest) throws IOException, SignatureException { final String date = DateFormatter.dateToRfc882(); httpRequest.addHeader(HOST, NetUtils.buildHostField(NetworkClientImpl.this.connectionDetails)); httpRequest.addHeader(DATE, date); httpRequest.addHeader(CONTENT_TYPE, this.ds3Request.getContentType().toString()); for(final Map.Entry<String, String> header: this.ds3Request.getHeaders().entrySet()) { httpRequest.addHeader(header.getKey(), header.getValue()); } if (!this.hash.isEmpty()) { httpRequest.addHeader(CONTENT_MD5, this.hash); } httpRequest.addHeader(AUTHORIZATION, this.getSignature(new SignatureDetails( this.ds3Request.getVerb(), this.hash, this.ds3Request.getContentType().toString(), date, "", this.ds3Request.getPath(), NetworkClientImpl.this.connectionDetails.getCredentials() ))); }
Source:
<code>public void testBlobExpired() throws Exception { initialize(false, "9"); ServerErrorCode[] serverErrorCodes = <START> {ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Expired}; <END> writeBlobRecordToServers(serverErrorCodes); blobRecordVerification(serverErrorCodes); future = router.deleteBlob(blobIdString, new UserCallback()); try { future.get(); fail(); } catch (Exception e) { assertEquals(RouterErrorCode.BlobExpired, ((RouterException) exception).getErrorCode()); } }</code><technical_language>this "ServerErrorCode.Blob_Expired"</technical_language>

Target:
public void testBlobExpired() throws Exception { ServerErrorCode[] serverErrorCodes = new ServerErrorCode[9]; Arrays.fill(serverErrorCodes, ServerErrorCode.Blob_Not_Found); serverErrorCodes[5] = ServerErrorCode.Blob_Expired; presetServerErrorCode(serverErrorCodes); future = router.deleteBlob(blobIdString, new ClientCallback()); try { future.get(); fail("Deletion should be unsuccessful. Error is expected."); } catch (Exception e) { assertEquals("RouterErrorCode should be BlobExpired", RouterErrorCode.BlobExpired, ((RouterException) e.getCause()).getErrorCode()); } }
Source:
<code>public <T> T api(Class<T> serviceInterface) { final ServiceCall serviceCall = this; final Map<Method, MethodInfo> genericReturnTypes = Reflect.methodsInfo(serviceInterface); return (T) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {serviceInterface}, (proxy, method, params) -> { final MethodInfo methodInfo = genericReturnTypes.get(method); final Class<?> returnType = methodInfo.parameterizedReturnType(); final boolean isServiceMessage = methodInfo.isRequestTypeServiceMessage(); Optional<Object> check = toStringOrEqualsOrHashCode(method.getName(), serviceInterface, params); if (check.isPresent()) { <START> return check.get(); END> } switch (methodInfo.communicationMode()) { case FIRE_AND_FORGET: return serviceCall.oneWay(toServiceMessage(methodInfo, params)); case REQUEST_RESPONSE: return serviceCall .requestOne(toServiceMessage(methodInfo, params), returnType) .transform(monoRespFn.apply(isServiceMessage)); case REQUEST_STREAM: return serviceCall .requestMany(toServiceMessage(methodInfo, params), returnType) .transform(fluxRespFn.apply(isServiceMessage)); case REQUEST_CHANNEL: return serviceCall .requestBidirectional( Flux.from((Publisher) params[0]) .map(data -> toServiceMessage(methodInfo, data)), returnType) .transform(fluxRespFn.apply(isServiceMessage)); default: throw new IllegalArgumentException( "Communication mode is not supported: " + method); } }); }</code><technical_language>) been, u meant</technical_language>

Target:
public <T> T api(Class<T> serviceInterface) { final ServiceCall serviceCall = this; final Map<Method, MethodInfo> genericReturnTypes = Reflect.methodsInfo(serviceInterface); return (T) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {serviceInterface}, (proxy, method, params) -> { final MethodInfo methodInfo = genericReturnTypes.get(method); final Class<?> returnType = methodInfo.parameterizedReturnType(); final boolean isServiceMessage = methodInfo.isRequestTypeServiceMessage(); Optional<Object> check = toStringOrEqualsOrHashCode(method.getName(), serviceInterface, params); if (check.isPresent()) { return check.get(); } switch (methodInfo.communicationMode()) { case FIRE_AND_FORGET: return serviceCall.oneWay(toServiceMessage(methodInfo, params)); case REQUEST_RESPONSE: return serviceCall .requestOne(toServiceMessage(methodInfo, params), returnType) .transform(asMono(isServiceMessage)); case REQUEST_STREAM: return serviceCall .requestMany(toServiceMessage(methodInfo, params), returnType) .transform(asFlux(isServiceMessage)); case REQUEST_CHANNEL: return serviceCall .requestBidirectional( Flux.from((Publisher) params[0]) .map(data -> toServiceMessage(methodInfo, data)), returnType) .transform(asFlux(isServiceMessage)); default: throw new IllegalArgumentException( "Communication mode is not supported: " + method); } }); }
Source:
<code>public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta incomingContainer : containers) { if (isInterestingContainer(incomingContainer)) { ITask task = (ITask) incomingContainer.getElement(); if (task != null) { <START> if (isArtifactCandidate(task)) { <END> setArtifactState(task, isArtifact(task)); } else { setArtifactState(task, false); } } } } }</code><technical_language>I methods: usesIssueTrackerWorfklow(), hasAssociatedTask(), hasTaskState() (meaning context dates). call setArtifactState(task, usesIssueTrackerWorfklow() && hasAssociatedTask() && !hasTaskState())</technical_language>

Target:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta incomingContainer : containers) { if (isInterestingContainer(incomingContainer)) { ITask task = (ITask) incomingContainer.getElement(); if (task != null) { setArtifactState(task, usesIssueTrackerWorkflow(task) && isArtifact(task)); } } } }
Source:
<code><START> public static SslContext newServerContext( <END> SslProvider provider, File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout, String keyStore) throws SSLException { try { return newServerContextInternal(provider, null, toX509Certificates(trustCertCollectionFile), trustManagerFactory, toX509Certificates(keyCertChainFile), toPrivateKey(keyFile, keyPassword), keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, ClientAuth.NONE, null, false, false, keyStore); } catch (Exception e) { if (e instanceof SSLException) { throw (SSLException) e; } throw new SSLException("failed to initialize the server-side SSL context", e); } }</code><technical_language>sense expose a protected method mark @Deprecated beginning. remove annotation package-private</technical_language>

Target:
static SslContext newServerContext( SslProvider provider, File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout, String keyStore) throws SSLException { try { return newServerContextInternal(provider, null, toX509Certificates(trustCertCollectionFile), trustManagerFactory, toX509Certificates(keyCertChainFile), toPrivateKey(keyFile, keyPassword), keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, ClientAuth.NONE, null, false, false, keyStore); } catch (Exception e) { if (e instanceof SSLException) { throw (SSLException) e; } throw new SSLException("failed to initialize the server-side SSL context", e); } }
Source:
<code>public void entriesExpire() { SlidingWindowWeightedMeanGauge expiringGauge = new SlidingWindowWeightedMeanGauge(Duration.ZERO); expiringGauge.update(100.0, 50); expiringGauge.update(50.0, 4); <START> assertThat(expiringGauge.getValue()).isCloseTo(0.0, withinPercentage(1)); <END> }</code><technical_language>reduce <1%? this a bit tighter</technical_language>

Target:
public void entriesExpire() { SlidingWindowWeightedMeanGauge expiringGauge = new SlidingWindowWeightedMeanGauge(Duration.ZERO); expiringGauge.update(100.0, 50); expiringGauge.update(50.0, 4); assertThat(expiringGauge.getValue()).isCloseTo(0.0, withinPercentage(0.1)); }
Source:
<code>public void processErrorWithChildContextAndHandledByParent() { Reference<EventContext> contextReference = new Reference<>(); InternalReactiveProcessor backPressureError = publisher -> from(publisher).map(in -> { throw propagateWrappingFatal(new FlowBackPressureMaxConcurrencyExceededException("flowName", MAX_CONCURRENCY_EXCEEDED)); }); <START> Flux.from(MessageProcessors.applyWithChildContext(Mono.just(input), createChain(backPressureError), Optional.empty(), <END> (exception, event) -> { contextReference .set(((MessagingException) exception).getEvent().getContext()); return null; })) .subscribe(); assertThat(contextReference.get(), notNullValue()); assertThat(contextReference.get(), is(not(input.getContext()))); BaseEventContext context = (BaseEventContext) contextReference.get(); assertThat(context.getParentContext().get(), is(input.getContext())); }</code><technical_language>static import</technical_language>

Target:
public void processErrorWithChildContextAndHandledByParent() { Reference<EventContext> contextReference = new Reference<>(); Reference<CoreEvent> eventReference = new Reference<>(); InternalReactiveProcessor backPressureError = publisher -> from(publisher).map(in -> { throw propagateWrappingFatal(new FlowBackPressureMaxConcurrencyExceededException("flowName", MAX_CONCURRENCY_EXCEEDED)); }); Flux.from(applyWithChildContext(just(input), createChain(backPressureError), Optional.empty(), (exception, event) -> { contextReference .set(((MessagingException) exception).getEvent().getContext()); eventReference .set(event); return event; })) .subscribe(); assertThat(contextReference.get(), notNullValue()); assertThat(contextReference.get(), is(not(input.getContext()))); BaseEventContext context = (BaseEventContext) contextReference.get(); assertThat(context.getParentContext().get(), is(input.getContext())); assertThat(context, is(eventReference.get().getContext())); }
Source:
<code>public List<String> getRequestIds() { List<String> request_ids = new ArrayList<String>(); try { Statement st = db.getConnection().createStatement(); ResultSet rs = st.executeQuery(ALL_REQUESTS_QUERY); while (rs.next()) { String id = rs.getString(1); request_ids.add(id); } } catch (SQLException ex) { LOGGER.error("failed to retrieve processes", ex); <START> } <END> return request_ids; }</code><technical_language>Clean in a finally</technical_language>

Target:
private List<String> getRequestIds() { Statement st = null; ResultSet rs = null; List<String> request_ids = new ArrayList<String>(); try { st = db.getConnection().createStatement(); rs = st.executeQuery(ALL_REQUESTS_QUERY); while (rs.next()) { String id = rs.getString(1); request_ids.add(id); } } catch (SQLException ex) { LOGGER.error("failed to retrieve processes", ex); } finally { closeResultSet(rs); closeStatement(st); } return request_ids; }
Source:
<code>public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.d(TAG, "onStartCommand"); <START> if (v1ToV2Migrator != null && !v1ToV2Migrator.isRunning()) { <END> executor.execute(new Runnable() { @Override public void run() { Log.d(TAG, "Begin Migration"); v1ToV2Migrator.migrate(); } }); } return START_STICKY; }</code><technical_language>v1ToV2Migrator null? .isRunning() private removed interface, call migrator if running do nothing. if a static executor, allows task a time, need check for this</technical_language>

Target:
public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.d(TAG, "onStartCommand"); executor.execute(new Runnable() { @Override public void run() { Migrator migrator = MigrationFactory.createVersionOneToVersionTwoMigrator( getApplicationContext(), getDatabasePath("downloads.db"), migrationCallback() ); Log.d(TAG, "Begin Migration: " + migrator.getClass()); migrator.migrate(); } }); return START_STICKY; }
Source:
<code>public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); onePhaseCommit = input.readBoolean(); retriedCommand = input.readBoolean(); <START> modifications = MarshallUtil.unmarshallArray(input, WriteCommand::array); <END> }</code><technical_language>prepare commands 0 modifications common</technical_language>

Target:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); onePhaseCommit = input.readBoolean(); retriedCommand = input.readBoolean(); modifications = MarshallUtil.unmarshallArray(input, WriteCommand[]::new); }
Source:
<code>private void writeDoc(String file) throws IOException { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(FlowStyle.BLOCK); options.setDefaultScalarStyle(ScalarStyle.LITERAL); Yaml yaml = new Yaml(options); Writer writer; if (Strings.isNullOrEmpty(file)) { <START> writer = new StringWriter(); <END> } else { writer = new OutputStreamWriter(new FileOutputStream(file), UTF_8); } try { Map<String, Map<String, Map<String, String>>> docs = docEntries.entrySet() .stream() .collect(Collectors.toMap( e -> e.getKey(), e -> e.getValue().entrySet() .stream() .collect(Collectors.toMap( e1 -> e1.getKey(), e1 -> e1.getValue().properties() )) )); yaml.dump(docs, writer); writer.flush(); if (writer instanceof StringWriter) { StringWriter sw = (StringWriter) writer; System.out.println(sw.toString()); } } finally { writer.close(); } }</code><technical_language>writer = System.out;</technical_language>

Target:
private void writeDoc(String file) throws IOException { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(FlowStyle.BLOCK); options.setDefaultScalarStyle(ScalarStyle.LITERAL); Yaml yaml = new Yaml(options); Writer writer; if (Strings.isNullOrEmpty(file)) { writer = new OutputStreamWriter(System.out, UTF_8); } else { writer = new OutputStreamWriter(new FileOutputStream(file), UTF_8); } try { Map<String, Map<String, Map<String, String>>> docs = docEntries.entrySet() .stream() .collect(Collectors.toMap( e -> e.getKey(), e -> e.getValue().entrySet() .stream() .collect(Collectors.toMap( e1 -> e1.getKey(), e1 -> e1.getValue().properties() )) )); yaml.dump(docs, writer); writer.flush(); } finally { writer.close(); } }
Source:
<code>public void test_update_by_id_with_subquery_returning_id() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = (select 1) returning id"); assertThat(printedTable(response.rows()), is("1\n" )); <START> refresh(); <END> }</code><technical_language>suggestion</technical_language>

Target:
public void test_update_by_id_with_subquery_returning_id() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = (select 1) returning id"); assertThat(printedTable(response.rows()), is("1\n" )); }
Source:
<code>public boolean processResponse(Intent intent, ODKView currentView, FormInstance instance, File destination) { if(intent == null){ return false; } String result = intent.getStringExtra(INTENT_RESULT_VALUE); ((ODKView) currentView).setBinaryData(result); Bundle response = intent.getBundleExtra(INTENT_RESULT_BUNDLE); if(responses != null) { for (String key : responses.keySet()) { if (!response.containsKey(key)) { continue; } String responseValue = response.getString(key); if (key == null) { key = ""; } <START> for (TreeReference ref : responses.get(key)) { <END> EvaluationContext context = new EvaluationContext(form.getEvaluationContext(), ref); AbstractTreeElement node = context.resolveReference(ref); if (node == null) { continue; } int dataType = node.getDataType(); if (dataType == Constants.DATATYPE_BINARY) { if (responseValue == null || responseValue.equals("")) { form.setValue(null, ref); continue; } File src = new File(responseValue); if (!src.exists()) { Log.w(TAG, "ODK received a link to a file at " + src.toString() + " to be included in the form, but it was not present on the phone!"); form.setValue(null, ref); continue; } File newFile = new File(destination, src.getName()); FileUtils.copyFile(src, newFile); if (newFile.exists() && newFile.length() == src.length()) { form.setValue(new StringData(newFile.toString()), ref); continue; } else { Log.e(TAG, "ODK Failed to property write a file to " + newFile.toString()); form.setValue(null, ref); continue; } } IAnswerData val = Recalculate.wrapData(responseValue, dataType); form.setValue(val == null ? null : AnswerDataFactory.templateByDataType(dataType).cast(val.uncast()), ref); } } } return (result != null); }</code><technical_language>If mind, sweet lift logic in this loop a helper method. pretty burly moment</technical_language>

Target:
public boolean processResponse(Intent intent, ODKView currentView, FormInstance instance, File destination) { if(intent == null){ return false; } String result = intent.getStringExtra(INTENT_RESULT_VALUE); ((ODKView) currentView).setBinaryData(result); Bundle response = intent.getBundleExtra(INTENT_RESULT_BUNDLE); if(responses != null) { for (String key : responses.keySet()) { if (!response.containsKey(key)) { continue; } String responseValue = response.getString(key); if (key == null) { key = ""; } for (TreeReference ref : responses.get(key)) { processResponseItem(ref, responseValue, destination); } } } return (result != null); }
Source:
<code>private static IgnoredPureOperation checkExpression(Expression expression) { if (expression.is(Tree.Kind.CALL_EXPR)) { CallExpression callExpression = (CallExpression) expression; Symbol symbol = callExpression.calleeSymbol(); if (symbol == null) { return null; } String fqn = symbol.fullyQualifiedName(); if (fqn != null && PURE_FUNCTIONS.contains(fqn)) { return new IgnoredPureOperation(callExpression.callee(), fqn); } } else if (expression.is(Tree.Kind.SUBSCRIPTION)) { <START> SubscriptionExpression subscriptionExpression = ((SubscriptionExpression) expression); <END> InferredType type = subscriptionExpression.object().type(); if (PURE_GETITEM_TYPES.stream().anyMatch(type::canBeOrExtend)) { return new IgnoredPureOperation(subscriptionExpression, "__getitem__"); } } else if (expression.is(Tree.Kind.IN)) { InExpression inExpression = ((InExpression) expression); InferredType type = inExpression.rightOperand().type(); if (PURE_CONTAINS_TYPES.stream().anyMatch(type::canOnlyBe)) { return new IgnoredPureOperation(inExpression, "__contains__"); } } return null; }</code><technical_language>Nitpick: remove unnecessary parentheses here</technical_language>

Target:
private static IgnoredPureOperation checkExpression(Expression expression) { if (expression.is(Tree.Kind.CALL_EXPR)) { CallExpression callExpression = (CallExpression) expression; Symbol symbol = callExpression.calleeSymbol(); if (symbol == null) { return null; } String fqn = symbol.fullyQualifiedName(); if (fqn != null && PURE_FUNCTIONS.contains(fqn)) { return new IgnoredPureOperation(callExpression.callee(), fqn); } } else if (expression.is(Tree.Kind.SUBSCRIPTION)) { SubscriptionExpression subscriptionExpression = (SubscriptionExpression) expression; InferredType type = subscriptionExpression.object().type(); if (PURE_GETITEM_TYPES.stream().anyMatch(type::canOnlyBe)) { return new IgnoredPureOperation(subscriptionExpression, "__getitem__"); } } else if (expression.is(Tree.Kind.IN)) { InExpression inExpression = (InExpression) expression; InferredType type = inExpression.rightOperand().type(); if (PURE_CONTAINS_TYPES.stream().anyMatch(type::canOnlyBe)) { return new IgnoredPureOperation(inExpression, "__contains__"); } } return null; }
Source:
<code>public void suggestDesiredDimensions(int minimumWidth, int minimumHeight) { try { int maximumTextureSize; try { maximumTextureSize = SystemProperties.getInt("sys.max_texture_size", 0); } catch (Exception e) { maximumTextureSize = 0; } <START> <END> if (maximumTextureSize > 0) { if (minimumWidth > maximumTextureSize) { float scale = (float) maximumTextureSize / (float)minimumWidth; minimumWidth = maximumTextureSize; minimumHeight = (int) ((float)minimumHeight * scale); } if (minimumHeight > maximumTextureSize) { float scale = (float) maximumTextureSize / (float)minimumHeight; minimumHeight = maximumTextureSize; minimumWidth = (int) ((float)minimumWidth * scale); } } if (sGlobals.mService == null) { Log.w(TAG, "WallpaperService not running"); } else { sGlobals.mService.setDimensionHints(minimumWidth, minimumHeight); } } catch (RemoteException e) { } }</code><technical_language>calculate scale apply it. this alter aspect ratio a tiny bit, in case perfectly preservable</technical_language>

Target:
public void suggestDesiredDimensions(int minimumWidth, int minimumHeight) { try { int maximumTextureSize; try { maximumTextureSize = SystemProperties.getInt("sys.max_texture_size", 0); } catch (Exception e) { maximumTextureSize = 0; } if (maximumTextureSize > 0) { if ((minimumWidth > maximumTextureSize) || (minimumHeight > maximumTextureSize)) { float aspect = (float)minimumHeight / (float)minimumWidth; if (minimumWidth > minimumHeight) { minimumWidth = maximumTextureSize; minimumHeight = (int)((minimumWidth * aspect) + 0.5); } else { minimumHeight = maximumTextureSize; minimumWidth = (int)((minimumHeight / aspect) + 0.5); } } } if (sGlobals.mService == null) { Log.w(TAG, "WallpaperService not running"); } else { sGlobals.mService.setDimensionHints(minimumWidth, minimumHeight); } } catch (RemoteException e) { } }
Source:
<code>public Map<String, Object> getProperties() { <START> return this.properties.size() == 0 ? null : this.properties; <END> }</code><technical_language>@Nullable this getter? Or, return it, if empty. Also, a mechanism modify map, return UnmodifableMap - if so, a field instead of wrapping map call</technical_language>

Target:
public Map<String, Object> getProperties() { return this.unmodifiableProperties; }
Source:
<code>private AxonServerEventStore buildEventStore(Configuration c) { <START> return AxonServerEventStore.builder() <END> .configuration(c.getComponent(AxonServerConfiguration.class)) .platformConnectionManager(c.getComponent(AxonServerConnectionManager.class)) .build(); }</code><technical_language>want add snapshot event serializers well</technical_language>

Target:
private AxonServerEventStore buildEventStore(Configuration c) { return AxonServerEventStore.builder() .configuration(c.getComponent(AxonServerConfiguration.class)) .platformConnectionManager(c.getComponent(AxonServerConnectionManager.class)) .snapshotSerializer(c.serializer()) .eventSerializer(c.eventSerializer()) .upcasterChain(c.upcasterChain()) .build(); }
Source:
<code>private void setupEntityHeader(PreferenceScreen screen) { LayoutPreference headerPref = (LayoutPreference) screen.findPreference(KEY_HEADER); mEntityHeaderController = EntityHeaderController.newInstance( mFragment.getActivity(), mFragment, headerPref.findViewById(R.id.entity_header)); mEntityHeaderController.setIcon( <START> mContext.getDrawable(com.android.internal.R.drawable.ic_bt_laptop)); <END> mEntityHeaderController.setLabel(mPairedDevice.getDeviceName()); mEntityHeaderController.done(mFragment.getActivity(), true); }</code><technical_language>mEntityHeaderController .setIcon(xxxx) .setLabel(xxxx) .done(xxxx)</technical_language>

Target:
private void setupEntityHeader(PreferenceScreen screen) { LayoutPreference headerPref = (LayoutPreference) screen.findPreference(KEY_HEADER); mEntityHeaderController = EntityHeaderController.newInstance( mFragment.getActivity(), mFragment, headerPref.findViewById(R.id.entity_header)); mEntityHeaderController .setIcon(mContext.getDrawable(com.android.internal.R.drawable.ic_bt_laptop)) .setLabel(mPairedDevice.getDeviceName()) .done(mFragment.getActivity(), true); }
Source:
<code>public void testLongParseSuccess() { Long num = NumberParser.parseLong("1"); <START> assertTrue(num == 1L); <END> }</code><technical_language>assertEquals work? for other tests</technical_language>

Target:
public void testLongParseSuccess() { Long num = NumberParser.parseLong("1"); assertEquals(new Long(1L), num); }
Source:
<code>public void testConstructor() { new RandomUtils(); <START> final Constructor<?>[] cons = RandomUtils.class.getDeclaredConstructors(); <END> assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(RandomUtils.class.getModifiers())); assertFalse(Modifier.isFinal(RandomUtils.class.getModifiers())); }</code><technical_language>If clear assertion, useless expression for new object. If used, removed</technical_language>

Target:
public void testConstructor() { CodeStructureAssertions.defaultConstructorOnly(RandomUtils.class); }
Source:
<code>EventHubSystemConsumer(EventHubConfig config, String systemName, EventHubClientManagerFactory eventHubClientManagerFactory, Map<String, Interceptor> interceptors, MetricsRegistry registry, Clock clock) { super(registry, clock); this.config = config; this.clock = clock; this.systemName = systemName; this.interceptors = interceptors; this.eventHubClientManagerFactory = eventHubClientManagerFactory; List<String> streamIds = config.getStreams(systemName); prefetchCount = config.getPrefetchCount(systemName); <START> retryCountWithinWindow = new SlidingTimeWindowReservoir(config.getRetryWindowMs(systemName), clock); <END> eventReadRates = streamIds.stream().collect(Collectors.toMap(Function.identity(), x -> registry.newCounter(x, EVENT_READ_RATE))); eventByteReadRates = streamIds.stream() .collect(Collectors.toMap(Function.identity(), x -> registry.newCounter(x, EVENT_BYTE_READ_RATE))); consumptionLagMs = streamIds.stream() .collect(Collectors.toMap(Function.identity(), x -> new SamzaHistogram(registry, x, CONSUMPTION_LAG_MS))); readErrors = streamIds.stream().collect(Collectors.toMap(Function.identity(), x -> registry.newCounter(x, READ_ERRORS))); synchronized (AGGREGATE_METRICS_LOCK) { if (aggEventReadRate == null) { aggEventReadRate = registry.newCounter(AGGREGATE, EVENT_READ_RATE); aggEventByteReadRate = registry.newCounter(AGGREGATE, EVENT_BYTE_READ_RATE); aggConsumptionLagMs = new SamzaHistogram(registry, AGGREGATE, CONSUMPTION_LAG_MS); aggReadErrors = registry.newCounter(AGGREGATE, READ_ERRORS); } } }</code><technical_language>s/retryCountWithinWindow/recentRetryAttempts</technical_language>

Target:
EventHubSystemConsumer(EventHubConfig config, String systemName, EventHubClientManagerFactory eventHubClientManagerFactory, Map<String, Interceptor> interceptors, MetricsRegistry registry, Clock clock) { super(registry, clock); this.config = config; this.clock = clock; this.systemName = systemName; this.interceptors = interceptors; this.eventHubClientManagerFactory = eventHubClientManagerFactory; List<String> streamIds = config.getStreams(systemName); prefetchCount = config.getPrefetchCount(systemName); recentRetryAttempts = new SlidingTimeWindowReservoir(config.getRetryWindowMs(systemName), clock); eventReadRates = streamIds.stream().collect(Collectors.toMap(Function.identity(), x -> registry.newCounter(x, EVENT_READ_RATE))); eventByteReadRates = streamIds.stream() .collect(Collectors.toMap(Function.identity(), x -> registry.newCounter(x, EVENT_BYTE_READ_RATE))); consumptionLagMs = streamIds.stream() .collect(Collectors.toMap(Function.identity(), x -> new SamzaHistogram(registry, x, CONSUMPTION_LAG_MS))); readErrors = streamIds.stream().collect(Collectors.toMap(Function.identity(), x -> registry.newCounter(x, READ_ERRORS))); synchronized (AGGREGATE_METRICS_LOCK) { if (aggEventReadRate == null) { aggEventReadRate = registry.newCounter(AGGREGATE, EVENT_READ_RATE); aggEventByteReadRate = registry.newCounter(AGGREGATE, EVENT_BYTE_READ_RATE); aggConsumptionLagMs = new SamzaHistogram(registry, AGGREGATE, CONSUMPTION_LAG_MS); aggReadErrors = registry.newCounter(AGGREGATE, READ_ERRORS); } } }
Source:
<code>private boolean isValidImport(String part, int executionCount) { try { CompletableFuture<Boolean> validImportFuture = new CompletableFuture<>(); <START> kernel.executeCode("Class.forName(\"" + part + "\")", new Message(), executionCount, seo -> { <END> validImportFuture.complete(!seo.getStatus().equals(EvaluationStatus.ERROR)); }); return validImportFuture.get(); } catch (InterruptedException | ExecutionException e) { return Boolean.FALSE; } }</code><technical_language>a more more direct of this executeCode this. For example, this fail Clojure kernel</technical_language>

Target:
private boolean isValidImport(String part, int executionCount) { try { CompletableFuture<Boolean> validImportFuture = new CompletableFuture<>(); kernel.executeCode("", new Message(), executionCount, seo -> validImportFuture.complete(!seo.getStatus().equals(EvaluationStatus.ERROR))); return validImportFuture.get(); } catch (InterruptedException | ExecutionException e) { return Boolean.FALSE; } }
Source:
<code>public void updateClusterConfigs(@Nonnull Stack stack, @Nonnull Cluster cluster, List<String> candidateAddresses) { try { Set<Node> nodes = stackUtil.collectReachableNodes(stack); GatewayConfig primaryGatewayConfig = gatewayConfigService.getPrimaryGatewayConfig(stack); List<GatewayConfig> gatewayConfigs = gatewayConfigService.getAllGatewayConfigs(stack); SaltConfig saltConfig = createSaltConfig(stack, cluster, primaryGatewayConfig, gatewayConfigs, nodes); <START> ExitCriteriaModel exitCriteriaModel = nonCancellableModel(); <END> hostOrchestrator.initSaltConfig(gatewayConfigs, nodes, saltConfig, exitCriteriaModel); hostOrchestrator.runService(gatewayConfigs, nodes, saltConfig, exitCriteriaModel); } catch (CloudbreakOrchestratorException | IOException e) { throw new CloudbreakServiceException(e.getMessage(), e); } }</code><technical_language>I this ClusterDeletionBasedExitCriteriaModel</technical_language>

Target:
public void updateClusterConfigs(@Nonnull Stack stack, @Nonnull Cluster cluster, List<String> candidateAddresses) { try { Set<Node> nodes = stackUtil.collectReachableNodes(stack); GatewayConfig primaryGatewayConfig = gatewayConfigService.getPrimaryGatewayConfig(stack); List<GatewayConfig> gatewayConfigs = gatewayConfigService.getAllGatewayConfigs(stack); SaltConfig saltConfig = createSaltConfig(stack, cluster, primaryGatewayConfig, gatewayConfigs, nodes); ExitCriteriaModel exitCriteriaModel = clusterDeletionBasedModel(stack.getId(), cluster.getId()); hostOrchestrator.initSaltConfig(gatewayConfigs, nodes, saltConfig, exitCriteriaModel); hostOrchestrator.runService(gatewayConfigs, nodes, saltConfig, exitCriteriaModel); } catch (CloudbreakOrchestratorException | IOException e) { throw new CloudbreakServiceException(e.getMessage(), e); } }
Source:
<code>public void oneDcMoreRacksThanRfAndMoreHostsThanRfSucceeds() throws TException { setTopology(defaultDcDetails(RACK_1, HOST_1), defaultDcDetails(RACK_2, HOST_2), defaultDcDetails(RACK_1, HOST_3), defaultDcDetails(RACK_2, HOST_4)); <START> when(config.replicationFactor()).thenReturn(2); <END> assertThat(CassandraVerifier.sanityCheckDatacenters(client, config)) .containsExactly(CassandraConstants.DEFAULT_DC); }</code><technical_language>nit: do want a rack? 2 racks more RF of 2</technical_language>

Target:
public void oneDcMoreRacksThanRfAndMoreHostsThanRfSucceeds() throws TException { setTopology(defaultDcDetails(RACK_1, HOST_1), defaultDcDetails(RACK_2, HOST_2), defaultDcDetails(RACK_1, HOST_3), defaultDcDetails(RACK_3, HOST_4)); when(config.replicationFactor()).thenReturn(2); assertThat(CassandraVerifier.sanityCheckDatacenters(client, config)) .containsExactly(CassandraConstants.DEFAULT_DC); }
Source:
<code>private void setDatacenter(String rack) { <START> this.datacenter = rack.substring(0, rack.length() - 1); <END> }</code><technical_language>please verify if is right approach</technical_language>

Target:
private void setDatacenter(String rack) { this.datacenter = ConfigUtils.getDataCenter(rack); }
Source:
<code>void createEncounter() { Encountercreate encountercreate=new Encountercreate(); encountercreate.setPatient(patient.getUuid()); encountercreate.setVisit(visit.getUuid()); encountercreate.setEncounterType(encountertype); List<Obscreate> observations=new ArrayList<>(); List<Fragment> activefrag=getActiveFragments(); for (Fragment f:activefrag) { FormPageFragment formPageFragment=(FormPageFragment)f; if(!formPageFragment.checkfields()) break; List<InputField> pageinputlist=formPageFragment.getInputFields(); inputlist.addAll(pageinputlist); } for (InputField input:inputlist) { Obscreate obscreate = new Obscreate(); obscreate.setConcept(input.getConcept()); obscreate.setValue(input.getValue()); LocalDateTime localDateTime = new LocalDateTime(); obscreate.setObsDatetime(localDateTime.toString()); obscreate.setPerson(patient.getUuid()); observations.add(obscreate); } encountercreate.setObservations(observations); <START> Call<Encounter> call = apiService.createEncounter(encountercreate); <END> call.enqueue(new Callback<Encounter>() { @Override public void onResponse(Call<Encounter> call, Response<Encounter> response) { if (response.isSuccessful()) { Encounter encounter = response.body(); linkvisit(encounter); } else { ToastUtil.error("Could not save encounter"); } } @Override public void onFailure(Call<Encounter> call, Throwable t) { ToastUtil.error(t.getLocalizedMessage()); } }); }</code><technical_language>do Encountercreate Encounter classes? Encounter suffice</technical_language>

Target:
void createEncounter() { Encountercreate encountercreate=new Encountercreate(); encountercreate.setPatient(patient.getUuid()); encountercreate.setEncounterType(encountertype); List<Obscreate> observations=new ArrayList<>(); List<Fragment> activefrag=getActiveFragments(); for (Fragment f:activefrag) { FormPageFragment formPageFragment=(FormPageFragment)f; if(!formPageFragment.checkfields()) break; List<InputField> pageinputlist=formPageFragment.getInputFields(); inputlist.addAll(pageinputlist); } for (InputField input:inputlist) { Obscreate obscreate = new Obscreate(); obscreate.setConcept(input.getConcept()); obscreate.setValue(input.getValue()); LocalDateTime localDateTime = new LocalDateTime(); obscreate.setObsDatetime(localDateTime.toString()); obscreate.setPerson(patient.getUuid()); observations.add(obscreate); } encountercreate.setObservations(observations); encountercreate.setFormname(formname); encountercreate.setPatientId(mPatientID); encountercreate.setObslist(); new EncounterService().addEncounter(encountercreate); finish(); }
Source:
<code>public Object debugStreamingSenderInputOutputAbort(ProceedingJoinPoint proceedingJoinPoint, String correlationId, String message, ParameterResolutionContext parameterResolutionContext, MessageOutputStream target) throws Throwable { <START> if (debug) System.out.println("debugStreamingSenderInputOutputAbort thread id +Thread.currentThread().getId()+ thread name +Thread.currentThread().getName()+ correlationId ["+correlationId+"]"); <END> return debugSenderWithParametersInputOutputAbort(proceedingJoinPoint, correlationId, message, parameterResolutionContext); }</code><technical_language>I dislike of printing sysout, a logger used? trace/debug</technical_language>

Target:
public Object debugStreamingSenderInputOutputAbort(ProceedingJoinPoint proceedingJoinPoint, String correlationId, String message, ParameterResolutionContext parameterResolutionContext, MessageOutputStream target) throws Throwable { if (log.isDebugEnabled()) log.debug("debugStreamingSenderInputOutputAbort thread id +Thread.currentThread().getId()+ thread name +Thread.currentThread().getName()+ correlationId ["+correlationId+"]"); return debugSenderWithParametersInputOutputAbort(proceedingJoinPoint, correlationId, message, parameterResolutionContext); }
Source:
<code>private static Set<ObjectId> refIdSet(Collection<Ref> refs) { Set<ObjectId> ids = new HashSet<ObjectId>(refs.size()); for (Ref ref : refs) { if (ref.getObjectId() != null) { ids.add(ref.getObjectId()); } if (ref.getPeeledObjectId() != null) { <START> ids.add(ref.getPeeledObjectId()); <END> } } return ids; }</code><technical_language>implementation of Ref.getPeeledObjectId() (the in SymbolicRef) expensive sense cache result of ref.getPeeledObjectId() in a local variable. do deal symbolic refs here</technical_language>

Target:
private static Set<ObjectId> refIdSet(Collection<Ref> refs) { Set<ObjectId> ids = new HashSet<ObjectId>(refs.size()); for (Ref ref : refs) { ObjectId id = ref.getObjectId(); if (id != null) { ids.add(id); } id = ref.getPeeledObjectId(); if (id != null) { ids.add(id); } } return ids; }
Source:
<code>public void tagEvent(ReplaceableTagEvent event) { Attribute attribute = event.getAttributes().fulfill(1); if (attribute.startsWith("weapon")) { <START> if (attribute.hasContext(1)) { <END> ItemStack weapon = utility.generateWeapon(attribute.getContext(1)); if (weapon != null) { event.setReplacedObject(new ItemTag(weapon).getObjectAttribute(attribute.fulfill(1))); } else { Debug.echoError("Invalid weapon name specified."); } } } }</code><technical_language>if lines combined &&</technical_language>

Target:
public void tagEvent(ReplaceableTagEvent event) { Attribute attribute = event.getAttributes().fulfill(1); if (attribute.startsWith("weapon") && attribute.hasContext(1)) { ItemStack weapon = utility.generateWeapon(attribute.getContext(1)); if (weapon != null) { event.setReplacedObject(new ItemTag(weapon).getObjectAttribute(attribute.fulfill(1))); } else { attribute.echoError("Invalid weapon name specified."); } } }
Source:
<code>public void testExtensionPoints() throws UserNotConnectedException { doLogin(); <START> ExplorerHomePage home = goHome(); <END> ArtifactHomePage ahome = home.navigateTo(home.currentExtensionPoints); assertTrue(ahome.isSelected(ahome.extensionPoints)); WebElement elt = ahome.getFirstListingElement(); WebElement link = elt.findElement(By.xpath(". assertEquals("actions", link.getText()); assertEquals("ActionService", elt.findElement(By.xpath(". assertEquals("org.nuxeo.ecm.platform.actions.ActionService", elt.findElement(By.xpath(". Locator.scrollAndForceClick(link);; ArtifactPage apage = asPage(ArtifactPage.class); assertTrue(apage.isSelected(apage.extensionPoints)); assertEquals("Extension point org.nuxeo.ecm.platform.actions.ActionService--actions", apage.getTitle()); assertEquals("Extension point actions", apage.header.getText()); assertEquals("In component org.nuxeo.ecm.platform.actions.ActionService", apage.description.getText()); doLogout(); }</code><technical_language>in mind tests; some Class (like ArtifactHomePage) accessors more understandable instead of relying direct selectors By.xpath consosr</technical_language>

Target:
public void testExtensionPoints() throws UserNotConnectedException { ExplorerHomePage home = goHome(); ArtifactHomePage ahome = home.navigateTo(home.currentExtensionPoints); assertTrue(ahome.isSelected(ahome.extensionPoints)); WebElement elt = ahome.getFirstListingElement(); WebElement link = elt.findElement(By.xpath(". assertEquals("actions", link.getText()); assertEquals("ActionService", elt.findElement(By.xpath(". assertEquals("org.nuxeo.ecm.platform.actions.ActionService", elt.findElement(By.xpath(". Locator.scrollAndForceClick(link); ArtifactPage apage = asPage(ArtifactPage.class); assertTrue(apage.isSelected(apage.extensionPoints)); assertEquals("Extension point org.nuxeo.ecm.platform.actions.ActionService--actions", apage.getTitle()); assertEquals("Extension point actions", apage.header.getText()); assertEquals("In component org.nuxeo.ecm.platform.actions.ActionService", apage.description.getText()); }
Source:
<code>private void addTransfers(Set<Integer> segments) { log.debugf("Adding inbound state transfer for segments %s of cache %s", segments, cacheName); Set<Address> excludedSources = new HashSet<Address>(); Map<Address, Set<Integer>> sources = new HashMap<Address, Set<Integer>>(); if (isTransactional && !isTotalOrder) { requestTransactions(segments, sources, excludedSources); } if (isFetchEnabled) { requestSegments(segments, sources, excludedSources); } <START> log.tracef("Finished adding inbound state transfer for segments %s of cache %s", segments, cacheName); <END> }</code><technical_language>if (trace) ..</technical_language>

Target:
private void addTransfers(Set<Integer> segments) { log.debugf("Adding inbound state transfer for segments %s of cache %s", segments, cacheName); Set<Address> excludedSources = new HashSet<Address>(); Map<Address, Set<Integer>> sources = new HashMap<Address, Set<Integer>>(); if (isTransactional && !isTotalOrder) { requestTransactions(segments, sources, excludedSources); } if (isFetchEnabled) { requestSegments(segments, sources, excludedSources); } if (trace) log.tracef("Finished adding inbound state transfer for segments %s of cache %s", segments, cacheName); }
Source:
<code>public boolean areAllProcessesDead() throws IOException { Set<Long> pids = getAllPids(); String user = getRunWorkerAsUser(); boolean allDead = true; try { if (pids.isEmpty()) { return true; } if (ServerUtils.IS_ON_WINDOWS) { return allDead = !isAnyProcessAlive(pids, user); } if (!cachedUserToUidMap.containsKey(user)) { <START> int uid = getPidPathOwnerUid(workerId, pids.iterator().next()); <END> if (uid < 0) { uid = getUserId(user); } if (uid >= 0) { cachedUserToUidMap.put(user, uid); } } if (cachedUserToUidMap.containsKey(user)) { return allDead = !isAnyProcessAlive(pids, cachedUserToUidMap.get(user)); } else { return allDead = !isAnyProcessAlive(pids, user); } } finally { if (allDead && shutdownTimer != null) { shutdownTimer.stop(); shutdownTimer = null; } } }</code><technical_language>check owner of pid file. Checking owner of worker-id directory good enough</technical_language>

Target:
public boolean areAllProcessesDead() throws IOException { Set<Long> pids = getAllPids(); String user = getRunWorkerAsUser(); boolean allDead = true; try { if (pids.isEmpty()) { return true; } if (ServerUtils.IS_ON_WINDOWS) { return allDead = !isAnyProcessAlive(pids, user); } if (!cachedUserToUidMap.containsKey(user)) { int uid = getWorkerPathOwnerUid(workerId); if (uid < 0) { uid = getUserId(user); } if (uid >= 0) { cachedUserToUidMap.put(user, uid); } } if (cachedUserToUidMap.containsKey(user)) { return allDead = !isAnyProcessAlive(pids, cachedUserToUidMap.get(user)); } else { return allDead = !isAnyProcessAlive(pids, user); } } finally { if (allDead && shutdownTimer != null) { shutdownTimer.stop(); shutdownTimer = null; } } }
Source:
<code><START> public String getUrl() { <END> return urlTemplate; }</code><technical_language>![INFO](<LINK_1> 'Severity: INFO') Do forget remove this deprecated code someday. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public String getUrl() { return template; }
Source:
<code>public void whenSchedulerPausedThenTimerNotFired() throws Exception { long processInstanceId = processService.startProcess(unit.getIdentifier(), PROCESS_ID); assertNotNull(processInstanceId); pauseScheduler(); CountDownLatch latch = new CountDownLatch(1); <START> latch.await(20, TimeUnit.SECONDS); <END> ProcessInstance pi = processService.getProcessInstance(processInstanceId); assertNotNull(processInstanceId); assertEquals(STATE_ACTIVE, pi.getState()); processService.abortProcessInstance(processInstanceId); }</code><technical_language>I call await configured countdown listener check outcome of await method - return false, meaning timed out. Wdyt? replace this plain Thread.sleep()</technical_language>

Target:
public void whenSchedulerPausedThenTimerNotFired() throws Exception { long processInstanceId = processService.startProcess(unit.getIdentifier(), PROCESS_ID); assertNotNull(processInstanceId); pauseScheduler(); awaitWithoutInterruption(); ProcessInstance pi = processService.getProcessInstance(processInstanceId); assertNotNull(processInstanceId); assertEquals(STATE_ACTIVE, pi.getState()); processService.abortProcessInstance(processInstanceId); }