id stringlengths 23 26 | content stringlengths 182 2.49k |
|---|---|
codereview_java_data_4222 | private void initializeGestureDetector(){
gestureDetector = new GestureDetectorCompat(this, gestureDetectorListener);
- gestureDetector.setOnDoubleTapListener(gestureDetectorListener);
}
private void initializeResources() {
you can use `TAG` instead of "ConversationActivity"
private void initializeGestureDetector(){
gestureDetector = new GestureDetectorCompat(this, gestureDetectorListener);
}
private void initializeResources() { |
codereview_java_data_4236 | private final OSS client;
private final OSSURI uri;
- private final AliyunProperties aliyunProperties;
private final File currentStagingFile;
private final OutputStream stream;
Nit: Any usage for this variable ? Seems it could be converted to use a local variable.
private final OSS client;
private final OSSURI uri;
private final File currentStagingFile;
private final OutputStream stream; |
codereview_java_data_4237 | return nodeWhitelist.remove(node);
}
- public boolean isNodeWhitelisted(final Peer node) {
return (!nodeWhitelistSet || (nodeWhitelistSet && nodeWhitelist.contains(node)));
}
}
Suggestion: s/isNodeWhiteListed/contains Reason: as a public scoped method, it would reduce repetition in context when calling the method i.e. nodeWhiteList.contains() vs nodeWhitelist.isNodeWhiteListed()
return nodeWhitelist.remove(node);
}
+ public boolean contains(final Peer node) {
return (!nodeWhitelistSet || (nodeWhitelistSet && nodeWhitelist.contains(node)));
}
} |
codereview_java_data_4240 | "COALESCE(?0.i, +(?0.i, ?0.h), 1)");
// not(x) is null should not optimized to x is not null
- checkSimplify(isNull(not(fRef)), "IS NULL(NOT(?0.f))");
- checkSimplify(isNotNull(not(fRef)), "IS NOT NULL(?0.f)");
}
Please rebase and use `isNull(not(vBool()))`
"COALESCE(?0.i, +(?0.i, ?0.h), 1)");
// not(x) is null should not optimized to x is not null
+ checkSimplify(isNull(not(vBool())), "IS NULL(NOT(?0.bool0))");
+ checkSimplify(isNull(not(vBoolNotNull())), "false");
+ checkSimplify(isNotNull(not(vBool())), "IS NOT NULL(?0.bool0)");
+ checkSimplify(isNotNull(not(vBoolNotNull())), "true");
} |
codereview_java_data_4249 | try {
if (enterPath(parser, "version", "number") != null) version = parser.getText();
} catch (RuntimeException | IOException possiblyParseException) {
- throw new IllegalArgumentException(
- "could not parse .version.number in response: " + contentString.get());
}
if (version == null) {
throw new IllegalArgumentException(
On phone so can't expand this file to see below but if it's duping the next line, commet instead is fine
try {
if (enterPath(parser, "version", "number") != null) version = parser.getText();
} catch (RuntimeException | IOException possiblyParseException) {
+ // EmptyCatch ignored
}
if (version == null) {
throw new IllegalArgumentException( |
codereview_java_data_4262 | return set;
}
- private StructLikeSet rowSetWithoutIds(Table iTable, List<Record> recordList, int... idsToRemove) {
Set<Integer> deletedIds = Sets.newHashSet(ArrayUtil.toIntList(idsToRemove));
- StructLikeSet set = StructLikeSet.create(iTable.schema().asStruct());
recordList.stream()
.filter(row -> !deletedIds.contains(row.getField("id")))
- .map(record -> new InternalRecordWrapper(iTable.schema().asStruct()).wrap(record))
.forEach(set::add);
return set;
}
Since you're passing the table in, can you make this a `static` method? You may also be able to use the name `table` instead of `iTable` if it is `static`.
return set;
}
+ private static StructLikeSet rowSetWithoutIds(Table table, List<Record> recordList, int... idsToRemove) {
Set<Integer> deletedIds = Sets.newHashSet(ArrayUtil.toIntList(idsToRemove));
+ StructLikeSet set = StructLikeSet.create(table.schema().asStruct());
recordList.stream()
.filter(row -> !deletedIds.contains(row.getField("id")))
+ .map(record -> new InternalRecordWrapper(table.schema().asStruct()).wrap(record))
.forEach(set::add);
return set;
} |
codereview_java_data_4263 | if (currentSize <= maxSize) {
this.eventQueue.add(event);
} else {
- log.warn("event queue size[{}] enough, so drop this event {}", currentSize, event.toString());
}
}
IMO, print currentSize and maxSize will be better.
if (currentSize <= maxSize) {
this.eventQueue.add(event);
} else {
+ log.warn("event queue size [{}] over the limit [{}], so drop this event {}", currentSize, maxSize, event.toString());
}
} |
codereview_java_data_4270 | @Override
default Iterator<T> dropWhile(Predicate<? super T> predicate) {
if (!hasNext()) {
return empty();
} else {
let's do `Objects.requireNonNull(predicate, "predicate is null")`. I've also forgotten in in various places and will add them later...
@Override
default Iterator<T> dropWhile(Predicate<? super T> predicate) {
+ Objects.requireNonNull(predicate, "predicate is null");
if (!hasNext()) {
return empty();
} else { |
codereview_java_data_4274 | throw new MQBrokerException(response.getCode(), response.getRemark());
}
public ClusterInfo getBrokerClusterInfo(String cluster,
final long timeoutMillis) throws InterruptedException, RemotingTimeoutException,
RemotingSendRequestException, RemotingConnectException, MQBrokerException {
how to insure the api compatibility
throw new MQBrokerException(response.getCode(), response.getRemark());
}
+ public ClusterInfo getBrokerClusterInfo(final long timeoutMillis) throws InterruptedException, RemotingTimeoutException,
+ RemotingSendRequestException, RemotingConnectException, MQBrokerException {
+ return this.getBrokerClusterInfo("", timeoutMillis);
+ }
+
public ClusterInfo getBrokerClusterInfo(String cluster,
final long timeoutMillis) throws InterruptedException, RemotingTimeoutException,
RemotingSendRequestException, RemotingConnectException, MQBrokerException { |
codereview_java_data_4275 | return SUPPORTED_TOKENS;
}
}
I think this was intended as part of the design to eventually support multi-tiered authentication, just like the `passwd` entry in Linux's `/etc/nsswitch.conf` can include an ordered list of authentication storage mechanisms or (at a higher level) PAM can be configured to use multiple authentication modules. In order to support this, it's necessary for modules to be able to declare what kinds of tokens they are able to understand. This isn't currently implemented, and can probably be done better, and may not be the best design anyway, so probably okay to remove regardless, as long as it's really not being used. Might want to double-check that callers aren't now getting the parent class' implementation of this method instead, though.
return SUPPORTED_TOKENS;
}
+ @Override
+ public boolean validTokenClass(String tokenClass) {
+ return SUPPORTED_TOKEN_NAMES.contains(tokenClass);
+ }
+
} |
codereview_java_data_4277 | "Usage:\n" +
" PutItem <tableName> <key> <keyVal> <albumtitle> <albumtitleval> <awards> <awardsval> <Songtitle> <songtitleval>\n\n" +
"Where:\n" +
- " tableName - the Amazon DynamoDB table in which an item is placed (for example, Music3).\n" +
- " key - the key used in the Amazon DynamoDB table (for example, Artist).\n" +
" keyval - the key value that represents the item to get (for example, Famous Band).\n" +
" albumTitle - album title (for example, AlbumTitle).\n" +
" AlbumTitleValue - the name of the album (for example, Songs About Life ).\n" +
You only need to say "Amazon DynamoDB" on first use. After that, you can just say "DynamoDB".
"Usage:\n" +
" PutItem <tableName> <key> <keyVal> <albumtitle> <albumtitleval> <awards> <awardsval> <Songtitle> <songtitleval>\n\n" +
"Where:\n" +
+ " tableName - the DynamoDB table in which an item is placed (for example, Music3).\n" +
+ " key - the key used in the DynamoDB table (for example, Artist).\n" +
" keyval - the key value that represents the item to get (for example, Famous Band).\n" +
" albumTitle - album title (for example, AlbumTitle).\n" +
" AlbumTitleValue - the name of the album (for example, Songs About Life ).\n" + |
codereview_java_data_4284 | private static final int NODE_ID_SIZE = 64;
private static final Pattern DISCPORT_QUERY_STRING_REGEX =
- Pattern.compile("discport=([0-9]{1,5})");
private static final Pattern NODE_ID_PATTERN = Pattern.compile("^[0-9a-fA-F]{128}$");
private final BytesValue nodeId;
If we're being really strict this should probably be `"(^|&)discport=([0-9]{1,4})"` I think. So discport should either be the first arg or after a & to prevent matching `enode://...@...:30303?notthediscport=1234`
private static final int NODE_ID_SIZE = 64;
private static final Pattern DISCPORT_QUERY_STRING_REGEX =
+ Pattern.compile("^discport=([0-9]{1,5})$");
private static final Pattern NODE_ID_PATTERN = Pattern.compile("^[0-9a-fA-F]{128}$");
private final BytesValue nodeId; |
codereview_java_data_4297 | if (address == null) {
return null;
}
- return address.getHost() + ":" + address.getPort();
}
/**
I think the `toString()` of our `HostAndPort` in core util already does this.
if (address == null) {
return null;
}
+ return address.toString();
}
/** |
codereview_java_data_4299 | String MANDATORY_NETWORK_FORMAT_HELP = "<NETWORK>";
String MANDATORY_NODE_ID_FORMAT_HELP = "<NODEID>";
Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000);
- long DEFAULT_RETENTION_PERIOD = 1000;
long DEFAULT_TRANSIENT_FORK_OUTLIVING_PERIOD = 10;
BytesValue DEFAULT_EXTRA_DATA = BytesValue.EMPTY;
long DEFAULT_MAX_REFRESH_DELAY = 3600000;
Should we up this to be at least 1024? Maybe more? I would like the default to be higher to ensure sweep doesn't cut past the finality gadget horizon, which starts at a 1024 block minimum. In a live system it will be functionally more but in a static replay we may get in trouble.
String MANDATORY_NETWORK_FORMAT_HELP = "<NETWORK>";
String MANDATORY_NODE_ID_FORMAT_HELP = "<NODEID>";
Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000);
+ long DEFAULT_RETENTION_PERIOD = 1024;
long DEFAULT_TRANSIENT_FORK_OUTLIVING_PERIOD = 10;
BytesValue DEFAULT_EXTRA_DATA = BytesValue.EMPTY;
long DEFAULT_MAX_REFRESH_DELAY = 3600000; |
codereview_java_data_4301 | return true;
}
- public static String getHadoopNonExistingPath() {
return System.getProperty("os.name").toLowerCase().contains("windows")
? "c:\\non\\existing\\path"
- : "/non/existing/path/";
}
/**
simply `getNonExistingPath()` or even `nonExistingPath()` ?
return true;
}
+ public static String hadoopNonExistingPath() {
return System.getProperty("os.name").toLowerCase().contains("windows")
? "c:\\non\\existing\\path"
+ : "/non/existing/path";
}
/** |
codereview_java_data_4303 | ProbeBuilder probeBuilder = this.nodeEngine.getMetricsRegistry().newProbeBuilder()
.withTag("module", "jet")
- .withTag("job", Long.toHexString(jobId))
- .withTag("exId", Long.toHexString(executionId))
.withTag("vertex", vertex.name());
if (vertex.inboundEdges().size() == 0) {
it would be better to use idToString for readability and consistency with logs. Saving a few characters doesn't matter in this case.
ProbeBuilder probeBuilder = this.nodeEngine.getMetricsRegistry().newProbeBuilder()
.withTag("module", "jet")
+ .withTag("job", idToString(jobId))
+ .withTag("exId", idToString(executionId))
.withTag("vertex", vertex.name());
if (vertex.inboundEdges().size() == 0) { |
codereview_java_data_4305 | */
public static Password promptUser() throws IOException {
if (System.console() == null) {
- return null;
}
ConsoleReader reader = new ConsoleReader();
String enteredPass = reader.readLine("Enter password: ", '*');
I'm thinking that throwing an exception here would be more clear. This method cannot properly function as the caller expected, so they should get a clear exception in this case (not just a null return value).
*/
public static Password promptUser() throws IOException {
if (System.console() == null) {
+ throw new IOException("Attempted to prompt user on the console when System.console = null");
}
ConsoleReader reader = new ConsoleReader();
String enteredPass = reader.readLine("Enter password: ", '*'); |
codereview_java_data_4312 | TableParams<T> clientProperties(Properties clientProperties);
/**
- * Set path to HDFS location containing accumulo-client.properties file. This setting is more
* secure than {@link #clientProperties(Properties)}
*
* @param clientPropsPath
- * HDFS path to accumulo-client.properties
*/
TableParams<T> clientPropertiesPath(String clientPropsPath);
}
This could be from a DFS location and doesn't have to be HDFS right?
TableParams<T> clientProperties(Properties clientProperties);
/**
+ * Set path to DFS location containing accumulo-client.properties file. This setting is more
* secure than {@link #clientProperties(Properties)}
*
* @param clientPropsPath
+ * DFS path to accumulo-client.properties
*/
TableParams<T> clientPropertiesPath(String clientPropsPath);
} |
codereview_java_data_4314 | if (pstmt.executeUpdate() == 1) {
final Data result = new Data(currentID, newID);
sequenceBlocks.put(type, result);
return result;
} else {
throw new IllegalStateException("Failed at attempt to obtain an ID, aborting...");
As this doesn't set abortTransaction to true, it's not actually aborted? Is that desired? FWIW, I'd default the rollback flag to true, and set it to false immediately before the the `return result;`, so it only needs to changed in one place.
if (pstmt.executeUpdate() == 1) {
final Data result = new Data(currentID, newID);
sequenceBlocks.put(type, result);
+ abortTransaction = false;
return result;
} else {
throw new IllegalStateException("Failed at attempt to obtain an ID, aborting..."); |
codereview_java_data_4316 | * @return {@link HttpRestResult}
* @throws Exception ex
*/
- public <T> HttpRestResult<T> exchangeFrom(String url, Header header,
Map<String, String> paramValues, Map<String, String> bodyValues, String httpMethod, Type responseType) throws Exception{
RequestHttpEntity requestHttpEntity = new RequestHttpEntity(
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED),
What's the mean of `From` I read the method think it should be `exchangeForm`, is it?
* @return {@link HttpRestResult}
* @throws Exception ex
*/
+ public <T> HttpRestResult<T> exchangeForm(String url, Header header,
Map<String, String> paramValues, Map<String, String> bodyValues, String httpMethod, Type responseType) throws Exception{
RequestHttpEntity requestHttpEntity = new RequestHttpEntity(
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), |
codereview_java_data_4355 | newHiveConf.set(HiveConf.ConfVars.METASTOREWAREHOUSE.varname, "file:" + hiveLocalDir.getAbsolutePath());
newHiveConf.set(HiveConf.ConfVars.METASTORE_TRY_DIRECT_SQL.varname, "false");
newHiveConf.set(HiveConf.ConfVars.METASTORE_DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES.varname, "false");
- newHiveConf.set("metastore.scheduled.queries.enabled", "false");
newHiveConf.set("iceberg.hive.client-pool-size", "2");
return newHiveConf;
}
Why is this needed?
newHiveConf.set(HiveConf.ConfVars.METASTOREWAREHOUSE.varname, "file:" + hiveLocalDir.getAbsolutePath());
newHiveConf.set(HiveConf.ConfVars.METASTORE_TRY_DIRECT_SQL.varname, "false");
newHiveConf.set(HiveConf.ConfVars.METASTORE_DISALLOW_INCOMPATIBLE_COL_TYPE_CHANGES.varname, "false");
newHiveConf.set("iceberg.hive.client-pool-size", "2");
return newHiveConf;
} |
codereview_java_data_4356 | .title(R.string.title_clear_history_dialog)
.content(R.string.text_clear_history_dialog)
.onPositive((dialog, which) -> {
- Utils.getAppDaoSession(getParent()).getHistoryProductDao().deleteAll();;
productItems.clear();
recyclerHistoryScanView.getAdapter().notifyDataSetChanged();
})
extract in a class field `Utils.getAppDaoSession(getParent()).getHistoryProductDao()` to `historyProductDao`
.title(R.string.title_clear_history_dialog)
.content(R.string.text_clear_history_dialog)
.onPositive((dialog, which) -> {
+ mHistoryProductDao.deleteAll();;
productItems.clear();
recyclerHistoryScanView.getAdapter().notifyDataSetChanged();
}) |
codereview_java_data_4359 | public class AliyunProperties implements Serializable {
/**
- * Location to put staging files for uploading to OSS, default to temp directory set in java.io.tmpdir.
*/
public static final String OSS_STAGING_DIRECTORY = "oss.staging-dir";
private final String ossStagingDirectory;
Nit: should be `defaults`. Might just be easier to say `...for uploading to OSS, defaults to the directory value of java.io.tmpdir`. Leave that up to you
public class AliyunProperties implements Serializable {
/**
+ * Location to put staging files for uploading to OSS, defaults to the directory value of java.io.tmpdir.
*/
public static final String OSS_STAGING_DIRECTORY = "oss.staging-dir";
private final String ossStagingDirectory; |
codereview_java_data_4361 | in.enterList();
final BytesValue target = in.readBytesValue();
final long expiration = in.readLongScalar();
- in.leaveList(true);
return new FindNeighborsPacketData(target, expiration);
}
(optional) make leaveList parameter an enum. Much easier to understand what `in.leaveList(RLPInput.IgnoreRest)` does as opposed to `in.leaveList(true)`
in.enterList();
final BytesValue target = in.readBytesValue();
final long expiration = in.readLongScalar();
+ in.leaveListLenient();
return new FindNeighborsPacketData(target, expiration);
} |
codereview_java_data_4363 | /**
* Return a list of possible completions given a prefix string that the user has started typing.
* @param start the amount of text written so far
- * @param detailLevel the level of detail the user wants in completions
*/
@RequestMapping(value = "/stream")
public CompletionProposalsResource completions(
Is there an accepted range of values for `detailLevel`? This should be specified here and in other places where it is accepted as a parameter.
/**
* Return a list of possible completions given a prefix string that the user has started typing.
* @param start the amount of text written so far
+ * @param detailLevel the level of detail the user wants in completions, starting at 1.
+ * Higher values request more detail, with values typically in the range [1..5]
*/
@RequestMapping(value = "/stream")
public CompletionProposalsResource completions( |
codereview_java_data_4368 | final StringBuilder buff = new StringBuilder();
final String name =
"GeneratedMetadata_" + simpleNameForHandler(def.handlerClass);
- final Set<MetadataHandler<?>> providerSet = new HashSet<>();
final Map<MetadataHandler<?>, String> handlerToName = new LinkedHashMap<>();
for (MetadataHandler<?> provider : map.values()) {
- if (providerSet.add(provider)) {
handlerToName.put(provider,
- "provider" + (providerSet.size() - 1));
}
}
Do you need both the `providerSet` and `handlerToName`? Couldn't we get rid of the `providerSet` and do a `contains` check against the map instead?
final StringBuilder buff = new StringBuilder();
final String name =
"GeneratedMetadata_" + simpleNameForHandler(def.handlerClass);
final Map<MetadataHandler<?>, String> handlerToName = new LinkedHashMap<>();
for (MetadataHandler<?> provider : map.values()) {
+ if (!handlerToName.containsKey(provider)) {
handlerToName.put(provider,
+ "provider" + (handlerToName.size() - 1));
}
} |
codereview_java_data_4371 | * Factory for providers of source code for JavaParser.
* Providers that have no parameter for encoding but need it will use UTF-8.
*/
-public abstract class Providers {
public static final Charset UTF8 = Charset.forName("utf-8");
private Providers() {
Why **abstract** and not **final** ?
* Factory for providers of source code for JavaParser.
* Providers that have no parameter for encoding but need it will use UTF-8.
*/
+public final class Providers {
public static final Charset UTF8 = Charset.forName("utf-8");
private Providers() { |
codereview_java_data_4376 | import com.hazelcast.jet.impl.execution.init.JetInitDataSerializerHook;
import com.hazelcast.nio.tcp.FirewallingConnectionManager;
import com.hazelcast.test.HazelcastSerialClassRunner;
-import com.hazelcast.test.annotation.Repeat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
There is a left-over `@Repeat` here.
import com.hazelcast.jet.impl.execution.init.JetInitDataSerializerHook;
import com.hazelcast.nio.tcp.FirewallingConnectionManager;
import com.hazelcast.test.HazelcastSerialClassRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith; |
codereview_java_data_4381 | EditText ingredientsUnauthorised;
@BindView(R.id.save_edits)
Button saveEdits;
- //Récupération de la langue (théorique) de saisie :
private String languageCode = Locale.getDefault().getLanguage();
private IDietRepository dietRepository;
```suggestion // Fetching of the (theoretical) language of input: ```
EditText ingredientsUnauthorised;
@BindView(R.id.save_edits)
Button saveEdits;
+ // Fetching of the (theoretical) language of input:
private String languageCode = Locale.getDefault().getLanguage();
private IDietRepository dietRepository; |
codereview_java_data_4383 | templatePath(),
"Compilation unit doesn't contain a class or interface declaration!"));
if (annotator == null) {
for (String section : sections) {
replaceSectionPlaceHolder(cls, section);
I'm not sure I get this change, can you explain please?
templatePath(),
"Compilation unit doesn't contain a class or interface declaration!"));
+ // ApplicationTemplate (no CDI/Spring) has placeholders to replace
if (annotator == null) {
for (String section : sections) {
replaceSectionPlaceHolder(cls, section); |
codereview_java_data_4391 | ts.exec("createtable twithcolontest");
ts.exec("insert row c:f cq value");
ts.exec("scan -r row -cf c:f", true, "value");
- String result = ts.exec("scan -b row -cf c:f -cq cq -e row");
- assertEquals(2, result.split("\n").length);
- result = ts.exec("scan -b row -c cf -cf c:f -cq cq -e row", false);
- assertTrue(result.contains("mutually exclusive"));
-
- result = ts.exec("scan -b row -cq col1 -e row", false);
- assertTrue(result.contains("cannot be empty"));
-
ts.exec("deletetable -f twithcolontest");
}
```suggestion ts.exec("scan -b row -cf c:f -cq cq -e row", true, "value"); ts.exec("scan -b row -c cf -cf c:f -cq cq -e row", false, "mutually exclusive"); ts.exec("scan -b row -cq col1 -e row", false, "cannot be empty"); ``` A slight simplification so we don't have to create the results object to compare against.
ts.exec("createtable twithcolontest");
ts.exec("insert row c:f cq value");
ts.exec("scan -r row -cf c:f", true, "value");
+ ts.exec("scan -b row -cf c:f -cq cq -e row", true, "value");
+ ts.exec("scan -b row -c cf -cf c:f -cq cq -e row", false, "mutually exclusive");
+ ts.exec("scan -b row -cq col1 -e row", false, "Option -cf is required when using -cq");
ts.exec("deletetable -f twithcolontest");
} |
codereview_java_data_4393 | //mAccount.setRemoteSearchFullText(mRemoteSearchFullText.isChecked());
}
- // Setting image attachment resize preferences.
mAccount.setResizeEnabled(mResizeEnabled.isChecked());
mAccount.setResizeFactor(Integer.parseInt(mResizeFactor.getValue()));
This isn't that useful.
//mAccount.setRemoteSearchFullText(mRemoteSearchFullText.isChecked());
}
+ // Global preferences for image attachment resizing
mAccount.setResizeEnabled(mResizeEnabled.isChecked());
mAccount.setResizeFactor(Integer.parseInt(mResizeFactor.getValue())); |
codereview_java_data_4395 | .to(() -> new CreateSession(this)),
post("/se/grid/distributor/node")
.to(() -> new AddNode(tracer, this, json, httpClientFactory)),
- post("/node/{nodeId}/drain")
- .to((params) -> new DrainNode(this, new NodeId(UUID.fromString(params.get("nodeId"))))),
post("/se/grid/distributor/node/{nodeId}/drain")
.to((params) -> new DrainNode(this, new NodeId(UUID.fromString(params.get("nodeId"))))),
delete("/se/grid/distributor/node/{nodeId}")
Prefix the URL with `/se/` to stay in conformance with the webdriver spec, please.
.to(() -> new CreateSession(this)),
post("/se/grid/distributor/node")
.to(() -> new AddNode(tracer, this, json, httpClientFactory)),
post("/se/grid/distributor/node/{nodeId}/drain")
.to((params) -> new DrainNode(this, new NodeId(UUID.fromString(params.get("nodeId"))))),
delete("/se/grid/distributor/node/{nodeId}") |
codereview_java_data_4396 | @JsonProperty
@NotNull
- private Boolean showTaskDiskSpace = false;
private boolean hideNewDeployButton = false;
private boolean hideNewRequestButton = false;
i know this is a nitpick, but `showTaskDiskResource` better describes what this is
@JsonProperty
@NotNull
+ private boolean showTaskDiskResource = false;
private boolean hideNewDeployButton = false;
private boolean hideNewRequestButton = false; |
codereview_java_data_4398 | */
// void setLocations(Collection<Assignment> assignments) throws DistributedStoreException;
- void setLocations(Collection<Assignment> assignments, TServerInstance prevLastLoc)
- throws DistributedStoreException;
/**
* Mark the tablets as having no known or future location.
At the hackathon we discussed the following change. Curious if you are considering this? ```suggestion void setLocations(Assignment assignments, TServerInstance prevLastLoc) ```
*/
// void setLocations(Collection<Assignment> assignments) throws DistributedStoreException;
+ void setLocations(Assignment assignment, TServerInstance prevLastLoc);
/**
* Mark the tablets as having no known or future location. |
codereview_java_data_4411 | Map<String, String> rawArgs = new HashMap<>();
rawArgs.putAll(request.getDefinition().getParameters());
rawArgs.putAll(request.getDeploymentProperties());
- Map<String, String> transformed = ModuleLauncherArgumentsHelper.qualifyArgs(0, rawArgs);
- for (Map.Entry<String, String> entry : transformed.entrySet()) {
environmentVariables.add(new EnvironmentVariable(entry.getKey(), entry.getValue()));
}
lrp.setEnv(environmentVariables.toArray(new EnvironmentVariable[environmentVariables.size()]));
change "transformed" to "qualifiedArgs"? (the code is easier to read when terminology is consistent, rather than multiple terms being introduced for the same thing)
Map<String, String> rawArgs = new HashMap<>();
rawArgs.putAll(request.getDefinition().getParameters());
rawArgs.putAll(request.getDeploymentProperties());
+ Map<String, String> qualifiedArgs = ModuleLauncherArgumentsHelper.qualifyArgs(0, rawArgs);
+ for (Map.Entry<String, String> entry : qualifiedArgs.entrySet()) {
environmentVariables.add(new EnvironmentVariable(entry.getKey(), entry.getValue()));
}
lrp.setEnv(environmentVariables.toArray(new EnvironmentVariable[environmentVariables.size()])); |
codereview_java_data_4413 | final ProposalMessageData message = ProposalMessageData.create(signedPayload);
- network.send(message, emptyList());
}
public void multicastPrepare(final ConsensusRoundIdentifier roundIdentifier, final Hash digest) {
Look like Mulitcaster.send(MessageData message) can be removed now since all messages are going through the gossiper.
final ProposalMessageData message = ProposalMessageData.create(signedPayload);
+ multicaster.send(message);
}
public void multicastPrepare(final ConsensusRoundIdentifier roundIdentifier, final Hash digest) { |
codereview_java_data_4420 | import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.List;
public class SWUrl extends SWItem {
-
private List<String> labels;
private List<String> values;
private String groupName;
this is only for radiobuttons
import android.widget.EditText;
import android.widget.LinearLayout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.List;
public class SWUrl extends SWItem {
+ private static Logger log = LoggerFactory.getLogger(SWUrl.class);
private List<String> labels;
private List<String> values;
private String groupName; |
codereview_java_data_4423 | /*
- * Copyright 2016 Federico Tomassetti
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
.. that the ClassLoader can *load*.
/*
+ * Copyright (C) 2016-2018 The JavaParser Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. |
codereview_java_data_4424 | */
@Configuration
@EnableConfigurationProperties(ZipkinUiProperties.class)
-@ConditionalOnProperty(value = "zipkin.ui.enabled", havingValue = "true", matchIfMissing = true)
@RestController
public class ZipkinUiAutoConfiguration extends WebMvcConfigurerAdapter {
Nits: `name` might be more clear than `value` (which is an alias for `name`). Maybe it is just me but `value = x, havingValue = y` reads kind of funny. Also, the default of `havingValue` should be sufficient for our purposes. Specifying `"true"` might mean something like `"TRUE"` doesn't work.
*/
@Configuration
@EnableConfigurationProperties(ZipkinUiProperties.class)
+@ConditionalOnProperty(name = "zipkin.ui.enabled", matchIfMissing = true)
@RestController
public class ZipkinUiAutoConfiguration extends WebMvcConfigurerAdapter { |
codereview_java_data_4428 | }
}, 10000, 10000);
- DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group, AclClient.getAclRPCHook(), new AllocateMessageQueueAveragely(), msgTraceEnable, null);
if (commandLine.hasOption('n')) {
String ns = commandLine.getOptionValue('n');
consumer.setNamesrvAddr(ns);
You need to maintain compatibility and let users choose whether to use ACL instead of forcing users to use ACL.
}
}, 10000, 10000);
+ RPCHook rpcHook = aclEnable ? AclClient.getAclRPCHook() : null;
+ DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group, rpcHook, new AllocateMessageQueueAveragely(), msgTraceEnable, null);
if (commandLine.hasOption('n')) {
String ns = commandLine.getOptionValue('n');
consumer.setNamesrvAddr(ns); |
codereview_java_data_4438 | return true;
}
}
-
- public boolean isNearbyLocked() {
- return isNearbyLocked;
- }
-
- public void setNearbyLocked(boolean nearbyLocked) {
- isNearbyLocked = nearbyLocked;
- }
}
Exposing code for test is a code smell. The option is to rewrite or use the nasty `@VisibleForTesting` annotation. I'd say rewrite because `lockUnlockNearby` sets it quite easily for you.
return true;
}
}
} |
codereview_java_data_4448 | @Test
public void correctHttpResponse() throws Exception {
- final PublicMetrics publicMetrics = () -> Collections.singleton(new Metric<Number>("mem.free", 1024));
- final ResponseEntity<String> response = responseForMetrics(publicMetrics);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
assertThat(response.getHeaders().getContentType().toString(),
no big deal, but we don't put final on variables even if it is explicit and there are good reasons why some folks make conventions like that. leaving them out keeps line shorter and focuses more attention on the test code (at risk of someone doing the shell-game with references)
@Test
public void correctHttpResponse() throws Exception {
+ PublicMetrics publicMetrics = () -> Collections.singleton(new Metric<Number>("mem.free", 1024));
+ ResponseEntity<String> response = responseForMetrics(publicMetrics);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
assertThat(response.getHeaders().getContentType().toString(), |
codereview_java_data_4452 | * Constructs a {@code TimestampedEntry} using the window end time as the
* timestamp.
*/
- public static <K, V> TimestampedEntry<K, V> mapWindowResult(long winStart, long winEnd, @Nonnull K key,
- @Nonnull V value) {
return new TimestampedEntry<>(winEnd, key, value);
}
}
I think `fromWindowResult` would be a better name
* Constructs a {@code TimestampedEntry} using the window end time as the
* timestamp.
*/
+ public static <K, V> TimestampedEntry<K, V> fromWindowResult(long winStart, long winEnd, @Nonnull K key,
+ @Nonnull V value) {
return new TimestampedEntry<>(winEnd, key, value);
}
} |
codereview_java_data_4457 | @Override
public Capabilities getCanonicalCapabilities() {
- return new ImmutableCapabilities(CapabilityType.BROWSER_NAME, BrowserType.CHROME, PLATFORM_NAME, System.getProperty("os.name"));
}
@Override
This isn't correct. It means that only the current platform can be used for a remote webdriver.
@Override
public Capabilities getCanonicalCapabilities() {
+ return new ImmutableCapabilities(CapabilityType.BROWSER_NAME, BrowserType.CHROME);
}
@Override |
codereview_java_data_4466 | package com.actiontech.dble.services.mysqlsharding;
import com.actiontech.dble.backend.mysql.proto.handler.Impl.MySQLProtoHandlerImpl;
import com.actiontech.dble.backend.mysql.proto.handler.ProtoHandlerResult;
import com.actiontech.dble.net.handler.LoadDataInfileHandler;
reset protoHandler in here maybe a good idea
package com.actiontech.dble.services.mysqlsharding;
import com.actiontech.dble.backend.mysql.proto.handler.Impl.MySQLProtoHandlerImpl;
+import com.actiontech.dble.backend.mysql.proto.handler.ProtoHandler;
import com.actiontech.dble.backend.mysql.proto.handler.ProtoHandlerResult;
import com.actiontech.dble.net.handler.LoadDataInfileHandler; |
codereview_java_data_4470 | case UNKNOWN:
case WAITING:
case SUCCESS:
- case INVALID_REQUEST_NOOP:
return true;
default:
LOG.trace("Task {} had abnormal LB state {}", taskId, loadBalancerUpdate);
return false;
In this case, we don't need to remove from Baragon b/c Baragon doesn't know about it, right?
case UNKNOWN:
case WAITING:
case SUCCESS:
return true;
+ case INVALID_REQUEST_NOOP:
+ return false; // don't need to remove because Baragon doesnt know about it
default:
LOG.trace("Task {} had abnormal LB state {}", taskId, loadBalancerUpdate);
return false; |
codereview_java_data_4483 | * @return RoleAccess object on success. ZTSClientException will be thrown in case of failure
*/
public RoleAccess getRoleAccess(String domainName, String principal) {
- updateServicePrincipal(); // TODO: Henry: what if this method returns true - the principal's credentials are changed: should we not clean up the relevant cache entries ?
// Try to fetch from cache.
ZTSClientCache.DomainAndPrincipal cacheKey = null;
- Cache<ZTSClientCache.DomainAndPrincipal, RoleAccess> cache = ZTSClientCache.getInstance().getRoleAccessCache();
if (cache != null) {
cacheKey = new ZTSClientCache.DomainAndPrincipal(domainName, principal);
RoleAccess cachedValue = cache.get(cacheKey);
We don't have to since it's still the same identity (just a new token) and it's just a lookup - anyone with just read credentials can get the access so it's not one of our access tokens where we need to protect and include which principal used that to get the token since the token is based on the principal itself.
* @return RoleAccess object on success. ZTSClientException will be thrown in case of failure
*/
public RoleAccess getRoleAccess(String domainName, String principal) {
+ updateServicePrincipal();
// Try to fetch from cache.
ZTSClientCache.DomainAndPrincipal cacheKey = null;
+ Cache<ZTSClientCache.DomainAndPrincipal, RoleAccess> cache = ztsClientCache.getRoleAccessCache();
if (cache != null) {
cacheKey = new ZTSClientCache.DomainAndPrincipal(domainName, principal);
RoleAccess cachedValue = cache.get(cacheKey); |
codereview_java_data_4493 | import java.util.List;
-public class ASTAnnotationTypeDeclaration extends ASTAnyTypeDeclaration {
public ASTAnnotationTypeDeclaration(int id) {
this is a breaking API change. Do we really need to do it in 6.2.0? Can't we just deprecate the methods?
import java.util.List;
+public class ASTAnnotationTypeDeclaration extends AbstractAnyTypeDeclaration{
public ASTAnnotationTypeDeclaration(int id) { |
codereview_java_data_4503 | private boolean isFunction(Production prod) {
Production realProd = prod.att().get("originalPrd", Production.class);
- if (!realProd.att().contains(Attribute.FUNCTION_KEY) && !realProd.att().contains(Attribute.ML_SYMBOL_KEY)) {
return false;
}
return true;
Again, I would rather call ConstructorChecks.isBuiltinLabel here.
private boolean isFunction(Production prod) {
Production realProd = prod.att().get("originalPrd", Production.class);
+ if (!realProd.att().contains(Attribute.FUNCTION_KEY) && !isBuiltinProduction(realProd)) {
return false;
}
return true; |
codereview_java_data_4504 | /**
* auth type AK/SK.
*/
- AKSK;
private String position;
Not need this enum. if you use enum, auth develop will need change the original codes when they add an new plugin.
/**
* auth type AK/SK.
*/
+ AKSK,
+ /**
+ * other auth type.
+ */
+ others;
private String position; |
codereview_java_data_4508 | /** Cache of pre-generated handlers by provider and kind of metadata.
* For the cache to be effective, providers should implement identity
* correctly. */
- @SuppressWarnings("unchecked")
private static final LoadingCache<Key, MetadataHandler<?>> HANDLERS =
maxSize(CacheBuilder.newBuilder(),
CalciteSystemProperty.METADATA_HANDLER_CACHE_MAXIMUM_SIZE.value())
Is this `SuppressWarnings` annotation still needed?
/** Cache of pre-generated handlers by provider and kind of metadata.
* For the cache to be effective, providers should implement identity
* correctly. */
private static final LoadingCache<Key, MetadataHandler<?>> HANDLERS =
maxSize(CacheBuilder.newBuilder(),
CalciteSystemProperty.METADATA_HANDLER_CACHE_MAXIMUM_SIZE.value()) |
codereview_java_data_4514 | // Checks if input schema and table schema are same(default: true)
public static final String CHECK_ORDERING = "check-ordering";
- // File scan task set ID that is being rewritten
public static final String REWRITTEN_FILE_SCAN_TASK_SET_ID = "rewritten-file-scan-task-set-id";
}
Should we be sharing this property key with the read? Maybe it should be belong to the file-scan-task object itself?
// Checks if input schema and table schema are same(default: true)
public static final String CHECK_ORDERING = "check-ordering";
+ // File scan task set ID that indicates which files must be replaced
public static final String REWRITTEN_FILE_SCAN_TASK_SET_ID = "rewritten-file-scan-task-set-id";
} |
codereview_java_data_4524 | return (RET) attach(
flatMapUsingServiceAsyncBatchedTransform(
- transform, operationName, serviceFactory, 2, maxBatchSize, flattenedFn),
fnAdapter);
}
This `2` is burried to deeply, should extract a descriptive constant
return (RET) attach(
flatMapUsingServiceAsyncBatchedTransform(
+ transform, operationName, serviceFactory, MAX_CONCURRENT_ASYNC_BATCHES, maxBatchSize, flattenedFn),
fnAdapter);
} |
codereview_java_data_4532 | }
@Test
- public void dropNamespace_notEmpty() {
Mockito.doReturn(GetTablesResponse.builder()
.tableList(
Table.builder().databaseName("db1").name("t1").parameters(
I think we should also test the case where the namespace is non-empty, but there is no Iceberg table.
}
@Test
+ public void dropNamespace_notEmpty_containsIcebergTable() {
Mockito.doReturn(GetTablesResponse.builder()
.tableList(
Table.builder().databaseName("db1").name("t1").parameters( |
codereview_java_data_4540 | allDemands.add(f.getName());
}
// also consider static fields, that are not public
- int requiredMod = Modifier.STATIC;
for (Field f : type.getDeclaredFields()) {
- if ((f.getModifiers() & requiredMod) == requiredMod) {
allDemands.add(f.getName());
}
}
Maybe use `Modifier.isStatic(f.getModifiers())` instead ?
allDemands.add(f.getName());
}
// also consider static fields, that are not public
for (Field f : type.getDeclaredFields()) {
+ if (Modifier.isStatic(f.getModifiers())) {
allDemands.add(f.getName());
}
} |
codereview_java_data_4546 | private void initializeActionBar() {
ActionBar actionBar = getActionBar();
-
- actionBar.setDisplayShowCustomEnabled(true);
- actionBar.setCustomView(R.layout.actionbar_custom);
actionBar.setDisplayHomeAsUpEnabled(true);
}
We didn't use the custom action bar before. No need to use it now.
private void initializeActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
} |
codereview_java_data_4548 | public abstract String getTable() throws TableNotFoundException;
/**
- * @return tablet that's is compacting
* @since 1.7.0
*/
public abstract TabletId getTablet();
Should be "that is" or "that's"
public abstract String getTable() throws TableNotFoundException;
/**
+ * @return tablet that is compacting
* @since 1.7.0
*/
public abstract TabletId getTablet(); |
codereview_java_data_4557 | import org.dom4j.Element;
import org.jivesoftware.openfire.Connection;
import org.xmpp.packet.Packet;
/**
* XEP-0198 Stream Manager.
Alternatively could use: `new PacketError(PacketError.Condition.unexpected_request).toXML()` ... initialized perhaps as a static for the sake of efficiency
import org.dom4j.Element;
import org.jivesoftware.openfire.Connection;
import org.xmpp.packet.Packet;
+import org.xmpp.packet.PacketError;
/**
* XEP-0198 Stream Manager. |
codereview_java_data_4558 | // exfiltrate the objects from a raw-typed WriteBatch.
private void addWriteRequestsToMap(WriteBatch writeBatch, Map<String, Collection<WriteRequest>> writeRequestMap) {
MappedTableResource mappedTableResource = writeBatch.mappedTableResource();
- Collection<BatchableWriteOperation> writeBatchOperations = writeBatch.writeOperations();
Collection<WriteRequest> writeRequestsForTable = writeRequestMap
.computeIfAbsent(mappedTableResource.tableName(), ignored -> new ArrayList<>());
The type erasure problem no longer exists due to this refactor, therefore we should be able to do a straight map into WriteRequests
// exfiltrate the objects from a raw-typed WriteBatch.
private void addWriteRequestsToMap(WriteBatch writeBatch, Map<String, Collection<WriteRequest>> writeRequestMap) {
MappedTableResource mappedTableResource = writeBatch.mappedTableResource();
+ Collection<BatchableWriteOperation> writeBatchOperations = writeBatchOperations(writeBatch);
Collection<WriteRequest> writeRequestsForTable = writeRequestMap
.computeIfAbsent(mappedTableResource.tableName(), ignored -> new ArrayList<>()); |
codereview_java_data_4568 | import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
-import java.util.Optional;
import com.google.common.io.Files;
import org.apache.logging.log4j.LogManager;
Doesn't look like this needs to be wrapped in an `Optional` now?
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import com.google.common.io.Files;
import org.apache.logging.log4j.LogManager; |
codereview_java_data_4576 | }
protected JobGroupInfo newJobGroupInfo(String groupId, String desc) {
- return new JobGroupInfo(groupId, desc + "-" + jobCounter.incrementAndGet(), false);
}
/**
* Returns all the path locations of all Manifest Lists for a given list of snapshots
I think I made a typo in the snippet. We should probably append jobCounter to id, not desc. My bad.
}
protected JobGroupInfo newJobGroupInfo(String groupId, String desc) {
+ return new JobGroupInfo(groupId + "-" + jobCounter.incrementAndGet(), desc, false);
}
/**
* Returns all the path locations of all Manifest Lists for a given list of snapshots |
codereview_java_data_4578 | String keyString = key;
try {
- synchronized (getName() + keyString.intern()) {
if (properties.containsKey(keyString)) {
String originalValue = properties.get(keyString);
answer = properties.put(keyString, value);
Is this right? I think this would result in a non-interned String, which would be a temporary object here, and so not syncrhonize properly. Appreciate this is existing code, but might be nice to fix if needed.
String keyString = key;
try {
+ synchronized ((getName() + keyString).intern()) {
if (properties.containsKey(keyString)) {
String originalValue = properties.get(keyString);
answer = properties.put(keyString, value); |
codereview_java_data_4585 | @Test
public void descriptionAndBlockTagsAreRetrievable() {
Javadoc javadoc = JavaParser.parseJavadoc("first line\nsecond line\n\n@param node a node\n@return result the result");
- assertEquals(javadoc.getDescription().toText(), "first line\nsecond line");
- assertEquals(2, javadoc.getBlockTagCount());
}
@Test
We should also invert this one
@Test
public void descriptionAndBlockTagsAreRetrievable() {
Javadoc javadoc = JavaParser.parseJavadoc("first line\nsecond line\n\n@param node a node\n@return result the result");
+ assertEquals("first line\nsecond line", javadoc.getDescription().toText());
+ assertEquals(2, javadoc.getBlockTags().size());
}
@Test |
codereview_java_data_4597 | /*
Copyright 2007-2009 Selenium committers
Licensed under the Apache License, Version 2.0 (the "License");
Change this to: ``` Copyright 2015 Software Freedom Conservancy Copyright 2007-2009 Selenium committers ```
/*
+Copyright 2015 Software Freedom Conservancy
Copyright 2007-2009 Selenium committers
Licensed under the Apache License, Version 2.0 (the "License"); |
codereview_java_data_4607 | };
}
- static protected TextView getTxtvFFFromActivity(MediaplayerActivity activity) {
return activity.txtvFF;
}
- static protected TextView getTxtvRevFromActivity(MediaplayerActivity activity) {
return activity.txtvRev;
}
can you change this to `protected static`? This order is really unconventional
};
}
+ protected static TextView getTxtvFFFromActivity(MediaplayerActivity activity) {
return activity.txtvFF;
}
+ protected static TextView getTxtvRevFromActivity(MediaplayerActivity activity) {
return activity.txtvRev;
} |
codereview_java_data_4628 | productRepository = ProductRepository.getInstance();
mDataObserver = new DataObserver();
bottomNavigationView = view.findViewById((R.id.bottom_navigation));
- bottomNavigationView.getMenu().getItem(0).setCheckable(false);
BottomNavigationListenerInstaller.install(bottomNavigationView,getActivity(),getContext());
productRepository.getAllergensByEnabledAndLanguageCode(true, Locale.getDefault().getLanguage());
Is it possible to put the line `bottomNavigationView.getMenu().getItem(0).setCheckable(false);` in the method `BottomNavigationListenerInstaller.install(bottomNavigationView, getActivity(), getContext());` instead of in the calling fragment and avoid repeat the line in all fragments
productRepository = ProductRepository.getInstance();
mDataObserver = new DataObserver();
bottomNavigationView = view.findViewById((R.id.bottom_navigation));
+ BottomNavigationListenerInstaller.selectNavigationItem(bottomNavigationView, 0);
BottomNavigationListenerInstaller.install(bottomNavigationView,getActivity(),getContext());
productRepository.getAllergensByEnabledAndLanguageCode(true, Locale.getDefault().getLanguage()); |
codereview_java_data_4657 | if (countDownLatch.await(2, TimeUnit.SECONDS)) {
// Compare sessionPresent flag from AWSIotMqttManager with the actual one
assertEquals(testSessionPresentFlag.getSessionPresent(), actualSessionPresent);
}
}
```suggestion if (countDownLatch.await(2, TimeUnit.SECONDS)) { // Compare sessionPresent flag from AWSIotMqttManager with the actual one assertEquals(testSessionPresentFlag.getSessionPresent(), actualSessionPresent); } else { fail("CountDownLatch timed out."); } ``` If the latch times out, then the `await` will return `false` and never assert anything, causing the test to pass erroneously.
if (countDownLatch.await(2, TimeUnit.SECONDS)) {
// Compare sessionPresent flag from AWSIotMqttManager with the actual one
assertEquals(testSessionPresentFlag.getSessionPresent(), actualSessionPresent);
+ } else {
+ fail("CountDownLatch timed out.");
}
} |
codereview_java_data_4658 | * the timestamps would be grouped into the following windows:
*
* <pre>
- * [0, 1], [0, 1, 2, 3], [3, 4, 5, 6], [5, 6]
* </pre>
*
* A sliding window where window size and slide by are the same is equivalent to a
Is it correct? Should not it be [0, 1], [0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6], [6] ?
* the timestamps would be grouped into the following windows:
*
* <pre>
+ * [0, 1], [0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6], [6]
* </pre>
*
* A sliding window where window size and slide by are the same is equivalent to a |
codereview_java_data_4659 | final static int ONE_SECOND = 1000;
final static long TIME_TO_WAIT_BETWEEN_SCANS = 60 * ONE_SECOND;
- final static long TIME_TO_CACHE_RECOVERY_WAL_EXISTENCE = 20 * ONE_SECOND;
final private static long TIME_BETWEEN_MIGRATION_CLEANUPS = 5 * 60 * ONE_SECOND;
final static long WAIT_BETWEEN_ERRORS = ONE_SECOND;
final private static long DEFAULT_WAIT_FOR_WATCHER = 10 * ONE_SECOND;
This should be private. It doesn't need to be available outside this class. Also, it'd probably be better to express these constants using TimeUnit conversions, rather than custom multipliers, as in: ```suggestion private static final long TIME_TO_CACHE_RECOVERY_WAL_EXISTENCE = TimeUnit.SECONDS.toMillis(20); ```
final static int ONE_SECOND = 1000;
final static long TIME_TO_WAIT_BETWEEN_SCANS = 60 * ONE_SECOND;
+ // made this less than TIME_TO_WAIT_BETWEEN_SCANS, so that the cache is cleared between cycles
+ final static long TIME_TO_CACHE_RECOVERY_WAL_EXISTENCE = (3 * TIME_TO_WAIT_BETWEEN_SCANS) / 4;
final private static long TIME_BETWEEN_MIGRATION_CLEANUPS = 5 * 60 * ONE_SECOND;
final static long WAIT_BETWEEN_ERRORS = ONE_SECOND;
final private static long DEFAULT_WAIT_FOR_WATCHER = 10 * ONE_SECOND; |
codereview_java_data_4660 | }
public void testParseDateWithForCest() throws Exception {
- GregorianCalendar exp1 = new GregorianCalendar(2017, 0, 28, 22, 00, 00);
exp1.setTimeZone(TimeZone.getTimeZone("UTC"));
Date expected1 = new Date(exp1.getTimeInMillis());
Date actual1 = DateUtils.parse("Sun, 29 Jan 2017 00:00:00 CEST");
assertEquals(expected1, actual1);
- GregorianCalendar exp2 = new GregorianCalendar(2017, 0, 28, 23, 00, 00);
exp2.setTimeZone(TimeZone.getTimeZone("UTC"));
Date expected2 = new Date(exp2.getTimeInMillis());
Date actual2 = DateUtils.parse("Sun, 29 Jan 2017 00:00:00 CET");
Intellij warns that `00` is octal. Shouldn't be a problem but maybe we can avoid the warnings by just writing a single `0`
}
public void testParseDateWithForCest() throws Exception {
+ GregorianCalendar exp1 = new GregorianCalendar(2017, 0, 28, 22, 0, 0);
exp1.setTimeZone(TimeZone.getTimeZone("UTC"));
Date expected1 = new Date(exp1.getTimeInMillis());
Date actual1 = DateUtils.parse("Sun, 29 Jan 2017 00:00:00 CEST");
assertEquals(expected1, actual1);
+ GregorianCalendar exp2 = new GregorianCalendar(2017, 0, 28, 23, 0, 0);
exp2.setTimeZone(TimeZone.getTimeZone("UTC"));
Date expected2 = new Date(exp2.getTimeInMillis());
Date actual2 = DateUtils.parse("Sun, 29 Jan 2017 00:00:00 CET"); |
codereview_java_data_4670 | LOG.debug("retrieveJWSDomain: retrieving domain {}", domainName);
}
- AthenzDomain athenzDomain = getAthenzDomain(domainName, true);
if (athenzDomain == null) {
return null;
}
why was the master flag set to false removed here since it ends up calling the same method?
LOG.debug("retrieveJWSDomain: retrieving domain {}", domainName);
}
+ AthenzDomain athenzDomain = getAthenzDomain(domainName, true, false);
if (athenzDomain == null) {
return null;
} |
codereview_java_data_4679 | throw new RuntimeException(msg);
}
try {
long flushID = getFlushID();
if (lastFlushID != 0 && flushID == 0) {
Didn't look at the rest of the PR, but one quick note: we'd want to log or throw these exceptions, rather than print them.
throw new RuntimeException(msg);
}
+ // If a table hasn't been flushed before it was closed then lastFlushID will be -1 while
+ // getFlushID will be 0.
try {
long flushID = getFlushID();
if (lastFlushID != 0 && flushID == 0) { |
codereview_java_data_4680 | @Override
public AccessResource parse(RemotingCommand request, String remoteAddr) {
PlainAccessResource accessResource = new PlainAccessResource();
- accessResource.setWhiteRemoteAddress(remoteAddr.split(":")[0]);
accessResource.setRequestCode(request.getCode());
accessResource.setAccessKey(request.getExtFields().get(SessionCredentials.ACCESS_KEY));
accessResource.setSignature(request.getExtFields().get(SessionCredentials.SIGNATURE));
It is better to check before split. If remoteAddr does not contains ':' , just set the original value, otherwise split it.
@Override
public AccessResource parse(RemotingCommand request, String remoteAddr) {
PlainAccessResource accessResource = new PlainAccessResource();
+ if (remoteAddr != null && remoteAddr.contains(":")) {
+ accessResource.setWhiteRemoteAddress(remoteAddr.split(":")[0]);
+ } else {
+ accessResource.setWhiteRemoteAddress(remoteAddr);
+ }
accessResource.setRequestCode(request.getCode());
accessResource.setAccessKey(request.getExtFields().get(SessionCredentials.ACCESS_KEY));
accessResource.setSignature(request.getExtFields().get(SessionCredentials.SIGNATURE)); |
codereview_java_data_4691 | import org.h2.table.TableFilter;
/**
- * An index for a function that returns a result set. Search is this index
* performs scan over all rows and should be avoided.
*/
public class FunctionIndex extends BaseIndex {
search is -> search in
import org.h2.table.TableFilter;
/**
+ * An index for a function that returns a result set. Search in this index
* performs scan over all rows and should be avoided.
*/
public class FunctionIndex extends BaseIndex { |
codereview_java_data_4699 | viewBinding.subscribeButton.setEnabled(true);
viewBinding.subscribeButton.setText(R.string.subscribe_label);
if (UserPreferences.isEnableAutodownload()) {
- viewBinding.autoDownloadCheckBox.setChecked(true);
viewBinding.autoDownloadCheckBox.setVisibility(View.VISIBLE);
}
}
I think it would be better to do this in XML, too. On my device, the line is executed again just before the settings are updated. That results in all feeds having autodl enabled, regardless of what you do with the checkbox
viewBinding.subscribeButton.setEnabled(true);
viewBinding.subscribeButton.setText(R.string.subscribe_label);
if (UserPreferences.isEnableAutodownload()) {
viewBinding.autoDownloadCheckBox.setVisibility(View.VISIBLE);
}
} |
codereview_java_data_4706 | try {
return LOCAL_DATE_OF_YEAR_MONTH_DAY.invoke(null, year, month, day);
} catch (InvocationTargetException e) {
- if (month == 2 && day == 29) {
// If proleptic Gregorian doesn't have such date use the next day
return LOCAL_DATE_OF_YEAR_MONTH_DAY.invoke(null, year, 3, 1);
}
since we're talking about proleptic, surely there should be a year < something condition here?
try {
return LOCAL_DATE_OF_YEAR_MONTH_DAY.invoke(null, year, month, day);
} catch (InvocationTargetException e) {
+ if (year <= 1500 && (year & 3) == 0 && month == 2 && day == 29) {
// If proleptic Gregorian doesn't have such date use the next day
return LOCAL_DATE_OF_YEAR_MONTH_DAY.invoke(null, year, 3, 1);
} |
codereview_java_data_4724 | * Helper to check all permissions defined on a plugin and see the state of each.
*
* @since 3.0.0
- * @return an map containing the permission names and the permission state
*/
public Map<String, PermissionState> getPermissionStates() {
return bridge.getPermissionStates(this);
We should probably rephrase this to talk about the "alias"
* Helper to check all permissions defined on a plugin and see the state of each.
*
* @since 3.0.0
+ * @return A mapping of permission aliases to the associated granted status.
*/
public Map<String, PermissionState> getPermissionStates() {
return bridge.getPermissionStates(this); |
codereview_java_data_4741 | return transportProvider;
}
- public synchronized Transport getInstance(Context context, StoreConfig storeConfig)
throws MessagingException {
String uri = storeConfig.getTransportUri();
if (uri.startsWith("smtp")) {
`getInstance` is weird. This method should probably be called `getTransport`.
return transportProvider;
}
+ public synchronized Transport getTransport(Context context, StoreConfig storeConfig)
throws MessagingException {
String uri = storeConfig.getTransportUri();
if (uri.startsWith("smtp")) { |
codereview_java_data_4750 | assertThatThrownBy(() -> sqlService.execute(
"SELECT *"
+ " FROM TABLE ("
- + "avro_file (path => '" + path + "')"
+ ")"
)).isInstanceOf(HazelcastSqlException.class)
.hasMessageContaining("The directory '" + path + "' does not exist");
```suggestion + "avro_file (path => '" + path + "')" ```
assertThatThrownBy(() -> sqlService.execute(
"SELECT *"
+ " FROM TABLE ("
+ + "avro_file (path => '" + path + "')"
+ ")"
)).isInstanceOf(HazelcastSqlException.class)
.hasMessageContaining("The directory '" + path + "' does not exist"); |
codereview_java_data_4761 | String result =
ConsumerRunningInfo.analyzeProcessQueue(next.getKey(), next.getValue());
if (result.length() > 0) {
- System.out.printf("%s", result);
}
}
} else {
If no need format, just `System.out.println`?
String result =
ConsumerRunningInfo.analyzeProcessQueue(next.getKey(), next.getValue());
if (result.length() > 0) {
+ System.out.printf(result);
}
}
} else { |
codereview_java_data_4762 | }
}
for (Production prod : iterable(module.productions())) {
- if (prod.att().contains("mlOp")) {
continue;
}
prod = computePolyProd(prod);
I would rather we call the function that enumerates the klabels than check an attribute like this.
}
}
for (Production prod : iterable(module.productions())) {
+ if (isBuiltinProduction(prod)) {
continue;
}
prod = computePolyProd(prod); |
codereview_java_data_4763 | public ResultWithGeneratedKeys executeUpdate(Object generatedKeysRequest) {
long start = 0;
Database database = session.getDatabase();
- Object sync = database.getMvStore() != null ? null : database.isMultiThreaded() ? session : database;
session.waitIfExclusiveModeEnabled();
boolean callStop = true;
boolean writing = !isReadOnly();
`Session` is usually locked before invocation of this method in `JdbcStatement.executeUpdateInternal()`, `executeInternal()`, `executeQuery()` etc. With such change there may be situations where `Session` is not locked at all, because transactional commands and internal usages of `SET` command have own code paths in `JdbcConnection`/`JdbcStatement` without synchronization. Is it safe? If such command will be executed at the same time as a normal command it may affect fields of the session in an unexpected way. For example, it can clear generated keys, override scope identities, `currentCommandStart` and `cancelAtNs`.
public ResultWithGeneratedKeys executeUpdate(Object generatedKeysRequest) {
long start = 0;
Database database = session.getDatabase();
+ Object sync = database.isMultiThreaded() || database.getMvStore() != null ? session : database;
session.waitIfExclusiveModeEnabled();
boolean callStop = true;
boolean writing = !isReadOnly(); |
codereview_java_data_4764 | }
public void saveResult(Optional<Integer> statusCode, Optional<String> responseBody, Optional<String> errorMessage, Optional<Throwable> throwable) {
- boolean inStartup = false;
- if (throwable.isPresent() && throwable.get() instanceof ConnectException) {
- inStartup = true;
- }
try {
SingularityTaskHealthcheckResult result = new SingularityTaskHealthcheckResult(statusCode, Optional.of(System.currentTimeMillis() - startTime), startTime, responseBody,
`boolean inStartup = throwable.isPresent() && throwable.get() instanceof ConnectException`
}
public void saveResult(Optional<Integer> statusCode, Optional<String> responseBody, Optional<String> errorMessage, Optional<Throwable> throwable) {
+ boolean inStartup = throwable.isPresent() && throwable.get() instanceof ConnectException;
try {
SingularityTaskHealthcheckResult result = new SingularityTaskHealthcheckResult(statusCode, Optional.of(System.currentTimeMillis() - startTime), startTime, responseBody, |
codereview_java_data_4768 | private static final int EXPECTED_DEFAULT_EPOCH_LENGTH = 30_000;
private static final int EXPECTED_DEFAULT_BLOCK_PERIOD = 1;
private static final int EXPECTED_DEFAULT_REQUEST_TIMEOUT = 1;
- private static final int EXPECTED_DEFAULT_MESSAGE_BUFFER_SIZE = 10_000;
@Test
public void shouldGetEpochLengthFromConfig() {
Are these oddly named? I.e. what does "EXPECTED_" indicate?
private static final int EXPECTED_DEFAULT_EPOCH_LENGTH = 30_000;
private static final int EXPECTED_DEFAULT_BLOCK_PERIOD = 1;
private static final int EXPECTED_DEFAULT_REQUEST_TIMEOUT = 1;
+ private static final int EXPECTED_DEFAULT_SEEN_MESSAGES_QUEUE_SIZE = 10_000;
+ private static final int EXPECTED_DEFAULT_EVENT_SIZE = 1000;
@Test
public void shouldGetEpochLengthFromConfig() { |
codereview_java_data_4770 | }
public boolean isInsideTranscodeFolder() {
- return parent != null && parent instanceof FileTranscodeVirtualFolder;
}
/**
`parent instanceof FileTranscodeVirtualFolder` also checks that it's non-null. `null` is never the instance of anything.
}
public boolean isInsideTranscodeFolder() {
+ return parent instanceof FileTranscodeVirtualFolder;
}
/** |
codereview_java_data_4771 | sb.append(",");
}
- if (MESSAGE_DIGEST != null) {
- synchronized (LOCK) {
- checksum =
- new BigInteger(1, MESSAGE_DIGEST.digest((sb.toString()).getBytes(Charset.forName("UTF-8")))).toString(16);
- }
} else {
checksum = RandomStringUtils.randomAscii(32);
}
Can ThreadLocal be used to avoid lock contention
sb.append(",");
}
+ if (MESSAGE_DIGEST_LOCAL.get() != null) {
+ checksum = new BigInteger(1,
+ MESSAGE_DIGEST_LOCAL.get().digest((sb.toString()).getBytes(Charset.forName("UTF-8"))))
+ .toString(16);
} else {
checksum = RandomStringUtils.randomAscii(32);
} |
codereview_java_data_4779 | //checks the product states_tags to determine which prompt to be shown
List<String> statesTags = product.getStatesTags();
- if (statesTags.contains(product.getLang()+":categories-to-be-completed")) {
showCategoryPrompt = true;
}
if (product.getNoNutritionData() != null && product.getNoNutritionData().equals("on")) {
showNutrientPrompt = false;
} else {
- if (statesTags.contains(product.getLang()+":nutrition-facts-to-be-completed")) {
showNutrientPrompt = true;
}
}
not quite sure why you're trying to change the language and put an English states. If you query on world.openfoodfacts.org, the states will always be `en:categories-to-be-completed` If you query on fr.openfoodfacts.org, the states will always be `fr:categories-a-completer` So the easiest way would be to use the english version of states, which is the canonical one
//checks the product states_tags to determine which prompt to be shown
List<String> statesTags = product.getStatesTags();
+ if (statesTags.contains("en:categories-to-be-completed")) {
showCategoryPrompt = true;
}
if (product.getNoNutritionData() != null && product.getNoNutritionData().equals("on")) {
showNutrientPrompt = false;
} else {
+ if (statesTags.contains("en:nutrition-facts-to-be-completed")) {
showNutrientPrompt = true;
}
} |
codereview_java_data_4781 | String getTraceId(HttpServletRequest req) {
final String stringValue = getStringParameter(req, "id", null);
return TRACE_ID_PATTERN.matcher(stringValue).matches() ? stringValue : null;
}
This looks like it could produce an NPE from the matcher if `stringValue` is null. We probably want to add a check for that: ```suggestion if (stringValue == null) { return null; } return TRACE_ID_PATTERN.matcher(stringValue).matches() ? stringValue : null; ```
String getTraceId(HttpServletRequest req) {
final String stringValue = getStringParameter(req, "id", null);
+ if (stringValue == null) {
+ return null;
+ }
return TRACE_ID_PATTERN.matcher(stringValue).matches() ? stringValue : null;
} |
codereview_java_data_4782 | }
@Override
- protected Long sequenceNumber() {
return replaceSequenceNumber;
}
With this approach, I think we need a validation that none of the data or delete files that are being replaced have sequence numbers newer than the override sequence number.
}
@Override
+ protected Long sequenceNumberOverride() {
return replaceSequenceNumber;
} |
codereview_java_data_4787 | // if the db name is equal to the schema name
ArrayList<String> list = Utils.newSmallArrayList();
do {
- if (currentTokenType == DOT) {
- list.add(null);
- } else {
list.add(readUniqueIdentifier());
}
} while (readIf(DOT));
schemaName = session.getCurrentSchemaName();
Why you expect a dot here?
// if the db name is equal to the schema name
ArrayList<String> list = Utils.newSmallArrayList();
do {
+ if (currentTokenType != DOT) {
list.add(readUniqueIdentifier());
+ } else if(database.getMode().allowEmptySchemaValuesAsDefaultSchema) {
+ list.add(null);
}
} while (readIf(DOT));
schemaName = session.getCurrentSchemaName(); |
codereview_java_data_4788 | }
}
- if (tracing() != null) {
- options.decorator(BraveClient.newDecorator(tracing(), "elasticsearch"));
- }
-
clientCustomizer().accept(options);
HttpClientBuilder client = new HttpClientBuilder(clientUrl)
.factory(clientFactory())
I wonder if we can somehow bind auth to the client factory. if so it makes the rest a little easier I think.
}
}
clientCustomizer().accept(options);
HttpClientBuilder client = new HttpClientBuilder(clientUrl)
.factory(clientFactory()) |
codereview_java_data_4797 | return buf.append(arg);
}
- private static final Pattern SPLIT_NEWLINE_PATTERN;
- static {
- SPLIT_NEWLINE_PATTERN = Pattern.compile("\r\n|\r|\n");
- }
-
private void updateCursor(String arg) {
- String[] lines = SPLIT_NEWLINE_PATTERN.split(arg);
if ( lines.length == 0 ) {
cursor = Position.pos(cursor.line + 1, 0);
} else if ( lines.length == 1 ) {
Egh, end of line characters defined somewhere in the code. Will have to look into that later.
return buf.append(arg);
}
private void updateCursor(String arg) {
+ String[] lines = NEWLINE_PATTERN.split(arg);
if ( lines.length == 0 ) {
cursor = Position.pos(cursor.line + 1, 0);
} else if ( lines.length == 1 ) { |
codereview_java_data_4802 | @Unique
private String wikiDataId;
- private Boolean isWikiDataIdPresent;
-
@ToMany(joinProperties = {
@JoinProperty(name = "tag", referencedName = "ingredientTag")
})
Isn't **isWikiDataIdPresent** redundant since we can check by null/empty the **wikiDataId** itself?
@Unique
private String wikiDataId;
@ToMany(joinProperties = {
@JoinProperty(name = "tag", referencedName = "ingredientTag")
}) |
codereview_java_data_4803 | private final Schema schema;
private final List<PartitionField> fields = Lists.newArrayList();
private final Set<String> partitionNames = Sets.newHashSet();
- private Map<String, PartitionField> partitionFields = Maps.newHashMap();
private int specId = 0;
private final AtomicInteger lastAssignedFieldId = new AtomicInteger(PARTITION_DATA_ID_START - 1);
Overall LGTM, one nit is that I think `partitionFields` here would be good to be renamed so that it's easy to tell it's just for collision detection. Also I wonder if we want to do this check for other transformations too (e.g. bucket, and record numBuckets in the string), so that we might be able to combine `fields` and `partitionFields` into potentially something like a LinkedHashMap?
private final Schema schema;
private final List<PartitionField> fields = Lists.newArrayList();
private final Set<String> partitionNames = Sets.newHashSet();
+ private Map<Map.Entry<Integer, String>, PartitionField> dedupFields = Maps.newHashMap();
private int specId = 0;
private final AtomicInteger lastAssignedFieldId = new AtomicInteger(PARTITION_DATA_ID_START - 1); |
codereview_java_data_4808 | RelMdUtil.linear(querySpec.fieldNames.size(), 2, 100, 1d, 2d))
.multiplyBy(getQueryTypeCostMultiplier())
// a plan with sort pushed to druid is better than doing sort outside of druid
- .multiplyBy(Util.last(rels) instanceof Bindables.BindableSort ? 0.1 : 0.2);
}
private double getQueryTypeCostMultiplier() {
// Cost of Select > GroupBy > Timeseries > TopN
We should use the superclass in case other rules do not generate a Sort with bindable convention, i.e., use _instanceof Sort_ instead of _BindableSort_. Further, if last operator is not a SortLimit, we should just leave cost as it is, i.e., multiply by _1_ instead of _0.2_.
RelMdUtil.linear(querySpec.fieldNames.size(), 2, 100, 1d, 2d))
.multiplyBy(getQueryTypeCostMultiplier())
// a plan with sort pushed to druid is better than doing sort outside of druid
+ .multiplyBy(Util.last(rels) instanceof Sort ? 0.1 : 1);
}
private double getQueryTypeCostMultiplier() {
// Cost of Select > GroupBy > Timeseries > TopN |
codereview_java_data_4821 | public class ApexUnitTestMethodShouldHaveIsTestAnnotationRule extends AbstractApexUnitTestRule {
private static final String TEST = "test";
@Override
public Object visit(final ASTUserClass node, final Object data) {
// test methods should have @isTest annotation.
This rule could make use of rule chain as well. If you do this, then you don't call super here, but just `return data`, to avoid useless traversion of the AST.
public class ApexUnitTestMethodShouldHaveIsTestAnnotationRule extends AbstractApexUnitTestRule {
private static final String TEST = "test";
+ public ApexUnitTestMethodShouldHaveIsTestAnnotationRule() {
+ addRuleChainVisit(ASTUserClass.class);
+ }
+
@Override
public Object visit(final ASTUserClass node, final Object data) {
// test methods should have @isTest annotation. |
codereview_java_data_4825 | if (!PositionUtils.areInOrder(a, b)) {
return thereAreLinesBetween(b, a);
}
- int endOfA = a.getRange().get().end.line;
- return b.getRange().get().begin.line > endOfA + 1;
}
}
Maybe this is a little bit too long to write. Should we create & use a `getEndLine` method?
if (!PositionUtils.areInOrder(a, b)) {
return thereAreLinesBetween(b, a);
}
+ int endOfA = a.getEnd().get().line;
+ return b.getBegin().get().line > endOfA + 1;
}
} |
codereview_java_data_4827 | * A compatibility wrapper around {@link com.sun.tools.javac.util.Filter}.
* Adapted from {@link com.google.errorprone.util.ErrorProneScope} with additional methods.
*
* TODO(fwindheuser): Delete after upstreaming missing methods into "ErrorProneScope".
*/
@SuppressWarnings("ThrowError")
Let's add a link to `ErrorProneScope.java` upstream at the commit we borrowed from and note the license (Apache 2.0)
* A compatibility wrapper around {@link com.sun.tools.javac.util.Filter}.
* Adapted from {@link com.google.errorprone.util.ErrorProneScope} with additional methods.
*
+ * Original code from (Apache-2.0 License):
+ * https://github.com/google/error-prone/blob/ce87ca1c7bb005371837b82ffa69041dd8a356e5/check_api/src/main/java/com/google/errorprone/util/ErrorProneScope.java
+ *
* TODO(fwindheuser): Delete after upstreaming missing methods into "ErrorProneScope".
*/
@SuppressWarnings("ThrowError") |
codereview_java_data_4833 | */
public class DBWriter {
private static final String TAG = "DBWriter";
- private static final String PREF_QUEUE_ADD_TO_FRONT = "prefQueueAddToFront";
private static final ExecutorService dbExec;
Wouldn't this be better off in PreferenceController.java?
*/
public class DBWriter {
private static final String TAG = "DBWriter";
private static final ExecutorService dbExec; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.