method2testcases
stringlengths
118
6.63k
### Question: SafetyFactory { @Deprecated public static XMLInputFactory createXMLInputFactory() { return SafeStaxParserFactory.createXMLInputFactory(); } private SafetyFactory(); @Deprecated static XMLInputFactory createXMLInputFactory(); @Deprecated static DocumentBuilder createDocumentBuilder(boolean namespaceAware)...
### Question: RuleMetadataLoader { static String[] getStringArray(Map<String, Object> map, String propertyName) { Object propertyValue = map.get(propertyName); if (!(propertyValue instanceof List)) { throw new IllegalStateException(String.format(INVALID_PROPERTY_MESSAGE, propertyName)); } return ((List<String>) propert...
### Question: SafetyFactory { @Deprecated public static DocumentBuilder createDocumentBuilder(boolean namespaceAware) { return SafeDomParserFactory.createDocumentBuilder(namespaceAware); } private SafetyFactory(); @Deprecated static XMLInputFactory createXMLInputFactory(); @Deprecated static DocumentBuilder createDocu...
### Question: Resources { static String toString(String path, Charset charset) throws IOException { try (InputStream input = Resources.class.getClassLoader().getResourceAsStream(path)) { if (input == null) { throw new IOException("Resource not found in the classpath: " + path); } ByteArrayOutputStream out = new ByteArr...
### Question: ExternalReportProvider { public static List<File> getReportFiles(SensorContext context, String externalReportsProperty) { boolean externalIssuesSupported = context.getSonarQubeVersion().isGreaterThanOrEqual(Version.create(7, 2)); String[] reportPaths = context.config().getStringArray(externalReportsProper...
### Question: ContainsDetector extends Detector { @Override public int scan(String line) { String lineWithoutWhitespaces = StringUtils.deleteWhitespace(line); int matchers = 0; for (String str : strs) { matchers += StringUtils.countMatches(lineWithoutWhitespaces, str); } return matchers; } ContainsDetector(double proba...
### Question: EndWithDetector extends Detector { @Override public int scan(String line) { for (int index = line.length() - 1; index >= 0; index--) { char character = line.charAt(index); for (char endOfLine : endOfLines) { if (character == endOfLine) { return 1; } } if (!Character.isWhitespace(character) && character !=...
### Question: CamelCaseDetector extends Detector { @Override public int scan(String line) { char previousChar = ' '; char indexChar; for (int i = 0; i < line.length(); i++) { indexChar = line.charAt(i); if (isLowerCaseThenUpperCase(previousChar, indexChar)) { return 1; } previousChar = indexChar; } return 0; } CamelCas...
### Question: XmlFile { @CheckForNull public static Node nodeAttribute(Node node, String attribute) { NamedNodeMap attributes = node.getAttributes(); if (attributes == null) { return null; } return attributes.getNamedItem(attribute); } private XmlFile(InputFile inputFile); private XmlFile(String str); static XmlFile ...
### Question: KeywordsDetector extends Detector { @Override public int scan(String line) { int matchers = 0; if (toUpperCase) { line = line.toUpperCase(Locale.getDefault()); } StringTokenizer tokenizer = new StringTokenizer(line, " \t(),{}"); while (tokenizer.hasMoreTokens()) { String word = tokenizer.nextToken(); if (...
### Question: CodeRecognizer { public final boolean isLineOfCode(String line) { return recognition(line) - threshold > 0; } CodeRecognizer(double threshold, LanguageFootprint language); final double recognition(String line); final List<String> extractCodeLines(List<String> lines); final boolean isLineOfCode(String line...
### Question: CodeRecognizer { public final List<String> extractCodeLines(List<String> lines) { List<String> codeLines = new ArrayList<>(); for (String line : lines) { if (recognition(line) >= threshold) { codeLines.add(line); } } return codeLines; } CodeRecognizer(double threshold, LanguageFootprint language); final d...
### Question: ProgressReport implements Runnable { public synchronized void cancel() { thread.interrupt(); join(); } ProgressReport(String threadName, long period, Logger logger, String adjective); ProgressReport(String threadName, long period, String adjective); ProgressReport(String threadName, long period); @Overr...
### Question: ProfileGenerator { public static File generateProfile(String serverUrl, String language, String repository, RulesConfiguration rulesConfiguration, Set<String> excludedRules) { try { Set<String> ruleKeys = getRuleKeys(serverUrl, language, repository); ruleKeys.removeAll(excludedRules); return generateProfi...
### Question: JsonParser { Map<String, Object> parse(String data) { try { return (Map<String, Object>) parser.parse(data); } catch (ParseException e) { throw new IllegalArgumentException("Could not parse JSON", e); } } }### Answer: @Test public void parse() throws Exception { JsonParser parser = new JsonParser(); Ma...
### Question: ReflectionResource { @POST public Reflection createReflection(Reflection reflection) { ReflectionGoal newReflection = reflectionServiceHelper.createReflection(reflection.toReflectionGoal()); String id = newReflection.getId().getId(); return new Reflection(newReflection, reflectionServiceHelper.getStatusFo...
### Question: ReflectionResource { @DELETE @Path("/{id}") public Response deleteReflection(@PathParam("id") String id) { reflectionServiceHelper.removeReflection(id); return Response.ok().build(); } @Inject ReflectionResource(ReflectionServiceHelper reflectionServiceHelper, CatalogServiceHelper catalogServiceHelper); ...
### Question: SourceResource { @GET @RolesAllowed({"admin", "user"}) public ResponseList<Source> getSources() { final ResponseList<Source> sources = new ResponseList<>(); final List<SourceConfig> sourceConfigs = sourceService.getSources(); for (SourceConfig sourceConfig : sourceConfigs) { Source source = fromSourceConf...
### Question: SourceResource { @POST @RolesAllowed({"admin"}) public SourceDeprecated addSource(SourceDeprecated source) { try { SourceConfig newSourceConfig = sourceService.createSource(source.toSourceConfig()); return fromSourceConfig(newSourceConfig); } catch (NamespaceException | ExecutionSetupException e) { throw ...
### Question: SourceResource { @PUT @RolesAllowed({"admin"}) @Path("/{id}") public SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source) { SourceConfig sourceConfig; try { sourceConfig = sourceService.updateSource(id, source.toSourceConfig()); return fromSourceConfig(sourceConfig); } catch ...
### Question: SourceResource { @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") public SourceDeprecated getSource(@PathParam("id") String id) throws NamespaceException { SourceConfig sourceConfig = sourceService.getById(id); return fromSourceConfig(sourceConfig); } @Inject SourceResource(SourceService sourceServic...
### Question: SetTableauDefaults extends UpgradeTask { @VisibleForTesting static boolean updateOptionsIfNeeded(Version previousVersion, Supplier<SystemOptionManager> optionManagerSupplier, boolean isOptionManagerOpen) throws Exception { if (Upgrade.UPGRADE_VERSION_ORDERING.compare(previousVersion, VERSION_460) >= 0) { ...
### Question: SourceResource { @VisibleForTesting protected SourceDeprecated fromSourceConfig(SourceConfig sourceConfig) { return new SourceDeprecated(sourceService.fromSourceConfig(sourceConfig)); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) R...
### Question: JobResource extends BaseResourceWithAllocator { @POST @Path("/{id}/cancel") public void cancelJob(@PathParam("id") String id) throws JobException { final String username = securityContext.getUserPrincipal().getName(); try { jobs.cancel(CancelJobRequest.newBuilder() .setUsername(username) .setJobId(JobsPro...
### Question: ClusterStatsResource { @VisibleForTesting public static Stats getSources(List<SourceConfig> allSources, SabotContext context){ final Stats resource = new Stats(); for (SourceConfig sourceConfig : allSources) { int pdsCount = -1; String type = sourceConfig.getType(); if(type == null && sourceConfig.getLega...
### Question: CatalogResource { @GET public ResponseList<? extends CatalogItem> listTopLevelCatalog(@QueryParam("include") final List<String> include) { return new ResponseList<>(catalogServiceHelper.getTopLevelCatalogItems(include)); } @Inject CatalogResource(CatalogServiceHelper catalogServiceHelper); @GET ResponseL...
### Question: UserResource { @GET @Path("/{id}") public User getUser(@PathParam("id") String id) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(new UID(id))); } @Inject UserResource(UserService userGroupService, NamespaceService namespaceService, @Context SecurityContext securityC...
### Question: UserResource { @RolesAllowed({"admin"}) @POST public User createUser(User user) throws IOException { final com.dremio.service.users.User userConfig = UserResource.addUser(of(user, Optional.empty()), user.getPassword(), userGroupService, namespaceService); return User.fromUser(userConfig); } @Inject UserR...
### Question: UserResource { @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") public User updateUser(User user, @PathParam("id") String id) throws UserNotFoundException, IOException, DACUnauthorizedException { if (Strings.isNullOrEmpty(id)) { throw new IllegalArgumentException("No user id provided"); } final com.dr...
### Question: UserResource { @GET @Path("/by-name/{name}") public User getUserByName(@PathParam("name") String name) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(name)); } @Inject UserResource(UserService userGroupService, NamespaceService namespaceService, @Context SecurityCont...
### Question: UserStats { public String getEdition() { return edition; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }### Answer: @Test public void testGetEdition() { UserStats.Builder stats = new...
### Question: UserStats { public List<Map<String, Object>> getUserStatsByDate() { return userStatsByDate; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }### Answer: @Test public void testGetStatsB...
### Question: UserStats { public List<Map<String, Object>> getUserStatsByWeek() { return userStatsByWeek; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }### Answer: @Test public void testGetStatsB...
### Question: UserStats { public List<Map<String, Object>> getUserStatsByMonth() { return userStatsByMonth; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }### Answer: @Test public void testGetStat...
### Question: MediaTypeFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { final UriInfo info = requestContext.getUriInfo(); MultivaluedMap<String, String> parameters = info.getQueryParameters(); String format = parameters.getFirst("format...
### Question: ClasspathHealthMonitor implements LiveHealthMonitor { @Override public boolean isHealthy() { logger.debug("Checking jars {}", necessaryJarFoldersSet.size()); for(String jarFolderPath : necessaryJarFoldersSet) { File jarFolder = new File(jarFolderPath); boolean folderAccessible = false; try { folderAccessi...
### Question: JSONJobDataFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (!APPLICATION_JSON_TYPE.equals(responseContext.getMediaType()) || !WebServer.X_DREMIO_JOB_DATA_NUMBERS_AS_STRINGS_SU...
### Question: JSONPrettyPrintFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { UriInfo info = requestContext.getUriInfo(); if (!info.getQueryParameters().containsKey("pretty")) { return; } Objec...
### Question: Doc { void generateDoc(String linkPrefix, PrintStream out) throws JsonMappingException, JsonProcessingException { Set<Class<?>> classes = new TreeSet<>(new Comparator<Class<?>>() { @Override public int compare(Class<?> o1, Class<?> o2) { return o1.getName().compareTo(o2.getName()); } }); classes.addAll(th...
### Question: HostProcessingRateUtil { public static Set<HostProcessingRate> computeRecordProcRateAtPhaseHostLevel(int major, Set<HostProcessingRate> hostProcessingRateSet) { if (hostProcessingRateSet == null || hostProcessingRateSet.isEmpty()) { return new TreeSet<>(); } Table<String, String, BigInteger> hostToColumnT...
### Question: HostProcessingRateUtil { public static Set<HostProcessingRate> computeRecordProcRateAtPhaseOperatorHostLevel(int major, List<ImmutablePair<UserBitShared.OperatorProfile, Integer>> ops, Table<Integer, Integer, String> majorMinorHostTable) { Table<String, String, BigInteger> hostToColumnToValueTable = HashB...
### Question: SimpleDurationFormat { static String formatNanos(long durationInNanos) { if (durationInNanos < 1) { return "0s"; } final long days = TimeUnit.NANOSECONDS.toDays(durationInNanos); final long hours = TimeUnit.NANOSECONDS.toHours(durationInNanos) - TimeUnit.DAYS.toHours(TimeUnit.NANOSECONDS.toDays(durationIn...
### Question: JobResultToLogEntryConverter implements Function<Job, LoggedQuery> { @Override public LoggedQuery apply(Job job) { final JobInfo info = job.getJobAttempt().getInfo(); final List<String> contextList = info.getContextList(); String outcomeReason = null; switch(job.getJobAttempt().getState()) { case CANCELED...
### Question: JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> T toStuff(Schema<T> protostuffSchema, M protobuf) { T message = protostuffSchema.newMessage(); ProtobufIOUtil.mergeFrom(protobuf.toByteArray(), message, protostuffSchema); return message; } private JobsProtoUt...
### Question: DatasetConfigUpgrade extends UpgradeTask implements LegacyUpgradeTask { @VisibleForTesting byte[] convertFromOldSchema(OldSchema oldSchema) { FlatBufferBuilder builder = new FlatBufferBuilder(); int[] fieldOffsets = new int[oldSchema.fieldsLength()]; for (int i = 0; i < oldSchema.fieldsLength(); i++) { fi...
### Question: AttemptsHelper { public static long getLegacyEnqueuedTime(JobAttempt jobAttempt) { final JobInfo jobInfo = jobAttempt.getInfo(); if (jobInfo == null) { return 0; } final ResourceSchedulingInfo schedulingInfo = jobInfo.getResourceSchedulingInfo(); if (schedulingInfo == null) { return 0; } final Long schedu...
### Question: AttemptsHelper { public Long getPlanningTime() { return getDuration(State.PLANNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAtt...
### Question: AttemptsHelper { public static long getLegacyExecutionTime(JobAttempt jobAttempt) { final JobInfo jobInfo = jobAttempt.getInfo(); if (jobInfo == null) { return 0; } final JobDetails jobDetails = jobAttempt.getDetails(); if (jobDetails == null) { return 0; } final long startTime = Optional.ofNullable(jobIn...
### Question: AttemptsHelper { public Long getPendingTime() { return getDuration(State.PENDING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttem...
### Question: AttemptsHelper { public Long getMetadataRetrievalTime() { return getDuration(State.METADATA_RETRIEVAL); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long get...
### Question: AttemptsHelper { public Long getEngineStartTime() { return getDuration(State.ENGINE_START); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime...
### Question: AttemptsHelper { public Long getQueuedTime() { return getDuration(State.QUEUED); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt...
### Question: AttemptsHelper { public Long getExecutionPlanningTime() { return getDuration(State.EXECUTION_PLANNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long get...
### Question: AttemptsHelper { public Long getStartingTime() { return getDuration(State.STARTING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAtt...
### Question: AttemptsHelper { public Long getRunningTime() { return getDuration(State.RUNNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttem...
### Question: SimpleUserService implements UserService { @Override public Iterable<? extends User> searchUsers(String searchTerm, String sortColumn, SortOrder order, Integer limit) throws IOException { limit = limit == null ? 10000 : limit; if (searchTerm == null || searchTerm.isEmpty()) { return getAllUsers(limit); } ...
### Question: MetricsCombiner { private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); } private MetricsCombiner(Stream<QueryProgressMetrics> executorMet...
### Question: ReconnectingConnection implements Closeable { public <R extends MessageLite, C extends RpcCommand<R, CONNECTION_TYPE>> void runCommand(C cmd) { if (closed.get()) { cmd.connectionFailed(FailureType.CONNECTION, new IOException("Connection has been closed: " + toString())); } ConnectionRunner r = new Connect...
### Question: RpcException extends IOException { public static <T extends Throwable> void propagateIfPossible(@Nullable RpcException e, Class<T> clazz) throws T { if (e == null) { return; } Throwable cause = e.getCause(); if (!(cause instanceof UserRemoteException)) { return; } UserRemoteException ure = (UserRemoteExce...
### Question: KeyPair extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2> KeyPair<K1, K2> of(List<Object> list) { checkArgument(list.size() == 2, "list should be of size 2, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 value2 = (K2...
### Question: KeyUtils { public static boolean equals(Object left, Object right) { if (left instanceof byte[] && right instanceof byte[]) { return Arrays.equals((byte[]) left, (byte[]) right); } return Objects.equals(left, right); } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(...
### Question: Clean { public static void go(String[] args) throws Exception { final DACConfig dacConfig = DACConfig.newConfig(); final Options options = Options.parse(args); if(options.help) { return; } if (!dacConfig.isMaster) { throw new UnsupportedOperationException("Cleanup should be run on master node"); } Optiona...
### Question: KeyUtils { public static String toString(Object key) { if (null == key) { return null; } return (key instanceof byte[] ? Arrays.toString((byte[]) key) : key.toString()); } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object ...
### Question: AdminCommandRunner { static void runCommand(String commandName, Class<?> command, String[] commandArgs) throws Exception { final Method mainMethod = command.getMethod("main", String[].class); Preconditions.checkState(Modifier.isStatic(mainMethod.getModifiers()) && Modifier.isPublic(mainMethod.getModifiers...
### Question: KeyUtils { public static int hash(Object... keys) { if (null == keys) { return 0; } int result = 1; for (Object key : keys) { result = 31 * result + hashCode(key); } return result; } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toStr...
### Question: KeyTriple extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2, K3> KeyTriple<K1, K2, K3> of(List<Object> list) { checkArgument(list.size() == 3, "list should be of size 3, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 ...
### Question: ReIndexer implements ReplayHandler { @Override public void put(String tableName, byte[] key, byte[] value) { if (!isIndexed(tableName)) { logger.trace("Ignoring put: {} on table '{}'", key, tableName); return; } final KVStoreTuple<?> keyTuple = keyTuple(tableName, key); final Document document = toDoc(tab...
### Question: ExportProfiles { private static void exportOffline(ExportProfilesOptions options, DACConfig dacConfig) throws Exception { Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("No database found. Profiles ...
### Question: ReIndexer implements ReplayHandler { @Override public void delete(String tableName, byte[] key) { if (!isIndexed(tableName)) { logger.trace("Ignoring delete: {} on table '{}'", key, tableName); return; } indexManager.getIndex(tableName) .deleteDocuments(keyAsTerm(keyTuple(tableName, key))); metrics(tableN...
### Question: TracingKVStore implements KVStore<K, V> { @Override public Document<K, V> get(K key, GetOption... options) { return trace("get", () -> delegate.get(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore...
### Question: TracingKVStore implements KVStore<K, V> { @Override public void delete(K key, DeleteOption... options) { trace("delete", () -> delegate.delete(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore<K,V>...
### Question: KVStoreOptionUtility { public static void validateOptions(KVStore.KVStoreOption... options) { if (null == options || options.length <= 1) { return; } boolean foundVersion = false; boolean foundCreate = false; for (KVStore.KVStoreOption option : options) { if (option == KVStore.PutOption.CREATE) { if (foun...
### Question: ResetCatalogSearch { static void go(String[] args) throws Exception { final DACConfig dacConfig = DACConfig.newConfig(); parse(args); if (!dacConfig.isMaster) { throw new UnsupportedOperationException("Reset catalog search should be run on master node"); } final Optional<LocalKVStoreProvider> providerOpti...
### Question: KVStoreOptionUtility { public static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options) { if (null == options || options.length == 0) { return; } for (KVStore.KVStoreOption option : options) { if (option instanceof IndexPutOption) { throw new IllegalArgumentException("IndexPutOption not s...
### Question: SystemStoragePluginInitializer implements Initializer<Void> { @VisibleForTesting void createOrUpdateSystemSource(final CatalogService catalogService, final NamespaceService ns, final SourceConfig config) throws Exception { try { config.setAllowCrossSourceSelection(true); final boolean isCreated = catalogS...
### Question: KVStoreOptionUtility { public static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options) { validateOptions(options); if (null == options || options.length == 0) { return Optional.empty(); } for (KVStore.KVStoreOption option : options) { if (option == KVStore.PutOption.CR...
### Question: DateUtils { public static long getStartOfLastMonth() { LocalDate now = LocalDate.now(); LocalDate targetDate = now.minusDays(now.getDayOfMonth() - 1).minusMonths(1); Instant instant = targetDate.atStartOfDay().toInstant(ZoneOffset.UTC); return instant.toEpochMilli(); } static long getStartOfLastMonth(); ...
### Question: KVStoreOptionUtility { public static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options) { if (null == options) { return null; } return Arrays .stream(options) .filter(option -> !(option instanceof IndexPutOption)) .toArray(KVStore.PutOption[]::new); } static void validateOptions(KVSto...
### Question: LegacyProtobufSerializer extends ProtobufSerializer<T> { public static <M extends Message> M parseFrom(Parser<M> parser, ByteString bytes) throws InvalidProtocolBufferException { return rewriteProtostuff(parser.parseFrom(bytes)); } LegacyProtobufSerializer(Class<T> clazz, Parser<T> parser); @Override T re...
### Question: DateUtils { public static LocalDate getLastSundayDate(final LocalDate dateWithinWeek) { int dayOfWeek = dateWithinWeek.getDayOfWeek().getValue(); dayOfWeek = (dayOfWeek == 7) ? 0 : dayOfWeek; return dateWithinWeek.minusDays(dayOfWeek); } static long getStartOfLastMonth(); static LocalDate getLastSundayDa...
### Question: DependencyGraph { public synchronized void loadFromStore() { for (Map.Entry<ReflectionId, ReflectionDependencies> entry : dependenciesStore.getAll()) { final List<ReflectionDependencyEntry> dependencies = entry.getValue().getEntryList(); if (dependencies == null || dependencies.isEmpty()) { continue; } tr...
### Question: ReflectionGoalChecker { public static boolean checkGoal(ReflectionGoal goal, Materialization materialization) { return Instance.isEqual(goal, materialization.getReflectionGoalVersion()); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal); boolean checkHash(ReflectionGoal g...
### Question: ReflectionGoalChecker { public boolean checkHash(ReflectionGoal goal, ReflectionEntry entry){ if(null == entry.getReflectionGoalHash()){ return false; } return entry.getReflectionGoalHash().equals(calculateReflectionGoalVersion(goal)); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal re...
### Question: DateUtils { public static LocalDate getMonthStartDate(final LocalDate dateWithinMonth) { int dayOfMonth = dateWithinMonth.getDayOfMonth(); return dateWithinMonth.minusDays((dayOfMonth - 1)); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static Lo...
### Question: OptionList extends ArrayList<OptionValue> { public void mergeIfNotPresent(OptionList list) { final Set<OptionValue> options = Sets.newTreeSet(this); for (OptionValue optionValue : list) { if (options.add(optionValue)) { this.add(optionValue); } } } void merge(OptionList list); void mergeIfNotPresent(Opti...
### Question: BoundCommandPool implements CommandPool { @Override public <V> CompletableFuture<V> submit(Priority priority, String descriptor, Command<V> command, boolean runInSameThread) { final long time = System.currentTimeMillis(); final CommandWrapper<V> wrapper = new CommandWrapper<>(priority, descriptor, time, c...
### Question: PartitionChunkId implements Comparable<PartitionChunkId> { @JsonCreator public static PartitionChunkId of(String partitionChunkId) { final String[] ids = partitionChunkId.split(DELIMITER, 3); Preconditions.checkArgument(ids.length == 3 && !ids[0].isEmpty() && !ids[1].isEmpty() && !ids[2].isEmpty(), "Inval...
### Question: DateUtils { public static LocalDate fromEpochMillis(final long epochMillis) { return Instant.ofEpochMilli(epochMillis).atZone(ZoneOffset.UTC).toLocalDate(); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final Lo...
### Question: DatasetStateMutator { public TransformResult apply(String oldCol, String newCol, ExpressionBase newExp, boolean dropSourceColumn) { return apply(oldCol, newCol, newExp.wrap(), dropSourceColumn); } DatasetStateMutator(String username, VirtualDatasetState virtualDatasetState, boolean preview); void setSql(Q...
### Question: PathUtils { public static final String join(final String... parts) { final StringBuilder sb = new StringBuilder(); for (final String part:parts) { Preconditions.checkNotNull(part, "parts cannot contain null"); if (!Strings.isNullOrEmpty(part)) { sb.append(part).append("/"); } } if (sb.length() > 0) { sb.d...
### Question: PathUtils { public static final String normalize(final String path) { if (Strings.isNullOrEmpty(Preconditions.checkNotNull(path))) { return path; } final StringBuilder builder = new StringBuilder(); char last = path.charAt(0); builder.append(last); for (int i=1; i<path.length(); i++) { char cur = path.cha...
### Question: QueueProcessor implements AutoCloseable { public QueueProcessor(String name, Supplier<AutoCloseableLock> lockSupplier, Consumer<T> consumer) { this.name = name; this.lockSupplier = lockSupplier; this.consumer = consumer; this.queue = new LinkedBlockingQueue<>(); this.workerThread = null; this.isClosed = f...
### Question: JmxConfigurator extends ReporterConfigurator { @Override public void configureAndStart(String name, MetricRegistry registry, MetricFilter filter) { reporter = JmxReporter.forRegistry(registry).convertRatesTo(rateUnit).convertDurationsTo(durationUnit).filter(filter).build(); reporter.start(); } @JsonCreato...
### Question: LocalSchedulerService implements SchedulerService { @Override public void close() throws Exception { LOGGER.info("Stopping SchedulerService"); AutoCloseables.close(AutoCloseables.iter(executorService), taskLeaderElectionServiceMap.values()); LOGGER.info("Stopped SchedulerService"); } LocalSchedulerService...
### Question: LocalSchedulerService implements SchedulerService { @VisibleForTesting public CloseableSchedulerThreadPool getExecutorService() { return executorService; } LocalSchedulerService(int corePoolSize); LocalSchedulerService(int corePoolSize, Provider<ClusterCoordinator> clusterC...
### Question: IncludesExcludesFilter implements MetricFilter { @Override public boolean matches(String name, Metric metric) { if (includes.isEmpty() || matches(name, includes)) { return allowedViaExcludes(name); } return false; } IncludesExcludesFilter(List<String> includes, List<String> excludes); @Override boolean ma...
### Question: MutableVarcharVector extends BaseVariableWidthVector { @Override public void close() { this.clear(); } MutableVarcharVector(String name, BufferAllocator allocator, double compactionThreshold); MutableVarcharVector(String name, FieldType fieldType, BufferAllocator allocator, double compactionThreshold); f...
### Question: UserRPCServer extends BasicServer<RpcType, UserRPCServer.UserClientConnectionImpl> { @Override protected Response handle(UserClientConnectionImpl connection, int rpcType, byte[] pBody, ByteBuf dBody) throws RpcException { throw new IllegalStateException("UserRPCServer#handle must not be invoked without Re...
### Question: QueriesClerk { QueriesClerk(final WorkloadTicketDepot workloadTicketDepot) { this.workloadTicketDepot = workloadTicketDepot; } QueriesClerk(final WorkloadTicketDepot workloadTicketDepot); void buildAndStartQuery(final PlanFragmentFull firstFragment, final SchedulingInfo schedulingInfo, ...
### Question: QueriesClerk { Collection<FragmentTicket> getFragmentTickets(QueryId queryId) { List<FragmentTicket> fragmentTickets = new ArrayList<>(); for (WorkloadTicket workloadTicket : getWorkloadTickets()) { QueryTicket queryTicket = workloadTicket.getQueryTicket(queryId); if (queryTicket != null) { for (PhaseTick...