code
stringlengths
73
34.1k
label
stringclasses
1 value
public Factor getOutsideEntries(int spanStart, int spanEnd) { Tensor entries = new DenseTensor(parentVar.getVariableNumsArray(), parentVar.getVariableSizes(), outsideChart[spanStart][spanEnd]); return new TableFactor(parentVar, entries); }
java
public Factor getMarginalEntries(int spanStart, int spanEnd) { return getOutsideEntries(spanStart, spanEnd).product(getInsideEntries(spanStart, spanEnd)); }
java
public CfgParseTree getBestParseTree() { Factor rootMarginal = getMarginalEntries(0, chartSize() - 1); Assignment bestAssignment = rootMarginal.getMostLikelyAssignments(1).get(0); return getBestParseTree(bestAssignment.getOnlyValue()); }
java
public CfgParseTree getBestParseTreeWithSpan(Object root, int spanStart, int spanEnd) { Preconditions.checkState(!sumProduct); Assignment rootAssignment = parentVar.outcomeArrayToAssignment(root); int rootNonterminalNum = parentVar.assignmentToIntArray(rootAssignment)[0]; double prob = insideCha...
java
public int get(long idx) { if (idx < 0 || idx >= size) { return 0; } return elements[SafeCast.safeLongToInt(idx + start)]; }
java
protected Element findTag(String tagName, Element element) { Node result = element.getFirstChild(); while (result != null) { if (result instanceof Element && (tagName.equals(((Element) result).getNodeName()) || tagName .equals(((Elemen...
java
protected NodeList getTagChildren(String tagName, Element element) { return element.getNamespaceURI() == null ? element.getElementsByTagName(tagName) : element.getElementsByTagNameNS( element.getNamespaceURI(), tagName); }
java
protected void addProperties(Element element, BeanDefinitionBuilder builder) { NamedNodeMap attributes = element.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node node = attributes.item(i); String attrName = getNodeName(node); attrName ...
java
protected String getNodeName(Node node) { String result = node.getLocalName(); return result == null ? node.getNodeName() : result; }
java
protected Object fromXml(String xml, String tagName) throws Exception { Document document = XMLUtil.parseXMLFromString(xml); NodeList nodeList = document.getElementsByTagName(tagName); if (nodeList == null || nodeList.getLength() != 1) { throw new DOMException(DOMException.N...
java
protected String getResourcePath(ParserContext parserContext) { if (parserContext != null) { try { Resource resource = parserContext.getReaderContext().getResource(); return resource == null ? null : resource.getURL().getPath(); } catch (IOException e) {} ...
java
protected void removeAction() { component.removeEventListener(eventName, this); if (component.getAttribute(attrName) == this) { component.removeAttribute(attrName); } }
java
public boolean isHelpSetFile(String fileName) { if (helpSetFilter == null) { helpSetFilter = new WildcardFileFilter(helpSetPattern); } return helpSetFilter.accept(new File(fileName)); }
java
public IResourceIterator load(String archiveName) throws Exception { File file = new File(archiveName); if (file.isDirectory()) { return new DirectoryIterator(file); } return iteratorClass.getConstructor(String.class).newInstance(archiveName); }
java
public void setUrl(String url) { this.url = url; if (child != null) { child.destroy(); child = null; } if (url.startsWith("http") || !url.endsWith(".fsp")) { child = new Iframe(); ((Iframe) child).setSrc(url); } else { ...
java
@Override public ISerializer<?> get(Class<?> clazz) { ISerializer<?> contextSerializer = super.get(clazz); if (contextSerializer != null) { return contextSerializer; } for (ISerializer<?> item : this) { if (item.getType().isAssignableFrom(clazz)) { ...
java
public ElementUI materialize(ElementUI parent) { boolean isDesktop = parent instanceof ElementDesktop; if (isDesktop) { parent.getDefinition().initElement(parent, root); } materializeChildren(parent, root, !isDesktop); ElementUI element = parent.getLastVisibleChild(...
java
private void materializeChildren(ElementBase parent, LayoutElement node, boolean ignoreInternal) { for (LayoutNode child : node.getChildren()) { PluginDefinition def = child.getDefinition(); ElementBase element = ignoreInternal && def.isInternal() ? null : createElement(parent, child); ...
java
public void setName(String value) { layoutName = value; if (root != null) { root.getAttributes().put("name", value); } }
java
public boolean saveToProperty(LayoutIdentifier layoutId) { setName(layoutId.name); try { LayoutUtil.saveLayout(layoutId, toString()); } catch (Exception e) { log.error("Error saving application layout.", e); return false; } return true; }
java
public Class<? extends ElementBase> getRootClass() { LayoutElement top = root == null ? null : root.getChild(LayoutElement.class); return top == null ? null : top.getDefinition().getClazz(); }
java
@Override public Layout fromClipboard(String data) { init(LayoutParser.parseText(data).root); return this; }
java
public boolean publish(String channel, Message message, Recipient... recipients) { boolean result = false; prepare(channel, message, recipients); for (IMessageProducer producer : producers) { result |= producer.publish(channel, message); } return result; }
java
private boolean publish(String channel, Message message, IMessageProducer producer, Recipient[] recipients) { if (producer != null) { prepare(channel, message, recipients); return producer.publish(channel, message); } return false; }
java
private IMessageProducer findRegisteredProducer(Class<?> clazz) { for (IMessageProducer producer : producers) { if (clazz.isInstance(producer)) { return producer; } } return null; }
java
private Message prepare(String channel, Message message, Recipient[] recipients) { message.setMetadata("cwf.pub.node", nodeId); message.setMetadata("cwf.pub.channel", channel); message.setMetadata("cwf.pub.event", UUID.randomUUID().toString()); message.setMetadata("cwf.pub.when", System....
java
protected Interest replaceFinalComponent(Interest interest, long segmentNumber, byte marker) { Interest copied = new Interest(interest); Component lastComponent = Component.fromNumberWithMarker(segmentNumber, marker); Name newName = (SegmentationHelper.isSegmented(copied.getName(), marker)) ? copied...
java
public static void setTime(Datebox datebox, Timebox timebox, Date value) { value = value == null ? new Date() : value; datebox.setValue(DateUtil.stripTime(value)); timebox.setValue(value); }
java
private boolean isFresh(Record record) { double period = record.data.getMetaInfo().getFreshnessPeriod(); return period < 0 || record.addedAt + (long) period > System.currentTimeMillis(); }
java
private boolean sameTopic(HelpTopic topic1, HelpTopic topic2) { return topic1 == topic2 || (topic1 != null && topic2 != null && topic1.equals(topic2)); }
java
private String lookupItemName(String itemName, boolean autoAdd) { String indexedName = index.get(itemName.toLowerCase()); if (indexedName == null && autoAdd) { index.put(itemName.toLowerCase(), itemName); } return indexedName == null ? itemName : indexedName; }
java
private String lookupItemName(String itemName, String suffix, boolean autoAdd) { return lookupItemName(itemName + "." + suffix, autoAdd); }
java
public void removeSubject(String subject) { String prefix = normalizePrefix(subject); for (String suffix : getSuffixes(prefix).keySet()) { setItem(prefix + suffix, null); } }
java
private Map<String, String> getSuffixes(String prefix, Boolean firstOnly) { HashMap<String, String> matches = new HashMap<>(); prefix = normalizePrefix(prefix); int i = prefix.length(); for (String itemName : index.keySet()) { if (itemName.startsWith(prefix)) { ...
java
public String getItem(String itemName, String suffix) { return items.get(lookupItemName(itemName, suffix, false)); }
java
@SuppressWarnings("unchecked") public <T> T getItem(String itemName, Class<T> clazz) throws ContextException { String item = getItem(itemName); if (item == null || item.isEmpty()) { return null; } ISerializer<?> contextSerializer = ContextSerializerRegistry.getInstance(...
java
public void setItem(String itemName, String value, String suffix) { itemName = lookupItemName(itemName, suffix, value != null); items.put(itemName, value); }
java
public void setDate(String itemName, Date date) { if (date == null) { setItem(itemName, null); } else { setItem(itemName, DateUtil.toHL7(date)); } }
java
public Date getDate(String itemName) { try { return DateUtil.parseDate(getItem(itemName)); } catch (Exception e) { return null; } }
java
public void addItems(String values) throws Exception { for (String line : values.split("[\\r\\n]")) { String[] pcs = line.split("\\=", 2); if (pcs.length == 2) { setItem(pcs[0], pcs[1]); } } }
java
private void addItems(Map<String, String> values) { for (String itemName : values.keySet()) { setItem(itemName, values.get(itemName)); } }
java
public static String[] getLibraryPaths() { String libraryPathString = System.getProperty("java.library.path"); String pathSeparator = System.getProperty("path.separator"); return libraryPathString.split(pathSeparator); }
java
public String put(final String key, final String Value) { return parameters.put(key, Value); }
java
public static long[] insertEntry(long[] a, int idx, long val) { long[] b = new long[a.length + 1]; for (int i = 0; i < b.length; i++) { if (i < idx) { b[i] = a[i]; } else if (i == idx) { b[idx] = val; } else { b[i] = a[i...
java
public int getIndex() { if (parent != null) { for (int i = 0; i < parent.children.size(); i++) { if (parent.children.get(i) == this) { return i; } } } return -1; }
java
public HelpTopicNode getNextSibling() { int i = getIndex() + 1; return i == 0 || i == parent.children.size() ? null : parent.children.get(i); }
java
public HelpTopicNode getPreviousSibling() { int i = getIndex() - 1; return i < 0 ? null : parent.children.get(i); }
java
public void addChild(HelpTopicNode node, int index) { node.detach(); node.parent = this; if (index < 0) { children.add(node); } else { children.add(index, node); } }
java
public static DialogControl<String> create(String message, String title, String styles, String responses, String excludeResponses, String defaultResponse, String saveResponseId, IPromptCallback<String> callback) { retu...
java
public DialogResponse<T> getLastResponse() { String saved = saveResponseId == null ? null : PropertyUtil.getValue(SAVED_RESPONSE_PROP_NAME, saveResponseId); int i = NumberUtils.toInt(saved, -1); DialogResponse<T> response = i < 0 || i >= responses.size() ? null : responses.get(i); return...
java
public void saveLastResponse(DialogResponse<T> response) { if (saveResponseId != null && (response == null || !response.isExcluded())) { int index = response == null ? -1 : responses.indexOf(response); PropertyUtil.saveValue(SAVED_RESPONSE_PROP_NAME, saveResponseId, false, ...
java
public void uniq() { if (size <= 1) { return; } int cursor = 0; for (int i=1; i<size; i++) { if (elements[cursor] != elements[i]) { cursor++; elements[cursor] = elements[i]; } } size = cursor+1; }
java
private static Object selfConvert( String parsingMethod, String value, Class<?> type ) { try { Method method = type.getMethod( parsingMethod, String.class ); return method.invoke( null, value ); } catch (InvocationTargetException e) { throw...
java
@Override public Calendar convertDateToCalendar(java.util.Date date) { Calendar calendar = null; if (date != null) { calendar = Calendar.getInstance(); calendar.setTime(date); calendar.clear(Calendar.ZONE_OFFSET); calendar.clear(Calendar.DST_OFFSET); ...
java
@Override public void execute() throws MojoExecutionException { if (StringUtils.isEmpty(moduleSource) && ignoreMissingSource) { getLog().info("No help module source specified."); return; } init("help", moduleBase); registerLoader(new SourceLo...
java
private void registerExternalLoaders() throws MojoExecutionException { if (archiveLoaders != null) { for (String entry : archiveLoaders) { try { SourceLoader loader = (SourceLoader) Class.forName(entry).newInstance(); registerLoader(loader); ...
java
public boolean verify(String base64Signature, String content, String timestamp) throws Exception { return verify(base64Signature, content, timestamp, keyName); }
java
protected static SessionController create(String sessionId, boolean originator) { Map<String, Object> args = new HashMap<>(); args.put("id", sessionId); args.put("title", StrUtil.formatMessage("@cwf.chat.session.title")); args.put("originator", originator ? true : null); Window d...
java
@Override public void afterInitialized(BaseComponent comp) { super.afterInitialized(comp); window = (Window) comp; sessionId = (String) comp.getAttribute("id"); lstParticipants.setRenderer(new ParticipantRenderer(chatService.getSelf(), null)); model.add(chatService.getSelf())...
java
public Listitem findMatchingItem(String label) { for (Listitem item : getChildren(Listitem.class)) { if (label.equalsIgnoreCase(item.getLabel())) { return item; } } return null; }
java
public Date getStartDate() { DateRange range = getSelectedRange(); return range == null ? null : range.getStartDate(); }
java
public Date getEndDate() { DateRange range = getSelectedRange(); return range == null ? null : range.getEndDate(); }
java
public static String shortMessage( List<CompilerError> messages ) { StringBuffer sb = new StringBuffer(); sb.append( "Compilation failure" ); if ( messages.size() == 1 ) { sb.append( LS ); CompilerError compilerError = (CompilerError) messages.get( 0 ); ...
java
public void sortAttachments(ByteArrayInputStream byteArrayInputStream) { List<String> attachmentNameList = new ArrayList<>(); List<AttachmentData> attacmentList = getAttachments(); List<AttachmentData> tempAttacmentList = new ArrayList<>(); try{ DocumentBuilderFacto...
java
public boolean hasBadValues() { for(int i=0; i<top; i++) { double v = vals[i]; boolean bad = Double.isNaN(v) || Double.isInfinite(v); if(bad) return true; } return false; }
java
public void setCharsetName(final String charsetName) { if(Charset.isSupported(charsetName)) { this.charsetName = charsetName; } else { throw new UnsupportedCharsetException("No support for, " + charsetName + ", is available in this instance of the JVM"); } }
java
protected byte[] serialize(IMessage<ID, DATA> msg) { return msg != null ? SerializationUtils.toByteArray(msg) : null; }
java
protected <T extends IMessage<ID, DATA>> T deserialize(byte[] msgData, Class<T> clazz) { return msgData != null ? SerializationUtils.fromByteArray(msgData, clazz) : null; }
java
private IQueryResult<T> filteredResult(IQueryResult<T> unfilteredResult) { List<T> unfilteredList = unfilteredResult.getResults(); List<T> filteredList = unfilteredList == null ? null : filters.filter(unfilteredList); Map<String, Object> metadata = Collections.<String, Object> singletonMap("unfi...
java
public static ApplicationContext contextMergedBeans(String xmlPath, Map<String, ?> extraBeans) { final DefaultListableBeanFactory parentBeanFactory = buildListableBeanFactory(extraBeans); //loads the xml and add definitions in the context GenericApplicationContext parentContext = new GenericApplicationConte...
java
public static ApplicationContext contextMergedBeans(Map<String, ?> extraBeans, Class<?> config) { final DefaultListableBeanFactory parentBeanFactory = buildListableBeanFactory(extraBeans); //loads the annotation classes and add definitions in the context GenericApplicationContext parent...
java
private static void setProperties(GenericApplicationContext newContext, Properties properties) { PropertiesPropertySource pps = new PropertiesPropertySource("external-props", properties); newContext.getEnvironment().getPropertySources().addFirst(pps); }
java
private static DefaultListableBeanFactory buildListableBeanFactory(Map<String, ?> extraBeans) { //new empty context final DefaultListableBeanFactory parentBeanFactory = new DefaultListableBeanFactory(); //Injection of the new beans in the context for (String key : extraBeans.k...
java
protected boolean validateBudgetForForm(ProposalDevelopmentDocumentContract pdDoc) throws S2SException { boolean valid = true; ProposalDevelopmentBudgetExtContract budget = s2SCommonBudgetService.getBudget(pdDoc.getDevelopmentProposal()); if(budget != null) { for (BudgetPeriodContra...
java
public static IStopWatch create() { if (factory == null) { throw new IllegalStateException("No stopwatch factory registered."); } try { return factory.clazz.newInstance(); } catch (Exception e) { throw new RuntimeException("Could not create st...
java
public static IStopWatch create(String tag, Map<String, Object> data) { IStopWatch sw = create(); sw.init(tag, data); return sw; }
java
private CumulativeTravels getCumulativeTravels(BudgetSummaryDto budgetSummaryData) { CumulativeTravels cumulativeTravels = CumulativeTravels.Factory.newInstance(); SummaryDataType summary = SummaryDataType.Factory.newInstance(); if (budgetSummaryData != null) { if (budgetSummaryData...
java
private GraduateStudents getGraduateStudents(OtherPersonnelDto otherPersonnel) { GraduateStudents graduate = GraduateStudents.Factory.newInstance(); if (otherPersonnel != null) { graduate.setNumberOfPersonnel(otherPersonnel.getNumberPersonnel()); graduate.setProjectRole(otherPer...
java
private UndergraduateStudents getUndergraduateStudents(OtherPersonnelDto otherPersonnel) { UndergraduateStudents undergraduate = UndergraduateStudents.Factory.newInstance(); if (otherPersonnel != null) { undergraduate.setNumberOfPersonnel(otherPersonnel.getNumberPersonnel()); un...
java
private Others getOthersForOtherDirectCosts(BudgetPeriodDto periodInfo) { Others othersDirect = Others.Factory.newInstance(); if (periodInfo != null && periodInfo.getOtherDirectCosts() != null) { Others.Other otherArray[] = new Others.Other[periodInfo.getOtherDirectCosts().size()]; ...
java
public static void applyThemeClass(BaseUIComponent component, IThemeClass... themeClasses) { StringBuilder sb = new StringBuilder(); for (IThemeClass themeClass : themeClasses) { String cls = themeClass == null ? null : themeClass.getThemeClass(); if (cls != null) { ...
java
public void setUrl(String url) { this.url = url; if (clazz == null && url != null) { setClazz(ElementPlugin.class); } }
java
@SuppressWarnings("unchecked") public <E extends IPluginResource> List<E> getResources(Class<E> clazz) { List<E> list = new ArrayList<>(); for (IPluginResource resource : resources) { if (clazz.isInstance(resource)) { list.add((E) resource); } } ...
java
public void setClazz(Class<? extends ElementBase> clazz) { this.clazz = clazz; try { // Force execution of static initializers Class.forName(clazz.getName()); } catch (ClassNotFoundException e) { MiscUtil.toUnchecked(e); } }
java
public boolean isForbidden() { if (authorities.size() == 0) { return false; // If no restrictions, return false } boolean result = true; for (Authority priv : authorities) { result = !SecurityUtil.isGranted(priv.name); if (requiresAll == result) { ...
java
public void setPath(String path) { if (path != null) { manifest = ManifestIterator.getInstance().findByPath(path); } }
java
private String getValueWithDefault(String value, String manifestKey) { if (StringUtils.isEmpty(value) && manifest != null) { value = manifest.getMainAttributes().getValue(manifestKey); } return value; }
java
public ElementBase createElement(ElementBase parent, IPropertyProvider propertyProvider, boolean deserializing) { try { ElementBase element = null; if (isForbidden()) { log.info("Access to plugin " + getName() + " is restricted."); } else if (isDisabled()) { ...
java
public void initElement(ElementBase element, IPropertyProvider propertyProvider) { if (propertyProvider != null) { for (PropertyInfo propInfo : getProperties()) { String key = propInfo.getId(); if (propertyProvider.hasProperty(key)) { String value...
java
public Person nextPerson() { if(!initialized) { init(); } Person person = new Person(); Gender gender = this.gender == null ? (random.nextBoolean() ? Gender.FEMALE : Gender.MALE) : this.gender; person.setGender(gender); List<String> givenNamesPool = gender == Gender.FEMALE ? givenFemaleNames : givenMaleNames...
java
public List<Person> nextPeople(int num) { List<Person> names = new ArrayList<Person>(num); for(int i = 0; i < num; i++) { names.add(nextPerson()); } return names; }
java
public String marshal(ContextItems contextItems) { SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyyMMddHHmmssz"); contextItems.setItem(PROPNAME_TIME, timestampFormat.format(new Date())); contextItems.setItem(PROPNAME_KEY, signer.getKeyName()); return contextItems.toString();...
java
public ContextItems unmarshal(String marshaledContext, String authSignature) throws Exception { ContextItems contextItems = new ContextItems(); contextItems.addItems(marshaledContext); String whichKey = contextItems.getItem(PROPNAME_KEY); String timestamp = contextItems.getItem(PROPNAME_...
java
private Travel getTravel(BudgetPeriodDto periodInfo) { Travel travel = Travel.Factory.newInstance(); if (periodInfo != null) { TotalDataType total = TotalDataType.Factory.newInstance(); if (periodInfo.getDomesticTravelCost() != null) { total.setFederal(periodInfo...
java
public static int count(int[] array, int value) { int count = 0; for (int i = 0; i < array.length; i++) { if (array[i] == value) { count++; } } return count; }
java
public static void reorder(int[] array, int[] order) { int[] original = copyOf(array); for (int i = 0; i < array.length; i++) { array[i] = original[order[i]]; } }
java
public static int countUnique(int[] indices1, int[] indices2) { int numUniqueIndices = 0; int i = 0; int j = 0; while (i < indices1.length && j < indices2.length) { if (indices1[i] < indices2[j]) { numUniqueIndices++; i++; } else if...
java
public static IActionType<?> getType(String script) { for (IActionType<?> actionType : instance) { if (actionType.matches(script)) { return actionType; } } throw new IllegalArgumentException("Script type was not recognized: " + script); }
java
public static boolean collectionExists(MongoDatabase db, String collectionName) { return db.listCollections().filter(Filters.eq("name", collectionName)).first() != null; }
java
public static MongoCollection<Document> createCollection(MongoDatabase db, String collectionName, CreateCollectionOptions options) { db.createCollection(collectionName, options); return db.getCollection(collectionName); }
java