Can you please give an example how to transform this using Java 8 Optional.
Motion motion = new Motion();
if (null!= site.getLocation() && null != site.getLocation().getLatitude() && null != site.getLocation().getLongitude()) {
Point p = GeoJson.point(site.getLocation().getLatitude(), site.getLocation().getLongitude());
motion.setLocation(p);
}
Up till now I do this
Motion motion = new Motion();
Optional<Location> locationOptional = Optional.ofNullable(site.getLocation());
Point p = locationOptional
.map(location -> {
if (Optional.ofNullable(location.getLatitude()).isPresent() && Optional.ofNullable(location.getLongitude()).isPresent()) {
return GeoJson.point(location.getLatitude(), location.getLongitude());
}
return null;
})
.orElse(null);
motion.setLocation(p);
GeoJson geoJson =
Optional.ofNullable(s.getLocation())
.filter(l -> l.getLatitude() != null)
.filter(l -> l.getLongitude() != null)
.map(l -> GeoJson.point(l.getLatitude(), l.getLongitude()))
.orElse(null);
Related
Is there any approach to saving the output of core NLP sentiment analysis in a file rather than messaging in the output?
my code that messages the result :
`
NLP.init();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("Qxykv655aAS4L5JFXszO1Ym0o");
cb.setOAuthConsumerSecret("EUSziBboNBzn8arsxt2cOgPJWGhs8uCK7yWwZSpKdbzBohRost");
cb.setOAuthAccessToken("825807469238706181-CD69DQaULHhZzNzyIPxDQaTXc4KIDHK");
cb.setOAuthAccessTokenSecret("Y836DvgGset2FMfe9VX3wlzaT69HV0qE7oQumZQCuT7vR");
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
StatusListener listener = new StatusListener() {
public void onStatus(Status status) {
if (((NLP.findSentiment(status.getText()) == 1) | (NLP.findSentiment(status.getText()) == 0))
){
System.out.println(status.getText());
if (status.getGeoLocation() != null) {
double latitude = status.getGeoLocation().getLatitude();
double longitude = status.getGeoLocation().getLongitude();
if (latitude != 20 && longitude != 78) {
return;
}
}
}
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = {"pizza, junk food, hamburger"};
fq.track(keywords);
fq.language(new String[]{"en"});
twitterStream.addListener(listener);
twitterStream.filter(fq);
`
I am working on a problem that requires to partition a directed labeled graph into several subgraphs. In each of the subgraph, the nodes are connected and they have the same label. Is there an efficient algorithm to solve this?
Here is my solution implemented in Java, it uses JGraphT as the graph library.
private Set<Set<Node>> partition(DirectedGraph<Node, Edge> graph) {
Map<Node, Set<Node>> map = new HashMap<Node, Set<Node>>();
for (Edge edge : graph.edgeSet()) {
Node source = graph.getEdgeSource(edge);
Node target = graph.getEdgeTarget(edge);
if (source.getLabel().equals(target.getLabel())) {
if (map.get(source) != null && map.get(target) == null) {
map.get(source).add(target);
map.put(target, map.get(source));
} else if (map.get(target) != null && map.get(source) == null) {
map.get(target).add(source);
map.put(source, map.get(target));
} else if (map.get(source) == null && map.get(target) == null) {
Set<Node> set = new HashSet<Node>();
set.add(source);
set.add(target);
map.put(source, set);
map.put(target, set);
} else {
Set<Node> sourceSet = map.get(source);
Set<Node> targetSet = map.get(target);
sourceSet.addAll(targetSet);
for(Node n : targetSet){
map.put(n,sourceSet);
}
targetSet = null;
}
} else {
if (map.get(source) == null) {
Set<Node> set = new HashSet<Node>();
set.add(source);
map.put(source, set);
}
if (map.get(target) == null) {
Set<Node> set = new HashSet<Node>();
set.add(target);
map.put(target, set);
}
}
Collection<Set<Node>> values = map.values();
}
return new HashSet<Set<Node>>(map.values());
}
I'm trying to write following LINQ query using ServiceStack Ormlite.
dbConn.Select<Product>(p => p.IsActive.HasValue && p.IsActive.Value)
Here, Product is my item class and "IsActive" is Nullable Bool property in that class. When this line executes it always throws "InvalidOperationException" with the message
variable 'p' of type '' referenced from scope '', but it is not defined
I tried different variants as following but still same exception result
dbConn.Select<Product>(p => p.IsActive.HasValue == true && p.IsActive.Value == true)
dbConn.Select<Product>(p => p.IsActive != null && p.IsActive.Value == true)
But if I just write
dbConn.Select<Product>(p => p.IsActive.HasValue)
then it works.
I'm puzzled what is the problem? Is this servicestack ormlite issue?
My answer can handle Nullable value like "value" and "HasValue" with servicestack ormlite. And But also with datetime nullable ,like 'createdate.value.Year'.
you must change two place.
modify VisitMemberAccess method:
protected virtual object VisitMemberAccess(MemberExpression m)
{
if (m.Expression != null)
{
if (m.Member.DeclaringType.IsNullableType())
{
if (m.Member.Name == nameof(Nullable<bool>.Value))
return Visit(m.Expression);
if (m.Member.Name == nameof(Nullable<bool>.HasValue))
{
var doesNotEqualNull = Expression.NotEqual(m.Expression, Expression.Constant(null));
return Visit(doesNotEqualNull); // Nullable<T>.HasValue is equivalent to "!= null"
}
throw new ArgumentException(string.Format("Expression '{0}' accesses unsupported property '{1}' of Nullable<T>", m, m.Member));
}
if (m.Member.DeclaringType == typeof(DateTime))
{
var ExpressionInfo = m.Expression as MemberExpression;
if (ExpressionInfo.Member.DeclaringType.IsNullableType())
{
if (ExpressionInfo.Member.Name == nameof(Nullable<bool>.Value))
{
var modelType = (ExpressionInfo.Expression as MemberExpression).Expression.Type;
var tableDef = modelType.GetModelDefinition();
var columnName = (ExpressionInfo.Expression as MemberExpression).Member.Name;
var QuotedColumnName = GetQuotedColumnName(tableDef, columnName);
if (m.Member.Name == "Year")
{
return new PartialSqlString(string.Format("DATEPART(yyyy,{0})", QuotedColumnName));
}
if (m.Member.Name == "Month")
return new PartialSqlString(string.Format("DATEPART(mm,{0})", QuotedColumnName));
}
if (ExpressionInfo.Member.Name == nameof(Nullable<bool>.HasValue))
{
var doesNotEqualNull = Expression.NotEqual(ExpressionInfo.Expression, Expression.Constant(null));
return Visit(doesNotEqualNull); // Nullable<T>.HasValue is equivalent to "!= null"
}
}
else
{
var modelType = ExpressionInfo.Expression.Type;
var tableDef = modelType.GetModelDefinition();
var columnName = ExpressionInfo.Member.Name;
var QuotedColumnName = GetQuotedColumnName(tableDef, columnName);
if (m.Member.Name == "Year")
return new PartialSqlString(string.Format("DATEPART(yyyy,{0})", QuotedColumnName));
if (m.Member.Name == "Month")
return new PartialSqlString(string.Format("DATEPART(mm,{0})", QuotedColumnName));
}
}
if (m.Expression.NodeType == ExpressionType.Parameter || m.Expression.NodeType == ExpressionType.Convert)
{
var propertyInfo = (PropertyInfo)m.Member;
var modelType = m.Expression.Type;
if (m.Expression.NodeType == ExpressionType.Convert)
{
var unaryExpr = m.Expression as UnaryExpression;
if (unaryExpr != null)
{
modelType = unaryExpr.Operand.Type;
}
}
var tableDef = modelType.GetModelDefinition();
if (propertyInfo.PropertyType.IsEnum)
return new EnumMemberAccess(
GetQuotedColumnName(tableDef, m.Member.Name), propertyInfo.PropertyType);
return new PartialSqlString(GetQuotedColumnName(tableDef, m.Member.Name));
}
}
var member = Expression.Convert(m, typeof(object));
var lambda = Expression.Lambda<Func<object>>(member);
var getter = lambda.Compile();
return getter();
}
modify VisitLambda method :
protected virtual object VisitLambda(LambdaExpression lambda)
{
if (lambda.Body.NodeType == ExpressionType.MemberAccess && sep == " ")
{
MemberExpression m = lambda.Body as MemberExpression;
if (m.Expression != null)
{
string r = VisitMemberAccess(m).ToString();
if (m.Member.DeclaringType.IsNullableType())
return r;
return string.Format("{0}={1}", r, GetQuotedTrueValue());
}
}
return Visit(lambda.Body);
}
This is nature of the Linq. In order to achieve what you need, you will need to use two where closes:
dbConn.Where<Product>(p => p.IsActive.HasValue).Where(p=>p.Value==true);
I was recently asked in the interview
What would be the efficient algorithm to find if two given binary trees are structurally identical but not the content?
a
/ \
b c
\
e
z
/ \
u v
\
t
are structurally identical.
Next question was find out if 2 binary tree are structurally mirror ?
Any pointer or help are appreciated.
My attempt was
boolean isStrucutrallyIdentitical(BinaryNode root1, BinayNode root2) {
if(root1==null && root2==null) return true;
if(root1==null || root2==null) return false;
if(root1!=null && roo2!=null) return true; // instead of value just check if its null or not
return isStrucutrallyIdentitical(root1.getLeft(), root2.getLeft()) && isStrucutrallyIdentitical(root1.getRight(), root2.getRight());
}
public boolean areStructuralySame(TreeNode<Integer> tree1, TreeNode<Integer> tree2) {
if(tree1 == null && tree2 == null) {
return true;
}
if(tree1 == null || tree2 == null) {
return false;
} else return (areStructuralySame(tree1.getLeft(), tree2.getLeft()) && areStructuralySame(tree1.getRight(), tree2.getRight()));
}
This works fine
private static boolean compare(TNode curRoot, TNode newRoot) {
if (curRoot == null && newRoot == null) {
return true;
} else if ((curRoot == null && newRoot != null) || (curRoot != null && newRoot == null))
return false;
else {
if (compare(curRoot.left, newRoot.left) && compare(curRoot.right, newRoot.right))
return true;
return false;
}
}
I have coded a JPA repository method and I am now realizing it is impossible to unit test.
Can anyone please advise how to unit test the following method or how to refactor my repository so that it is unit-testable?
Here is the problematic method:
#Override
public List<Pli> findPlisByMultiField(String identifiant, Date dateReceptionFrom, Date dateReceptionTo, PaiementEnum paiement, AREnum ar, String numeroAR, FDVEnum FDV, ConteneurNum conteneurNum, StatutPli statut) {
log.debug("findPlisByMultiField");
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Pli> c = criteriaBuilder.createQuery(Pli.class);
Root<Pli> pli = c.from(Pli.class);
List<Predicate> criteria = new ArrayList<Predicate>();
if (identifiant != null && !identifiant.trim().equals("")) {
ParameterExpression<String> parameterIdentifiant = criteriaBuilder.parameter(String.class, "identifiant");
Predicate conditionIdentifiant = criteriaBuilder.like(pli.<String> get("identifiant"), parameterIdentifiant);
criteria.add(conditionIdentifiant);
}
if (dateReceptionFrom != null && dateReceptionTo != null) {
ParameterExpression<Date> parameterDateReceptionFrom = criteriaBuilder.parameter(Date.class, "dateReceptionFrom");
ParameterExpression<Date> parameterDateReceptionTo = criteriaBuilder.parameter(Date.class, "dateReceptionTo");
Predicate conditionDateReception = criteriaBuilder.between(pli.<Date> get("dateReception"), parameterDateReceptionFrom, parameterDateReceptionTo);
criteria.add(conditionDateReception);
}
if (paiement != null) {
if (paiement.equals(PaiementEnum.IsPaiement)) {
Predicate conditionPaiementEnum = criteriaBuilder.equal(pli.<PaiementEnum> get("paiement"), true);
criteria.add(conditionPaiementEnum);
} else {
Predicate conditionPaiementEnum = criteriaBuilder.equal(pli.<PaiementEnum> get("paiement"), false);
criteria.add(conditionPaiementEnum);
}
}
if (ar != null) {
if (ar.equals(AREnum.IsAR)) {
Predicate conditionAREnum = criteriaBuilder.equal(pli.<AREnum> get("AR"), true);
criteria.add(conditionAREnum);
} else {
Predicate conditionAREnum = criteriaBuilder.equal(pli.<AREnum> get("AR"), false);
criteria.add(conditionAREnum);
}
}
if (numeroAR != null && !numeroAR.trim().equals("")) {
ParameterExpression<String> parameterNumeroAR = criteriaBuilder.parameter(String.class, "numeroAR");
Predicate conditionNumeroAR = criteriaBuilder.like(pli.<String> get("numeroAR"), parameterNumeroAR);
criteria.add(conditionNumeroAR);
}
if (FDV != null) {
if (FDV.equals(FDVEnum.IsFDV)) {
Predicate conditionFDVEnum = criteriaBuilder.equal(pli.<FDVEnum> get("FDV"), true);
criteria.add(conditionFDVEnum);
} else {
Predicate conditionFDVEnum = criteriaBuilder.equal(pli.<FDVEnum> get("FDV"), false);
criteria.add(conditionFDVEnum);
}
}
if (conteneurNum != null) {
ParameterExpression<ConteneurNum> parameterConteneurNum = criteriaBuilder.parameter(ConteneurNum.class, "conteneurNum");
Predicate conditionConteneurNum = criteriaBuilder.equal(pli.<ConteneurNum> get("conteneurNum"), parameterConteneurNum);
criteria.add(conditionConteneurNum);
}
if (statut != null) {
ParameterExpression<StatutPli> parameterStatut = criteriaBuilder.parameter(StatutPli.class, "statut");
Predicate conditionStatut = criteriaBuilder.equal(pli.<StatutPli> get("statut"), parameterStatut);
criteria.add(conditionStatut);
}
if (criteria.size() == 0) {
return Pli.findAllPlis();
} else if (criteria.size() == 1) {
c.where(criteria.get(0));
} else {
c.where(criteriaBuilder.and(criteria.toArray(new Predicate[0])));
}
TypedQuery<Pli> q = em.createQuery(c);
if (identifiant != null && !identifiant.trim().equals("")) {
q.setParameter("identifiant", "%" + identifiant + "%");
}
if (dateReceptionFrom != null && dateReceptionTo != null) {
q.setParameter("dateReceptionFrom", dateReceptionFrom);
q.setParameter("dateReceptionTo", dateReceptionTo);
}
if (numeroAR != null && !numeroAR.trim().equals("")) {
q.setParameter("numeroAR", "%" + numeroAR + "%");
}
if (conteneurNum != null) {
q.setParameter("conteneurNum", conteneurNum);
}
if (statut != null) {
q.setParameter("statut", statut);
}
return q.getResultList();
}
Well, I don't think you will be able to Unit Test it as it's strictly specified, but you can make a test using an in memory database (look out for HSQL) so that the app don't need to actually go to the real database just for testing.
That way you will be able to create an automated test that could run inside JUnit for example, mocking maybe only some of the methods.