_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q17200
FrameworkController.getController
train
@SuppressWarnings("unchecked") public static <T> T getController(BaseComponent comp, Class<T> type) { while (comp != null) { Object controller = getController(comp); if (type.isInstance(controller)) { return (T) controller; } comp = comp.getParent(); } return null; }
java
{ "resource": "" }
q17201
FrameworkController.afterInitialized
train
@Override public void afterInitialized(BaseComponent comp) { root = (BaseUIComponent) comp; this.comp = root; comp.setAttribute(Constants.ATTR_COMPOSER, this); comp.addEventListener(ThreadEx.ON_THREAD_COMPLETE, threadCompletionListener); appContext = SpringUtil.getAppContext(); appFramework = FrameworkUtil.getAppFramework(); eventManager = EventManager.getInstance(); initialize(); }
java
{ "resource": "" }
q17202
DropContainer.render
train
public static DropContainer render(BaseComponent dropRoot, BaseComponent droppedItem) { IDropRenderer dropRenderer = DropUtil.getDropRenderer(droppedItem); if (dropRenderer == null || !dropRenderer.isEnabled()) { return null; } BaseComponent renderedItem = dropRenderer.renderDroppedItem(droppedItem); DropContainer dropContainer = null; if (renderedItem != null) { String title = dropRenderer.getDisplayText(droppedItem); dropContainer = renderedItem.getAncestor(DropContainer.class); if (dropContainer != null) { dropContainer.setTitle(title); dropContainer.moveToTop(dropRoot); } else { dropContainer = DropContainer.create(dropRoot, renderedItem, title, InfoPanelService.getActionListeners(droppedItem)); } } return dropContainer; }
java
{ "resource": "" }
q17203
DropContainer.create
train
private static DropContainer create(BaseComponent dropRoot, BaseComponent cmpt, String title, List<ActionListener> actionListeners) { DropContainer dc = (DropContainer) PageUtil.createPage(TEMPLATE, null); dc.actionListeners = actionListeners; dc.setTitle(title); dc.setDropid(SCLASS); dc.setDragid(SCLASS); dc.addChild(cmpt); dc.moveToTop(dropRoot); ActionListener.bindActionListeners(dc, actionListeners); return dc; }
java
{ "resource": "" }
q17204
DropContainer.doAction
train
@Override public void doAction(Action action) { switch (action) { case REMOVE: close(); break; case HIDE: setVisible(false); break; case SHOW: setVisible(true); break; case COLLAPSE: setSize(Size.MINIMIZED); break; case EXPAND: setSize(Size.NORMAL); break; case TOP: moveToTop(); break; } }
java
{ "resource": "" }
q17205
DropContainer.onDrop
train
@EventHandler("drop") private void onDrop(DropEvent event) { BaseComponent dragged = event.getRelatedTarget(); if (dragged instanceof DropContainer) { getParent().addChild(dragged, this); } }
java
{ "resource": "" }
q17206
BaseRenderer.addContent
train
public Span addContent(Row row, String label) { Span cell = new Span(); cell.addChild(CWFUtil.getTextComponent(label)); row.addChild(cell); return cell; }
java
{ "resource": "" }
q17207
BaseRenderer.addCell
train
public Cell addCell(Row row, String label) { Cell cell = new Cell(label); row.addChild(cell); return cell; }
java
{ "resource": "" }
q17208
BaseRenderer.addColumn
train
public Column addColumn(Grid grid, String label, String width, String sortBy) { Column column = new Column(); grid.getColumns().addChild(column); column.setLabel(label); column.setWidth(width); column.setSortComparator(sortBy); column.setSortOrder(SortOrder.ASCENDING); return column; }
java
{ "resource": "" }
q17209
FileReportGenerator.outputNameFor
train
public String outputNameFor(String output) { Report report = openReport(output); return outputNameOf(report); }
java
{ "resource": "" }
q17210
PropertyEditorEnum.init
train
@Override protected void init(Object target, PropertyInfo propInfo, PropertyGrid propGrid) { super.init(target, propInfo, propGrid); Iterable<?> iter = (Iterable<?>) propInfo.getPropertyType().getSerializer(); for (Object value : iter) { appendItem(value.toString(), value); } }
java
{ "resource": "" }
q17211
Jashing.bootstrap
train
public Jashing bootstrap() { if (bootstrapped.compareAndSet(false, true)) { /* bootstrap event sources* */ ServiceManager eventSources = injector.getInstance(ServiceManager.class); eventSources.startAsync(); /* bootstrap server */ Service application = injector.getInstance(JashingServer.class); application.startAsync(); Runtime.getRuntime().addShutdownHook(shutdownHook); LOGGER.info("Jashing has started!"); } else { throw new IllegalStateException("Jashing already bootstrapped"); } return this; }
java
{ "resource": "" }
q17212
Jashing.shutdown
train
public void shutdown() { if (bootstrapped.compareAndSet(true, false)) { LOGGER.info("Shutting down Jashing..."); injector.getInstance(ServiceManager.class).stopAsync().awaitStopped(); injector.getInstance(JashingServer.class).stopAsync().awaitTerminated(); /* shutdown method might be called by this hook. So, trying to remove * hook which is currently is progress causes error */ if (!shutdownHook.isAlive()) { Runtime.getRuntime().removeShutdownHook(shutdownHook); } LOGGER.info("Jashing has stopped."); } else { throw new IllegalStateException("Jashing is not bootstrapped"); } }
java
{ "resource": "" }
q17213
LayoutUtil.copyAttributes
train
public static void copyAttributes(Element source, Map<String, String> dest) { NamedNodeMap attributes = source.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); dest.put(attribute.getNodeName(), attribute.getNodeValue()); } } }
java
{ "resource": "" }
q17214
LayoutUtil.copyAttributes
train
public static void copyAttributes(Map<String, String> source, Element dest) { for (Entry<String, String> entry : source.entrySet()) { dest.setAttribute(entry.getKey(), entry.getValue()); } }
java
{ "resource": "" }
q17215
HelpView.initTopicTree
train
private void initTopicTree() { DefaultMutableTreeNode topicTree = getDataAsTree(); if (topicTree != null) { initTopicTree(rootNode, topicTree.getRoot()); } }
java
{ "resource": "" }
q17216
HelpView.initTopicTree
train
private void initTopicTree(HelpTopicNode htnParent, TreeNode ttnParent) { for (int i = 0; i < ttnParent.getChildCount(); i++) { TreeNode ttnChild = ttnParent.getChildAt(i); HelpTopic ht = getTopic(ttnChild); HelpTopicNode htnChild = new HelpTopicNode(ht); htnParent.addChild(htnChild); initTopicTree(htnChild, ttnChild); } }
java
{ "resource": "" }
q17217
HelpView.getDataAsTree
train
protected DefaultMutableTreeNode getDataAsTree() { try { return (DefaultMutableTreeNode) MethodUtils.invokeMethod(view, "getDataAsTree", null); } catch (Exception e) { return null; } }
java
{ "resource": "" }
q17218
TreeUtil.findNodeByLabel
train
public static Treenode findNodeByLabel(Treeview tree, String label, boolean caseSensitive) { for (Treenode item : tree.getChildren(Treenode.class)) { if (caseSensitive ? label.equals(item.getLabel()) : label.equalsIgnoreCase(item.getLabel())) { return item; } } return null; }
java
{ "resource": "" }
q17219
TreeUtil.getPath
train
public static String getPath(Treenode item, boolean useLabels) { StringBuilder sb = new StringBuilder(); boolean needsDelim = false; while (item != null) { if (needsDelim) { sb.insert(0, '\\'); } else { needsDelim = true; } sb.insert(0, useLabels ? item.getLabel() : item.getIndex()); item = (Treenode) item.getParent(); } return sb.toString(); }
java
{ "resource": "" }
q17220
TreeUtil.sort
train
public static void sort(BaseComponent parent, boolean recurse) { if (parent == null || parent.getChildren().size() < 2) { return; } int i = 1; int size = parent.getChildren().size(); while (i < size) { Treenode item1 = (Treenode) parent.getChildren().get(i - 1); Treenode item2 = (Treenode) parent.getChildren().get(i); if (compare(item1, item2) > 0) { parent.swapChildren(i - 1, i); i = i == 1 ? 2 : i - 1; } else { i++; } } if (recurse) { for (BaseComponent child : parent.getChildren()) { sort(child, recurse); } } }
java
{ "resource": "" }
q17221
TreeUtil.compare
train
private static int compare(Treenode item1, Treenode item2) { String label1 = item1.getLabel(); String label2 = item2.getLabel(); return label1 == label2 ? 0 : label1 == null ? -1 : label2 == null ? -1 : label1.compareToIgnoreCase(label2); }
java
{ "resource": "" }
q17222
TreeUtil.search
train
private static Treenode search(Iterable<Treenode> root, String text, ITreenodeSearch search) { for (Treenode node : root) { if (search.isMatch(node, text)) { return node; } } return null; }
java
{ "resource": "" }
q17223
CommandRegistry.get
train
public Command get(String commandName, boolean forceCreate) { Command command = commands.get(commandName); if (command == null && forceCreate) { command = new Command(commandName); add(command); } return command; }
java
{ "resource": "" }
q17224
CommandRegistry.bindShortcuts
train
private void bindShortcuts(Map<Object, Object> shortcuts) { for (Object commandName : shortcuts.keySet()) { bindShortcuts(commandName.toString(), shortcuts.get(commandName).toString()); } }
java
{ "resource": "" }
q17225
PropertiesLoaderBuilder.loadProperty
train
public PropertiesLoaderBuilder loadProperty(String name) { if (env.containsProperty(name)) { props.put(name, env.getProperty(name)); } return this; }
java
{ "resource": "" }
q17226
PropertiesLoaderBuilder.addProperty
train
public PropertiesLoaderBuilder addProperty(String name, String value) { props.put(name, value); return this; }
java
{ "resource": "" }
q17227
AbstractRenderer.createCell
train
protected <C extends BaseUIComponent> C createCell(BaseComponent parent, Object value, String prefix, String style, String width, Class<C> clazz) { C container = null; try { container = clazz.newInstance(); container.setParent(parent); container.setStyles(cellStyle); if (width != null) { container.setWidth(width); } if (value instanceof BaseComponent) { ((BaseComponent) value).setParent(container); } else if (value != null) { createLabel(container, value, prefix, style); } } catch (Exception e) {} ; return container; }
java
{ "resource": "" }
q17228
ByteArrays.removeEntry
train
public static byte[] removeEntry(byte[] a, int idx) { byte[] b = new byte[a.length - 1]; for (int i = 0; i < b.length; i++) { if (i < idx) { b[i] = a[i]; } else { b[i] = a[i + 1]; } } return b; }
java
{ "resource": "" }
q17229
KafkaService.getConfigParams
train
private Map<String, Object> getConfigParams(Class<?> clazz) { Map<String, Object> params = new HashMap<>(); for (Field field : clazz.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers()) && field.getName().endsWith("_CONFIG")) { try { String key = field.get(null).toString(); String value = SpringUtil.getProperty("org.carewebframework.messaging.kafka." + key); if (value != null) { params.put(key, value); } } catch (Exception e) {} } } return params; }
java
{ "resource": "" }
q17230
QueryWhereClauseBuilder.buildWhereClause
train
public static String buildWhereClause(Object object, MapSqlParameterSource params) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { LOGGER.debug("Building query"); final StringBuilder query = new StringBuilder(); boolean first = true; for (Field field : object.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(QueryWhereClause.class) || field.isAnnotationPresent(QueryWhereClauses.class)) { final String fieldName = field.getName(); LOGGER.trace("New annotated field found: {}", fieldName); QueryWhereClause[] annotations = field.getAnnotationsByType(QueryWhereClause.class); for (QueryWhereClause annotation : annotations) { String whereValue = annotation.value(); int[] types = annotation.fieldTypes(); int index = 0; LOGGER.trace("Unprocessed whereClause: {}", whereValue); Matcher matcher = PARAM_PATTERN.matcher(whereValue); boolean hasValue = false; while (matcher.find()) { String originalParam = matcher.group(1); LOGGER.debug("New parameter found in the query: {}", originalParam); String convertedParam = originalParam.replaceAll("this", fieldName); Object value = null; try { value = BeanUtils.getNestedProperty(object, convertedParam); } catch (NestedNullException e) { LOGGER.info("Bean not accessible= {}", e.getMessage()); } if (value == null) { LOGGER.debug("Param {} was null, ignoring in the query", convertedParam); } else { hasValue = true; whereValue = StringUtils.replace(whereValue, "{"+originalParam+ "}", ":" + convertedParam); if (params != null) { if (index <= types.length-1) { params.addValue(convertedParam, value, types[index]); } else { params.addValue(convertedParam, value); } } } index ++; } if (hasValue) { if (!first) { query.append(" AND "); } else { first = false; } query.append(whereValue); } } } } LOGGER.debug("built query={}", query); return query.toString(); }
java
{ "resource": "" }
q17231
LayoutManager.show
train
public static void show(boolean manage, String deflt, IEventListener closeListener) { Map<String, Object> args = new HashMap<>(); args.put("manage", manage); args.put("deflt", deflt); PopupDialog.show(RESOURCE_PREFIX + "layoutManager.fsp", args, true, true, true, closeListener); }
java
{ "resource": "" }
q17232
ManagedContext.compareTo
train
@Override public int compareTo(IManagedContext<DomainClass> o) { int pri1 = o.getPriority(); int pri2 = getPriority(); return this == o ? 0 : pri1 < pri2 ? -1 : 1; }
java
{ "resource": "" }
q17233
MenuUtil.pruneMenus
train
public static void pruneMenus(BaseComponent parent) { while (parent != null && parent instanceof BaseMenuComponent) { if (parent.getChildren().isEmpty()) { BaseComponent newParent = parent.getParent(); parent.destroy(); parent = newParent; } else { break; } } }
java
{ "resource": "" }
q17234
MenuUtil.findMenu
train
public static BaseMenuComponent findMenu(BaseComponent parent, String label, BaseComponent insertBefore) { for (BaseMenuComponent child : parent.getChildren(BaseMenuComponent.class)) { if (label.equalsIgnoreCase(child.getLabel())) { return child; } } BaseMenuComponent cmp = createMenuOrMenuitem(parent); cmp.setLabel(label); parent.addChild(cmp, insertBefore); return cmp; }
java
{ "resource": "" }
q17235
MenuUtil.sortMenu
train
public static void sortMenu(BaseComponent parent, int startIndex, int endIndex) { List<BaseComponent> items = parent.getChildren(); int bottom = startIndex + 1; for (int i = startIndex; i < endIndex;) { BaseComponent item1 = items.get(i++); BaseComponent item2 = items.get(i); if (item1 instanceof BaseMenuComponent && item2 instanceof BaseMenuComponent && ((BaseMenuComponent) item1) .getLabel().compareToIgnoreCase(((BaseMenuComponent) item2).getLabel()) > 0) { parent.swapChildren(i - 1, i); if (i > bottom) { i -= 2; } } } }
java
{ "resource": "" }
q17236
MenuUtil.getPath
train
public static String getPath(BaseMenuComponent comp) { StringBuilder sb = new StringBuilder(); getPath(comp, sb); return sb.toString(); }
java
{ "resource": "" }
q17237
MenuUtil.getPath
train
private static void getPath(BaseComponent comp, StringBuilder sb) { while (comp instanceof BaseMenuComponent) { sb.insert(0, "\\" + ((BaseMenuComponent) comp).getLabel()); comp = comp.getParent(); } }
java
{ "resource": "" }
q17238
PluginWakeOnMessage.onPluginEvent
train
@Override public void onPluginEvent(PluginEvent event) { switch (event.getAction()) { case SUBSCRIBE: // Upon initial subscription, begin listening for specified generic events. plugin = event.getPlugin(); doSubscribe(true); break; case LOAD: // Stop listening once loaded. plugin.unregisterListener(this); break; case UNSUBSCRIBE: // Stop listening for generic events once unsubscribed from plugin events. doSubscribe(false); break; } }
java
{ "resource": "" }
q17239
DefaultRetryClient.retry
train
@Override public void retry(Face face, Interest interest, OnData onData, OnTimeout onTimeout) throws IOException { RetryContext context = new RetryContext(face, interest, onData, onTimeout); retryInterest(context); }
java
{ "resource": "" }
q17240
DefaultRetryClient.retryInterest
train
private synchronized void retryInterest(RetryContext context) throws IOException { LOGGER.info("Retrying interest: " + context.interest.toUri()); context.face.expressInterest(context.interest, context, context); totalRetries++; }
java
{ "resource": "" }
q17241
ServerBaseImpl.register
train
public void register() throws IOException { try { registeredPrefixId = face.registerPrefix(prefix, this, new OnRegisterFailed() { @Override public void onRegisterFailed(Name prefix) { registeredPrefixId = UNREGISTERED; logger.log(Level.SEVERE, "Failed to register prefix: " + prefix.toUri()); } }, new ForwardingFlags()); logger.log(Level.FINER, "Registered a new prefix: " + prefix.toUri()); } catch (net.named_data.jndn.security.SecurityException e) { throw new IOException("Failed to communicate to face due to security error", e); } }
java
{ "resource": "" }
q17242
MessageUtil.isMessageExcluded
train
public static boolean isMessageExcluded(Message message, Recipient recipient) { return isMessageExcluded(message, recipient.getType(), recipient.getValue()); }
java
{ "resource": "" }
q17243
MessageUtil.isMessageExcluded
train
public static boolean isMessageExcluded(Message message, RecipientType recipientType, String recipientValue) { Recipient[] recipients = (Recipient[]) message.getMetadata("cwf.pub.recipients"); if (recipients == null || recipients.length == 0) { return false; } boolean excluded = false; for (Recipient recipient : recipients) { if (recipient.getType() == recipientType) { excluded = true; if (recipient.getValue().equals(recipientValue)) { return false; } } } return excluded; }
java
{ "resource": "" }
q17244
Proxy.getLabel
train
public String getLabel() { String label = getProperty(labelProperty); label = label == null ? node.getLabel() : label; if (label == null) { label = getDefaultInstanceName(); setProperty(labelProperty, label); } return label; }
java
{ "resource": "" }
q17245
Proxy.getProperty
train
private String getProperty(String propertyName) { return propertyName == null ? null : (String) getPropertyValue(propertyName); }
java
{ "resource": "" }
q17246
QueueSpec.setField
train
public QueueSpec setField(String fieldName, Object value) { fieldData.put(fieldName, value); return this; }
java
{ "resource": "" }
q17247
UserContext.changeUser
train
public static void changeUser(IUser user) { try { getUserContext().requestContextChange(user); } catch (Exception e) { log.error("Error during user context change.", e); } }
java
{ "resource": "" }
q17248
UserContext.getUserContext
train
@SuppressWarnings("unchecked") public static ISharedContext<IUser> getUserContext() { return (ISharedContext<IUser>) ContextManager.getInstance().getSharedContext(UserContext.class.getName()); }
java
{ "resource": "" }
q17249
PHSCoverLetterV1_2Generator.getPHSCoverLetter
train
private PHSCoverLetter12Document getPHSCoverLetter() { PHSCoverLetter12Document phsCoverLetterDocument = PHSCoverLetter12Document.Factory .newInstance(); PHSCoverLetter12 phsCoverLetter = PHSCoverLetter12.Factory .newInstance(); CoverLetterFile coverLetterFile = CoverLetterFile.Factory.newInstance(); phsCoverLetter.setFormVersion(FormVersion.v1_2.getVersion()); AttachedFileDataType attachedFileDataType = null; for (NarrativeContract narrative : pdDoc.getDevelopmentProposal() .getNarratives()) { if (narrative.getNarrativeType().getCode() != null && Integer.parseInt(narrative.getNarrativeType().getCode()) == NARRATIVE_PHS_COVER_LETTER) { attachedFileDataType = getAttachedFileType(narrative); if(attachedFileDataType != null){ coverLetterFile.setCoverLetterFilename(attachedFileDataType); break; } } } phsCoverLetter.setCoverLetterFile(coverLetterFile); phsCoverLetterDocument.setPHSCoverLetter12(phsCoverLetter); return phsCoverLetterDocument; }
java
{ "resource": "" }
q17250
RRBudget10V1_3Generator.setBudgetYearDataType
train
private void setBudgetYearDataType(RRBudget1013 rrBudget,BudgetPeriodDto periodInfo) { BudgetYearDataType budgetYear = rrBudget.addNewBudgetYear(); if (periodInfo != null) { budgetYear.setBudgetPeriodStartDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getStartDate())); budgetYear.setBudgetPeriodEndDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getEndDate())); budgetYear.setKeyPersons(getKeyPersons(periodInfo)); budgetYear.setOtherPersonnel(getOtherPersonnel(periodInfo)); if (periodInfo.getTotalCompensation() != null) { budgetYear.setTotalCompensation(periodInfo .getTotalCompensation().bigDecimalValue()); } budgetYear.setEquipment(getEquipment(periodInfo)); budgetYear.setTravel(getTravel(periodInfo)); budgetYear .setParticipantTraineeSupportCosts(getParticipantTraineeSupportCosts(periodInfo)); budgetYear.setOtherDirectCosts(getOtherDirectCosts(periodInfo)); BigDecimal directCosts = periodInfo.getDirectCostsTotal() .bigDecimalValue(); budgetYear.setDirectCosts(directCosts); IndirectCosts indirectCosts = getIndirectCosts(periodInfo); if (indirectCosts != null) { budgetYear.setIndirectCosts(indirectCosts); budgetYear.setTotalCosts(periodInfo.getDirectCostsTotal().bigDecimalValue().add(indirectCosts.getTotalIndirectCosts())); }else{ budgetYear.setTotalCosts(periodInfo.getDirectCostsTotal().bigDecimalValue()); } budgetYear.setCognizantFederalAgency(periodInfo .getCognizantFedAgency()); } }
java
{ "resource": "" }
q17251
PropertyAwareResource.setApplicationContext
train
@Override public void setApplicationContext(ApplicationContext appContext) throws BeansException { try (InputStream is = originalResource.getInputStream();) { ConfigurableListableBeanFactory beanFactory = ((AbstractRefreshableApplicationContext) appContext) .getBeanFactory(); StringBuilder sb = new StringBuilder(); Iterator<String> iter = IOUtils.lineIterator(is, "UTF-8"); boolean transformed = false; while (iter.hasNext()) { String line = iter.next(); if (line.contains("${")) { transformed = true; line = beanFactory.resolveEmbeddedValue(line); } sb.append(line); } transformedResource = !transformed ? originalResource : new ByteArrayResource(sb.toString().getBytes()); } catch (IOException e) { throw MiscUtil.toUnchecked(e); } }
java
{ "resource": "" }
q17252
PHS398CoverPageSupplementBaseGenerator.getCellLines
train
protected List<String> getCellLines(String explanation) { int startPos = 0; List<String> cellLines = new ArrayList<>(); for (int commaPos = 0; commaPos > -1;) { commaPos = explanation.indexOf(",", startPos); if (commaPos >= 0) { String cellLine = (explanation.substring(startPos, commaPos).trim()); explanation = explanation.substring(commaPos + 1); if (cellLine.length() > 0) { cellLines.add(cellLine); } } else if (explanation.length() > 0) { cellLines.add(explanation.trim()); } } return cellLines; }
java
{ "resource": "" }
q17253
TempFileHandler.reset
train
public void reset() throws IOException { if (t1==null || t2==null) { throw new IllegalStateException("Cannot swap after close."); } if (getOutput().length()>0) { toggle = !toggle; // reset the new output to length()=0 try (OutputStream unused = new FileOutputStream(getOutput())) { //this is empty because we only need to close it } } else { throw new IOException("Cannot swap to an empty file."); } }
java
{ "resource": "" }
q17254
TempFileHandler.close
train
public void close() throws IOException { if (t1==null || t2==null) { return; } try { if (getOutput().length() > 0) { Files.copy(getOutput().toPath(), output.toPath(), StandardCopyOption.REPLACE_EXISTING); } else if (getInput().length() > 0) { Files.copy(getInput().toPath(), output.toPath(), StandardCopyOption.REPLACE_EXISTING); } else { throw new IOException("Temporary files corrupted."); } } finally { t1.delete(); t2.delete(); t1 = null; t2 = null; } }
java
{ "resource": "" }
q17255
GlobalLibraryV1_0Generator.getAddressRequireCountryDataType
train
public AddressRequireCountryDataType getAddressRequireCountryDataType(DepartmentalPersonDto person) { AddressRequireCountryDataType address = AddressRequireCountryDataType.Factory.newInstance(); if (person != null) { String street1 = person.getAddress1(); address.setStreet1(street1); String street2 = person.getAddress2(); if (street2 != null && !street2.equals("")) { address.setStreet2(street2); } String city = person.getCity(); address.setCity(city); String county = person.getCounty(); if (county != null && !county.equals("")) { address.setCounty(county); } String state = person.getState(); if (state != null && !state.equals("")) { address.setState(state); } String zipcode = person.getPostalCode(); if (zipcode != null && !zipcode.equals("")) { address.setZipCode(zipcode); } String country = person.getCountryCode(); address.setCountry(CountryCodeType.Enum.forString(country)); } return address; }
java
{ "resource": "" }
q17256
GlobalLibraryV1_0Generator.getHumanNameDataType
train
public HumanNameDataType getHumanNameDataType(KeyPersonDto keyPerson) { HumanNameDataType humanName = HumanNameDataType.Factory.newInstance(); humanName.setFirstName(keyPerson.getFirstName()); humanName.setLastName(keyPerson.getLastName()); String middleName = keyPerson.getMiddleName(); if (middleName != null && !middleName.equals("")) { humanName.setMiddleName(middleName); } return humanName; }
java
{ "resource": "" }
q17257
Broker.sendMessage
train
public void sendMessage(String channel, Message message) { ensureChannel(channel); admin.getRabbitTemplate().convertAndSend(exchange.getName(), channel, message); }
java
{ "resource": "" }
q17258
ActiveMqQueue.putToQueue
train
protected boolean putToQueue(IQueueMessage<ID, DATA> msg) { try { BytesMessage message = getProducerSession().createBytesMessage(); message.writeBytes(serialize(msg)); getMessageProducer().send(message); return true; } catch (Exception e) { throw e instanceof QueueException ? (QueueException) e : new QueueException(e); } }
java
{ "resource": "" }
q17259
CompositeException.hasException
train
public boolean hasException(Class<? extends Throwable> type) { for (Throwable exception : exceptions) { if (type.isInstance(exception)) { return true; } } return false; }
java
{ "resource": "" }
q17260
CompositeException.getStackTrace
train
@Override public StackTraceElement[] getStackTrace() { ArrayList<StackTraceElement> stackTrace = new ArrayList<>(); for (Throwable exception : exceptions) { stackTrace.addAll(Arrays.asList(exception.getStackTrace())); } return stackTrace.toArray(new StackTraceElement[stackTrace.size()]); }
java
{ "resource": "" }
q17261
LongIntSortedVector.dot
train
public int dot(int[] other) { int dot = 0; for (int c = 0; c < used && indices[c] < other.length; c++) { if (indices[c] > Integer.MAX_VALUE) { break; } dot += values[c] * other[SafeCast.safeLongToInt(indices[c])]; } return dot; }
java
{ "resource": "" }
q17262
LongIntSortedVector.dot
train
public int dot(int[][] matrix, int col) { int ret = 0; for (int c = 0; c < used && indices[c] < matrix.length; c++) { if (indices[c] > Integer.MAX_VALUE) { break; } ret += values[c] * matrix[SafeCast.safeLongToInt(indices[c])][col]; } return ret; }
java
{ "resource": "" }
q17263
ResourceUtil.copyResourceToFile
train
public static void copyResourceToFile(String resourceAbsoluteClassPath, File targetFile) throws IOException { InputStream is = ResourceUtil.class.getResourceAsStream(resourceAbsoluteClassPath); if (is == null) { throw new IOException("Resource not found! " + resourceAbsoluteClassPath); } OutputStream os = null; try { os = new FileOutputStream(targetFile); byte[] buffer = new byte[2048]; int length; while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); } os.flush(); } finally { try { is.close(); if (os != null) { os.close(); } } catch (Exception ignore) { // ignore } } }
java
{ "resource": "" }
q17264
ResourceUtil.getAbsolutePath
train
public static String getAbsolutePath(String classPath) { URL configUrl = Thread.currentThread().getContextClassLoader().getResource(classPath.substring(1)); if (configUrl == null) { configUrl = ResourceUtil.class.getResource(classPath); } if (configUrl == null) { return null; } try { return configUrl.toURI().getPath(); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q17265
PropertyEditorBoolean.setFocus
train
@Override public void setFocus() { Radiobutton radio = editor.getSelected(); if (radio == null) { radio = (Radiobutton) editor.getChildren().get(0); } radio.setFocus(true); }
java
{ "resource": "" }
q17266
DesignContextMenu.getInstance
train
public static DesignContextMenu getInstance() { Page page = ExecutionContext.getPage(); DesignContextMenu contextMenu = page.getAttribute(DesignConstants.ATTR_DESIGN_MENU, DesignContextMenu.class); if (contextMenu == null) { contextMenu = create(); page.setAttribute(DesignConstants.ATTR_DESIGN_MENU, contextMenu); } return contextMenu; }
java
{ "resource": "" }
q17267
DesignContextMenu.create
train
public static DesignContextMenu create() { return PageUtil.createPage(DesignConstants.RESOURCE_PREFIX + "designContextMenu.fsp", ExecutionContext.getPage()) .get(0).getAttribute("controller", DesignContextMenu.class); }
java
{ "resource": "" }
q17268
DesignContextMenu.disable
train
private void disable(IDisable comp, boolean disabled) { if (comp != null) { comp.setDisabled(disabled); if (comp instanceof BaseUIComponent) { ((BaseUIComponent) comp).addStyle("opacity", disabled ? ".2" : "1"); } } }
java
{ "resource": "" }
q17269
FastMath.logAdd
train
public static double logAdd(double x, double y) { if (FastMath.useLogAddTable) { return SmoothedLogAddTable.logAdd(x,y); } else { return FastMath.logAddExact(x,y); } }
java
{ "resource": "" }
q17270
FastMath.mod
train
public static int mod(int val, int mod) { val = val % mod; if (val < 0) { val += mod; } return val; }
java
{ "resource": "" }
q17271
VerifierImpl.prepareXMLReader
train
protected void prepareXMLReader() throws VerifierConfigurationException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); reader = factory.newSAXParser().getXMLReader(); } catch( SAXException e ) { throw new VerifierConfigurationException(e); } catch( ParserConfigurationException pce ) { throw new VerifierConfigurationException(pce); } }
java
{ "resource": "" }
q17272
SchemaImpl.makeBuiltinMode
train
private Mode makeBuiltinMode(String name, Class cls) { // lookup/create a mode with the given name. Mode mode = lookupCreateMode(name); // Init the element action set for this mode. ActionSet actions = new ActionSet(); // from the current mode we will use further the built in mode. ModeUsage modeUsage = new ModeUsage(Mode.CURRENT, mode); // Add the action corresponding to the built in mode. if (cls == AttachAction.class) actions.setResultAction(new AttachAction(modeUsage)); else if (cls == AllowAction.class) actions.addNoResultAction(new AllowAction(modeUsage)); else if (cls == UnwrapAction.class) actions.setResultAction(new UnwrapAction(modeUsage)); else actions.addNoResultAction(new RejectAction(modeUsage)); // set the actions on any namespace. mode.bindElement(NamespaceSpecification.ANY_NAMESPACE, NamespaceSpecification.DEFAULT_WILDCARD, actions); // the mode is not defined in the script explicitelly mode.noteDefined(null); // creates attribute actions AttributeActionSet attributeActions = new AttributeActionSet(); // if we have a schema for attributes then in the built in modes // we reject attributes by default // otherwise we attach attributes by default in the built in modes if (attributesSchema) attributeActions.setReject(true); else attributeActions.setAttach(true); // set the attribute actions on any namespace mode.bindAttribute(NamespaceSpecification.ANY_NAMESPACE, NamespaceSpecification.DEFAULT_WILDCARD, attributeActions); return mode; }
java
{ "resource": "" }
q17273
SchemaImpl.installHandlers
train
SchemaFuture installHandlers(XMLReader in, SchemaReceiverImpl sr) { Handler h = new Handler(sr); in.setContentHandler(h); return h; }
java
{ "resource": "" }
q17274
SchemaImpl.getModeAttribute
train
private Mode getModeAttribute(Attributes attributes, String localName) { return lookupCreateMode(attributes.getValue("", localName)); }
java
{ "resource": "" }
q17275
SchemaImpl.lookupCreateMode
train
private Mode lookupCreateMode(String name) { if (name == null) return null; name = name.trim(); Mode mode = (Mode)modeMap.get(name); if (mode == null) { mode = new Mode(name, defaultBaseMode); modeMap.put(name, mode); } return mode; }
java
{ "resource": "" }
q17276
DailyTimeIntervalTrigger._advanceToNextDayOfWeekIfNecessary
train
private Date _advanceToNextDayOfWeekIfNecessary (final Date aFireTime, final boolean forceToAdvanceNextDay) { // a. Advance or adjust to next dayOfWeek if need to first, starting next // day with startTimeOfDay. Date fireTime = aFireTime; final TimeOfDay sTimeOfDay = getStartTimeOfDay (); final Date fireTimeStartDate = sTimeOfDay.getTimeOfDayForDate (fireTime); final Calendar fireTimeStartDateCal = _createCalendarTime (fireTimeStartDate); int nDayOfWeekOfFireTime = fireTimeStartDateCal.get (Calendar.DAY_OF_WEEK); final int nCalDay = nDayOfWeekOfFireTime; DayOfWeek eDayOfWeekOfFireTime = PDTHelper.getAsDayOfWeek (nCalDay); // b2. We need to advance to another day if isAfterTimePassEndTimeOfDay is // true, or dayOfWeek is not set. final Set <DayOfWeek> daysOfWeekToFire = getDaysOfWeek (); if (forceToAdvanceNextDay || !daysOfWeekToFire.contains (eDayOfWeekOfFireTime)) { // Advance one day at a time until next available date. for (int i = 1; i <= 7; i++) { fireTimeStartDateCal.add (Calendar.DATE, 1); nDayOfWeekOfFireTime = fireTimeStartDateCal.get (Calendar.DAY_OF_WEEK); final int nCalDay1 = nDayOfWeekOfFireTime; eDayOfWeekOfFireTime = PDTHelper.getAsDayOfWeek (nCalDay1); if (daysOfWeekToFire.contains (eDayOfWeekOfFireTime)) { fireTime = fireTimeStartDateCal.getTime (); break; } } } // Check fireTime not pass the endTime final Date eTime = getEndTime (); if (eTime != null && fireTime.getTime () > eTime.getTime ()) { return null; } return fireTime; }
java
{ "resource": "" }
q17277
QuartzSchedulerHelper.getScheduler
train
@Nonnull public static IScheduler getScheduler (final boolean bStartAutomatically) { try { // Don't try to use a name - results in NPE final IScheduler aScheduler = s_aSchedulerFactory.getScheduler (); if (bStartAutomatically && !aScheduler.isStarted ()) aScheduler.start (); return aScheduler; } catch (final SchedulerException ex) { throw new IllegalStateException ("Failed to create" + (bStartAutomatically ? " and start" : "") + " scheduler!", ex); } }
java
{ "resource": "" }
q17278
QuartzSchedulerHelper.getSchedulerMetaData
train
@Nonnull public static SchedulerMetaData getSchedulerMetaData () { try { // Get the scheduler without starting it return s_aSchedulerFactory.getScheduler ().getMetaData (); } catch (final SchedulerException ex) { throw new IllegalStateException ("Failed to get scheduler metadata", ex); } }
java
{ "resource": "" }
q17279
CronCalendar.setCronExpression
train
public void setCronExpression (@Nonnull final String expression) throws ParseException { final CronExpression newExp = new CronExpression (expression); setCronExpression (newExp); }
java
{ "resource": "" }
q17280
GroupMatcher.groupEquals
train
public static <T extends Key <T>> GroupMatcher <T> groupEquals (final String compareTo) { return new GroupMatcher <> (compareTo, StringOperatorName.EQUALS); }
java
{ "resource": "" }
q17281
GroupMatcher.groupStartsWith
train
public static <T extends Key <T>> GroupMatcher <T> groupStartsWith (final String compareTo) { return new GroupMatcher <> (compareTo, StringOperatorName.STARTS_WITH); }
java
{ "resource": "" }
q17282
GroupMatcher.groupEndsWith
train
public static <T extends Key <T>> GroupMatcher <T> groupEndsWith (final String compareTo) { return new GroupMatcher <> (compareTo, StringOperatorName.ENDS_WITH); }
java
{ "resource": "" }
q17283
GroupMatcher.groupContains
train
public static <T extends Key <T>> GroupMatcher <T> groupContains (final String compareTo) { return new GroupMatcher <> (compareTo, StringOperatorName.CONTAINS); }
java
{ "resource": "" }
q17284
KeyMatcher.keyEquals
train
public static <U extends Key <U>> KeyMatcher <U> keyEquals (final U compareTo) { return new KeyMatcher <> (compareTo); }
java
{ "resource": "" }
q17285
ComponentFactory.instantiate
train
public static <T> T instantiate(Class<T> clazz, CRestConfig crestConfig) throws InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException { try { return accessible(clazz.getDeclaredConstructor(CRestConfig.class)).newInstance(crestConfig); } catch (NoSuchMethodException e) { return accessible(clazz.getDeclaredConstructor()).newInstance(); } }
java
{ "resource": "" }
q17286
AbstractSetTypeConverter.doReverseOne
train
public Object doReverseOne( JTransfo jTransfo, Object domainObject, SyntheticField toField, Class<?> toType, String... tags) throws JTransfoException { return jTransfo.convertTo(domainObject, jTransfo.getToSubType(toType, domainObject), tags); }
java
{ "resource": "" }
q17287
JobChainingJobListener.addJobChainLink
train
public void addJobChainLink (final JobKey firstJob, final JobKey secondJob) { ValueEnforcer.notNull (firstJob, "FirstJob"); ValueEnforcer.notNull (firstJob.getName (), "FirstJob.Name"); ValueEnforcer.notNull (secondJob, "SecondJob"); ValueEnforcer.notNull (secondJob.getName (), "SecondJob.Name"); m_aChainLinks.put (firstJob, secondJob); }
java
{ "resource": "" }
q17288
SvgPathData.checkM
train
private void checkM() throws DatatypeException, IOException { if (context.length() == 0) { appendToContext(current); } current = reader.read(); appendToContext(current); skipSpaces(); checkArg('M', "x coordinate"); skipCommaSpaces(); checkArg('M', "y coordinate"); boolean expectNumber = skipCommaSpaces2(); _checkL('M', expectNumber); }
java
{ "resource": "" }
q17289
SvgPathData.checkC
train
private void checkC() throws DatatypeException, IOException { if (context.length() == 0) { appendToContext(current); } current = reader.read(); appendToContext(current); skipSpaces(); boolean expectNumber = true; for (;;) { switch (current) { default: if (expectNumber) reportNonNumber('C', current); return; case '+': case '-': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; } checkArg('C', "x1 coordinate"); skipCommaSpaces(); checkArg('C', "y1 coordinate"); skipCommaSpaces(); checkArg('C', "x2 coordinate"); skipCommaSpaces(); checkArg('C', "y2 coordinate"); skipCommaSpaces(); checkArg('C', "x coordinate"); skipCommaSpaces(); checkArg('C', "y coordinate"); expectNumber = skipCommaSpaces2(); } }
java
{ "resource": "" }
q17290
TimeOfDay.before
train
public boolean before (final TimeOfDay timeOfDay) { if (timeOfDay.m_nHour > m_nHour) return true; if (timeOfDay.m_nHour < m_nHour) return false; if (timeOfDay.m_nMinute > m_nMinute) return true; if (timeOfDay.m_nMinute < m_nMinute) return false; if (timeOfDay.m_nSecond > m_nSecond) return true; if (timeOfDay.m_nSecond < m_nSecond) return false; return false; // must be equal... }
java
{ "resource": "" }
q17291
TimeOfDay.getTimeOfDayForDate
train
@Nullable public Date getTimeOfDayForDate (final Date dateTime) { if (dateTime == null) return null; final Calendar cal = PDTFactory.createCalendar (); cal.setTime (dateTime); cal.set (Calendar.HOUR_OF_DAY, m_nHour); cal.set (Calendar.MINUTE, m_nMinute); cal.set (Calendar.SECOND, m_nSecond); cal.clear (Calendar.MILLISECOND); return cal.getTime (); }
java
{ "resource": "" }
q17292
ValidatingDocumentBuilder.parse
train
public Document parse(InputSource inputsource) throws SAXException, IOException { return verify(_WrappedBuilder.parse(inputsource)); }
java
{ "resource": "" }
q17293
ValidatingDocumentBuilder.parse
train
public Document parse(File file) throws SAXException, IOException { return verify(_WrappedBuilder.parse(file)); }
java
{ "resource": "" }
q17294
ValidatingDocumentBuilder.parse
train
public Document parse(InputStream strm) throws SAXException, IOException { return verify(_WrappedBuilder.parse(strm)); }
java
{ "resource": "" }
q17295
ValidatingDocumentBuilder.parse
train
public Document parse(String url) throws SAXException, IOException { return verify(_WrappedBuilder.parse(url)); }
java
{ "resource": "" }
q17296
DatatypeBuilderImpl.convertNonNegativeInteger
train
private int convertNonNegativeInteger(String str) { str = str.trim(); DecimalDatatype decimal = new DecimalDatatype(); if (!decimal.lexicallyAllows(str)) return -1; // Canonicalize the value str = decimal.getValue(str, null).toString(); // Reject negative and fractional numbers if (str.charAt(0) == '-' || str.indexOf('.') >= 0) return -1; try { return Integer.parseInt(str); } catch (NumberFormatException e) { // Map out of range integers to MAX_VALUE return Integer.MAX_VALUE; } }
java
{ "resource": "" }
q17297
MicrodataChecker.checkItem
train
private void checkItem(Element root, Deque<Element> parents) throws SAXException { Deque<Element> pending = new ArrayDeque<Element>(); Set<Element> memory = new HashSet<Element>(); memory.add(root); for (Element child : root.children) { pending.push(child); } if (root.itemRef != null) { for (String id : root.itemRef) { Element refElm = idmap.get(id); if (refElm != null) { pending.push(refElm); } else { err("The \u201Citemref\u201D attribute referenced \u201C" + id + "\u201D, but there is no element with an \u201Cid\u201D attribute with that value.", root.locator); } } } boolean memoryError = false; while (pending.size() > 0) { Element current = pending.pop(); if (memory.contains(current)) { memoryError = true; continue; } memory.add(current); if (!current.itemScope) { for (Element child : current.children) { pending.push(child); } } if (current.itemProp != null) { properties.remove(current); if (current.itemScope) { if (!parents.contains(current)) { parents.push(root); checkItem(current, parents); parents.pop(); } else { err("The \u201Citemref\u201D attribute created a circular reference with another item.", current.locator); } } } } if (memoryError) { err("The \u201Citemref\u201D attribute contained redundant references.", root.locator); } }
java
{ "resource": "" }
q17298
Contracts.condition
train
public static <T> ContractCondition<T> condition( final Predicate<T> condition, final Function<T, String> describer) { return ContractCondition.of(condition, describer); }
java
{ "resource": "" }
q17299
TriggerTimeComparator.compare
train
static int compare (final Date nextFireTime1, final int priority1, final TriggerKey key1, final Date nextFireTime2, final int priority2, final TriggerKey key2) { if (nextFireTime1 != null || nextFireTime2 != null) { if (nextFireTime1 == null) return 1; if (nextFireTime2 == null) return -1; if (nextFireTime1.before (nextFireTime2)) return -1; if (nextFireTime1.after (nextFireTime2)) return 1; } int comp = priority2 - priority1; if (comp == 0) comp = key1.compareTo (key2); return comp; }
java
{ "resource": "" }