auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String getFieldName(AccessibleObject fieldOrMethod) { if (fieldOrMethod instanceof Field) { return ((Field) fieldOrMethod).getName(); } Method method = (Method) fieldOrMethod; String name = method.getName(); boolean hasValidParameterCount = method.getParameterCount() == 0 <START> || isRequestScopeableMethod((Method) fieldOrMethod); <END> if (name.startsWith("get") && hasValidParameterCount) { name = StringUtils.uncapitalize(name.substring("get".length())); } else if (name.startsWith("is") && hasValidParameterCount) { name = StringUtils.uncapitalize(name.substring("is".length())); } else { return null; } return name; }</code><technical_language>pass method here</technical_language>

Target:
public static String getFieldName(AccessibleObject fieldOrMethod) { if (fieldOrMethod instanceof Field) { return ((Field) fieldOrMethod).getName(); } Method method = (Method) fieldOrMethod; String name = method.getName(); boolean hasValidParameterCount = method.getParameterCount() == 0 || isRequestScopeableMethod(method); if (name.startsWith("get") && hasValidParameterCount) { return StringUtils.uncapitalize(name.substring("get".length())); } if (name.startsWith("is") && hasValidParameterCount) { return StringUtils.uncapitalize(name.substring("is".length())); } return null; }
Source:
<code>public static StructuralNode getRootNode() { Model model = Model.getSingleton(); if (!Constant.isLowMemoryOptionSet()) { return new StructuralSiteNode(model.getSession().getSiteTree().getRootNode()); } Session session = Model.getSingleton().getSession(); RecordStructure rs; try { <START> rs = model.getDb().getTableStructure().find(session.getSessionId(), ROOT, "Get"); <END> if (rs != null) { return new StructuralTableNode(rs); } } catch (DatabaseException e) { log.error(e.getMessage(), e); } return null; }</code><technical_language>method upper case</technical_language>

Target:
public static StructuralNode getRootNode() { Model model = Model.getSingleton(); if (!Constant.isLowMemoryOptionSet()) { return new StructuralSiteNode(model.getSession().getSiteTree().getRoot()); } Session session = Model.getSingleton().getSession(); RecordStructure rs; try { rs = model.getDb().getTableStructure().find(session.getSessionId(), ROOT, HttpRequestHeader.GET); if (rs != null) { return new StructuralTableNode(rs); } } catch (DatabaseException e) { log.error(e.getMessage(), e); } return null; }
Source:
<code>public void preparedStatementCacheMetrics(){ navigation.selectRow().invoke("View"); Application.waitUntilVisible(); <START> <END> MetricsAreaFragment metricsArea = dsPage.getPreparedStatementCacheMetricsArea(); double expectedHitCountPercentage = metricsArea.getPercentage(HIT_COUNT, ACCESS_COUNT); double expectedMissCountPercentage = metricsArea.getPercentage(MISS_COUNT, ACCESS_COUNT); MetricsFragment hitCountMetrics = metricsArea.getMetricsFragment(HIT_COUNT); MetricsFragment missCountMetrics = metricsArea.getMetricsFragment(MISS_COUNT); assertEquals(expectedHitCountPercentage, hitCountMetrics.getPercentage(), DELTA); assertEquals(expectedMissCountPercentage, missCountMetrics.getPercentage(), DELTA); }</code><technical_language>Please move this end of before() method</technical_language>

Target:
public void preparedStatementCacheMetrics(){ MetricsAreaFragment metricsArea = dsPage.getPreparedStatementCacheMetricsArea(); double expectedHitCountPercentage = metricsArea.getPercentage(HIT_COUNT, ACCESS_COUNT); double expectedMissCountPercentage = metricsArea.getPercentage(MISS_COUNT, ACCESS_COUNT); MetricsFragment hitCountMetrics = metricsArea.getMetricsFragment(HIT_COUNT); MetricsFragment missCountMetrics = metricsArea.getMetricsFragment(MISS_COUNT); assertEquals(expectedHitCountPercentage, hitCountMetrics.getPercentage(), DELTA); assertEquals(expectedMissCountPercentage, missCountMetrics.getPercentage(), DELTA); }
Source:
<code>public <S> LinkedHashSet<S> loadJavaServices(Class<S> serviceContract) { <START> ServiceLoader<S> serviceLoader; <END> if ( serviceLoaders.containsKey( serviceContract ) ) { serviceLoader = serviceLoaders.get( serviceContract ); } else { serviceLoader = ServiceLoader.load( serviceContract, aggregatedClassLoader ); serviceLoaders.put( serviceContract, serviceLoader ); } final LinkedHashSet<S> services = new LinkedHashSet<S>(); for ( S service : serviceLoader ) { services.add( service ); } return services; }</code><technical_language>do need caching of originating _serviceLoader_</technical_language>

Target:
public <S> LinkedHashSet<S> loadJavaServices(Class<S> serviceContract) { ServiceLoader<S> serviceLoader = ServiceLoader.load( serviceContract, aggregatedClassLoader ); final LinkedHashSet<S> services = new LinkedHashSet<S>(); for ( S service : serviceLoader ) { services.add( service ); } return services; }
Source:
<code>private String getFactoryMethodName(TypeName returnType, TypeElement factoryClass) { List<? extends Element> elements = factoryClass.getEnclosedElements(); for (Element element : elements) { if (element.getKind() != ElementKind.METHOD || !element.getModifiers().contains(Modifier.STATIC)) { continue; } ExecutableElement method = (ExecutableElement) element; if (methodTakesAndReturns(method, CURSOR, returnType)) { return method.getSimpleName().toString(); } } <START> return null; <END> }</code><technical_language>Throw error message instead of returning null. Right javapoet throw IllegalArgumentException in line 132 for passing in null</technical_language>

