_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q19300 | TaskQueue.executeAsyncTimed | train | public <T extends Runnable> T executeAsyncTimed(T runnable, long inMs) {
final Runnable theRunnable = runnable;
// This implementation is not really suitable for now as the timer uses its own thread
// The TaskQueue itself should be able in the future to handle this without using a new thread
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
TaskQueue.this.executeAsync(theRunnable);
}
}, inMs);
return runnable;
} | java | {
"resource": ""
} |
q19301 | TaskQueue.waitForTasks | train | protected boolean waitForTasks() {
synchronized (this.tasks) {
while (!this.closed && !this.hasTaskPending()) {
try {
this.tasks.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return !this.closed;
} | java | {
"resource": ""
} |
q19302 | TaskQueue.waitAllTasks | train | public void waitAllTasks() {
synchronized (this.tasks) {
while (this.hasTaskPending()) {
try {
this.tasks.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (this.tasksReachesZero) {
if (this.runningTasks > 0) {
try {
this.tasksReachesZero.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} | java | {
"resource": ""
} |
q19303 | AbstractSchemaScannerPlugin.scanConnection | train | protected List<SchemaDescriptor> scanConnection(String url, String user, String password, String infoLevelName, String bundledDriverName,
Properties properties, Store store) throws IOException {
LOGGER.info("Scanning schema '{}'", url);
Catalog catalog = getCatalog(url, user, password, infoLevelName, bundledDriverName, properties);
return createSchemas(catalog, store);
} | java | {
"resource": ""
} |
q19304 | AbstractSchemaScannerPlugin.getCatalog | train | protected Catalog getCatalog(String url, String user, String password, String infoLevelName, String bundledDriverName, Properties properties)
throws IOException {
// Determine info level
InfoLevel level = InfoLevel.valueOf(infoLevelName.toLowerCase());
SchemaInfoLevel schemaInfoLevel = level.getSchemaInfoLevel();
// Set options
for (InfoLevelOption option : InfoLevelOption.values()) {
String value = properties.getProperty(option.getPropertyName());
if (value != null) {
LOGGER.info("Setting option " + option.name() + "=" + value);
option.set(schemaInfoLevel, Boolean.valueOf(value.toLowerCase()));
}
}
SchemaCrawlerOptions options;
if (bundledDriverName != null) {
options = getOptions(bundledDriverName, level);
} else {
options = new SchemaCrawlerOptions();
}
options.setSchemaInfoLevel(schemaInfoLevel);
LOGGER.debug("Scanning database schemas on '" + url + "' (user='" + user + "', info level='" + level.name() + "')");
Catalog catalog;
try (Connection connection = DriverManager.getConnection(url, user, password)) {
catalog = SchemaCrawlerUtility.getCatalog(connection, options);
} catch (SQLException | SchemaCrawlerException e) {
throw new IOException(String.format("Cannot scan schema (url='%s', user='%s'", url, user), e);
}
return catalog;
} | java | {
"resource": ""
} |
q19305 | AbstractSchemaScannerPlugin.getOptions | train | private SchemaCrawlerOptions getOptions(String bundledDriverName, InfoLevel level) throws IOException {
for (BundledDriver bundledDriver : BundledDriver.values()) {
if (bundledDriver.name().toLowerCase().equals(bundledDriverName.toLowerCase())) {
return bundledDriver.getOptions(level);
}
}
throw new IOException("Unknown bundled driver name '" + bundledDriverName + "', supported values are " + Arrays.asList(BundledDriver.values()));
} | java | {
"resource": ""
} |
q19306 | AbstractSchemaScannerPlugin.createSchemas | train | private List<SchemaDescriptor> createSchemas(Catalog catalog, Store store) throws IOException {
List<SchemaDescriptor> schemaDescriptors = new ArrayList<>();
Map<String, ColumnTypeDescriptor> columnTypes = new HashMap<>();
Map<Column, ColumnDescriptor> allColumns = new HashMap<>();
Set<ForeignKey> allForeignKeys = new HashSet<>();
for (Schema schema : catalog.getSchemas()) {
SchemaDescriptor schemaDescriptor = store.create(SchemaDescriptor.class);
schemaDescriptor.setName(schema.getName());
// Tables
createTables(catalog, schema, schemaDescriptor, columnTypes, allColumns, allForeignKeys, store);
// Sequences
createSequences(catalog.getSequences(schema), schemaDescriptor, store);
// Procedures and Functions
createRoutines(catalog.getRoutines(schema), schemaDescriptor, columnTypes, store);
schemaDescriptors.add(schemaDescriptor);
}
// Foreign keys
createForeignKeys(allForeignKeys, allColumns, store);
return schemaDescriptors;
} | java | {
"resource": ""
} |
q19307 | AbstractSchemaScannerPlugin.createTables | train | private void createTables(Catalog catalog, Schema schema, SchemaDescriptor schemaDescriptor, Map<String, ColumnTypeDescriptor> columnTypes,
Map<Column, ColumnDescriptor> allColumns, Set<ForeignKey> allForeignKeys, Store store) {
for (Table table : catalog.getTables(schema)) {
TableDescriptor tableDescriptor = getTableDescriptor(table, schemaDescriptor, store);
Map<String, ColumnDescriptor> localColumns = new HashMap<>();
for (Column column : table.getColumns()) {
ColumnDescriptor columnDescriptor = createColumnDescriptor(column, ColumnDescriptor.class, columnTypes, store);
columnDescriptor.setDefaultValue(column.getDefaultValue());
columnDescriptor.setGenerated(column.isGenerated());
columnDescriptor.setPartOfIndex(column.isPartOfIndex());
columnDescriptor.setPartOfPrimaryKey(column.isPartOfPrimaryKey());
columnDescriptor.setPartOfForeignKey(column.isPartOfForeignKey());
columnDescriptor.setAutoIncremented(column.isAutoIncremented());
tableDescriptor.getColumns().add(columnDescriptor);
localColumns.put(column.getName(), columnDescriptor);
allColumns.put(column, columnDescriptor);
}
// Primary key
PrimaryKey primaryKey = table.getPrimaryKey();
if (primaryKey != null) {
PrimaryKeyDescriptor primaryKeyDescriptor = storeIndex(primaryKey, tableDescriptor, localColumns, PrimaryKeyDescriptor.class,
PrimaryKeyOnColumnDescriptor.class, store);
tableDescriptor.setPrimaryKey(primaryKeyDescriptor);
}
// Indices
for (Index index : table.getIndices()) {
IndexDescriptor indexDescriptor = storeIndex(index, tableDescriptor, localColumns, IndexDescriptor.class, IndexOnColumnDescriptor.class, store);
tableDescriptor.getIndices().add(indexDescriptor);
}
// Trigger
for (Trigger trigger : table.getTriggers()) {
TriggerDescriptor triggerDescriptor = store.create(TriggerDescriptor.class);
triggerDescriptor.setName(trigger.getName());
triggerDescriptor.setActionCondition(trigger.getActionCondition());
triggerDescriptor.setActionOrder(trigger.getActionOrder());
triggerDescriptor.setActionOrientation(trigger.getActionOrientation().name());
triggerDescriptor.setActionStatement(trigger.getActionStatement());
triggerDescriptor.setConditionTiming(trigger.getConditionTiming().name());
triggerDescriptor.setEventManipulationTime(trigger.getEventManipulationType().name());
tableDescriptor.getTriggers().add(triggerDescriptor);
}
allForeignKeys.addAll(table.getForeignKeys());
}
} | java | {
"resource": ""
} |
q19308 | AbstractSchemaScannerPlugin.createColumnDescriptor | train | private <T extends BaseColumnDescriptor> T createColumnDescriptor(BaseColumn column, Class<T> descriptorType,
Map<String, ColumnTypeDescriptor> columnTypes, Store store) {
T columnDescriptor = store.create(descriptorType);
columnDescriptor.setName(column.getName());
columnDescriptor.setNullable(column.isNullable());
columnDescriptor.setSize(column.getSize());
columnDescriptor.setDecimalDigits(column.getDecimalDigits());
ColumnDataType columnDataType = column.getColumnDataType();
ColumnTypeDescriptor columnTypeDescriptor = getColumnTypeDescriptor(columnDataType, columnTypes, store);
columnDescriptor.setColumnType(columnTypeDescriptor);
return columnDescriptor;
} | java | {
"resource": ""
} |
q19309 | AbstractSchemaScannerPlugin.createForeignKeys | train | private void createForeignKeys(Set<ForeignKey> allForeignKeys, Map<Column, ColumnDescriptor> allColumns, Store store) {
// Foreign keys
for (ForeignKey foreignKey : allForeignKeys) {
ForeignKeyDescriptor foreignKeyDescriptor = store.create(ForeignKeyDescriptor.class);
foreignKeyDescriptor.setName(foreignKey.getName());
foreignKeyDescriptor.setDeferrability(foreignKey.getDeferrability().name());
foreignKeyDescriptor.setDeleteRule(foreignKey.getDeleteRule().name());
foreignKeyDescriptor.setUpdateRule(foreignKey.getUpdateRule().name());
for (ForeignKeyColumnReference columnReference : foreignKey.getColumnReferences()) {
ForeignKeyReferenceDescriptor keyReferenceDescriptor = store.create(ForeignKeyReferenceDescriptor.class);
// foreign key table and column
Column foreignKeyColumn = columnReference.getForeignKeyColumn();
ColumnDescriptor foreignKeyColumnDescriptor = allColumns.get(foreignKeyColumn);
keyReferenceDescriptor.setForeignKeyColumn(foreignKeyColumnDescriptor);
// primary key table and column
Column primaryKeyColumn = columnReference.getPrimaryKeyColumn();
ColumnDescriptor primaryKeyColumnDescriptor = allColumns.get(primaryKeyColumn);
keyReferenceDescriptor.setPrimaryKeyColumn(primaryKeyColumnDescriptor);
foreignKeyDescriptor.getForeignKeyReferences().add(keyReferenceDescriptor);
}
}
} | java | {
"resource": ""
} |
q19310 | AbstractSchemaScannerPlugin.createRoutines | train | private void createRoutines(Collection<Routine> routines, SchemaDescriptor schemaDescriptor, Map<String, ColumnTypeDescriptor> columnTypes, Store store)
throws IOException {
for (Routine routine : routines) {
RoutineDescriptor routineDescriptor;
String returnType;
switch (routine.getRoutineType()) {
case procedure:
routineDescriptor = store.create(ProcedureDescriptor.class);
returnType = ((ProcedureReturnType) routine.getReturnType()).name();
schemaDescriptor.getProcedures().add((ProcedureDescriptor) routineDescriptor);
break;
case function:
routineDescriptor = store.create(FunctionDescriptor.class);
returnType = ((FunctionReturnType) routine.getReturnType()).name();
schemaDescriptor.getFunctions().add((FunctionDescriptor) routineDescriptor);
break;
case unknown:
routineDescriptor = store.create(RoutineDescriptor.class);
returnType = null;
schemaDescriptor.getUnknownRoutines().add(routineDescriptor);
break;
default:
throw new IOException("Unsupported routine type " + routine.getRoutineType());
}
routineDescriptor.setName(routine.getName());
routineDescriptor.setReturnType(returnType);
routineDescriptor.setBodyType(routine.getRoutineBodyType().name());
routineDescriptor.setDefinition(routine.getDefinition());
for (RoutineColumn<? extends Routine> routineColumn : routine.getColumns()) {
RoutineColumnDescriptor columnDescriptor = createColumnDescriptor(routineColumn, RoutineColumnDescriptor.class, columnTypes, store);
routineDescriptor.getColumns().add(columnDescriptor);
RoutineColumnType columnType = routineColumn.getColumnType();
if (columnType instanceof ProcedureColumnType) {
ProcedureColumnType procedureColumnType = (ProcedureColumnType) columnType;
columnDescriptor.setType(procedureColumnType.name());
} else if (columnType instanceof FunctionColumnType) {
FunctionColumnType functionColumnType = (FunctionColumnType) columnType;
columnDescriptor.setType(functionColumnType.name());
} else {
throw new IOException("Unsupported routine column type " + columnType.getClass().getName());
}
}
}
} | java | {
"resource": ""
} |
q19311 | AbstractSchemaScannerPlugin.createSequences | train | private void createSequences(Collection<Sequence> sequences, SchemaDescriptor schemaDescriptor, Store store) {
for (Sequence sequence : sequences) {
SequenceDesriptor sequenceDesriptor = store.create(SequenceDesriptor.class);
sequenceDesriptor.setName(sequence.getName());
sequenceDesriptor.setIncrement(sequence.getIncrement());
sequenceDesriptor.setMinimumValue(sequence.getMinimumValue().longValue());
sequenceDesriptor.setMaximumValue(sequence.getMaximumValue().longValue());
sequenceDesriptor.setCycle(sequence.isCycle());
schemaDescriptor.getSequences().add(sequenceDesriptor);
}
} | java | {
"resource": ""
} |
q19312 | AbstractSchemaScannerPlugin.getTableDescriptor | train | private TableDescriptor getTableDescriptor(Table table, SchemaDescriptor schemaDescriptor, Store store) {
TableDescriptor tableDescriptor;
if (table instanceof View) {
View view = (View) table;
ViewDescriptor viewDescriptor = store.create(ViewDescriptor.class);
viewDescriptor.setUpdatable(view.isUpdatable());
CheckOptionType checkOption = view.getCheckOption();
if (checkOption != null) {
viewDescriptor.setCheckOption(checkOption.name());
}
schemaDescriptor.getViews().add(viewDescriptor);
tableDescriptor = viewDescriptor;
} else {
tableDescriptor = store.create(TableDescriptor.class);
schemaDescriptor.getTables().add(tableDescriptor);
}
tableDescriptor.setName(table.getName());
return tableDescriptor;
} | java | {
"resource": ""
} |
q19313 | AbstractSchemaScannerPlugin.storeIndex | train | private <I extends IndexDescriptor> I storeIndex(Index index, TableDescriptor tableDescriptor, Map<String, ColumnDescriptor> columns, Class<I> indexType,
Class<? extends OnColumnDescriptor> onColumnType, Store store) {
I indexDescriptor = store.create(indexType);
indexDescriptor.setName(index.getName());
indexDescriptor.setUnique(index.isUnique());
indexDescriptor.setCardinality(index.getCardinality());
indexDescriptor.setIndexType(index.getIndexType().name());
indexDescriptor.setPages(index.getPages());
for (IndexColumn indexColumn : index.getColumns()) {
ColumnDescriptor columnDescriptor = columns.get(indexColumn.getName());
OnColumnDescriptor onColumnDescriptor = store.create(indexDescriptor, onColumnType, columnDescriptor);
onColumnDescriptor.setIndexOrdinalPosition(indexColumn.getIndexOrdinalPosition());
onColumnDescriptor.setSortSequence(indexColumn.getSortSequence().name());
}
return indexDescriptor;
} | java | {
"resource": ""
} |
q19314 | AbstractSchemaScannerPlugin.getColumnTypeDescriptor | train | private ColumnTypeDescriptor getColumnTypeDescriptor(ColumnDataType columnDataType, Map<String, ColumnTypeDescriptor> columnTypes, Store store) {
String databaseSpecificTypeName = columnDataType.getDatabaseSpecificTypeName();
ColumnTypeDescriptor columnTypeDescriptor = columnTypes.get(databaseSpecificTypeName);
if (columnTypeDescriptor == null) {
columnTypeDescriptor = store.find(ColumnTypeDescriptor.class, databaseSpecificTypeName);
if (columnTypeDescriptor == null) {
columnTypeDescriptor = store.create(ColumnTypeDescriptor.class);
columnTypeDescriptor.setDatabaseType(databaseSpecificTypeName);
columnTypeDescriptor.setAutoIncrementable(columnDataType.isAutoIncrementable());
columnTypeDescriptor.setCaseSensitive(columnDataType.isCaseSensitive());
columnTypeDescriptor.setPrecision(columnDataType.getPrecision());
columnTypeDescriptor.setMinimumScale(columnDataType.getMinimumScale());
columnTypeDescriptor.setMaximumScale(columnDataType.getMaximumScale());
columnTypeDescriptor.setFixedPrecisionScale(columnDataType.isFixedPrecisionScale());
columnTypeDescriptor.setNumericPrecisionRadix(columnDataType.getNumPrecisionRadix());
columnTypeDescriptor.setUnsigned(columnDataType.isUnsigned());
columnTypeDescriptor.setUserDefined(columnDataType.isUserDefined());
columnTypeDescriptor.setNullable(columnDataType.isNullable());
}
columnTypes.put(databaseSpecificTypeName, columnTypeDescriptor);
}
return columnTypeDescriptor;
} | java | {
"resource": ""
} |
q19315 | ProfilePackageSummaryBuilder.getInstance | train | public static ProfilePackageSummaryBuilder getInstance(Context context,
PackageDoc pkg, ProfilePackageSummaryWriter profilePackageWriter,
Profile profile) {
return new ProfilePackageSummaryBuilder(context, pkg, profilePackageWriter,
profile);
} | java | {
"resource": ""
} |
q19316 | BoardPanel.addItem | train | public void addItem(Point coordinates, Drawable item) {
assertEDT();
if (coordinates == null || item == null) {
throw new IllegalArgumentException("Coordinates and added item cannot be null");
}
log.trace("[addItem] New item added @ {}", coordinates);
getPanelAt(coordinates).addModel(item);
getPanelAt(coordinates).repaint();
} | java | {
"resource": ""
} |
q19317 | BoardPanel.moveItem | train | public void moveItem(Point oldCoordinates, Point newCoordinates) {
assertEDT();
if (oldCoordinates == null || newCoordinates == null) {
throw new IllegalArgumentException("Coordinates cannot be null");
}
if (getPanelAt(newCoordinates).hasModel()) {
throw new IllegalStateException(
"New position contains a model in the UI already. New position = " + newCoordinates);
}
if (!getPanelAt(oldCoordinates).hasModel()) {
throw new IllegalStateException("Old position doesn't contain a model in the UI. Old position = "
+ oldCoordinates);
}
// all good
Drawable item = getPanelAt(oldCoordinates).getModel();
removeItem(oldCoordinates);
addItem(newCoordinates, item);
} | java | {
"resource": ""
} |
q19318 | BoardPanel.clear | train | public void clear() {
assertEDT();
log.debug("[clear] Cleaning board");
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
removeItem(new Point(col, row));
}
}
} | java | {
"resource": ""
} |
q19319 | BoardPanel.refresh | train | public void refresh(Point coordinates) {
assertEDT();
if (coordinates == null) {
throw new IllegalArgumentException("Coordinates cannot be null");
}
getPanelAt(coordinates).repaint();
} | java | {
"resource": ""
} |
q19320 | TablePanel.removeAll | train | public TablePanel removeAll() {
for (int i = 0; i < content.length; ++i)
for (int j = 0; j < content[i].length; ++j)
content[i][j] = null;
this.sendElement();
return this;
} | java | {
"resource": ""
} |
q19321 | TablePanel.remove | train | public TablePanel remove(Widget widget) {
for (int i = 0; i < content.length; ++i)
for (int j = 0; j < content[i].length; ++j)
if (content[i][j] == widget) content[i][j] = null;
this.sendElement();
return this;
} | java | {
"resource": ""
} |
q19322 | TablePanel.put | train | public TablePanel put(Widget widget, int x, int y) {
if (x < 0 || y < 0 || x >= content.length || y >= content[x].length)
throw new IndexOutOfBoundsException();
attach(widget);
content[x][y] = widget;
this.sendElement();
return this;
} | java | {
"resource": ""
} |
q19323 | ComponentBindingsProviderWebConsole.loadProperties | train | private Map<String, String> loadProperties(ServiceReference reference) {
log.trace("loadProperties");
Map<String, String> properties = new HashMap<String, String>();
properties.put("id", OsgiUtil.toString(
reference.getProperty(Constants.SERVICE_ID), ""));
properties.put("class", OsgiUtil.toString(
reference.getProperty(Constants.SERVICE_PID), ""));
properties.put("description", OsgiUtil.toString(
reference.getProperty(Constants.SERVICE_DESCRIPTION), ""));
properties.put(
"vendor",
OsgiUtil.toString(
reference.getProperty(Constants.SERVICE_VENDOR), ""));
properties
.put("resourceTypes",
Arrays.toString(OsgiUtil.toStringArray(
reference
.getProperty(ComponentBindingsProvider.RESOURCE_TYPE_PROP),
new String[0])));
properties.put("priority", OsgiUtil.toString(
reference.getProperty(ComponentBindingsProvider.PRIORITY), ""));
properties.put("bundle_id",
String.valueOf(reference.getBundle().getBundleId()));
properties.put("bundle_name", reference.getBundle().getSymbolicName());
log.debug("Loaded properties {}", properties);
return properties;
} | java | {
"resource": ""
} |
q19324 | ComponentBindingsProviderWebConsole.renderBlock | train | private void renderBlock(HttpServletResponse res, String templateName,
Map<String, String> properties) throws IOException {
InputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String template = null;
try {
is = getClass().getClassLoader().getResourceAsStream(templateName);
if (is != null) {
IOUtils.copy(is, baos);
template = baos.toString();
} else {
throw new IOException("Unable to load template " + templateName);
}
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(baos);
}
StrSubstitutor sub = new StrSubstitutor(properties);
res.getWriter().write(sub.replace(template));
} | java | {
"resource": ""
} |
q19325 | XlsxWorksheet.unmarshall | train | private void unmarshall()
{
sheetData = sheet.getJaxbElement().getSheetData();
rows = sheetData.getRow();
if(rows != null && rows.size() > 0)
{
Row r = (Row)rows.get(0);
numColumns = r.getC().size();
}
} | java | {
"resource": ""
} |
q19326 | XlsxWorksheet.getRows | train | public int getRows()
{
if(sheetData == null)
unmarshall();
int ret = 0;
if(rows != null)
ret = rows.size();
return ret;
} | java | {
"resource": ""
} |
q19327 | ManifestVersionFactory.get | train | public static ManifestVersion get(final Class<?> clazz)
{
final String manifestUrl = ClassExtensions.getManifestUrl(clazz);
try
{
return of(manifestUrl != null ? new URL(manifestUrl) : null);
}
catch (final MalformedURLException ignore)
{
return of(null);
}
} | java | {
"resource": ""
} |
q19328 | UserAdminTask.processTask | train | @Override
public Object processTask(String taskName, Map<String, String[]> parameterMap) {
if ("createAdmin".equalsIgnoreCase(taskName)) {
return userService.createDefaultAdmin();
}
return null;
} | java | {
"resource": ""
} |
q19329 | StorageComponent.get | train | public ValueType get(final KeyType... keys) {
if (ArrayUtils.isEmpty(keys)) {
return null;
}
int keysLength = keys.length;
if (keysLength == 1) {
return get(keys[0]);
} else {
StorageComponent<KeyType, ValueType> storageComponent = this;
int lastKeyIndex = keysLength - 1;
for (int i = 0; i < lastKeyIndex; i++) {
KeyType storageComponentKey = keys[i];
storageComponent = storageComponent.getStorageComponent(storageComponentKey);
}
return storageComponent.get(keys[lastKeyIndex]);
}
} | java | {
"resource": ""
} |
q19330 | StorageComponent.put | train | public void put(final ValueType value, final KeyType... keys) {
if (ArrayUtils.isEmpty(keys)) {
return;
}
int keysLength = keys.length;
if (keysLength == 1) {
put(value, keys[0]);
} else {
StorageComponent<KeyType, ValueType> childStorageComponent = getStorageComponent(keys[0]);
int lastKeyIndex = keysLength - 1;
for (int i = 1; i < lastKeyIndex; i++) {
childStorageComponent = childStorageComponent.getStorageComponent(keys[i]);
}
childStorageComponent.put(value, keys[lastKeyIndex]);
}
} | java | {
"resource": ""
} |
q19331 | StorageComponent.getStorageComponent | train | public StorageComponent<KeyType, ValueType> getStorageComponent(final KeyType key) {
KeyToStorageComponent<KeyType, ValueType> storage = getkeyToStorage();
StorageComponent<KeyType, ValueType> storageComponent = storage.get(key);
if (storageComponent == null) {
storageComponent = new StorageComponent<KeyType, ValueType>();
storage.put(key, storageComponent);
}
return storageComponent;
} | java | {
"resource": ""
} |
q19332 | ClassIndexer.add | train | public boolean add(T element, Class<?> accessibleClass) {
boolean added = false;
while (accessibleClass != null && accessibleClass != this.baseClass) {
added |= this.addSingle(element, accessibleClass);
for (Class<?> interf : accessibleClass.getInterfaces()) {
this.addSingle(element, interf);
}
accessibleClass = accessibleClass.getSuperclass();
}
return added;
} | java | {
"resource": ""
} |
q19333 | ClassIndexer.remove | train | public void remove(T element, Class<?> accessibleClass) {
while (accessibleClass != null && accessibleClass != this.baseClass) {
this.removeSingle(element, accessibleClass);
for (Class<?> interf : accessibleClass.getInterfaces()) {
this.removeSingle(element, interf);
}
accessibleClass = accessibleClass.getSuperclass();
}
} | java | {
"resource": ""
} |
q19334 | IBANManager._readIBANDataFromXML | train | private static void _readIBANDataFromXML ()
{
final IMicroDocument aDoc = MicroReader.readMicroXML (new ClassPathResource ("codelists/iban-country-data.xml"));
if (aDoc == null)
throw new InitializationException ("Failed to read IBAN country data [1]");
if (aDoc.getDocumentElement () == null)
throw new InitializationException ("Failed to read IBAN country data [2]");
final DateTimeFormatter aDTPattern = DateTimeFormatter.ISO_DATE;
for (final IMicroElement eCountry : aDoc.getDocumentElement ().getAllChildElements (ELEMENT_COUNTRY))
{
// get descriptive string
final String sDesc = eCountry.getTextContent ();
final String sCountryCode = sDesc.substring (0, 2);
if (CountryCache.getInstance ().getCountry (sCountryCode) == null)
if (LOGGER.isWarnEnabled ())
LOGGER.warn ("IBAN country data: no such country code '" + sCountryCode + "' - be careful");
LocalDate aValidFrom = null;
if (eCountry.hasAttribute (ATTR_VALIDFROM))
{
// Constant format, conforming to XML date
aValidFrom = PDTFromString.getLocalDateFromString (eCountry.getAttributeValue (ATTR_VALIDFROM), aDTPattern);
}
LocalDate aValidTo = null;
if (eCountry.hasAttribute (ATTR_VALIDUNTIL))
{
// Constant format, conforming to XML date
aValidTo = PDTFromString.getLocalDateFromString (eCountry.getAttributeValue (ATTR_VALIDUNTIL), aDTPattern);
}
final String sLayout = eCountry.getAttributeValue (ATTR_LAYOUT);
final String sCheckDigits = eCountry.getAttributeValue (ATTR_CHECKDIGITS);
// get expected length
final String sLen = eCountry.getAttributeValue (ATTR_LEN);
final int nExpectedLength = StringParser.parseInt (sLen, CGlobal.ILLEGAL_UINT);
if (nExpectedLength == CGlobal.ILLEGAL_UINT)
throw new InitializationException ("Failed to convert length '" + sLen + "' to int!");
if (s_aIBANData.containsKey (sCountryCode))
throw new IllegalArgumentException ("Country " + sCountryCode + " is already contained!");
s_aIBANData.put (sCountryCode,
IBANCountryData.createFromString (sCountryCode,
nExpectedLength,
sLayout,
sCheckDigits,
aValidFrom,
aValidTo,
sDesc));
}
} | java | {
"resource": ""
} |
q19335 | IBANManager.getCountryData | train | @Nullable
public static IBANCountryData getCountryData (@Nonnull final String sCountryCode)
{
ValueEnforcer.notNull (sCountryCode, "CountryCode");
return s_aIBANData.get (sCountryCode.toUpperCase (Locale.US));
} | java | {
"resource": ""
} |
q19336 | IBANManager.unifyIBAN | train | @Nullable
public static String unifyIBAN (@Nullable final String sIBAN)
{
if (sIBAN == null)
return null;
// to uppercase
String sRealIBAN = sIBAN.toUpperCase (Locale.US);
// kick all non-IBAN chars
sRealIBAN = RegExHelper.stringReplacePattern ("[^0-9A-Z]", sRealIBAN, "");
if (sRealIBAN.length () < 4)
return null;
return sRealIBAN;
} | java | {
"resource": ""
} |
q19337 | IBANManager.isValidIBAN | train | public static boolean isValidIBAN (@Nullable final String sIBAN, final boolean bReturnCodeIfNoCountryData)
{
// kick all non-IBAN chars
final String sRealIBAN = unifyIBAN (sIBAN);
if (sRealIBAN == null)
return false;
// is the country supported?
final IBANCountryData aData = s_aIBANData.get (sRealIBAN.substring (0, 2));
if (aData == null)
return bReturnCodeIfNoCountryData;
// Does the length match the expected length?
if (aData.getExpectedLength () != sRealIBAN.length ())
return false;
// Are the checksum characters valid?
if (!_isValidChecksumChar (sRealIBAN.charAt (2)) || !_isValidChecksumChar (sRealIBAN.charAt (3)))
return false;
// Is existing checksum valid?
if (_calculateChecksum (sRealIBAN) != 1)
return false;
// Perform pattern check
if (!aData.matchesPattern (sRealIBAN))
return false;
return true;
} | java | {
"resource": ""
} |
q19338 | PackageSummaryBuilder.buildContent | train | public void buildContent(XMLNode node, Content contentTree) {
Content packageContentTree = packageWriter.getContentHeader();
buildChildren(node, packageContentTree);
contentTree.addContent(packageContentTree);
} | java | {
"resource": ""
} |
q19339 | JavacTaskImpl.asJavaFileObject | train | public JavaFileObject asJavaFileObject(File file) {
JavacFileManager fm = (JavacFileManager)context.get(JavaFileManager.class);
return fm.getRegularFile(file);
} | java | {
"resource": ""
} |
q19340 | JavacTaskImpl.parse | train | public Iterable<? extends CompilationUnitTree> parse() throws IOException {
try {
prepareCompiler();
List<JCCompilationUnit> units = compiler.parseFiles(fileObjects);
for (JCCompilationUnit unit: units) {
JavaFileObject file = unit.getSourceFile();
if (notYetEntered.containsKey(file))
notYetEntered.put(file, unit);
}
return units;
}
finally {
parsed = true;
if (compiler != null && compiler.log != null)
compiler.log.flush();
}
} | java | {
"resource": ""
} |
q19341 | ClassLoaders.findMostCompleteClassLoader | train | public static ClassLoader findMostCompleteClassLoader(Class<?> target) {
// Try the most complete class loader we can get
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Then fallback to the class loader from a specific class given
if (classLoader == null && target != null) {
classLoader = target.getClassLoader();
}
// Then fallback to the class loader that loaded this class
if (classLoader == null) {
classLoader = ClassLoaders.class.getClassLoader();
}
// Then fallback to the system class loader
if (classLoader == null) {
classLoader = ClassLoader.getSystemClassLoader();
}
// Throw an exception if no classloader was found at all
if (classLoader == null) {
throw new RuntimeException("Unable to find a classloader");
}
return classLoader;
} | java | {
"resource": ""
} |
q19342 | ManagedComponent.emit | train | @Override
public void emit(Level level, String message, long sequence) {
if (_broadcaster != null) _broadcaster.sendNotification(new Notification(
level.toString(),
_name != null ? _name : this,
sequence,
message
));
} | java | {
"resource": ""
} |
q19343 | ManagedComponent.emit | train | @Override
public <T extends Throwable> T emit(T throwable, String message, long sequence) {
if (_broadcaster != null) _broadcaster.sendNotification(new Notification(
Level.WARNING.toString(),
_name != null ? _name : this,
sequence,
message == null ? Throwables.getFullMessage(throwable) : message + ": " + Throwables.getFullMessage(throwable)
));
return throwable;
} | java | {
"resource": ""
} |
q19344 | ManagedComponent.emit | train | @Override
public void emit(Level level, String message, long sequence, Logger logger) {
emit(level, message, sequence);
logger.log(level, message);
} | java | {
"resource": ""
} |
q19345 | ManagedComponent.emit | train | @Override
public <T extends Throwable> T emit(T throwable, String message, long sequence, Logger logger) {
message = message == null ? Throwables.getFullMessage(throwable) : message + ": " + Throwables.getFullMessage(throwable);
emit(Level.WARNING, message, sequence, logger);
return throwable;
} | java | {
"resource": ""
} |
q19346 | Schema.getSchema | train | public ArrayList<SchemaField> getSchema()
{
final ArrayList<SchemaField> items = new ArrayList<SchemaField>(schemaFields.values());
Collections.sort(items, new Comparator<SchemaField>()
{
@Override
public int compare(final SchemaField left, final SchemaField right)
{
return left.getId() - right.getId();
}
});
return items;
} | java | {
"resource": ""
} |
q19347 | PlatformControl.bind | train | PlatformControl bind(ServicePlatform p, XmlWebApplicationContext c, ClassLoader l) {
_platform = p;
_root = c;
_cloader = l;
return this;
} | java | {
"resource": ""
} |
q19348 | MediaTypeUtils.isSafeMediaType | train | public static boolean isSafeMediaType(final String mediaType) {
return mediaType != null && VALID_MIME_TYPE.matcher(mediaType).matches()
&& !DANGEROUS_MEDIA_TYPES.contains(mediaType);
} | java | {
"resource": ""
} |
q19349 | StreamBytes.writeStream | train | public WriteStream writeStream() {
detachReader();
if (writer == null) {
writer = new BytesWriteStream(bytes, maxCapacity);
}
return writer;
} | java | {
"resource": ""
} |
q19350 | StreamBytes.readStream | train | public ReadStream readStream() {
detachWriter();
if (reader == null) {
reader = new BytesReadStream(bytes, 0, length);
}
return reader;
} | java | {
"resource": ""
} |
q19351 | EntityCache.add | train | public void add(Collection<Entity> entities)
{
for(Entity entity : entities)
this.entities.put(entity.getId(), entity);
} | java | {
"resource": ""
} |
q19352 | MockBundle.loadClass | train | @Override
public Class<?> loadClass(String classname) throws ClassNotFoundException {
return getClass().getClassLoader().loadClass(classname);
} | java | {
"resource": ""
} |
q19353 | SmileStorage.getSchema | train | @Override
public ResourceSchema getSchema(final String location, final Job job) throws IOException
{
final List<Schema.FieldSchema> schemaList = new ArrayList<Schema.FieldSchema>();
for (final GoodwillSchemaField field : schema.getSchema()) {
schemaList.add(new Schema.FieldSchema(field.getName(), getPigType(field.getType())));
}
return new ResourceSchema(new Schema(schemaList));
} | java | {
"resource": ""
} |
q19354 | ConfigurationExtensions.getUserApplicationConfigurationFilePath | train | public static String getUserApplicationConfigurationFilePath(
@NonNull final String applicationName, @NonNull final String configFileName)
{
return System.getProperty(USER_HOME_PROPERTY_KEY) + File.separator + applicationName
+ File.separator + configFileName;
} | java | {
"resource": ""
} |
q19355 | ConfigurationExtensions.getTemporaryApplicationConfigurationFilePath | train | public static String getTemporaryApplicationConfigurationFilePath(
@NonNull final String applicationName, @NonNull final String fileName)
{
return System.getProperty(JAVA_IO_TPMDIR_PROPERTY_KEY) + File.separator + applicationName
+ File.separator + fileName;
} | java | {
"resource": ""
} |
q19356 | ClassUtils.instantiateClass | train | public static <T> T instantiateClass(final Class<T> clazz) throws IllegalArgumentException,
BeanInstantiationException {
return instantiateClass(clazz, MethodUtils.EMPTY_PARAMETER_CLASSTYPES,
MethodUtils.EMPTY_PARAMETER_VALUES);
} | java | {
"resource": ""
} |
q19357 | ClassUtils.instantiateClass | train | public static <T> T instantiateClass(final Class<T> clazz, final Class<?>[] parameterTypes,
final Object[] parameterValues) throws BeanInstantiationException {
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, CLASS_IS_INTERFACE);
}
try {
Constructor<T> constructor = clazz.getConstructor(parameterTypes);
T newInstance = constructor.newInstance(parameterValues);
return newInstance;
} catch (Exception e) {
throw new BeanInstantiationException(clazz, NO_DEFAULT_CONSTRUCTOR_FOUND, e);
}
} | java | {
"resource": ""
} |
q19358 | ClassUtils.isDataObject | train | public static boolean isDataObject(final Object object) {
if (object == null) {
return true;
}
Class<?> clazz = object.getClass();
return isDataClass(clazz);
} | java | {
"resource": ""
} |
q19359 | ClassUtils.isDataClass | train | public static boolean isDataClass(final Class<?> clazz) {
if (clazz == null || clazz.isPrimitive()) {
return true;
}
boolean isWrapperClass = contains(WRAPPER_CLASSES, clazz);
if (isWrapperClass) {
return true;
}
boolean isDataClass = contains(DATA_PRIMITIVE_CLASS, clazz);
if (isDataClass) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q19360 | cufftType.stringFor | train | public static String stringFor(int m)
{
switch (m)
{
case CUFFT_R2C : return "CUFFT_R2C";
case CUFFT_C2R : return "CUFFT_C2R";
case CUFFT_C2C : return "CUFFT_C2C";
case CUFFT_D2Z : return "CUFFT_D2Z";
case CUFFT_Z2D : return "CUFFT_Z2D";
case CUFFT_Z2Z : return "CUFFT_Z2Z";
}
return "INVALID cufftType: " + m;
} | java | {
"resource": ""
} |
q19361 | Struct.setContract | train | @Override
public void setContract(Contract c) {
super.setContract(c);
for (Field f : fields.values()) {
f.setContract(c);
}
} | java | {
"resource": ""
} |
q19362 | Struct.getFieldsPlusParents | train | public Map<String,Field> getFieldsPlusParents() {
Map<String,Field> tmp = new HashMap<String,Field>();
tmp.putAll(fields);
if (extend != null && !extend.equals("")) {
Struct parent = contract.getStructs().get(extend);
tmp.putAll(parent.getFieldsPlusParents());
}
return tmp;
} | java | {
"resource": ""
} |
q19363 | Struct.getFieldNamesPlusParents | train | public List<String> getFieldNamesPlusParents() {
List<String> tmp = new ArrayList<String>();
tmp.addAll(getFieldNames());
if (extend != null && !extend.equals("")) {
Struct parent = contract.getStructs().get(extend);
tmp.addAll(parent.getFieldNamesPlusParents());
}
return tmp;
} | java | {
"resource": ""
} |
q19364 | MobileApplicationCache.add | train | public void add(Collection<MobileApplication> mobileApplications)
{
for(MobileApplication mobileApplication : mobileApplications)
this.mobileApplications.put(mobileApplication.getId(), mobileApplication);
} | java | {
"resource": ""
} |
q19365 | FileSystemAccess.getFileSystemSafe | train | private FileSystem getFileSystemSafe() throws IOException
{
try {
fs.getFileStatus(new Path("/"));
return fs;
}
catch (NullPointerException e) {
throw new IOException("file system not initialized");
}
} | java | {
"resource": ""
} |
q19366 | PostalCodeManager.isValidPostalCode | train | @Nonnull
public ETriState isValidPostalCode (@Nullable final Locale aCountry, @Nullable final String sPostalCode)
{
final IPostalCodeCountry aPostalCountry = getPostalCountryOfCountry (aCountry);
if (aPostalCountry == null)
return ETriState.UNDEFINED;
return ETriState.valueOf (aPostalCountry.isValidPostalCode (sPostalCode));
} | java | {
"resource": ""
} |
q19367 | PostalCodeManager.isValidPostalCodeDefaultYes | train | public boolean isValidPostalCodeDefaultYes (@Nullable final Locale aCountry, @Nullable final String sPostalCode)
{
return isValidPostalCode (aCountry, sPostalCode).getAsBooleanValue (true);
} | java | {
"resource": ""
} |
q19368 | PostalCodeManager.isValidPostalCodeDefaultNo | train | public boolean isValidPostalCodeDefaultNo (@Nullable final Locale aCountry, @Nullable final String sPostalCode)
{
return isValidPostalCode (aCountry, sPostalCode).getAsBooleanValue (false);
} | java | {
"resource": ""
} |
q19369 | PostalCodeManager.getPostalCodeExamples | train | @Nullable
@ReturnsMutableCopy
public ICommonsList <String> getPostalCodeExamples (@Nullable final Locale aCountry)
{
final IPostalCodeCountry aPostalCountry = getPostalCountryOfCountry (aCountry);
return aPostalCountry == null ? null : aPostalCountry.getAllExamples ();
} | java | {
"resource": ""
} |
q19370 | MockBundleContext.registerService | train | @Override
public ServiceRegistration<?> registerService(String clazz, Object service, Dictionary<String, ?> properties) {
MockServiceReference<Object> serviceReference = new MockServiceReference<Object>(getBundle(), properties);
if (serviceRegistrations.get(clazz) == null) { serviceRegistrations.put(clazz, new ArrayList<ServiceReference<?>>()); }
serviceRegistrations.get(clazz).add(serviceReference);
serviceImplementations.put(serviceReference, service);
notifyListenersAboutNewService(clazz, serviceReference);
return new MockServiceRegistration<Object>(this, serviceReference);
} | java | {
"resource": ""
} |
q19371 | MockBundleContext.addServiceListener | train | @Override
public void addServiceListener(ServiceListener listener, String filter) throws InvalidSyntaxException {
if (null == filteredServiceListeners.get(filter)) {
filteredServiceListeners.put(filter, new ArrayList<ServiceListener>(1));
}
filteredServiceListeners.get(filter).add(listener);
} | java | {
"resource": ""
} |
q19372 | MockBundleContext.removeServiceListener | train | @Override
public void removeServiceListener(ServiceListener listener) {
// Note: if unfiltered service listeners are implemented
// This method needs to look for, and remove, the listener there
// as well
// Go through all of the filters, and for each filter
// remove the listener from the filter's list.
for(Entry<String, List<ServiceListener>> filteredList : filteredServiceListeners.entrySet()) {
filteredList.getValue().remove(listener);
}
} | java | {
"resource": ""
} |
q19373 | Log4jConfigurer.getLoggerList | train | @Nonnull
public String[] getLoggerList() {
try {
Enumeration<Logger> currentLoggers = LogManager.getLoggerRepository().getCurrentLoggers();
List<String> loggerNames = new ArrayList<String>();
while (currentLoggers.hasMoreElements()) {
loggerNames.add(currentLoggers.nextElement().getName());
}
return loggerNames.toArray(new String[0]);
} catch (RuntimeException e) {
logger.warn("Exception getting logger names", e);
throw e;
}
} | java | {
"resource": ""
} |
q19374 | SimpleSentence.checkHead | train | private void checkHead(Token token, Optional<Integer> optHead) {
if (optHead.isPresent()) {
int head = optHead.get();
Preconditions.checkArgument(head >= 0 && head <= tokens.size(), String.format("Head should refer to token or 0: %s", token));
}
} | java | {
"resource": ""
} |
q19375 | ValueUtils.getValue | train | public static Long getValue(final Long value, final Long defaultValue) {
return value == null ? defaultValue : value;
} | java | {
"resource": ""
} |
q19376 | TextFile.read | train | public boolean read() throws IOException
{
valid = false;
File file = new File(filename);
FileReader reader = new FileReader(file);
if(file.exists())
{
// Load the file contents
contents = getContents(reader, "\n");
if(contents != null)
valid = true;
else
logger.severe("Unable to read file contents: "+file.getAbsolutePath());
}
else
{
logger.severe("File does not exist: "+file.getAbsolutePath());
}
try
{
if(reader != null)
reader.close();
}
catch(IOException e)
{
}
return valid;
} | java | {
"resource": ""
} |
q19377 | TextFile.read | train | public boolean read(InputStream stream) throws IOException
{
valid = false;
InputStreamReader reader = new InputStreamReader(stream);
// Load the file contents
contents = getContents(reader, "\n");
if(contents != null)
valid = true;
else
logger.severe("Unable to read file contents: "+filename);
try
{
if(reader != null)
reader.close();
}
catch(IOException e)
{
}
return valid;
} | java | {
"resource": ""
} |
q19378 | TextFile.getContents | train | private String getContents(Reader reader, String terminator) throws IOException
{
String line = null;
StringBuffer buff = new StringBuffer();
BufferedReader in = new BufferedReader(reader);
while((line = in.readLine()) != null)
{
buff.append(line);
if(terminator != null)
buff.append(terminator);
}
reader.close();
return buff.toString();
} | java | {
"resource": ""
} |
q19379 | MirroredTypeException.readObject | train | private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
type = null;
types = null;
} | java | {
"resource": ""
} |
q19380 | ExportHandler.generatePdf | train | public void generatePdf(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) {
try {
Document document = new Document();
PdfWriter.getInstance(document, out);
if (columns == null)
{
if (rows.size() > 0) return;
columns = new ArrayList<ColumnDef>(CollectionUtils.collect(rows.get(0).keySet(), new Transformer() {
@Override
public Object transform(final Object input) {
return new ColumnDef()
{{
setName((String)input);
}};
}
}));
}
if (columns.size() > 14)
document.setPageSize(PageSize.A1);
else if (columns.size() > 10)
document.setPageSize(PageSize.A2);
else if (columns.size() > 7)
document.setPageSize(PageSize.A3);
else
document.setPageSize(PageSize.A4);
document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL, BaseColor.BLACK);
Font headerFont = FontFactory.getFont(FontFactory.COURIER, 8, Font.BOLD, BaseColor.BLACK);
int size = columns.size();
PdfPTable table = new PdfPTable(size);
for (ColumnDef column : columns)
{
PdfPCell c1 = new PdfPCell(new Phrase(column.getName(), headerFont));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
}
table.setHeaderRows(1);
if (rows != null)
for (Map<String, Object> row : rows)
{
for (ColumnDef column : columns)
{
table.addCell(new Phrase(String.valueOf(row.get(column.getName())), font));
}
}
document.add(table);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q19381 | ExportHandler.generateCsv | train | public void generateCsv(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) {
ICsvMapWriter csvWriter = null;
try {
csvWriter = new CsvMapWriter(new OutputStreamWriter(out), CsvPreference.STANDARD_PREFERENCE);
// the header elements are used to map the bean values to each column (names must match)
String[] header = new String[] {};
CellProcessor[] processors = new CellProcessor[] {};
if (columns != null)
{
header = (String[])CollectionUtils.collect(columns, new Transformer() {
@Override
public Object transform(Object input) {
ColumnDef column = (ColumnDef)input;
return column.getName();
}
}).toArray(new String[0]) ;
processors = (CellProcessor[]) CollectionUtils.collect(columns, new Transformer() {
@Override
public Object transform(Object input) {
return new Optional();
}
}).toArray(new CellProcessor[0]);
} else if (rows.size() > 0)
{
header = new ArrayList<String>(rows.get(0).keySet()).toArray(new String[0]);
processors = (CellProcessor[]) CollectionUtils.collect(rows.get(0).keySet(), new Transformer() {
@Override
public Object transform(Object input) {
return new Optional();
}
}).toArray(new CellProcessor[0]);
}
if (header.length > 0)
csvWriter.writeHeader(header);
if (rows != null)
for (Map<String, Object> row : rows)
{
csvWriter.write(row, header, processors);
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
if( csvWriter != null ) {
try {
csvWriter.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
} | java | {
"resource": ""
} |
q19382 | ExportHandler.generateXls | train | public void generateXls(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) {
try {
Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();
String safeName = WorkbookUtil.createSafeSheetName("Report"); // returns " O'Brien's sales "
Sheet reportSheet = wb.createSheet(safeName);
short rowc = 0;
Row nrow = reportSheet.createRow(rowc++);
short cellc = 0;
if (rows == null) return;
if (columns == null && rows.size() > 0)
{
columns = new ArrayList<ColumnDef>(CollectionUtils.collect(rows.get(0).keySet(), new Transformer() {
@Override
public Object transform(final Object input) {
return new ColumnDef()
{{
setName((String)input);
}};
}
}));
}
if (columns != null)
{
for (ColumnDef column : columns)
{
Cell cell = nrow.createCell(cellc++);
cell.setCellValue(column.getName());
}
}
for (Map<String, Object> row : rows)
{
nrow = reportSheet.createRow(rowc++);
cellc = 0;
for (ColumnDef column : columns)
{
Cell cell = nrow.createCell(cellc++);
cell.setCellValue(String.valueOf(row.get(column.getName())));
}
}
wb.write(out);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} | java | {
"resource": ""
} |
q19383 | Extern.readPackageListFromFile | train | private void readPackageListFromFile(String path, DocFile pkgListPath)
throws Fault {
DocFile file = pkgListPath.resolve(DocPaths.PACKAGE_LIST);
if (! (file.isAbsolute() || linkoffline)){
file = file.resolveAgainst(DocumentationTool.Location.DOCUMENTATION_OUTPUT);
}
try {
if (file.exists() && file.canRead()) {
boolean pathIsRelative =
!DocFile.createFileForInput(configuration, path).isAbsolute()
&& !isUrl(path);
readPackageList(file.openInputStream(), path, pathIsRelative);
} else {
throw new Fault(configuration.getText("doclet.File_error", file.getPath()), null);
}
} catch (IOException exc) {
throw new Fault(configuration.getText("doclet.File_error", file.getPath()), exc);
}
} | java | {
"resource": ""
} |
q19384 | VisibleMemberMap.sort | train | private void sort(List<ClassDoc> list) {
List<ClassDoc> classes = new ArrayList<ClassDoc>();
List<ClassDoc> interfaces = new ArrayList<ClassDoc>();
for (int i = 0; i < list.size(); i++) {
ClassDoc cd = list.get(i);
if (cd.isClass()) {
classes.add(cd);
} else {
interfaces.add(cd);
}
}
list.clear();
list.addAll(classes);
list.addAll(interfaces);
} | java | {
"resource": ""
} |
q19385 | ThreadExtensions.runCallableWithCpuCores | train | public static <T> T runCallableWithCpuCores(Callable<T> task, int cpuCores)
throws ExecutionException, InterruptedException
{
ForkJoinPool forkJoinPool = new ForkJoinPool(cpuCores);
return forkJoinPool.submit(task).get();
} | java | {
"resource": ""
} |
q19386 | ThreadExtensions.runAsyncSupplierWithCpuCores | train | public static <T> T runAsyncSupplierWithCpuCores(Supplier<T> supplier, int cpuCores)
throws ExecutionException, InterruptedException
{
ForkJoinPool forkJoinPool = new ForkJoinPool(cpuCores);
CompletableFuture<T> future = CompletableFuture.supplyAsync(supplier, forkJoinPool);
return future.get();
} | java | {
"resource": ""
} |
q19387 | ThreadExtensions.resolveRunningThreads | train | public static Thread[] resolveRunningThreads()
{
final Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
final Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
return threadArray;
} | java | {
"resource": ""
} |
q19388 | TraceWrapper.alert | train | public final Trace alert(Class<?> c, String message) {
return _trace.alert(c, message);
} | java | {
"resource": ""
} |
q19389 | GeneratedDFactoryDaoImpl.queryByBaseUrl | train | public Iterable<DFactory> queryByBaseUrl(java.lang.String baseUrl) {
return queryByField(null, DFactoryMapper.Field.BASEURL.getFieldName(), baseUrl);
} | java | {
"resource": ""
} |
q19390 | GeneratedDFactoryDaoImpl.queryByClientId | train | public Iterable<DFactory> queryByClientId(java.lang.String clientId) {
return queryByField(null, DFactoryMapper.Field.CLIENTID.getFieldName(), clientId);
} | java | {
"resource": ""
} |
q19391 | GeneratedDFactoryDaoImpl.queryByClientSecret | train | public Iterable<DFactory> queryByClientSecret(java.lang.String clientSecret) {
return queryByField(null, DFactoryMapper.Field.CLIENTSECRET.getFieldName(), clientSecret);
} | java | {
"resource": ""
} |
q19392 | CONLLReader.constructSentence | train | private Sentence constructSentence(List<Token> tokens) throws IOException {
Sentence sentence;
try {
sentence = new SimpleSentence(tokens, strict);
} catch (IllegalArgumentException e) {
throw new IOException(e.getMessage());
}
return sentence;
} | java | {
"resource": ""
} |
q19393 | Options.checkAccess | train | public boolean checkAccess(AccessFlags flags){
boolean isPublic = flags.is(AccessFlags.ACC_PUBLIC);
boolean isProtected = flags.is(AccessFlags.ACC_PROTECTED);
boolean isPrivate = flags.is(AccessFlags.ACC_PRIVATE);
boolean isPackage = !(isPublic || isProtected || isPrivate);
if ((showAccess == AccessFlags.ACC_PUBLIC) && (isProtected || isPrivate || isPackage))
return false;
else if ((showAccess == AccessFlags.ACC_PROTECTED) && (isPrivate || isPackage))
return false;
else if ((showAccess == 0) && (isPrivate))
return false;
else
return true;
} | java | {
"resource": ""
} |
q19394 | RequestMatcher.matchProduces | train | public static boolean matchProduces(InternalRoute route, InternalRequest<?> request) {
if (nonEmpty(request.getAccept())) {
List<MediaType> matchedAcceptTypes = getAcceptedMediaTypes(route.getProduces(), request.getAccept());
if (nonEmpty(matchedAcceptTypes)) {
request.setMatchedAccept(matchedAcceptTypes.get(0));
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q19395 | RequestMatcher.matchConsumes | train | public static boolean matchConsumes(InternalRoute route, InternalRequest<?> request) {
if (route.getConsumes().contains(WILDCARD)) {
return true;
}
return route.getConsumes().contains(request.getContentType());
} | java | {
"resource": ""
} |
q19396 | IOUtils.getBytes | train | public static byte[] getBytes(final InputStream sourceInputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
for (int len = 0; (len = sourceInputStream.read(buffer)) != -1;) {
byteArrayOutputStream.write(buffer, 0, len);
}
byte[] arrayOfByte = byteArrayOutputStream.toByteArray();
return arrayOfByte;
} | java | {
"resource": ""
} |
q19397 | IOUtils.write | train | public static boolean write(final InputStream sourceInputStream,
final OutputStream destinationOutputStream) throws IOException {
byte[] buffer = buildBuffer(BUFFER_SIZE);
for (int len = 0; (len = sourceInputStream.read(buffer)) != -1;) {
destinationOutputStream.write(buffer, 0, len);
}
destinationOutputStream.flush();
return true;
} | java | {
"resource": ""
} |
q19398 | IOUtils.write | train | public static boolean write(final byte[] sourceBytes, final OutputStream destinationOutputStream)
throws IOException {
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(destinationOutputStream);
bufferedOutputStream.write(sourceBytes, 0, sourceBytes.length);
bufferedOutputStream.flush();
return true;
} | java | {
"resource": ""
} |
q19399 | CachedResultSet.asList | train | public <T extends DataObject> List<T> asList(Class<T> type) throws InstantiationException, IllegalAccessException {
Map<String, Field> fields = new HashMap<String, Field>();
for (String column: columns) try { fields.put(column, Beans.getKnownField(type, column)); } catch (Exception x) {}
List<T> list = new ArrayList<T>();
for (Object[] row: rows) {
T object = type.newInstance();
for (int i = 0; i < row.length; ++i) {
Field field = fields.get(columns[i]);
if (field != null) {
Beans.setValue(object, field, row[i]);
}
}
list.add(object);
}
return list;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.