_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q163000
QueryControllerGroup.updateQuery
train
public void updateQuery(QueryControllerQuery query) { int position = getElementPosition(query.getID()); queries.set(position, query); }
java
{ "resource": "" }
q163001
DataSource2PropertiesConvertor.convert
train
public static Properties convert(OBDADataSource source) { String id = source.getSourceID().toString(); String url = source.getParameter(RDBMSourceParameterConstants.DATABASE_URL); String username = source.getParameter(RDBMSourceParameterConstants.DATABASE_USERNAME); String password = source.getParameter(RDBMSourceParameterConstants.DATABASE_PASSWORD); String driver = source.getParameter(RDBMSourceParameterConstants.DATABASE_DRIVER); Properties p = new Properties(); p.put(OntopSQLCoreSettings.JDBC_NAME, id); p.put(OntopSQLCoreSettings.JDBC_URL, url); p.put(OntopSQLCredentialSettings.JDBC_USER, username); p.put(OntopSQLCredentialSettings.JDBC_PASSWORD, password); p.put(OntopSQLCoreSettings.JDBC_DRIVER, driver); return p; }
java
{ "resource": "" }
q163002
UnionNodeImpl.liftBindingFromLiftedChildren
train
private IQTree liftBindingFromLiftedChildren(ImmutableList<IQTree> liftedChildren, VariableGenerator variableGenerator, IQProperties currentIQProperties) { /* * Cannot lift anything if some children do not have a construction node */ if (liftedChildren.stream() .anyMatch(c -> !(c.getRootNode() instanceof ConstructionNode))) return iqFactory.createNaryIQTree(this, liftedChildren, currentIQProperties.declareLifted()); ImmutableSubstitution<ImmutableTerm> mergedSubstitution = mergeChildSubstitutions( projectedVariables, liftedChildren.stream() .map(c -> (ConstructionNode) c.getRootNode()) .map(ConstructionNode::getSubstitution) .collect(ImmutableCollectors.toList()), variableGenerator); if (mergedSubstitution.isEmpty()) { return iqFactory.createNaryIQTree(this, liftedChildren, currentIQProperties.declareLifted()); } ConstructionNode newRootNode = iqFactory.createConstructionNode(projectedVariables, mergedSubstitution); ImmutableSet<Variable> unionVariables = newRootNode.getChildVariables(); UnionNode newUnionNode = iqFactory.createUnionNode(unionVariables); NaryIQTree unionIQ = iqFactory.createNaryIQTree(newUnionNode, liftedChildren.stream() .map(c -> (UnaryIQTree) c) .map(c -> updateChild(c, mergedSubstitution, unionVariables)) .collect(ImmutableCollectors.toList())); return iqFactory.createUnaryIQTree(newRootNode, unionIQ); }
java
{ "resource": "" }
q163003
UnionNodeImpl.projectAwayUnnecessaryVariables
train
private IQTree projectAwayUnnecessaryVariables(IQTree child, IQProperties currentIQProperties) { if (child.getRootNode() instanceof ConstructionNode) { ConstructionNode constructionNode = (ConstructionNode) child.getRootNode(); AscendingSubstitutionNormalization normalization = normalizeAscendingSubstitution( constructionNode.getSubstitution(), projectedVariables); Optional<ConstructionNode> proposedConstructionNode = normalization.generateTopConstructionNode(); if (proposedConstructionNode .filter(c -> c.isSyntacticallyEquivalentTo(constructionNode)) .isPresent()) return child; IQTree grandChild = normalization.normalizeChild(((UnaryIQTree) child).getChild()); return proposedConstructionNode .map(c -> (IQTree) iqFactory.createUnaryIQTree(c, grandChild, currentIQProperties.declareLifted())) .orElse(grandChild); } else return child; }
java
{ "resource": "" }
q163004
ResultViewTablePanel.canWrite
train
private boolean canWrite(File outputFile) { boolean fileIsValid = false; if (outputFile.exists()) { int result = JOptionPane.showConfirmDialog( this, "File exists, overwrite?", "Warning", JOptionPane.YES_NO_CANCEL_OPTION); switch (result) { case JOptionPane.YES_OPTION: fileIsValid = true; break; default: fileIsValid = false; } } else { fileIsValid = true; } return fileIsValid; }
java
{ "resource": "" }
q163005
IQTreeTools.normalizeDescendingSubstitution
train
public Optional<ImmutableSubstitution<? extends VariableOrGroundTerm>> normalizeDescendingSubstitution( IQTree tree, ImmutableSubstitution<? extends VariableOrGroundTerm> descendingSubstitution) throws UnsatisfiableDescendingSubstitutionException { ImmutableSubstitution<? extends VariableOrGroundTerm> reducedSubstitution = descendingSubstitution .reduceDomainToIntersectionWith(tree.getVariables()); if (reducedSubstitution.isEmpty()) return Optional.empty(); if (reducedSubstitution.getImmutableMap().values().stream().anyMatch(value -> value.equals(termFactory.getNullConstant()))) { throw new UnsatisfiableDescendingSubstitutionException(); } return Optional.of(reducedSubstitution); }
java
{ "resource": "" }
q163006
VirtualABoxStatistics.getStatistics
train
public int getStatistics(String datasourceId, String mappingId) { final HashMap<String, Integer> mappingStat = getStatistics(datasourceId); int triplesCount = mappingStat.get(mappingId).intValue(); return triplesCount; }
java
{ "resource": "" }
q163007
VirtualABoxStatistics.getTotalTriples
train
public int getTotalTriples() throws Exception { int total = 0; for (HashMap<String, Integer> mappingStat : statistics.values()) { for (Integer triplesCount : mappingStat.values()) { int triples = triplesCount.intValue(); if (triples == -1) { throw new Exception("An error was occurred in the counting process."); } total = total + triples; } } return total; }
java
{ "resource": "" }
q163008
OracleSQLDialectAdapter.nameViewOrVariable
train
private String nameViewOrVariable(final String prefix, final String intermediateName, final String suffix, final Collection<String> alreadyDefinedNames, boolean putQuote) { int borderLength = prefix.length() + suffix.length(); int signatureVarLength = intermediateName.length(); if (borderLength >= (NAME_MAX_LENGTH - NAME_NUMBER_LENGTH)) { throw new IllegalArgumentException("The prefix and the suffix are too long (their accumulated length must " + "be less than " + (NAME_MAX_LENGTH - NAME_NUMBER_LENGTH) + ")"); } /** * If the length limit is not reached, processes as usual. */ if (signatureVarLength + borderLength <= NAME_MAX_LENGTH) { String unquotedName = buildDefaultName(prefix, intermediateName, suffix); String name = putQuote ? sqlQuote(unquotedName) : unquotedName; return name; } String shortenIntermediateNamePrefix = intermediateName.substring(0, NAME_MAX_LENGTH - borderLength - NAME_NUMBER_LENGTH); /** * Naive implementation */ for (int i = 0; i < Math.pow(10, NAME_NUMBER_LENGTH); i++) { String unquotedVarName = buildDefaultName(prefix, shortenIntermediateNamePrefix + i, suffix); String mainVarName = putQuote ? sqlQuote(unquotedVarName) : unquotedVarName; if (!alreadyDefinedNames.contains(mainVarName)) { return mainVarName; } } // TODO: find a better exception throw new RuntimeException("Impossible to create a new variable/view " + prefix + shortenIntermediateNamePrefix + "???" + suffix + " : already " + Math.pow(10, NAME_NUMBER_LENGTH) + " of them."); }
java
{ "resource": "" }
q163009
ImmutableCQSyntacticContainmentCheck.isContainedIn
train
@Override public boolean isContainedIn(ImmutableCQ cq1, ImmutableCQ cq2) { return cq2.getAnswerVariables().equals(cq1.getAnswerVariables()) && !cq2.getAtoms().stream().anyMatch(a -> !cq1.getAtoms().contains(a)); }
java
{ "resource": "" }
q163010
TargetQueryRenderer.getNestedConcats
train
public static void getNestedConcats(StringBuilder stb, ImmutableTerm term1, ImmutableTerm term2) { if (term1 instanceof ImmutableFunctionalTerm) { ImmutableFunctionalTerm f = (ImmutableFunctionalTerm) term1; getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1)); } else { stb.append(appendTerms(term1)); } if (term2 instanceof ImmutableFunctionalTerm) { ImmutableFunctionalTerm f = (ImmutableFunctionalTerm) term2; getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1)); } else { stb.append(appendTerms(term2)); } }
java
{ "resource": "" }
q163011
TargetQueryRenderer.getDisplayName
train
private static String getDisplayName(ImmutableTerm term, PrefixManager prefixManager) { if (term instanceof ImmutableFunctionalTerm) return displayFunction((ImmutableFunctionalTerm) term, prefixManager); if (term instanceof Variable) return displayVariable((Variable)term); if (term instanceof IRIConstant) return displayURIConstant((Constant)term, prefixManager); if (term instanceof ValueConstant) return displayValueConstant((Constant)term); if (term instanceof BNode) return displayBnode((BNode)term); throw new UnexpectedTermException(term); }
java
{ "resource": "" }
q163012
JDBC2ConstantConverter.buildDefaultDateTimeFormatter
train
private static ImmutableList<DateTimeFormatter> buildDefaultDateTimeFormatter() { return ImmutableList.<DateTimeFormatter>builder() .add(DateTimeFormatter.ISO_LOCAL_DATE_TIME) // ISO with 'T' .add(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[[.SSSSSSSSS][.SSSSSSS][.SSSSSS][.SSS][.SS][.S][XXXXX][XXXX][x]")) // ISO without 'T' // new DateTimeFormatterBuilder().parseLenient().appendPattern("yyyy-MM-dd HH:mm:ss[XXXXX][XXXX][x]").appendFraction(ChronoField.MICRO_OF_SECOND, 0, 9, true) .add(DateTimeFormatter.ISO_DATE) // ISO with or without time .add(new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd-MMM-yy[ HH:mm:ss]").toFormatter()) // another common case .build(); }
java
{ "resource": "" }
q163013
JDBC2ConstantConverter.buildDateTimeFormatterMap
train
private static ImmutableMap<System,ImmutableList<DateTimeFormatter>> buildDateTimeFormatterMap() { return ImmutableMap.of( DEFAULT, ImmutableList.<DateTimeFormatter>builder() .addAll(defaultDateTimeFormatter) // another common case .build(), ORACLE, ImmutableList.<DateTimeFormatter>builder() .addAll(defaultDateTimeFormatter) .add(new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd-MMM-yy[ hh[.][:]mm[.][:]ss[.][,][n][ a][ ZZZZZ][ VV]]").toFormatter()) .add(new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd-MMM-yy[ HH[.][:]mm[.][:]ss[.][,][n][ ZZZZZ][ VV]]").toFormatter()) .build(), MSSQL, ImmutableList.<DateTimeFormatter>builder() .addAll(defaultDateTimeFormatter) .add(new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("MMM dd yyyy[ hh:mm[a]]").toFormatter()) .build() ); }
java
{ "resource": "" }
q163014
QuestStatement.execute
train
@Override public <R extends OBDAResultSet> R execute(InputQuery<R> inputQuery) throws OntopConnectionException, OntopReformulationException, OntopQueryEvaluationException, OntopResultConversionException { if (inputQuery instanceof SelectQuery) { return (R) executeInThread((SelectQuery) inputQuery, this::executeSelectQuery); } else if (inputQuery instanceof AskQuery) { return (R) executeInThread((AskQuery) inputQuery, this::executeBooleanQuery); } else if (inputQuery instanceof ConstructQuery) { return (R) executeInThread((ConstructQuery) inputQuery, this::executeConstructQuery); } else if (inputQuery instanceof DescribeQuery) { return (R) executeDescribeQuery((DescribeQuery) inputQuery); } else { throw new OntopUnsupportedInputQueryException("Unsupported query type: " + inputQuery); } }
java
{ "resource": "" }
q163015
QuestStatement.executeInThread
train
private <R extends OBDAResultSet, Q extends InputQuery<R>> R executeInThread(Q inputQuery, Evaluator<R, Q> evaluator) throws OntopReformulationException, OntopQueryEvaluationException { log.debug("Executing SPARQL query: \n{}", inputQuery); CountDownLatch monitor = new CountDownLatch(1); ExecutableQuery executableQuery = engine.reformulateIntoNativeQuery(inputQuery); QueryExecutionThread<R, Q> executionthread = new QueryExecutionThread<>(inputQuery, executableQuery, evaluator, monitor); this.executionThread = executionthread; executionthread.start(); try { monitor.await(); } catch (InterruptedException e) { e.printStackTrace(); } if (executionthread.errorStatus()) { Exception ex = executionthread.getException(); if (ex instanceof OntopReformulationException) { throw (OntopReformulationException) ex; } else if (ex instanceof OntopQueryEvaluationException) { throw (OntopQueryEvaluationException) ex; } else { throw new OntopQueryEvaluationException(ex); } } if (canceled) { canceled = false; throw new OntopQueryEvaluationException("Query execution was cancelled"); } return executionthread.getResultSet(); }
java
{ "resource": "" }
q163016
RAExpressionAttributes.isAbsent
train
private boolean isAbsent(QuotedID attribute) { ImmutableSet<RelationID> occurrences = attributeOccurrences.get(attribute); return (occurrences == null) || occurrences.isEmpty(); }
java
{ "resource": "" }
q163017
RAExpressionAttributes.attributeOccurrencesUnion
train
private static ImmutableSet<RelationID> attributeOccurrencesUnion(QuotedID id, RAExpressionAttributes re1, RAExpressionAttributes re2) { ImmutableSet<RelationID> s1 = re1.attributeOccurrences.get(id); ImmutableSet<RelationID> s2 = re2.attributeOccurrences.get(id); if (s1 == null) return s2; if (s2 == null) return s1; return ImmutableSet.<RelationID>builder().addAll(s1).addAll(s2).build(); }
java
{ "resource": "" }
q163018
RAExpressionAttributes.checkRelationAliasesConsistency
train
private static void checkRelationAliasesConsistency(RAExpressionAttributes re1, RAExpressionAttributes re2) throws IllegalJoinException { ImmutableSet<RelationID> alias1 = re1.attributes.keySet().stream() .filter(id -> id.getRelation() != null) .map(QualifiedAttributeID::getRelation).collect(ImmutableCollectors.toSet()); ImmutableSet<RelationID> alias2 = re2.attributes.keySet().stream() .filter(id -> id.getRelation() != null) .map(QualifiedAttributeID::getRelation).collect(ImmutableCollectors.toSet()); if (alias1.stream().anyMatch(alias2::contains)) throw new IllegalJoinException(re1, re2 ,"Relation alias " + alias1.stream().filter(alias2::contains).collect(ImmutableCollectors.toList()) + " occurs in both arguments of the JOIN"); }
java
{ "resource": "" }
q163019
RedundantJoinFKExecutor.extractDataNodeMap
train
private ImmutableMultimap<RelationDefinition, ExtensionalDataNode> extractDataNodeMap(IntermediateQuery query, InnerJoinNode joinNode) { return query.getChildren(joinNode).stream() .filter(c -> c instanceof ExtensionalDataNode) .map(c -> (ExtensionalDataNode) c) .map(c -> Maps.immutableEntry(c.getProjectionAtom().getPredicate().getRelationDefinition(), c)) .collect(ImmutableCollectors.toMultimap()); }
java
{ "resource": "" }
q163020
TreeWitnessSet.getTreeWitnessGenerators
train
private Collection<TreeWitnessGenerator> getTreeWitnessGenerators(QueryFolding qf) { Collection<TreeWitnessGenerator> twg = null; log.debug("CHECKING WHETHER THE FOLDING {} CAN BE GENERATED: ", qf); for (TreeWitnessGenerator g : allTWgenerators) { Intersection<ObjectPropertyExpression> subp = qf.getProperties(); if (!subp.subsumes(g.getProperty())) { log.debug(" NEGATIVE PROPERTY CHECK {}", g.getProperty()); continue; } else log.debug(" POSITIVE PROPERTY CHECK {}", g.getProperty()); Intersection<ClassExpression> subc = qf.getInternalRootConcepts(); if (!g.endPointEntailsAnyOf(subc)) { log.debug(" ENDTYPE TOO SPECIFIC: {} FOR {}", subc, g); continue; } else log.debug(" ENDTYPE IS FINE: TOP FOR {}", g); boolean failed = false; for (TreeWitness tw : qf.getInteriorTreeWitnesses()) if (!g.endPointEntailsAnyOf(tw.getGeneratorSubConcepts())) { log.debug(" ENDTYPE TOO SPECIFIC: {} FOR {}", tw, g); failed = true; break; } else log.debug(" ENDTYPE IS FINE: {} FOR {}", tw, g); if (failed) continue; if (twg == null) twg = new LinkedList<>(); twg.add(g); log.debug(" OK"); } return twg; }
java
{ "resource": "" }
q163021
OntopModelSettingsImpl.getBoolean
train
Optional<Boolean> getBoolean(String key) { Object value = get(key); if (value == null) { return Optional.empty(); } if (value instanceof Boolean) { return Optional.of((Boolean) value); } else if (value instanceof String) { return Optional.of(Boolean.parseBoolean((String)value)); } else { throw new InvalidOntopConfigurationException("A boolean was expected: " + value); } }
java
{ "resource": "" }
q163022
OntopModelSettingsImpl.getInteger
train
Optional<Integer> getInteger(String key) { String value = (String) get(key); return Optional.ofNullable(Integer.parseInt(value)); }
java
{ "resource": "" }
q163023
TurtleWriter.put
train
void put(String subject, String predicate, String object) { // Subject to Predicates map ArrayList<String> predicateList = subjectToPredicates.get(subject); if (predicateList == null) { predicateList = new ArrayList<String>(); } insert(predicateList, predicate); subjectToPredicates.put(subject, predicateList); // Predicate to Objects map ArrayList<String> objectList = predicateToObjects.get(predicate + "_" + subject); // predicate that appears in 2 different subjects should not have all objects assigned to both subjects if (objectList == null) { objectList = new ArrayList<String>(); } objectList.add(object); predicateToObjects.put(predicate + "_" + subject, objectList); }
java
{ "resource": "" }
q163024
TurtleWriter.insert
train
private void insert(ArrayList<String> list, String input) { if (!list.contains(input)) { if (input.equals("a") || input.equals("rdf:type")) { list.add(0, input); } else { list.add(input); } } }
java
{ "resource": "" }
q163025
TurtleWriter.print
train
String print() { StringBuilder sb = new StringBuilder(); for (String subject : subjectToPredicates.keySet()) { sb.append(subject); sb.append(" "); boolean semiColonSeparator = false; for (String predicate : subjectToPredicates.get(subject)) { if (semiColonSeparator) { sb.append(" ; "); } sb.append(predicate); sb.append(" "); semiColonSeparator = true; boolean commaSeparator = false; for (String object : predicateToObjects.get(predicate+ "_" + subject)) { if (commaSeparator) { sb.append(" , "); } sb.append(object); commaSeparator = true; } } sb.append(" "); sb.append("."); sb.append(" "); } return sb.toString(); }
java
{ "resource": "" }
q163026
DefaultIntermediateQueryBuilder.buildQuery
train
protected IntermediateQuery buildQuery(DBMetadata metadata, DistinctVariableOnlyDataAtom projectionAtom, QueryTreeComponent treeComponent) { return new IntermediateQueryImpl(metadata, projectionAtom, treeComponent, executorRegistry, validator, settings, iqFactory); }
java
{ "resource": "" }
q163027
CompositeQueryNodeImpl.normalizeAscendingSubstitution
train
protected AscendingSubstitutionNormalization normalizeAscendingSubstitution( ImmutableSubstitution<ImmutableTerm> ascendingSubstitution, ImmutableSet<Variable> projectedVariables) { Var2VarSubstitution downRenamingSubstitution = substitutionFactory.getVar2VarSubstitution( ascendingSubstitution.getImmutableMap().entrySet().stream() .filter(e -> e.getValue() instanceof Variable) .map(e -> Maps.immutableEntry(e.getKey(), (Variable) e.getValue())) .filter(e -> !projectedVariables.contains(e.getValue())) .collect(ImmutableCollectors.toMap( Map.Entry::getValue, Map.Entry::getKey, (v1, v2) -> v1))); ImmutableSubstitution<ImmutableTerm> newAscendingSubstitution = downRenamingSubstitution .composeWith(ascendingSubstitution) .reduceDomainToIntersectionWith(projectedVariables) .normalizeValues(); return new AscendingSubstitutionNormalization(newAscendingSubstitution, downRenamingSubstitution, projectedVariables); }
java
{ "resource": "" }
q163028
LangDatatype.getCommonDenominator
train
private TermType getCommonDenominator(LanguageTag otherLanguageTag) { return langTag.getCommonDenominator(otherLanguageTag) .map(newLangTag -> newLangTag.equals(langTag) ? (TermType) this : new LangDatatype(newLangTag, parentAncestry, typeFactory)) // Incompatible lang tags --> common denominator is xsd:string .orElseGet(typeFactory::getXsdStringDatatype); }
java
{ "resource": "" }
q163029
IQ2DatalogTranslatorImpl.translate
train
@Override public DatalogProgram translate(IQ initialQuery) { IQ orderLiftedQuery = liftOrderBy(initialQuery); Optional<MutableQueryModifiers> optionalModifiers = extractTopQueryModifiers(orderLiftedQuery); // Mutable DatalogProgram dProgram; if (optionalModifiers.isPresent()){ MutableQueryModifiers mutableModifiers = optionalModifiers.get(); dProgram = datalogFactory.getDatalogProgram(mutableModifiers); } else { dProgram = datalogFactory.getDatalogProgram(); } normalizeIQ(orderLiftedQuery) .forEach(q -> translate(q, dProgram)); // CQIEs are mutable dProgram.getRules().forEach(q -> unfoldJoinTrees(q.getBody())); return dProgram; }
java
{ "resource": "" }
q163030
IQ2DatalogTranslatorImpl.extractTopQueryModifiers
train
private Optional<MutableQueryModifiers> extractTopQueryModifiers(IQ query) { IQTree tree = query.getTree(); QueryNode rootNode = tree.getRootNode(); if (rootNode instanceof QueryModifierNode) { Optional<SliceNode> sliceNode = Optional.of(rootNode) .filter(n -> n instanceof SliceNode) .map(n -> (SliceNode)n); IQTree firstNonSliceTree = sliceNode .map(n -> ((UnaryIQTree) tree).getChild()) .orElse(tree); Optional<DistinctNode> distinctNode = Optional.of(firstNonSliceTree) .map(IQTree::getRootNode) .filter(n -> n instanceof DistinctNode) .map(n -> (DistinctNode) n); IQTree firstNonSliceDistinctTree = distinctNode .map(n -> ((UnaryIQTree) firstNonSliceTree).getChild()) .orElse(firstNonSliceTree); Optional<OrderByNode> orderByNode = Optional.of(firstNonSliceDistinctTree) .map(IQTree::getRootNode) .filter(n -> n instanceof OrderByNode) .map(n -> (OrderByNode) n); MutableQueryModifiers mutableQueryModifiers = new MutableQueryModifiersImpl(); sliceNode.ifPresent(n -> { n.getLimit() .ifPresent(mutableQueryModifiers::setLimit); long offset = n.getOffset(); if (offset > 0) mutableQueryModifiers.setOffset(offset); }); if(distinctNode.isPresent()) mutableQueryModifiers.setDistinct(); orderByNode .ifPresent(n -> n.getComparators() .forEach(c -> convertOrderComparator(c, mutableQueryModifiers))); return Optional.of(mutableQueryModifiers); } else return Optional.empty(); }
java
{ "resource": "" }
q163031
IQ2DatalogTranslatorImpl.getFirstNonQueryModifierTree
train
private IQTree getFirstNonQueryModifierTree(IQ query) { // Non-final IQTree iqTree = query.getTree(); while (iqTree.getRootNode() instanceof QueryModifierNode) { iqTree = ((UnaryIQTree) iqTree).getChild(); } return iqTree; }
java
{ "resource": "" }
q163032
AbstractTurtleOBDAParser.parse
train
@Override public ImmutableList<TargetAtom> parse(String input) throws TargetQueryParserException { StringBuffer bf = new StringBuffer(input.trim()); if (!bf.substring(bf.length() - 2, bf.length()).equals(" .")) { bf.insert(bf.length() - 1, ' '); } if (!prefixes.isEmpty()) { // Update the input by appending the directives appendDirectives(bf); } try { CharStream inputStream = CharStreams.fromString(bf.toString()); TurtleOBDALexer lexer = new TurtleOBDALexer(inputStream); //substitute the standard ConsoleErrorListener (simply print out the error) with ThrowingErrorListener lexer.removeErrorListeners(); lexer.addErrorListener(ThrowingErrorListener.INSTANCE); CommonTokenStream tokenStream = new CommonTokenStream(lexer); TurtleOBDAParser parser = new TurtleOBDAParser(tokenStream); //substitute the standard ConsoleErrorListener (simply print out the error) with ThrowingErrorListener parser.removeErrorListeners(); parser.addErrorListener(ThrowingErrorListener.INSTANCE); return (ImmutableList<TargetAtom>)visitor.visitParse(parser.parse()); } catch (RuntimeException e) { throw new TargetQueryParserException(e.getMessage(), e); } }
java
{ "resource": "" }
q163033
AbstractTurtleOBDAParser.appendDirectives
train
private void appendDirectives(StringBuffer query) { StringBuffer sb = new StringBuffer(); for (String prefix : prefixes.keySet()) { sb.append("@PREFIX"); sb.append(" "); sb.append(prefix); sb.append(" "); sb.append("<"); sb.append(prefixes.get(prefix)); sb.append(">"); sb.append(" .\n"); } sb.append("@PREFIX " + OntopInternal.PREFIX_XSD + " <" + XSD.PREFIX + "> .\n"); sb.append("@PREFIX " + OntopInternal.PREFIX_OBDA + " <" + Ontop.PREFIX + "> .\n"); sb.append("@PREFIX " + OntopInternal.PREFIX_RDF + " <" + RDF.PREFIX + "> .\n"); sb.append("@PREFIX " + OntopInternal.PREFIX_RDFS + " <" + RDFS.PREFIX + "> .\n"); sb.append("@PREFIX " + OntopInternal.PREFIX_OWL + " <" + OWL.PREFIX + "> .\n"); query.insert(0, sb); }
java
{ "resource": "" }
q163034
MappingManagerPanel.parseSearchString
train
private List<TreeModelFilter<SQLPPTriplesMap>> parseSearchString(String textToParse) throws Exception { List<TreeModelFilter<SQLPPTriplesMap>> listOfFilters = null; if (textToParse != null) { ANTLRStringStream inputStream = new ANTLRStringStream(textToParse); MappingFilterLexer lexer = new MappingFilterLexer(inputStream); CommonTokenStream tokenStream = new CommonTokenStream(lexer); MappingFilterParser parser = new MappingFilterParser(tokenStream); listOfFilters = parser.parse(); if (parser.getNumberOfSyntaxErrors() != 0) { throw new Exception("Syntax Error: The filter string invalid"); } } return listOfFilters; }
java
{ "resource": "" }
q163035
MappingManagerPanel.applyFilters
train
private void applyFilters(List<TreeModelFilter<SQLPPTriplesMap>> filters) { FilteredModel model = (FilteredModel) mappingList.getModel(); model.removeAllFilters(); model.addFilters(filters); }
java
{ "resource": "" }
q163036
Builder.add
train
public Builder add(Attribute attribute) { if (relation != attribute.getRelation()) throw new IllegalArgumentException("Unique Key requires the same table in all attributes: " + relation + " " + attribute); builder.add(attribute); return this; }
java
{ "resource": "" }
q163037
LeftJoinNodeImpl.getPossibleVariableDefinitions
train
@Override public ImmutableSet<ImmutableSubstitution<NonVariableTerm>> getPossibleVariableDefinitions(IQTree leftChild, IQTree rightChild) { ImmutableSet<ImmutableSubstitution<NonVariableTerm>> leftDefs = leftChild.getPossibleVariableDefinitions(); ImmutableSet<Variable> rightSpecificVariables = Sets.difference(rightChild.getVariables(), leftChild.getVariables()) .immutableCopy(); ImmutableSet<ImmutableSubstitution<NonVariableTerm>> rightDefs = leftChild.getPossibleVariableDefinitions().stream() .map(s -> s.reduceDomainToIntersectionWith(rightSpecificVariables)) .collect(ImmutableCollectors.toSet()); if (leftDefs.isEmpty()) return rightDefs; else if (rightDefs.isEmpty()) return leftDefs; else return leftDefs.stream() .flatMap(l -> rightDefs.stream() .map(r -> combine(l, r))) .collect(ImmutableCollectors.toSet()); }
java
{ "resource": "" }
q163038
LeftJoinNodeImpl.selectDownSubstitution
train
private ImmutableSubstitution<NonFunctionalTerm> selectDownSubstitution( ImmutableSubstitution<NonFunctionalTerm> simplificationSubstitution, ImmutableSet<Variable> rightVariables) { ImmutableMap<Variable, NonFunctionalTerm> newMap = simplificationSubstitution.getImmutableMap().entrySet().stream() .filter(e -> rightVariables.contains(e.getKey())) .collect(ImmutableCollectors.toMap()); return substitutionFactory.getSubstitution(newMap); }
java
{ "resource": "" }
q163039
LeftJoinNodeImpl.containsEqualityRightSpecificVariable
train
private boolean containsEqualityRightSpecificVariable( ImmutableSubstitution<? extends VariableOrGroundTerm> descendingSubstitution, IQTree leftChild, IQTree rightChild) { ImmutableSet<Variable> leftVariables = leftChild.getVariables(); ImmutableSet<Variable> rightVariables = rightChild.getVariables(); ImmutableSet<Variable> domain = descendingSubstitution.getDomain(); ImmutableCollection<? extends VariableOrGroundTerm> range = descendingSubstitution.getImmutableMap().values(); return rightVariables.stream() .filter(v -> !leftVariables.contains(v)) .anyMatch(v -> (domain.contains(v) && (!isFreshVariable(descendingSubstitution.get(v), leftVariables, rightVariables))) // The domain of the substitution is assumed not to contain fresh variables // (normalized before) || range.contains(v)); }
java
{ "resource": "" }
q163040
OrderByNodeImpl.liftChildConstructionNode
train
private IQTree liftChildConstructionNode(ConstructionNode newChildRoot, UnaryIQTree newChild, IQProperties liftedProperties) { UnaryIQTree newOrderByTree = iqFactory.createUnaryIQTree( applySubstitution(newChildRoot.getSubstitution()), newChild.getChild(), liftedProperties); return iqFactory.createUnaryIQTree(newChildRoot, newOrderByTree, liftedProperties); }
java
{ "resource": "" }
q163041
PushUpBooleanExpressionOptimizerImpl.pushAboveUnions
train
private IntermediateQuery pushAboveUnions(IntermediateQuery query) throws EmptyQueryException { boolean fixPointReached; do { fixPointReached = true; for (QueryNode node : query.getNodesInTopDownOrder()) { if (node instanceof UnionNode) { Optional<PushUpBooleanExpressionProposal> proposal = makeProposalForUnionNode((UnionNode) node, query); if (proposal.isPresent()) { query = ((PushUpBooleanExpressionResults) query.applyProposal(proposal.get())).getResultingQuery(); fixPointReached = false; } } } } while (!fixPointReached); return query; }
java
{ "resource": "" }
q163042
PushUpBooleanExpressionOptimizerImpl.getExpressionsToPropagateAboveUnion
train
private ImmutableSet<ImmutableExpression> getExpressionsToPropagateAboveUnion(ImmutableSet<CommutativeJoinOrFilterNode> providers) { return providers.stream() .map(n -> n.getOptionalFilterCondition().get().flattenAND()) .reduce(this::computeIntersection).get(); }
java
{ "resource": "" }
q163043
PushUpBooleanExpressionOptimizerImpl.adjustProposal
train
private Optional<PushUpBooleanExpressionProposal> adjustProposal(PushUpBooleanExpressionProposal proposal, IntermediateQuery query) { QueryNode currentNode = proposal.getUpMostPropagatingNode(); Optional<QueryNode> optChild; // Will be removed from the list of inbetween projectors ImmutableSet.Builder<ExplicitVariableProjectionNode> removedProjectors = ImmutableSet.builder(); while ((optChild = query.getFirstChild(currentNode)).isPresent()) { if (currentNode instanceof ConstructionNode || currentNode instanceof QueryModifierNode) { if(currentNode instanceof ConstructionNode) { removedProjectors.add((ConstructionNode) currentNode); } currentNode = optChild.get(); continue; } // Note that the iteration is stopped (among other) by any binary operator break; } // If we went back to the provider node if(proposal.getProvider2NonPropagatedExpressionMap().keySet().contains(currentNode)){ return Optional.empty(); } // adjust the upmost propagating node QueryNode upMostPropagatingNode = currentNode; // if it it a filter or join, use it as a recipient for the expression Optional<JoinOrFilterNode> recipient = currentNode instanceof CommutativeJoinOrFilterNode ? Optional.of((JoinOrFilterNode) currentNode) : Optional.empty(); // update inbetween projectors ImmutableSet<ExplicitVariableProjectionNode> inbetweenProjectors = computeDifference( proposal.getInbetweenProjectors(), removedProjectors.build() ); return Optional.of( new PushUpBooleanExpressionProposalImpl( proposal.getPropagatedExpression(), proposal.getProvider2NonPropagatedExpressionMap(), upMostPropagatingNode, recipient, inbetweenProjectors )); }
java
{ "resource": "" }
q163044
SQLPPMappingImpl.checkDuplicates
train
private static void checkDuplicates(ImmutableList<SQLPPTriplesMap> mappings) throws DuplicateMappingException { Set<SQLPPTriplesMap> mappingSet = new HashSet<>(mappings); int duplicateCount = mappings.size() - mappingSet.size(); /** * If there are some triplesMaps, finds them */ if (duplicateCount > 0) { Set<String> duplicateIds = new HashSet<>(); int remaining = duplicateCount; for (SQLPPTriplesMap mapping : mappings) { if (mappingSet.contains(mapping)) { mappingSet.remove(mapping); } /** * Duplicate */ else { duplicateIds.add(mapping.getId()); if (--remaining == 0) break; } } //TODO: indicate the source throw new DuplicateMappingException(String.format("Found %d duplicates in the following ids: %s", duplicateCount, duplicateIds.toString())); } }
java
{ "resource": "" }
q163045
RedundantSelfJoinExecutor.propose
train
private Optional<ConcreteProposal> propose(InnerJoinNode joinNode, ImmutableMultimap<RelationPredicate, ExtensionalDataNode> initialDataNodeMap, ImmutableList<Variable> priorityVariables, IntermediateQuery query, DBMetadata dbMetadata) throws AtomUnificationException { ImmutableList.Builder<PredicateLevelProposal> proposalListBuilder = ImmutableList.builder(); for (RelationPredicate predicate : initialDataNodeMap.keySet()) { ImmutableCollection<ExtensionalDataNode> initialNodes = initialDataNodeMap.get(predicate); Optional<PredicateLevelProposal> predicateProposal = proposePerPredicate(joinNode, initialNodes, predicate, dbMetadata, priorityVariables, query); predicateProposal.ifPresent(proposalListBuilder::add); } return createConcreteProposal(proposalListBuilder.build(), priorityVariables); }
java
{ "resource": "" }
q163046
RedundantSelfJoinExecutor.applyOptimization
train
private NodeCentricOptimizationResults<InnerJoinNode> applyOptimization(IntermediateQuery query, QueryTreeComponent treeComponent, InnerJoinNode topJoinNode, ConcreteProposal proposal) throws EmptyQueryException { /* * First, add and remove non-top nodes */ proposal.getDataNodesToRemove() .forEach(treeComponent::removeSubTree); return updateJoinNodeAndPropagateSubstitution(query, treeComponent, topJoinNode, proposal); }
java
{ "resource": "" }
q163047
FormAutoCompleteTextView.addValidator
train
public void addValidator(com.andreabaccega.formedittextvalidator.Validator theValidator) throws IllegalArgumentException { editTextValidator.addValidator(theValidator); }
java
{ "resource": "" }
q163048
FormAutoCompleteTextView.onKeyPreIme
train
@Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (TextUtils.isEmpty(getText().toString()) && keyCode == KeyEvent.KEYCODE_DEL) return true; else return super.onKeyPreIme(keyCode, event); }
java
{ "resource": "" }
q163049
FormAutoCompleteTextView.showErrorIconHax
train
private void showErrorIconHax(Drawable icon) { if (icon == null) return; // only for JB 4.2 and 4.2.1 if (android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN && android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN_MR1) return; try { Class<?> textview = Class.forName("android.widget.TextView"); Field tEditor = textview.getDeclaredField("mEditor"); tEditor.setAccessible(true); Class<?> editor = Class.forName("android.widget.Editor"); Method privateShowError = editor.getDeclaredMethod("setErrorIcon", Drawable.class); privateShowError.setAccessible(true); privateShowError.invoke(tEditor.get(this), icon); } catch (Exception e) { // e.printStackTrace(); // oh well, we tried } }
java
{ "resource": "" }
q163050
SettingsActivity.isXLargeTablet
train
private static boolean isXLargeTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; }
java
{ "resource": "" }
q163051
Sample.fetcher
train
public static SampleFetcher fetcher(final String pathAssistantSid, final String pathTaskSid, final String pathSid) { return new SampleFetcher(pathAssistantSid, pathTaskSid, pathSid); }
java
{ "resource": "" }
q163052
Sample.creator
train
public static SampleCreator creator(final String pathAssistantSid, final String pathTaskSid, final String language, final String taggedText) { return new SampleCreator(pathAssistantSid, pathTaskSid, language, taggedText); }
java
{ "resource": "" }
q163053
Sample.updater
train
public static SampleUpdater updater(final String pathAssistantSid, final String pathTaskSid, final String pathSid) { return new SampleUpdater(pathAssistantSid, pathTaskSid, pathSid); }
java
{ "resource": "" }
q163054
Sample.deleter
train
public static SampleDeleter deleter(final String pathAssistantSid, final String pathTaskSid, final String pathSid) { return new SampleDeleter(pathAssistantSid, pathTaskSid, pathSid); }
java
{ "resource": "" }
q163055
Member.creator
train
public static MemberCreator creator(final String pathServiceSid, final String pathChannelSid, final String identity) { return new MemberCreator(pathServiceSid, pathChannelSid, identity); }
java
{ "resource": "" }
q163056
Member.deleter
train
public static MemberDeleter deleter(final String pathServiceSid, final String pathChannelSid, final String pathSid) { return new MemberDeleter(pathServiceSid, pathChannelSid, pathSid); }
java
{ "resource": "" }
q163057
StreamMessage.creator
train
public static StreamMessageCreator creator(final String pathServiceSid, final String pathStreamSid, final Map<String, Object> data) { return new StreamMessageCreator(pathServiceSid, pathStreamSid, data); }
java
{ "resource": "" }
q163058
CredentialList.updater
train
public static CredentialListUpdater updater(final String pathAccountSid, final String pathSid, final String friendlyName) { return new CredentialListUpdater(pathAccountSid, pathSid, friendlyName); }
java
{ "resource": "" }
q163059
WorkerChannel.fetcher
train
public static WorkerChannelFetcher fetcher(final String pathWorkspaceSid, final String pathWorkerSid, final String pathSid) { return new WorkerChannelFetcher(pathWorkspaceSid, pathWorkerSid, pathSid); }
java
{ "resource": "" }
q163060
WorkerChannel.updater
train
public static WorkerChannelUpdater updater(final String pathWorkspaceSid, final String pathWorkerSid, final String pathSid) { return new WorkerChannelUpdater(pathWorkspaceSid, pathWorkerSid, pathSid); }
java
{ "resource": "" }
q163061
Message.fetcher
train
public static MessageFetcher fetcher(final String pathServiceSid, final String pathChannelSid, final String pathSid) { return new MessageFetcher(pathServiceSid, pathChannelSid, pathSid); }
java
{ "resource": "" }
q163062
Message.deleter
train
public static MessageDeleter deleter(final String pathServiceSid, final String pathChannelSid, final String pathSid) { return new MessageDeleter(pathServiceSid, pathChannelSid, pathSid); }
java
{ "resource": "" }
q163063
FlexFlow.creator
train
public static FlexFlowCreator creator(final String friendlyName, final String chatServiceSid, final FlexFlow.ChannelType channelType) { return new FlexFlowCreator(friendlyName, chatServiceSid, channelType); }
java
{ "resource": "" }
q163064
AuthCallsCredentialListMapping.creator
train
public static AuthCallsCredentialListMappingCreator creator(final String pathAccountSid, final String pathDomainSid, final String credentialListSid) { return new AuthCallsCredentialListMappingCreator(pathAccountSid, pathDomainSid, credentialListSid); }
java
{ "resource": "" }
q163065
AuthCallsCredentialListMapping.fetcher
train
public static AuthCallsCredentialListMappingFetcher fetcher(final String pathAccountSid, final String pathDomainSid, final String pathSid) { return new AuthCallsCredentialListMappingFetcher(pathAccountSid, pathDomainSid, pathSid); }
java
{ "resource": "" }
q163066
AuthCallsCredentialListMapping.deleter
train
public static AuthCallsCredentialListMappingDeleter deleter(final String pathAccountSid, final String pathDomainSid, final String pathSid) { return new AuthCallsCredentialListMappingDeleter(pathAccountSid, pathDomainSid, pathSid); }
java
{ "resource": "" }
q163067
UserBinding.fetcher
train
public static UserBindingFetcher fetcher(final String pathServiceSid, final String pathUserSid, final String pathSid) { return new UserBindingFetcher(pathServiceSid, pathUserSid, pathSid); }
java
{ "resource": "" }
q163068
UserBinding.deleter
train
public static UserBindingDeleter deleter(final String pathServiceSid, final String pathUserSid, final String pathSid) { return new UserBindingDeleter(pathServiceSid, pathUserSid, pathSid); }
java
{ "resource": "" }
q163069
Challenge.creator
train
public static ChallengeCreator creator(final String pathServiceSid, final String pathIdentity, final String pathFactorSid) { return new ChallengeCreator(pathServiceSid, pathIdentity, pathFactorSid); }
java
{ "resource": "" }
q163070
Challenge.deleter
train
public static ChallengeDeleter deleter(final String pathServiceSid, final String pathIdentity, final String pathFactorSid, final String pathSid) { return new ChallengeDeleter(pathServiceSid, pathIdentity, pathFactorSid, pathSid); }
java
{ "resource": "" }
q163071
Challenge.fetcher
train
public static ChallengeFetcher fetcher(final String pathServiceSid, final String pathIdentity, final String pathFactorSid, final String pathSid) { return new ChallengeFetcher(pathServiceSid, pathIdentity, pathFactorSid, pathSid); }
java
{ "resource": "" }
q163072
Challenge.updater
train
public static ChallengeUpdater updater(final String pathServiceSid, final String pathIdentity, final String pathFactorSid, final String pathSid) { return new ChallengeUpdater(pathServiceSid, pathIdentity, pathFactorSid, pathSid); }
java
{ "resource": "" }
q163073
FeedbackSummary.creator
train
public static FeedbackSummaryCreator creator(final String pathAccountSid, final LocalDate startDate, final LocalDate endDate) { return new FeedbackSummaryCreator(pathAccountSid, startDate, endDate); }
java
{ "resource": "" }
q163074
Invite.fetcher
train
public static InviteFetcher fetcher(final String pathServiceSid, final String pathChannelSid, final String pathSid) { return new InviteFetcher(pathServiceSid, pathChannelSid, pathSid); }
java
{ "resource": "" }
q163075
Invite.creator
train
public static InviteCreator creator(final String pathServiceSid, final String pathChannelSid, final String identity) { return new InviteCreator(pathServiceSid, pathChannelSid, identity); }
java
{ "resource": "" }
q163076
Invite.deleter
train
public static InviteDeleter deleter(final String pathServiceSid, final String pathChannelSid, final String pathSid) { return new InviteDeleter(pathServiceSid, pathChannelSid, pathSid); }
java
{ "resource": "" }
q163077
Reader.nextPage
train
public Page<T> nextPage(final Page<T> page) { return nextPage(page, Twilio.getRestClient()); }
java
{ "resource": "" }
q163078
Reader.previousPage
train
public Page<T> previousPage(final Page<T> page) { return previousPage(page, Twilio.getRestClient()); }
java
{ "resource": "" }
q163079
Reader.limit
train
public Reader<T> limit(final long limit) { this.limit = limit; if (this.pageSize == null) { this.pageSize = (new Long(this.limit)).intValue(); } return this; }
java
{ "resource": "" }
q163080
PrefixedCollapsibleMap.serialize
train
public static Map<String, String> serialize(Map<String, Object> map, String prefix) { if (map == null || map.isEmpty()) { return Collections.emptyMap(); } Map<String, String> flattened = flatten(map, new HashMap<String, String>(), new ArrayList<String>()); Map<String, String> result = new HashMap<>(); for (Map.Entry<String, String> entry : flattened.entrySet()) { result.put(prefix + "." + entry.getKey(), entry.getValue()); } return result; }
java
{ "resource": "" }
q163081
Execution.creator
train
public static ExecutionCreator creator(final String pathFlowSid, final com.twilio.type.PhoneNumber to, final com.twilio.type.PhoneNumber from) { return new ExecutionCreator(pathFlowSid, to, from); }
java
{ "resource": "" }
q163082
RequestCanonicalizer.create
train
public String create(List<String> sortedIncludedHeaders, HashFunction hashFunction) { // Add the method and uri StringBuilder canonicalRequest = new StringBuilder(); canonicalRequest.append(method).append(NEW_LINE); String canonicalUri = CANONICALIZE_PATH.apply(uri); canonicalRequest.append(canonicalUri).append(NEW_LINE); // Get the query args, replace whitespace and values that should be not encoded, sort and rejoin String canonicalQuery = CANONICALIZE_QUERY.apply(queryString); canonicalRequest.append(canonicalQuery).append(NEW_LINE); // Normalize all the headers Header[] normalizedHeaders = NORMALIZE_HEADERS.apply(headers); Map<String, List<String>> combinedHeaders = COMBINE_HEADERS.apply(normalizedHeaders); // Add the headers that we care about for (String header : sortedIncludedHeaders) { String lowercase = header.toLowerCase().trim(); if (combinedHeaders.containsKey(lowercase)) { List<String> values = combinedHeaders.get(lowercase); Collections.sort(values); canonicalRequest.append(lowercase) .append(":") .append(Joiner.on(',').join(values)) .append(NEW_LINE); } } canonicalRequest.append(NEW_LINE); // Mark the headers that we care about canonicalRequest.append(Joiner.on(";").join(sortedIncludedHeaders)).append(NEW_LINE); // Hash and hex the request payload if (!Strings.isNullOrEmpty(requestBody)) { String hashedPayload = hashFunction.hashString(requestBody, Charsets.UTF_8).toString(); canonicalRequest.append(hashedPayload); } return canonicalRequest.toString(); }
java
{ "resource": "" }
q163083
RequestCanonicalizer.replace
train
private static String replace(String string, boolean replaceSlash) { if (Strings.isNullOrEmpty(string)) { return string; } StringBuffer buffer = new StringBuffer(string.length()); Matcher matcher = TOKEN_REPLACE_PATTERN.matcher(string); while (matcher.find()) { String replacement = matcher.group(0); if ("+".equals(replacement)) { replacement = "%20"; } else if ("*".equals(replacement)) { replacement = "%2A"; } else if ("%7E".equals(replacement)) { replacement = "~"; } else if (replaceSlash && "%2F".equals(replacement)) { replacement = "/"; } matcher.appendReplacement(buffer, replacement); } matcher.appendTail(buffer); return buffer.toString(); }
java
{ "resource": "" }
q163084
AvailablePhoneNumberCountryReader.getPage
train
@Override @SuppressWarnings("checkstyle:linelength") public Page<AvailablePhoneNumberCountry> getPage(final String targetUrl, final TwilioRestClient client) { this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid; Request request = new Request( HttpMethod.GET, targetUrl ); return pageForRequest(client, request); }
java
{ "resource": "" }
q163085
AvailablePhoneNumberCountryReader.pageForRequest
train
private Page<AvailablePhoneNumberCountry> pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); if (response == null) { throw new ApiConnectionException("AvailablePhoneNumberCountry read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) { RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); if (restException == null) { throw new ApiException("Server Error, no content"); } throw new ApiException( restException.getMessage(), restException.getCode(), restException.getMoreInfo(), restException.getStatus(), null ); } return Page.fromJson( "countries", response.getContent(), AvailablePhoneNumberCountry.class, client.getObjectMapper() ); }
java
{ "resource": "" }
q163086
Page.getFirstPageUrl
train
public String getFirstPageUrl(String domain, String region) { if (firstPageUrl != null) { return firstPageUrl; } return urlFromUri(domain, region, firstPageUri); }
java
{ "resource": "" }
q163087
Page.getNextPageUrl
train
public String getNextPageUrl(String domain, String region) { if (nextPageUrl != null) { return nextPageUrl; } return urlFromUri(domain, region, nextPageUri); }
java
{ "resource": "" }
q163088
Page.getPreviousPageUrl
train
public String getPreviousPageUrl(String domain, String region) { if (previousPageUrl != null) { return previousPageUrl; } return urlFromUri(domain, region, previousPageUri); }
java
{ "resource": "" }
q163089
Page.getUrl
train
public String getUrl(String domain, String region) { if (url != null) { return url; } return urlFromUri(domain, region, uri); }
java
{ "resource": "" }
q163090
Page.fromJson
train
public static <T> Page<T> fromJson(String recordKey, String json, Class<T> recordType, ObjectMapper mapper) { try { List<T> results = new ArrayList<>(); JsonNode root = mapper.readTree(json); JsonNode records = root.get(recordKey); for (final JsonNode record : records) { results.add(mapper.readValue(record.toString(), recordType)); } JsonNode uriNode = root.get("uri"); if (uriNode != null) { return buildPage(root, results); } else { return buildNextGenPage(root, results); } } catch (final IOException e) { throw new ApiConnectionException( "Unable to deserialize response: " + e.getMessage() + "\nJSON: " + json, e ); } }
java
{ "resource": "" }
q163091
SyncListItem.fetcher
train
public static SyncListItemFetcher fetcher(final String pathServiceSid, final String pathListSid, final Integer pathIndex) { return new SyncListItemFetcher(pathServiceSid, pathListSid, pathIndex); }
java
{ "resource": "" }
q163092
SyncListItem.deleter
train
public static SyncListItemDeleter deleter(final String pathServiceSid, final String pathListSid, final Integer pathIndex) { return new SyncListItemDeleter(pathServiceSid, pathListSid, pathIndex); }
java
{ "resource": "" }
q163093
SyncListItem.creator
train
public static SyncListItemCreator creator(final String pathServiceSid, final String pathListSid, final Map<String, Object> data) { return new SyncListItemCreator(pathServiceSid, pathListSid, data); }
java
{ "resource": "" }
q163094
Request.getAuthString
train
public String getAuthString() { String credentials = this.username + ":" + this.password; try { String encoded = new Base64().encodeAsString(credentials.getBytes("ascii")); return "Basic " + encoded; } catch (final UnsupportedEncodingException e) { throw new InvalidRequestException("It must be possible to encode credentials as ascii", credentials, e); } }
java
{ "resource": "" }
q163095
Request.constructURL
train
@SuppressWarnings("checkstyle:abbreviationaswordinname") public URL constructURL() { String params = encodeQueryParams(); String stringUri = url; if (params.length() > 0) { stringUri += "?" + params; } try { URI uri = new URI(stringUri); return uri.toURL(); } catch (final URISyntaxException e) { throw new ApiException("Bad URI: " + stringUri, e); } catch (final MalformedURLException e) { throw new ApiException("Bad URL: " + stringUri, e); } }
java
{ "resource": "" }
q163096
Promoter.listOfOne
train
public static <T> List<T> listOfOne(final T one) { List<T> list = new ArrayList<>(); list.add(one); return list; }
java
{ "resource": "" }
q163097
Promoter.enumFromString
train
public static <T extends Enum<?>> T enumFromString(final String value, final T[] values) { if (value == null) { return null; } for (T v : values) { if (v.toString().equalsIgnoreCase(value)) { return v; } } return null; }
java
{ "resource": "" }
q163098
ExecutionStep.fetcher
train
public static ExecutionStepFetcher fetcher(final String pathFlowSid, final String pathExecutionSid, final String pathSid) { return new ExecutionStepFetcher(pathFlowSid, pathExecutionSid, pathSid); }
java
{ "resource": "" }
q163099
SessionUpdater.setParticipants
train
public SessionUpdater setParticipants(final Map<String, Object> participants) { return setParticipants(Promoter.listOfOne(participants)); }
java
{ "resource": "" }