Target:
private String getFactoryMethodName(TypeName returnType, TypeElement factoryClass) { List<? extends Element> elements = factoryClass.getEnclosedElements(); for (Element element : elements) { if (element.getKind() != ElementKind.METHOD || !element.getModifiers().contains(Modifier.STATIC)) { continue; } ExecutableElement method = (ExecutableElement) element; if (methodTakesAndReturns(method, CURSOR, returnType)) { return method.getSimpleName().toString(); } } throw new IllegalArgumentException(String.format("Class \"%s\" needs to define a " + "public static method taking a \"Cursor\" and returning \"%s\"", factoryClass.getSimpleName(), returnType.toString())); }
Source:
<code>public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { NonEntityDictionary nonEntityDictionary = fetcher.getNonEntityDictionary(); String fieldName = context.field.getName(); Object returnObject; if (KEY.equalsIgnoreCase(fieldName)) { returnObject = entry.getKey(); } else if (VALUE.equalsIgnoreCase(fieldName)) { returnObject = entry.getValue(); } else { throw new BadRequestException("Invalid field: '" + fieldName + "'. Maps only contain fields 'key' and 'value'"); } <START> if (nonEntityDictionary.hasBinding(new ClassType(returnObject.getClass()))) { <END> return new NonEntityContainer(returnObject); } return returnObject; }</code><technical_language>call object.getClass in code. getType method in entity dictionary</technical_language>

Target:
public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { NonEntityDictionary nonEntityDictionary = fetcher.getNonEntityDictionary(); String fieldName = context.field.getName(); Object returnObject; if (KEY.equalsIgnoreCase(fieldName)) { returnObject = entry.getKey(); } else if (VALUE.equalsIgnoreCase(fieldName)) { returnObject = entry.getValue(); } else { throw new BadRequestException("Invalid field: '" + fieldName + "'. Maps only contain fields 'key' and 'value'"); } if (nonEntityDictionary.hasBinding(EntityDictionary.getType(returnObject))) { return new NonEntityContainer(returnObject); } return returnObject; }
Source:
<code>public JobModel getJobModel() { JavaSystemConfig systemConfig = new JavaSystemConfig(this.config); <START> Map<String, SystemAdmin> systemAdminMap = systemConfig.getSystemAdmins(); <END> SystemAdmins systemAdmins = new SystemAdmins(Util.javaMapAsScalaMap(systemAdminMap)); StreamMetadataCache streamMetadataCache = new StreamMetadataCache(Util.javaMapAsScalaMap(systemAdminMap), 5000, SystemClock.instance()); systemAdmins.start(); String containerId = Integer.toString(config.getInt(JobConfig.PROCESSOR_ID())); JobModel jobModel = JobModelManager.readJobModel(this.config, Collections.emptyMap(), null, streamMetadataCache, Collections.singletonList(containerId)); systemAdmins.stop(); return jobModel; }</code><technical_language>This is in a lot of places. cleaner add a helper/constructor in SystemAdmins this</technical_language>

Target:
public JobModel getJobModel() { SystemAdmins systemAdmins = new SystemAdmins(config); StreamMetadataCache streamMetadataCache = new StreamMetadataCache(systemAdmins, 5000, SystemClock.instance()); systemAdmins.start(); String containerId = Integer.toString(config.getInt(JobConfig.PROCESSOR_ID())); JobModel jobModel = JobModelManager.readJobModel(this.config, Collections.emptyMap(), null, streamMetadataCache, Collections.singletonList(containerId)); systemAdmins.stop(); return jobModel; }
Source:
<code><START> public static int comp(String str1, String str2) { <END> if (str1 == null) { return (str2 == null) ? 0 : -1; } else if (str2 == null) { return 1; } boolean isDigitTurn = false; int begSeq1 = 0, begSeq2 = 0, endSeq1, endSeq2; while ((endSeq1 = findEndOfSequence(str1, begSeq1, isDigitTurn)) != begSeq1) { if ((endSeq2 = findEndOfSequence(str2, begSeq2, isDigitTurn)) == begSeq2) { return 1; } String seq1 = str1.substring(begSeq1, endSeq1); String seq2 = str2.substring(begSeq2, endSeq2); int compRes = compareSequence(seq1, seq2, isDigitTurn); if (compRes != 0) { return compRes; } isDigitTurn = !isDigitTurn; begSeq1 = endSeq1; begSeq2 = endSeq2; } if (begSeq2 != str2.length()) { return -1; } return 0; }</code><technical_language>is this a public method</technical_language>

Target:
public static int comp(String str1, String str2) { if (str1 == null) { return (str2 == null) ? 0 : -1; } else if (str2 == null) { return 1; } boolean digitTurn = false; int begSeq1 = 0; int begSeq2 = 0; while (begSeq1 != str1.length()) { if (begSeq2 == str2.length()) { return 1; } int endSeq1 = findEndOfSequence(str1, begSeq1, digitTurn); int endSeq2 = findEndOfSequence(str2, begSeq2, digitTurn); String seq1 = str1.substring(begSeq1, endSeq1); String seq2 = str2.substring(begSeq2, endSeq2); int compRes = compareSequence(seq1, seq2, digitTurn); if (compRes != 0) { return compRes; } digitTurn = !digitTurn; begSeq1 = endSeq1; begSeq2 = endSeq2; } if (begSeq2 != str2.length()) { return -1; } return 0; }
Source:
<code>public void runCoalescedRequest(long startIndex) throws InterruptedException { <START> fTrace = setupTrace(TmfTestTrace.A_TEST_10K.getFullPath()); <END> TmfSignalManager.register(this); TmfTestTriggerSignal signal = new TmfTestTriggerSignal(this, startIndex, false); TmfSignalManager.dispatchSignal(signal); request1.waitForCompletion(); request2.waitForCompletion(); request3.waitForCompletion(); try { assertEquals("Request1: nbEvents", NB_EVENTS, requestedEvents1.size()); assertTrue("Request1: isCompleted", request1.isCompleted()); assertFalse("Request1: isCancelled", request1.isCancelled()); assertEquals("Request2: nbEvents", NB_EVENTS, requestedEvents2.size()); assertTrue("Request2: isCompleted", request2.isCompleted()); assertFalse("Request2: isCancelled", request2.isCancelled()); assertEquals("Request3: nbEvents", NB_EVENTS, requestedEvents3.size()); assertTrue("Request3: isCompleted", request3.isCompleted()); assertFalse("Request3: isCancelled", request3.isCancelled()); for (int i = 0; i < NB_EVENTS; i++) { assertEquals("Distinct events", i + 1 + request1.getIndex(), requestedEvents1.get(i).getTimestamp().getValue()); assertEquals("Distinct events", i + 1 + request2.getIndex(), requestedEvents2.get(i).getTimestamp().getValue()); assertEquals("Distinct events", i + 1 + request3.getIndex(), requestedEvents3.get(i).getTimestamp().getValue()); } } finally { TmfSignalManager.deregister(this); fTrace.dispose(); fTrace = null; } }</code><technical_language>saved in a local variable</technical_language>

