code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
private String getSuperMethodCallParameters(ExecutableElement sourceMethod) {
return sourceMethod
.getParameters()
.stream()
.map(parameter -> parameter.getSimpleName().toString())
.collect(Collectors.joining(", "));
} | java |
private void addEmitEventCall(ExecutableElement originalMethod,
MethodSpec.Builder proxyMethodBuilder, String methodCallParameters) {
String methodName = "$emit";
if (methodCallParameters != null && !"".equals(methodCallParameters)) {
proxyMethodBuilder.addStatement("vue().$L($S, $L)",
methodName,
methodToEventName(originalMethod),
methodCallParameters);
} else {
proxyMethodBuilder.addStatement("vue().$L($S)",
methodName,
methodToEventName(originalMethod));
}
} | java |
private boolean isHookMethod(TypeElement component, ExecutableElement method,
Set<ExecutableElement> hookMethodsFromInterfaces) {
if (hasAnnotation(method, HookMethod.class)) {
validateHookMethod(method);
return true;
}
for (ExecutableElement hookMethodsFromInterface : hookMethodsFromInterfaces) {
if (elements.overrides(method, hookMethodsFromInterface, component)) {
return true;
}
}
return false;
} | java |
private String getNativeNameForJavaType(TypeMirror typeMirror) {
TypeName typeName = TypeName.get(typeMirror);
if (typeName.equals(TypeName.INT)
|| typeName.equals(TypeName.BYTE)
|| typeName.equals(TypeName.SHORT)
|| typeName.equals(TypeName.LONG)
|| typeName.equals(TypeName.FLOAT)
|| typeName.equals(TypeName.DOUBLE)) {
return "Number";
} else if (typeName.equals(TypeName.BOOLEAN)) {
return "Boolean";
} else if (typeName.equals(TypeName.get(String.class)) || typeName.equals(TypeName.CHAR)) {
return "String";
} else if (typeMirror.toString().startsWith(JsArray.class.getCanonicalName())) {
return "Array";
} else {
return "Object";
}
} | java |
private void processInjectedFields(TypeElement component) {
getInjectedFields(component).stream().peek(this::validateField).forEach(field -> {
String fieldName = field.getSimpleName().toString();
addInjectedVariable(field, fieldName);
injectedFieldsName.add(fieldName);
});
} | java |
private void processInjectedMethods(TypeElement component) {
getInjectedMethods(component)
.stream()
.peek(this::validateMethod)
.forEach(this::processInjectedMethod);
} | java |
private void addInjectedVariable(VariableElement element, String fieldName) {
TypeName typeName = resolveVariableTypeName(element, messager);
// Create field
FieldSpec.Builder fieldBuilder = FieldSpec.builder(typeName, fieldName, Modifier.PUBLIC);
// Copy field annotations
element
.getAnnotationMirrors()
.stream()
.map(AnnotationSpec::get)
.forEach(fieldBuilder::addAnnotation);
// If the variable element is a method parameter, it might not have the Inject annotation
if (!hasInjectAnnotation(element)) {
fieldBuilder.addAnnotation(Inject.class);
}
// And add field
builder.addField(fieldBuilder.build());
} | java |
public LocalVariableInfo addLocalVariable(String typeQualifiedName, String name) {
return contextLayers.getFirst().addLocalVariable(typeQualifiedName, name);
} | java |
public DestructuredPropertyInfo addDestructuredProperty(String propertyType,
String propertyName,
LocalVariableInfo destructuredVariable) {
return contextLayers.getFirst()
.addDestructuredProperty(propertyType, propertyName, destructuredVariable);
} | java |
public VariableInfo findVariable(String name) {
for (ContextLayer contextLayer : contextLayers) {
VariableInfo variableInfo = contextLayer.getVariableInfo(name);
if (variableInfo != null) {
return variableInfo;
}
}
return null;
} | java |
public void addImport(String fullyQualifiedName) {
String[] importSplit = fullyQualifiedName.split("\\.");
String className = importSplit[importSplit.length - 1];
classNameToFullyQualifiedName.put(className, fullyQualifiedName);
} | java |
public String getFullyQualifiedNameForClassName(String className) {
if (!classNameToFullyQualifiedName.containsKey(className)) {
return className;
}
return classNameToFullyQualifiedName.get(className);
} | java |
public void addStaticImport(String fullyQualifiedName) {
String[] importSplit = fullyQualifiedName.split("\\.");
String symbolName = importSplit[importSplit.length - 1];
methodNameToFullyQualifiedName.put(symbolName, fullyQualifiedName);
propertyNameToFullyQualifiedName.put(symbolName, fullyQualifiedName);
} | java |
public String getFullyQualifiedNameForMethodName(String methodName) {
if (!methodNameToFullyQualifiedName.containsKey(methodName)) {
return methodName;
}
return methodNameToFullyQualifiedName.get(methodName);
} | java |
public String getFullyQualifiedNameForPropertyName(String propertyName) {
if (!propertyNameToFullyQualifiedName.containsKey(propertyName)) {
return propertyName;
}
return propertyNameToFullyQualifiedName.get(propertyName);
} | java |
public Optional<Integer> getCurrentLine() {
if (currentSegment == null) {
return Optional.empty();
}
return Optional.of(currentSegment.getSource().getRow(currentSegment.getBegin()));
} | java |
@JsIgnore
public static void initWithoutVueLib() {
if (!isVueLibInjected()) {
throw new RuntimeException(
"Couldn't find Vue.js on init. Either include it Vue.js in your index.html or call VueGWT.init() instead of initWithoutVueLib.");
}
// Register custom observers for Collection and Maps
VueGWTObserverManager.get().registerVueGWTObserver(new CollectionObserver());
VueGWTObserverManager.get().registerVueGWTObserver(new MapObserver());
isReady = true;
// Call on ready callbacks
for (Runnable onReadyCbk : onReadyCallbacks) {
onReadyCbk.run();
}
onReadyCallbacks.clear();
} | java |
@JsIgnore
public static void onReady(Runnable callback) {
if (isReady) {
callback.run();
return;
}
onReadyCallbacks.push(callback);
} | java |
public static void resolveRichTextField(ArrayResource array, CDAClient client) {
for (CDAEntry entry : array.entries().values()) {
ensureContentType(entry, client);
for (CDAField field : entry.contentType().fields()) {
if ("RichText".equals(field.type())) {
resolveRichDocument(entry, field);
resolveRichLink(array, entry, field);
}
}
}
} | java |
private static void resolveRichDocument(CDAEntry entry, CDAField field) {
final Map<String, Object> rawValue = (Map<String, Object>) entry.rawFields().get(field.id());
if (rawValue == null) {
return;
}
for (final String locale : rawValue.keySet()) {
final Object raw = rawValue.get(locale);
if (raw == null || raw instanceof CDARichNode) {
// ignore null and already parsed values
continue;
}
final Map<String, Object> map = (Map<String, Object>) rawValue.get(locale);
entry.setField(locale, field.id(), RESOLVER_MAP.get("document").resolve(map));
}
} | java |
private static void resolveRichLink(ArrayResource array, CDAEntry entry, CDAField field) {
final Map<String, Object> rawValue = (Map<String, Object>) entry.rawFields().get(field.id());
if (rawValue == null) {
return;
}
for (final String locale : rawValue.keySet()) {
final CDARichDocument document = entry.getField(locale, field.id());
for (final CDARichNode node : document.getContent()) {
resolveOneLink(array, field, locale, node);
}
}
} | java |
private static void resolveOneLink(ArrayResource array, CDAField field, String locale,
CDARichNode node) {
if (node instanceof CDARichHyperLink
&& ((CDARichHyperLink) node).data instanceof Map) {
final CDARichHyperLink link = (CDARichHyperLink) node;
final Map<String, Object> data = (Map<String, Object>) link.data;
final Object target = data.get("target");
if (target instanceof Map) {
if (isLink(target)) {
final Map<String, Object> map = (Map<String, Object>) target;
final Map<String, Object> sys = (Map<String, Object>) map.get("sys");
final String linkType = (String) sys.get("linkType");
final String id = (String) sys.get("id");
if ("Asset".equals(linkType)) {
link.data = array.assets().get(id);
} else if ("Entry".equals(linkType)) {
link.data = array.entries().get(id);
}
} else {
throw new IllegalStateException("Could not parse content of data field '"
+ field.id() + "' for locale '" + locale + "' at node '" + node
+ "'. Please check your content type model.");
}
} else if (target == null && data.containsKey("uri")) {
link.data = data.get("uri");
}
} else if (node instanceof CDARichParagraph) {
for (final CDARichNode child : ((CDARichParagraph) node).getContent()) {
resolveOneLink(array, field, locale, child);
}
}
} | java |
private static boolean isLink(Object data) {
try {
final Map<String, Object> map = (Map<String, Object>) data;
final Map<String, Object> sys = (Map<String, Object>) map.get("sys");
final String type = (String) sys.get("type");
final String linkType = (String) sys.get("linkType");
final String id = (String) sys.get("id");
if ("Link".equals(type)
&& ("Entry".equals(linkType) || "Asset".equals(linkType)
&& id != null)) {
return true;
}
} catch (ClassCastException cast) {
return false;
}
return false;
} | java |
public <T> T getField(String locale, String key) {
return localize(locale).getField(key);
} | java |
public Flowable<Transformed> one(String id) {
try {
return baseQuery()
.one(id)
.filter(new Predicate<CDAEntry>() {
@Override
public boolean test(CDAEntry entry) {
return entry.contentType().id()
.equals(contentTypeId);
}
})
.map(new Function<CDAEntry, Transformed>() {
@Override
public Transformed apply(CDAEntry entry) throws Exception {
return TransformQuery.this.transform(entry);
}
});
} catch (NullPointerException e) {
throw new CDAResourceNotFoundException(CDAEntry.class, id);
}
} | java |
public CDACallback<Transformed> one(String id, CDACallback<Transformed> callback) {
return Callbacks.subscribeAsync(
baseQuery()
.one(id)
.filter(new Predicate<CDAEntry>() {
@Override
public boolean test(CDAEntry entry) {
return entry.contentType().id().equals(contentTypeId);
}
})
.map(this::transform),
callback,
client);
} | java |
public Flowable<Collection<Transformed>> all() {
return baseQuery()
.all()
.map(
new Function<CDAArray, Collection<Transformed>>() {
@Override
public Collection<Transformed> apply(CDAArray array) {
final ArrayList<Transformed> result = new ArrayList<>(array.total());
for (final CDAResource resource : array.items) {
if (resource instanceof CDAEntry
&& ((CDAEntry) resource).contentType().id().equals(contentTypeId)) {
result.add(TransformQuery.this.transform((CDAEntry) resource));
}
}
return result;
}
}
);
} | java |
public CDACallback<Collection<Transformed>> all(CDACallback<Collection<Transformed>> callback) {
return Callbacks.subscribeAsync(
baseQuery()
.all()
.map(
new Function<CDAArray, List<Transformed>>() {
@Override
public List<Transformed> apply(CDAArray array) {
final ArrayList<Transformed> result = new ArrayList<>(array.total());
for (final CDAResource resource : array.items) {
if (resource instanceof CDAEntry
&& ((CDAEntry) resource).contentType().id().equals(contentTypeId)) {
result.add(TransformQuery.this.transform((CDAEntry) resource));
}
}
return result;
}
}
),
callback,
client);
} | java |
@SuppressWarnings("unchecked")
public <T> T getAttribute(String key) {
return (T) attrs.get(key);
} | java |
public Flowable<CDAArray> all() {
return client.cacheAll(false)
.flatMap(
new Function<Cache, Publisher<Response<CDAArray>>>() {
@Override
public Publisher<Response<CDAArray>> apply(Cache cache) {
return client.service.array(client.spaceId, client.environmentId, path(), params);
}
}
).map(new Function<Response<CDAArray>, CDAArray>() {
@Override
public CDAArray apply(Response<CDAArray> response) {
return ResourceFactory.array(response, client);
}
});
} | java |
public static ImageOption jpegQualityOf(int quality) {
if (quality < 1 || quality > 100) {
throw new IllegalArgumentException("Quality has to be in the range from 1 to 100.");
}
return new ImageOption("q", Integer.toString(quality));
} | java |
public String apply(String url) {
return format(
getDefault(),
"%s%s%s=%s",
url,
concatenationOperator(url),
operation,
argument);
} | java |
@SuppressWarnings("unchecked")
public <C extends CDACallback<CDASpace>> C fetchSpace(C callback) {
return (C) Callbacks.subscribeAsync(observeSpace(), callback, this);
} | java |
public static void ensureContentType(CDAEntry entry, CDAClient client) {
CDAContentType contentType = entry.contentType();
if (contentType != null) {
return;
}
String contentTypeId = extractNested(entry.attrs(), "contentType", "sys", "id");
try {
contentType = client.cacheTypeWithId(contentTypeId).blockingFirst();
} catch (CDAResourceNotFoundException e) {
throw new CDAContentTypeNotFoundException(entry.id(), CDAEntry.class, contentTypeId, e);
}
entry.setContentType(contentType);
} | java |
@SuppressWarnings("unchecked")
public <C extends CDACallback<CDAArray>> C all(C callback) {
return (C) Callbacks.subscribeAsync(baseQuery().all(), callback, client);
} | java |
public static CamundaBpmProducer createProducer(final CamundaBpmEndpoint endpoint, final ParsedUri uri,
final Map<String, Object> parameters) throws IllegalArgumentException {
switch (uri.getType()) {
case StartProcess:
return new StartProcessProducer(endpoint, parameters);
case SendSignal:
case SendMessage:
return new MessageProducer(endpoint, parameters);
default:
throw new IllegalArgumentException("Cannot create a producer for URI '" + uri + "' - new ProducerType '"
+ uri.getType() + "' not yet supported?");
}
} | java |
protected void removeExcessiveInProgressTasks(Queue<Exchange> exchanges, int limit) {
while (exchanges.size() > limit) {
// must remove last
Exchange exchange = exchanges.poll();
releaseTask(exchange);
}
} | java |
@SuppressWarnings("rawtypes")
public static Map<String, Object> prepareVariables(Exchange exchange, Map<String, Object> parameters) {
Map<String, Object> processVariables = new HashMap<String, Object>();
Object camelBody = exchange.getIn().getBody();
if (camelBody instanceof String) {
// If the COPY_MESSAGE_BODY_AS_PROCESS_VARIABLE_PARAMETER was passed
// the value of it
// is taken as variable to store the (string) body in
String processVariableName = "camelBody";
if (parameters.containsKey(CamundaBpmConstants.COPY_MESSAGE_BODY_AS_PROCESS_VARIABLE_PARAMETER)) {
processVariableName = (String) parameters.get(
CamundaBpmConstants.COPY_MESSAGE_BODY_AS_PROCESS_VARIABLE_PARAMETER);
}
processVariables.put(processVariableName, camelBody);
} else if (camelBody instanceof Map<?, ?>) {
Map<?, ?> camelBodyMap = (Map<?, ?>) camelBody;
for (Map.Entry e : camelBodyMap.entrySet()) {
if (e.getKey() instanceof String) {
processVariables.put((String) e.getKey(), e.getValue());
}
}
} else if (camelBody != null) {
log.log(Level.WARNING,
"unkown type of camel body - not handed over to process engine: " + camelBody.getClass());
}
return processVariables;
} | java |
@Override
public void close() {
if (closed) {
return;
}
if (SHOULD_CHECK && !txn.isReadOnly()) {
txn.checkReady();
}
LIB.mdb_cursor_close(ptrCursor);
kv.close();
closed = true;
} | java |
public long count() {
if (SHOULD_CHECK) {
checkNotClosed();
txn.checkReady();
}
final NativeLongByReference longByReference = new NativeLongByReference();
checkRc(LIB.mdb_cursor_count(ptrCursor, longByReference));
return longByReference.longValue();
} | java |
public boolean put(final T key, final T val, final PutFlags... op) {
if (SHOULD_CHECK) {
requireNonNull(key);
requireNonNull(val);
checkNotClosed();
txn.checkReady();
txn.checkWritesAllowed();
}
kv.keyIn(key);
kv.valIn(val);
final int mask = mask(op);
final int rc = LIB.mdb_cursor_put(ptrCursor, kv.pointerKey(),
kv.pointerVal(), mask);
if (rc == MDB_KEYEXIST) {
if (isSet(mask, MDB_NOOVERWRITE)) {
kv.valOut(); // marked as in,out in LMDB C docs
} else if (!isSet(mask, MDB_NODUPDATA)) {
checkRc(rc);
}
return false;
}
checkRc(rc);
return true;
} | java |
public void renew(final Txn<T> newTxn) {
if (SHOULD_CHECK) {
requireNonNull(newTxn);
checkNotClosed();
this.txn.checkReadOnly(); // existing
newTxn.checkReadOnly();
newTxn.checkReady();
}
checkRc(LIB.mdb_cursor_renew(newTxn.pointer(), ptrCursor));
this.txn = newTxn;
} | java |
public long runFor(final long duration, final TimeUnit unit) {
final long deadline = System.currentTimeMillis() + unit.toMillis(duration);
final ExecutorService es = Executors.newSingleThreadExecutor();
final Future<Long> future = es.submit(this);
try {
while (System.currentTimeMillis() < deadline && !future.isDone()) {
Thread.sleep(unit.toMillis(1));
}
} catch (final InterruptedException ignored) {
} finally {
stop();
}
final long result;
try {
result = future.get();
} catch (final InterruptedException | ExecutionException ex) {
throw new IllegalStateException(ex);
} finally {
es.shutdown();
}
return result;
} | java |
public static Version version() {
final IntByReference major = new IntByReference();
final IntByReference minor = new IntByReference();
final IntByReference patch = new IntByReference();
LIB.mdb_version(major, minor, patch);
return new Version(major.intValue(), minor.intValue(), patch.
intValue());
} | java |
public void copy(final File path, final CopyFlags... flags) {
requireNonNull(path);
if (!path.exists()) {
throw new InvalidCopyDestination("Path must exist");
}
if (!path.isDirectory()) {
throw new InvalidCopyDestination("Path must be a directory");
}
final String[] files = path.list();
if (files != null && files.length > 0) {
throw new InvalidCopyDestination("Path must contain no files");
}
final int flagsMask = mask(flags);
checkRc(LIB.mdb_env_copy2(ptr, path.getAbsolutePath(), flagsMask));
} | java |
public List<byte[]> getDbiNames() {
final List<byte[]> result = new ArrayList<>();
final Dbi<T> names = openDbi((byte[]) null);
try (Txn<T> txn = txnRead();
Cursor<T> cursor = names.openCursor(txn)) {
if (!cursor.first()) {
return Collections.emptyList();
}
do {
final byte[] name = proxy.getBytes(cursor.key());
result.add(name);
} while (cursor.next());
}
return result;
} | java |
public EnvInfo info() {
if (closed) {
throw new AlreadyClosedException();
}
final MDB_envinfo info = new MDB_envinfo(RUNTIME);
checkRc(LIB.mdb_env_info(ptr, info));
final long mapAddress;
if (info.f0_me_mapaddr.get() == null) {
mapAddress = 0;
} else {
mapAddress = info.f0_me_mapaddr.get().address();
}
return new EnvInfo(
mapAddress,
info.f1_me_mapsize.longValue(),
info.f2_me_last_pgno.longValue(),
info.f3_me_last_txnid.longValue(),
info.f4_me_maxreaders.intValue(),
info.f5_me_numreaders.intValue());
} | java |
public Stat stat() {
if (closed) {
throw new AlreadyClosedException();
}
final MDB_stat stat = new MDB_stat(RUNTIME);
checkRc(LIB.mdb_env_stat(ptr, stat));
return new Stat(
stat.f0_ms_psize.intValue(),
stat.f1_ms_depth.intValue(),
stat.f2_ms_branch_pages.longValue(),
stat.f3_ms_leaf_pages.longValue(),
stat.f4_ms_overflow_pages.longValue(),
stat.f5_ms_entries.longValue());
} | java |
public void sync(final boolean force) {
if (closed) {
throw new AlreadyClosedException();
}
final int f = force ? 1 : 0;
checkRc(LIB.mdb_env_sync(ptr, f));
} | java |
public Txn<T> txn(final Txn<T> parent, final TxnFlags... flags) {
if (closed) {
throw new AlreadyClosedException();
}
return new Txn<>(this, parent, proxy, flags);
} | java |
@SuppressWarnings("checkstyle:ReturnCount")
public static int compareBuff(final DirectBuffer o1, final DirectBuffer o2) {
requireNonNull(o1);
requireNonNull(o2);
if (o1.equals(o2)) {
return 0;
}
final int minLength = Math.min(o1.capacity(), o2.capacity());
final int minWords = minLength / Long.BYTES;
for (int i = 0; i < minWords * Long.BYTES; i += Long.BYTES) {
final long lw = o1.getLong(i, BIG_ENDIAN);
final long rw = o2.getLong(i, BIG_ENDIAN);
final int diff = Long.compareUnsigned(lw, rw);
if (diff != 0) {
return diff;
}
}
for (int i = minWords * Long.BYTES; i < minLength; i++) {
final int lw = Byte.toUnsignedInt(o1.getByte(i));
final int rw = Byte.toUnsignedInt(o2.getByte(i));
final int result = Integer.compareUnsigned(lw, rw);
if (result != 0) {
return result;
}
}
return o1.capacity() - o2.capacity();
} | java |
public boolean delete(final T key) {
try (Txn<T> txn = env.txnWrite()) {
final boolean ret = delete(txn, key);
txn.commit();
return ret;
}
} | java |
public boolean delete(final Txn<T> txn, final T key) {
return delete(txn, key, null);
} | java |
public Cursor<T> openCursor(final Txn<T> txn) {
if (SHOULD_CHECK) {
requireNonNull(txn);
txn.checkReady();
}
final PointerByReference cursorPtr = new PointerByReference();
checkRc(LIB.mdb_cursor_open(txn.pointer(), ptr, cursorPtr));
return new Cursor<>(cursorPtr.getValue(), txn);
} | java |
public Stat stat(final Txn<T> txn) {
if (SHOULD_CHECK) {
requireNonNull(txn);
txn.checkReady();
}
final MDB_stat stat = new MDB_stat(RUNTIME);
checkRc(LIB.mdb_stat(txn.pointer(), ptr, stat));
return new Stat(
stat.f0_ms_psize.intValue(),
stat.f1_ms_depth.intValue(),
stat.f2_ms_branch_pages.longValue(),
stat.f3_ms_leaf_pages.longValue(),
stat.f4_ms_overflow_pages.longValue(),
stat.f5_ms_entries.longValue());
} | java |
@Override
public void close() {
if (state == RELEASED) {
return;
}
if (state == READY) {
LIB.mdb_txn_abort(ptr);
}
keyVal.close();
state = RELEASED;
} | java |
protected String getNextLine(int newlineCount) throws IOException {
if (newlineCount == 0) {
return "";
}
StringBuffer str = new StringBuffer();
int b;
while (pis.available() > 0) {
b = pis.read();
if (b == -1) {
return "";
}
if (b == '\n') {
newlineCount--;
if (newlineCount == 0) {
log.debug("Read lines: " + str.toString());
String[] lines = str.toString().split("\n");
// FIXME: this leads to queuing lines so we will have time lag!
return lines[lines.length - 1];
}
}
str.append((char) b);
}
return "";
} | java |
public static Transport getTransport(SocketAddress addr) throws IOException {
Transport trans;
try {
log.debug("Connecting TCP");
trans = TCPInstance(addr);
if (!trans.test()) {
throw new IOException("Agent is unreachable via TCP");
}
return trans;
} catch (IOException e) {
log.info("Can't connect TCP transport for host: " + addr.toString(), e);
try {
log.debug("Connecting UDP");
trans = UDPInstance(addr);
if (!trans.test()) {
throw new IOException("Agent is unreachable via UDP");
}
return trans;
} catch (IOException ex) {
log.info("Can't connect UDP transport for host: " + addr.toString(), ex);
throw ex;
}
}
} | java |
public static Transport TCPInstance(SocketAddress addr) throws IOException {
Socket sock = new Socket();
sock.setSoTimeout(getTimeout());
sock.connect(addr);
StreamTransport trans = new StreamTransport();
trans.setStreams(sock.getInputStream(), sock.getOutputStream());
trans.setAddressLabel(addr.toString());
return trans;
} | java |
public static Transport UDPInstance(SocketAddress addr) throws IOException {
DatagramSocket sock = new DatagramSocket();
sock.setSoTimeout(getTimeout());
sock.connect(addr);
StreamTransport trans = new StreamTransport();
trans.setStreams(new UDPInputStream(sock), new UDPOutputStream(sock));
trans.setAddressLabel(addr.toString());
return trans;
} | java |
public ProgressBar maxHint(long n) {
if (n < 0)
progress.setAsIndefinite();
else {
progress.setAsDefinite();
progress.maxHint(n);
}
return this;
} | java |
public static <R, S> Tuple2<R, S> create(R r, S s) {
return new Tuple2<R, S>(r, s);
} | java |
public static BigDecimal factorial(int n) {
if (n < 0) {
throw new ArithmeticException("Illegal factorial(n) for n < 0: n = " + n);
}
if (n < factorialCache.length) {
return factorialCache[n];
}
BigDecimal result = factorialCache[factorialCache.length - 1];
return result.multiply(factorialRecursion(factorialCache.length, n));
} | java |
public static BigDecimal pi(MathContext mathContext) {
checkMathContext(mathContext);
BigDecimal result = null;
synchronized (piCacheLock) {
if (piCache != null && mathContext.getPrecision() <= piCache.precision()) {
result = piCache;
} else {
piCache = piChudnovski(mathContext);
return piCache;
}
}
return round(result, mathContext);
} | java |
public static BigDecimal e(MathContext mathContext) {
checkMathContext(mathContext);
BigDecimal result = null;
synchronized (eCacheLock) {
if (eCache != null && mathContext.getPrecision() <= eCache.precision()) {
result = eCache;
} else {
eCache = exp(ONE, mathContext);
return eCache;
}
}
return round(result, mathContext);
} | java |
private BigRational multiply(BigDecimal value) {
BigDecimal n = numerator.multiply(value);
BigDecimal d = denominator;
return of(n, d);
} | java |
public static BigRational valueOf(int integer, int fractionNumerator, int fractionDenominator) {
if (fractionNumerator < 0 || fractionDenominator < 0) {
throw new ArithmeticException("Negative value");
}
BigRational integerPart = valueOf(integer);
BigRational fractionPart = valueOf(fractionNumerator, fractionDenominator);
return integerPart.isPositive() ? integerPart.add(fractionPart) : integerPart.subtract(fractionPart);
} | java |
public static BigRational valueOf(double value) {
if (value == 0.0) {
return ZERO;
}
if (value == 1.0) {
return ONE;
}
if (Double.isInfinite(value)) {
throw new NumberFormatException("Infinite");
}
if (Double.isNaN(value)) {
throw new NumberFormatException("NaN");
}
return valueOf(new BigDecimal(String.valueOf(value)));
} | java |
public static BigRational valueOf(String string) {
String[] strings = string.split("/");
BigRational result = valueOfSimple(strings[0]);
for (int i = 1; i < strings.length; i++) {
result = result.divide(valueOfSimple(strings[i]));
}
return result;
} | java |
public static BigRational min(BigRational... values) {
if (values.length == 0) {
return BigRational.ZERO;
}
BigRational result = values[0];
for (int i = 1; i < values.length; i++) {
result = result.min(values[i]);
}
return result;
} | java |
public static BigRational max(BigRational... values) {
if (values.length == 0) {
return BigRational.ZERO;
}
BigRational result = values[0];
for (int i = 1; i < values.length; i++) {
result = result.max(values[i]);
}
return result;
} | java |
public BigComplex add(BigComplex value) {
return valueOf(
re.add(value.re),
im.add(value.im));
} | java |
public BigComplex subtract(BigComplex value) {
return valueOf(
re.subtract(value.re),
im.subtract(value.im));
} | java |
public BigComplex multiply(BigComplex value) {
return valueOf(
re.multiply(value.re).subtract(im.multiply(value.im)),
re.multiply(value.im).add(im.multiply(value.re)));
} | java |
public BigDecimal absSquare(MathContext mathContext) {
return re.multiply(re, mathContext).add(im.multiply(im, mathContext), mathContext);
} | java |
public BigComplex round(MathContext mathContext) {
return valueOf(re.round(mathContext), im.round(mathContext));
} | java |
public boolean strictEquals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BigComplex other = (BigComplex) obj;
return re.equals(other.re) && im.equals(other.im);
} | java |
protected BigRational getFactor(int index) {
while (factors.size() <= index) {
BigRational factor = getCurrentFactor();
factors.add(factor);
calculateNextFactor();
}
return factors.get(index);
} | java |
protected static DBFField createField(DataInput in, Charset charset, boolean useFieldFlags) throws IOException {
DBFField field = new DBFField();
byte t_byte = in.readByte(); /* 0 */
if (t_byte == (byte) 0x0d) {
return null;
}
byte[] fieldName = new byte[11];
in.readFully(fieldName, 1, 10); /* 1-10 */
fieldName[0] = t_byte;
int nameNullIndex = fieldName.length -1;
for (int i = 0; i < fieldName.length; i++) {
if (fieldName[i] == (byte) 0) {
nameNullIndex = i;
break;
}
}
field.name = new String(fieldName, 0, nameNullIndex,charset);
try {
field.type = DBFDataType.fromCode(in.readByte()); /* 11 */
} catch (Exception e) {
field.type = DBFDataType.UNKNOWN;
}
field.reserv1 = DBFUtils.readLittleEndianInt(in); /* 12-15 */
field.length = in.readUnsignedByte(); /* 16 */
field.decimalCount = in.readByte(); /* 17 */
field.reserv2 = DBFUtils.readLittleEndianShort(in); /* 18-19 */
field.workAreaId = in.readByte(); /* 20 */
field.reserv3 = DBFUtils.readLittleEndianShort(in); /* 21-22 */
field.setFieldsFlag = in.readByte(); /* 23 */
in.readFully(field.reserv4); /* 24-30 */
field.indexFieldFlag = in.readByte(); /* 31 */
adjustLengthForLongCharSupport(field);
if (!useFieldFlags) {
field.reserv2 = 0;
}
return field;
} | java |
protected void write(DataOutput out, Charset charset) throws IOException {
// Field Name
out.write(this.name.getBytes(charset)); /* 0-10 */
out.write(new byte[11 - this.name.length()]);
// data type
out.writeByte(this.type.getCode()); /* 11 */
out.writeInt(0x00); /* 12-15 */
out.writeByte(this.length); /* 16 */
out.writeByte(this.decimalCount); /* 17 */
out.writeShort((short) 0x00); /* 18-19 */
out.writeByte((byte) 0x00); /* 20 */
out.writeShort((short) 0x00); /* 21-22 */
out.writeByte((byte) 0x00); /* 23 */
out.write(new byte[7]); /* 24-30 */
out.writeByte((byte) 0x00); /* 31 */
} | java |
public void setName(String name) {
if (name == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (name.length() == 0 || name.length() > 10) {
throw new IllegalArgumentException("Field name should be of length 0-10");
}
if (!DBFUtils.isPureAscii(name)) {
throw new IllegalArgumentException("Field name must be ASCII");
}
this.name = name;
} | java |
public void setType(DBFDataType type) {
if (!type.isWriteSupported()) {
throw new IllegalArgumentException("No support for writting " + type);
}
this.type = type;
if (type.getDefaultSize() > 0) {
this.length = type.getDefaultSize();
}
} | java |
public static Charset getCharsetByByte(int b) {
switch (b) {
case 0x01:
// U.S. MS-DOS
return forName("IBM437");
case 0x02:
// International MS-DOS
return forName("IBM850");
case 0x03:
// Windows ANSI
return forName("windows-1252");
case 0x04:
// Standard Macintosh
return forName("MacRoman");
case 0x57:
// ESRI shape files use code 0x57 to indicate that
// data is written in ANSI (whatever that means).
// http://www.esricanada.com/english/support/faqs/arcview/avfaq21.asp
return forName("windows-1252");
case 0x59:
return forName("windows-1252");
case 0x64:
// Eastern European MS-DOS
return forName("IBM852");
case 0x65:
// Russian MS-DOS
return forName("IBM866");
case 0x66:
// Nordic MS-DOS
return forName("IBM865");
case 0x67:
// Icelandic MS-DOS
return forName("IBM861");
// case 0x68:
// Kamenicky (Czech) MS-DOS
// return Charset.forName("895");
// case 0x69:
// Mazovia (Polish) MS-DOS
// return Charset.forName("620");
case 0x6A:
// Greek MS-DOS (437G)
return forName("x-IBM737");
case 0x6B:
// Turkish MS-DOS
return forName("IBM857");
case 0x78:
// Chinese (Hong Kong SAR, Taiwan) Windows
return forName("windows-950");
case 0x79:
// Korean Windows
return Charset.forName("windows-949");
case 0x7A:
// Chinese (PRC, Singapore) Windows
return forName("GBK");
case 0x7B:
// Japanese Windows
return forName("windows-932");
case 0x7C:
// Thai Windows
return forName("windows-874");
case 0x7D:
// Hebrew Windows
return forName("windows-1255");
case 0x7E:
// Arabic Windows
return forName("windows-1256");
case 0x96:
// Russian Macintosh
return forName("x-MacCyrillic");
case 0x97:
// Macintosh EE
return forName("x-MacCentralEurope");
case 0x98:
// Greek Macintosh
return forName("x-MacGreek");
case 0xC8:
// Eastern European Windows
return forName("windows-1250");
case 0xC9:
// Russian Windows
return forName("windows-1251");
case 0xCA:
// Turkish Windows
return forName("windows-1254");
case 0xCB:
// Greek Windows
return forName("windows-1253");
}
return null;
} | java |
public static int getDBFCodeForCharset(Charset charset) {
if (charset == null) {
return 0;
}
String charsetName = charset.toString();
if ("ibm437".equalsIgnoreCase(charsetName)) {
return 0x01;
}
if ("ibm850".equalsIgnoreCase(charsetName)) {
return 0x02;
}
if ("windows-1252".equalsIgnoreCase(charsetName)) {
return 0x03;
}
if ("iso-8859-1".equalsIgnoreCase(charsetName)) {
return 0x03;
}
if ("MacRoman".equalsIgnoreCase(charsetName)) {
return 0x04;
}
if ("IBM852".equalsIgnoreCase(charsetName)) {
return 0x64;
}
if ("IBM865".equalsIgnoreCase(charsetName)) {
return 0x66;
}
if ("IBM866".equalsIgnoreCase(charsetName)) {
return 0x65;
}
if ("IBM861".equalsIgnoreCase(charsetName)) {
return 0x67;
}
// 0x68
// 0x69
if ("IBM737".equalsIgnoreCase(charsetName)) {
return 0x6a;
}
if ("IBM857".equalsIgnoreCase(charsetName)) {
return 0x6b;
}
if ("windows-950".equalsIgnoreCase(charsetName)) {
return 0x78;
}
if ("windows-949".equalsIgnoreCase(charsetName)) {
return 0x79;
}
if ("gbk".equalsIgnoreCase(charsetName)) {
return 0x7a;
}
if ("windows-932".equalsIgnoreCase(charsetName)) {
return 0x7b;
}
if ("windows-874".equalsIgnoreCase(charsetName)) {
return 0x7c;
}
if ("windows-1255".equalsIgnoreCase(charsetName)) {
return 0x7d;
}
if ("windows-1256".equalsIgnoreCase(charsetName)) {
return 0x7e;
}
if ("x-MacCyrillic".equalsIgnoreCase(charsetName)) {
return 0x96;
}
if ("x-MacCentralEurope".equalsIgnoreCase(charsetName)) {
return 0x97;
}
if ("x-MacGreek".equalsIgnoreCase(charsetName)) {
return 0x98;
}
if ("windows-1250".equalsIgnoreCase(charsetName)) {
return 0xc8;
}
if ("windows-1251".equalsIgnoreCase(charsetName)) {
return 0xc9;
}
if ("windows-1254".equalsIgnoreCase(charsetName)) {
return 0xca;
}
if ("windows-1253".equalsIgnoreCase(charsetName)) {
return 0xcb;
}
// Unsupported charsets returns 0
return 0;
} | java |
public Date getLastModificationDate() {
if (this.year == 0 || this.month == 0 || this.day == 0){
return null;
}
try {
Calendar calendar = Calendar.getInstance();
calendar.set(this.year, this.month, this.day, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
catch (Exception e) {
return null;
}
} | java |
public static Number readNumericStoredAsText(DataInputStream dataInput, int length) throws IOException {
try {
byte t_float[] = new byte[length];
int readed = dataInput.read(t_float);
if (readed != length) {
throw new EOFException("failed to read:" + length + " bytes");
}
t_float = DBFUtils.removeSpaces(t_float);
t_float = DBFUtils.removeNullBytes(t_float);
if (t_float.length > 0 && DBFUtils.isPureAscii(t_float) && !DBFUtils.contains(t_float, (byte) '?') && !DBFUtils.contains(t_float, (byte) '*')) {
String aux = new String(t_float, StandardCharsets.US_ASCII).replace(',', '.');
if (".".equals(aux)) {
return BigDecimal.ZERO;
}
return new BigDecimal(aux);
} else {
return null;
}
} catch (NumberFormatException e) {
throw new DBFException("Failed to parse Float: " + e.getMessage(), e);
}
} | java |
public static int littleEndian(int value) {
int num1 = value;
int mask = 0xff;
int num2 = 0x00;
num2 |= num1 & mask;
for (int i = 1; i < 4; i++) {
num2 <<= 8;
mask <<= 8;
num2 |= (num1 & mask) >> (8 * i);
}
return num2;
} | java |
public static byte[] doubleFormating(Number num, Charset charset, int fieldLength, int sizeDecimalPart) {
int sizeWholePart = fieldLength - (sizeDecimalPart > 0 ? (sizeDecimalPart + 1) : 0);
StringBuilder format = new StringBuilder(fieldLength);
for (int i = 0; i < sizeWholePart-1; i++) {
format.append("#");
}
if (format.length() < sizeWholePart) {
format.append("0");
}
if (sizeDecimalPart > 0) {
format.append(".");
for (int i = 0; i < sizeDecimalPart; i++) {
format.append("0");
}
}
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
df.applyPattern(format.toString());
return textPadding(df.format(num).toString(), charset, fieldLength, DBFAlignment.RIGHT,
(byte) ' ');
} | java |
public static boolean contains(byte[] array, byte value) {
if (array != null) {
for (byte data : array) {
if (data == value) {
return true;
}
}
}
return false;
} | java |
public static boolean isPureAscii(String stringToCheck) {
if (stringToCheck == null || stringToCheck.length() == 0) {
return true;
}
synchronized (ASCII_ENCODER) {
return ASCII_ENCODER.canEncode(stringToCheck);
}
} | java |
public static boolean isPureAscii(byte[] data) {
if (data == null) {
return false;
}
for (byte b : data) {
if (b < 0x20) {
return false;
}
}
return true;
} | java |
public static byte[] trimRightSpaces(byte[] b_array) {
if (b_array == null || b_array.length == 0) {
return new byte[0];
}
int pos = getRightPos(b_array);
int length = pos + 1;
byte[] newBytes = new byte[length];
System.arraycopy(b_array, 0, newBytes, 0, length);
return newBytes;
} | java |
public void setFields(DBFField[] fields) {
if (this.closed) {
throw new IllegalStateException("You can not set fields to a closed DBFWriter");
}
if (this.header.fieldArray != null) {
throw new DBFException("Fields has already been set");
}
if (fields == null || fields.length == 0) {
throw new DBFException("Should have at least one field");
}
for (int i = 0; i < fields.length; i++) {
if (fields[i] == null) {
throw new DBFException("Field " + i + " is null");
}
}
this.header.fieldArray = new DBFField[fields.length];
for (int i = 0; i < fields.length; i++) {
this.header.fieldArray[i] = new DBFField(fields[i]);
}
try {
if (this.raf != null && this.raf.length() == 0) {
// this is a new/non-existent file. So write header before proceeding
this.header.write(this.raf);
}
} catch (IOException e) {
throw new DBFException("Error accesing file:" + e.getMessage(), e);
}
} | java |
public void addRecord(Object[] values) {
if (this.closed) {
throw new IllegalStateException("You can add records a closed DBFWriter");
}
if (this.header.fieldArray == null) {
throw new DBFException("Fields should be set before adding records");
}
if (values == null) {
throw new DBFException("Null cannot be added as row");
}
if (values.length != this.header.fieldArray.length) {
throw new DBFException("Invalid record. Invalid number of fields in row");
}
for (int i = 0; i < this.header.fieldArray.length; i++) {
Object value = values[i];
if (value == null) {
continue;
}
switch (this.header.fieldArray[i].getType()) {
case CHARACTER:
if (!(value instanceof String)) {
throw new DBFException("Invalid value for field " + i + ":" + value);
}
break;
case LOGICAL:
if (!(value instanceof Boolean)) {
throw new DBFException("Invalid value for field " + i + ":" + value);
}
break;
case DATE:
if (!(value instanceof Date)) {
throw new DBFException("Invalid value for field " + i + ":" + value);
}
break;
case NUMERIC:
case FLOATING_POINT:
if (!(value instanceof Number)) {
throw new DBFException("Invalid value for field " + i + ":" + value);
}
break;
default:
throw new DBFException("Unsupported writting of field type " + i + " "
+ this.header.fieldArray[i].getType());
}
}
if (this.raf == null) {
this.v_records.add(values);
} else {
try {
writeRecord(this.raf, values);
this.recordCount++;
} catch (IOException e) {
throw new DBFException("Error occured while writing record. " + e.getMessage(), e);
}
}
} | java |
@Override
public void close() {
if (this.closed) {
return;
}
this.closed = true;
if (this.raf != null) {
/*
* everything is written already. just update the header for
* record count and the END_OF_DATA mark
*/
try {
this.header.numberOfRecords = this.recordCount;
this.raf.seek(0);
this.header.write(this.raf);
this.raf.seek(this.raf.length());
this.raf.writeByte(END_OF_DATA);
}
catch (IOException e) {
throw new DBFException(e.getMessage(), e);
}
finally {
DBFUtils.close(this.raf);
}
}
else if (this.outputStream != null) {
try {
writeToStream(this.outputStream);
}
finally {
DBFUtils.close(this.outputStream);
}
}
} | java |
public String getString(int columnIndex) {
if (columnIndex < 0 || columnIndex >= data.length) {
throw new IllegalArgumentException("Invalid index field: (" + columnIndex+"). Valid range is 0 to " + (data.length - 1));
}
Object fieldValue = data[columnIndex];
if (fieldValue == null) {
return null;
}
if (fieldValue instanceof String) {
return (String) fieldValue;
}
return fieldValue.toString();
} | java |
public BigDecimal getBigDecimal(int columnIndex) {
Object fieldValue = data[columnIndex];
if (fieldValue == null) {
return null;
}
if (fieldValue instanceof BigDecimal) {
return (BigDecimal) fieldValue;
}
throw new DBFException("Unsupported type for BigDecimal at column:" + columnIndex + " "
+ fieldValue.getClass().getCanonicalName());
} | java |
public boolean getBoolean(int columnIndex) {
Object fieldValue = data[columnIndex];
if (fieldValue == null) {
return Boolean.FALSE;
}
if (fieldValue instanceof Boolean) {
return (Boolean) fieldValue;
}
throw new DBFException("Unsupported type for Boolean at column:" + columnIndex + " "
+ fieldValue.getClass().getCanonicalName());
} | java |
public Date getDate(int columnIndex) {
Object fieldValue = data[columnIndex];
if (fieldValue == null) {
return null;
}
if (fieldValue instanceof Date) {
return (Date) fieldValue;
}
throw new DBFException(
"Unsupported type for Date at column:" + columnIndex + " " + fieldValue.getClass().getCanonicalName());
} | java |
public double getDouble(int columnIndex) {
Object fieldValue = data[columnIndex];
if (fieldValue == null) {
return 0.0;
}
if (fieldValue instanceof Number) {
return ((Number) fieldValue).doubleValue();
}
throw new DBFException("Unsupported type for Number at column:" + columnIndex + " "
+ fieldValue.getClass().getCanonicalName());
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.