code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
protected void setNextValue(final long pValue, final int pLength, final int pMaxSize) {
long value = pValue;
// Set to max value if pValue cannot be stored on pLength bits.
long bitMax = (long) Math.pow(2, Math.min(pLength, pMaxSize));
if (pValue > bitMax) {
value = bitMax - 1;
}
// size to wrote
... | java |
public void setNextInteger(final int pValue, final int pLength) {
if (pLength > Integer.SIZE) {
throw new IllegalArgumentException("Integer overflow with length > 32");
}
setNextValue(pValue, pLength, Integer.SIZE - 1);
} | java |
public void setNextString(final String pValue, final int pLength, final boolean pPaddedBefore) {
setNextByte(pValue.getBytes(Charset.defaultCharset()), pLength, pPaddedBefore);
} | java |
public void setResult(R result) {
try {
lock.lock();
this.result = result;
notifyHaveResult();
}
finally {
lock.unlock();
}
} | java |
public void failure(Throwable failure) {
try {
lock.lock();
this.failure = failure;
notifyHaveResult();
}
finally {
lock.unlock();
}
} | java |
void clean(QNode pred, QNode s) {
Thread w = s.waiter;
if (w != null) { // Wake up thread
s.waiter = null;
if (w != Thread.currentThread()) {
LockSupport.unpark(w);
}
}
/*
* At any given time, exactly one node on li... | java |
private QNode reclean() {
/*
* cleanMe is, or at one time was, predecessor of cancelled
* node s that was the tail so could not be unspliced. If s
* is no longer the tail, try to unsplice if necessary and
* make cleanMe slot available. This differs from similar
* c... | java |
static StorageCache initCache(Configuration configuration) {
if (configuration.getBoolean(Configuration.CACHE_ENABLED) && configuration.getLong(Configuration.CACHE_BYTES) > 0) {
return new StorageCache(configuration);
} else {
return new DisabledCache();
}
} | java |
public synchronized void registerSerializer(Serializer serializer) {
Class objClass = getSerializerType(serializer);
if (!serializers.containsKey(objClass)) {
int index = COUNTER.getAndIncrement();
serializers.put(objClass, new SerializerWrapper(index, serializer));
if (serializersArray.length... | java |
static void serialize(DataOutput out, Serializers serializers)
throws IOException {
StringBuilder msg = new StringBuilder(String.format("Serialize %d serializer classes:", serializers.serializers.values().size()));
int size = serializers.serializers.values().size();
out.writeInt(size);
if (size >... | java |
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
// Init
COUNTER = new AtomicInteger();
serializers = new HashMap<Class, SerializerWrapper>();
serializersArray = new Serializer[0];
deserialize(in, this);
} | java |
static void deserialize(DataInput in, Serializers serializers)
throws IOException, ClassNotFoundException {
int size = in.readInt();
if (size > 0) {
StringBuilder msg = new StringBuilder(String.format("Deserialize %d serializer classes:", size));
if (serializers.serializersArray.length < size... | java |
Serializer getSerializer(int index) {
if (index >= serializersArray.length) {
throw new IllegalArgumentException(String.format("The serializer can't be found at index %d", index));
}
return serializersArray[index];
} | java |
private static Class<?> getSerializerType(Object instance) {
Type type = instance.getClass().getGenericInterfaces()[0];
if (type instanceof ParameterizedType) {
Class<?> cls = null;
Type clsType = ((ParameterizedType) type).getActualTypeArguments()[0];
if (clsType instanceof GenericArrayType)... | java |
public byte[] get(byte[] key)
throws IOException {
int keyLength = key.length;
if (keyLength >= slots.length || keyCounts[keyLength] == 0) {
return null;
}
long hash = (long) hashUtils.hash(key);
int numSlots = slots[keyLength];
int slotSize = slotSizes[keyLength];
int indexOffse... | java |
public void close()
throws IOException {
channel.close();
mappedFile.close();
indexBuffer = null;
dataBuffers = null;
mappedFile = null;
channel = null;
System.gc();
} | java |
private byte[] getMMapBytes(long offset)
throws IOException {
//Read the first 4 bytes to get the size of the data
ByteBuffer buf = getDataBuffer(offset);
int maxLen = (int) Math.min(5, dataSize - offset);
int size;
if (buf.remaining() >= maxLen) {
//Continuous read
int pos = buf.... | java |
private byte[] getDiskBytes(long offset)
throws IOException {
mappedFile.seek(dataOffset + offset);
//Get size of data
int size = LongPacker.unpackInt(mappedFile);
//Create output bytes
byte[] res = new byte[size];
//Read data
if (mappedFile.read(res) == -1) {
throw new EOFExc... | java |
private ByteBuffer getDataBuffer(long index) {
ByteBuffer buf = dataBuffers[(int) (index / segmentSize)];
buf.position((int) (index % segmentSize));
return buf;
} | java |
private void ensureAvail(int n) {
if (pos + n >= buf.length) {
int newSize = Math.max(pos + n, buf.length * 2);
buf = Arrays.copyOf(buf, newSize);
}
} | java |
static public int unpackInt(DataInput is)
throws IOException {
for (int offset = 0, result = 0; offset < 32; offset += 7) {
int b = is.readUnsignedByte();
result |= (b & 0x7F) << offset;
if ((b & 0x80) == 0) {
return result;
}
}
throw new Error("Malformed integer.");
... | java |
static public int unpackInt(ByteBuffer bb)
throws IOException {
for (int offset = 0, result = 0; offset < 32; offset += 7) {
int b = bb.get() & 0xffff;
result |= (b & 0x7F) << offset;
if ((b & 0x80) == 0) {
return result;
}
}
throw new Error("Malformed integer.");
} | java |
private void mergeFiles(List<File> inputFiles, OutputStream outputStream)
throws IOException {
long startTime = System.nanoTime();
//Merge files
for (File f : inputFiles) {
if (f.exists()) {
FileInputStream fileInputStream = new FileInputStream(f);
BufferedInputStream bufferedIn... | java |
private DataOutputStream getDataStream(int keyLength)
throws IOException {
// Resize array if necessary
if (dataStreams.length <= keyLength) {
dataStreams = Arrays.copyOf(dataStreams, keyLength + 1);
dataFiles = Arrays.copyOf(dataFiles, keyLength + 1);
}
DataOutputStream dos = dataStr... | java |
private DataOutputStream getIndexStream(int keyLength)
throws IOException {
// Resize array if necessary
if (indexStreams.length <= keyLength) {
indexStreams = Arrays.copyOf(indexStreams, keyLength + 1);
indexFiles = Arrays.copyOf(indexFiles, keyLength + 1);
keyCounts = Arrays.copyOf(key... | java |
static int execute(Arg arguments, PrintStream stream, PrintStream errorStream) {
if (arguments == null) {
return 2;
}
if (arguments.checkBcryptHash != null) { // verify mode
BCrypt.Result result = BCrypt.verifyer().verify(arguments.password, arguments.checkBcryptHash);
... | java |
public static Hasher with(Version version, SecureRandom secureRandom, LongPasswordStrategy longPasswordStrategy) {
return new Hasher(version, secureRandom, longPasswordStrategy);
} | java |
private static int streamToWord(byte[] data, int[] offp) {
int i;
int word = 0;
int off = offp[0];
for (i = 0; i < 4; i++) {
word = (word << 8) | (data[off] & 0xff);
off = (off + 1) % data.length;
}
offp[0] = off;
return word;
} | java |
private void encipher(int[] P, int[] S, int[] lr, int off) {
int i, n, l = lr[off], r = lr[off + 1];
l ^= P[0];
for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2; ) {
// Feistel substitution on left word
n = S[(l >> 24) & 0xff];
n += S[0x100 | ((l >> 16) & 0xff)];
... | java |
protected void expand(int min_size_needed) {
LogEntry[] new_entries=new LogEntry[Math.max(entries.length + INCR, entries.length + min_size_needed)];
System.arraycopy(entries, 0, new_entries, 0, entries.length);
entries=new_entries;
} | java |
public V remove(K key) throws Exception {
return invoke(REMOVE, key, null, true);
} | java |
public void printMetadata() throws Exception {
log.info("-----------------");
log.info("RAFT Log Metadata");
log.info("-----------------");
byte[] firstAppendedBytes = db.get(FIRSTAPPENDED);
log.info("First Appended: %d", fromByteArrayToInt(firstAppendedBytes));
byte[] ... | java |
public Counter getOrCreateCounter(String name, long initial_value) throws Exception {
Object existing_value=allow_dirty_reads? _get(name) : invoke(Command.get, name, false);
if(existing_value != null)
counters.put(name, (Long)existing_value);
else {
Object retval=invoke(C... | java |
protected int getFirstIndexOfConflictingTerm(int start_index, int conflicting_term) {
Log log=raft.log_impl;
int first=Math.max(1, log.firstAppended()), last=log.lastAppended();
int retval=Math.min(start_index, last);
for(int i=retval; i >= first; i--) {
LogEntry entry=log.ge... | java |
public static boolean isNumber(JsonNode node, boolean isTypeLoose) {
if (node.isNumber()) {
return true;
} else if (isTypeLoose) {
if (TypeFactory.getValueNodeType(node) == JsonType.STRING) {
return isNumeric(node.textValue());
}
}
retu... | java |
private boolean isTypeLooseContainsInEnum(JsonNode node) {
if (TypeFactory.getValueNodeType(node) == JsonType.STRING) {
String nodeText = node.textValue();
for (JsonNode n : nodes) {
String value = n.asText();
if (value != null && value.equals(nodeText)) {... | java |
public Writer sheet(String sheetName) {
if (StringUtil.isEmpty(sheetName)) {
throw new IllegalArgumentException("sheet cannot be empty");
}
this.sheetName = sheetName;
return this;
} | java |
public Writer withTemplate(File template) {
if (null == template || !template.exists()) {
throw new IllegalArgumentException("template file not exist");
}
this.template = template;
return this;
} | java |
public void to(File file) throws WriterException {
try {
this.to(new FileOutputStream(file));
} catch (FileNotFoundException e) {
throw new WriterException(e);
}
} | java |
public void to(OutputStream outputStream) throws WriterException {
if (!withRaw && (null == rows || rows.isEmpty())) {
throw new WriterException("write rows cannot be empty, please check it");
}
if (excelType == ExcelType.XLSX) {
new WriterWith2007(outputStream).writeShee... | java |
public Reader<T> from(File fromFile) {
if (null == fromFile || !fromFile.exists()) {
throw new IllegalArgumentException("excel file must be exist");
}
this.fromFile = fromFile;
return this;
} | java |
public Reader<T> sheet(String sheetName) {
if (StringUtil.isEmpty(sheetName)) {
throw new IllegalArgumentException("sheet cannot be empty");
}
this.sheetName = sheetName;
return this;
} | java |
public Stream<T> asStream() {
if (modelType == null) {
throw new IllegalArgumentException("modelType can be not null");
}
if (fromFile == null && fromStream == null) {
throw new IllegalArgumentException("Excel source not is null");
}
if (fromFile != null... | java |
public List<T> asList() throws ReaderException {
Stream<T> stream = this.asStream();
return stream.collect(toList());
} | java |
private static void applyTypeface(ViewGroup viewGroup, TypefaceCollection typefaceCollection) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View childView = viewGroup.getChildAt(i);
if (childView instanceof ViewGroup) {
applyTypeface((ViewGroup) childView, typefaceCollection);
} else {
app... | java |
private static void applyForView(View view, TypefaceCollection typefaceCollection) {
if (view instanceof TextView) {
TextView textView = (TextView) view;
Typeface oldTypeface = textView.getTypeface();
final int style = oldTypeface == null ? Typeface.NORMAL : oldTypeface.getStyle();
textView.setTypeface(t... | java |
public PermissionProfile createPermissionProfile(String accountId, PermissionProfile permissionProfile) throws ApiException {
return createPermissionProfile(accountId, permissionProfile, null);
} | java |
public Brand getBrand(String accountId, String brandId) throws ApiException {
return getBrand(accountId, brandId, null);
} | java |
public PermissionProfile getPermissionProfile(String accountId, String permissionProfileId) throws ApiException {
return getPermissionProfile(accountId, permissionProfileId, null);
} | java |
public ConsumerDisclosure updateConsumerDisclosure(String accountId, String langCode, ConsumerDisclosure consumerDisclosure) throws ApiException {
return updateConsumerDisclosure(accountId, langCode, consumerDisclosure, null);
} | java |
public CustomFields updateCustomField(String accountId, String customFieldId, CustomField customField) throws ApiException {
return updateCustomField(accountId, customFieldId, customField, null);
} | java |
public PermissionProfile updatePermissionProfile(String accountId, String permissionProfileId, PermissionProfile permissionProfile) throws ApiException {
return updatePermissionProfile(accountId, permissionProfileId, permissionProfile, null);
} | java |
public CloudStorageProviders getProvider(String accountId, String userId, String serviceId) throws ApiException {
return getProvider(accountId, userId, serviceId, null);
} | java |
public ExternalFolder listFolders(String accountId, String userId, String serviceId) throws ApiException {
return listFolders(accountId, userId, serviceId, null);
} | java |
public BulkEnvelopeStatus get(String accountId, String batchId) throws ApiException {
return get(accountId, batchId, null);
} | java |
public BulkRecipientsResponse getRecipients(String accountId, String envelopeId, String recipientId) throws ApiException {
return getRecipients(accountId, envelopeId, recipientId, null);
} | java |
public ChunkedUploadResponse getChunkedUpload(String accountId, String chunkedUploadId) throws ApiException {
return getChunkedUpload(accountId, chunkedUploadId, null);
} | java |
public ConsumerDisclosure getConsumerDisclosureDefault(String accountId, String envelopeId, String recipientId) throws ApiException {
return getConsumerDisclosureDefault(accountId, envelopeId, recipientId, null);
} | java |
public byte[] getDocumentPageImage(String accountId, String envelopeId, String documentId, String pageNumber) throws ApiException {
return getDocumentPageImage(accountId, envelopeId, documentId, pageNumber, null);
} | java |
public Envelope getEnvelope(String accountId, String envelopeId) throws ApiException {
return getEnvelope(accountId, envelopeId, null);
} | java |
public Tabs listTabs(String accountId, String envelopeId, String recipientId) throws ApiException {
return listTabs(accountId, envelopeId, recipientId, null);
} | java |
public TemplateInformation listTemplates(String accountId, String envelopeId) throws ApiException {
return listTemplates(accountId, envelopeId, null);
} | java |
public TemplateInformation listTemplatesForDocument(String accountId, String envelopeId, String documentId) throws ApiException {
return listTemplatesForDocument(accountId, envelopeId, documentId, null);
} | java |
public ChunkedUploadResponse updateChunkedUpload(String accountId, String chunkedUploadId) throws ApiException {
return updateChunkedUpload(accountId, chunkedUploadId, null);
} | java |
public byte[] getCommentsTranscript(String accountId, String envelopeId) throws ApiException {
return getCommentsTranscript(accountId, envelopeId, null);
} | java |
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
for(Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
OAuth oauth = (OAuth) auth;
oauth.registerAccessTokenListener(accessTokenListener);
return;
}
}
} | java |
private String getXWWWFormUrlencodedParams(Map<String, Object> formParams) {
StringBuilder formParamBuilder = new StringBuilder();
for (Entry<String, Object> param : formParams.entrySet()) {
String valueStr = parameterToString(param.getValue());
try {
formParamBuilder.append(URLEncoder.enco... | java |
private <T> String serializeToCsv(T obj) {
if(obj == null) {
return "";
}
for (Method method: obj.getClass().getMethods()) {
if ("java.util.List".equals(method.getReturnType().getName())) {
try {
@SuppressWarnings("rawtypes")
java.util.List itemList = (java.util.List) me... | java |
public Recipients createRecipients(String accountId, String templateId, TemplateRecipients templateRecipients) throws ApiException {
return createRecipients(accountId, templateId, templateRecipients, null);
} | java |
public EnvelopeTemplate get(String accountId, String templateId) throws ApiException {
return get(accountId, templateId, null);
} | java |
public byte[] getDocumentPageImage(String accountId, String templateId, String documentId, String pageNumber) throws ApiException {
return getDocumentPageImage(accountId, templateId, documentId, pageNumber, null);
} | java |
public Recipients listRecipients(String accountId, String templateId) throws ApiException {
return listRecipients(accountId, templateId, null);
} | java |
public Tabs listTabs(String accountId, String templateId, String recipientId) throws ApiException {
return listTabs(accountId, templateId, recipientId, null);
} | java |
public EnvelopeDocument updateDocument(String accountId, String templateId, String documentId, EnvelopeDefinition envelopeDefinition) throws ApiException {
return updateDocument(accountId, templateId, documentId, envelopeDefinition, null);
} | java |
public TemplateDocumentsResult updateDocuments(String accountId, String templateId, EnvelopeDefinition envelopeDefinition) throws ApiException {
return updateDocuments(accountId, templateId, envelopeDefinition, null);
} | java |
public NotaryJournalList listNotaryJournals(NotaryApi.ListNotaryJournalsOptions options) throws ApiException {
Object localVarPostBody = "{}";
// create path and map variables
String localVarPath = "/v2/current_user/notary/journals".replaceAll("\\{format\\}","json");
// query params
java.util.... | java |
public static String calculatePath(String uri) {
if (!uri.startsWith("/")) {
return "/";
}
int idx = uri.lastIndexOf('/');
return uri.substring(0, idx + 1);
} | java |
public static boolean isDomainSuffix(String domain, String domainSuffix) {
if (domain.length() < domainSuffix.length()) {
return false;
}
if (domain.length() == domainSuffix.length()) {
return domain.equals(domainSuffix);
}
return domain.endsWith(domainSu... | java |
public static boolean match(Cookie cookie, String protocol, String host, String path) {
if (cookie.secure() && !protocol.equalsIgnoreCase("https")) {
return false;
}
// check domain
if (isIP(host) || cookie.hostOnly()) {
if (!host.equals(cookie.domain())) {
... | java |
@Nullable
public static Cookie parseCookie(String cookieStr, String host, String defaultPath) {
String[] items = cookieStr.split(";");
Parameter<String> param = parseCookieNameValue(items[0]);
if (param == null) {
return null;
}
String domain = "";
String... | java |
private static String normalizeDomain(String value) {
if (value.startsWith(".")) {
return value.substring(1);
}
return value.toLowerCase();
} | java |
public static Proxy httpProxy(String host, int port) {
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Objects.requireNonNull(host), port));
} | java |
public static Proxy socksProxy(String host, int port) {
return new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(Objects.requireNonNull(host), port));
} | java |
public static RequestBuilder newRequest(String method, String url) {
return new RequestBuilder().method(method).url(url);
} | java |
@SafeVarargs
public final RequestBuilder headers(Map.Entry<String, ?>... headers) {
headers(Lists.of(headers));
return this;
} | java |
@SafeVarargs
public final RequestBuilder cookies(Map.Entry<String, ?>... cookies) {
cookies(Lists.of(cookies));
return this;
} | java |
@SafeVarargs
public final RequestBuilder params(Map.Entry<String, ?>... params) {
this.params = Lists.of(params);
return this;
} | java |
public RawResponse send() {
Request request = build();
RequestExecutorFactory factory = RequestExecutorFactory.getInstance();
HttpExecutor executor = factory.getHttpExecutor();
return new InterceptorChain(interceptors, executor).proceed(request);
} | java |
public Part<T> contentType(String contentType) {
requireNonNull(contentType);
return new Part<>(name, fileName, body, contentType, charset, partWriter);
} | java |
public Part<T> charset(Charset charset) {
requireNonNull(charset);
return new Part<>(name, fileName, body, contentType, charset, partWriter);
} | java |
public static String encodeForm(Parameter<String> query, Charset charset) {
try {
return URLEncoder.encode(query.name(), charset.name()) + "=" + URLEncoder.encode(query.value(),
charset.name());
} catch (UnsupportedEncodingException e) {
// should not happen
... | java |
public static String encodeForms(Collection<? extends Parameter<String>> queries, Charset charset) {
StringBuilder sb = new StringBuilder();
try {
for (Parameter<String> query : queries) {
sb.append(URLEncoder.encode(query.name(), charset.name()));
sb.append('... | java |
public static Parameter<String> decodeForm(String s, Charset charset) {
int idx = s.indexOf("=");
try {
if (idx < 0) {
return Parameter.of("", URLDecoder.decode(s, charset.name()));
}
return Parameter.of(URLDecoder.decode(s.substring(0, idx), charset.n... | java |
public static List<Parameter<String>> decodeForms(String queryStr, Charset charset) {
String[] queries = queryStr.split("&");
List<Parameter<String>> list = new ArrayList<>(queries.length);
for (String query : queries) {
list.add(decodeForm(query, charset));
}
return... | java |
@Nullable
public Cookie getCookie(String name) {
for (Cookie cookie : cookies) {
if (cookie.name().equals(name)) {
return cookie;
}
}
return null;
} | java |
private static void registerAllTypeFactories(GsonBuilder gsonBuilder) {
ServiceLoader<TypeAdapterFactory> loader = ServiceLoader.load(TypeAdapterFactory.class);
for (TypeAdapterFactory typeFactory : loader) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Add gson type fac... | java |
public static KeyStore load(String path, char[] password) {
try {
return load(new FileInputStream(path), password);
} catch (FileNotFoundException e) {
throw new TrustManagerLoadFailedException(e);
}
} | java |
public static KeyStore load(InputStream in, char[] password) {
try {
KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
myTrustStore.load(in, password);
return myTrustStore;
} catch (CertificateException | NoSuchAlgorithmException | KeyStoreExce... | java |
private RawResponse getResponse(URL url, HttpURLConnection conn, CookieJar cookieJar, String method)
throws IOException {
// read result
int status = conn.getResponseCode();
String host = url.getHost().toLowerCase();
String statusLine = null;
// headers and cookies
... | java |
@NonNull
public JsonProcessor lookup() {
JsonProcessor registeredJsonProcessor = this.registeredJsonProcessor;
if (registeredJsonProcessor != null) {
return registeredJsonProcessor;
}
if (!init) {
synchronized (this) {
if (!init) {
... | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.