Target:
public void runCoalescedRequest(long startIndex) throws InterruptedException { fTrace = setupTrace(TEST_TRACE.getFullPath()); TmfSignalManager.register(this); TmfTestTriggerSignal signal = new TmfTestTriggerSignal(this, startIndex, false); TmfSignalManager.dispatchSignal(signal); request1.waitForCompletion(); request2.waitForCompletion(); request3.waitForCompletion(); try { assertEquals("Request1: nbEvents", NB_EVENTS, requestedEvents1.size()); assertTrue("Request1: isCompleted", request1.isCompleted()); assertFalse("Request1: isCancelled", request1.isCancelled()); assertEquals("Request2: nbEvents", NB_EVENTS, requestedEvents2.size()); assertTrue("Request2: isCompleted", request2.isCompleted()); assertFalse("Request2: isCancelled", request2.isCancelled()); assertEquals("Request3: nbEvents", NB_EVENTS, requestedEvents3.size()); assertTrue("Request3: isCompleted", request3.isCompleted()); assertFalse("Request3: isCancelled", request3.isCancelled()); for (int i = 0; i < NB_EVENTS; i++) { assertEquals("Distinct events", i + 1 + request1.getIndex(), requestedEvents1.get(i).getTimestamp().getValue()); assertEquals("Distinct events", i + 1 + request2.getIndex(), requestedEvents2.get(i).getTimestamp().getValue()); assertEquals("Distinct events", i + 1 + request3.getIndex(), requestedEvents3.get(i).getTimestamp().getValue()); } } finally { TmfSignalManager.deregister(this); fTrace.dispose(); fTrace = null; } }
Source:
<code>public void testCancelIntp() { if (getSparkVersionNumber() > 11) { assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret("a = 1\n", context).code()); new Thread(new infinityPythonJob()).start(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } <START> pySparkInterpreter.cancel(context); <END> } }</code><technical_language>need checks if thread is finished not? I thread.join() is required here. test fail if job is cancelled</technical_language>

Target:
public void testCancelIntp() throws InterruptedException { if (getSparkVersionNumber() > 11) { assertEquals(InterpreterResult.Code.SUCCESS, pySparkInterpreter.interpret("a = 1\n", context).code()); Thread t = new Thread(new infinityPythonJob()); t.start(); Thread.sleep(5000); pySparkInterpreter.cancel(context); assertTrue(t.isAlive()); t.join(2000); assertFalse(t.isAlive()); } }
Source:
<code>private void setResultIdsAndFinish() { Intent intent = new Intent(); if (mGridAdapter.getSelectedItemCount() > 0) { ArrayList<Long> remoteMediaIds = new ArrayList<>(); for (Integer localId : mGridAdapter.getSelectedItems()) { <START> remoteMediaIds.add(mMediaStore.getMediaWithLocalId(localId).getMediaId()); <END> } intent.putExtra(RESULT_IDS, ListUtils.toLongArray(remoteMediaIds)); } setResult(RESULT_OK, intent); finish(); }</code><technical_language>getMediaWithLocalId returns null here</technical_language>

Target:
private void setResultIdsAndFinish() { Intent intent = new Intent(); if (mGridAdapter.getSelectedItemCount() > 0) { ArrayList<Long> remoteMediaIds = new ArrayList<>(); for (Integer localId : mGridAdapter.getSelectedItems()) { MediaModel media = mMediaStore.getMediaWithLocalId(localId); if (media != null) { remoteMediaIds.add(media.getMediaId()); } } intent.putExtra(RESULT_IDS, ListUtils.toLongArray(remoteMediaIds)); } setResult(RESULT_OK, intent); finish(); }
Source:
<code>private int readPacket(byte[] packet, int offset, int psize) throws IOException { int bytesRead=0; if (psize == 0) { return 0; } <START> if (buff.capacity()< psize){ <END> int packetSize = psize + 32; ByteBuffer newBuff = ByteBuffer.allocate(packetSize); newBuff.put((ByteBuffer) buff.flip()); buff = newBuff; } buff.position(offset); while (bytesRead < packet.length && buff.remaining() > 0){ int len = rbChannel.read(buff.get(packet)); bytesRead += len; } return bytesRead; }</code><technical_language>dont a predefined buffer size, in case incoming packet is bigger, deny traffic?? redimensioning buffer for packet size a bit unsafe..</technical_language>

