code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
public static void printUsage(PrintWriter out) {
CliArguments arguments = new CliArguments();
CmdLineParser parser = new CmdLineParser(arguments);
parser.setUsageWidth(120);
parser.printUsage(out, null);
} | java |
public boolean isSet() {
if (isUsageMode()) {
return true;
}
if (getJobFile() != null) {
return true;
}
if (getListType() != null) {
return true;
}
return false;
} | java |
private void writeObject(ObjectOutputStream out) throws IOException {
logger.info("Serialization requested, awaiting reference to load.");
get();
out.defaultWriteObject();
logger.info("Serialization finished!");
} | java |
public static EscEvents create(final JsonArray jsonArray) {
final List<EscEvent> events = new ArrayList<>();
for (final JsonValue jsonValue : jsonArray) {
if (jsonValue.getValueType() != JsonValue.ValueType.OBJECT) {
throw new IllegalArgumentException(
... | java |
static KAFDocument load(File file) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
} | java |
static KAFDocument load(Reader stream) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(stream);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
} | java |
static void save(KAFDocument kaf, String filename) {
try {
File file = new File(filename);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println("Error writing to file");
... | java |
static void print(KAFDocument kaf) {
try {
Writer out = new BufferedWriter(new OutputStreamWriter(System.out, "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println(e);
}
} | java |
static String kafToStr(KAFDocument kaf) {
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setLineSeparator(LineSeparator.UNIX).setTextMode(Format.TextMode.TRIM_FULL_WHITE));
Document jdom = KAFToDOM(kaf);
return out.outputString(jdom);
} | java |
public Query getOptimizedQuery() {
// if (isOptimizable()) {
// return _baseQuery;
// }
// create a copy/clone of the original query
Query q = _baseQuery.clone();
Set<Entry<FilterConsumer, FilterOutcome>> entries = _optimizedFilters.entrySet();
for (Entry<Filter... | java |
@Override
public List<Token> tokenize(String s) {
List<Token> result = new ArrayList<Token>();
result.add(new UndefinedToken(s));
for (PredefinedTokenDefinition predefinedTokenDefinition : _predefinedTokenDefitions) {
Set<Pattern> patterns = predefinedTokenDefinition.getTokenRegexPatterns();
for (Pattern ... | java |
public void doLog(String clientID, String name, long time, Level level,
Object message, Throwable t) {
if (logOpen && formatter != null) {
sendMessage(syslogMessage.createMessageData(formatter.format(clientID, name, time, level, message, t)));
}
} | java |
public String format(String clientID, String name, long time, Level level, Object message,
Throwable t){
if (!patternParsed && pattern != null) {
parsePattern(pattern);
}
StringBuffer formattedStringBuffer = new StringBuffer(64);
if (commandArray != null) {
int length = commandArray.length;
... | java |
public void setPattern(String pattern) throws IllegalArgumentException{
if (pattern == null) {
throw new IllegalArgumentException("The pattern must not be null.");
}
this.pattern = pattern;
parsePattern(this.pattern);
} | java |
private void parsePattern(String pattern){
int currentIndex = 0;
int patternLength = pattern.length();
Vector<FormatCommandInterface> converterVector = new Vector<FormatCommandInterface>(20);
while (currentIndex < patternLength) {
char currentChar = pattern.charAt(currentIndex);
if (currentChar == '%')... | java |
@Beta
public static <K, V> Map<K, V> zip(List<K> keys, List<V> values) {
checkArgument(keys != null, "Expected non-null keys");
checkArgument(values != null, "Expected non-null values");
checkArgument(keys.size() == values.size(), "Expected equal size of lists, got %s and %s", keys.size(), v... | java |
@Beta
public static <K, V> Map.Entry<K, V> getOnlyEntry(Map<K, V> map) {
checkArgument(map != null, "Expected non-null map");
return getOnlyElement(map.entrySet());
} | java |
@Beta
public static <K, V> Map<K, V> mergeMaps(Map<K, V> first, Map<K, V> second, V defaultValue) {
checkArgument(first != null, "Expected non-null first map");
checkArgument(second != null, "Expected non-null second map");
checkArgument(defaultValue != null, "Expected non-null default value... | java |
public static <M extends PMessage<M,F>, F extends PField, B extends PMessageBuilder<M,F>>
List<M> buildAll(Collection<B> builders) {
if (builders == null) {
return null;
}
return builders.stream()
.map(PMessageBuilder::build)
.collect... | java |
@SuppressWarnings("unchecked")
public static <M extends PMessage<M,F>, F extends PField, B extends PMessageBuilder<M,F>>
List<B> mutateAll(Collection<M> messages) {
if (messages == null) {
return null;
}
return (List<B>) messages.stream()
.map... | java |
public static <M extends PMessage<M,F>, F extends PField, B extends PMessageBuilder<M,F>>
M buildIfNotNull(B builder) {
if (builder == null) {
return null;
}
return builder.build();
} | java |
@SuppressWarnings("unchecked")
public static <M extends PMessage<M,F>, F extends PField, B extends PMessageBuilder<M,F>>
B mutateIfNotNull(M message) {
if (message == null) {
return null;
}
return (B) message.mutate();
} | java |
static boolean isSupported(int index) {
if ((index <= 0) || (index >= NAMED_CURVE_OID_TABLE.length)) {
return false;
}
if (fips == false) {
// in non-FIPS mode, we support all valid indices
return true;
}
return DEFAULT.contains(index);
} | java |
public static <M extends PMessage<M,F>, F extends PField>
MessageFieldArgument<M,F> toField(M message, F field) {
return new MessageFieldArgument<>(message, field);
} | java |
public static <F extends PField> MappedField<F> withColumn(F field) {
return new MappedField<>(field.getName(), field);
} | java |
public static <F extends PField> MappedField<F> withColumn(String name, F field) {
return new MappedField<>(name, field);
} | java |
@Override
public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms, AuthenticationToken token) throws AuthenticationException {
final SimpleAuthenticationInfo authenticationInfo = (SimpleAuthenticationInfo) super.beforeAllAttempts(realms, token);
authenticationInfo.setPrincipa... | java |
protected final void set(M config) {
ArrayList<WeakReference<ConfigListener<M,F>>> iterateOver;
synchronized (this) {
M old = instance.get();
if (old == config || (old != null && old.equals(config))) {
return;
}
instance.set(config);
... | java |
private List<AgigaTypedDependency> parseDependencies(VTDNav vn, DependencyForm form) throws NavException,
PilotException {
require (vn.matchElement(AgigaConstants.SENTENCE));
// Move to the <basic-deps> tag
require (vn.toElement(VTDNav.FC, form.getXmlTag()));
List<AgigaType... | java |
public void configure(String filename, boolean isExternalFile) {
try {
Properties properties;
InputStream inputStream;
if (!isExternalFile) {
Resources resources = context.getResources();
AssetManager assetManager = resources.getAssets();
... | java |
public void configure(int resId) {
Resources resources = context.getResources();
try {
InputStream rawResource = resources.openRawResource(resId);
Properties properties = loadProperties(rawResource);
startConfiguration(properties);
} catch (NotFoundException ... | java |
private void startConfiguration(Properties properties) {
if (properties.containsKey(Configurator.ROOT_LOGGER_KEY)) {
Log.i(TAG, "Modern configuration not yet supported");
} else {
Log.i(TAG, "Configure using the simple style (aka classic style)");
configureSimpleStyl... | java |
void setVersion(ProtocolVersion protocolVersion) {
this.protocolVersion = protocolVersion;
setVersionSE(protocolVersion);
output.r.setVersion(protocolVersion);
} | java |
void activate(ProtocolVersion helloVersion) throws IOException {
if (activeProtocols == null) {
activeProtocols = getActiveProtocols();
}
if (activeProtocols.collection().isEmpty() ||
activeProtocols.max.v == ProtocolVersion.NONE.v) {
throw new SSLHandsha... | java |
boolean isNegotiable(CipherSuite s) {
if (activeCipherSuites == null) {
activeCipherSuites = getActiveCipherSuites();
}
return activeCipherSuites.contains(s) && s.isNegotiable();
} | java |
boolean isNegotiable(ProtocolVersion protocolVersion) {
if (activeProtocols == null) {
activeProtocols = getActiveProtocols();
}
return activeProtocols.contains(protocolVersion);
} | java |
ProtocolVersion selectProtocolVersion(ProtocolVersion protocolVersion) {
if (activeProtocols == null) {
activeProtocols = getActiveProtocols();
}
return activeProtocols.selectProtocolVersion(protocolVersion);
} | java |
CipherSuiteList getActiveCipherSuites() {
if (activeCipherSuites == null) {
if (activeProtocols == null) {
activeProtocols = getActiveProtocols();
}
ArrayList<CipherSuite> suites = new ArrayList<>();
if (!(activeProtocols.collection().isEmpty()) &... | java |
CipherBox newReadCipher() throws NoSuchAlgorithmException {
BulkCipher cipher = cipherSuite.cipher;
CipherBox box;
if (isClient) {
box = cipher.newCipher(protocolVersion, svrWriteKey, svrWriteIV,
sslContext.getSecureRandom(), false);
svr... | java |
MAC newReadMAC() throws NoSuchAlgorithmException, InvalidKeyException {
MacAlg macAlg = cipherSuite.macAlg;
MAC mac;
if (isClient) {
mac = macAlg.newMac(protocolVersion, svrMacSecret);
svrMacSecret = null;
} else {
mac = macAlg.newMac(protocolVersion, ... | java |
static void throwSSLException(String msg, Throwable cause)
throws SSLException {
SSLException e = new SSLException(msg);
e.initCause(cause);
throw e;
} | java |
static Object getInMessage(PMessage message, String key) throws ProvidenceConfigException {
return getInMessage(message, key, null);
} | java |
static Object getInMessage(PMessage message, final String key, Object defValue)
throws ProvidenceConfigException {
String sub = key;
String name;
PMessageDescriptor descriptor = message.descriptor();
while (sub.contains(".")) {
int idx = sub.indexOf(".");
... | java |
static double asDouble(Object value) throws ProvidenceConfigException {
if (value instanceof Number) {
return ((Number) value).doubleValue();
} else if (value instanceof Numeric) {
return ((Numeric) value).asInteger();
}
throw new ProvidenceConfigException(
... | java |
static String asString(Object value) throws ProvidenceConfigException {
if (value instanceof Collection || value instanceof Map) {
throw new ProvidenceConfigException(
"Unable to convert " + value.getClass().getSimpleName() + " to a string");
} else if (value instanceof S... | java |
static Path resolveFile(Path reference, String path) throws IOException {
if (reference == null) {
Path file = canonicalFileLocation(Paths.get(path));
if (Files.exists(file)) {
if (Files.isRegularFile(file)) {
return file;
}
... | java |
public static int getNextAvailablePort(int fromPort, int toPort) {
if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER || fromPort > toPort) {
throw new IllegalArgumentException(format("Invalid port range: %d ~ %d", fromPort, toPort));
}
int nextPort = fromPort;
//noi... | java |
public static boolean isPortAvailable(int port) {
StringBuilder builder = new StringBuilder();
builder.append("Testing port ").append(port).append("\n");
try (Socket s = new Socket("localhost", port)) {
// If the code makes it this far without an exception it means
// som... | java |
@Nonnull
public Collection<F> presentFields() {
return Arrays.stream(descriptor().getFields())
.filter(this::isSet)
.collect(Collectors.toList());
} | java |
@Nonnull
public Collection<F> modifiedFields() {
return Arrays.stream(descriptor().getFields())
.filter(this::isModified)
.collect(Collectors.toList());
} | java |
public static <T extends Enum<T> & RichEnum<T>> RichEnumConstants<T> richConstants(Class<T> theClass) {
return new RichEnumConstants<>(theClass);
} | java |
@JsonAnySetter
public void putConfigurationValue(String key, Object value) {
this.configuration.put(key, value);
} | java |
@javax.annotation.Nonnull
public java.util.Optional<String> optionalFilePath() {
return java.util.Optional.ofNullable(mFilePath);
} | java |
@javax.annotation.Nonnull
public java.util.Optional<java.util.List<String>> optionalFileLines() {
return java.util.Optional.ofNullable(mFileLines);
} | java |
@javax.annotation.Nonnull
public java.util.Optional<net.morimekta.providence.model.ProgramType> optionalProgram() {
return java.util.Optional.ofNullable(mProgram);
} | java |
@Nonnull
public ProgramTypeRegistry registryForPath(String path) {
return registryMap.computeIfAbsent(path, p -> new ProgramTypeRegistry(programNameFromPath(path)));
} | java |
public boolean containsProgramPath(String path) {
return registryMap.containsKey(path) && registryMap.get(path).getProgram() != null;
} | java |
public void completeFrame() throws IOException {
int frameSize = buffer.position();
if (frameSize > 0) {
frameSizeBuffer.rewind();
try (ByteBufferOutputStream bos = new ByteBufferOutputStream(frameSizeBuffer);
BinaryWriter writer = new BigEndianBinaryWriter(bos))... | java |
public synchronized void put(ApnsConnection connection) {
if (connection == null) {
throw new IllegalArgumentException("connection must not be null");
}
if (mPool.size() < mCapacity) {
mPool.add(connection);
}
} | java |
public static HashCode newHash(String input, HashFunction function) {
return function.hashString(input, Charsets.UTF_8);
} | java |
private static boolean equalsQualifiedName(PDescriptor a, PDescriptor b) {
return (a != null) && (b != null) && (a.getQualifiedName()
.equals(b.getQualifiedName()));
} | java |
private boolean setupPrivateKeyAndChain(String algorithm) {
X509ExtendedKeyManager km = sslContext.getX509KeyManager();
String alias;
if (conn != null) {
alias = km.chooseServerAlias(algorithm, null, conn);
} else {
alias = km.chooseEngineServerAlias(algorithm, nu... | java |
private boolean setupKerberosKeys() {
if (kerberosKeys != null) {
return true;
}
try {
final AccessControlContext acc = getAccSE();
kerberosKeys = AccessController.doPrivileged(
// Eliminate dependency on KerberosKey
new Privile... | java |
@Programmatic
public boolean implies(final ApplicationFeatureId featureId, final ApplicationPermissionMode mode) {
if(getRule() != ApplicationPermissionRule.ALLOW) {
// only allow rules can imply
return false;
}
if(getMode() == ApplicationPermissionMode.VIEWING && mod... | java |
public static PPrimitive findByName(String name) {
switch (name) {
case "void":
return VOID;
case "bool":
return BOOL;
case "byte":
case "i8":
return BYTE;
case "i16":
return I16;
... | java |
public String execute(String clientID, String name, long time, Level level,
Object message, Throwable throwable){
StringBuilder sb = new StringBuilder();
if (throwable != null) {
sb.append(throwable.toString());
String newline = System.getProperty("line.separator");
StackTraceElement[] stackTrace... | java |
public String createMessageData(String message) {
messageStringBuffer.delete(0, messageStringBuffer.length());
// Create the PRI part
messageStringBuffer.append('<');
int priority = facility * 8 + severity;
messageStringBuffer.append(priority);
messageStringBuffer.append('>');
// Create the HEADER part... | java |
public void setFacility(byte facility) {
if (facility < SyslogMessage.FACILITY_KERNAL_MESSAGE
|| facility > SyslogMessage.FACILITY_LOCAL_USE_7) {
throw new IllegalArgumentException("Not a valid facility.");
}
this.facility = facility;
} | java |
public void setSeverity(byte severity) throws IllegalArgumentException {
if (severity < SyslogMessage.SEVERITY_EMERGENCY
|| severity > SyslogMessage.SEVERITY_DEBUG) {
throw new IllegalArgumentException("Not a valid severity.");
}
this.severity = severity;
} | java |
public void setTag(String tag) throws IllegalArgumentException {
if (tag == null
|| (tag != null && (tag.length() < 1 || tag.length() > 32))) {
throw new IllegalArgumentException(
"The tag must not be null, the length between 1..32");
}
this.tag = tag;
} | java |
public static Properties getFileAsProperties(String path) {
File file = new File(nullToEmpty(path));
return getFileAsProperties(file);
} | java |
@javax.annotation.Nonnull
public java.util.Optional<net.morimekta.util.Binary> optionalData() {
return java.util.Optional.ofNullable(mData);
} | java |
private void reload() {
try {
if (!configFile.exists()) {
LOGGER.warn("Config file deleted " + configFile + ", keeping old config.");
return;
}
LOGGER.trace("Config reload triggered for " + configFile);
if (parentSupplier != null) {... | java |
public static <Message extends PMessage<Message, Field>, Field extends PField>
Message readMessage(BigEndianBinaryReader input,
PMessageDescriptor<Message, Field> descriptor,
boolean strict) throws IOException {
PMessageBuilder<Message, Field> builder = descri... | java |
public static void consumeMessage(BigEndianBinaryReader in) throws IOException {
FieldInfo fieldInfo;
while ((fieldInfo = readFieldInfo(in)) != null) {
readFieldValue(in, fieldInfo, null, false);
}
} | java |
public static <Message extends PMessage<Message, Field>, Field extends PField>
int writeMessage(BigEndianBinaryWriter writer, Message message)
throws IOException {
if (message instanceof BinaryWriter) {
return ((BinaryWriter) message).writeBinary(writer);
}
int len =... | java |
protected void register(Serializer serializer, String... mediaTypes) {
for (String mediaType : mediaTypes) {
this.serializerMap.put(mediaType, serializer);
}
} | java |
public String getContentLocation() {
String[] values = getMimeHeader("Content-Location");
if (values != null && values.length > 0)
return values[0];
return null;
} | java |
public String readBinary(char end) throws IOException {
int startOffset = bufferOffset;
int startLinePos = linePos;
CharArrayWriter baos = new CharArrayWriter();
while (readNextChar()) {
if (lastChar == end) {
lastChar = 0;
return baos.toString... | java |
public static ApplicationFeatureViewModel newViewModel(
final ApplicationFeatureId featureId,
final ApplicationFeatureRepositoryDefault applicationFeatureRepository,
final DomainObjectContainer container) {
final Class<? extends ApplicationFeatureViewModel> cls = viewModelCla... | java |
@Property(
domainEvent = MemberNameDomainEvent.class
)
@PropertyLayout(typicalLength=ApplicationFeature.TYPICAL_LENGTH_MEMBER_NAME)
@MemberOrder(name="Id", sequence = "2.4")
public String getMemberName() {
return getFeatureId().getMemberName();
} | java |
@Programmatic
public ApplicationFeatureViewModel getParentPackage() {
return Functions.asViewModelForId(applicationFeatureRepository, container).apply(getFeatureId().getParentPackageId());
} | java |
@Programmatic
public ApplicationUser findByUsernameCached(final String username) {
return queryResultsCache.execute(new Callable<ApplicationUser>() {
@Override public ApplicationUser call() throws Exception {
return findByUsername(username);
}
}, ApplicationUs... | java |
@Programmatic
public List<ApplicationUser> findByAtPath(final String atPath) {
return container.allMatches(new QueryDefault<>(
ApplicationUser.class,
"findByAtPath", "atPath", atPath));
} | java |
@SuppressWarnings("unchecked")
private static <V> V resolve(ProvidenceConfigContext context,
Token token,
Tokenizer tokenizer,
PDescriptor descriptor) throws TokenizerException {
Object value = resolveAny(cont... | java |
public static ClassLoader getContextClassLoader(Class<?> contextClass) {
return Objects.firstNonNull(
Thread.currentThread().getContextClassLoader(),
contextClass.getClassLoader()
);
} | java |
public static String buildPath(String first, String... parts) {
StringBuilder result = new StringBuilder(first);
for (String part : parts) {
if (result.length() == 0) {
if (part.startsWith("/")) {
result.append(part.substring(1));
} else {... | java |
private TokenType lexUtf8Char(Bytes jsonText, int curChar) {
if (curChar <= 0x7f) {
/* single byte */
return STRING;
} else if ((curChar >> 5) == 0x6) {
/* two byte */
if (jsonText.readRemaining() == 0) return EOF;
curChar = readChar(jsonText)... | java |
private TokenType lexString(Bytes jsonText) {
TokenType tok = ERROR;
boolean hasEscapes = false;
finish_string_lex:
for (;;) {
int curChar;
/* now jump into a faster scanning routine to skip as much
* of the buffers as possible */
{
... | java |
@Beta
public static <T> Predicate<T> nor(Predicate<? super T> first, Predicate<? super T> second) {
return com.google.common.base.Predicates.not(com.google.common.base.Predicates.or(first, second));
} | java |
public JsonParserBuilder options(JsonParserOption first, JsonParserOption... rest) {
this.options = EnumSet.of(first, rest);
return this;
} | java |
public JsonParserBuilder applyAdapter(JsonHandlerBase a) {
boolean applied = false;
if (a instanceof ObjectStartHandler) {
objectStartHandler((ObjectStartHandler) a);
applied = true;
}
if (a instanceof ObjectEndHandler) {
objectEndHandler((ObjectEndHan... | java |
public static String camelCase(String prefix, String name) {
return Strings.camelCase(prefix, name);
} | java |
public static String macroCase(String name) {
return Strings.c_case(name).toUpperCase(Locale.US);
} | java |
public static void ensure(boolean condition, String message, Object... args) {
if (!condition) {
throw new EnsureViolation(format(message, args));
}
} | java |
public void reset() {
lexer.reset();
stateStack.clear();
stateStack.push(START);
parseError = null;
if (resetHook != null)
resetHook.onReset();
} | java |
public boolean finish() {
if (!parse(finishSpace())) return false;
switch(stateStack.current()) {
case PARSE_ERROR:
case LEXICAL_ERROR:
case HANDLER_CANCEL:
case HANDLER_EXCEPTION:
throw new AssertionError("exception should be thrown direc... | java |
public static String asString(byte id) {
switch (id) {
case STOP:
return "stop(0)";
case VOID:
return "void(1)";
case BOOL:
return "bool(2)";
case BYTE:
return "byte(3)";
case DOUBLE:
... | java |
public MediaItem getMediaItem(String id) {
DailyMotionUrl url = new DailyMotionUrl(requestPrefix + id);
HttpRequest request;
try {
request = requestFactory.buildGetRequest(url);
DailyMotionVideo video = request.execute().parseAs(DailyMotionVideo.class);
if(video != null) {
MediaItem mediaIt... | java |
String toAbsoluteFormat(long time){
calendar.setTime(new Date(time));
long hours = calendar.get(Calendar.HOUR_OF_DAY);
StringBuffer buffer = new StringBuffer();
if (hours < 10) {
buffer.append('0');
}
buffer.append(hours);
buffer.append(':');
long minutes = calendar.get(Calendar.MINUTE);
if (mi... | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.