_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q167100
SequenceFileStorage.verifyWritableClass
validation
private static <W extends Writable> void verifyWritableClass(Class<W> writableClass, boolean isKeyClass, WritableConverter<W> writableConverter) { Preconditions.checkNotNull(writableClass, "%s Writable class is undefined;" + " WritableConverter of type '%s' does not define default Writable type," + " and no type was specified by user", isKeyClass ? "Key" : "Value", writableConverter .getClass().getName()); }
java
{ "resource": "" }
q167101
ThriftConverter.newInstance
validation
public static <M extends TBase<?, ?>> ThriftConverter<M> newInstance(Class<M> tClass) { return new ThriftConverter<M>(new TypeRef<M>(tClass){}); }
java
{ "resource": "" }
q167102
PigUtil.getClass
validation
public static Class<?> getClass(String className) { try { return PigContext.resolveClassName(className); } catch (IOException e) { throw new RuntimeException("Could not instantiate " + className, e); } }
java
{ "resource": "" }
q167103
PigUtil.getThriftTypeRef
validation
public static<T extends TBase<?,?>> TypeRef<T> getThriftTypeRef(String thriftClassName) { return ThriftUtils.getTypeRef(getClass(thriftClassName)); }
java
{ "resource": "" }
q167104
RCFileUtil.findColumnsToRead
validation
public static ArrayList<Integer> findColumnsToRead( Configuration conf, List<Integer> currFieldIds, ColumnarMetadata storedInfo) throws IOException { ArrayList<Integer> columnsToRead = Lists.newArrayList(); // first find the required fields ArrayList<Integer> requiredFieldIds = Lists.newArrayList(); String reqFieldStr = conf.get(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, ""); int numKnownFields = currFieldIds.size(); if (reqFieldStr == null || reqFieldStr.equals("")) { for(int i=0; i<numKnownFields; i++) { requiredFieldIds.add(currFieldIds.get(i)); } } else { for (String str : reqFieldStr.split(",")) { int idx = Integer.valueOf(str); if (idx < 0 || idx >= numKnownFields) { throw new IOException("idx " + idx + " is out of range for known fields"); } requiredFieldIds.add(currFieldIds.get(idx)); } } List<Integer> storedFieldIds = storedInfo.getFieldIdList(); for(int i=0; i < storedFieldIds.size(); i++) { int sid = storedFieldIds.get(i); if (sid > 0 && requiredFieldIds.contains(sid)) { columnsToRead.add(i); } } // unknown fields : the required fields that are not listed in storedFieldIds String unknownFields = ""; for(int rid : requiredFieldIds) { if (!storedFieldIds.contains(rid)) { unknownFields += " " + rid; } } if (unknownFields.length() > 0) { int last = storedFieldIds.size() - 1; LOG.info("unknown fields among required fileds :" + unknownFields); if (storedFieldIds.get(last) != -1) { // not expected throw new IOException("No unknowns column in in input"); } columnsToRead.add(last); } LOG.info(String.format( "reading %d%s out of %d stored columns for %d required columns", columnsToRead.size(), (unknownFields.length() > 0 ? " (including unknowns column)" : ""), storedInfo.getFieldIdList().size(), requiredFieldIds.size())); return columnsToRead; }
java
{ "resource": "" }
q167105
LzoThriftB64LineOutputFormat.setClassConf
validation
public static <M extends TBase<?, ?>> void setClassConf(Class<M> thriftClass, Configuration jobConf) { ThriftUtils.setClassConf(jobConf, LzoThriftB64LineOutputFormat.class, thriftClass); }
java
{ "resource": "" }
q167106
RedditHttpClient.executeHttpRequest
validation
private String executeHttpRequest(HttpUriRequest request) { try { // Attempt to do execute request HttpResponse response = httpClient.execute(request); // Return response if successful if (response != null) { return EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (UnsupportedEncodingException uee) { LOGGER.warn("Unsupported Encoding Exception thrown in request", uee); } catch (ClientProtocolException cpe) { LOGGER.warn("Client Protocol Exception thrown in request", cpe); } catch (IOException ioe) { LOGGER.warn("I/O Exception thrown in request", ioe); } return null; }
java
{ "resource": "" }
q167107
RedditHttpClient.addAuthorization
validation
private void addAuthorization(HttpRequest request, RedditToken rToken) { request.addHeader("Authorization", rToken.getTokenType() + " " + rToken.getAccessToken()); }
java
{ "resource": "" }
q167108
RedditListingParser.validate
validation
public void validate(Object response) throws RedditParseException { // Check for null if (response == null) { throw new RedditParseException(); } // Check it is a JSON response if (!(response instanceof JSONObject)) { throw new RedditParseException("not a JSON response"); } // Cast to JSON object JSONObject jsonResponse = ((JSONObject) response); // Check for error if (jsonResponse.get("error") != null) { throw new RedditParseException(JsonUtils.safeJsonToInteger(jsonResponse.get("error"))); } // Check that data exists if (jsonResponse.get("data") == null && jsonResponse.get("json") == null) { throw new RedditParseException("data is missing from listing"); } }
java
{ "resource": "" }
q167109
RedditListingParser.parseThing
validation
private Thing parseThing(Kind kind, JSONObject data) { // For a comment if (kind == Kind.COMMENT) { return new Comment(data); // For a submission } else if (kind == Kind.LINK) { return new Submission(data); // For a subreddit } else if (kind == Kind.SUBREDDIT) { return new Subreddit(data); // For a more } else if (kind == Kind.MORE) { return new More(data); // In all other cases (null, or of a different type) } else { return null; } }
java
{ "resource": "" }
q167110
MixedListingParser.parse
validation
public List<MixedListingElement> parse(String jsonText) throws RedditParseException { // Parse to a list of things List<Thing> things = this.parseGeneric(jsonText); // List of comment and submission mixed elements List<MixedListingElement> mixedElements = new LinkedList<MixedListingElement>(); // Iterate over things for (Thing t : things) { if (t instanceof Comment) { mixedElements.add((Comment) t); } else if (t instanceof Submission) { mixedElements.add((Submission) t); } else { LOGGER.warn("Encountered an unexpected reddit thing (" + t.getKind().value() + "), skipping it."); } } // Return result return mixedElements; }
java
{ "resource": "" }
q167111
KeyValueFormatter.formatCommaSeparatedList
validation
public static String formatCommaSeparatedList(List<String> list) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < list.size(); i++) { if (i != 0) { builder.append(","); } builder.append(list.get(i)); } return builder.toString(); }
java
{ "resource": "" }
q167112
RedditPoliteClient.waitIfNeeded
validation
private void waitIfNeeded() { // Calculate elapsed milliseconds long elapsed = System.currentTimeMillis() - lastReqTime; // If enough time has elapsed, no need to wait if (elapsed >= interval) { return; } // If not enough time was elapsed, wait the remainder long toWait = interval - elapsed; try { Thread.sleep(toWait); } catch (InterruptedException ie) { LOGGER.warn("Interrupted Exception thrown while politely waiting for remainder of interval", ie); } }
java
{ "resource": "" }
q167113
RedditOAuthAgent.addBasicAuthentication
validation
private void addBasicAuthentication(OAuthClientRequest request, RedditApp app) { String authString = app.getClientID() + ":" + app.getClientSecret(); String authStringEnc = DatatypeConverter.printBase64Binary(authString.getBytes()); request.addHeader(HEADER_AUTHORIZATION, "Basic " + authStringEnc); }
java
{ "resource": "" }
q167114
RedditToken.refresh
validation
public void refresh(OAuthJSONAccessTokenResponse token) { this.accessToken = token.getAccessToken(); this.expiration = currentTimeSeconds() + token.getExpiresIn(); this.expirationSpan = token.getExpiresIn(); this.scopes = new RedditTokenCompleteScope(token.getScope()); this.tokenType = token.getParam(PARAM_TOKEN_TYPE); }
java
{ "resource": "" }
q167115
CommentTreeUtils.printCommentTree
validation
public static String printCommentTree(List<CommentTreeElement> cs) { StringBuilder builder = new StringBuilder(); for (CommentTreeElement c : cs) { builder.append(printCommentTree(c, 0)); } return builder.toString(); }
java
{ "resource": "" }
q167116
JsonUtils.safeJsonToInteger
validation
public static Integer safeJsonToInteger(Object obj) { Integer intValue = null; try { String str = safeJsonToString(obj); intValue = str != null ? Integer.parseInt(str) : null; } catch (NumberFormatException e) { LOGGER.warn("Safe JSON conversion to Integer failed", e); } return intValue; }
java
{ "resource": "" }
q167117
JsonUtils.safeJsonToDouble
validation
public static Double safeJsonToDouble(Object obj) { Double doubleValue = null; try { String str = safeJsonToString(obj); doubleValue = str != null ? Double.parseDouble(str) : null; } catch (NumberFormatException e) { LOGGER.warn("Safe JSON conversion to Double failed", e); } return doubleValue; }
java
{ "resource": "" }
q167118
JsonUtils.safeJsonToBoolean
validation
public static Boolean safeJsonToBoolean(Object obj) { String str = safeJsonToString(obj); Boolean booleanValue = str != null ? Boolean.parseBoolean(str) : null; return booleanValue; }
java
{ "resource": "" }
q167119
JsonUtils.safeJsonToLong
validation
public static Long safeJsonToLong(Object obj) { Long longValue = null; try { String str = safeJsonToString(obj); longValue = str != null ? Long.parseLong(str) : null; } catch (NumberFormatException e) { LOGGER.warn("Safe JSON conversion to Long failed", e); } return longValue; }
java
{ "resource": "" }
q167120
FullSubmissionParser.parseRecursive
validation
protected List<CommentTreeElement> parseRecursive(JSONObject main) throws RedditParseException { List<CommentTreeElement> commentTree = new ArrayList<CommentTreeElement>(); // Iterate over the comment tree results JSONArray array = (JSONArray) ((JSONObject) main.get("data")).get("children"); for (Object element : array) { // Get the element JSONObject data = (JSONObject) element; // Make sure it is of the correct kind String kind = safeJsonToString(data.get("kind")); // If it is a comment if (kind != null && kind.equals(Kind.COMMENT.value())) { // Create comment Comment comment = new Comment( (JSONObject) data.get("data") ); // Retrieve replies Object replies = ((JSONObject) data.get("data")).get("replies"); // If it is an JSON object if (replies instanceof JSONObject) { comment.setReplies(parseRecursive( (JSONObject) replies )); // If there are no replies, end with an empty one } else { comment.setReplies(new ArrayList<CommentTreeElement>()); } // Add comment to the tree commentTree.add(comment); } // If it is a more if (kind != null && kind.equals(Kind.MORE.value())) { // Add to comment tree commentTree.add(new More((JSONObject) data.get("data"))); } } return commentTree; }
java
{ "resource": "" }
q167121
SubredditsListingParser.parse
validation
public List<Subreddit> parse(String jsonText) throws RedditParseException { // Parse to a list of things List<Thing> things = this.parseGeneric(jsonText); // List of comment and submission mixed elements List<Subreddit> subreddits = new LinkedList<Subreddit>(); // Iterate over things for (Thing t : things) { if (t instanceof Subreddit) { subreddits.add((Subreddit) t); } else { LOGGER.warn("Encountered an unexpected reddit thing (" + t.getKind().value() + "), skipping it."); } } // Return resulting comments list return subreddits; }
java
{ "resource": "" }
q167122
EnforceSignedRequestUtils.signature
validation
public static String signature(String endpoint, Map<String, String> params, String clientSecret) throws InstagramException { SecretKeySpec keySpec = new SecretKeySpec(clientSecret.getBytes(UTF_8), HMAC_SHA256); // ensure we iterate through the keys in sorted order List<String> values = new ArrayList<String>(params.size()); for (String key : MapUtils.getSortedKeys(params)) { values.add(String.format("%s=%s", key, params.get(key))); } // the sig string to sign in the form "endpoint|key1=value1|key2=value2|...." String sig = String.format("%s|%s", endpoint, StringUtils.join(values, '|')); try { Mac mac = Mac.getInstance(HMAC_SHA256); mac.init(keySpec); byte[] result = mac.doFinal(sig.getBytes(UTF_8)); return Hex.encodeHexString(result); } catch (NoSuchAlgorithmException e) { throw new InstagramException("Invalid algorithm name!", e); } catch (InvalidKeyException e) { throw new InstagramException("Invalid key: " + clientSecret, e); } }
java
{ "resource": "" }
q167123
MapUtils.sort
validation
public static Map<String, String> sort(Map<String, String> map) { Preconditions.checkNotNull(map, "Cannot sort a null object."); Map<String, String> sorted = new LinkedHashMap<String, String>(); for (String key : getSortedKeys(map)) { sorted.put(key, map.get(key)); } return sorted; }
java
{ "resource": "" }
q167124
InstagramOembed.getOembedInformation
validation
public OembedInformation getOembedInformation(String url) throws InstagramException { String apiMethod = String.format(Methods.OEMBED_INFORMATION, url); return createInstagramObject(Verbs.GET, OembedInformation.class, apiMethod, null); }
java
{ "resource": "" }
q167125
InstagramOembed.createInstagramObject
validation
private static <T> T createInstagramObject(Verbs verbs, Class<T> clazz, String methodName, Map<String, String> params) throws InstagramException { Response response; try { response = getApiResponse(verbs, methodName, params); } catch (IOException e) { throw new InstagramException("IOException while retrieving data", e); } if (response.getCode() >= 200 && response.getCode() < 300) { return createObjectFromResponse(clazz, response.getBody()); } throw handleInstagramError(response); }
java
{ "resource": "" }
q167126
InstagramOembed.createObjectFromResponse
validation
private static <T> T createObjectFromResponse(Class<T> clazz, final String response) throws InstagramException { Gson gson = new Gson(); T object; try { object = gson.fromJson(response, clazz); } catch (Exception e) { throw new InstagramException("Error parsing json to object type " + clazz.getName(), e); } return object; }
java
{ "resource": "" }
q167127
Preconditions.checkBothNotNull
validation
public static void checkBothNotNull(Object object1, Object object2, String errorMsg) { check(!(object1 == null && object2 == null), errorMsg); }
java
{ "resource": "" }
q167128
Preconditions.checkEmptyString
validation
public static void checkEmptyString(String string, String errorMsg) { check(StringUtils.isNotBlank(string), errorMsg); }
java
{ "resource": "" }
q167129
Preconditions.checkValidUrl
validation
public static void checkValidUrl(String url, String errorMsg) { checkEmptyString(url, errorMsg); check(isUrl(url), errorMsg); }
java
{ "resource": "" }
q167130
Preconditions.checkValidOAuthCallback
validation
public static void checkValidOAuthCallback(String url, String errorMsg) { checkEmptyString(url, errorMsg); if (url.toLowerCase().compareToIgnoreCase(OAuthConstants.OUT_OF_BAND) != 0) { check(isUrl(url), errorMsg); } }
java
{ "resource": "" }
q167131
InstagramService.getSignedHeaderInstagram
validation
@Deprecated public InstagramClient getSignedHeaderInstagram(Token accessToken, String ipAddress) { return new Instagram(accessToken.getToken(), config.getApiSecret(), ipAddress); }
java
{ "resource": "" }
q167132
InstagramBase.configureConnectionSettings
validation
public static void configureConnectionSettings(final Request request, final InstagramConfig config) { request.setConnectTimeout(config.getConnectionTimeoutMills(), TimeUnit.MILLISECONDS); request.setReadTimeout(config.getReadTimeoutMills(), TimeUnit.MILLISECONDS); // #51 Connection Keep Alive request.setConnectionKeepAlive(config.isConnectionKeepAlive()); }
java
{ "resource": "" }
q167133
Request.getBodyContents
validation
public String getBodyContents() { try { return new String(getByteBodyContents(), getCharset()); } catch (UnsupportedEncodingException uee) { throw new OAuthException("Unsupported Charset: " + charset, uee); } }
java
{ "resource": "" }
q167134
LogHelper.prettyPrintJSONResponse
validation
public static void prettyPrintJSONResponse(Logger logger, String jsonString) { if(logger.isDebugEnabled()) { // it can fail...on 404 it usually not a json String s; try { final JsonElement element = new JsonParser().parse(jsonString); s = new GsonBuilder().setPrettyPrinting().create().toJson(element); } catch(Exception e) { s = jsonString; } logger.debug("Received JSON response from Instagram - " + s); } }
java
{ "resource": "" }
q167135
InstagramSubscription.callback
validation
public InstagramSubscription callback(String callback) { Preconditions.checkValidUrl(callback, "Invalid Callback Url"); this.params.put(Constants.CALLBACK_URL, callback); return this; }
java
{ "resource": "" }
q167136
InstagramSubscription.clientId
validation
public InstagramSubscription clientId(String clientId) { Preconditions.checkEmptyString(clientId, "Invalid 'clientId' key"); this.params.put(Constants.CLIENT_ID, clientId); return this; }
java
{ "resource": "" }
q167137
InstagramSubscription.clientSecret
validation
public InstagramSubscription clientSecret(String clientSecret) { Preconditions.checkEmptyString(clientSecret, "Invalid 'clientSecret' key"); this.params.put(Constants.CLIENT_SECRET, clientSecret); return this; }
java
{ "resource": "" }
q167138
InstagramSubscription.object
validation
public InstagramSubscription object(SubscriptionType type) { this.params.put(Constants.SUBSCRIPTION_TYPE, type.toString()); return this; }
java
{ "resource": "" }
q167139
InstagramSubscription.verifyToken
validation
public InstagramSubscription verifyToken(String verifyToken) { Preconditions.checkEmptyString(verifyToken, "Invalid 'verifyToken' key"); this.params.put(Constants.VERIFY_TOKEN, verifyToken); return this; }
java
{ "resource": "" }
q167140
InstagramSubscription.aspect
validation
public InstagramSubscription aspect(String aspect) { Preconditions.checkEmptyString(aspect, "Invalid 'aspect' key"); this.params.put(Constants.ASPECT, aspect); return this; }
java
{ "resource": "" }
q167141
InstagramSubscription.latitute
validation
public InstagramSubscription latitute(String latitude){ Preconditions.checkValidLatLong(latitude, "Invalid 'lat' key"); this.params.put(Constants.LATITUDE, latitude); return this; }
java
{ "resource": "" }
q167142
InstagramSubscription.longitude
validation
public InstagramSubscription longitude(String longitude){ Preconditions.checkValidLatLong(longitude, "Invalid 'lng' key"); this.params.put(Constants.LONGITUDE, longitude); return this; }
java
{ "resource": "" }
q167143
InstagramSubscription.radius
validation
public InstagramSubscription radius(String radius){ Preconditions.checkValidRadius(radius, "Invalid 'radius' key"); this.params.put(Constants.RADIUS, radius); return this; }
java
{ "resource": "" }
q167144
InstagramSubscription.deleteSubscription
validation
public SubscriptionResponse deleteSubscription(String id) throws InstagramException { final OAuthRequest request = prepareOAuthRequest(Verbs.DELETE); request.addQuerystringParameter("id", id); try { final Response response = request.send(); return getSubscriptionResponse(response.getBody()); } catch (IOException e) { throw new InstagramException("Failed to delete subscription with id ["+id+"]", e); } }
java
{ "resource": "" }
q167145
InstagramSubscription.deleteAllSubscription
validation
public SubscriptionResponse deleteAllSubscription() throws InstagramException { final OAuthRequest request = prepareOAuthRequest(Verbs.DELETE); request.addQuerystringParameter(Constants.SUBSCRIPTION_TYPE, "all"); try { final Response response = request.send(); return getSubscriptionResponse(response.getBody()); } catch (IOException e) { throw new InstagramException("Failed to delete all subscriptions", e); } }
java
{ "resource": "" }
q167146
InstagramSubscription.getSubscriptionList
validation
public SubscriptionsListResponse getSubscriptionList() throws InstagramException { final OAuthRequest request = prepareOAuthRequest(Verbs.GET); try { final Response response = request.send(); return getSubscriptionsListResponse(response.getBody()); } catch (IOException e) { throw new InstagramException("Failed to get subscription list", e); } }
java
{ "resource": "" }
q167147
URLUtils.formURLEncodeMap
validation
public static String formURLEncodeMap(Map<String, String> map) { Preconditions.checkNotNull(map, "Cannot url-encode a null object"); return (map.size() <= 0) ? EMPTY_STRING : doFormUrlEncode(map); }
java
{ "resource": "" }
q167148
URLUtils.percentEncode
validation
public static String percentEncode(String string) { String encoded = formURLEncode(string); for (EncodingRule rule : ENCODING_RULES) { encoded = rule.apply(encoded); } return encoded; }
java
{ "resource": "" }
q167149
URLUtils.appendParametersToQueryString
validation
public static String appendParametersToQueryString(String url, Map<String, String> params) { Preconditions.checkNotNull(url, "Cannot append to null URL"); String queryString = URLUtils.formURLEncodeMap(params); if (queryString.equals(EMPTY_STRING)) { return url; } else { url += (url.indexOf(QUERY_STRING_SEPARATOR) != -1) ? PARAM_SEPARATOR : QUERY_STRING_SEPARATOR; url += queryString; return url; } }
java
{ "resource": "" }
q167150
URLUtils.concatSortedPercentEncodedParams
validation
public static String concatSortedPercentEncodedParams(Map<String, String> params) { StringBuilder result = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { result.append(entry.getKey()).append(PAIR_SEPARATOR); result.append(entry.getValue()).append(PARAM_SEPARATOR); } return result.toString().substring(0, result.length() - 1); }
java
{ "resource": "" }
q167151
URLUtils.queryStringToMap
validation
public static Map<String, String> queryStringToMap(String queryString) { Map<String, String> result = new HashMap<String, String>(); if ((queryString != null) && (queryString.length() > 0)) { for (String param : queryString.split(PARAM_SEPARATOR)) { String pair[] = param.split(PAIR_SEPARATOR); String key = formURLDecode(pair[0]); String value = (pair.length > 1) ? formURLDecode(pair[1]) : EMPTY_STRING; result.put(key, value); } } return result; }
java
{ "resource": "" }
q167152
InstagramErrorResponse.throwException
validation
public void throwException() throws InstagramException { if (errorMeta != null) { String msg = errorMeta.getErrorType() + ": " + errorMeta.getErrorMessage(); switch (errorMeta.getCode()) { case 400: throw new InstagramBadRequestException(errorMeta.getErrorType(), msg, this.headers); case 429: throw new InstagramRateLimitException(errorMeta.getErrorType(), msg, this.headers); default: throw new InstagramException(errorMeta.getErrorType(), msg, this.headers); } } else { throw new InstagramException("No metadata found in response", this.headers); } }
java
{ "resource": "" }
q167153
BaseTick.addTrade
validation
public void addTrade(Decimal tradeVolume, Decimal tradePrice) { if (openPrice == null) { openPrice = tradePrice; } closePrice = tradePrice; if (maxPrice == null) { maxPrice = tradePrice; } else { maxPrice = maxPrice.isLessThan(tradePrice) ? tradePrice : maxPrice; } if (minPrice == null) { minPrice = tradePrice; } else { minPrice = minPrice.isGreaterThan(tradePrice) ? tradePrice : minPrice; } volume = volume.plus(tradeVolume); amount = amount.plus(tradeVolume.multipliedBy(tradePrice)); trades++; }
java
{ "resource": "" }
q167154
CachedIndicator.increaseLengthTo
validation
private void increaseLengthTo(int index, int maxLength) { if (highestResultIndex > -1) { int newResultsCount = Math.min(index-highestResultIndex, maxLength); if (newResultsCount == maxLength) { results.clear(); results.addAll(Collections.<T> nCopies(maxLength, null)); } else if (newResultsCount > 0) { results.addAll(Collections.<T> nCopies(newResultsCount, null)); removeExceedingResults(maxLength); } } else { // First use of cache assert results.isEmpty() : "Cache results list should be empty"; results.addAll(Collections.<T> nCopies(Math.min(index+1, maxLength), null)); } }
java
{ "resource": "" }
q167155
MaximumDrawdownCriterion.calculateMaximumDrawdown
validation
private Decimal calculateMaximumDrawdown(TimeSeries series, CashFlow cashFlow) { Decimal maximumDrawdown = Decimal.ZERO; Decimal maxPeak = Decimal.ZERO; if (!series.isEmpty()) { // The series is not empty for (int i = series.getBeginIndex(); i <= series.getEndIndex(); i++) { Decimal value = cashFlow.getValue(i); if (value.isGreaterThan(maxPeak)) { maxPeak = value; } Decimal drawdown = maxPeak.minus(value).dividedBy(maxPeak); if (drawdown.isGreaterThan(maximumDrawdown)) { maximumDrawdown = drawdown; } } } return maximumDrawdown; }
java
{ "resource": "" }
q167156
WalkForward.getSplitBeginIndexes
validation
public static List<Integer> getSplitBeginIndexes(TimeSeries series, Duration splitDuration) { ArrayList<Integer> beginIndexes = new ArrayList<>(); int beginIndex = series.getBeginIndex(); int endIndex = series.getEndIndex(); // Adding the first begin index beginIndexes.add(beginIndex); // Building the first interval before next split ZonedDateTime beginInterval = series.getFirstTick().getEndTime(); ZonedDateTime endInterval = beginInterval.plus(splitDuration); for (int i = beginIndex; i <= endIndex; i++) { // For each tick... ZonedDateTime tickTime = series.getTick(i).getEndTime(); if (tickTime.isBefore(beginInterval) || !tickTime.isBefore(endInterval)) { // Tick out of the interval if (!endInterval.isAfter(tickTime)) { // Tick after the interval // --> Adding a new begin index beginIndexes.add(i); } // Building the new interval before next split beginInterval = endInterval.isBefore(tickTime) ? tickTime : endInterval; endInterval = beginInterval.plus(splitDuration); } } return beginIndexes; }
java
{ "resource": "" }
q167157
SimpleLinearRegressionIndicator.calculateRegressionLine
validation
private void calculateRegressionLine(int startIndex, int endIndex) { // First pass: compute xBar and yBar Decimal sumX = Decimal.ZERO; Decimal sumY = Decimal.ZERO; for (int i = startIndex; i <= endIndex; i++) { sumX = sumX.plus(Decimal.valueOf(i)); sumY = sumY.plus(indicator.getValue(i)); } Decimal nbObservations = Decimal.valueOf(endIndex - startIndex + 1); Decimal xBar = sumX.dividedBy(nbObservations); Decimal yBar = sumY.dividedBy(nbObservations); // Second pass: compute slope and intercept Decimal xxBar = Decimal.ZERO; Decimal xyBar = Decimal.ZERO; for (int i = startIndex; i <= endIndex; i++) { Decimal dX = Decimal.valueOf(i).minus(xBar); Decimal dY = indicator.getValue(i).minus(yBar); xxBar = xxBar.plus(dX.multipliedBy(dX)); xyBar = xyBar.plus(dX.multipliedBy(dY)); } slope = xyBar.dividedBy(xxBar); intercept = yBar.minus(slope.multipliedBy(xBar)); }
java
{ "resource": "" }
q167158
Trade.operate
validation
public Order operate(int index, Decimal price, Decimal amount) { Order order = null; if (isNew()) { order = new Order(index, startingType, price, amount); entry = order; } else if (isOpened()) { if (index < entry.getIndex()) { throw new IllegalStateException("The index i is less than the entryOrder index"); } order = new Order(index, startingType.complementType(), price, amount); exit = order; } return order; }
java
{ "resource": "" }
q167159
BuyAndSellSignalsToChart.buildChartTimeSeries
validation
private static org.jfree.data.time.TimeSeries buildChartTimeSeries(TimeSeries tickSeries, Indicator<Decimal> indicator, String name) { org.jfree.data.time.TimeSeries chartTimeSeries = new org.jfree.data.time.TimeSeries(name); for (int i = 0; i < tickSeries.getTickCount(); i++) { Tick tick = tickSeries.getTick(i); chartTimeSeries.add(new Minute(Date.from(tick.getEndTime().toInstant())), indicator.getValue(i).toDouble()); } return chartTimeSeries; }
java
{ "resource": "" }
q167160
TradingBotOnMovingTimeSeries.randDecimal
validation
private static Decimal randDecimal(Decimal min, Decimal max) { Decimal randomDecimal = null; if (min != null && max != null && min.isLessThan(max)) { randomDecimal = max.minus(min).multipliedBy(Decimal.valueOf(Math.random())).plus(min); } return randomDecimal; }
java
{ "resource": "" }
q167161
TradingBotOnMovingTimeSeries.generateRandomTick
validation
private static Tick generateRandomTick() { final Decimal maxRange = Decimal.valueOf("0.03"); // 3.0% Decimal openPrice = LAST_TICK_CLOSE_PRICE; Decimal minPrice = openPrice.minus(openPrice.multipliedBy(maxRange.multipliedBy(Decimal.valueOf(Math.random())))); Decimal maxPrice = openPrice.plus(openPrice.multipliedBy(maxRange.multipliedBy(Decimal.valueOf(Math.random())))); Decimal closePrice = randDecimal(minPrice, maxPrice); LAST_TICK_CLOSE_PRICE = closePrice; return new BaseTick(ZonedDateTime.now(), openPrice, maxPrice, minPrice, closePrice, Decimal.ONE); }
java
{ "resource": "" }
q167162
ParabolicSarIndicator.incrementAcceleration
validation
private void incrementAcceleration() { if (acceleration.isGreaterThanOrEqual(ACCELERATION_THRESHOLD)) { acceleration = MAX_ACCELERATION; } else { acceleration = acceleration.plus(ACCELERATION_INCREMENT); } }
java
{ "resource": "" }
q167163
ParabolicSarIndicator.calculateSar
validation
private Decimal calculateSar(int index) { Decimal previousSar = getValue(index - 1); return extremePoint.multipliedBy(acceleration) .plus(Decimal.ONE.minus(acceleration).multipliedBy(previousSar)); }
java
{ "resource": "" }
q167164
CashFlow.calculate
validation
private void calculate(Trade trade) { final int entryIndex = trade.getEntry().getIndex(); int begin = entryIndex + 1; if (begin > values.size()) { Decimal lastValue = values.get(values.size() - 1); values.addAll(Collections.nCopies(begin - values.size(), lastValue)); } int end = trade.getExit().getIndex(); for (int i = Math.max(begin, 1); i <= end; i++) { Decimal ratio; if (trade.getEntry().isBuy()) { ratio = timeSeries.getTick(i).getClosePrice().dividedBy(timeSeries.getTick(entryIndex).getClosePrice()); } else { ratio = timeSeries.getTick(entryIndex).getClosePrice().dividedBy(timeSeries.getTick(i).getClosePrice()); } values.add(values.get(entryIndex).multipliedBy(ratio)); } }
java
{ "resource": "" }
q167165
CashFlow.fillToTheEnd
validation
private void fillToTheEnd() { if (timeSeries.getEndIndex() >= values.size()) { Decimal lastValue = values.get(values.size() - 1); values.addAll(Collections.nCopies(timeSeries.getEndIndex() - values.size() + 1, lastValue)); } }
java
{ "resource": "" }
q167166
StrategyExecutionLogging.loadLoggerConfiguration
validation
private static void loadLoggerConfiguration() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); try { configurator.doConfigure(LOGBACK_CONF_FILE); } catch (JoranException je) { Logger.getLogger(StrategyExecutionLogging.class.getName()).log(Level.SEVERE, "Unable to load Logback configuration", je); } }
java
{ "resource": "" }
q167167
CandlestickChart.createOHLCDataset
validation
private static OHLCDataset createOHLCDataset(TimeSeries series) { final int nbTicks = series.getTickCount(); Date[] dates = new Date[nbTicks]; double[] opens = new double[nbTicks]; double[] highs = new double[nbTicks]; double[] lows = new double[nbTicks]; double[] closes = new double[nbTicks]; double[] volumes = new double[nbTicks]; for (int i = 0; i < nbTicks; i++) { Tick tick = series.getTick(i); dates[i] = new Date(tick.getEndTime().toEpochSecond() * 1000); opens[i] = tick.getOpenPrice().toDouble(); highs[i] = tick.getMaxPrice().toDouble(); lows[i] = tick.getMinPrice().toDouble(); closes[i] = tick.getClosePrice().toDouble(); volumes[i] = tick.getVolume().toDouble(); } OHLCDataset dataset = new DefaultHighLowDataset("btc", dates, highs, lows, opens, closes, volumes); return dataset; }
java
{ "resource": "" }
q167168
CandlestickChart.createAdditionalDataset
validation
private static TimeSeriesCollection createAdditionalDataset(TimeSeries series) { ClosePriceIndicator indicator = new ClosePriceIndicator(series); TimeSeriesCollection dataset = new TimeSeriesCollection(); org.jfree.data.time.TimeSeries chartTimeSeries = new org.jfree.data.time.TimeSeries("Btc price"); for (int i = 0; i < series.getTickCount(); i++) { Tick tick = series.getTick(i); chartTimeSeries.add(new Second(new Date(tick.getEndTime().toEpochSecond() * 1000)), indicator.getValue(i).toDouble()); } dataset.addSeries(chartTimeSeries); return dataset; }
java
{ "resource": "" }
q167169
CashFlowToChart.addCashFlowAxis
validation
private static void addCashFlowAxis(XYPlot plot, TimeSeriesCollection dataset) { final NumberAxis cashAxis = new NumberAxis("Cash Flow Ratio"); cashAxis.setAutoRangeIncludesZero(false); plot.setRangeAxis(1, cashAxis); plot.setDataset(1, dataset); plot.mapDatasetToRangeAxis(1, 1); final StandardXYItemRenderer cashFlowRenderer = new StandardXYItemRenderer(); cashFlowRenderer.setSeriesPaint(0, Color.blue); plot.setRenderer(1, cashFlowRenderer); }
java
{ "resource": "" }
q167170
CashFlowToChart.displayChart
validation
private static void displayChart(JFreeChart chart) { // Chart panel ChartPanel panel = new ChartPanel(chart); panel.setFillZoomRectangle(true); panel.setMouseWheelEnabled(true); panel.setPreferredSize(new Dimension(1024, 400)); // Application frame ApplicationFrame frame = new ApplicationFrame("Ta4j example - Cash flow to chart"); frame.setContentPane(panel); frame.pack(); RefineryUtilities.centerFrameOnScreen(frame); frame.setVisible(true); }
java
{ "resource": "" }
q167171
BaseTimeSeries.removeExceedingTicks
validation
private void removeExceedingTicks() { int tickCount = ticks.size(); if (tickCount > maximumTickCount) { // Removing old ticks int nbTicksToRemove = tickCount - maximumTickCount; for (int i = 0; i < nbTicksToRemove; i++) { ticks.remove(0); } // Updating removed ticks count removedTicksCount += nbTicksToRemove; } }
java
{ "resource": "" }
q167172
CsvTradesLoader.buildEmptyTicks
validation
private static List<Tick> buildEmptyTicks(ZonedDateTime beginTime, ZonedDateTime endTime, int duration) { List<Tick> emptyTicks = new ArrayList<>(); Duration tickDuration = Duration.ofSeconds(duration); ZonedDateTime tickEndTime = beginTime; do { tickEndTime = tickEndTime.plus(tickDuration); emptyTicks.add(new BaseTick(tickDuration, tickEndTime)); } while (tickEndTime.isBefore(endTime)); return emptyTicks; }
java
{ "resource": "" }
q167173
ObservableGroup.destroy
validation
void destroy() { destroyed = true; for (Map<String, ManagedObservable<?>> observableMap : groupMap.values()) { for (ManagedObservable<?> managedObservable : observableMap.values()) { managedObservable.cancel(); } observableMap.clear(); } groupMap.clear(); }
java
{ "resource": "" }
q167174
GroupLifecycleManager.onSaveInstanceState
validation
public void onSaveInstanceState(Bundle outState) { hasSavedState = true; outState.putParcelable(KEY_STATE, new State(observableManager.id(), group.id())); }
java
{ "resource": "" }
q167175
AbstractWatchKey.signalEvent
validation
final void signalEvent(WatchEvent.Kind<Path> kind, Path context) { post(new Event<>(kind, 1, context)); signal(); }
java
{ "resource": "" }
q167176
DirectoryWatcher.watchAsync
validation
public CompletableFuture<Void> watchAsync(Executor executor) { return CompletableFuture.supplyAsync( () -> { watch(); return null; }, executor); }
java
{ "resource": "" }
q167177
DirectoryWatcher.register
validation
private void register(Path directory, boolean useFileTreeModifier) throws IOException { logger.debug("Registering [{}].", directory); Watchable watchable = isMac ? new WatchablePath(directory) : directory; WatchEvent.Modifier[] modifiers = useFileTreeModifier ? new WatchEvent.Modifier[] {ExtendedWatchEventModifier.FILE_TREE} : new WatchEvent.Modifier[] {}; WatchEvent.Kind<?>[] kinds = new WatchEvent.Kind<?>[] {ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY}; WatchKey watchKey = watchable.register(watchService, kinds, modifiers); keyRoots.put(watchKey, directory); }
java
{ "resource": "" }
q167178
ExecJavaMojo.getClassLoader
validation
private ClassLoader getClassLoader() throws MojoExecutionException { List<Path> classpathURLs = new ArrayList<>(); this.addRelevantPluginDependenciesToClasspath( classpathURLs ); this.addRelevantProjectDependenciesToClasspath( classpathURLs ); this.addAdditionalClasspathElements( classpathURLs ); try { return LoaderFinder.find( classpathURLs, mainClass ); } catch ( NullPointerException | IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } }
java
{ "resource": "" }
q167179
ExecJavaMojo.addRelevantPluginDependenciesToClasspath
validation
private void addRelevantPluginDependenciesToClasspath( List<Path> path ) throws MojoExecutionException { if ( hasCommandlineArgs() ) { arguments = parseCommandlineArgs(); } for ( Artifact classPathElement : this.determineRelevantPluginDependencies() ) { getLog().debug( "Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath" ); path.add( classPathElement.getFile().toPath() ); } }
java
{ "resource": "" }
q167180
ExecJavaMojo.addRelevantProjectDependenciesToClasspath
validation
private void addRelevantProjectDependenciesToClasspath( List<Path> path ) throws MojoExecutionException { if ( this.includeProjectDependencies ) { getLog().debug( "Project Dependencies will be included." ); List<Artifact> artifacts = new ArrayList<>(); List<Path> theClasspathFiles = new ArrayList<>(); collectProjectArtifactsAndClasspath( artifacts, theClasspathFiles ); for ( Path classpathFile : theClasspathFiles ) { getLog().debug( "Adding to classpath : " + classpathFile ); path.add( classpathFile ); } for ( Artifact classPathElement : artifacts ) { getLog().debug( "Adding project dependency artifact: " + classPathElement.getArtifactId() + " to classpath" ); path.add( classPathElement.getFile().toPath() ); } } else { getLog().debug( "Project Dependencies will be excluded." ); } }
java
{ "resource": "" }
q167181
ExecJavaMojo.resolveExecutableDependencies
validation
private Set<Artifact> resolveExecutableDependencies( Artifact executablePomArtifact ) throws MojoExecutionException { Set<Artifact> executableDependencies = new LinkedHashSet<>(); try { ProjectBuildingRequest buildingRequest = getSession().getProjectBuildingRequest(); MavenProject executableProject = this.projectBuilder.build( executablePomArtifact, buildingRequest ).getProject(); for ( ArtifactResult artifactResult : dependencyResolver.resolveDependencies( buildingRequest, executableProject.getModel(), null ) ) { executableDependencies.add( artifactResult.getArtifact() ); } } catch ( Exception ex ) { throw new MojoExecutionException( "Encountered problems resolving dependencies of the executable " + "in preparation for its execution.", ex ); } return executableDependencies; }
java
{ "resource": "" }
q167182
AbstractExecMojo.findExecutableArtifact
validation
protected Artifact findExecutableArtifact() throws MojoExecutionException { // ILimitedArtifactIdentifier execToolAssembly = this.getExecutableToolAssembly(); Artifact executableTool = null; for ( Artifact pluginDep : this.pluginDependencies ) { if ( this.executableDependency.matches( pluginDep ) ) { executableTool = pluginDep; break; } } if ( executableTool == null ) { throw new MojoExecutionException( "No dependency of the plugin matches the specified executableDependency." + " Specified executableToolAssembly is: " + executableDependency.toString() ); } return executableTool; }
java
{ "resource": "" }
q167183
ExecMojo.handleWorkingDirectory
validation
private void handleWorkingDirectory() throws MojoExecutionException { if ( workingDirectory == null ) { workingDirectory = basedir; } if ( !workingDirectory.exists() ) { getLog().debug( "Making working directory '" + workingDirectory.getAbsolutePath() + "'." ); if ( !workingDirectory.mkdirs() ) { throw new MojoExecutionException( "Could not make working directory: '" + workingDirectory.getAbsolutePath() + "'" ); } } }
java
{ "resource": "" }
q167184
FeedStats.getCalendarServiceRangeStart
validation
public LocalDate getCalendarServiceRangeStart() { int startDate = 0; for (Service service : feed.services.values()) { if (service.calendar == null) continue; // if (startDate == 0 || service.calendar.start_date < startDate) { // startDate = service.calendar.start_date; // } } if (startDate == 0) return null; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); return LocalDate.parse(String.valueOf(startDate), formatter); }
java
{ "resource": "" }
q167185
FeedStats.getBounds
validation
public Rectangle2D getBounds () { Rectangle2D ret = null; for (Stop stop : feed.stops.values()) { // skip over stops that don't have any stop times if (!feed.stopCountByStopTime.containsKey(stop.stop_id)) { continue; } if (ret == null) { ret = new Rectangle2D.Double(stop.stop_lon, stop.stop_lat, 0, 0); } else { ret.add(new Point2D.Double(stop.stop_lon, stop.stop_lat)); } } return ret; }
java
{ "resource": "" }
q167186
SpeedTripValidator.checkDistanceAndTime
validation
private boolean checkDistanceAndTime (double distanceMeters, double travelTimeSeconds, StopTime stopTime) { boolean good = true; // TODO Use Epsilon for very tiny travel e.g. < 5 meters if (distanceMeters == 0) { registerError(stopTime, TRAVEL_DISTANCE_ZERO); good = false; } if (travelTimeSeconds < 0) { registerError(stopTime, TRAVEL_TIME_NEGATIVE, travelTimeSeconds); good = false; } else if (travelTimeSeconds == 0) { // Only register the travel time zero error if not all travel times are rounded. Otherwise, hold onto the // error in the travelTimeZeroErrors collection until the completion of this validator. if (!allTravelTimesAreRounded) registerError(stopTime, TRAVEL_TIME_ZERO); else travelTimeZeroErrors.add(createUnregisteredError(stopTime, TRAVEL_TIME_ZERO)); good = false; } return good; }
java
{ "resource": "" }
q167187
JdbcGtfsLoader.load
validation
private TableLoadResult load (Table table) { // This object will be returned to the caller to summarize the contents of the table and any errors. TableLoadResult tableLoadResult = new TableLoadResult(); int initialErrorCount = errorStorage.getErrorCount(); try { tableLoadResult.rowCount = loadInternal(table); tableLoadResult.fileSize = getTableSize(table); LOG.info(String.format("loaded in %d %s records", tableLoadResult.rowCount, table.name)); } catch (Exception ex) { LOG.error("Fatal error loading table", ex); tableLoadResult.fatalException = ex.toString(); // Rollback connection so that fatal exception does not impact loading of other tables. try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } finally { // Explicitly delete the tmp file now that load is finished (either success or failure). // Otherwise these multi-GB files clutter the drive. if (tempTextFile != null) { tempTextFile.delete(); } } int finalErrorCount = errorStorage.getErrorCount(); tableLoadResult.errorCount = finalErrorCount - initialErrorCount; return tableLoadResult; }
java
{ "resource": "" }
q167188
JdbcGtfsLoader.getTableSize
validation
private int getTableSize(Table table) { ZipEntry zipEntry = zip.getEntry(table.name + ".txt"); if (zipEntry == null) return 0; return (int) zipEntry.getSize(); }
java
{ "resource": "" }
q167189
JdbcGtfsLoader.setFieldToNull
validation
private void setFieldToNull(boolean postgresText, String[] transformedStrings, int fieldIndex, Field field) { if (postgresText) transformedStrings[fieldIndex + 1] = POSTGRES_NULL_TEXT; // Adjust parameter index by two: indexes are one-based and the first one is the CSV line number. else try { // LOG.info("setting {} index to null", fieldIndex + 2); field.setNull(insertStatement, fieldIndex + 2); } catch (SQLException e) { e.printStackTrace(); // FIXME: store error here? It appears that an exception should only be thrown if the type value is invalid, // the connection is closed, or the index is out of bounds. So storing an error may be unnecessary. } }
java
{ "resource": "" }
q167190
JdbcGtfsSnapshotter.copyTables
validation
public SnapshotResult copyTables() { // This result object will be returned to the caller to summarize the feed and report any critical errors. SnapshotResult result = new SnapshotResult(); try { long startTime = System.currentTimeMillis(); // We get a single connection object and share it across several different methods. // This ensures that actions taken in one method are visible to all subsequent SQL statements. // If we create a schema or table on one connection, then access it in a separate connection, we have no // guarantee that it exists when the accessing statement is executed. connection = dataSource.getConnection(); // Generate a unique prefix that will identify this feed. this.tablePrefix = randomIdString(); result.uniqueIdentifier = tablePrefix; // Create entry in snapshots table. registerSnapshot(); // Include the dot separator in the table prefix. // This allows everything to work even when there's no prefix. this.tablePrefix += "."; // Copy each table in turn // FIXME: NO non-fatal exception errors are being captured during copy operations. result.agency = copy(Table.AGENCY, true); result.calendar = copy(Table.CALENDAR, true); result.calendarDates = copy(Table.CALENDAR_DATES, true); result.fareAttributes = copy(Table.FARE_ATTRIBUTES, true); result.fareRules = copy(Table.FARE_RULES, true); result.feedInfo = copy(Table.FEED_INFO, true); result.frequencies = copy(Table.FREQUENCIES, true); result.routes = copy(Table.ROUTES, true); // FIXME: Find some place to store errors encountered on copy for patterns and pattern stops. copy(Table.PATTERNS, true); copy(Table.PATTERN_STOP, true); // see method comments fo why different logic is needed for this table result.scheduleExceptions = createScheduleExceptionsTable(); result.shapes = copy(Table.SHAPES, true); result.stops = copy(Table.STOPS, true); // TODO: Should we defer index creation on stop times? // Copying all tables for STIF w/ stop times idx = 156 sec; w/o = 28 sec // Other feeds w/ stop times AC Transit = 3 sec; Brooklyn bus = result.stopTimes = copy(Table.STOP_TIMES, true); result.transfers = copy(Table.TRANSFERS, true); result.trips = copy(Table.TRIPS, true); result.completionTime = System.currentTimeMillis(); result.loadTimeMillis = result.completionTime - startTime; LOG.info("Copying tables took {} sec", (result.loadTimeMillis) / 1000); } catch (Exception ex) { // Note: Exceptions that occur during individual table loads are separately caught and stored in // TableLoadResult. LOG.error("Exception while creating snapshot: {}", ex.toString()); ex.printStackTrace(); result.fatalException = ex.toString(); } return result; }
java
{ "resource": "" }
q167191
JdbcGtfsSnapshotter.tableExists
validation
private boolean tableExists(String namespace, String tableName) { // Preempt SQL check with null check of either namespace or table name. if (namespace == null || tableName == null) return false; try { // This statement is postgres-specific. PreparedStatement tableExistsStatement = connection.prepareStatement( "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ?)" ); tableExistsStatement.setString(1, namespace); tableExistsStatement.setString(2, tableName); ResultSet resultSet = tableExistsStatement.executeQuery(); resultSet.next(); return resultSet.getBoolean(1); } catch (SQLException e) { e.printStackTrace(); return false; } }
java
{ "resource": "" }
q167192
JdbcGtfsSnapshotter.addEditorSpecificFields
validation
private void addEditorSpecificFields(Connection connection, String tablePrefix, Table table) throws SQLException { LOG.info("Adding any missing columns for {}", tablePrefix + table.name); Statement statement = connection.createStatement(); for (Field field : table.editorFields()) { // The following statement requires PostgreSQL 9.6+. String addColumnSql = String.format("ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s", tablePrefix + table.name, field.name, field.getSqlTypeName()); LOG.info(addColumnSql); statement.execute(addColumnSql); } }
java
{ "resource": "" }
q167193
JdbcGtfsSnapshotter.registerSnapshot
validation
private void registerSnapshot () { try { // We cannot simply insert into the feeds table because if we are creating an empty snapshot (to create/edit // a GTFS feed from scratch), the feed registry table will not exist. // TODO copy over feed_id and feed_version from source namespace? // TODO: Record total snapshot processing time? createFeedRegistryIfNotExists(connection); createSchema(connection, tablePrefix); PreparedStatement insertStatement = connection.prepareStatement( "insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)"); insertStatement.setString(1, tablePrefix); insertStatement.setString(2, feedIdToSnapshot); insertStatement.execute(); connection.commit(); LOG.info("Created new snapshot namespace: {}", insertStatement); } catch (Exception ex) { LOG.error("Exception while registering snapshot namespace in feeds table", ex); DbUtils.closeQuietly(connection); } }
java
{ "resource": "" }
q167194
Frequency.getId
validation
public String getId() { StringBuilder sb = new StringBuilder(); sb.append(trip_id); sb.append('_'); sb.append(convertToGtfsTime(start_time)); sb.append("_to_"); sb.append(convertToGtfsTime(end_time)); sb.append("_every_"); sb.append(String.format("%dm%02ds", headway_secs / 60, headway_secs % 60)); if (exact_times == 1) sb.append("_exact"); return sb.toString(); }
java
{ "resource": "" }
q167195
BatchTracker.executeRemaining
validation
public int executeRemaining() throws SQLException { if (currentBatchSize > 0) { totalRecordsProcessed += currentBatchSize; preparedStatement.executeBatch(); currentBatchSize = 0; } // Avoid reuse, signal that this was cleanly closed. preparedStatement = null; LOG.info(String.format("Processed %d %s records", totalRecordsProcessed, recordType)); return totalRecordsProcessed; }
java
{ "resource": "" }
q167196
JdbcGtfsExporter.cleanUpZipFile
validation
private void cleanUpZipFile() { long startTime = System.currentTimeMillis(); // Define ZIP File System Properties in HashMap Map<String, String> zip_properties = new HashMap<>(); // We want to read an existing ZIP File, so we set this to False zip_properties.put("create", "false"); // Specify the path to the ZIP File that you want to read as a File System // (File#toURI allows this to work across different operating systems, including Windows) URI zip_disk = URI.create("jar:" + new File(outFile).toURI()); // Create ZIP file System try (FileSystem fileSystem = FileSystems.newFileSystem(zip_disk, zip_properties)) { // Get the Path inside ZIP File to delete the ZIP Entry for (String fileName : emptyTableList) { Path filePath = fileSystem.getPath(fileName); // Execute Delete Files.delete(filePath); LOG.info("Empty file {} successfully deleted", fileName); } } catch (IOException e) { LOG.error("Could not remove empty zip files"); e.printStackTrace(); } LOG.info("Deleted {} empty files in {} ms", emptyTableList.size(), System.currentTimeMillis() - startTime); }
java
{ "resource": "" }
q167197
JdbcGtfsExporter.export
validation
private TableLoadResult export (Table table, String filterSql) { long startTime = System.currentTimeMillis(); TableLoadResult tableLoadResult = new TableLoadResult(); try { if (filterSql == null) { throw new IllegalArgumentException("filterSql argument cannot be null"); } else { // Surround filter SQL in parentheses. filterSql = String.format("(%s)", filterSql); } // Create entry for table String textFileName = table.name + ".txt"; ZipEntry zipEntry = new ZipEntry(textFileName); zipOutputStream.putNextEntry(zipEntry); // don't let CSVWriter close the stream when it is garbage-collected OutputStream protectedOut = new FilterOutputStream(zipOutputStream); String copySql = String.format("copy %s to STDOUT DELIMITER ',' CSV HEADER", filterSql); LOG.info(copySql); // Our connection pool wraps the Connection objects, so we need to unwrap the Postgres connection interface. CopyManager copyManager = new CopyManager(connection.unwrap(BaseConnection.class)); tableLoadResult.rowCount = (int) copyManager.copyOut(copySql, protectedOut); if (tableLoadResult.rowCount == 0) { // If no rows were exported, keep track of table name for later removal. emptyTableList.add(textFileName); } zipOutputStream.closeEntry(); LOG.info("Copied {} {} in {} ms.", tableLoadResult.rowCount, table.name, System.currentTimeMillis() - startTime); connection.commit(); } catch (SQLException | IOException | IllegalArgumentException e) { // Rollback connection so that fatal exception does not impact loading of other tables. try { connection.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } tableLoadResult.fatalException = e.toString(); LOG.error("Exception while exporting tables", e); } return tableLoadResult; }
java
{ "resource": "" }
q167198
Validator.registerError
validation
public void registerError(Entity entity, NewGTFSErrorType errorType) { errorStorage.storeError(NewGTFSError.forEntity(entity, errorType)); }
java
{ "resource": "" }
q167199
Validator.registerError
validation
public void registerError(Entity entity, NewGTFSErrorType errorType, Object badValue) { errorStorage.storeError(NewGTFSError.forEntity(entity, errorType).setBadValue(badValue.toString())); }
java
{ "resource": "" }