Target:
public int readPacket(byte[] packet, int offset, int psize) throws IOException { int length = 0; int len=0; int packetSize = psize + offset + headerSize; if (buff.capacity()< psize){ ByteBuffer newBuff = ByteBuffer.allocate(packetSize); newBuff.put((ByteBuffer) buff.flip()); buff = newBuff; } try { buff.position(offset); len = rbChannel.read(ByteBuffer.wrap(packet,offset,psize)); if (len == -1){ return length; } length += len; return length; } catch (Exception e) { logger.error(e); } return length; }
Source:
<code>private synchronized void updateAvailableNetworks(List<QualifiedNetworks> networksList) { log("updateAvailableNetworks: " + networksList); for (QualifiedNetworks networks : networksList) { if (areNetworksValid(networks)) { mCurrentAvailableNetworks.put(networks.apnType, networks.qualifiedNetworks); if (isHandoverNeeded(networks)) { int targetTransport = ACCESS_NETWORK_TRANSPORT_TYPE_MAP.get( networks.qualifiedNetworks[0]); mHandoverNeededEventRegistrants.notifyResult(new HandoverEntry(networks.apnType, targetTransport)); } else { int transport = TransportType.WWAN; if (!ArrayUtils.isEmpty(networks.qualifiedNetworks) && ACCESS_NETWORK_TRANSPORT_TYPE_MAP.containsKey( networks.qualifiedNetworks[0])) { transport = ACCESS_NETWORK_TRANSPORT_TYPE_MAP <START> .get(networks.qualifiedNetworks[0]); <END> } setCurrentTransport(networks.apnType, transport); } } } }</code><technical_language>structure is a apn_type <-> a list a network picking network handle apn type, Is intended a TODO handle other networks</technical_language>

Target:
private synchronized void updateAvailableNetworks(List<QualifiedNetworks> networksList) { log("updateAvailableNetworks: " + networksList); for (QualifiedNetworks networks : networksList) { if (areNetworksValid(networks)) { mCurrentAvailableNetworks.put(networks.apnType, networks.qualifiedNetworks); if (isHandoverNeeded(networks)) { int targetTransport = ACCESS_NETWORK_TRANSPORT_TYPE_MAP.get( networks.qualifiedNetworks[0]); mHandoverNeededEventRegistrants.notifyResult( new HandoverParams(networks.apnType, targetTransport)); } else { log("Handover not needed for APN type: " + ApnSetting.getApnTypeString(networks.apnType)); int transport = TransportType.WWAN; if (!ArrayUtils.isEmpty(networks.qualifiedNetworks) && ACCESS_NETWORK_TRANSPORT_TYPE_MAP.containsKey( networks.qualifiedNetworks[0])) { transport = ACCESS_NETWORK_TRANSPORT_TYPE_MAP .get(networks.qualifiedNetworks[0]); } setCurrentTransport(networks.apnType, transport); } } } }
Source:
<code>public String toString() { <START> return "ExcludeRange{" + <END> "m_begin='" + m_begin + '\'' + ", m_end='" + m_end + '\'' + ", m_location='" + m_location + '\'' + '}'; }</code><technical_language>include m_ prefix in toString labels. While changing this, consider MoreObjects.ToStringHelper</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("begin", m_begin) .add("end", m_end) .add("location", m_location) .toString(); }
Source:
<code>public Money toMoney() { <START> return Money.of(this.currency, this.getAmount()); <END> }</code><technical_language>This is trivial, inconsistent access currency field amount field getter</technical_language>

Target:
public Money toMoney() { return Money.of(this.getCurrency(), this.getAmount()); }
Source:
<code>private void toggleViewSize(View v){ TextView title = (TextView)v.findViewById(R.id.title); TextView album = (TextView)v.findViewById(R.id.album); TextView artist = (TextView)v.findViewById(R.id.artist); if(v.getHeight()>getResources().getDimension(R.dimen.song_height)){ title.setMaxLines(1); album.setMaxLines(1); <START> artist.setMaxLines(1); <END> v.findViewById(R.id.user_color).setMinimumHeight((int) getResources().getDimension(R.dimen.song_height)); } else{ title.setMaxLines(10); album.setMaxLines(10); artist.setMaxLines(10); int viewHeight = (int) getResources().getDimension(R.dimen.song_height) + (title.getLineCount()-1)*title.getLineHeight() + (artist.getLineCount()-1)*artist.getLineHeight() + (album.getLineCount()-1)*album.getLineHeight(); v.findViewById(R.id.user_color).setMinimumHeight(viewHeight); } }</code><technical_language>Magic numbers...please pull appropriately named constant variable</technical_language>

Target:
private void toggleViewSize(View v){ TextView title = (TextView)v.findViewById(R.id.title); TextView album = (TextView)v.findViewById(R.id.album); TextView artist = (TextView)v.findViewById(R.id.artist); if(v.getHeight()>getResources().getDimension(R.dimen.song_height)){ title.setMaxLines(SHORT_VIEW); album.setMaxLines(SHORT_VIEW); artist.setMaxLines(SHORT_VIEW); v.findViewById(R.id.user_color).setMinimumHeight((int) getResources().getDimension(R.dimen.song_height)); } else{ title.setMaxLines(EXPANDED_VIEW); album.setMaxLines(EXPANDED_VIEW); artist.setMaxLines(EXPANDED_VIEW); int titleHeight = (title.getLineCount()-1)*title.getLineHeight(); int artistHeight = (artist.getLineCount()-1)*artist.getLineHeight(); int albumHeight = (album.getLineCount()-1)*album.getLineHeight(); int viewHeight = (int) getResources().getDimension(R.dimen.song_height) + titleHeight + artistHeight + albumHeight; v.findViewById(R.id.user_color).setMinimumHeight(viewHeight); } }
Source:
<code>public CompletableFuture<Void> unrankMapVersion(MapBean map) { <START> evictCache(); <END> return fafService.unrankeMapVersion(map); }</code><technical_language>This evict cache call a spring bean proxy class. this work, service needs injected @Autowired reference instead</technical_language>

Target:
public CompletableFuture<Void> unrankMapVersion(MapBean map) { applicationContext.getBean(this.getClass()).evictCache(); return fafService.unrankeMapVersion(map); }
Source:
<code>public GlusterVolumeTaskReturnForXmlRpc glusterVolumeRebalanceStop(String volumeName) { try { <START> Map<String, Object> xmlRpcReturnValue = vdsServer.glusterVolumeRebalanceStatus(volumeName); <END> GlusterVolumeTaskReturnForXmlRpc wrapper = new GlusterVolumeTaskReturnForXmlRpc(xmlRpcReturnValue); return wrapper; } catch (UndeclaredThrowableException ute) { throw new XmlRpcRunTimeException(ute); } }</code><technical_language>this method stop rebalance well? I stop call here</technical_language>

