_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q174200 | AbstractOpenRtbJsonWriter.writeContentCategories | test | protected final void writeContentCategories(
String fieldName, List<String> cats, JsonGenerator gen)
throws IOException {
if (!cats.isEmpty()) {
gen.writeArrayFieldStart(fieldName);
for (String cat : cats) {
writeContentCategory(cat, gen);
}
gen.writeEndArray();
}
} | java | {
"resource": ""
} |
q174201 | SnippetProcessor.process | test | public String process(SnippetProcessorContext ctx, String snippet) {
checkNotNull(ctx);
StringBuilder sb = ctx.builder();
sb.setLength(0);
String currSnippet = snippet;
boolean processedMacros = false;
int snippetPos = 0;
int macroPos = currSnippet.indexOf("${");
while (macroPos != -1) {
sb.append(currSnippet.substring(snippetPos, macroPos));
int macroEnd = processMacroAt(ctx, currSnippet, macroPos);
if (macroEnd == -1) {
sb.append("${");
snippetPos = macroPos + 2;
} else {
snippetPos = macroEnd;
processedMacros = true;
}
macroPos = currSnippet.indexOf("${", snippetPos);
}
if (processedMacros) {
sb.append(currSnippet, snippetPos, currSnippet.length());
currSnippet = sb.toString();
}
sb.setLength(0);
String ret = urlEncode(ctx, currSnippet);
sb.setLength(0);
return ret;
} | java | {
"resource": ""
} |
q174202 | OpenRtbUtils.bids | test | public static Iterable<Bid.Builder> bids(BidResponse.Builder response) {
return new ResponseBidsIterator(response, SEAT_ANY, null);
} | java | {
"resource": ""
} |
q174203 | OpenRtbUtils.bidWithId | test | @Nullable public static Bid.Builder bidWithId(BidResponse.Builder response, String id) {
checkNotNull(id);
for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) {
for (Bid.Builder bid : seatbid.getBidBuilderList()) {
if (id.equals(bid.getId())) {
return bid;
}
}
}
return null;
} | java | {
"resource": ""
} |
q174204 | OpenRtbUtils.updateBids | test | public static boolean updateBids(
BidResponse.Builder response, Function<Bid.Builder, Boolean> updater) {
checkNotNull(updater);
boolean updated = false;
for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) {
updated |= ProtoUtils.update(seatbid.getBidBuilderList(), updater);
}
return updated;
} | java | {
"resource": ""
} |
q174205 | OpenRtbUtils.removeBids | test | public static boolean removeBids(BidResponse.Builder response, Predicate<Bid.Builder> filter) {
checkNotNull(filter);
boolean updated = false;
for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) {
updated |= removeBids(seatbid, filter);
}
return updated;
} | java | {
"resource": ""
} |
q174206 | OpenRtbUtils.impsWith | test | public static Iterable<Imp> impsWith(BidRequest request, Predicate<Imp> impFilter) {
checkNotNull(impFilter);
List<Imp> imps = request.getImpList();
if (imps.isEmpty() || impFilter == IMP_ALL) {
return imps;
} else if (impFilter == IMP_NONE) {
return ImmutableList.of();
}
boolean included = impFilter.test(imps.get(0));
int size = imps.size(), i;
for (i = 1; i < size; ++i) {
if (impFilter.test(imps.get(i)) != included) {
break;
}
}
if (i == size) {
return included
? imps // Unmodifiable, comes from protobuf
: ImmutableList.<Imp>of();
}
int headingSize = i;
return new FluentIterable<Imp>() {
@Override public Iterator<Imp> iterator() {
Iterator<Imp> unfiltered = imps.iterator();
return new AbstractIterator<Imp>() {
private int heading = 0;
@Override protected Imp computeNext() {
while (unfiltered.hasNext()) {
Imp imp = unfiltered.next();
if ((heading++ < headingSize)
? included
: impFilter.test(imp)) {
return imp;
}
}
return endOfData();
}};
}};
} | java | {
"resource": ""
} |
q174207 | AbstractOpenRtbJsonReader.readExtensions | test | protected final <EB extends ExtendableBuilder<?, EB>>
void readExtensions(EB msg, JsonParser par) throws IOException {
@SuppressWarnings("unchecked")
Set<OpenRtbJsonExtReader<EB>> extReaders = factory.getReaders((Class<EB>) msg.getClass());
if (extReaders.isEmpty()) {
par.skipChildren();
return;
}
startObject(par);
JsonToken tokLast = par.getCurrentToken();
JsonLocation locLast = par.getCurrentLocation();
while (true) {
boolean extRead = false;
for (OpenRtbJsonExtReader<EB> extReader : extReaders) {
if (extReader.filter(par)) {
extReader.read(msg, par);
JsonToken tokNew = par.getCurrentToken();
JsonLocation locNew = par.getCurrentLocation();
boolean advanced = tokNew != tokLast || !locNew.equals(locLast);
extRead |= advanced;
if (!endObject(par)) {
return;
} else if (advanced && par.getCurrentToken() != JsonToken.FIELD_NAME) {
tokLast = par.nextToken();
locLast = par.getCurrentLocation();
} else {
tokLast = tokNew;
locLast = locNew;
}
}
}
if (!endObject(par)) {
// Can't rely on this exit condition inside the for loop because no readers may filter.
return;
}
if (!extRead) {
// No field was consumed by any reader, so we need to skip the field to make progress.
if (logger.isDebugEnabled()) {
logger.debug("Extension field not consumed by any reader, skipping: {} @{}:{}",
par.getCurrentName(), locLast.getLineNr(), locLast.getCharOffset());
}
par.nextToken();
par.skipChildren();
tokLast = par.nextToken();
locLast = par.getCurrentLocation();
}
// Else loop, try all readers again
}
} | java | {
"resource": ""
} |
q174208 | AbstractOpenRtbJsonReader.emptyToNull | test | protected final boolean emptyToNull(JsonParser par) throws IOException {
JsonToken token = par.getCurrentToken();
if (token == null) {
token = par.nextToken();
}
return !factory().isStrict() && token == null;
} | java | {
"resource": ""
} |
q174209 | OpenRtbJsonFactory.register | test | public final <EB extends ExtendableBuilder<?, EB>> OpenRtbJsonFactory register(
OpenRtbJsonExtReader<EB> extReader, Class<EB> msgKlass) {
extReaders.put(msgKlass.getName(), extReader);
return this;
} | java | {
"resource": ""
} |
q174210 | OpenRtbJsonFactory.register | test | public final <T> OpenRtbJsonFactory register(OpenRtbJsonExtWriter<T> extWriter,
Class<T> extKlass, Class<? extends Message> msgKlass, String fieldName) {
Map<String, Map<String, OpenRtbJsonExtWriter<?>>> mapMsg = extWriters.get(msgKlass.getName());
if (mapMsg == null) {
extWriters.put(msgKlass.getName(), mapMsg = new LinkedHashMap<>());
}
Map<String, OpenRtbJsonExtWriter<?>> mapKlass = mapMsg.get(extKlass.getName());
if (mapKlass == null) {
mapMsg.put(extKlass.getName(), mapKlass = new LinkedHashMap<>());
}
mapKlass.put(fieldName == null ? FIELDNAME_ALL : fieldName, extWriter);
return this;
} | java | {
"resource": ""
} |
q174211 | OpenRtbSnippetProcessor.process | test | public void process(SnippetProcessorContext bidCtx) {
for (SeatBid.Builder seat : bidCtx.response().getSeatbidBuilderList()) {
for (Bid.Builder bid : seat.getBidBuilderList()) {
bidCtx.setBid(bid);
processFields(bidCtx);
}
}
} | java | {
"resource": ""
} |
q174212 | OpenRtbSnippetProcessor.processFields | test | protected void processFields(SnippetProcessorContext bidCtx) {
Bid.Builder bid = bidCtx.getBid();
// Properties that can also be in the RHS of macros used by other properties.
if (extendedFields) {
if (bid.hasAdid()) {
bid.setAdid(process(bidCtx, bid.getAdid()));
}
bid.setId(process(bidCtx, bid.getId()));
}
// Properties that are NOT the RHS of any macro.
if (bid.hasAdm()) {
bid.setAdm(process(bidCtx, bid.getAdm()));
}
if (extendedFields) {
if (bid.hasBurl()) {
bid.setBurl(process(bidCtx, bid.getBurl()));
}
if (bid.hasCid()) {
bid.setCid(process(bidCtx, bid.getCid()));
}
if (bid.hasCrid()) {
bid.setCrid(process(bidCtx, bid.getCrid()));
}
if (bid.hasDealid()) {
bid.setDealid(process(bidCtx, bid.getDealid()));
}
bid.setImpid(process(bidCtx, bid.getImpid()));
if (bid.hasIurl()) {
bid.setIurl(process(bidCtx, bid.getIurl()));
}
if (bid.hasLurl()) {
bid.setIurl(process(bidCtx, bid.getLurl()));
}
if (bid.hasNurl()) {
bid.setNurl(process(bidCtx, bid.getNurl()));
}
}
} | java | {
"resource": ""
} |
q174213 | ProtoUtils.update | test | public static <B extends MessageLite.Builder> boolean update(
Iterable<B> objs, Function<B, Boolean> updater) {
checkNotNull(updater);
boolean updated = false;
for (B obj : objs) {
updated |= updater.apply(obj);
}
return updated;
} | java | {
"resource": ""
} |
q174214 | ProtoUtils.filter | test | public static <M extends MessageLiteOrBuilder>
List<M> filter(List<M> objs, Predicate<M> filter) {
checkNotNull(filter);
for (int i = 0; i < objs.size(); ++i) {
if (!filter.test(objs.get(i))) {
// At least one discarded object, go to slow-path.
return filterFrom(objs, filter, i);
}
}
// Optimized common case: all items filtered, return the input sequence.
return objs;
} | java | {
"resource": ""
} |
q174215 | OpenRtbJsonUtils.getCurrentName | test | public static String getCurrentName(JsonParser par) throws IOException {
String name = par.getCurrentName();
return name == null ? "" : name;
} | java | {
"resource": ""
} |
q174216 | OpenRtbJsonUtils.startObject | test | public static void startObject(JsonParser par) throws IOException {
JsonToken token = par.getCurrentToken();
if (token == null || token == JsonToken.FIELD_NAME) {
token = par.nextToken();
}
if (token == JsonToken.START_OBJECT) {
par.nextToken();
} else {
throw new JsonParseException(par, "Expected start of object");
}
} | java | {
"resource": ""
} |
q174217 | OpenRtbJsonUtils.startArray | test | public static void startArray(JsonParser par) throws IOException {
JsonToken token = par.getCurrentToken();
if (token == null || token == JsonToken.FIELD_NAME) {
token = par.nextToken();
}
if (token == JsonToken.START_ARRAY) {
par.nextToken();
} else {
throw new JsonParseException(par, "Expected start of array");
}
} | java | {
"resource": ""
} |
q174218 | OpenRtbJsonUtils.peekToken | test | public static JsonToken peekToken(JsonParser par) throws IOException {
JsonToken token = par.getCurrentToken();
if (token == null || token == JsonToken.FIELD_NAME) {
token = par.nextToken();
}
return token;
} | java | {
"resource": ""
} |
q174219 | OpenRtbJsonUtils.writeIntBoolField | test | public static void writeIntBoolField(String fieldName, boolean data, JsonGenerator gen)
throws IOException {
gen.writeNumberField(fieldName, data ? 1 : 0);
} | java | {
"resource": ""
} |
q174220 | OpenRtbJsonUtils.writeStrings | test | public static void writeStrings(String fieldName, List<String> data, JsonGenerator gen)
throws IOException {
if (!data.isEmpty()) {
gen.writeArrayFieldStart(fieldName);
for (String d : data) {
gen.writeString(d);
}
gen.writeEndArray();
}
} | java | {
"resource": ""
} |
q174221 | OpenRtbJsonUtils.writeInts | test | public static void writeInts(String fieldName, List<Integer> data, JsonGenerator gen)
throws IOException {
if (!data.isEmpty()) {
gen.writeArrayFieldStart(fieldName);
for (Integer d : data) {
gen.writeNumber(d);
}
gen.writeEndArray();
}
} | java | {
"resource": ""
} |
q174222 | OpenRtbJsonUtils.writeLongs | test | public static void writeLongs(String fieldName, List<Long> data, JsonGenerator gen)
throws IOException {
if (!data.isEmpty()) {
gen.writeArrayFieldStart(fieldName);
for (long d : data) {
writeLong(d, gen);
}
gen.writeEndArray();
}
} | java | {
"resource": ""
} |
q174223 | OpenRtbJsonUtils.writeEnums | test | public static void writeEnums(
String fieldName, List<? extends ProtocolMessageEnum> enums, JsonGenerator gen)
throws IOException {
if (!enums.isEmpty()) {
gen.writeArrayFieldStart(fieldName);
for (ProtocolMessageEnum e : enums) {
writeEnum(e, gen);
}
gen.writeEndArray();
}
} | java | {
"resource": ""
} |
q174224 | URLUtil.resolveURL | test | public static URL resolveURL(URL base, String target)
throws MalformedURLException {
target = target.trim();
if (target.startsWith("?")) {
return fixPureQueryTargets(base, target);
}
return new URL(base, target);
} | java | {
"resource": ""
} |
q174225 | URLUtil.fixPureQueryTargets | test | static URL fixPureQueryTargets(URL base, String target)
throws MalformedURLException {
if (!target.startsWith("?"))
return new URL(base, target);
String basePath = base.getPath();
String baseRightMost = "";
int baseRightMostIdx = basePath.lastIndexOf("/");
if (baseRightMostIdx != -1) {
baseRightMost = basePath.substring(baseRightMostIdx + 1);
}
if (target.startsWith("?"))
target = baseRightMost + target;
return new URL(base, target);
} | java | {
"resource": ""
} |
q174226 | URLUtil.getHostSegments | test | public static String[] getHostSegments(URL url) {
String host = url.getHost();
// return whole hostname, if it is an ipv4
// TODO : handle ipv6
if (IP_PATTERN.matcher(host).matches())
return new String[] { host };
return host.split("\\.");
} | java | {
"resource": ""
} |
q174227 | URLUtil.getHost | test | public static String getHost(String url) {
try {
return new URL(url).getHost().toLowerCase(Locale.ROOT);
} catch (MalformedURLException e) {
return null;
}
} | java | {
"resource": ""
} |
q174228 | URLUtil.getPage | test | public static String getPage(String url) {
try {
// get the full url, and replace the query string with and empty
// string
url = url.toLowerCase(Locale.ROOT);
String queryStr = new URL(url).getQuery();
return (queryStr != null) ? url.replace("?" + queryStr, "") : url;
} catch (MalformedURLException e) {
return null;
}
} | java | {
"resource": ""
} |
q174229 | ConfUtils.loadListFromConf | test | public static List<String> loadListFromConf(String paramKey, Map stormConf) {
Object obj = stormConf.get(paramKey);
List<String> list = new LinkedList<>();
if (obj == null)
return list;
if (obj instanceof PersistentVector) {
list.addAll((PersistentVector) obj);
} else { // single value?
list.add(obj.toString());
}
return list;
} | java | {
"resource": ""
} |
q174230 | ConfUtils.extractConfigElement | test | public static Map extractConfigElement(Map conf) {
if (conf.size() == 1) {
Object confNode = conf.get("config");
if (confNode != null && confNode instanceof Map) {
conf = (Map) confNode;
}
}
return conf;
} | java | {
"resource": ""
} |
q174231 | ProtocolFactory.getProtocol | test | public synchronized Protocol getProtocol(URL url) {
// get the protocol
String protocol = url.getProtocol();
return cache.get(protocol);
} | java | {
"resource": ""
} |
q174232 | WARCRecordFormat.generateWARCInfo | test | public static byte[] generateWARCInfo(Map<String, String> fields) {
StringBuffer buffer = new StringBuffer();
buffer.append(WARC_VERSION);
buffer.append(CRLF);
buffer.append("WARC-Type: warcinfo").append(CRLF);
String mainID = UUID.randomUUID().toString();
// retrieve the date and filename from the map
String date = fields.get("WARC-Date");
buffer.append("WARC-Date: ").append(date).append(CRLF);
String filename = fields.get("WARC-Filename");
buffer.append("WARC-Filename: ").append(filename).append(CRLF);
buffer.append("WARC-Record-ID").append(": ").append("<urn:uuid:")
.append(mainID).append(">").append(CRLF);
buffer.append("Content-Type").append(": ")
.append("application/warc-fields").append(CRLF);
StringBuilder fieldsBuffer = new StringBuilder();
// add WARC fields
// http://bibnum.bnf.fr/warc/WARC_ISO_28500_version1_latestdraft.pdf
Iterator<Entry<String, String>> iter = fields.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String key = entry.getKey();
if (key.startsWith("WARC-"))
continue;
fieldsBuffer.append(key).append(": ").append(entry.getValue())
.append(CRLF);
}
buffer.append("Content-Length")
.append(": ")
.append(fieldsBuffer.toString()
.getBytes(StandardCharsets.UTF_8).length).append(CRLF);
buffer.append(CRLF);
buffer.append(fieldsBuffer.toString());
buffer.append(CRLF);
buffer.append(CRLF);
return buffer.toString().getBytes(StandardCharsets.UTF_8);
} | java | {
"resource": ""
} |
q174233 | RefreshTag.extractRefreshURL | test | public static String extractRefreshURL(String value) {
if (StringUtils.isBlank(value))
return null;
// 0;URL=http://www.apollocolors.com/site
try {
if (matcher.reset(value).matches()) {
return matcher.group(1);
}
} catch (Exception e) {
}
return null;
} | java | {
"resource": ""
} |
q174234 | MetadataTransfer.getMetaForOutlink | test | public Metadata getMetaForOutlink(String targetURL, String sourceURL,
Metadata parentMD) {
Metadata md = _filter(parentMD, mdToTransfer);
// keep the path?
if (trackPath) {
md.addValue(urlPathKeyName, sourceURL);
}
// track depth
if (trackDepth) {
String existingDepth = md.getFirstValue(depthKeyName);
int depth;
try {
depth = Integer.parseInt(existingDepth);
} catch (Exception e) {
depth = 0;
}
md.setValue(depthKeyName, Integer.toString(++depth));
}
return md;
} | java | {
"resource": ""
} |
q174235 | MetadataTransfer.filter | test | public Metadata filter(Metadata metadata) {
Metadata filtered_md = _filter(metadata, mdToTransfer);
// add the features that are only persisted but
// not transfered like __redirTo_
filtered_md.putAll(_filter(metadata, mdToPersistOnly));
return filtered_md;
} | java | {
"resource": ""
} |
q174236 | MemorySpout.add | test | public static void add(String url, Metadata md, Date nextFetch) {
LOG.debug("Adding {} with md {} and nextFetch {}", url, md, nextFetch);
ScheduledURL tuple = new ScheduledURL(url, md, nextFetch);
synchronized (queue) {
queue.add(tuple);
}
} | java | {
"resource": ""
} |
q174237 | CloudSearchUtils.cleanFieldName | test | public static String cleanFieldName(String name) {
String lowercase = name.toLowerCase();
lowercase = lowercase.replaceAll("[^a-z_0-9]", "_");
if (lowercase.length() < 3 || lowercase.length() > 64)
throw new RuntimeException(
"Field name must be between 3 and 64 chars : " + lowercase);
if (lowercase.equals("score"))
throw new RuntimeException("Field name must be score");
return lowercase;
} | java | {
"resource": ""
} |
q174238 | CharsetIdentification.getCharsetFromBOM | test | private static String getCharsetFromBOM(final byte[] byteData) {
BOMInputStream bomIn = new BOMInputStream(new ByteArrayInputStream(
byteData));
try {
ByteOrderMark bom = bomIn.getBOM();
if (bom != null) {
return bom.getCharsetName();
}
} catch (IOException e) {
return null;
}
return null;
} | java | {
"resource": ""
} |
q174239 | CharsetIdentification.getCharsetFromText | test | private static String getCharsetFromText(byte[] content,
String declaredCharset, int maxLengthCharsetDetection) {
String charset = null;
// filter HTML tags
CharsetDetector charsetDetector = new CharsetDetector();
charsetDetector.enableInputFilter(true);
// give it a hint
if (declaredCharset != null)
charsetDetector.setDeclaredEncoding(declaredCharset);
// trim the content of the text for the detection
byte[] subContent = content;
if (maxLengthCharsetDetection != -1
&& content.length > maxLengthCharsetDetection) {
subContent = Arrays.copyOfRange(content, 0,
maxLengthCharsetDetection);
}
charsetDetector.setText(subContent);
try {
CharsetMatch charsetMatch = charsetDetector.detect();
charset = validateCharset(charsetMatch.getName());
} catch (Exception e) {
charset = null;
}
return charset;
} | java | {
"resource": ""
} |
q174240 | CharsetIdentification.getCharsetFromMeta | test | private static String getCharsetFromMeta(byte buffer[], int maxlength) {
// convert to UTF-8 String -- which hopefully will not mess up the
// characters we're interested in...
int len = buffer.length;
if (maxlength > 0 && maxlength < len) {
len = maxlength;
}
String html = new String(buffer, 0, len, DEFAULT_CHARSET);
Document doc = Parser.htmlParser().parseInput(html, "dummy");
// look for <meta http-equiv="Content-Type"
// content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
Elements metaElements = doc
.select("meta[http-equiv=content-type], meta[charset]");
String foundCharset = null;
for (Element meta : metaElements) {
if (meta.hasAttr("http-equiv"))
foundCharset = getCharsetFromContentType(meta.attr("content"));
if (foundCharset == null && meta.hasAttr("charset"))
foundCharset = meta.attr("charset");
if (foundCharset != null)
return foundCharset;
}
return foundCharset;
} | java | {
"resource": ""
} |
q174241 | SiteMapParserBolt.sniff | test | private final boolean sniff(byte[] content) {
byte[] beginning = content;
if (content.length > maxOffsetGuess && maxOffsetGuess > 0) {
beginning = Arrays.copyOfRange(content, 0, maxOffsetGuess);
}
int position = Bytes.indexOf(beginning, clue);
if (position != -1) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q174242 | Metadata.setValue | test | public void setValue(String key, String value) {
md.put(key, new String[] { value });
} | java | {
"resource": ""
} |
q174243 | Metadata.getFirstValue | test | public static String getFirstValue(Metadata md, String... keys) {
for (String key : keys) {
String val = md.getFirstValue(key);
if (StringUtils.isBlank(val))
continue;
return val;
}
return null;
} | java | {
"resource": ""
} |
q174244 | CookieConverter.getCookies | test | public static List<Cookie> getCookies(String[] cookiesStrings, URL targetURL) {
ArrayList<Cookie> list = new ArrayList<Cookie>();
for (String cs : cookiesStrings) {
String name = null;
String value = null;
String expires = null;
String domain = null;
String path = null;
boolean secure = false;
String[] tokens = cs.split(";");
int equals = tokens[0].indexOf("=");
name = tokens[0].substring(0, equals);
value = tokens[0].substring(equals + 1);
for (int i = 1; i < tokens.length; i++) {
String ti = tokens[i].trim();
if (ti.equalsIgnoreCase("secure"))
secure = true;
if (ti.toLowerCase().startsWith("path=")) {
path = ti.substring(5);
}
if (ti.toLowerCase().startsWith("domain=")) {
domain = ti.substring(7);
}
if (ti.toLowerCase().startsWith("expires=")) {
expires = ti.substring(8);
}
}
BasicClientCookie cookie = new BasicClientCookie(name, value);
// check domain
if (domain != null) {
cookie.setDomain(domain);
if (!checkDomainMatchToUrl(domain, targetURL.getHost()))
continue;
}
// check path
if (path != null) {
cookie.setPath(path);
if (!path.equals("") && !path.equals("/")
&& !targetURL.getPath().startsWith(path))
continue;
}
// check secure
if (secure) {
cookie.setSecure(secure);
if (!targetURL.getProtocol().equalsIgnoreCase("https"))
continue;
}
// check expiration
if (expires != null) {
try {
Date expirationDate = DATE_FORMAT.parse(expires);
cookie.setExpiryDate(expirationDate);
// check that it hasn't expired?
if (cookie.isExpired(new Date()))
continue;
cookie.setExpiryDate(expirationDate);
} catch (ParseException e) {
// ignore exceptions
}
}
// attach additional infos to cookie
list.add(cookie);
}
return list;
} | java | {
"resource": ""
} |
q174245 | CookieConverter.checkDomainMatchToUrl | test | public static boolean checkDomainMatchToUrl(String cookieDomain,
String urlHostName) {
try {
if (cookieDomain.startsWith(".")) {
cookieDomain = cookieDomain.substring(1);
}
String[] domainTokens = cookieDomain.split("\\.");
String[] hostTokens = urlHostName.split("\\.");
int tokenDif = hostTokens.length - domainTokens.length;
if (tokenDif < 0) {
return false;
}
for (int i = domainTokens.length - 1; i >= 0; i--) {
if (!domainTokens[i].equalsIgnoreCase(hostTokens[i + tokenDif])) {
return false;
}
}
return true;
} catch (Exception e) {
return true;
}
} | java | {
"resource": ""
} |
q174246 | HttpRobotRulesParser.getCacheKey | test | protected static String getCacheKey(URL url) {
String protocol = url.getProtocol().toLowerCase(Locale.ROOT);
String host = url.getHost().toLowerCase(Locale.ROOT);
int port = url.getPort();
if (port == -1) {
port = url.getDefaultPort();
}
/*
* Robot rules apply only to host, protocol, and port where robots.txt
* is hosted (cf. NUTCH-1752). Consequently
*/
return protocol + ":" + host + ":" + port;
} | java | {
"resource": ""
} |
q174247 | HttpRobotRulesParser.getRobotRulesSetFromCache | test | public BaseRobotRules getRobotRulesSetFromCache(URL url) {
String cacheKey = getCacheKey(url);
BaseRobotRules robotRules = CACHE.getIfPresent(cacheKey);
if (robotRules != null) {
return robotRules;
}
return EMPTY_RULES;
} | java | {
"resource": ""
} |
q174248 | RobotsTags.extractMetaTags | test | public void extractMetaTags(DocumentFragment doc)
throws XPathExpressionException {
NodeList nodes = (NodeList) expression.evaluate(doc,
XPathConstants.NODESET);
if (nodes == null)
return;
int numNodes = nodes.getLength();
for (int i = 0; i < numNodes; i++) {
Node n = (Node) nodes.item(i);
// iterate on the attributes
// and check that it has name=robots and content
// whatever the case is
boolean isRobots = false;
String content = null;
NamedNodeMap attrs = n.getAttributes();
for (int att = 0; att < attrs.getLength(); att++) {
Node keyval = attrs.item(att);
if ("name".equalsIgnoreCase(keyval.getNodeName())
&& "robots".equalsIgnoreCase(keyval.getNodeValue())) {
isRobots = true;
continue;
}
if ("content".equalsIgnoreCase(keyval.getNodeName())) {
content = keyval.getNodeValue();
continue;
}
}
if (isRobots && content != null) {
// got a value - split it
String[] vals = content.split(" *, *");
parseValues(vals);
return;
}
}
} | java | {
"resource": ""
} |
q174249 | AbstractStatusUpdaterBolt.ack | test | protected final void ack(Tuple t, String url) {
// keep the URL in the cache
if (useCache) {
cache.put(url, "");
}
_collector.ack(t);
} | java | {
"resource": ""
} |
q174250 | Rules.filter | test | public boolean filter(String url, Metadata metadata)
throws MalformedURLException {
URL u = new URL(url);
// first try the full hostname
String hostname = u.getHost();
if (checkScope(hostNameRules.get(hostname), u)) {
return true;
}
// then on the various components of the domain
String[] domainParts = hostname.split("\\.");
String domain = null;
for (int i = domainParts.length - 1; i >= 0; i--) {
domain = domainParts[i] + (domain == null ? "" : "." + domain);
if (checkScope(domainRules.get(domain), u)) {
return true;
}
}
// check on parent's URL metadata
for (MDScope scope : metadataRules) {
String[] vals = metadata.getValues(scope.getKey());
if (vals == null) {
continue;
}
for (String v : vals) {
if (v.equalsIgnoreCase(scope.getValue())) {
FastURLFilter.LOG.debug(
"Filtering {} matching metadata {}:{}", url,
scope.getKey(), scope.getValue());
if (checkScope(scope, u)) {
return true;
}
}
}
}
if (checkScope(globalRules, u)) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q174251 | RegexURLNormalizer.filter | test | @Override
public String filter(URL sourceUrl, Metadata sourceMetadata,
String urlString) {
Iterator<Rule> i = rules.iterator();
while (i.hasNext()) {
Rule r = i.next();
Matcher matcher = r.pattern.matcher(urlString);
urlString = matcher.replaceAll(r.substitution);
}
if (urlString.equals("")) {
urlString = null;
}
return urlString;
} | java | {
"resource": ""
} |
q174252 | RegexURLNormalizer.readRules | test | private List<Rule> readRules(String rulesFile) {
try {
InputStream regexStream = getClass().getClassLoader()
.getResourceAsStream(rulesFile);
Reader reader = new InputStreamReader(regexStream,
StandardCharsets.UTF_8);
return readConfiguration(reader);
} catch (Exception e) {
LOG.error("Error loading rules from file: {}", e);
return EMPTY_RULES;
}
} | java | {
"resource": ""
} |
q174253 | BasicURLNormalizer.processQueryElements | test | private String processQueryElements(String urlToFilter) {
try {
// Handle illegal characters by making a url first
// this will clean illegal characters like |
URL url = new URL(urlToFilter);
String query = url.getQuery();
String path = url.getPath();
// check if the last element of the path contains parameters
// if so convert them to query elements
if (path.contains(";")) {
String[] pathElements = path.split("/");
String last = pathElements[pathElements.length - 1];
// replace last value by part without params
int semicolon = last.indexOf(";");
if (semicolon != -1) {
pathElements[pathElements.length - 1] = last.substring(0,
semicolon);
String params = last.substring(semicolon + 1).replaceAll(
";", "&");
if (query == null) {
query = params;
} else {
query += "&" + params;
}
// rebuild the path
StringBuilder newPath = new StringBuilder();
for (String p : pathElements) {
if (StringUtils.isNotBlank(p)) {
newPath.append("/").append(p);
}
}
path = newPath.toString();
}
}
if (StringUtils.isEmpty(query)) {
return urlToFilter;
}
List<NameValuePair> pairs = URLEncodedUtils.parse(query,
StandardCharsets.UTF_8);
Iterator<NameValuePair> pairsIterator = pairs.iterator();
while (pairsIterator.hasNext()) {
NameValuePair param = pairsIterator.next();
if (queryElementsToRemove.contains(param.getName())) {
pairsIterator.remove();
} else if (removeHashes && param.getValue() != null) {
Matcher m = thirtytwobithash.matcher(param.getValue());
if (m.matches()) {
pairsIterator.remove();
}
}
}
StringBuilder newFile = new StringBuilder();
if (StringUtils.isNotBlank(path)) {
newFile.append(path);
}
if (!pairs.isEmpty()) {
Collections.sort(pairs, comp);
String newQueryString = URLEncodedUtils.format(pairs,
StandardCharsets.UTF_8);
newFile.append('?').append(newQueryString);
}
if (url.getRef() != null) {
newFile.append('#').append(url.getRef());
}
return new URL(url.getProtocol(), url.getHost(), url.getPort(),
newFile.toString()).toString();
} catch (MalformedURLException e) {
LOG.warn("Invalid urlToFilter {}. {}", urlToFilter, e);
return null;
}
} | java | {
"resource": ""
} |
q174254 | NavigationFilters.fromConf | test | @SuppressWarnings("rawtypes")
public static NavigationFilters fromConf(Map stormConf) {
String configfile = ConfUtils.getString(stormConf,
"navigationfilters.config.file");
if (StringUtils.isNotBlank(configfile)) {
try {
return new NavigationFilters(stormConf, configfile);
} catch (IOException e) {
String message = "Exception caught while loading the NavigationFilters from "
+ configfile;
LOG.error(message);
throw new RuntimeException(message, e);
}
}
return NavigationFilters.emptyNavigationFilters;
} | java | {
"resource": ""
} |
q174255 | GzipHdfsBolt.addRecordFormat | test | public GzipHdfsBolt addRecordFormat(RecordFormat format, int position) {
MultipleRecordFormat formats;
if (this.format == null) {
formats = new MultipleRecordFormat(format);
this.format = formats;
} else {
if (this.format instanceof MultipleRecordFormat) {
formats = (MultipleRecordFormat) this.format;
} else {
formats = new MultipleRecordFormat(this.format);
this.format = formats;
}
formats.addFormat(new GzippedRecordFormat(format), position);
}
return this;
} | java | {
"resource": ""
} |
q174256 | AbstractQueryingSpout.throttleQueries | test | private long throttleQueries() {
if (timeLastQuerySent != 0) {
// check that we allowed some time between queries
long difference = System.currentTimeMillis() - timeLastQuerySent;
if (difference < minDelayBetweenQueries) {
return minDelayBetweenQueries - difference;
}
}
return -1;
} | java | {
"resource": ""
} |
q174257 | AbstractQueryingSpout.triggerQueries | test | private boolean triggerQueries() {
if (timeLastQueryReceived != 0 && maxDelayBetweenQueries > 0) {
// check that we allowed some time between queries
long difference = System.currentTimeMillis()
- timeLastQueryReceived;
if (difference > maxDelayBetweenQueries) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q174258 | ParseFilters.fromConf | test | @SuppressWarnings("rawtypes")
public static ParseFilters fromConf(Map stormConf) {
String parseconfigfile = ConfUtils.getString(stormConf,
"parsefilters.config.file");
if (StringUtils.isNotBlank(parseconfigfile)) {
try {
return new ParseFilters(stormConf, parseconfigfile);
} catch (IOException e) {
String message = "Exception caught while loading the ParseFilters from "
+ parseconfigfile;
LOG.error(message);
throw new RuntimeException(message, e);
}
}
return ParseFilters.emptyParseFilter;
} | java | {
"resource": ""
} |
q174259 | DOMBuilder.append | test | protected void append(Node newNode) throws org.xml.sax.SAXException {
Node currentNode = m_currentNode;
if (null != currentNode) {
currentNode.appendChild(newNode);
// System.out.println(newNode.getNodeName());
} else if (null != m_docFrag) {
m_docFrag.appendChild(newNode);
} else {
boolean ok = true;
short type = newNode.getNodeType();
if (type == Node.TEXT_NODE) {
String data = newNode.getNodeValue();
if ((null != data) && (data.trim().length() > 0)) {
throw new org.xml.sax.SAXException(
"Warning: can't output text before document element! Ignoring...");
}
ok = false;
} else if (type == Node.ELEMENT_NODE) {
if (m_doc.getDocumentElement() != null) {
throw new org.xml.sax.SAXException(
"Can't have more than one root on a DOM!");
}
}
if (ok) {
m_doc.appendChild(newNode);
}
}
} | java | {
"resource": ""
} |
q174260 | DOMBuilder.ignorableWhitespace | test | @Override
public void ignorableWhitespace(char ch[], int start, int length)
throws org.xml.sax.SAXException {
if (isOutsideDocElem()) {
return; // avoid DOM006 Hierarchy request error
}
String s = new String(ch, start, length);
append(m_doc.createTextNode(s));
} | java | {
"resource": ""
} |
q174261 | DOMBuilder.processingInstruction | test | @Override
public void processingInstruction(String target, String data)
throws org.xml.sax.SAXException {
append(m_doc.createProcessingInstruction(target, data));
} | java | {
"resource": ""
} |
q174262 | DOMBuilder.comment | test | @Override
public void comment(char ch[], int start, int length)
throws org.xml.sax.SAXException {
// tagsoup sometimes submits invalid values here
if (ch == null || start < 0 || length >= (ch.length - start)
|| length < 0) {
return;
}
append(m_doc.createComment(new String(ch, start, length)));
} | java | {
"resource": ""
} |
q174263 | DOMBuilder.cdata | test | public void cdata(char ch[], int start, int length) {
if (isOutsideDocElem()
&& XMLCharacterRecognizer.isWhiteSpace(ch, start, length)) {
return; // avoid DOM006 Hierarchy request error
}
String s = new String(ch, start, length);
// XXX ab@apache.org: modified from the original, to accomodate TagSoup.
Node n = m_currentNode.getLastChild();
if (n instanceof CDATASection) {
((CDATASection) n).appendData(s);
} else if (n instanceof Comment) {
((Comment) n).appendData(s);
}
} | java | {
"resource": ""
} |
q174264 | DOMBuilder.startDTD | test | @Override
public void startDTD(String name, String publicId, String systemId)
throws org.xml.sax.SAXException {
// Do nothing for now.
} | java | {
"resource": ""
} |
q174265 | DOMBuilder.startPrefixMapping | test | @Override
public void startPrefixMapping(String prefix, String uri)
throws org.xml.sax.SAXException {
/*
* // Not sure if this is needed or wanted // Also, it fails in the
* stree. if((null != m_currentNode) && (m_currentNode.getNodeType() ==
* Node.ELEMENT_NODE)) { String qname; if(((null != prefix) &&
* (prefix.length() == 0)) || (null == prefix)) qname = "xmlns"; else
* qname = "xmlns:"+prefix;
*
* Element elem = (Element)m_currentNode; String val =
* elem.getAttribute(qname); // Obsolete, should be DOM2...? if(val ==
* null) { elem.setAttributeNS("http://www.w3.org/XML/1998/namespace",
* qname, uri); } }
*/
} | java | {
"resource": ""
} |
q174266 | AbstractIndexerBolt.valueForURL | test | protected String valueForURL(Tuple tuple) {
String url = tuple.getStringByField("url");
Metadata metadata = (Metadata) tuple.getValueByField("metadata");
// functionality deactivated
if (StringUtils.isBlank(canonicalMetadataParamName)) {
return url;
}
String canonicalValue = metadata.getFirstValue(canonicalMetadataName);
// no value found?
if (StringUtils.isBlank(canonicalValue)) {
return url;
}
try {
URL sURL = new URL(url);
URL canonical = URLUtil.resolveURL(sURL, canonicalValue);
String sDomain = PaidLevelDomain.getPLD(sURL.getHost());
String canonicalDomain = PaidLevelDomain
.getPLD(canonical.getHost());
// check that the domain is the same
if (sDomain.equalsIgnoreCase(canonicalDomain)) {
return canonical.toExternalForm();
} else {
LOG.info(
"Canonical URL references a different domain, ignoring in {} ",
url);
}
} catch (MalformedURLException e) {
LOG.error("Malformed canonical URL {} was found in {} ",
canonicalValue, url);
}
return url;
} | java | {
"resource": ""
} |
q174267 | AbstractIndexerBolt.trimText | test | protected String trimText(String text) {
if (maxLengthText == -1)
return text;
if (text == null)
return text;
if (text.length() <= maxLengthText)
return text;
return text.substring(0, maxLengthText);
} | java | {
"resource": ""
} |
q174268 | DefaultScheduler.checkCustomInterval | test | protected final Optional<Integer> checkCustomInterval(Metadata metadata,
Status s) {
if (customIntervals == null)
return Optional.empty();
for (CustomInterval customInterval : customIntervals) {
String[] values = metadata.getValues(customInterval.key);
if (values == null) {
continue;
}
for (String v : values) {
if (v.equals(customInterval.value)) {
return customInterval.getDurationForStatus(s);
}
}
}
return Optional.empty();
} | java | {
"resource": ""
} |
q174269 | URLFilters.fromConf | test | public static URLFilters fromConf(Map stormConf) {
String configFile = ConfUtils.getString(stormConf,
"urlfilters.config.file");
if (StringUtils.isNotBlank(configFile)) {
try {
return new URLFilters(stormConf, configFile);
} catch (IOException e) {
String message = "Exception caught while loading the URLFilters from "
+ configFile;
LOG.error(message);
throw new RuntimeException(message, e);
}
}
return URLFilters.emptyURLFilters;
} | java | {
"resource": ""
} |
q174270 | WheelView.setWheelItemCount | test | public void setWheelItemCount(int count) {
mItemCount = count;
mItemAngle = calculateItemAngle(count);
if (mWheelBounds != null) {
invalidate();
//TODO ?
}
} | java | {
"resource": ""
} |
q174271 | WheelView.resolveSizeAndState | test | public static int resolveSizeAndState(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
if (specSize < size) {
result = specSize;
} else {
result = size;
}
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
} | java | {
"resource": ""
} |
q174272 | WheelView.setEmptyItemDrawable | test | public void setEmptyItemDrawable(Drawable drawable) {
mEmptyItemDrawable = drawable;
EMPTY_CACHE_ITEM.mDrawable = drawable;
if (mWheelBounds != null) {
invalidate();
}
} | java | {
"resource": ""
} |
q174273 | WheelView.setAngle | test | public void setAngle(float angle) {
mAngle = angle;
updateSelectedPosition();
if (mOnAngleChangeListener != null) {
mOnAngleChangeListener.onWheelAngleChange(mAngle);
}
invalidate();
} | java | {
"resource": ""
} |
q174274 | WheelView.updateSelectedPosition | test | private void updateSelectedPosition() {
int position = (int) ((-mAngle + -0.5 * Math.signum(mAngle) * mItemAngle) / mItemAngle);
setSelectedPosition(position);
} | java | {
"resource": ""
} |
q174275 | WheelView.invalidateWheelItemDrawable | test | public void invalidateWheelItemDrawable(int position) {
int adapterPos = rawPositionToAdapterPosition(position);
if (isEmptyItemPosition(adapterPos)) return;
CacheItem cacheItem = mItemCacheArray[adapterPos];
if (cacheItem != null) cacheItem.mDirty = true;
invalidate();
} | java | {
"resource": ""
} |
q174276 | WheelView.rawPositionToWheelPosition | test | public int rawPositionToWheelPosition(int position, int adapterPosition) {
int circularOffset = mIsRepeatable ? ((int) Math.floor((position /
(float) mAdapterItemCount)) * (mAdapterItemCount - mItemCount)) : 0;
return Circle.clamp(adapterPosition + circularOffset, mItemCount);
} | java | {
"resource": ""
} |
q174277 | WheelView.update | test | private void update(float deltaTime) {
float vel = mAngularVelocity;
float velSqr = vel*vel;
if (vel > 0f) {
//TODO the damping is not based on time
mAngularVelocity -= velSqr * VELOCITY_FRICTION_COEFFICIENT + CONSTANT_FRICTION_COEFFICIENT;
if (mAngularVelocity < 0f) mAngularVelocity = 0f;
} else if (vel < 0f) {
mAngularVelocity -= velSqr * -VELOCITY_FRICTION_COEFFICIENT - CONSTANT_FRICTION_COEFFICIENT;
if (mAngularVelocity > 0f) mAngularVelocity = 0f;
}
if (mAngularVelocity != 0f) {
addAngle(mAngularVelocity * deltaTime);
} else {
mRequiresUpdate = false;
}
} | java | {
"resource": ""
} |
q174278 | MainActivity.getContrastColor | test | private int getContrastColor(Map.Entry<String, Integer> entry) {
String colorName = MaterialColor.getColorName(entry);
return MaterialColor.getContrastColor(colorName);
} | java | {
"resource": ""
} |
q174279 | Circle.clamp | test | static int clamp(int value, int upperLimit) {
if (value < 0) {
return value + (-1 * (int) Math.floor(value / (float) upperLimit)) * upperLimit;
} else {
return value % upperLimit;
}
} | java | {
"resource": ""
} |
q174280 | CoverallsReportMojo.writeCoveralls | test | protected void writeCoveralls(final JsonWriter writer, final SourceCallback sourceCallback, final List<CoverageParser> parsers) throws ProcessingException, IOException {
try {
getLog().info("Writing Coveralls data to " + writer.getCoverallsFile().getAbsolutePath() + "...");
long now = System.currentTimeMillis();
sourceCallback.onBegin();
for (CoverageParser parser : parsers) {
getLog().info("Processing coverage report from " + parser.getCoverageFile().getAbsolutePath());
parser.parse(sourceCallback);
}
sourceCallback.onComplete();
long duration = System.currentTimeMillis() - now;
getLog().info("Successfully wrote Coveralls data in " + duration + "ms");
} finally {
writer.close();
}
} | java | {
"resource": ""
} |
q174281 | ArrayChar.getDataAsByteBuffer | test | @Override
public ByteBuffer getDataAsByteBuffer() {
ByteBuffer bb = ByteBuffer.allocate((int)getSize());
resetLocalIterator();
while (hasNext())
bb.put( nextByte());
return bb;
} | java | {
"resource": ""
} |
q174282 | ArrayChar.setString | test | public void setString(String val) {
int rank = getRank();
if (rank != 1)
throw new IllegalArgumentException("ArayChar.setString rank must be 1");
int arrayLen = indexCalc.getShape(0);
int strLen = Math.min(val.length(), arrayLen);
for (int k = 0; k < strLen; k++)
storage[k] = val.charAt(k);
char c = 0;
for (int k = strLen; k < arrayLen; k++)
storage[k] = c;
} | java | {
"resource": ""
} |
q174283 | ArrayChar.make1DStringArray | test | public ArrayObject make1DStringArray() {
int nelems = (getRank() == 0) ? 1 : (int) getSize() / indexCalc.getShape(getRank()-1);
Array sarr = Array.factory(DataType.STRING, new int[]{nelems});
IndexIterator newsiter = sarr.getIndexIterator();
ArrayChar.StringIterator siter = getStringIterator();
while (siter.hasNext()) {
newsiter.setObjectNext(siter.next());
}
return (ArrayObject) sarr;
} | java | {
"resource": ""
} |
q174284 | ArrayChar.makeFromString | test | public static ArrayChar makeFromString(String s, int max) {
ArrayChar result = new ArrayChar.D1( max);
for (int i=0; i<max && i<s.length(); i++)
result.setChar( i, s.charAt(i));
return result;
} | java | {
"resource": ""
} |
q174285 | ArrayChar.makeFromStringArray | test | public static ArrayChar makeFromStringArray(ArrayObject values) {
// find longest string
IndexIterator ii = values.getIndexIterator();
int strlen = 0;
while (ii.hasNext()) {
String s = (String) ii.next();
strlen = Math.max(s.length(), strlen);
}
return makeFromStringArray(values, strlen);
} | java | {
"resource": ""
} |
q174286 | ArrayChar.makeFromStringArray | test | public static ArrayChar makeFromStringArray(ArrayObject values, int strlen) {
// create shape for equivilent charArray
try {
Section section = new Section(values.getShape());
section.appendRange(strlen);
int[] shape = section.getShape();
long size = section.computeSize();
// populate char array
char[] cdata = new char[(int) size];
int start = 0;
IndexIterator ii = values.getIndexIterator();
while (ii.hasNext()) {
String s = (String) ii.next();
for (int k = 0; k < s.length() && k < strlen; k++)
cdata[start + k] = s.charAt(k);
start += strlen;
}
// ready to create the char Array
Array carr = Array.factory(DataType.CHAR, shape, cdata);
return (ArrayChar) carr;
} catch (InvalidRangeException e) {
e.printStackTrace(); // cant happen.
return null;
}
} | java | {
"resource": ""
} |
q174287 | CfsrLocalTables.getForecastTimeIntervalOffset | test | @Override
public int[] getForecastTimeIntervalOffset(Grib2Record gr) {
Grib2Pds pds = gr.getPDS();
if (!pds.isTimeInterval()) {
return null;
}
// LOOK this is hack for CFSR monthly combobulation
// see http://rda.ucar.edu/datasets/ds093.2/#docs/time_ranges.html
int statType = pds.getOctet(47);
int n = pds.getInt4StartingAtOctet(50);
int p2 = pds.getInt4StartingAtOctet(55);
int p2mp1 = pds.getInt4StartingAtOctet(62);
int p1 = p2 - p2mp1;
int start, end;
switch (statType) {
case 193:
start = p1;
end = p1 + n * p2;
break;
case 194:
start = 0;
end = n * p2;
break;
case 195:
case 204:
case 205:
start = p1;
end = p2;
break;
default:
throw new IllegalArgumentException("unknown statType " + statType);
}
return new int[]{start, end};
} | java | {
"resource": ""
} |
q174288 | IndependentWindow.show | test | public void show() {
setState( Frame.NORMAL ); // deiconify if needed
super.toFront();
// need to put on event thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
IndependentWindow.super.show();
}
});
} | java | {
"resource": ""
} |
q174289 | IndependentWindow.showIfNotIconified | test | public void showIfNotIconified() {
if (getState() == Frame.ICONIFIED) return;
// need to put on event thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
IndependentWindow.super.show();
}
});
} | java | {
"resource": ""
} |
q174290 | CFGridWriter2.makeSizeEstimate | test | static public long makeSizeEstimate(ucar.nc2.dt.GridDataset gds, List<String> gridList,
LatLonRect llbb, ProjectionRect projRect, int horizStride, Range zRange,
CalendarDateRange dateRange, int stride_time, boolean addLatLon) throws IOException, InvalidRangeException {
CFGridWriter2 writer2 = new CFGridWriter2();
return writer2.writeOrTestSize(gds, gridList, llbb, projRect, horizStride, zRange, dateRange, stride_time, addLatLon, true, null);
} | java | {
"resource": ""
} |
q174291 | Grib1RecordScanner.main | test | public static void main(String[] args) throws IOException {
int count = 0;
String file = (args.length > 0) ? args[0] : "Q:/cdmUnitTest/formats/grib1/ECMWF.hybrid.grib1";
RandomAccessFile raf = new RandomAccessFile(file, "r");
System.out.printf("Read %s%n", raf.getLocation());
Grib1RecordScanner scan = new Grib1RecordScanner(raf);
while (scan.hasNext()) {
scan.next();
count++;
}
raf.close();
System.out.printf("count=%d%n", count);
} | java | {
"resource": ""
} |
q174292 | UnitName.newUnitName | test | public static UnitName newUnitName(final String name, final String plural)
throws NameException {
return newUnitName(name, plural, null);
} | java | {
"resource": ""
} |
q174293 | UnitName.newUnitName | test | public static UnitName newUnitName(final String name, final String plural,
final String symbol) throws NameException {
return new UnitName(name, plural, symbol);
} | java | {
"resource": ""
} |
q174294 | UnitName.makePlural | test | protected String makePlural(final String name) {
String plural;
final int length = name.length();
final char lastChar = name.charAt(length - 1);
if (lastChar != 'y') {
plural = name
+ (lastChar == 's' || lastChar == 'x' || lastChar == 'z'
|| name.endsWith("ch")
? "es"
: "s");
}
else {
if (length == 1) {
plural = name + "s";
}
else {
final char penultimateChar = name.charAt(length - 2);
plural = (penultimateChar == 'a' || penultimateChar == 'e'
|| penultimateChar == 'i' || penultimateChar == 'o' || penultimateChar == 'u')
? name + "s"
: name.substring(0, length - 1) + "ies";
}
}
return plural;
} | java | {
"resource": ""
} |
q174295 | DateRange.included | test | public boolean included(Date d) {
if (isEmpty) return false;
if (getStart().after(d)) return false;
if (getEnd().before(d)) return false;
return true;
} | java | {
"resource": ""
} |
q174296 | DateRange.intersect | test | public DateRange intersect(DateRange clip) {
if (isEmpty) return this;
if (clip.isEmpty) return clip;
DateType ss = getStart();
DateType s = ss.before(clip.getStart()) ? clip.getStart() : ss;
DateType ee = getEnd();
DateType e = ee.before(clip.getEnd()) ? ee : clip.getEnd();
return new DateRange(s, e, null, resolution);
} | java | {
"resource": ""
} |
q174297 | DateRange.extend | test | public void extend(DateRange dr) {
boolean localEmpty = isEmpty;
if (localEmpty || dr.getStart().before(getStart()))
setStart(dr.getStart());
if (localEmpty || getEnd().before(dr.getEnd()))
setEnd(dr.getEnd());
} | java | {
"resource": ""
} |
q174298 | DateRange.extend | test | public void extend(Date d) {
if (d.before(getStart().getDate()))
setStart( new DateType(false, d));
if (getEnd().before(d))
setEnd(new DateType(false, d));
} | java | {
"resource": ""
} |
q174299 | DateRange.setStart | test | public void setStart(DateType start) {
this.start = start;
useStart = true;
if (useEnd) {
this.isMoving = this.start.isPresent() || this.end.isPresent();
useDuration = false;
recalcDuration();
} else {
this.isMoving = this.start.isPresent();
this.end = this.start.add(duration);
}
checkIfEmpty();
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.