_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q7200
BoxTermsOfServiceUserStatus.updateInfo
train
public void updateInfo(BoxTermsOfServiceUserStatus.Info info) { URL url = TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); request.setBody(info.getPendingChanges()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); info.update(responseJSON); }
java
{ "resource": "" }
q7201
BatchAPIRequest.execute
train
public List<BoxAPIResponse> execute(List<BoxAPIRequest> requests) { this.prepareRequest(requests); BoxJSONResponse batchResponse = (BoxJSONResponse) send(); return this.parseResponse(batchResponse); }
java
{ "resource": "" }
q7202
BatchAPIRequest.prepareRequest
train
protected void prepareRequest(List<BoxAPIRequest> requests) { JsonObject body = new JsonObject(); JsonArray requestsJSONArray = new JsonArray(); for (BoxAPIRequest request: requests) { JsonObject batchRequest = new JsonObject(); batchRequest.add("method", request.getMethod()); batchRequest.add("relative_url", request.getUrl().toString().substring(this.api.getBaseURL().length() - 1)); //If the actual request has a JSON body then add it to vatch request if (request instanceof BoxJSONRequest) { BoxJSONRequest jsonRequest = (BoxJSONRequest) request; batchRequest.add("body", jsonRequest.getBodyAsJsonValue()); } //Add any headers that are in the request, except Authorization if (request.getHeaders() != null) { JsonObject batchRequestHeaders = new JsonObject(); for (RequestHeader header: request.getHeaders()) { if (header.getKey() != null && !header.getKey().isEmpty() && !HttpHeaders.AUTHORIZATION.equals(header.getKey())) { batchRequestHeaders.add(header.getKey(), header.getValue()); } } batchRequest.add("headers", batchRequestHeaders); } //Add the request to array requestsJSONArray.add(batchRequest); } //Add the requests array to body body.add("requests", requestsJSONArray); super.setBody(body); }
java
{ "resource": "" }
q7203
BatchAPIRequest.parseResponse
train
protected List<BoxAPIResponse> parseResponse(BoxJSONResponse batchResponse) { JsonObject responseJSON = JsonObject.readFrom(batchResponse.getJSON()); List<BoxAPIResponse> responses = new ArrayList<BoxAPIResponse>(); Iterator<JsonValue> responseIterator = responseJSON.get("responses").asArray().iterator(); while (responseIterator.hasNext()) { JsonObject jsonResponse = responseIterator.next().asObject(); BoxAPIResponse response = null; //Gather headers Map<String, String> responseHeaders = new HashMap<String, String>(); if (jsonResponse.get("headers") != null) { JsonObject batchResponseHeadersObject = jsonResponse.get("headers").asObject(); for (JsonObject.Member member : batchResponseHeadersObject) { String headerName = member.getName(); String headerValue = member.getValue().asString(); responseHeaders.put(headerName, headerValue); } } // Construct a BoxAPIResponse when response is null, or a BoxJSONResponse when there's a response // (not anticipating any other response as per current APIs. // Ideally we should do it based on response header) if (jsonResponse.get("response") == null || jsonResponse.get("response").isNull()) { response = new BoxAPIResponse(jsonResponse.get("status").asInt(), responseHeaders); } else { response = new BoxJSONResponse(jsonResponse.get("status").asInt(), responseHeaders, jsonResponse.get("response").asObject()); } responses.add(response); } return responses; }
java
{ "resource": "" }
q7204
ScanUtil.generateJson
train
private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder, PrintStream out) throws JsonIOException { Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0) .create(); Map<String, String> json = new LinkedHashMap<>(); for (RowColumnValue rcv : cellScanner) { json.put(FLUO_ROW, encoder.apply(rcv.getRow())); json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily())); json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier())); json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility())); json.put(FLUO_VALUE, encoder.apply(rcv.getValue())); gson.toJson(json, out); out.append("\n"); if (out.checkError()) { break; } } out.flush(); }
java
{ "resource": "" }
q7205
TxInfo.getTransactionInfo
train
public static TxInfo getTransactionInfo(Environment env, Bytes prow, Column pcol, long startTs) { // TODO ensure primary is visible IteratorSetting is = new IteratorSetting(10, RollbackCheckIterator.class); RollbackCheckIterator.setLocktime(is, startTs); Entry<Key, Value> entry = ColumnUtil.checkColumn(env, is, prow, pcol); TxInfo txInfo = new TxInfo(); if (entry == null) { txInfo.status = TxStatus.UNKNOWN; return txInfo; } ColumnType colType = ColumnType.from(entry.getKey()); long ts = entry.getKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK; switch (colType) { case LOCK: { if (ts == startTs) { txInfo.status = TxStatus.LOCKED; txInfo.lockValue = entry.getValue().get(); } else { txInfo.status = TxStatus.UNKNOWN; // locked by another tx } break; } case DEL_LOCK: { DelLockValue dlv = new DelLockValue(entry.getValue().get()); if (ts != startTs) { // expect this to always be false, must be a bug in the iterator throw new IllegalStateException(prow + " " + pcol + " (" + ts + " != " + startTs + ") "); } if (dlv.isRollback()) { txInfo.status = TxStatus.ROLLED_BACK; } else { txInfo.status = TxStatus.COMMITTED; txInfo.commitTs = dlv.getCommitTimestamp(); } break; } case WRITE: { long timePtr = WriteValue.getTimestamp(entry.getValue().get()); if (timePtr != startTs) { // expect this to always be false, must be a bug in the iterator throw new IllegalStateException( prow + " " + pcol + " (" + timePtr + " != " + startTs + ") "); } txInfo.status = TxStatus.COMMITTED; txInfo.commitTs = ts; break; } default: throw new IllegalStateException("unexpected col type returned " + colType); } return txInfo; }
java
{ "resource": "" }
q7206
OracleServerUtils.oracleExists
train
public static boolean oracleExists(CuratorFramework curator) { boolean exists = false; try { exists = curator.checkExists().forPath(ZookeeperPath.ORACLE_SERVER) != null && !curator.getChildren().forPath(ZookeeperPath.ORACLE_SERVER).isEmpty(); } catch (Exception nne) { if (nne instanceof KeeperException.NoNodeException) { // you'll do nothing } else { throw new RuntimeException(nne); } } return exists; }
java
{ "resource": "" }
q7207
SharedBatchWriter.waitForAsyncFlush
train
public void waitForAsyncFlush() { long numAdded = asyncBatchesAdded.get(); synchronized (this) { while (numAdded > asyncBatchesProcessed) { try { wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
java
{ "resource": "" }
q7208
Span.exact
train
public static Span exact(Bytes row) { Objects.requireNonNull(row); return new Span(row, true, row, true); }
java
{ "resource": "" }
q7209
Span.exact
train
public static Span exact(CharSequence row) { Objects.requireNonNull(row); return exact(Bytes.of(row)); }
java
{ "resource": "" }
q7210
Span.prefix
train
public static Span prefix(Bytes rowPrefix) { Objects.requireNonNull(rowPrefix); Bytes fp = followingPrefix(rowPrefix); return new Span(rowPrefix, true, fp == null ? Bytes.EMPTY : fp, false); }
java
{ "resource": "" }
q7211
Span.prefix
train
public static Span prefix(CharSequence rowPrefix) { Objects.requireNonNull(rowPrefix); return prefix(Bytes.of(rowPrefix)); }
java
{ "resource": "" }
q7212
SimpleConfiguration.load
train
public void load(InputStream in) { try { PropertiesConfiguration config = new PropertiesConfiguration(); // disabled to prevent accumulo classpath value from being shortened config.setDelimiterParsingDisabled(true); config.load(in); ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException e) { throw new IllegalArgumentException(e); } }
java
{ "resource": "" }
q7213
SimpleConfiguration.load
train
public void load(File file) { try { PropertiesConfiguration config = new PropertiesConfiguration(); // disabled to prevent accumulo classpath value from being shortened config.setDelimiterParsingDisabled(true); config.load(file); ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException e) { throw new IllegalArgumentException(e); } }
java
{ "resource": "" }
q7214
FluoConfigurationImpl.getTxInfoCacheWeight
train
public static long getTxInfoCacheWeight(FluoConfiguration conf) { long size = conf.getLong(TX_INFO_CACHE_WEIGHT, TX_INFO_CACHE_WEIGHT_DEFAULT); if (size <= 0) { throw new IllegalArgumentException("Cache size must be positive for " + TX_INFO_CACHE_WEIGHT); } return size; }
java
{ "resource": "" }
q7215
FluoConfigurationImpl.getVisibilityCacheWeight
train
public static long getVisibilityCacheWeight(FluoConfiguration conf) { long size = conf.getLong(VISIBILITY_CACHE_WEIGHT, VISIBILITY_CACHE_WEIGHT_DEFAULT); if (size <= 0) { throw new IllegalArgumentException( "Cache size must be positive for " + VISIBILITY_CACHE_WEIGHT); } return size; }
java
{ "resource": "" }
q7216
ZookeeperUtil.parseServers
train
public static String parseServers(String zookeepers) { int slashIndex = zookeepers.indexOf("/"); if (slashIndex != -1) { return zookeepers.substring(0, slashIndex); } return zookeepers; }
java
{ "resource": "" }
q7217
ZookeeperUtil.parseRoot
train
public static String parseRoot(String zookeepers) { int slashIndex = zookeepers.indexOf("/"); if (slashIndex != -1) { return zookeepers.substring(slashIndex).trim(); } return "/"; }
java
{ "resource": "" }
q7218
ZookeeperUtil.getGcTimestamp
train
public static long getGcTimestamp(String zookeepers) { ZooKeeper zk = null; try { zk = new ZooKeeper(zookeepers, 30000, null); // wait until zookeeper is connected long start = System.currentTimeMillis(); while (!zk.getState().isConnected() && System.currentTimeMillis() - start < 30000) { Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS); } byte[] d = zk.getData(ZookeeperPath.ORACLE_GC_TIMESTAMP, false, null); return LongUtil.fromByteArray(d); } catch (KeeperException | InterruptedException | IOException e) { log.warn("Failed to get oldest timestamp of Oracle from Zookeeper", e); return OLDEST_POSSIBLE; } finally { if (zk != null) { try { zk.close(); } catch (InterruptedException e) { log.error("Failed to close zookeeper client", e); } } } }
java
{ "resource": "" }
q7219
ByteUtil.toBytes
train
public static Bytes toBytes(Text t) { return Bytes.of(t.getBytes(), 0, t.getLength()); }
java
{ "resource": "" }
q7220
FluoEntryInputFormat.configure
train
public static void configure(Job conf, SimpleConfiguration config) { try { FluoConfiguration fconfig = new FluoConfiguration(config); try (Environment env = new Environment(fconfig)) { long ts = env.getSharedResources().getTimestampTracker().allocateTimestamp().getTxTimestamp(); conf.getConfiguration().setLong(TIMESTAMP_CONF_KEY, ts); ByteArrayOutputStream baos = new ByteArrayOutputStream(); config.save(baos); conf.getConfiguration().set(PROPS_CONF_KEY, new String(baos.toByteArray(), StandardCharsets.UTF_8)); AccumuloInputFormat.setZooKeeperInstance(conf, fconfig.getAccumuloInstance(), fconfig.getAccumuloZookeepers()); AccumuloInputFormat.setConnectorInfo(conf, fconfig.getAccumuloUser(), new PasswordToken(fconfig.getAccumuloPassword())); AccumuloInputFormat.setInputTableName(conf, env.getTable()); AccumuloInputFormat.setScanAuthorizations(conf, env.getAuthorizations()); } } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q7221
TransactionImpl.readUnread
train
private void readUnread(CommitData cd, Consumer<Entry<Key, Value>> locksSeen) { // TODO make async // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user // may not iterate over entire range Map<Bytes, Set<Column>> columnsToRead = new HashMap<>(); for (Entry<Bytes, Set<Column>> entry : cd.getRejected().entrySet()) { Set<Column> rowColsRead = columnsRead.get(entry.getKey()); if (rowColsRead == null) { columnsToRead.put(entry.getKey(), entry.getValue()); } else { HashSet<Column> colsToRead = new HashSet<>(entry.getValue()); colsToRead.removeAll(rowColsRead); if (!colsToRead.isEmpty()) { columnsToRead.put(entry.getKey(), colsToRead); } } } for (Entry<Bytes, Set<Column>> entry : columnsToRead.entrySet()) { getImpl(entry.getKey(), entry.getValue(), locksSeen); } }
java
{ "resource": "" }
q7222
Bytes.byteAt
train
public byte byteAt(int i) { if (i < 0) { throw new IndexOutOfBoundsException("i < 0, " + i); } if (i >= length) { throw new IndexOutOfBoundsException("i >= length, " + i + " >= " + length); } return data[offset + i]; }
java
{ "resource": "" }
q7223
Bytes.subSequence
train
public Bytes subSequence(int start, int end) { if (start > end || start < 0 || end > length) { throw new IndexOutOfBoundsException("Bad start and/end start = " + start + " end=" + end + " offset=" + offset + " length=" + length); } return new Bytes(data, offset + start, end - start); }
java
{ "resource": "" }
q7224
Bytes.toArray
train
public byte[] toArray() { byte[] copy = new byte[length]; System.arraycopy(data, offset, copy, 0, length); return copy; }
java
{ "resource": "" }
q7225
Bytes.contentEquals
train
public boolean contentEquals(byte[] bytes, int offset, int len) { Preconditions.checkArgument(len >= 0 && offset >= 0 && offset + len <= bytes.length); return contentEqualsUnchecked(bytes, offset, len); }
java
{ "resource": "" }
q7226
Bytes.contentEqualsUnchecked
train
private boolean contentEqualsUnchecked(byte[] bytes, int offset, int len) { if (length != len) { return false; } return compareToUnchecked(bytes, offset, len) == 0; }
java
{ "resource": "" }
q7227
Bytes.of
train
public static final Bytes of(byte[] array) { Objects.requireNonNull(array); if (array.length == 0) { return EMPTY; } byte[] copy = new byte[array.length]; System.arraycopy(array, 0, copy, 0, array.length); return new Bytes(copy); }
java
{ "resource": "" }
q7228
Bytes.of
train
public static final Bytes of(byte[] data, int offset, int length) { Objects.requireNonNull(data); if (length == 0) { return EMPTY; } byte[] copy = new byte[length]; System.arraycopy(data, offset, copy, 0, length); return new Bytes(copy); }
java
{ "resource": "" }
q7229
Bytes.of
train
public static final Bytes of(ByteBuffer bb) { Objects.requireNonNull(bb); if (bb.remaining() == 0) { return EMPTY; } byte[] data; if (bb.hasArray()) { data = Arrays.copyOfRange(bb.array(), bb.position() + bb.arrayOffset(), bb.limit() + bb.arrayOffset()); } else { data = new byte[bb.remaining()]; // duplicate so that it does not change position bb.duplicate().get(data); } return new Bytes(data); }
java
{ "resource": "" }
q7230
Bytes.of
train
public static final Bytes of(CharSequence cs) { if (cs instanceof String) { return of((String) cs); } Objects.requireNonNull(cs); if (cs.length() == 0) { return EMPTY; } ByteBuffer bb = StandardCharsets.UTF_8.encode(CharBuffer.wrap(cs)); if (bb.hasArray()) { // this byte buffer has never escaped so can use its byte array directly return new Bytes(bb.array(), bb.position() + bb.arrayOffset(), bb.limit()); } else { byte[] data = new byte[bb.remaining()]; bb.get(data); return new Bytes(data); } }
java
{ "resource": "" }
q7231
Bytes.of
train
public static final Bytes of(String s) { Objects.requireNonNull(s); if (s.isEmpty()) { return EMPTY; } byte[] data = s.getBytes(StandardCharsets.UTF_8); return new Bytes(data, s); }
java
{ "resource": "" }
q7232
Bytes.of
train
public static final Bytes of(String s, Charset c) { Objects.requireNonNull(s); Objects.requireNonNull(c); if (s.isEmpty()) { return EMPTY; } byte[] data = s.getBytes(c); return new Bytes(data); }
java
{ "resource": "" }
q7233
Bytes.startsWith
train
public boolean startsWith(Bytes prefix) { Objects.requireNonNull(prefix, "startWith(Bytes prefix) cannot have null parameter"); if (prefix.length > this.length) { return false; } else { int end = this.offset + prefix.length; for (int i = this.offset, j = prefix.offset; i < end; i++, j++) { if (this.data[i] != prefix.data[j]) { return false; } } } return true; }
java
{ "resource": "" }
q7234
Bytes.endsWith
train
public boolean endsWith(Bytes suffix) { Objects.requireNonNull(suffix, "endsWith(Bytes suffix) cannot have null parameter"); int startOffset = this.length - suffix.length; if (startOffset < 0) { return false; } else { int end = startOffset + this.offset + suffix.length; for (int i = startOffset + this.offset, j = suffix.offset; i < end; i++, j++) { if (this.data[i] != suffix.data[j]) { return false; } } } return true; }
java
{ "resource": "" }
q7235
Bytes.copyTo
train
public void copyTo(int start, int end, byte[] dest, int destPos) { // this.subSequence(start, end).copyTo(dest, destPos) would allocate another Bytes object arraycopy(start, dest, destPos, end - start); }
java
{ "resource": "" }
q7236
ColumnBuffer.copyTo
train
public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) { dest.clear(); if (key != null) { dest.key = new Key(key); } for (int i = 0; i < timeStamps.size(); i++) { long time = timeStamps.get(i); if (timestampTest.test(time)) { dest.add(time, values.get(i)); } } }
java
{ "resource": "" }
q7237
AccumuloUtil.getClient
train
public static AccumuloClient getClient(FluoConfiguration config) { return Accumulo.newClient().to(config.getAccumuloInstance(), config.getAccumuloZookeepers()) .as(config.getAccumuloUser(), config.getAccumuloPassword()).build(); }
java
{ "resource": "" }
q7238
ByteArrayUtil.encode
train
public static byte[] encode(byte[] ba, int offset, long v) { ba[offset + 0] = (byte) (v >>> 56); ba[offset + 1] = (byte) (v >>> 48); ba[offset + 2] = (byte) (v >>> 40); ba[offset + 3] = (byte) (v >>> 32); ba[offset + 4] = (byte) (v >>> 24); ba[offset + 5] = (byte) (v >>> 16); ba[offset + 6] = (byte) (v >>> 8); ba[offset + 7] = (byte) (v >>> 0); return ba; }
java
{ "resource": "" }
q7239
ByteArrayUtil.decodeLong
train
public static long decodeLong(byte[] ba, int offset) { return ((((long) ba[offset + 0] << 56) + ((long) (ba[offset + 1] & 255) << 48) + ((long) (ba[offset + 2] & 255) << 40) + ((long) (ba[offset + 3] & 255) << 32) + ((long) (ba[offset + 4] & 255) << 24) + ((ba[offset + 5] & 255) << 16) + ((ba[offset + 6] & 255) << 8) + ((ba[offset + 7] & 255) << 0))); }
java
{ "resource": "" }
q7240
ByteArrayUtil.concat
train
public static byte[] concat(Bytes... listOfBytes) { int offset = 0; int size = 0; for (Bytes b : listOfBytes) { size += b.length() + checkVlen(b.length()); } byte[] data = new byte[size]; for (Bytes b : listOfBytes) { offset = writeVint(data, offset, b.length()); b.copyTo(0, b.length(), data, offset); offset += b.length(); } return data; }
java
{ "resource": "" }
q7241
ByteArrayUtil.writeVint
train
public static int writeVint(byte[] dest, int offset, int i) { if (i >= -112 && i <= 127) { dest[offset++] = (byte) i; } else { int len = -112; if (i < 0) { i ^= -1L; // take one's complement' len = -120; } long tmp = i; while (tmp != 0) { tmp = tmp >> 8; len--; } dest[offset++] = (byte) len; len = (len < -120) ? -(len + 120) : -(len + 112); for (int idx = len; idx != 0; idx--) { int shiftbits = (idx - 1) * 8; long mask = 0xFFL << shiftbits; dest[offset++] = (byte) ((i & mask) >> shiftbits); } } return offset; }
java
{ "resource": "" }
q7242
ByteArrayUtil.checkVlen
train
public static int checkVlen(int i) { int count = 0; if (i >= -112 && i <= 127) { return 1; } else { int len = -112; if (i < 0) { i ^= -1L; // take one's complement' len = -120; } long tmp = i; while (tmp != 0) { tmp = tmp >> 8; len--; } count++; len = (len < -120) ? -(len + 120) : -(len + 112); while (len != 0) { count++; len--; } return count; } }
java
{ "resource": "" }
q7243
YarnAppRunner.getResourceReport
train
private ResourceReport getResourceReport(TwillController controller, int maxWaitMs) { ResourceReport report = controller.getResourceReport(); int elapsed = 0; while (report == null) { report = controller.getResourceReport(); try { Thread.sleep(500); } catch (InterruptedException e) { throw new IllegalStateException(e); } elapsed += 500; if ((maxWaitMs != -1) && (elapsed > maxWaitMs)) { String msg = String.format("Exceeded max wait time to retrieve ResourceReport from Twill." + " Elapsed time = %s ms", elapsed); log.error(msg); throw new IllegalStateException(msg); } if ((elapsed % 10000) == 0) { log.info("Waiting for ResourceReport from Twill. Elapsed time = {} ms", elapsed); } } return report; }
java
{ "resource": "" }
q7244
FluoConfiguration.verifyApplicationName
train
private void verifyApplicationName(String name) { if (name == null) { throw new IllegalArgumentException("Application name cannot be null"); } if (name.isEmpty()) { throw new IllegalArgumentException("Application name length must be > 0"); } String reason = null; char[] chars = name.toCharArray(); char c; for (int i = 0; i < chars.length; i++) { c = chars[i]; if (c == 0) { reason = "null character not allowed @" + i; break; } else if (c == '/' || c == '.' || c == ':') { reason = "invalid character '" + c + "'"; break; } else if (c > '\u0000' && c <= '\u001f' || c >= '\u007f' && c <= '\u009F' || c >= '\ud800' && c <= '\uf8ff' || c >= '\ufff0' && c <= '\uffff') { reason = "invalid character @" + i; break; } } if (reason != null) { throw new IllegalArgumentException( "Invalid application name \"" + name + "\" caused by " + reason); } }
java
{ "resource": "" }
q7245
FluoConfiguration.addObservers
train
@Deprecated public FluoConfiguration addObservers(Iterable<ObserverSpecification> observers) { int next = getNextObserverId(); for (ObserverSpecification oconf : observers) { addObserver(oconf, next++); } return this; }
java
{ "resource": "" }
q7246
FluoConfiguration.clearObservers
train
@Deprecated public FluoConfiguration clearObservers() { Iterator<String> iter1 = getKeys(OBSERVER_PREFIX.substring(0, OBSERVER_PREFIX.length() - 1)); while (iter1.hasNext()) { String key = iter1.next(); clearProperty(key); } return this; }
java
{ "resource": "" }
q7247
FluoConfiguration.print
train
public void print() { Iterator<String> iter = getKeys(); while (iter.hasNext()) { String key = iter.next(); log.info(key + " = " + getRawString(key)); } }
java
{ "resource": "" }
q7248
FluoConfiguration.hasRequiredClientProps
train
public boolean hasRequiredClientProps() { boolean valid = true; valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP); valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP); valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP); valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP); return valid; }
java
{ "resource": "" }
q7249
FluoConfiguration.hasRequiredAdminProps
train
public boolean hasRequiredAdminProps() { boolean valid = true; valid &= hasRequiredClientProps(); valid &= verifyStringPropSet(ACCUMULO_TABLE_PROP, ADMIN_ACCUMULO_TABLE_PROP); return valid; }
java
{ "resource": "" }
q7250
FluoConfiguration.hasRequiredMiniFluoProps
train
public boolean hasRequiredMiniFluoProps() { boolean valid = true; if (getMiniStartAccumulo()) { // ensure that client properties are not set since we are using MiniAccumulo valid &= verifyStringPropNotSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP); valid &= verifyStringPropNotSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP); valid &= verifyStringPropNotSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP); valid &= verifyStringPropNotSet(ACCUMULO_ZOOKEEPERS_PROP, CLIENT_ACCUMULO_ZOOKEEPERS_PROP); valid &= verifyStringPropNotSet(CONNECTION_ZOOKEEPERS_PROP, CLIENT_ZOOKEEPER_CONNECT_PROP); if (valid == false) { log.error("Client properties should not be set in your configuration if MiniFluo is " + "configured to start its own accumulo (indicated by fluo.mini.start.accumulo being " + "set to true)"); } } else { valid &= hasRequiredClientProps(); valid &= hasRequiredAdminProps(); valid &= hasRequiredOracleProps(); valid &= hasRequiredWorkerProps(); } return valid; }
java
{ "resource": "" }
q7251
FluoConfiguration.getClientConfiguration
train
public SimpleConfiguration getClientConfiguration() { SimpleConfiguration clientConfig = new SimpleConfiguration(); Iterator<String> iter = getKeys(); while (iter.hasNext()) { String key = iter.next(); if (key.startsWith(CONNECTION_PREFIX) || key.startsWith(ACCUMULO_PREFIX) || key.startsWith(CLIENT_PREFIX)) { clientConfig.setProperty(key, getRawString(key)); } } return clientConfig; }
java
{ "resource": "" }
q7252
FluoConfiguration.setDefaultConfiguration
train
public static void setDefaultConfiguration(SimpleConfiguration config) { config.setProperty(CONNECTION_ZOOKEEPERS_PROP, CONNECTION_ZOOKEEPERS_DEFAULT); config.setProperty(CONNECTION_ZOOKEEPER_TIMEOUT_PROP, CONNECTION_ZOOKEEPER_TIMEOUT_DEFAULT); config.setProperty(DFS_ROOT_PROP, DFS_ROOT_DEFAULT); config.setProperty(ACCUMULO_ZOOKEEPERS_PROP, ACCUMULO_ZOOKEEPERS_DEFAULT); config.setProperty(WORKER_NUM_THREADS_PROP, WORKER_NUM_THREADS_DEFAULT); config.setProperty(TRANSACTION_ROLLBACK_TIME_PROP, TRANSACTION_ROLLBACK_TIME_DEFAULT); config.setProperty(LOADER_NUM_THREADS_PROP, LOADER_NUM_THREADS_DEFAULT); config.setProperty(LOADER_QUEUE_SIZE_PROP, LOADER_QUEUE_SIZE_DEFAULT); config.setProperty(MINI_START_ACCUMULO_PROP, MINI_START_ACCUMULO_DEFAULT); config.setProperty(MINI_DATA_DIR_PROP, MINI_DATA_DIR_DEFAULT); }
java
{ "resource": "" }
q7253
FluoOutputFormat.configure
train
public static void configure(Job conf, SimpleConfiguration props) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); props.save(baos); conf.getConfiguration().set(PROPS_CONF_KEY, new String(baos.toByteArray(), StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q7254
TimestampTracker.allocateTimestamp
train
public Stamp allocateTimestamp() { synchronized (this) { Preconditions.checkState(!closed, "tracker closed "); if (node == null) { Preconditions.checkState(allocationsInProgress == 0, "expected allocationsInProgress == 0 when node == null"); Preconditions.checkState(!updatingZk, "unexpected concurrent ZK update"); createZkNode(getTimestamp().getTxTimestamp()); } allocationsInProgress++; } try { Stamp ts = getTimestamp(); synchronized (this) { timestamps.add(ts.getTxTimestamp()); } return ts; } catch (RuntimeException re) { synchronized (this) { allocationsInProgress--; } throw re; } }
java
{ "resource": "" }
q7255
FluoWait.waitTillNoNotifications
train
private static boolean waitTillNoNotifications(Environment env, TableRange range) throws TableNotFoundException { boolean sawNotifications = false; long retryTime = MIN_SLEEP_MS; log.debug("Scanning tablet {} for notifications", range); long start = System.currentTimeMillis(); while (hasNotifications(env, range)) { sawNotifications = true; long sleepTime = Math.max(System.currentTimeMillis() - start, retryTime); log.debug("Tablet {} had notfications, will rescan in {}ms", range, sleepTime); UtilWaitThread.sleep(sleepTime); retryTime = Math.min(MAX_SLEEP_MS, (long) (retryTime * 1.5)); start = System.currentTimeMillis(); } return sawNotifications; }
java
{ "resource": "" }
q7256
FluoWait.waitUntilFinished
train
private static void waitUntilFinished(FluoConfiguration config) { try (Environment env = new Environment(config)) { List<TableRange> ranges = getRanges(env); outer: while (true) { long ts1 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp(); for (TableRange range : ranges) { boolean sawNotifications = waitTillNoNotifications(env, range); if (sawNotifications) { ranges = getRanges(env); // This range had notifications. Processing those notifications may have created // notifications in previously scanned ranges, so start over. continue outer; } } long ts2 = env.getSharedResources().getOracleClient().getStamp().getTxTimestamp(); // Check to ensure the Oracle issued no timestamps during the scan for notifications. if (ts2 - ts1 == 1) { break; } } } catch (Exception e) { log.error("An exception was thrown -", e); System.exit(-1); } }
java
{ "resource": "" }
q7257
SpanUtil.toRange
train
public static Range toRange(Span span) { return new Range(toKey(span.getStart()), span.isStartInclusive(), toKey(span.getEnd()), span.isEndInclusive()); }
java
{ "resource": "" }
q7258
SpanUtil.toKey
train
public static Key toKey(RowColumn rc) { if ((rc == null) || (rc.getRow().equals(Bytes.EMPTY))) { return null; } Text row = ByteUtil.toText(rc.getRow()); if ((rc.getColumn().equals(Column.EMPTY)) || !rc.getColumn().isFamilySet()) { return new Key(row); } Text cf = ByteUtil.toText(rc.getColumn().getFamily()); if (!rc.getColumn().isQualifierSet()) { return new Key(row, cf); } Text cq = ByteUtil.toText(rc.getColumn().getQualifier()); if (!rc.getColumn().isVisibilitySet()) { return new Key(row, cf, cq); } Text cv = ByteUtil.toText(rc.getColumn().getVisibility()); return new Key(row, cf, cq, cv); }
java
{ "resource": "" }
q7259
SpanUtil.toSpan
train
public static Span toSpan(Range range) { return new Span(toRowColumn(range.getStartKey()), range.isStartKeyInclusive(), toRowColumn(range.getEndKey()), range.isEndKeyInclusive()); }
java
{ "resource": "" }
q7260
SpanUtil.toRowColumn
train
public static RowColumn toRowColumn(Key key) { if (key == null) { return RowColumn.EMPTY; } if ((key.getRow() == null) || key.getRow().getLength() == 0) { return RowColumn.EMPTY; } Bytes row = ByteUtil.toBytes(key.getRow()); if ((key.getColumnFamily() == null) || key.getColumnFamily().getLength() == 0) { return new RowColumn(row); } Bytes cf = ByteUtil.toBytes(key.getColumnFamily()); if ((key.getColumnQualifier() == null) || key.getColumnQualifier().getLength() == 0) { return new RowColumn(row, new Column(cf)); } Bytes cq = ByteUtil.toBytes(key.getColumnQualifier()); if ((key.getColumnVisibility() == null) || key.getColumnVisibility().getLength() == 0) { return new RowColumn(row, new Column(cf, cq)); } Bytes cv = ByteUtil.toBytes(key.getColumnVisibility()); return new RowColumn(row, new Column(cf, cq, cv)); }
java
{ "resource": "" }
q7261
FluoKeyValueGenerator.set
train
public FluoKeyValueGenerator set(RowColumnValue rcv) { setRow(rcv.getRow()); setColumn(rcv.getColumn()); setValue(rcv.getValue()); return this; }
java
{ "resource": "" }
q7262
FluoKeyValueGenerator.getKeyValues
train
public FluoKeyValue[] getKeyValues() { FluoKeyValue kv = keyVals[0]; kv.setKey(new Key(row, fam, qual, vis, ColumnType.WRITE.encode(1))); kv.getValue().set(WriteValue.encode(0, false, false)); kv = keyVals[1]; kv.setKey(new Key(row, fam, qual, vis, ColumnType.DATA.encode(0))); kv.getValue().set(val); return keyVals; }
java
{ "resource": "" }
q7263
RowColumn.following
train
public RowColumn following() { if (row.equals(Bytes.EMPTY)) { return RowColumn.EMPTY; } else if (col.equals(Column.EMPTY)) { return new RowColumn(followingBytes(row)); } else if (!col.isQualifierSet()) { return new RowColumn(row, new Column(followingBytes(col.getFamily()))); } else if (!col.isVisibilitySet()) { return new RowColumn(row, new Column(col.getFamily(), followingBytes(col.getQualifier()))); } else { return new RowColumn(row, new Column(col.getFamily(), col.getQualifier(), followingBytes(col.getVisibility()))); } }
java
{ "resource": "" }
q7264
FluoMutationGenerator.put
train
public FluoMutationGenerator put(Column col, CharSequence value) { return put(col, value.toString().getBytes(StandardCharsets.UTF_8)); }
java
{ "resource": "" }
q7265
CuratorUtil.newAppCurator
train
public static CuratorFramework newAppCurator(FluoConfiguration config) { return newCurator(config.getAppZookeepers(), config.getZookeeperTimeout(), config.getZookeeperSecret()); }
java
{ "resource": "" }
q7266
CuratorUtil.newFluoCurator
train
public static CuratorFramework newFluoCurator(FluoConfiguration config) { return newCurator(config.getInstanceZookeepers(), config.getZookeeperTimeout(), config.getZookeeperSecret()); }
java
{ "resource": "" }
q7267
CuratorUtil.newCurator
train
public static CuratorFramework newCurator(String zookeepers, int timeout, String secret) { final ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10); if (secret.isEmpty()) { return CuratorFrameworkFactory.newClient(zookeepers, timeout, timeout, retry); } else { return CuratorFrameworkFactory.builder().connectString(zookeepers) .connectionTimeoutMs(timeout).sessionTimeoutMs(timeout).retryPolicy(retry) .authorization("digest", ("fluo:" + secret).getBytes(StandardCharsets.UTF_8)) .aclProvider(new ACLProvider() { @Override public List<ACL> getDefaultAcl() { return CREATOR_ALL_ACL; } @Override public List<ACL> getAclForPath(String path) { switch (path) { case ZookeeperPath.ORACLE_GC_TIMESTAMP: // The garbage collection iterator running in Accumulo tservers needs to read this // value w/o authenticating. return PUBLICLY_READABLE_ACL; default: return CREATOR_ALL_ACL; } } }).build(); } }
java
{ "resource": "" }
q7268
CuratorUtil.startAndWait
train
public static void startAndWait(PersistentNode node, int maxWaitSec) { node.start(); int waitTime = 0; try { while (node.waitForInitialCreate(1, TimeUnit.SECONDS) == false) { waitTime += 1; log.info("Waited " + waitTime + " sec for ephemeral node to be created"); if (waitTime > maxWaitSec) { throw new IllegalStateException("Failed to create ephemeral node"); } } } catch (InterruptedException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q7269
CuratorUtil.startAppIdWatcher
train
public static NodeCache startAppIdWatcher(Environment env) { try { CuratorFramework curator = env.getSharedResources().getCurator(); byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID); if (uuidBytes == null) { Halt.halt("Fluo Application UUID not found"); throw new RuntimeException(); // make findbugs happy } final String uuid = new String(uuidBytes, StandardCharsets.UTF_8); final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID); nodeCache.getListenable().addListener(() -> { ChildData node = nodeCache.getCurrentData(); if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) { Halt.halt("Fluo Application UUID has changed or disappeared"); } }); nodeCache.start(); return nodeCache; } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q7270
Environment.readZookeeperConfig
train
private void readZookeeperConfig() { try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) { curator.start(); accumuloInstance = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME), StandardCharsets.UTF_8); accumuloInstanceID = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID), StandardCharsets.UTF_8); fluoApplicationID = new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID), StandardCharsets.UTF_8); table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE), StandardCharsets.UTF_8); observers = ObserverUtil.load(curator); config = FluoAdminImpl.mergeZookeeperConfig(config); // make sure not to include config passed to env, only want config from zookeeper appConfig = config.getAppConfiguration(); } catch (Exception e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q7271
TransactorNode.close
train
@Override public void close() { status = TrStatus.CLOSED; try { node.close(); } catch (IOException e) { log.error("Failed to close ephemeral node"); throw new IllegalStateException(e); } }
java
{ "resource": "" }
q7272
BeanInfoIntrospector.expand
train
private static Map<String, Set<String>> expand(Map<String, Set<String>> viewToPropNames) { Set<String> baseProps = viewToPropNames.get(PropertyView.BASE_VIEW); if (baseProps == null) { baseProps = ImmutableSet.of(); } if (!SquigglyConfig.isFilterImplicitlyIncludeBaseFieldsInView()) { // make an exception for full view Set<String> fullView = viewToPropNames.get(PropertyView.FULL_VIEW); if (fullView != null) { fullView.addAll(baseProps); } return viewToPropNames; } for (Map.Entry<String, Set<String>> entry : viewToPropNames.entrySet()) { String viewName = entry.getKey(); Set<String> propNames = entry.getValue(); if (!PropertyView.BASE_VIEW.equals(viewName)) { propNames.addAll(baseProps); } } return viewToPropNames; }
java
{ "resource": "" }
q7273
SquigglyParser.parse
train
public List<SquigglyNode> parse(String filter) { filter = StringUtils.trim(filter); if (StringUtils.isEmpty(filter)) { return Collections.emptyList(); } // get it from the cache if we can List<SquigglyNode> cachedNodes = CACHE.getIfPresent(filter); if (cachedNodes != null) { return cachedNodes; } SquigglyExpressionLexer lexer = ThrowingErrorListener.overwrite(new SquigglyExpressionLexer(new ANTLRInputStream(filter))); SquigglyExpressionParser parser = ThrowingErrorListener.overwrite(new SquigglyExpressionParser(new CommonTokenStream(lexer))); Visitor visitor = new Visitor(); List<SquigglyNode> nodes = Collections.unmodifiableList(visitor.visit(parser.parse())); CACHE.put(filter, nodes); return nodes; }
java
{ "resource": "" }
q7274
SquigglyUtils.collectify
train
public static <E> Collection<E> collectify(ObjectMapper mapper, Object source, Class<? extends Collection> targetCollectionType, Class<E> targetElementType) { CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(targetCollectionType, targetElementType); return objectify(mapper, convertToCollection(source), collectionType); }
java
{ "resource": "" }
q7275
SquigglyUtils.listify
train
public static List<Map<String, Object>> listify(ObjectMapper mapper, Object source) { return (List<Map<String, Object>>) collectify(mapper, source, List.class); }
java
{ "resource": "" }
q7276
SquigglyUtils.listify
train
public static <E> List<E> listify(ObjectMapper mapper, Object source, Class<E> targetElementType) { return (List<E>) collectify(mapper, source, List.class, targetElementType); }
java
{ "resource": "" }
q7277
SquigglyUtils.objectify
train
public static Object objectify(ObjectMapper mapper, Object source) { return objectify(mapper, source, Object.class); }
java
{ "resource": "" }
q7278
SquigglyUtils.objectify
train
public static <T> T objectify(ObjectMapper mapper, Object source, JavaType targetType) { try { return mapper.readValue(mapper.writeValueAsBytes(source), targetType); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q7279
SquigglyUtils.setify
train
public static Set<Map<String, Object>> setify(ObjectMapper mapper, Object source) { return (Set<Map<String, Object>>) collectify(mapper, source, Set.class); }
java
{ "resource": "" }
q7280
SquigglyUtils.setify
train
public static <E> Set<E> setify(ObjectMapper mapper, Object source, Class<E> targetElementType) { return (Set<E>) collectify(mapper, source, Set.class, targetElementType); }
java
{ "resource": "" }
q7281
SquigglyUtils.stringify
train
public static String stringify(ObjectMapper mapper, Object object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e); } }
java
{ "resource": "" }
q7282
SquigglyPropertyFilter.getPath
train
private Path getPath(PropertyWriter writer, JsonStreamContext sc) { LinkedList<PathElement> elements = new LinkedList<>(); if (sc != null) { elements.add(new PathElement(writer.getName(), sc.getCurrentValue())); sc = sc.getParent(); } while (sc != null) { if (sc.getCurrentName() != null && sc.getCurrentValue() != null) { elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue())); } sc = sc.getParent(); } return new Path(elements); }
java
{ "resource": "" }
q7283
SquigglyPropertyFilter.pathMatches
train
private boolean pathMatches(Path path, SquigglyContext context) { List<SquigglyNode> nodes = context.getNodes(); Set<String> viewStack = null; SquigglyNode viewNode = null; int pathSize = path.getElements().size(); int lastIdx = pathSize - 1; for (int i = 0; i < pathSize; i++) { PathElement element = path.getElements().get(i); if (viewNode != null && !viewNode.isSquiggly()) { Class beanClass = element.getBeanClass(); if (beanClass != null && !Map.class.isAssignableFrom(beanClass)) { Set<String> propertyNames = getPropertyNamesFromViewStack(element, viewStack); if (!propertyNames.contains(element.getName())) { return false; } } } else if (nodes.isEmpty()) { return false; } else { SquigglyNode match = findBestSimpleNode(element, nodes); if (match == null) { match = findBestViewNode(element, nodes); if (match != null) { viewNode = match; viewStack = addToViewStack(viewStack, viewNode); } } else if (match.isAnyShallow()) { viewNode = match; } else if (match.isAnyDeep()) { return true; } if (match == null) { if (isJsonUnwrapped(element)) { continue; } return false; } if (match.isNegated()) { return false; } nodes = match.getChildren(); if (i < lastIdx && nodes.isEmpty() && !match.isEmptyNested() && SquigglyConfig.isFilterImplicitlyIncludeBaseFields()) { nodes = BASE_VIEW_NODES; } } } return true; }
java
{ "resource": "" }
q7284
SquigglyMetrics.asMap
train
public static SortedMap<String, Object> asMap() { SortedMap<String, Object> metrics = Maps.newTreeMap(); METRICS_SOURCE.applyMetrics(metrics); return metrics; }
java
{ "resource": "" }
q7285
UnsafeUtil.newDirectByteBuffer
train
public static ByteBuffer newDirectByteBuffer(long addr, int size, Object att) { dbbCC.setAccessible(true); Object b = null; try { b = dbbCC.newInstance(new Long(addr), new Integer(size), att); return ByteBuffer.class.cast(b); } catch(Exception e) { throw new IllegalStateException(String.format("Failed to create DirectByteBuffer: %s", e.getMessage())); } }
java
{ "resource": "" }
q7286
DefaultMemoryAllocator.releaseAll
train
public void releaseAll() { synchronized(this) { Object[] refSet = allocatedMemoryReferences.values().toArray(); if(refSet.length != 0) { logger.finer("Releasing allocated memory regions"); } for(Object ref : refSet) { release((MemoryReference) ref); } } }
java
{ "resource": "" }
q7287
LArrayLoader.md5sum
train
public static String md5sum(InputStream input) throws IOException { InputStream in = new BufferedInputStream(input); try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); DigestInputStream digestInputStream = new DigestInputStream(in, digest); while(digestInputStream.read() >= 0) { } OutputStream md5out = new ByteArrayOutputStream(); md5out.write(digest.digest()); return md5out.toString(); } catch(NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 algorithm is not available: " + e.getMessage()); } finally { in.close(); } }
java
{ "resource": "" }
q7288
LBufferAPI.fill
train
public void fill(long offset, long length, byte value) { unsafe.setMemory(address() + offset, length, value); }
java
{ "resource": "" }
q7289
LBufferAPI.copyTo
train
public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) { int cursor = destOffset; for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) { int bbSize = bb.remaining(); if ((cursor + bbSize) > destArray.length) throw new ArrayIndexOutOfBoundsException(String.format("cursor + bbSize = %,d", cursor + bbSize)); bb.get(destArray, cursor, bbSize); cursor += bbSize; } }
java
{ "resource": "" }
q7290
LBufferAPI.copyTo
train
public void copyTo(long srcOffset, LBufferAPI dest, long destOffset, long size) { unsafe.copyMemory(address() + srcOffset, dest.address() + destOffset, size); }
java
{ "resource": "" }
q7291
LBufferAPI.slice
train
public LBuffer slice(long from, long to) { if(from > to) throw new IllegalArgumentException(String.format("invalid range %,d to %,d", from, to)); long size = to - from; LBuffer b = new LBuffer(size); copyTo(from, b, 0, size); return b; }
java
{ "resource": "" }
q7292
LBufferAPI.toArray
train
public byte[] toArray() { if (size() > Integer.MAX_VALUE) throw new IllegalStateException("Cannot create byte array of more than 2GB"); int len = (int) size(); ByteBuffer bb = toDirectByteBuffer(0L, len); byte[] b = new byte[len]; // Copy data to the array bb.get(b, 0, len); return b; }
java
{ "resource": "" }
q7293
LBufferAPI.writeTo
train
public void writeTo(WritableByteChannel channel) throws IOException { for (ByteBuffer buffer : toDirectByteBuffers()) { channel.write(buffer); } }
java
{ "resource": "" }
q7294
LBufferAPI.writeTo
train
public void writeTo(File file) throws IOException { FileChannel channel = new FileOutputStream(file).getChannel(); try { writeTo(channel); } finally { channel.close(); } }
java
{ "resource": "" }
q7295
LBufferAPI.readFrom
train
public int readFrom(byte[] src, int srcOffset, long destOffset, int length) { int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length)); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src, srcOffset, readLen); return readLen; }
java
{ "resource": "" }
q7296
LBufferAPI.readFrom
train
public int readFrom(ByteBuffer src, long destOffset) { if (src.remaining() + destOffset >= size()) throw new BufferOverflowException(); int readLen = src.remaining(); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src); return readLen; }
java
{ "resource": "" }
q7297
LBufferAPI.loadFrom
train
public static LBuffer loadFrom(File file) throws IOException { FileChannel fin = new FileInputStream(file).getChannel(); long fileSize = fin.size(); if (fileSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Cannot load from file more than 2GB: " + file); LBuffer b = new LBuffer((int) fileSize); long pos = 0L; WritableChannelWrap ch = new WritableChannelWrap(b); while (pos < fileSize) { pos += fin.transferTo(0, fileSize, ch); } return b; }
java
{ "resource": "" }
q7298
LBufferAPI.toDirectByteBuffers
train
public ByteBuffer[] toDirectByteBuffers(long offset, long size) { long pos = offset; long blockSize = Integer.MAX_VALUE; long limit = offset + size; int numBuffers = (int) ((size + (blockSize - 1)) / blockSize); ByteBuffer[] result = new ByteBuffer[numBuffers]; int index = 0; while (pos < limit) { long blockLength = Math.min(limit - pos, blockSize); result[index++] = UnsafeUtil.newDirectByteBuffer(address() + pos, (int) blockLength, this) .order(ByteOrder.nativeOrder()); pos += blockLength; } return result; }
java
{ "resource": "" }
q7299
WrappingHint.getWrappingHint
train
public String getWrappingHint(String fieldName) { if (isEmpty()) { return ""; } return String.format(" You can use this expression: %s(%s(%s))", formatMethod(wrappingMethodOwnerName, wrappingMethodName, ""), formatMethod(copyMethodOwnerName, copyMethodName, copyTypeParameterName), fieldName); }
java
{ "resource": "" }