Target:
public GlusterVolumeTaskReturnForXmlRpc glusterVolumeRebalanceStop(String volumeName) { try { Map<String, Object> xmlRpcReturnValue = vdsServer.glusterVolumeRebalanceStop(volumeName); GlusterVolumeTaskReturnForXmlRpc wrapper = new GlusterVolumeTaskReturnForXmlRpc(xmlRpcReturnValue); return wrapper; } catch (UndeclaredThrowableException ute) { throw new XmlRpcRunTimeException(ute); } }
Source:
<code>public List<ContainerInfo> find(RuntimeIdentity id) throws InternalInfrastructureException { try { List<ContainerInfo> result = new ArrayList<>(); <START> for (ContainerListEntry runningEntry : docker.listContainers(ListContainersParams.create().withAll(false))) { <END> if (id.equals(Labels.newDeserializer(runningEntry.getLabels()).runtimeId())) { result.add(docker.inspectContainer(runningEntry.getId())); } } return result; } catch (IOException x) { throw new InternalInfrastructureException(x.getMessage(), x); } }</code><technical_language>considered filtering of containers in Docker API? <LINK_0></technical_language>

Target:
public List<ContainerListEntry> find(RuntimeIdentity id) throws InternalInfrastructureException { return listNonStoppedContainers(Labels.newSerializer() .runtimeId(id) .labels() .entrySet() .stream() .map(entry -> entry.getKey() + '=' + entry.getValue()) .toArray(String[]::new)); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar); mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mRegistrationProgressBar.setVisibility(ProgressBar.GONE); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); boolean sentToken = sharedPreferences .getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false); if (sentToken) { mInformationTextView.setText(getString(R.string.gcm_send_message)); } else { mInformationTextView.setText(getString(R.string.token_error_message)); } } }; mInformationTextView = (TextView) findViewById(R.id.informationTextView); LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE)); <START> isReceiverRegistered =true; <END> if (checkPlayServices()) { Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } }</code><technical_language>Please add a space = true, consider encapsulating this a method, called in onCreate onResume. Eg: registerReceiver()</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar); mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mRegistrationProgressBar.setVisibility(ProgressBar.GONE); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); boolean sentToken = sharedPreferences .getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false); if (sentToken) { mInformationTextView.setText(getString(R.string.gcm_send_message)); } else { mInformationTextView.setText(getString(R.string.token_error_message)); } } }; mInformationTextView = (TextView) findViewById(R.id.informationTextView); registerReceiver(); if (checkPlayServices()) { Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } }
Source:
<code>public String getContactName(String number) { ContactInfo contact = contactStore.getContact(number); if(contact == null) { <START> return number; <END> } else { return contact.name; } }</code><technical_language>I return empty string here, indicate, contact is unknown</technical_language>

Target:
public String getContactName(String number) { ContactInfo contact = contactStore.getContact(number); if (contact == null) { return ""; } else { return contact.name; } }
Source:
<code>private Object getJSONValue(String val) throws DatabaseEngineException { try { PGobject dataObject = new PGobject(); dataObject.setType("jsonb"); dataObject.setValue(val); return dataObject; } catch (SQLException ex) { <START> throw new DatabaseEngineException("Error while mapping variables to database", ex); <END> } }</code><technical_language>value, worthwhile including in exception for more context</technical_language>

Target:
private Object getJSONValue(String val) throws DatabaseEngineException { try { PGobject dataObject = new PGobject(); dataObject.setType("jsonb"); dataObject.setValue(val); return dataObject; } catch (SQLException ex) { throw new DatabaseEngineException("Error while mapping variables to database, value = " + val, ex); } }
Source:
<code>private boolean isAttrCopy(StatementTree statement) { return statement.is(Kind.EXPRESSION_STATEMENT) <START> && ((ExpressionStatementTree) statement).expression().is(Kind.ASSIGNMENT) <END> && ((AssignmentExpressionTree) ((ExpressionStatementTree) statement).expression()).variable() instanceof MemberExpressionTree; }</code><technical_language>@vilchik-elena Style: I created a variable for (ExpressionStatementTree) statement).expression()</technical_language>

Target:
private static boolean isAttrCopy(StatementTree statement) { if (statement.is(Kind.EXPRESSION_STATEMENT)) { Tree expression = ((ExpressionStatementTree) statement).expression(); if (expression.is(Kind.ASSIGNMENT)) { AssignmentExpressionTree assignment = (AssignmentExpressionTree) expression; return assignment.variable().is(Kind.BRACKET_MEMBER_EXPRESSION); } } return false; }
Source:
<code>public void walkTree(final IResourceVisitor visitor) throws IOException { if (!exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } if (!file.isDirectory()) { return; } java.nio.file.Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { <START> visitor.visitResource( <END> getResource(dir.toFile(), attrs), NIOFileResource.this.file.toPath().relativize(dir).toString() ); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { visitor.visitResource( getResource(file.toFile(), attrs), NIOFileResource.this.file.toPath().relativize(file).toString() ); return FileVisitResult.CONTINUE; } }); }</code><technical_language>This needs check for empty name (because callback is called for top level directory) String name = NIOFileResource.this.file.toPath().relativize(dir).toString(); if (name.length() > 0) { visitor.visitResource( getResource(dir.toFile(), attrs), name ); }</technical_language>

Target:
public void walkTree(final IResourceVisitor visitor) throws IOException { if (!exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } if (!file.isDirectory()) { return; } java.nio.file.Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { String name = NIOFileResource.this.file.toPath().relativize(dir).toString(); boolean cont = true; if (name.length() > 0) { cont = visitor.visitResource( getResource(dir.toFile(), attrs), NIOFileResource.this.file.toPath().relativize(dir).toString().replace("\\", "/") ); } return cont ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { visitor.visitResource( getResource(file.toFile(), attrs), NIOFileResource.this.file.toPath().relativize(file).toString().replace("\\", "/") ); return FileVisitResult.CONTINUE; } }); }
Source:
<code><START> public int hashCode() { <END> return a.hashCode() + 31 * b.hashCode(); }</code><technical_language>break if A B is null. Recommend autogenerated intellij equals + hashcode a good reason</technical_language>

