_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q19200
Beans.classForName
train
public static Class<?> classForName(String name) throws ClassNotFoundException { if ("void".equals(name)) return void.class; if ("char".equals(name)) return char.class; if ("boolean".equals(name)) return boolean.class; if ("byte".equals(name)) return byte.class; if ("short".equals(name)) return short.class; if ("int".equals(name)) return int.class; if ("long".equals(name)) return long.class; if ("float".equals(name)) return float.class; if ("double".equals(name)) return double.class; return Class.forName(name, true, Thread.currentThread().getContextClassLoader()); }
java
{ "resource": "" }
q19201
Beans.toPrimitive
train
public static Class<?> toPrimitive(Class<?> type) { if (type.isPrimitive()) { return type; } else if (type == Boolean.class) { return Boolean.TYPE; } else if (type == Character.class) { return Character.TYPE; } else if (type == Byte.class) { return Byte.TYPE; } else if (type == Short.class) { return Short.TYPE; } else if (type == Integer.class) { return Integer.TYPE; } else if (type == Long.class) { return Long.TYPE; } else if (type == Float.class) { return Float.TYPE; } else if (type == Double.class) { return Double.TYPE; } else { return null; } }
java
{ "resource": "" }
q19202
Beans.boxPrimitives
train
public static Class<?>[] boxPrimitives(Class<?>[] types) { for (int i = 0; i < types.length; ++i) { types[i] = boxPrimitive(types[i]); } return types; }
java
{ "resource": "" }
q19203
Beans.getKnownField
train
public static Field getKnownField(Class<?> type, String name) throws NoSuchFieldException { NoSuchFieldException last = null; do { try { Field field = type.getDeclaredField(name); field.setAccessible(true); return field; } catch (NoSuchFieldException x) { last = x; type = type.getSuperclass(); } } while (type != null); throw last; }
java
{ "resource": "" }
q19204
Beans.accessible
train
public static <T extends AccessibleObject> T accessible(T object) throws SecurityException { object.setAccessible(true); return object; }
java
{ "resource": "" }
q19205
Beans.setValue
train
@SuppressWarnings("unchecked") public static void setValue(Object object, Field field, Object value) throws IllegalArgumentException, IllegalAccessException { if (value == null) { //if (Number.class.isAssignableFrom(field.getType())) { //value = java.math.BigDecimal.ZERO; //} else return; return; } try { field.setAccessible(true); field.set(object, value); } catch (IllegalArgumentException x) { if (value instanceof Number) { // size of "value" bigger than that of "field"? try { Number number = (Number)value; Class<?> ftype = field.getType(); if (Enum.class.isAssignableFrom(ftype)) { field.set(object, ftype.getEnumConstants()[number.intValue()]); } else if (BigDecimal.class.isAssignableFrom(ftype)) { field.set(object, BigDecimal.valueOf(number.doubleValue())); } else if (BigInteger.class.isAssignableFrom(ftype)) { field.set(object, BigInteger.valueOf(number.longValue())); } else if (Double.TYPE == ftype || Double.class.isAssignableFrom(ftype)) { field.set(object, number.doubleValue()); } else if (Float.TYPE == ftype || Float.class.isAssignableFrom(ftype)) { field.set(object, number.floatValue()); } else if (Long.TYPE == ftype || Long.class.isAssignableFrom(ftype)) { field.set(object, number.longValue()); } else if (Integer.TYPE == ftype || Integer.class.isAssignableFrom(ftype)) { field.set(object, number.intValue()); } else if (Short.TYPE == ftype || Short.class.isAssignableFrom(ftype)) { field.set(object, number.shortValue()); } else { field.set(object, number.byteValue()); } } catch (Throwable t) { throw new IllegalArgumentException(t); } } else if (value instanceof java.sql.Timestamp) { try { field.set(object, new java.sql.Date(((java.sql.Timestamp)value).getTime())); } catch (Throwable t) { throw new IllegalArgumentException(t); } } else if (value instanceof String) { field.set(object, new ValueOf(field.getType(), field.getAnnotation(typeinfo.class)).invoke((String)value)); } else { throw x; } } }
java
{ "resource": "" }
q19206
Beans.fill
train
public static <T> T fill(T destination, Object source) { if (destination != source) { Class<?> stype = source.getClass(); for (Field field: destination.getClass().getFields()) { try { Object value = field.get(destination); if (value == null) { field.set(destination, stype.getField(field.getName()).get(source)); } } catch (Exception x) { } } } return destination; }
java
{ "resource": "" }
q19207
Beans.update
train
public static <T, V> T update(T object, Class<V> type, String pattern, Bifunctor<V, String, V> updater) { if (type.isPrimitive()) { throw new IllegalArgumentException("Primitive type must be boxed"); } Pattern regex = pattern != null ? Pattern.compile(pattern) : null; for (Field field: object.getClass().getFields()) { if ((regex == null || regex.matcher(field.getName()).matches()) && type.isAssignableFrom(boxPrimitive(field.getType()))) { try { field.set(object, updater.invoke(field.getName(), type.cast(field.get(object)))); } catch (Exception x) {} } } return object; }
java
{ "resource": "" }
q19208
Beans.print
train
public static StringBuilder print(StringBuilder sb, Object bean, int level) throws IntrospectionException { return print(sb, Collections.newSetFromMap(new IdentityHashMap<Object, Boolean>()), bean, level); }
java
{ "resource": "" }
q19209
ImplementationLoader.get
train
public static <E> E get(Class<E> type) { ServiceLoader<E> loader = ServiceLoader.load(type); Iterator<E> iterator = loader.iterator(); if (iterator.hasNext()) { return iterator.next(); // only one is expected } try { //loads the default implementation return (E) Class.forName(getDefaultImplementationName(type)).newInstance(); } catch (Exception e) { throw new TruggerException(e); } }
java
{ "resource": "" }
q19210
PriceGraduation.createSimple
train
@Nonnull public static IMutablePriceGraduation createSimple (@Nonnull final IMutablePrice aPrice) { final PriceGraduation ret = new PriceGraduation (aPrice.getCurrency ()); ret.addItem (new PriceGraduationItem (1, aPrice.getNetAmount ().getValue ())); return ret; }
java
{ "resource": "" }
q19211
ServicePlatform.contextInitialized
train
@Override public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); _dict.addTypeSet(org.xillium.data.validation.StandardDataTypes.class); _packaged = _context.getResourcePaths("/WEB-INF/lib/"); _extended = discover(System.getProperty("xillium.service.ExtensionsRoot")); // servlet mappings must be registered before this method returns Functor<Void, ServiceModule> functor = new Functor<Void, ServiceModule>() { public Void invoke(ServiceModule module) { _context.getServletRegistration("dispatcher").addMapping("/" + module.simple + "/*"); return null; } }; ServiceModule.scan(_context, _packaged, functor, _logger); ServiceModule.scan(_context, _extended, functor, _logger); try { XmlWebApplicationContext wac = new XmlWebApplicationContext(); wac.setServletContext(_context); wac.refresh(); wac.start(); try { // let the life cycle control take over PlatformControl controlling = wac.getBean(CONTROLLING, PlatformControl.class); ManagementFactory.getPlatformMBeanServer().registerMBean( controlling.bind(this, wac, Thread.currentThread().getContextClassLoader()), new ObjectName(controlling.getClass().getPackage().getName(), "type", controlling.getClass().getSimpleName()) ); if (controlling.isAutomatic()) { controlling.reload(); } } catch (BeansException x) { // go ahead with platform realization realize(wac, null); } catch (Exception x) { _logger.warning(Throwables.getFirstMessage(x)); } } catch (BeanDefinitionStoreException x) { _logger.warning(Throwables.getFirstMessage(x)); } }
java
{ "resource": "" }
q19212
ServicePlatform.realize
train
public void realize(ApplicationContext wac, ConfigurableApplicationContext child) { if (WebApplicationContextUtils.getWebApplicationContext(_context) == null) { _context.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); } else { _logger.warning("Already realized"); return; } if (child != null) wac = child; ServiceModuleInfo info = new ServiceModuleInfo(); if (wac.containsBean(PERSISTENCE)) { // persistence may not be there if persistent storage is not required info.persistence.first = info.persistence.second = (Persistence)wac.getBean(PERSISTENCE); _persistences.put("-", info.persistence.first); } _logger.log(Level.CONFIG, "install packaged modules"); wac = install(wac, sort(_context, _packaged), info); _logger.log(Level.CONFIG, "install extension modules"); wac = install(wac, sort(_context, _extended), info); _logger.log(Level.CONFIG, "install service augmentations"); for (ServiceAugmentation fi: info.augmentations) { fi.install(_registry); } String hide = System.getProperty("xillium.service.HideDescription"); if (hide == null || hide.length() == 0) { _registry.put("x!/desc", new Pair<Service, Persistence>(new DescService(info.descriptions), info.persistence.first)); _registry.put("x!/list", new Pair<Service, Persistence>(new ListService(_registry), info.persistence.first)); } _registry.put("x!/ping", new Pair<Service, Persistence>(new PingService(), info.persistence.first)); if (System.getProperty("xillium.persistence.DisablePrecompilation") == null) { for (Persistence persistence: _persistences.values()) { if (persistence.getTransactionManager() != null) { persistence.doReadWrite(null, new Persistence.Task<Void, Void>() { public Void run(Void facility, Persistence persistence) throws Exception { _logger.info("parametric statements compiled: " + persistence.compile()); return null; } }); } else { _logger.warning("Persistence precompilation is ON (default) but TransactionManager is not configured"); } } } }
java
{ "resource": "" }
q19213
ServicePlatform.destroy
train
public void destroy() { XmlWebApplicationContext wac = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(_context); if (wac != null) { _context.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); } else { _logger.warning("Nothing more to destroy"); return; } _logger.info("<<<< Service Platform(" + _application + ") destruction starting"); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); while (!_manageables.empty()) { ObjectName on = _manageables.pop(); _logger.info("<<<<<<<< MBean(" + on + ") unregistration starting"); try { mbs.unregisterMBean(on); } catch (Exception x) { _logger.log(Level.WARNING, on.toString()); } _logger.info("<<<<<<<< MBean(" + on + ") unregistration complete"); } while (!_plca.empty()) { List<Pair<String, PlatformAware>> plcas = _plca.pop(); for (Pair<String, PlatformAware> plca: plcas) { _logger.info("<<<<<<<< PlatformAware(" + plca.first + '/' + plca.second.getClass().getName() + ") termination starting"); plca.second.terminate(_application, plca.first); _logger.info("<<<<<<<< PlatformAware(" + plca.first + '/' + plca.second.getClass().getName() + ") termination complete"); } } // finally, deregisters JDBC driver manually to prevent Tomcat 7 from complaining about memory leaks Enumeration<java.sql.Driver> drivers = java.sql.DriverManager.getDrivers(); while (drivers.hasMoreElements()) { java.sql.Driver driver = drivers.nextElement(); _logger.info("<<<<<<<< JDBC Driver(" + driver + ") deregistration starting"); try { java.sql.DriverManager.deregisterDriver(driver); } catch (java.sql.SQLException x) { _logger.log(Level.WARNING, "Error deregistering driver " + driver, x); } _logger.info("<<<<<<<< JDBC Driver(" + driver + ") deregistration complete"); } for (Iterator<String> it = _registry.keySet().iterator(); it.hasNext();) { if (!it.next().startsWith("x!/")) it.remove(); } _registry.remove("x!/ping"); _registry.remove("x!/list"); _registry.remove("x!/desc"); while (!_applc.empty()) { _applc.pop().close(); } wac.close(); _logger.info("<<<< Service Platform(" + _application + ") destruction complete"); }
java
{ "resource": "" }
q19214
ServicePlatform.install
train
private ApplicationContext install(ApplicationContext wac, ModuleSorter.Sorted sorted, ServiceModuleInfo info) { // scan special modules, configuring and initializing PlatformAware objects as each module is loaded wac = install(wac, sorted.specials(), info, true); // scan regular modules, collecting all PlatformAware objects install(wac, sorted.regulars(), info, false); if (info.plcas.size() > 0) { _logger.info("configure PlatformAware objects in regular modules"); for (Pair<String, PlatformAware> plca: info.plcas) { _logger.info("Configuring REGULAR PlatformAware " + plca.second.getClass().getName()); plca.second.configure(_application, plca.first); } _logger.info("initialize PlatformAware objects in regular modules"); for (Pair<String, PlatformAware> plca: info.plcas) { _logger.info("Initalizing REGULAR PlatformAware " + plca.second.getClass().getName()); plca.second.initialize(_application, plca.first); } _plca.push(info.plcas); info.plcas = new ArrayList<Pair<String, PlatformAware>>(); } else { _logger.info("No PlatformAware objects in regular modules"); } return wac; }
java
{ "resource": "" }
q19215
Persistence.doReadOnly
train
public <T, F> T doReadOnly(F facility, Task<T, F> task) { return doTransaction(facility, task, _readonly); }
java
{ "resource": "" }
q19216
Persistence.doReadWrite
train
public <T, F> T doReadWrite(F facility, Task<T, F> task) { return doTransaction(facility, task, null); }
java
{ "resource": "" }
q19217
Persistence.getParametricStatement
train
public ParametricStatement getParametricStatement(String name) { ParametricStatement statement = _statements.get(name); if (statement != null) { return statement; } else { throw new RuntimeException("ParametricStatement '" + name + "' not found"); } }
java
{ "resource": "" }
q19218
Persistence.executeSelect
train
public <T> T executeSelect(String name, DataObject object, ResultSetWorker<T> worker) throws Exception { ParametricQuery statement = (ParametricQuery)_statements.get(name); if (statement != null) { return statement.executeSelect(DataSourceUtils.getConnection(_dataSource), object, worker); } else { throw new RuntimeException("ParametricQuery '" + name + "' not found"); } }
java
{ "resource": "" }
q19219
Persistence.getResults
train
public <T extends DataObject> List<T> getResults(String name, DataObject object) throws Exception { @SuppressWarnings("unchecked") ObjectMappedQuery<T> statement = (ObjectMappedQuery<T>)_statements.get(name); if (statement != null) { return statement.getResults(DataSourceUtils.getConnection(_dataSource), object); } else { throw new RuntimeException("ObjectMappedQuery '" + name + "' not found"); } }
java
{ "resource": "" }
q19220
Persistence.compile
train
public int compile() throws SQLException { int count = 0; for (Map.Entry<String, ParametricStatement> entry: _statements.entrySet()) { try { ParametricStatement statement = entry.getValue(); Connection connection = DataSourceUtils.getConnection(_dataSource); if (statement instanceof ParametricQuery) { connection.prepareStatement(statement.getSQL()); } else { try { connection.prepareCall(statement.getSQL()); } catch (Exception x) { connection.prepareStatement(statement.getSQL()); } } ++count; } catch (SQLException x) { throw new SQLException(entry.getKey(), x); } } return count; }
java
{ "resource": "" }
q19221
ProfileWriterImpl.addPackageDeprecationInfo
train
public void addPackageDeprecationInfo(Content li, PackageDoc pkg) { Tag[] deprs; if (Util.isDeprecated(pkg)) { deprs = pkg.tags("deprecated"); HtmlTree deprDiv = new HtmlTree(HtmlTag.DIV); deprDiv.addStyle(HtmlStyle.deprecatedContent); Content deprPhrase = HtmlTree.SPAN(HtmlStyle.deprecatedLabel, deprecatedPhrase); deprDiv.addContent(deprPhrase); if (deprs.length > 0) { Tag[] commentTags = deprs[0].inlineTags(); if (commentTags.length > 0) { addInlineDeprecatedComment(pkg, deprs[0], deprDiv); } } li.addContent(deprDiv); } }
java
{ "resource": "" }
q19222
ProfileWriterImpl.getNavLinkPrevious
train
public Content getNavLinkPrevious() { Content li; if (prevProfile == null) { li = HtmlTree.LI(prevprofileLabel); } else { li = HtmlTree.LI(getHyperLink(pathToRoot.resolve(DocPaths.profileSummary( prevProfile.name)), prevprofileLabel, "", "")); } return li; }
java
{ "resource": "" }
q19223
ProfileWriterImpl.getNavLinkNext
train
public Content getNavLinkNext() { Content li; if (nextProfile == null) { li = HtmlTree.LI(nextprofileLabel); } else { li = HtmlTree.LI(getHyperLink(pathToRoot.resolve(DocPaths.profileSummary( nextProfile.name)), nextprofileLabel, "", "")); } return li; }
java
{ "resource": "" }
q19224
TypeVariableImpl.owner
train
public ProgramElementDoc owner() { Symbol osym = type.tsym.owner; if ((osym.kind & Kinds.TYP) != 0) { return env.getClassDoc((ClassSymbol)osym); } Names names = osym.name.table.names; if (osym.name == names.init) { return env.getConstructorDoc((MethodSymbol)osym); } else { return env.getMethodDoc((MethodSymbol)osym); } }
java
{ "resource": "" }
q19225
ComponentBindingsProviderFactoryImpl.activate
train
protected void activate(final ComponentContext context) throws InvalidSyntaxException { log.info("activate"); bundleContext = context.getBundleContext(); sl = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.UNREGISTERING) { cache.unregisterComponentBindingsProvider(event .getServiceReference()); } else if (event.getType() == ServiceEvent.REGISTERED) { cache.registerComponentBindingsProvider(event .getServiceReference()); } } }; bundleContext.addServiceListener(sl, "(" + Constants.OBJECTCLASS + "=" + ComponentBindingsProvider.class.getName() + ")"); reloadCache(); log.info("Activation successful"); }
java
{ "resource": "" }
q19226
ComponentBindingsProviderFactoryImpl.deactivate
train
protected void deactivate(ComponentContext context) { log.info("deactivate"); bundleContext = context.getBundleContext(); bundleContext.removeServiceListener(sl); log.info("Deactivate successful"); }
java
{ "resource": "" }
q19227
ComponentBindingsProviderFactoryImpl.reloadCache
train
protected void reloadCache() { log.info("reloadCache"); cache.clear(); try { ServiceReference[] references = bundleContext .getAllServiceReferences( ComponentBindingsProvider.class.getCanonicalName(), null); if (references != null) { for (ServiceReference reference : references) { cache.registerComponentBindingsProvider(reference); } } } catch (Exception e) { log.error( "Exception reloading cache of component binding providers", e); } }
java
{ "resource": "" }
q19228
DocLocale.htmlSentenceTerminatorFound
train
private boolean htmlSentenceTerminatorFound(String str, int index) { for (int i = 0; i < sentenceTerminators.length; i++) { String terminator = sentenceTerminators[i]; if (str.regionMatches(true, index, terminator, 0, terminator.length())) { return true; } } return false; }
java
{ "resource": "" }
q19229
JavacTrees.getOriginalType
train
public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) { if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) { return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType(); } return com.sun.tools.javac.code.Type.noType; }
java
{ "resource": "" }
q19230
JavaMailService.createBodyPart
train
private static MimeBodyPart createBodyPart(byte[] data, String type, String filename) throws MessagingException { final MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setFileName(filename); ByteArrayDataSource source = new ByteArrayDataSource(data, type); attachmentPart.setDataHandler(new DataHandler(source)); attachmentPart.setHeader("Content-ID", createContentID(filename)); attachmentPart.setDisposition(MimeBodyPart.INLINE); return attachmentPart; }
java
{ "resource": "" }
q19231
ObjectMappedQuery.getObject
train
public T getObject(Connection conn, DataObject object) throws Exception { return executeSelect(conn, object, new ResultSetMapper<SingleObjectCollector<T>>(new SingleObjectCollector<T>())).value; }
java
{ "resource": "" }
q19232
ObjectMappedQuery.getResults
train
public Collector<T> getResults(Connection conn, DataObject object, Collector<T> collector) throws Exception { return executeSelect(conn, object, new ResultSetMapper<Collector<T>>(collector)); }
java
{ "resource": "" }
q19233
CacheFSInfo.preRegister
train
public static void preRegister(Context context) { context.put(FSInfo.class, new Context.Factory<FSInfo>() { public FSInfo make(Context c) { FSInfo instance = new CacheFSInfo(); c.put(FSInfo.class, instance); return instance; } }); }
java
{ "resource": "" }
q19234
InternalRequest.getContentType
train
public MediaType getContentType() { if (isNull(this.contentType)) { contentType = getHeader(HeaderName.CONTENT_TYPE) .map(MediaType::of) .orElse(WILDCARD); } return contentType; }
java
{ "resource": "" }
q19235
InternalRequest.getAccept
train
public List<MediaType> getAccept() { if (isNull(accept)) { List<MediaType> accepts = getHeader(HeaderName.ACCEPT) .map(MediaType::list) .get(); this.accept = nonEmpty(accepts) ? accepts : singletonList(WILDCARD); } return accept; }
java
{ "resource": "" }
q19236
TokenBasedVerifier.verify
train
public int verify(Request request, Response response) { String authValue = request.getHeaders().getValues("Authorization"); log.debug("Auth header value is: "+ authValue); if (authValue == null) { return Verifier.RESULT_MISSING; } String[] tokenValues = authValue.split(" "); if (tokenValues.length < 2) { return Verifier.RESULT_MISSING; } if (!"Bearer".equals(tokenValues[0])) { return Verifier.RESULT_INVALID; } String token = tokenValues[1]; log.debug("Token: "+ token); return checkToken(token); }
java
{ "resource": "" }
q19237
TypeAnnotations.organizeTypeAnnotationsSignatures
train
public void organizeTypeAnnotationsSignatures(final Env<AttrContext> env, final JCClassDecl tree) { annotate.afterRepeated( new Worker() { @Override public void run() { JavaFileObject oldSource = log.useSource(env.toplevel.sourcefile); try { new TypeAnnotationPositions(true).scan(tree); } finally { log.useSource(oldSource); } } } ); }
java
{ "resource": "" }
q19238
ClassUtils.classForNameWithException
train
public static Class<?> classForNameWithException(final String name, final ClassLoader cl) throws ClassNotFoundException { if (cl != null) { try { return Class.forName(name, false, cl); } catch (final ClassNotFoundException | NoClassDefFoundError e) { // fall through and try with default classloader } } return Class.forName(name); }
java
{ "resource": "" }
q19239
ClassUtils.getContextClassLoader
train
public static ClassLoader getContextClassLoader() { return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { ClassLoader cl = null; try { cl = Thread.currentThread().getContextClassLoader(); } catch (final SecurityException ex) { // fall through } return cl; } }); }
java
{ "resource": "" }
q19240
CompoundChannel.sendMessage
train
@Override public void sendMessage(String subject, String message) { first.sendMessage(subject, message); second.sendMessage(subject, message); }
java
{ "resource": "" }
q19241
FileColumn.getCellType
train
private short getCellType(String value) { short ret = STRING_TYPE; if(value.equals("number")) ret = NUMBER_TYPE; else if(value.equals("datetime")) ret = DATETIME_TYPE; else if(value.equals("boolean")) ret = BOOLEAN_TYPE; return ret; }
java
{ "resource": "" }
q19242
FileColumn.getDataType
train
private short getDataType(String value) { short ret = STRING_TYPE; if(value.equals("number")) ret = NUMBER_TYPE; else if(value.equals("integer")) ret = INTEGER_TYPE; else if(value.equals("decimal")) ret = DECIMAL_TYPE; else if(value.equals("seconds")) ret = SECONDS_TYPE; else if(value.equals("datetime")) ret = DATETIME_TYPE; else if(value.equals("boolean")) ret = BOOLEAN_TYPE; return ret; }
java
{ "resource": "" }
q19243
FileColumn.getAlignment
train
private short getAlignment(String value) { short ret = ALIGN_LEFT; if(value.equals("centre")) ret = ALIGN_CENTRE; else if(value.equals("left")) ret = ALIGN_LEFT; else if(value.equals("right")) ret = ALIGN_RIGHT; else if(value.equals("justify")) ret = ALIGN_JUSTIFY; else if(value.equals("fill")) ret = ALIGN_FILL; return ret; }
java
{ "resource": "" }
q19244
FileColumn.getCellFormat
train
public WritableCellFormat getCellFormat(boolean create) { WritableCellFormat ret = null; if(cellFormat != null) ret = cellFormat; else if(create) ret = new WritableCellFormat(NumberFormats.TEXT); return ret; }
java
{ "resource": "" }
q19245
FileColumn.convert
train
private String convert(String str, String dateFormat) { String ret = str; // Carry out the required string conversion long longValue = 0L; double doubleValue = 0.0d; // Convert the input value to a number if(str.length() > 0) { if(inputType == INTEGER_TYPE || inputType == NUMBER_TYPE) longValue = Long.parseLong(str); else if(inputType == DECIMAL_TYPE || inputType == SECONDS_TYPE) doubleValue = Double.parseDouble(str); else if(inputType == DATETIME_TYPE && inputFormat.length() > 0) longValue = parseDateTime(str, inputFormat); } // Convert seconds to milliseconds if(inputType == SECONDS_TYPE) doubleValue *= 1000.0d; // Allow for cross type conversions // eg. decimal->datetime, seconds->datetime if(inputType == DECIMAL_TYPE || inputType == SECONDS_TYPE) longValue = (long)doubleValue; else doubleValue = (double)longValue; // Convert the number to the output format if(outputType == INTEGER_TYPE) ret = Long.toString(longValue); else if(outputType == DECIMAL_TYPE || outputType == SECONDS_TYPE) ret = convertDecimal(doubleValue, outputFormat); else if(outputType == DATETIME_TYPE) ret = convertDateTime(longValue, outputFormat.length() > 0 ? outputFormat : dateFormat); else if(outputType == STRING_TYPE) ret = convertString(str, outputFormat, regex); return ret; }
java
{ "resource": "" }
q19246
FileColumn.parseDateTime
train
private long parseDateTime(String str, String format) { return FormatUtilities.getDateTime(str, format, false, true); }
java
{ "resource": "" }
q19247
FileColumn.convertDateTime
train
private String convertDateTime(long dt, String format) { if(format.length() == 0) format = Formats.DATETIME_FORMAT; return FormatUtilities.getFormattedDateTime(dt, format, false, 0L); }
java
{ "resource": "" }
q19248
FileColumn.convertDecimal
train
private String convertDecimal(double d, String format) { String ret = ""; if(format.length() > 0) { DecimalFormat f = new DecimalFormat(format); ret = f.format(d); } else { ret = Double.toString(d); } return ret; }
java
{ "resource": "" }
q19249
FileColumn.convertString
train
private String convertString(String str, String format, String expr) { String ret = str; String[] params = null; if(format.length() > 0) { ret = ""; if(expr.length() > 0) // Indicates a format using regex { Pattern pattern = getPattern(expr); Matcher m = pattern.matcher(str); if(m.find()) { params = new String[m.groupCount()]; for(int i = 0; i < m.groupCount(); i++) params[i] = m.group(i+1); } } else if(str != null) { params = new String[]{str}; } if(params != null) ret = String.format(format, params); } return ret; }
java
{ "resource": "" }
q19250
FileColumn.getPattern
train
private Pattern getPattern(String expr) { Pattern pattern = patterns.get(expr); if(pattern == null) { pattern = Pattern.compile(expr); patterns.put(expr, pattern); } return pattern; }
java
{ "resource": "" }
q19251
DocletInvoker.languageVersion
train
public LanguageVersion languageVersion() { try { Object retVal; String methodName = "languageVersion"; Class<?>[] paramTypes = new Class<?>[0]; Object[] params = new Object[0]; try { retVal = invoke(methodName, JAVA_1_1, paramTypes, params); } catch (DocletInvokeException exc) { return JAVA_1_1; } if (retVal instanceof LanguageVersion) { return (LanguageVersion)retVal; } else { messager.error(Messager.NOPOS, "main.must_return_languageversion", docletClassName, methodName); return JAVA_1_1; } } catch (NoClassDefFoundError ex) { // for boostrapping, no Enum class. return null; } }
java
{ "resource": "" }
q19252
DocletInvoker.invoke
train
private Object invoke(String methodName, Object returnValueIfNonExistent, Class<?>[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } }
java
{ "resource": "" }
q19253
ZipFileIndexCache.getZipFileIndexes
train
public synchronized List<ZipFileIndex> getZipFileIndexes(boolean openedOnly) { List<ZipFileIndex> zipFileIndexes = new ArrayList<ZipFileIndex>(); zipFileIndexes.addAll(map.values()); if (openedOnly) { for(ZipFileIndex elem : zipFileIndexes) { if (!elem.isOpen()) { zipFileIndexes.remove(elem); } } } return zipFileIndexes; }
java
{ "resource": "" }
q19254
ZipFileIndexCache.setOpenedIndexes
train
public synchronized void setOpenedIndexes(List<ZipFileIndex>indexes) throws IllegalStateException { if (map.isEmpty()) { String msg = "Setting opened indexes should be called only when the ZipFileCache is empty. " + "Call JavacFileManager.flush() before calling this method."; throw new IllegalStateException(msg); } for (ZipFileIndex zfi : indexes) { map.put(zfi.zipFile, zfi); } }
java
{ "resource": "" }
q19255
Qdb.close
train
public void close() throws IOException, QdbException { this.compoundRegistry.close(); this.propertyRegistry.close(); this.descriptorRegistry.close(); this.modelRegistry.close(); this.predictionRegistry.close(); try { this.storage.close(); } finally { this.storage = null; } try { if(this.tempDir != null){ FileUtil.deleteTempDirectory(this.tempDir); } } finally { this.tempDir = null; } }
java
{ "resource": "" }
q19256
ExceptionThrowerFactory.instance
train
public static ExceptionThrower instance(Class<? extends RuntimeException> classType) { iae.throwIfNull(classType, "The parameter of exception type can not be null."); if (classType.equals(IllegalArgumentException.class)) { return iae; } else { iae.throwIfTrue(true, "Not fond ExceptionThrower Utils for :", classType.getClass() .toString()); return null; } }
java
{ "resource": "" }
q19257
Pair.cleanse
train
@SuppressWarnings("unchecked") public static <T> T cleanse(T list, T element) { if (list == null || list == element) { return null; } else if (list instanceof Pair) { Pair<T, T> pair = (Pair<T, T>)list; if (pair.first == element) { return pair.second; } else if (pair.second == element) { return pair.first; } else if (pair.second instanceof Pair) { pair.second = cleanse(pair.second, element); } } return list; }
java
{ "resource": "" }
q19258
Pair.includes
train
@SuppressWarnings("unchecked") public static <T> boolean includes(T list, T element) { if (list == null) { return false; } else if (list == element) { return true; } else if (list instanceof Pair) { Pair<T, T> pair = (Pair<T, T>)list; if (pair.first == element || pair.second == element) { return true; } else if (pair.second instanceof Pair) { return includes(pair.second, element); } else { return false; } } else { return false; } }
java
{ "resource": "" }
q19259
Pair.count
train
@SuppressWarnings("unchecked") public static <T> int count(T list) { if (list == null) { return 0; } else if (list instanceof Pair) { return 1 + count(((Pair<T, T>)list).second); } else { return 1; } }
java
{ "resource": "" }
q19260
Pair.traverse
train
@SuppressWarnings("unchecked") public static <T> int traverse(T list, Functor<?, T> func) { if (list == null) { return 0; } else if (list instanceof Pair) { Pair<T, T> pair = (Pair<T, T>)list; func.invoke(pair.first); return 1 + traverse(pair.second, func); } else { func.invoke(list); return 1; } }
java
{ "resource": "" }
q19261
JSONBuilder.quote
train
public JSONBuilder quote(String value) { _sb.append('"'); for (int i = 0; i < value.length(); ++i) { char c = value.charAt(i); switch (c) { case '"': _sb.append("\\\""); break; case '\\': _sb.append("\\\\"); break; default: if (c < 0x20) { _sb.append(CTRLCHARS[c]); } else { _sb.append(c); } break; } } _sb.append('"'); return this; }
java
{ "resource": "" }
q19262
JSONBuilder.serialize
train
public JSONBuilder serialize(Object value) { if (value == null) { _sb.append("null"); } else { Class<?> t = value.getClass(); if (t.isArray()) { _sb.append('['); boolean hasElements = false; for (int i = 0, ii = Array.getLength(value); i < ii; ++i) { serialize(Array.get(value, i)); _sb.append(','); hasElements = true; } if (hasElements) { _sb.setCharAt(_sb.length()-1, ']'); } else { _sb.append(']'); } } else if (Iterable.class.isAssignableFrom(t)) { _sb.append('['); boolean hasElements = false; for (Object object: (Iterable<?>)value) { serialize(object); _sb.append(','); hasElements = true; } if (hasElements) { _sb.setCharAt(_sb.length()-1, ']'); } else { _sb.append(']'); } } else if (Number.class.isAssignableFrom(t) || Boolean.class.isAssignableFrom(t)) { _sb.append(value.toString()); } else if (String.class == t) { quote((String)value); } else { quote(value.toString()); } } return this; }
java
{ "resource": "" }
q19263
ExceptionThrower.createExceptionMessage
train
protected String createExceptionMessage(final String message, final Object... messageParameters) { if (ArrayUtils.isEmpty(messageParameters)) { return message; } else { return String.format(message, messageParameters); } }
java
{ "resource": "" }
q19264
PaymentRequest.get
train
public static ApruveResponse<PaymentRequest> get(String paymentRequestId) { return ApruveClient.getInstance().get( PAYMENT_REQUESTS_PATH + paymentRequestId, PaymentRequest.class); }
java
{ "resource": "" }
q19265
PaymentRequest.toSecureHash
train
public String toSecureHash() { String apiKey = ApruveClient.getInstance().getApiKey(); String shaInput = apiKey + toValueString(); return ShaUtil.getDigest(shaInput); }
java
{ "resource": "" }
q19266
AnnotationTypeElementDocImpl.defaultValue
train
public AnnotationValue defaultValue() { return (sym.defaultValue == null) ? null : new AnnotationValueImpl(env, sym.defaultValue); }
java
{ "resource": "" }
q19267
GUI.sessionReady
train
public void sessionReady(boolean isReady) { if (isReady) { speedSlider.setValue(session.getClockPeriod()); } startAction.setEnabled(isReady); speedSlider.setEnabled(isReady); stepAction.setEnabled(isReady); reloadAction.setEnabled(isReady); }
java
{ "resource": "" }
q19268
ReaderInputStream.mark
train
@Override public synchronized void mark(final int limit) { try { in.mark(limit); } catch (IOException ioe) { throw new RuntimeException(ioe.getMessage()); } }
java
{ "resource": "" }
q19269
ReaderInputStream.reset
train
@Override public synchronized void reset() throws IOException { if (in == null) { throw new IOException("Stream Closed"); } slack = null; in.reset(); }
java
{ "resource": "" }
q19270
ReaderInputStream.close
train
@Override public synchronized void close() throws IOException { if(in != null) in.close(); slack = null; in = null; }
java
{ "resource": "" }
q19271
Entity.getValues
train
public Collection<String> getValues(String property) { Multimap<Optional<String>, String> values = properties.get(property); if (values == null) { return Collections.emptyList(); } return values.values(); }
java
{ "resource": "" }
q19272
Entity.getValue
train
public String getValue(String property, String language) { Multimap<Optional<String>, String> values = properties.get(property); if (values == null) { return null; } Iterator<String> it = values.get(Optional.of(language)).iterator(); return it.hasNext() ? it.next() : null; }
java
{ "resource": "" }
q19273
Entity.getFirstPropertyValue
train
public String getFirstPropertyValue(String property) { Iterator<String> it = getValues(property).iterator(); return it.hasNext() ? it.next() : null; }
java
{ "resource": "" }
q19274
GeneratedDConnectionDaoImpl.findByAccessToken
train
public DConnection findByAccessToken(java.lang.String accessToken) { return queryUniqueByField(null, DConnectionMapper.Field.ACCESSTOKEN.getFieldName(), accessToken); }
java
{ "resource": "" }
q19275
GeneratedDConnectionDaoImpl.queryByExpireTime
train
public Iterable<DConnection> queryByExpireTime(java.util.Date expireTime) { return queryByField(null, DConnectionMapper.Field.EXPIRETIME.getFieldName(), expireTime); }
java
{ "resource": "" }
q19276
GeneratedDConnectionDaoImpl.queryByImageUrl
train
public Iterable<DConnection> queryByImageUrl(java.lang.String imageUrl) { return queryByField(null, DConnectionMapper.Field.IMAGEURL.getFieldName(), imageUrl); }
java
{ "resource": "" }
q19277
GeneratedDConnectionDaoImpl.queryByProfileUrl
train
public Iterable<DConnection> queryByProfileUrl(java.lang.String profileUrl) { return queryByField(null, DConnectionMapper.Field.PROFILEURL.getFieldName(), profileUrl); }
java
{ "resource": "" }
q19278
GeneratedDConnectionDaoImpl.queryByProviderId
train
public Iterable<DConnection> queryByProviderId(java.lang.String providerId) { return queryByField(null, DConnectionMapper.Field.PROVIDERID.getFieldName(), providerId); }
java
{ "resource": "" }
q19279
GeneratedDConnectionDaoImpl.queryByProviderUserId
train
public Iterable<DConnection> queryByProviderUserId(java.lang.String providerUserId) { return queryByField(null, DConnectionMapper.Field.PROVIDERUSERID.getFieldName(), providerUserId); }
java
{ "resource": "" }
q19280
GeneratedDConnectionDaoImpl.findByRefreshToken
train
public DConnection findByRefreshToken(java.lang.String refreshToken) { return queryUniqueByField(null, DConnectionMapper.Field.REFRESHTOKEN.getFieldName(), refreshToken); }
java
{ "resource": "" }
q19281
GeneratedDConnectionDaoImpl.queryBySecret
train
public Iterable<DConnection> queryBySecret(java.lang.String secret) { return queryByField(null, DConnectionMapper.Field.SECRET.getFieldName(), secret); }
java
{ "resource": "" }
q19282
GeneratedDConnectionDaoImpl.queryByUserId
train
public Iterable<DConnection> queryByUserId(java.lang.Long userId) { return queryByField(null, DConnectionMapper.Field.USERID.getFieldName(), userId); }
java
{ "resource": "" }
q19283
GeneratedDConnectionDaoImpl.queryByUserRoles
train
public Iterable<DConnection> queryByUserRoles(java.lang.String userRoles) { return queryByField(null, DConnectionMapper.Field.USERROLES.getFieldName(), userRoles); }
java
{ "resource": "" }
q19284
LabelCache.add
train
public void add(Collection<Label> labels) { for(Label label : labels) this.labels.put(label.getKey(), label); }
java
{ "resource": "" }
q19285
User.sendGlobal
train
public final void sendGlobal(String handler, String data) { try { connection.sendMessage("{\"id\":-1,\"type\":\"global\",\"handler\":" + Json.escapeString(handler) + ",\"data\":" + data + "}"); } catch (IOException e) { e.printStackTrace(); } }
java
{ "resource": "" }
q19286
ThriftEnvelope.replaceWith
train
public void replaceWith(final ThriftEnvelope thriftEnvelope) { this.typeName = thriftEnvelope.typeName; this.name = thriftEnvelope.name; this.payload.clear(); this.payload.addAll(thriftEnvelope.payload); }
java
{ "resource": "" }
q19287
FrameOutputWriter.addFrameWarning
train
protected void addFrameWarning(Content contentTree) { Content noframes = new HtmlTree(HtmlTag.NOFRAMES); Content noScript = HtmlTree.NOSCRIPT( HtmlTree.DIV(getResource("doclet.No_Script_Message"))); noframes.addContent(noScript); Content noframesHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Frame_Alert")); noframes.addContent(noframesHead); Content p = HtmlTree.P(getResource("doclet.Frame_Warning_Message", getHyperLink(configuration.topFile, configuration.getText("doclet.Non_Frame_Version")))); noframes.addContent(p); contentTree.addContent(noframes); }
java
{ "resource": "" }
q19288
FrameOutputWriter.addAllPackagesFrameTag
train
private void addAllPackagesFrameTag(Content contentTree) { HtmlTree frame = HtmlTree.FRAME(DocPaths.OVERVIEW_FRAME.getPath(), "packageListFrame", configuration.getText("doclet.All_Packages")); contentTree.addContent(frame); }
java
{ "resource": "" }
q19289
FrameOutputWriter.addAllClassesFrameTag
train
private void addAllClassesFrameTag(Content contentTree) { HtmlTree frame = HtmlTree.FRAME(DocPaths.ALLCLASSES_FRAME.getPath(), "packageFrame", configuration.getText("doclet.All_classes_and_interfaces")); contentTree.addContent(frame); }
java
{ "resource": "" }
q19290
FrameOutputWriter.addClassFrameTag
train
private void addClassFrameTag(Content contentTree) { HtmlTree frame = HtmlTree.FRAME(configuration.topFile.getPath(), "classFrame", configuration.getText("doclet.Package_class_and_interface_descriptions"), SCROLL_YES); contentTree.addContent(frame); }
java
{ "resource": "" }
q19291
TreeInfo.declarationFor
train
public static JCTree declarationFor(final Symbol sym, final JCTree tree) { class DeclScanner extends TreeScanner { JCTree result = null; public void scan(JCTree tree) { if (tree!=null && result==null) tree.accept(this); } public void visitTopLevel(JCCompilationUnit that) { if (that.packge == sym) result = that; else super.visitTopLevel(that); } public void visitClassDef(JCClassDecl that) { if (that.sym == sym) result = that; else super.visitClassDef(that); } public void visitMethodDef(JCMethodDecl that) { if (that.sym == sym) result = that; else super.visitMethodDef(that); } public void visitVarDef(JCVariableDecl that) { if (that.sym == sym) result = that; else super.visitVarDef(that); } public void visitTypeParameter(JCTypeParameter that) { if (that.type != null && that.type.tsym == sym) result = that; else super.visitTypeParameter(that); } } DeclScanner s = new DeclScanner(); tree.accept(s); return s.result; }
java
{ "resource": "" }
q19292
TreeInfo.types
train
public static List<Type> types(List<? extends JCTree> trees) { ListBuffer<Type> ts = new ListBuffer<Type>(); for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) ts.append(l.head.type); return ts.toList(); }
java
{ "resource": "" }
q19293
EmailChannel.configure
train
protected void configure(Properties properties) { _properties = properties; _recipients = properties.getProperty("mail.smtp.to").split(" *[,;] *"); _authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(_properties.getProperty("mail.smtp.user"), _properties.getProperty("mail.smtp.pass")); } }; }
java
{ "resource": "" }
q19294
TagletManager.initStandardTagsLowercase
train
private void initStandardTagsLowercase() { Iterator<String> it = standardTags.iterator(); while (it.hasNext()) { standardTagsLowercase.add(StringUtils.toLowerCase(it.next())); } }
java
{ "resource": "" }
q19295
Subscription.get
train
public static ApruveResponse<Subscription> get(String suscriptionId) { return ApruveClient.getInstance().get( getSubscriptionsPath() + suscriptionId, Subscription.class); }
java
{ "resource": "" }
q19296
Subscription.cancel
train
public static ApruveResponse<SubscriptionCancelResponse> cancel( String subscriptionId) { return ApruveClient.getInstance().post(getCancelPath(subscriptionId), "", SubscriptionCancelResponse.class); }
java
{ "resource": "" }
q19297
TaskQueue.handleNextTask
train
public boolean handleNextTask() { Runnable task = this.getNextTask(); if (task != null) { synchronized (this.tasksReachesZero) { this.runningTasks++; } try { task.run(); } catch (Throwable t) { t.printStackTrace(); } synchronized (this.tasksReachesZero) { this.runningTasks--; if (this.runningTasks == 0) { this.tasksReachesZero.notifyAll(); } } synchronized (task) { task.notifyAll(); } return true; } return false; }
java
{ "resource": "" }
q19298
TaskQueue.executeSync
train
public <T extends Runnable> T executeSync(T runnable) { synchronized (runnable) { this.executeAsync(runnable); try { runnable.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } return runnable; }
java
{ "resource": "" }
q19299
TaskQueue.executeSyncTimed
train
public <T extends Runnable> T executeSyncTimed(T runnable, long inMs) { try { Thread.sleep(inMs); this.executeSync(runnable); } catch (InterruptedException e) { e.printStackTrace(); } return runnable; }
java
{ "resource": "" }