auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Supplier<URI> provideStorageUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion, @Named(LocationConstants.PROPERTY_REGION) String region) { //Get the URI's keyed by their region name Supplier<Map<String, Supplier<URI>>> endpointsSupplier = factory.createForApiTypeAndVersion(ServiceType.OBJECT_STORE, apiVersion); //Pick the matching region name (if any) otherwise just return an arbitrary URL if no region name is set //NOTE: The region string should never be null (it can be empty) if this object was instantiated via guice // as it pulls these named strings from a Properties object. That being said, there's no real reason we // should treat a null string differently to an empty string. START if (!Strings.isNullOrEmpty(region)) { END return getValueInMapOrNull(endpointsSupplier, region); } else { return getLastValueInMap(endpointsSupplier); } } If `region` cannot be `null`, how about just `if (!region.equals("")...`..?

Target:
protected Supplier<URI> provideStorageUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion, @Named(LocationConstants.PROPERTY_REGION) String region) { //Get the URI's keyed by their region name Supplier<Map<String, Supplier<URI>>> endpointsSupplier = factory.createForApiTypeAndVersion(ServiceType.OBJECT_STORE, apiVersion); //Pick the matching region name (if any) otherwise just return an arbitrary URL if no region name is set //NOTE: The region string should never be null (it can be empty) if this object was instantiated via guice // as it pulls these named strings from a Properties object. if (region.isEmpty()) { return getLastValueInMap(endpointsSupplier); } else { return getValueInMapOrNull(endpointsSupplier, region); } }
Source:
public void handle(Exception exception) { if (exception instanceof IllegalArgumentException START || exception instanceof IllegalStateException) { END throw new InterceptionException(exception); } if (exception instanceof ReflectionProviderException) { throwIfNotValidationException(exception, exception.getCause()); } throwIfNotValidationException(exception, exception); } I'm almost tending to use VRaptor specific exceptions for this case, instead of reusing IllegalArg and IllegalState... We're doing this only because of validations, right? We could create a ValidationFailedException.

Target:
public void handle(Exception exception) { if (exception instanceof ReflectionProviderException) { throwIfNotValidationException(exception, exception.getCause()); } throwIfNotValidationException(exception, exception); }
Source:
protected boolean replay(Exception e) { ExceptionRecorder<Result> exresult = exceptions.findByException(e); if (exresult == null) { return false; } reportException(e); START logger.debug("handling exception {}", e); END exresult.replay(result); return true; } maybe you should do `logger.debug("handling exception {}", e.getClass(), e);`, which would print the stacktrace after "Handling exception BazingaException".

Target:
protected boolean replay(Exception e) { ExceptionRecorder<Result> exresult = exceptions.findByException(e); if (exresult == null) { return false; } reportException(e); logger.debug("handling exception {}", e.getClass(), e); exresult.replay(result); return true; }
Source:
public static ControllerMethod instanceFor(Class<?> type, Method method) { START CDIProxies.extractRawTypeIfPossible(type); END return new DefaultControllerMethod(new DefaultBeanClass(type), method); } Use `tabs` instead of `spaces`.

Target:
public static ControllerMethod instanceFor(Class<?> type, Method method) { type = extractRawTypeIfPossible(type); return new DefaultControllerMethod(new DefaultBeanClass(type), method); }
Source:
public void setup() throws Exception { contexts.startRequestScope(); contexts.startSessionScope(); START contexts.startApplicationScope(); END initEvent.fire(new VRaptorInitialized(null)); super.setup(); } shouldn't it be started from largest scope to smallest?

Target:
public void setup() throws Exception { contexts.startApplicationScope(); contexts.startSessionScope(); initEvent.fire(new VRaptorInitialized(null)); super.setup(); }
Source:
public <T extends View> T onErrorUse(Class<T> view) { if (!hasErrors()) { return new MockResult(proxifier).use(view); //ignore anything, no errors occurred } result.include("errors", getErrors()); outjector.outjectRequestMap(); START logger.debug("there are errors on result: {}", messages.handleErrors()); END return viewsFactory.instanceFor(view, messages.handleErrors()); } it includes `getErrors()` to the view, but now we're logging `messages.handleErrors()`. Is it right?

Target:
public <T extends View> T onErrorUse(Class<T> view) { if (!hasErrors()) { return new MockResult(proxifier).use(view); //ignore anything, no errors occurred } result.include("errors", getErrors()); outjector.outjectRequestMap(); logger.debug("there are errors on result: {}", getErrors()); return viewsFactory.instanceFor(view, messages.handleErrors()); }
Source:
public void shouldDelegateToStatusOnPermanentlyRedirectToControllerInstance() throws Exception { Status status = mockResult(Status.class); result.permanentlyRedirectTo(new RandomController()); verify(status).movedPermanentlyTo(RandomController.class); START verify(messages).assertAbsenceOfErrors(); END } leave this verify only for the method which is checking this behavior. No need to repeat it on all.

Target:
public void shouldDelegateToStatusOnPermanentlyRedirectToControllerInstance() throws Exception { Status status = mockResult(Status.class); result.permanentlyRedirectTo(new RandomController()); verify(status).movedPermanentlyTo(RandomController.class); }
Source:
public XMLSerialization indented() { START indented = environment.get(ENVIRONMENT_INDENTED_KEY, "true").equalsIgnoreCase("true"); END return this; } although it will throw an exception if the key is not found. I guess we could change the supports method to return false if the key doesn't exist.

Target:
public XMLSerialization indented() { indented = true; return this; }
Source:
public void shouldReturnEmptyList() { when(dao.searchSimilarTitle(music.getTitle())).thenReturn(new ArrayList<Music>()); controller.search(music); List<Music> musics = (List<Music>) result.included().get("musics"); Assert.assertTrue(musics.isEmpty()); START } END `assertThat(musics, empty())`

Target:
public void shouldReturnEmptyList() { when(dao.searchSimilarTitle(music.getTitle())).thenReturn(new ArrayList<Music>()); controller.search(music); List<Music> musics = (List<Music>) result.included().get("musics"); assertThat(musics, empty()); }
Source:
public void shouldAddUser() { controller.add(user); verify(userDao).add(user); assertEquals("User " + user.getName() + " successfully added", result.included().get("notice")); START } END `assertThat(result.included().get("notice"), "User " + user.getName() + " successfully added")` Yes, `assertThat` have inverted parameters unlike another JUnit methods.

Target:
public void shouldAddUser() { controller.add(user); verify(userDao).add(user); assertThat(result.included().get("notice").toString(), is("User " + user.getName() + " successfully added")); }
Source:
private Predicate<String> currentOrSubpackage(final String controllerPackageName) { return new Predicate<String>() { @Override public boolean apply(String input) { START return controllerPackageName.contains(input); END } }; } I'd write a simple test case to make sure (if not already there), but makes sence to use `startsWith`

Target:
private Predicate<String> currentOrSubpackage(final String controllerPackageName) { return new Predicate<String>() { @Override public boolean apply(String input) { return controllerPackageName.startsWith(input); } }; }
Source:
public String get(InjectionPoint ip) { Annotated annotated = ip.getAnnotated(); START Property property = annotated.getAnnotation(Property.class); END String key = property.value(); if (isNullOrEmpty(key)) key = ip.getMember().getName(); return environment.get(key); } :sadpanda:

Target:
public String get(InjectionPoint ip) { Annotated annotated = ip.getAnnotated(); Property property = annotated.getAnnotation(Property.class); String key = property.value(); if (isNullOrEmpty(key)) { key = ip.getMember().getName(); } return environment.get(key); }
Source:
public <T> T instanceFor(Class<T> type) { type = (Class<T>) Proxies.extractRawType(type); START logger.debug("asking cdi to get instance for {}", type); END Bean<?> bean = getBeanFrom(type); CreationalContext<?> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, type, ctx); } you could _extract method_ here, to avoid duplicated code on `instanceFor` and `canProvide` methods (just like `type = extractRawType(type)`) or just add this 2 lines on `getBeanFrom`

Target:
public <T> T instanceFor(Class<T> type) { Bean<?> bean = getBeanFrom(type); CreationalContext<?> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, type, ctx); }
Source:
public void setControllerMethod(ControllerMethod controllerMethod) { START createValuedParameter(controllerMethod); END this.controllerMethod = controllerMethod; } I think this method should be called on `getValuedParameters` because even if i'll never use, it always create valued parameters when VRaptor sets ControllerMethod (and to create this, we use `parameterNameProvider`, etc... it is kind of expensive). Maybe a simple lazy strategy: ``` Java if (valuedParameters != null) createValuedParameter(controllerMethod); ```

Target:
public void setControllerMethod(ControllerMethod controllerMethod) { this.controllerMethod = controllerMethod; }
Source:
START public LocaleBasedPrimitiveDoubleConverter() { END } protected

Target:
public LocaleBasedPrimitiveDoubleConverter() { this(null); }
Source:
private void addRedirectListener() { response.addRedirectListener(new MutableResponse.RedirectListener() { @Override public void beforeRedirect() { if (!validator.hasErrors() && entityManager.getTransaction().isActive()) { START entityManager.getTransaction().commit(); END } } }); } Change to commit();

Target:
private void addRedirectListener() { response.addRedirectListener(new MutableResponse.RedirectListener() { @Override public void beforeRedirect() { commit(entityManager.getTransaction()); } }); }
Source:
public void intercept(SimpleInterceptorStack stack) { addRedirectListener(); EntityTransaction transaction = null; try { transaction = entityManager.getTransaction(); transaction.begin(); stack.next(); if (!validator.hasErrors() && transaction.isActive()) { transaction.commit(); START } END } finally { if (transaction != null && transaction.isActive()) { transaction.rollback(); } } } Change to commit();

Target:
public void intercept(SimpleInterceptorStack stack) { addRedirectListener(); EntityTransaction transaction = null; try { transaction = entityManager.getTransaction(); transaction.begin(); stack.next(); commit(transaction); } finally { if (transaction != null && transaction.isActive()) { transaction.rollback(); } } }
Source:
@Override void apply(RequestBuilder builder, @Nullable Object value) { try { checkNotNull(value, "@Url parameter is null."); START } catch (NullPointerException npe) { END throw Utils.parameterError(method, npe, p, "@Url parameter is null."); } builder.setRelativeUrl(value); } There's no need to do this. We can just check for null locally and pass null as the cause to the `Utils` method.

Target:
@Override void apply(RequestBuilder builder, @Nullable Object value) { if (value == null) { throw Utils.parameterError(method, p, "@Url parameter is null."); } builder.setRelativeUrl(value); }
Source:
Part(Method method, int p, Headers headers, Converter<T, RequestBody> converter) { this.headers = headers; this.converter = converter; this.method = method; START this.p = p; END } Can we make the field order and statement order match the constructor argument order?

Target:
Part(Method method, int p, Headers headers, Converter<T, RequestBody> converter) { this.method = method; this.p = p; this.headers = headers; this.converter = converter; }
Source:
Path(Method method, int p, String name, Converter<T, String> valueConverter, boolean encoded) { START this.name = checkNotNull(name, "name == null"); END this.valueConverter = valueConverter; this.encoded = encoded; this.method = method; this.p = p; } If they're impossible we actually usually prefer `AssertionError`. I would leave them as-is because they should never be observable by users.

Target:
Path(Method method, int p, String name, Converter<T, String> valueConverter, boolean encoded) { this.method = method; this.p = p; this.name = checkNotNull(name, "name == null"); this.valueConverter = valueConverter; this.encoded = encoded; }
Source:
static Type getParameterLowerBound(int index, ParameterizedType type) { Type[] types = type.getActualTypeArguments(); if (index < 0 || index >= types.length) { START throw new IllegalArgumentException( END "Index " + index + " not in range [0," + types.length + ") for " + type); } Type paramType = types[index]; if (paramType instanceof WildcardType) { return ((WildcardType) paramType).getLowerBounds()[0]; } return paramType; } Just let the regular array bounds checking do this?

Target:
static Type getParameterLowerBound(int index, ParameterizedType type) { Type paramType = type.getActualTypeArguments()[index]; if (paramType instanceof WildcardType) { return ((WildcardType) paramType).getLowerBounds()[0]; } return paramType; }
Source:
public static <T> Response<T> success(int code, @Nullable T body) { START if (code < 200 || code >= 300) throw new IllegalArgumentException("code < 200 or >= 300: " + code); END return success(body, new okhttp3.Response.Builder() // .code(code) .message("Response.success()") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); } Line too long. Please add `{` and `}` when wrapping.

Target:
public static <T> Response<T> success(int code, @Nullable T body) { if (code < 200 || code >= 300) { throw new IllegalArgumentException("code < 200 or >= 300: " + code); } return success(body, new okhttp3.Response.Builder() // .code(code) .message("Response.success()") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); }
Source:
@Test public void builtInConvertersAbsentInCloneBuilder() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .build(); START assertEquals(retrofit.converterFactories().size() - 1, END retrofit.newBuilder().converterFactories().size()); } should this just assert that it’s empty? Otherwise if we split the built in ones across two factories then this test is wrong

Target:
@Test public void builtInConvertersAbsentInCloneBuilder() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .build(); assertEquals(0, retrofit.newBuilder().converterFactories().size()); }
Source:
void emitError(Throwable t) { set(STATE_TERMINATED); if (!isUnsubscribed()) { try { START if (!isUnsubscribed()) { END subscriber.onError(t); } } catch (Throwable inner) { Exceptions.throwIfFatal(inner); CompositeException composite = new CompositeException(t, inner); RxJavaPlugins.getInstance().getErrorHandler().handleError(composite); } } } This seems redundant? It's checked two lines above

Target:
void emitError(Throwable t) { set(STATE_TERMINATED); if (!isUnsubscribed()) { try { subscriber.onError(t); } catch (Throwable inner) { Exceptions.throwIfFatal(inner); CompositeException composite = new CompositeException(t, inner); RxJavaPlugins.getInstance().getErrorHandler().handleError(composite); } } }
Source:
START private void checkPercentageValidity(int percentage, String message) { END if (percentage < 0 || percentage > 100) { throw new IllegalArgumentException(message); } } +`static`

Target:
private static void checkPercentageValidity(int percentage, String message) { if (percentage < 0 || percentage > 100) { throw new IllegalArgumentException(message); } }
Source:
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { JsonAdapter<?> adapter = moshi.adapter(type, jsonAnnotations(annotations)); if (lenient) { adapter = adapter.lenient(); } if (failOnUnknown) { START adapter.failOnUnknown(); END } return new MoshiResponseBodyConverter<>(adapter); } this would need to be `adapter = adapter.failOnUnknown()`

Target:
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { JsonAdapter<?> adapter = moshi.adapter(type, jsonAnnotations(annotations)); if (lenient) { adapter = adapter.lenient(); } if (failOnUnknown) { adapter = adapter.failOnUnknown(); } return new MoshiResponseBodyConverter<>(adapter); }
Source:
public Builder(Retrofit retrofit) { this.platform = retrofit.platform; this.callFactory = retrofit.callFactory; this.baseUrl = retrofit.baseUrl; START this.converterFactories = retrofit.converterFactories; END this.adapterFactories = retrofit.adapterFactories; this.callbackExecutor = retrofit.callbackExecutor; this.validateEagerly = retrofit.validateEagerly; } All lists should use `addAll` and not retain these unmodifiable references.

Target:
public Builder(Retrofit retrofit) { this.platform = retrofit.platform; this.callFactory = retrofit.callFactory; this.baseUrl = retrofit.baseUrl; this.converterFactories.addAll(retrofit.converterFactories); this.adapterFactories.addAll(retrofit.adapterFactories); this.callbackExecutor = retrofit.callbackExecutor; this.validateEagerly = retrofit.validateEagerly; }
Source:
public MoshiConverterFactory asLenient() { START if (lenient) { END return this; } return create(moshi, true); } I would just delete this `if`. It'll never happen and even if it does it's not that big of a deal to create a new instance.

Target:
public MoshiConverterFactory asLenient() { return new MoshiConverterFactory(moshi, true); }
Source:
@Test public void completableSuccess200() { server.enqueue(new MockResponse().setBody("Hi")); try { service.completable().await(); assertThat(true); } catch (RuntimeException e) { fail(); START } END } You can delete the try/catch and `assertThat`, they don't add value

Target:
@Test public void completableSuccess200() { server.enqueue(new MockResponse().setBody("Hi")); service.completable().await(); }
Source:
START private CompletableCallOnSubscribe(Call originalCall) { END this.originalCall = originalCall; } nit: remove `private` to avoid the need for a synthetic accessor method to be generated

Target:
CompletableCallOnSubscribe(Call originalCall) { this.originalCall = originalCall; }
Source:
@Override public T convert(ResponseBody value) throws IOException { START BufferedSource source = value.source(); END try { return adapter.decode(source); } finally { if (source != null) { try { source.close(); } catch (IOException ignored) { } } } } calling `value.source()` can throw, so this will need split into two lines, variable initialization and retrieving the source–the latter of which is inside the `try` block

Target:
@Override public T convert(ResponseBody value) throws IOException { BufferedSource source = null; try { source = value.source(); return adapter.decode(source); } finally { if (source != null) { try { source.close(); } catch (IOException ignored) { } } } }
Source:
@Override public <R> Observable<Result<R>> adapt(Call<R> call, Retrofit retrofit) { return Observable.create(new CallOnSubscribe<>(call, retrofit)) // START .onErrorReturn(new Func1<Throwable, Result<R>>() { END @Override public Result<R> call(Throwable throwable) { return Result.error(throwable); } }); } This can be removed now.

Target:
@Override public <R> Observable<Result<R>> adapt(Call<R> call, Retrofit retrofit) { return Observable.create(new CallOnSubscribe<>(call, retrofit)); }
Source:
START public static ObservableBehaviorAdapter create() { END return INSTANCE; } Is this an pattern? Weird for create to not create.

Target:
public static ObservableBehaviorAdapter create() { return new ObservableBehaviorAdapter(); }
Source:
public static <T> Call<T> response(final Response<T> response) { return new Call<T>() { @Override public Response<T> execute() throws IOException { return response; } @Override public void enqueue(Callback<T> callback) { callback.onResponse(response); } @Override public void cancel() { } @SuppressWarnings("CloneDoesntCallSuperClone") // Immutable object. @Override public Call<T> clone() { START return response(response); END } }; } return this ?

Target:
public static <T> Call<T> response(final Response<T> response) { return new Call<T>() { @Override public Response<T> execute() throws IOException { return response; } @Override public void enqueue(Callback<T> callback) { callback.onResponse(response); } @Override public void cancel() { } @SuppressWarnings("CloneDoesntCallSuperClone") // Immutable object. @Override public Call<T> clone() { return this; } }; }
Source:
START public synchronized void cancel() { END canceled = true; com.squareup.okhttp.Call rawCall = this.rawCall; if (rawCall != null) { rawCall.cancel(); } } I hate that the use of this ends up in the docs.

Target:
public void cancel() { canceled = true; com.squareup.okhttp.Call rawCall = this.rawCall; if (rawCall != null) { rawCall.cancel(); } }
Source:
@FromJson public AnInterface read(JsonReader jsonReader) throws IOException { jsonReader.beginObject(); String name = null; START while (jsonReader.peek() != JsonReader.Token.END_OBJECT) { END switch (jsonReader.nextName()) { case "name": name = jsonReader.nextString(); break; } } jsonReader.endObject(); return new AnImplementation(name); } `while (jsonReader.hasNext())` ... Unless you're going for symmetry with the other libraries!

Target:
@FromJson public AnInterface read(JsonReader jsonReader) throws IOException { jsonReader.beginObject(); String name = null; while (jsonReader.hasNext()) { switch (jsonReader.nextName()) { case "name": name = jsonReader.nextString(); break; } } jsonReader.endObject(); return new AnImplementation(name); }
Source:
static <T> T checkNotNull(T object, String message, Object... args) { START if (args.length > 0) message = String.format(message, args); END if (object == null) throw new NullPointerException(message); return object; } Don't need to format the message unless `object` is null.

Target:
static <T> T checkNotNull(T object, String message, Object... args) { if (object == null) { throw new NullPointerException(String.format(message, args)); } return object; }
Source:
private static TypedInput createResponseBody(final ResponseBody body) { START if (body == null) { END return null; } return new TypedInput() { @Override public String mimeType() { return body.contentType().toString(); } @Override public long length() { return body.contentLength(); } @Override public InputStream in() throws IOException { return body.byteStream(); } }; } I don't think this is reachable

Target:
private static TypedInput createResponseBody(final ResponseBody body) { if (body.contentLength() == 0) { return null; } return new TypedInput() { @Override public String mimeType() { return body.contentType().toString(); } @Override public long length() { return body.contentLength(); } @Override public InputStream in() throws IOException { return body.byteStream(); } }; }
Source:
START public String toString() { END try { return "TypedString[" + new String(getBytes(), "UTF-8") + "]"; } catch (UnsupportedEncodingException e) { throw new AssertionError("Must be able to decode UTF-8"); } } `@Override`

Target:
@Override public String toString() { try { return "TypedString[" + new String(getBytes(), "UTF-8") + "]"; } catch (UnsupportedEncodingException e) { throw new AssertionError("Must be able to decode UTF-8"); } }
Source:
void addFieldListParams(String name, Iterable<?> values) { if (name == null) { throw new IllegalArgumentException("Field name must not be null."); } if (values == null) { throw new IllegalArgumentException("Field param values must not be null."); } for (Object value : values) { START formBody.addField(name, value.toString()); END } } This will NPE if someone passes a list with `null`. Do we ignore or throw an exception?

Target:
void addFieldListParams(String name, Iterable<?> values) { if (name == null) { throw new IllegalArgumentException("Field name must not be null."); } if (values == null) { throw new IllegalArgumentException("Field param values must not be null."); } for (Object value : values) { if (value != null) { formBody.addField(name, value.toString()); } } }
Source:
public List<byte[]> getParts() throws Exception { START List<byte[]> parts = new ArrayList<byte[]>(); END for (MimePart part : mimeParts) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { part.writeTo(bos); parts.add(bos.toByteArray()); } finally { bos.close(); } } return parts; } Pass `mimeParts.size()` to constructor.

Target:
List<byte[]> getParts() throws IOException { List<byte[]> parts = new ArrayList<byte[]>(mimeParts.size()); for (MimePart part : mimeParts) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); part.writeTo(bos); parts.add(bos.toByteArray()); } return parts; }
Source:
START public String fileName() { END return null; } The `@Override` should be on this line.

Target:
@Override public String fileName() { return null; }
Source:
START public String mimeType() { END return "multipart/form-data; boundary=" + boundary; } The `@Override` should be on this line.

Target:
@Override public String mimeType() { return "multipart/form-data; boundary=" + boundary; }
Source:
START public long length() { END return length; } The `@Override` should be on this line.

Target:
@Override public long length() { return length; }
Source:
START public void writeTo(OutputStream out) throws IOException { END for (MimePart part : mimeParts) { part.writeTo(out); } out.write(footer); } The `@Override` should be on this line.

Target:
@Override public void writeTo(OutputStream out) throws IOException { for (MimePart part : mimeParts) { part.writeTo(out); } out.write(footer); }
Source:
@Test public void arrayIterable() throws Exception { FormUrlEncodedTypedOutput fe = new FormUrlEncodedTypedOutput(); START fe.addField("ping", Arrays.asList(new String[]{"pong", "pong-too"})); END ByteArrayOutputStream out = new ByteArrayOutputStream(); fe.writeTo(out); String actual = new String(out.toByteArray(), "UTF-8"); assertThat(actual).isEqualTo("ping=pong&ping=pong-too"); } Drop `new String[]` as above.

Target:
@Test public void arrayIterable() throws Exception { FormUrlEncodedTypedOutput fe = new FormUrlEncodedTypedOutput(); fe.addField("ping", Arrays.asList("pong", "pong-too")); ByteArrayOutputStream out = new ByteArrayOutputStream(); fe.writeTo(out); String actual = new String(out.toByteArray(), "UTF-8"); assertThat(actual).isEqualTo("ping=pong&ping=pong-too"); }
Source:
@Override public void addPathParam(String name, String value) { START boolean disableUrlEncoding = false; END addPathParam(name, value, disableUrlEncoding); } While I appreciate the explicit-ness, I'd rather this value just be inlined into the method call. If you want to be specific you can do: ``` java addPathParam(name, value, false /* do not URL encode */); ```

Target:
@Override public void addPathParam(String name, String value) { addPathParam(name, value, true); }
Source:
public ApacheClient() { this(new DefaultHttpClient()); DefaultHttpClient client = (DefaultHttpClient) this.client; START this.redirectHandler = new RedirectHandler(); END client.setRedirectHandler(this.redirectHandler); } Drop the `this` on this and the next line.

Target:
public ApacheClient() { this(new DefaultHttpClient()); }
Source:
void addPart(String name, TypedOutput body) { if (name == null) { throw new NullPointerException("Part name must not be null."); } if (body == null) { throw new NullPointerException("Part body must not be null."); } boolean first = (parts.size() == 0); START byte[] part = buildPart(name, body, first); END parts.add(part); length += part.length; } Replace `first` with `parts.isEmpty()`

Target:
void addPart(String name, TypedOutput body) { if (name == null) { throw new NullPointerException("Part name must not be null."); } if (body == null) { throw new NullPointerException("Part body must not be null."); } byte[] part = buildPart(name, body, parts.isEmpty()); parts.add(part); length += part.length; }
Source:
public static Method getMethod(Class c, String name) { START Method[] methods = c.getDeclaredMethods(); END for (Method method : methods) { if (method.getName().equals(name)) { return method; } } throw new IllegalArgumentException("Unknown method '" + name + "' on " + c); } inline?

Target:
public static Method getMethod(Class c, String name) { for (Method method : c.getDeclaredMethods()) { if (method.getName().equals(name)) { return method; } } throw new IllegalArgumentException("Unknown method '" + name + "' on " + c); }
Source:
public static boolean isBeginningOfEntity(String label) { return StringUtils.startsWith(label, TaggingLabels.GROBID_START_ENTITY_LABEL_PREFIX) || StringUtil.startsWith(label, TaggingLabels.IOB_START_ENTITY_LABEL_PREFIX) START || StringUtil.startsWith(label, TaggingLabels.ENAMEX_START_ENTITY_LABEL_PREFIX); END } This method will fail with `IOB_INSIDE_LABEL_PREFIX` returning `true` for `isBeginningOfEntity()` while it is not the beginning of an entity. Problem `IOB_INSIDE_LABEL_PREFIX` == `GROBID_START_ENTITY_LABEL_PREFIX` == "I-". Normally this method should not be called with IOB labels... but not 100% sure.

Target:
public static boolean isBeginningOfEntity(String label) { return StringUtils.startsWith(label, TaggingLabels.GROBID_START_ENTITY_LABEL_PREFIX) || StringUtil.startsWith(label, TaggingLabels.ENAMEX_START_ENTITY_LABEL_PREFIX); }
Source:
public void processingReferenceSection() throws Exception { String text = "(1) Ahrens, M. Home fires that began with upholstered furniture; National Fire Protection Association: Quincy, Massachusetts, 2011.\n" + "(2) Evarts, B. Home fires that began with matresses and bedding; National Fire Protection Association: Quincy, Massachusetts, 2011.\n" + "(3) Kramer, R. H.; Zammarano, M.; Linteris, G. T.; Gedde, U. W.; Gilman, J. W. Polym. Degrad. Stab. 2010, 95, 1115−1122.\n" + "(4) Underwriter Laboratories, UL test: Legacy home contents and new content fires, YouTube online video clip, 2011.\n" + "(5) Gallagher, S.; Campbell, J. In Siloxane-Phosphonate Finishes on Cellulose: Thermal Characterization and Flammability Data; Proceed-ings of the Beltwide Cotton Conference, San Antonio, TX, 2004; pp 2443-2847.\n" + "(6) Watanabe, I.; Sakai, S. Environ. Int. 2003, 29, 665−682. (7) Babrauskas, V.; Blum,\n"; List<BibDataSet> res = engine.getParsers().getCitationParser().processingReferenceSection(text, engine.getParsers().getReferenceSegmenterParser()); assertNotNull(res); START System.out.println(res); END assertTrue(res.size() > 2); } remove this println please ;-)

Target:
public void processingReferenceSection() throws Exception { String text = "(1) Ahrens, M. Home fires that began with upholstered furniture; National Fire Protection Association: Quincy, Massachusetts, 2011.\n" + "(2) Evarts, B. Home fires that began with matresses and bedding; National Fire Protection Association: Quincy, Massachusetts, 2011.\n" + "(3) Kramer, R. H.; Zammarano, M.; Linteris, G. T.; Gedde, U. W.; Gilman, J. W. Polym. Degrad. Stab. 2010, 95, 1115−1122.\n" + "(4) Underwriter Laboratories, UL test: Legacy home contents and new content fires, YouTube online video clip, 2011.\n" + "(5) Gallagher, S.; Campbell, J. In Siloxane-Phosphonate Finishes on Cellulose: Thermal Characterization and Flammability Data; Proceed-ings of the Beltwide Cotton Conference, San Antonio, TX, 2004; pp 2443-2847.\n" + "(6) Watanabe, I.; Sakai, S. Environ. Int. 2003, 29, 665−682. (7) Babrauskas, V.; Blum,\n"; List<BibDataSet> res = engine.getParsers().getCitationParser().processingReferenceSection(text, engine.getParsers().getReferenceSegmenterParser()); assertNotNull(res); assertTrue(res.size() > 2); }
Source:
public static void main(String[] args) throws Exception { GrobidProperties.getInstance(); AcknowledgmentTrainer trainer = new AcknowledgmentTrainer(); AbstractTrainer.runTraining(trainer); START AbstractTrainer.runEvaluation(trainer); END System.exit(0); } yes, the first link in AbstractTrainer there is a method called `evaluateNFold` or something like that (I'm trying to remember)

Target:
public static void main(String[] args) throws Exception { GrobidProperties.getInstance(); AcknowledgmentTrainer trainer = new AcknowledgmentTrainer(); AbstractTrainer.runTraining(trainer); System.out.println(AbstractTrainer.runEvaluation(trainer)); System.exit(0); }
Source:
public static <T> ZooKeeperNode<T> create(ZooKeeperClient zkClient, String nodePath, Function<byte[], T> deserializer, Closure<T> dataUpdateListener) throws InterruptedException, KeeperException, ZooKeeperConnectionException { ZooKeeperNode<T> zkNode = START new ZooKeeperNode<T>(zkClient, nodePath, new FunctionWrapper<T>(deserializer), END dataUpdateListener); zkNode.init(); return zkNode; } this should chain to once of the creates below

Target:
public static <T> ZooKeeperNode<T> create(ZooKeeperClient zkClient, String nodePath, Function<byte[], T> deserializer, Closure<T> dataUpdateListener) throws InterruptedException, KeeperException, ZooKeeperConnectionException { return create(zkClient, nodePath, new FunctionWrapper<T>(deserializer), dataUpdateListener); }
Source:
public void onAttach(Activity activity) { super.onAttach(activity); // Initialize Baidu Map library START com.baidu.mapapi.SDKInitializer.initialize(getActivity().getApplicationContext()); END mDpApp = (DroidPlannerApp) activity.getApplication(); } @droneboost use the `activity` parameter instead of calling the `getActivity()` method.

Target:
public void onAttach(Activity activity) { super.onAttach(activity); // Initialize Baidu Map library com.baidu.mapapi.SDKInitializer.initialize(activity.getApplicationContext()); mDpApp = (DroidPlannerApp) activity.getApplication(); }
Source:
private void setAutoPanMode(AutoPanMode current, AutoPanMode update) { START if (mPanMode.compareAndSet(current, update)) { END switch (current) { case DRONE: LocalBroadcastManager.getInstance(getActivity().getApplicationContext()) .unregisterReceiver(eventReceiver); break; case DISABLED: default: break; } switch (update) { case DRONE: LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).registerReceiver (eventReceiver, mEventFilter); break; case DISABLED: default: break; } } } @droneboost here you can just call `mPanMode.compareAndSet(current, update)` to accomplish the intended functionality. You especially don't want to unregister the event receiver since it's filtering over events besides the drone gps updates.

Target:
private void setAutoPanMode(AutoPanMode current, AutoPanMode update) { mPanMode.compareAndSet(current, update); }
Source:
public void search(View view) { ArrayList<MKOLSearchRecord> records = mOffline.searchCity(mCityNameView .getText().toString()); START if (records == null || records.size() != 1) { END return; } mCidView.setText(String.valueOf(records.get(0).cityID)); } @droneboost any reason the size of `records` is restricted to `1`? If there are more than one results, we can just still grab the first one as you're doing below.

Target:
public void search(View view) { ArrayList<MKOLSearchRecord> records = mOffline.searchCity(mCityNameView .getText().toString()); if (records == null) { return; } mCidView.setText(String.valueOf(records.get(0).cityID)); }
Source:
public void finishedLoadingLogs() { FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_geotag_layout); START if (fragment == null || !(fragment instanceof GeoTagImagesFragment)) { END fragment = new GeoTagImagesFragment(); fm.beginTransaction().replace(R.id.fragment_geotag_layout, fragment).commit(); } } @chaviw you can skip the check for `null`. If `fragment` is `null` then the `instanceof` check will also fail.

Target:
public void finishedLoadingLogs() { FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_geotag_layout); if (!(fragment instanceof GeoTagImagesFragment)) { fragment = new GeoTagImagesFragment(); fm.beginTransaction().replace(R.id.fragment_geotag_layout, fragment).commit(); } }
Source:
public void updateTitle(@StringRes int title) { final int toolbarId = getToolbarId(); final FragmentManager fm = getSupportFragmentManager(); Fragment actionBarGeoTag = fm.findFragmentById(toolbarId); START if (actionBarGeoTag != null && actionBarGeoTag instanceof ActionBarGeoTagFragment) { END ((ActionBarGeoTagFragment) actionBarGeoTag).updateTitle(title); } } @chaviw same here. you can skip the check for null.

Target:
public void updateTitle(@StringRes int title) { final int toolbarId = getToolbarId(); final FragmentManager fm = getSupportFragmentManager(); Fragment actionBarGeoTag = fm.findFragmentById(toolbarId); if (actionBarGeoTag instanceof ActionBarGeoTagFragment) { ((ActionBarGeoTagFragment) actionBarGeoTag).updateTitle(title); } }
Source:
private void finishedGeotagging(Intent intent) { boolean success = intent.getBooleanExtra(GeoTagImagesService.EXTRA_SUCCESS, false); if (success) { ArrayList<File> files = (ArrayList<File>) intent.getSerializableExtra(GeoTagImagesService.EXTRA_GEOTAGGED_FILES); START activity.finishedGeotagging(files); END } else { String failure = intent.getStringExtra(GeoTagImagesService.EXTRA_FAILURE_MESSAGE); failedLoading(failure); } } @chaviw check for `activity` being null.

Target:
private void finishedGeotagging(Intent intent) { boolean success = intent.getBooleanExtra(GeoTagImagesService.EXTRA_SUCCESS, false); if (success) { if (activity != null) { ArrayList<File> files = (ArrayList<File>) intent.getSerializableExtra(GeoTagImagesService.EXTRA_GEOTAGGED_FILES); activity.finishedGeotagging(files); } } else { String failure = intent.getStringExtra(GeoTagImagesService.EXTRA_FAILURE_MESSAGE); failedLoading(failure); } }
Source:
private void startGeoTagging() { START File folder = getApplicationContext().getExternalFilesDir(null); END File tlogFile = new File(folder.getPath() + "/camera_msgs.tlog"); Timber.d("path: " + tlogFile.getPath()); geoTagImages(getApplicationContext(), tlogFile); } @chaviw you should be able to call `getExternalFilesDir(null)` directly.

Target:
private void startGeoTagging() { File folder = getExternalFilesDir(null); File tlogFile = new File(folder.getPath() + "/camera_msgs.tlog"); Timber.d("path: " + tlogFile.getPath()); geoTagImages(tlogFile); }
Source:
private static String findRootPath(File extFile) { START File currPath = null; END if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { currPath = extFile; try { while (Environment.isExternalStorageRemovable(currPath.getParentFile())) { currPath = currPath.getParentFile(); } } catch (IllegalArgumentException e) { //swallow return currPath.getAbsolutePath(); } } return currPath.getAbsolutePath(); } @chaviw check for `extFile` being `null`.

Target:
private static String findRootPath(File extFile) { if (extFile == null) { return null; } File currPath = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { currPath = extFile; try { while (Environment.isExternalStorageRemovable(currPath.getParentFile())) { currPath = currPath.getParentFile(); } } catch (IllegalArgumentException e) { //swallow return currPath.getAbsolutePath(); } } return currPath.getAbsolutePath(); }
Source:
public static UVCDialog newInstance() { final UVCDialog dialog = new UVCDialog(); final Bundle args = new Bundle(); START dialog.setArguments(args); END return dialog; } @guiseco what's the `Bundle args` for here, since no arguments is being added to it?

Target:
public static UVCDialog newInstance() { final UVCDialog dialog = new UVCDialog(); return dialog; }
Source:
public UsbDevice getItem(final int position) { START if ((position >= 0) && (position < mList.size())) END return mList.get(position); else return null; } @guiseco you don't need to check the validity of the `position` argument here, since it's based on the `getCount()` that you overrode above.

Target:
public UsbDevice getItem(final int position) { return mList.get(position); }
Source:
public CharSequence[][] getHelpItems() { START return new CharSequence[][] { { getResources().getString(R.string.help_item_description) }, END { "https://www.youtube.com/watch?v=btsk7bzn-9Q" } }; } @metalnow not a bug, but in an `Activity`, you can call `getString(...)` directly.

Target:
public CharSequence[][] getHelpItems() { return new CharSequence[][] { { getString(R.string.help_item_description) }, { "https://www.youtube.com/watch?v=btsk7bzn-9Q" } }; }
Source:
public void onDroneEvent(DroneInterfaces.DroneEventsType event, Drone drone) { START if(event.equals(DroneInterfaces.DroneEventsType.STATE)){ END if(drone.getState().isCollisionImminent()){ mPool.play(beepBeep,1f,1f,1,1,1f); }else{ mPool.stop(beepBeep); } } } @TShapinsky DroneEventsType is an enum, so you can use `event == DroneEventsType.STATE` instead of using the `equals()` method.

Target:
public void onDroneEvent(DroneInterfaces.DroneEventsType event, Drone drone) { if(event == DroneInterfaces.DroneEventsType.STATE){ if(drone.getState().isCollisionImminent()){ mPool.play(beepBeep,1f,1f,1,1,1f); }else{ mPool.stop(beepBeep); } } }
Source:
private static String getCustomClassName(Class<? extends ObjCObject> type) { CustomClass customClassAnno = type.getAnnotation(CustomClass.class); String name = type.getName(); if (customClassAnno != null && customClassAnno.value().length() > 0) { name = customClassAnno.value(); } START name = CUSTOM_CLASS_NAME_PREFIX + name.replace('.', '_'); END return name; } This should only be done if there is no `@CustomClass` annotation. If there is the name it specifies should be used as is and the user will have to make sure there are no collisions.

Target:
private static String getCustomClassName(Class<? extends ObjCObject> type) { CustomClass customClassAnno = type.getAnnotation(CustomClass.class); String name = type.getName(); if (customClassAnno != null && customClassAnno.value().length() > 0) { name = customClassAnno.value(); } else { name = CUSTOM_CLASS_NAME_PREFIX + name; } name = name.replace('.', '_'); return name; }
Source:
private void generateIBClassesFile(File installDir) throws IOException { List<String> customClasses = config.getCustomIBClasses(); if (!customClasses.isEmpty()) { START FileWriter fw = new FileWriter(new File(installDir, "ib.classes")); END String array = StringUtils.toString(customClasses.toArray(new String[customClasses.size()]), ","); fw.write(array); fw.close(); } } Again, use try-with-resources.

Target:
private void generateIBClassesFile(File installDir) throws IOException { List<String> customClasses = config.getCustomIBClasses(); if (!customClasses.isEmpty()) { try (FileWriter fw = new FileWriter(new File(installDir, "ib.classes"))) { String array = StringUtils.toString(customClasses.toArray(new String[customClasses.size()]), ","); fw.write(array); } } }
Source:
private static void release(@Pointer long self, @Pointer long sel) { if (ObjCRuntime.int_objc_msgSend(self, retainCount) == 1) { synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.remove(self); } } long cls = ObjCRuntime.object_getClass(self); START long nativeSuper = customClassToNativeSuper.get(cls); END Super sup = new Super(self, nativeSuper); ObjCRuntime.void_objc_msgSendSuper(sup.getHandle(), sel); } Should the `customClassToNativeSuper.get()` call be in a synchronized block?

Target:
private static void release(@Pointer long self, @Pointer long sel) { if (ObjCRuntime.int_objc_msgSend(self, retainCount) == 1) { synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.remove(self); } } long cls = ObjCRuntime.object_getClass(self); long nativeSuper = 0; synchronized(customClassToNativeSuper) { nativeSuper = customClassToNativeSuper.get(cls); } Super sup = new Super(self, nativeSuper); ObjCRuntime.void_objc_msgSendSuper(sup.getHandle(), sel); }
Source:
private static @Pointer long retain (ObjCObject self, @Pointer long sel) { START if (ObjCRuntime.int_objc_msgSend(self.getHandle(), retainCount) == 1) { END synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.put(self.getHandle(), self); } } return ObjCRuntime.ptr_objc_msgSendSuper(new Super(self.getHandle(), NS_OBJECT_CLASS).getHandle(), sel); } Not sure whether it should be `== 0` instead here?

Target:
private static @Pointer long retain(ObjCObject self, @Pointer long sel) { if (ObjCRuntime.int_objc_msgSend(self.getHandle(), retainCount) <= 1) { synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.put(self.getHandle(), self); } } return ObjCRuntime.ptr_objc_msgSendSuper(new Super(self.getHandle(), NS_OBJECT_CLASS).getHandle(), sel); }
Source:
public static ConversionResult getResult(int error) { switch (error) { case 0: return CONVERSION_OK; case 1: return ILLEGAL_SEQUENCE; case 2: return OUTPUT_BUFFER_TOO_SMALL; case 3: return INCOMPLETE_SEQUENCE; case 4: return ERROR_METHOD_ID; case 5: return ERROR_ARRAY_FUNCTION_CALL; case 6: return ERROR_DESCRIPTOR; default: START return WEIRD_ERROR; END } } If this should never happen throw an `IllegalArgumentException` instead.

Target:
public static ConversionResult getResult(int error) { switch (error) { case 0: return CONVERSION_OK; case 1: return ILLEGAL_SEQUENCE; case 2: return OUTPUT_BUFFER_TOO_SMALL; case 3: return INCOMPLETE_SEQUENCE; default: throw new IllegalArgumentException(); } }
Source:
public IconvEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar) { super(cs, averageBytesPerChar, maxBytesPerChar); START this.iconv_tPointer = IconvProvider.initConversion("UTF-16LE", ((IconvCharset) cs).getIconvName()); END } I believe we talked about doing this lazily?

Target:
public IconvEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar) { super(cs, averageBytesPerChar, maxBytesPerChar); }
Source:
private boolean containsAll(final NullnessAnnotation... search) { START Boolean result = null; END if (this.annotations.isEmpty()) { // an empty list of annotations can never contain all result = false; } else { for (final NullnessAnnotation obj : search) { if (!this.annotations.contains(obj)) { result = false; break; } } } if (result == null) { result = true; } return result; } This could just default to `true` and be primitive and remove the `if` statement below.

Target:
private boolean containsAll(final NullnessAnnotation... search) { boolean result = true; if (this.annotations.isEmpty()) { // an empty list of annotations can never contain all result = false; } else { for (final NullnessAnnotation obj : search) { if (!this.annotations.contains(obj)) { result = false; break; } } } return result; }
Source:
private boolean containsAny(final NullnessAnnotation... search) { START Boolean result = null; END if (this.annotations.isEmpty()) { result = false; } else { for (final NullnessAnnotation obj : search) { if (this.annotations.contains(obj)) { result = true; break; } } } if (result == null) { result = false; } return result; } Same but this would default to `false`.

Target:
private boolean containsAny(final NullnessAnnotation... search) { boolean result = false; if (!this.annotations.isEmpty()) { for (final NullnessAnnotation obj : search) { if (this.annotations.contains(obj)) { result = true; break; } } } return result; }
Source:
public boolean contains(int num) { final boolean lowerLimitCheckPassed = lowerLimit == null || num >= lowerLimit; START final boolean upperLimitCheckPassed = upperLimit == null || num <= upperLimit; END return lowerLimitCheckPassed && upperLimitCheckPassed; } you should not have null in code, you can use 0 or MAX .

Target:
public boolean contains(int num) { return num >= lowerLimit && num <= upperLimit; }
Source:
START protected boolean isClassEnumeration(DetailAST aAST) { END return hasMembers(aAST, mExcludes); } For this method the { bracket is on the same line, while for other methods it is on the other lines. Normally you should not think about such thing at all and use IDE-autoformatting, but checkstyle is somewhat special. I have not found usages of this method outside this class - should it be private?

Target:
private boolean isClassEnumeration(DetailAST aAST) { return hasMembers(aAST, mExcludes); }