Target:
public int hashCode() { int result = a != null ? a.hashCode() : 0; result = 31 * result + (b != null ? b.hashCode() : 0); return result; }
Source:
<code>public final Document asXml() { final Document document = DocumentHelper.createDocument(); <START> final FindBugsExcludes.ExcludesXml xml = new FindBugsExcludes.ExcludesXml( <END> document.addElement("FindBugsFilter") ); this.env.excludes("findbugs").stream().forEach(xml::addExclude); return document; }</code><technical_language>@ilyakharlamov Please indent need LineLengthCheck</technical_language>

Target:
public final Document asXml() { try { final Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .newDocument(); final FindBugsExcludes.Xml xml = new FindBugsExcludes.Xml(doc); final Node root = doc.appendChild( doc.createElement("FindBugsFilter") ); this.env.excludes("findbugs").stream() .map(Pattern.compile(":")::split) .map(xml::createMatchNode) .filter(Node::hasChildNodes) .forEach(root::appendChild); return doc; } catch (final ParserConfigurationException exc) { throw new IllegalStateException(exc); } }
Source:
<code><START> private File getSaveFileName() { <END> return new File(TasksUiPlugin.getDefault().getDataDirectory(), SAVE_DIR); }</code><technical_language>Rename this method; returning a file name. returning a File</technical_language>

Target:
private File getSaveFileName() { return new File(dataDirectory, SAVE_DIR); }
Source:
<code>public List<CommitValidationMessage> onCommitReceived( CommitReceivedEvent receiveEvent) throws CommitValidationException { try { PersonIdent committer = receiveEvent.commit.getCommitterIdent(); ServiceUserInfo serviceUser = serviceUserResolver.getAsServiceUser(committer); if (serviceUser.owner != null && serviceUserResolver.listActiveOwners(serviceUser).isEmpty()) { throw new CommitValidationException(String.format( "Commit %s of service user %s (%s) is rejected because " + <START> "the accounts of all service user owners are inactive.", <END> receiveEvent.commit.getId().getName(), committer.getName(), committer.getEmailAddress())); } else { AccountState creator = accountCache.get(serviceUser.createdBy._id); if (creator == null || !creator.getAccount().isActive()) { throw new CommitValidationException(String.format( "Commit %s of service user %s (%s) is rejected because " + "the account of the service creator is inactive.", receiveEvent.commit.getId().getName(), committer.getName(), committer.getEmailAddress())); } } } catch (OrmException e) { throw new CommitValidationException( "Internal error while checking for service user commits.", e); } return Collections.emptyList(); }</code><technical_language>"all service user owner accounts inactive"</technical_language>

Target:
public List<CommitValidationMessage> onCommitReceived( CommitReceivedEvent receiveEvent) throws CommitValidationException { try { PersonIdent committer = receiveEvent.commit.getCommitterIdent(); ServiceUserInfo serviceUser = serviceUserResolver.getAsServiceUser(committer); if (serviceUser.owner != null && serviceUserResolver.listActiveOwners(serviceUser).isEmpty()) { throw new CommitValidationException(String.format( "Commit %s of service user %s (%s) is rejected because " + "all service user owner accounts are inactive.", receiveEvent.commit.getId().getName(), committer.getName(), committer.getEmailAddress())); } else { AccountState creator = accountCache.get(serviceUser.createdBy._id); if (creator == null || !creator.getAccount().isActive()) { throw new CommitValidationException(String.format( "Commit %s of service user %s (%s) is rejected because " + "the account of the service creator is inactive.", receiveEvent.commit.getId().getName(), committer.getName(), committer.getEmailAddress())); } } } catch (OrmException e) { throw new CommitValidationException( "Internal error while checking for service user commits.", e); } return Collections.emptyList(); }
Source:
<code>private static String sanitizeWord(String word) { String result = word; String[] splitWord = word.split("-"); if (splitWord.length > 1) { for (int i = splitWord.length - 1; i >= 0; i--) { <START> if (!splitWord[i].trim().equals("") && !splitWord[i].trim().equals(null)) { <END> return splitWord[i]; } } } return result; }</code><technical_language>I 2nd condition is necessary trim return a null-value. (If could, 1st condition throw a NullPointerException. Therefore, I recommend writing !"".equals(splitWord[i].trim()))</technical_language>

Target:
private static String sanitizeWord(String word) { String result = word; String[] splitWord = word.split("-"); if (splitWord.length > 1) { for (int i = splitWord.length - 1; i >= 0; i--) { if (splitWord[i] != null && !"".equals(splitWord[i].trim())) { return splitWord[i]; } } } return result; }
Source:
<code>PhoneNumberAsyncClient(PhoneNumberAdminClientImpl phoneNumberAdminClient) { <START> this.phoneNumberAdminClient = phoneNumberAdminClient; <END> }</code><technical_language>APIs in this class phoneNumberAdminClient.getAdministrations(). So, simpler Administrations type instance variable</technical_language>

Target:
PhoneNumberAsyncClient(PhoneNumberAdminClientImpl phoneNumberAdminClient) { this.phoneNumberAdministrations = phoneNumberAdminClient.getPhoneNumberAdministrations(); }
Source:
<code>public void testCurveSrs26713() throws IOException { try (InputStream is = open("/curve-eps26713.xml")) { WfsFeatureCollection wfc = (WfsFeatureCollection) getxStream().fromXML(is); assertThat(wfc.getFeatureMembers(), hasSize(1)); assertThat( wfc.getFeatureMembers().get(0).getLocation(), is( <START> "LINESTRING (598566.26906782 4914058.52150682, 598557.69477679 4914085.33977038, 598494.67747205 4914254.76475676, 598513.91541973 4914348.11723536, 598593.95441378 4914440.37147034, 598656.43584271 4914500.87603708, 598659.42742456 4914521.61846645, 598652.10605456 4914532.58195028, 598648.43115534 4914544.16261933, 598635.63083991 4914558.16462797, 598554.58586588 4914636.67913744, 598498.3814486 4914752.4469346, 598489.81000042 4914778.04541272, 598421.49284933 4914873.66244196, 598409.19817361 4914931.57794141, 598404.90249957 4914948.64642947, 598340.17638384 4915068.66645978, 598342.49317686 4915118.07263127, 598346.0824185 4915117.02463364, 598566.26906782 4914058.52150682)")); <END> } }</code><technical_language>A worrisome update a test here. code broken before</technical_language>

Target:
public void testCurveSrs26713() throws IOException { try (InputStream is = open("/curve-eps26713.xml")) { Metacard metacard = (Metacard) getxStream().fromXML(is); assertThat( metacard.getLocation(), is( "MULTILINESTRING ((598566.26906782 4914058.52150682, 598557.69477679 4914085.33977038, 598494.67747205 4914254.76475676, 598513.91541973 4914348.11723536, 598593.95441378 4914440.37147034, 598656.43584271 4914500.87603708, 598659.42742456 4914521.61846645, 598652.10605456 4914532.58195028, 598648.43115534 4914544.16261933, 598635.63083991 4914558.16462797, 598554.58586588 4914636.67913744, 598498.3814486 4914752.4469346, 598489.81000042 4914778.04541272, 598421.49284933 4914873.66244196, 598409.19817361 4914931.57794141, 598404.90249957 4914948.64642947, 598340.17638384 4915068.66645978, 598342.49317686 4915118.07263127, 598346.0824185 4915117.02463364, 598566.26906782 4914058.52150682))")); } }
Source:
<code>public void should_be_able_to_read_asset() throws FileNotFoundException { Map<String, Object> options = OptionsBuilder.options().safe(SafeMode.SAFE) .attributes(AttributesBuilder.attributes().dataUri(false)) .compact(true).asMap(); Document document = asciidoctor.load(DOCUMENT, options); File inputFile = classpath.getResource("rendersample.asciidoc"); String content = document.readAsset(inputFile.getAbsolutePath(), new HashMap<Object, Object>()); <START> assertThat(content, is(IOUtils.readFull(new FileReader(inputFile)).replaceAll("\r","\\"))); <END> }</code><technical_language>Actually, want avoid this type of hack, in tests. I looked implementation of IOUtils.readFull strange me. Java reading file systems, not</technical_language>

Target:
public void should_be_able_to_read_asset() throws FileNotFoundException { Map<String, Object> options = OptionsBuilder.options().safe(SafeMode.SAFE) .attributes(AttributesBuilder.attributes().dataUri(false)) .compact(true).asMap(); Document document = asciidoctor.load(DOCUMENT, options); File inputFile = classpath.getResource("rendersample.asciidoc"); String content = document.readAsset(inputFile.getAbsolutePath(), new HashMap<Object, Object>()); assertThat(content, is(IOUtils.readFull(new FileReader(inputFile)))); }
Source:
<code>public void getHighestUid_imapConnectionThrowsIOException_shouldThrowMessagingException() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = singletonList(createImapResponse("* SEARCH 42")); when(imapConnection.executeSimpleCommand("UID SEARCH *:*")) .thenThrow(IOException.class); folder.open(OPEN_MODE_RW); try { <START> folder.getHighestUid(); <END> } catch (MessagingException e) { assertEquals("IO Error", e.getMessage()); } }</code><technical_language>missing a failure assertion</technical_language>

Target:
public void getHighestUid_imapConnectionThrowsIOException_shouldThrowMessagingException() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); when(imapConnection.executeSimpleCommand("UID SEARCH *:*")) .thenThrow(IOException.class); folder.open(OPEN_MODE_RW); try { folder.getHighestUid(); fail("Expected MessagingException"); } catch (MessagingException e) { assertEquals("IO Error", e.getMessage()); } }
Source:
<code>public Map<String, SearchSourceBuilder> build() { for (final EventQuery event_query : query.eventQueries()) { SearchSourceBuilder search_source_builder = new SearchSourceBuilder(); if (query.isSummary()) { <START> System.out.println("HERE123"); <END> search_source_builder.aggregation(bucketsAgg(event_query.filter(), query.interval())); search_source_builder.size(0); } else { search_source_builder.from(query.from()); search_source_builder.size(query.to() - query.from()); } if (event_query.filter() != null) { search_source_builder.query(setFilter(event_query.filter())); } search_source_builders.put(event_query.namespace().toLowerCase(), search_source_builder); } return search_source_builders; }</code><technical_language>lots of cleanup</technical_language>

Target:
public Map<String, SearchSourceBuilder> build() { for (final EventQuery event_query : query.eventQueries()) { SearchSourceBuilder search_source_builder = new SearchSourceBuilder(); if (query.isSummary()) { search_source_builder.aggregation(bucketsAgg(event_query.filter(), query.interval())); search_source_builder.size(0); } else { search_source_builder.from(query.from()); search_source_builder.size(query.to() - query.from()); } QueryBuilder builder = timeFilter(query.startTimestamp(), query .endTimestamp()); if (event_query.namespace()!=null) { ((BoolQueryBuilder) builder).must((setFilter(EventLiteralOrFilter.newBuilder ().setField("namespace.lowercase").setFilter(event_query.namespace ().toLowerCase()).build() ))); } if (event_query.filter() != null) { search_source_builder.query(((BoolQueryBuilder) builder).must(setFilter (event_query.filter()))); } search_source_builders.put(event_query.namespace().toLowerCase(), search_source_builder); } return search_source_builders; }
Source:
<code>public void createRulesTest() { RulesDefinition.Repository repository = buildRepository(); assertThat(repository).isNotNull(); assertThat(repository.language()).isEqualTo("py"); assertThat(repository.name()).isEqualTo("SonarAnalyzer"); List<RulesDefinition.Rule> rules = repository.rules(); assertThat(rules).isNotNull(); <START> assertThat(rules).hasSize(66); <END> RulesDefinition.Rule s1578 = repository.rule("S1578"); assertThat(s1578).isNotNull(); assertThat(s1578.activatedByDefault()).isFalse(); RulesDefinition.Rule backstickUsage = repository.rule("BackticksUsage"); assertThat(backstickUsage).isNotNull(); assertThat(backstickUsage.activatedByDefault()).isTrue(); }</code><technical_language>change test, cumbersome implement rules in parallel</technical_language>

Target:
public void createRulesTest() { RulesDefinition.Repository repository = buildRepository(); assertThat(repository).isNotNull(); assertThat(repository.language()).isEqualTo("py"); assertThat(repository.name()).isEqualTo("SonarAnalyzer"); List<RulesDefinition.Rule> rules = repository.rules(); assertThat(rules).isNotNull(); assertThat(rules).hasSize(67); RulesDefinition.Rule s1578 = repository.rule("S1578"); assertThat(s1578).isNotNull(); assertThat(s1578.activatedByDefault()).isFalse(); RulesDefinition.Rule backstickUsage = repository.rule("BackticksUsage"); assertThat(backstickUsage).isNotNull(); assertThat(backstickUsage.activatedByDefault()).isTrue(); }
Source:
<code>protected TmfTimestamp getInitialRangeOffset() { <START> final long DEFAULT_INITIAL_OFFSET_VALUE = (1L * 100 * 1000 * 1000); END> final int DEFAULT_INITIAL_OFFSET_SCALE = -9; return new TmfTimestamp(DEFAULT_INITIAL_OFFSET_VALUE, DEFAULT_INITIAL_OFFSET_SCALE); }</code><technical_language>constant ITmfTimestamp for nano seconds instead of hardcoded of -9</technical_language>

Target:
protected TmfTimestamp getInitialRangeOffset() { final long DEFAULT_INITIAL_OFFSET_VALUE = (1L * 100 * 1000 * 1000); return new TmfTimestamp(DEFAULT_INITIAL_OFFSET_VALUE, ITmfTimestamp.NANOSECOND_SCALE); }
Source:
<code>private void showLint(LintContext context, JsArray<LintItem> lint) <START> { <END> JsArray<LintItem> finalLint; if (context.excludeCurrentStatement && docDisplay_.getCursorPosition().isEqualTo(context.cursorPosition)) { finalLint = JsArray.createArray().cast(); Position pos = context.cursorPosition; for (int i = 0; i < lint.length(); i++) if (!lint.get(i).asRange().contains(pos)) finalLint.push(lint.get(i)); } else finalLint = lint; if (uiPrefs_.realTimeSpellChecking().getValue() && TypoSpellChecker.isLoaded()) { JsArray<LintItem> spellingLint = target_.getSpellingTarget().getLint(); for (int i = 0; i < spellingLint.length(); i++) { finalLint.push(spellingLint.get(i)); } } docDisplay_.showLint(finalLint); }</code><technical_language>I recall this code worth confirming this interfere e.g. autocompletion popup menus (e.g. if start typing something, press <TAB> request completions popup menu is shown -- if lint shown time?)</technical_language>

Target:
private void showLint(LintContext context, JsArray<LintItem> lint) { if (docDisplay_.isPopupVisible()) return; JsArray<LintItem> finalLint; if (context.excludeCurrentStatement && docDisplay_.getCursorPosition().isEqualTo(context.cursorPosition)) { finalLint = JsArray.createArray().cast(); Position pos = context.cursorPosition; for (int i = 0; i < lint.length(); i++) if (!lint.get(i).asRange().contains(pos)) finalLint.push(lint.get(i)); } else finalLint = lint; if (uiPrefs_.realTimeSpellChecking().getValue() && TypoSpellChecker.isLoaded()) { JsArray<LintItem> spellingLint = target_.getSpellingTarget().getLint(); for (int i = 0; i < spellingLint.length(); i++) { finalLint.push(spellingLint.get(i)); } } docDisplay_.showLint(finalLint); }
Source:
<code>public void setUp() throws Exception { createProject(); <START> baseActivityTestRule.launchActivity(null); <END> }</code><technical_language>please baseActivityTestRule.launchActivity() (without "null")</technical_language>

Target:
public void setUp() throws Exception { createProject(); baseActivityTestRule.launchActivity(); }
Source:
<code><START> public String getPublicKey() { <END> InstanceIdentityProvider<RSAPublicKey, RSAPrivateKey> provider = InstanceIdentityProvider.get(RSAPrivateKey.class); RSAPublicKey key = provider == null ? null : provider.getPublicKey(); if (key == null) { return null; } byte[] encoded = Base64.encodeBase64(key.getEncoded()); int index = 0; StringBuilder buf = new StringBuilder(encoded.length + 20); while (index < encoded.length) { int len = Math.min(64, encoded.length - index); if (index > 0) { buf.append("\n"); } buf.append(new String(encoded, index, len, Charsets.UTF_8)); index += len; } return String.format("-----BEGIN PUBLIC KEY-----%n%s%n-----END PUBLIC KEY-----%n", buf.toString()); }</code><technical_language>ant: Deserves a functional test</technical_language>

Target:
public String getPublicKey() { RSAPublicKey key = InstanceIdentityProvider.RSA.getPublicKey(); if (key == null) { return null; } byte[] encoded = Base64.encodeBase64(key.getEncoded()); int index = 0; StringBuilder buf = new StringBuilder(encoded.length + 20); while (index < encoded.length) { int len = Math.min(64, encoded.length - index); if (index > 0) { buf.append("\n"); } buf.append(new String(encoded, index, len, Charsets.UTF_8)); index += len; } return String.format("-----BEGIN PUBLIC KEY-----%n%s%n-----END PUBLIC KEY-----%n", buf.toString()); }