Neo4j nested query - neo4j

I am working with this cypher to retrieve nested data for a set of libraries, each having 0-X number of books with each book having 0-X number of authors. The cypher looks like this:
MATCH (library:Library)--(book:Book)--(author:Author)
WITH library, book, {name: author.name} AS nest_author
WITH library, {name: book.name, authors: collect(nest_author)} AS nest_book
WITH {name: library.name, books: collect(nest_book)} AS nest_library
RETURN {library_data: collect(nest_library)}
The only problem with this cypher is that is only works when a library has a book and a book has an author. I tried the query below, but the structure is lost and all the authors appear under all the books and all the books appear under all the libraries:
MATCH (library:Library),(book:Book),(author:Author)
OPTIONAL MATCH (library)--(book)
OPTIONAL MATCH (book)--(author)
WITH library, book, {name: author.name} AS nest_author
WITH library, {name: book.name, authors: collect(nest_author)} AS nest_book
WITH {name: library.name, books: collect(nest_book)} AS nest_library
RETURN {library_data: collect(nest_library)}
How would I write the first query so that the relationships are optional and the collect just returns an empty list when the library doesn't have any books or a book doesn't contain an author?

In your second query you are creating cross products behavior.
Based on the following neo4j console example : http://console.neo4j.org/r/l1cpwz
This query do the trick :
MATCH (n:Library)
OPTIONAL MATCH (n)--(book:Book)
OPTIONAL MATCH (book)--(author:Author)
RETURN n.name, collect({ book: book.title, author: author.lastname })
The example result is the following :
n.name collect({ book: book.title, author: author.lastname })
aspernatur [ {book:"Eligendi fuga est harum est nobis nam id.", author:null}, {book:"Numquam animi ex alias rerum quas.", author:null}]
consectetur [ {book:"Vel nostrum modi officia.", author:null}, {book:"Dolorum dolor optio aut ipsum.", author:null}, {book:"Iste sit quo reprehenderit dolores neque.", author:null}]
corrupti [ {book:"Minus sit sed quia tempora quaerat.", author:null}]
deserunt [ {book:"Temporibus impedit quod aut vel et.", author:null}, {book:"Praesentium perspiciatis blanditiis et omnis suscipit nostrum repudiandae.", author:null}]
labore [ {book:"Non quis maxime doloremque et.", author:null}, {book:"Eos voluptatem voluptatibus mollitia exercitationem nobis.", author:null}, {book:"Vel voluptatem quae libero non est eaque.", author:null}, {book:"Atque velit accusantium perspiciatis assumenda voluptas ea corporis.", author:null}]
nihil [ {book:"Deleniti illo earum eaque sapiente perspiciatis omnis quia.", author:null}, {book:"Est eum enim quo suscipit et molestias.", author:null}, {book:"Consequuntur nam temporibus explicabo quia ipsum.", author:null}, {book:"Facilis ratione illum ipsum sed cum ut.", author:null}, {book:"Est eos quis suscipit ratione alias necessitatibus asperiores sunt.", author:null}, {book:"Odit voluptatem est reiciendis quod tempora.", author:null}]
officiis [ {book:"Ad libero porro quibusdam voluptatum.", author:null}, {book:"Numquam omnis ut unde sequi sint enim.", author:null}]
omnis [ {book:"Qui laboriosam alias repellendus quibusdam incidunt et.", author:null}, {book:"Eos officia vitae consequatur qui.", author:null}, {book:"Explicabo nemo eos maxime.", author:null}, {book:"Dolores voluptatum et similique natus dolore fuga perferendis molestiae.", author:null}, {book:"Quidem aut ut ut quas veritatis.", author:null}, {book:"In in quos et aspernatur dolores.", author:null}, {book:"Alias sed quasi explicabo possimus veniam temporibus.", author:null}, {book:"Omnis dolor eum molestiae veritatis.", author:null}]
tempore [ {book:null, author:null}]

Related

Multiline Textfield with .Vertical axis going below keyboard

I am having some issues with the textfield not moving up with the view.
I am using a textfield with Vertical axis (iOS 16) to create the multiline. This works correctly and stays above the keyboard as expected when it is not embedded in a scrollview. But as soon as the textfield is embedded in the scrollview the multiline just goes below the keyboard and you have to manually scroll to see the last line.
Please see code below. This should work correctly. But if you remove the scrollview you will notice the issue when typing.
struct ContentView: View {
#State private var text = "Lorem ipsum dolor sit amet. Nam voluptatem necessitatibus aut quis odio rem error repudiandae id aliquam perferendis et quidem quaerat et enim harum! Cum nesciunt animi rem quia vero aut omnis eligendi in ducimus eaque sit mollitia fugit est animi nesciunt. Ut exercitationem nulla qui dolor nihil ad autem vero quo internos sapiente eum dicta nihil qui exercitationem cumque et consectetur dolore. Et fugiat officiis non harum voluptas et modi repellendus ut repellat dolorem 33 eveniet quidem qui galisum veritatis. Id consequatur tenetur et eaque voluptas in assumenda delectus et fuga praesentium rem provident delectus est necessitatibus sunt quo dignissimos dolorum. Et reiciendis error et rerum eligendi qui illum error? In soluta ipsum est molestiae pariatur hic voluptas animi qui cupiditate amet."
var body: some View {
ScrollView {
VStack() {
TextField("Enter something", text: $text, axis: .vertical)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
}
}
If there are any GitHub repos you know that would also be great.
Update:
I have found a solution and will be posting it in the coming days.
This is not a definitive answer. In the simulator some buggy behavior appears. Try this out and see on a real device (that I don't have here).
import SwiftUI
struct ContentView: View {
#State private var text = "Lorem ipsum dolor sit amet. Nam voluptatem necessitatibus aut quis odio rem error repudiandae id aliquam perferendis et quidem quaerat et enim harum! Cum nesciunt animi rem quia vero aut omnis eligendi in ducimus eaque sit mollitia fugit est animi nesciunt. Ut exercitationem nulla qui dolor nihil ad autem vero quo internos sapiente eum dicta nihil qui exercitationem cumque et consectetur dolore. Et fugiat officiis non harum voluptas et modi repellendus ut repellat dolorem 33 eveniet quidem qui galisum veritatis. Id consequatur tenetur et eaque voluptas in assumenda delectus et fuga praesentium rem provident delectus est necessitatibus sunt quo dignissimos dolorum. Et reiciendis error et rerum eligendi qui illum error? In soluta ipsum est molestiae pariatur hic voluptas animi qui cupiditate amet."
#Namespace var bottomText
var body: some View {
ScrollViewReader { proxy in
ScrollView {
Text("Title")
.font(.largeTitle)
TextField("Enter something", text: $text, axis: .vertical)
.textFieldStyle(RoundedBorderTextFieldStyle())
.onChange(of: text) { newValue in
print("Fired.")
withAnimation {
proxy.scrollTo(bottomText, anchor: .center)
}
}
Color.red.frame(height: 50).id(bottomText)
}
}
}
}
When TextField axis is .vertical, anchor must be .top
VStack {
// ... other code
.onSubmit {
// update state here !!
if (i + 1) < inputsValues.count {
focusedInput = i + 1
} else {
focusedInput = nil
}
}
}
.onChange(of: focusedInput) {
// When TextField axis is .vertical, anchor must be .top
proxy.scrollTo($0, anchor: .top)
}
Here is full source code.

Nokogiri: why does this return only the removed tag and not the remainder?

Where body is this:
<img src='/Users/test/Documents/cd-rum/whatever/spec/factories/images/rda.jpg' />Et qui incidunt provident sed nemo modi pariatur quia.
Why does this:
parsed_body = Nokogiri::HTML(body).search('img').first.remove
parsed_body.to_html
Return only the image tag?
Failure/Error: specify { expect(post.parsed_body).to_not include('<img') }
expected "<img src=\"/Users/test/Documents/cd-rum/whatever/spec/factories/images/rda.jpg\">" not to include "<img"
Because you're assigning the result of .remove to that variable - just remove the assignment
body = "<img src='/Users/test/Documents/cd-rum/whatever/spec/factories/images/rda.jpg' />Et qui incidunt provident sed nemo modi pariatur quia."
parsed_body = Nokogiri::HTML::fragment(body)
parsed_body.search('img').first.remove
parsed_body.to_html # => "Et qui incidunt provident sed nemo modi pariatur quia."

Handle multiple JSON formats in Swift

I have created these typealias in my project
typealias JSON = [String: AnyObject]
typealias JSONArray = [JSON]
I'm testing an JSON API Client using JSONPlaceholder and getting two different JSON responses.
Response 1 (JSON)
{
userId: 1,
id: 1,
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body: "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
}
Response 2 (Array of JSON)
[
{
userId: 1,
id: 1,
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body: "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
},
{
userId: 1,
id: 2,
title: "qui est esse",
body: "est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla"
},
...
]
In order to create my code as generic as possible, I'm using a protocol approach. Everything works fine but I have a small issue parsing the json response.
// JSONResource is a protocol
extension JSONResource {
func handleResponse(_ data: Data?, response: URLResponse?, error: NSError?) -> WebServiceResult<Response> {
let parsedData = try! JSONSerialization.jsonObject(with: data, options: .allowFragments)
do {
if let json = parsedData as? JSON {
let parsedResponse = try Response(json: json)
return .success(parsedResponse)
}
if let jsonArray = parsedData as? JSONArray {
let parsedResponse = try Response(jsonArray: jsonArray)
return .success(parsedResponse)
}
} catch let error as NSError {
return .failure(error)
}
}
}
The Response is created using a protocol too
protocol JSONServiceResponse: WebServiceResponse {
init(json: JSON) throws
init(jsonArray: JSONArray) throws
}
My problem is my code seems redundant because I have to handle JSON an JSONArray types but I'll only know that when I'm creating the type who implements the protocol.
Is there a different way to handle the JSON and JSONArray responses from the server in order to use a unique init(json: JSON) ?
Thanks

CKEditor: Text is displayed in html format

I am making a blog website in rails 5. But I wanted to create dynamic articles, where I can add headers, images and more. I discovered CKEditor. I have coded CKEditor into my form, <%= f.cktext_area :body, ckeditor: { language: 'en', uiColor: '#F0F0F0', toolbar: 'mini'} %> and it works great! It adds text to the body of my post, as I intended.
The only problem I have is that it is displaying in html format. The image below is a sample post I made. This is how I want my post to look after I submit.
And here is the problem. This is the exact result of the image above. When I save my post, this is what I see.
<p><span style="font-size:18px">A nice header</span></p>
<p>Lorem ipsum dolor sit amet, et eam lorem assum nihil, oportere erroribus mei no. At ius errem utamur, est nonumes consectetuer necessitatibus te. Cum et sumo nulla aliquid. Eos summo nihil no. Iusto inermis no qui.</p>
<p>Agam dicat mediocrem et vel, augue consulatu disputationi nam eu, vel id mentitum invidunt. Te assum accumsan nam, nam in recteque ullamcorper. Vix ei vitae labores legimus. Ea vis saepe meliore salutatus, usu an homero quaerendum disputationi. Eu menandri mediocritatem pri.</p>
<hr />
<p><img alt="" src="https://static01.nyt.com/images/2016/07/23/us/politics/23fd-campaign/23fd-campaign-master768.jpg" style="height:512px; width:768px" /></p>
<hr />
<p>Vim minim nonumy et, quodsi pertinax at pro, eu audiam facilisi cotidieque vel. Ius no quis probatus, ad eam equidem repudiare vulputate, no eos ponderum incorrupte. Cu delenit torquatos cum, at aperiam vocibus sit. Nec euismod incorrupte et.</p>
<p>Sit et molestie insolens oportere, dicam laudem no mel, et soleat vituperatoribus ius. In vix justo doming admodum, duo choro verear utamur an. Qui ut fugit atomorum, duo agam virtute et. Eam te nobis aliquando instructior, vix ancillae accusamus no. Nisl lucilius percipitur at pri, duo ne probo salutandi conceptam. Sed magna iudicabit forensibus ex, sed ne maiorum neglegentur.</p>
<p>Eu vix vidit convenire, pro id lorem aliquid quaerendum. Enim lobortis no mei, labore putant delectus et qui, ad solum petentium interesset nam. Pro virtute utroque debitis et, mei eu case blandit omittantur, id sed graecis abhorreant. Sed inimicus consequat id, choro commune ad cum, per dicat laudem phaedrum te.</p>
How can I get CKEditor to produce posts that look like the one in the image.
try using <%= raw(object.body)%>

Facing issue with NSPredicate

In my project below is the Dictionary, i have a list of dictionaries which i am trying to get the same value based on predicate but i am not getting the value.
NSPredicate* searchPredicate = [NSPredicate predicateWithFormat:#"(%K CONTAINS[c] %#)",#"**equipArray.equipmentName**",textField.text];
NSLog(#"searchPredicate %#",searchPredicate);
NSArray* searchList = [list filteredArrayUsingPredicate:searchPredicate];
But i am not able to get the list. can anyone help me ?
{
equipArray = (
{
equipmentIcon = "outside.png";
equipmentName = Outside;
},
{
equipmentIcon = "steps.png";
equipmentName = Steps;
},
{
equipmentIcon = "partner.png";
equipmentName = Partner;
}
);
exId = 4;
exeName = "Fireman Carry";
exerciseAudioCue = "DG Fighting Fit-exercise_audio_test.mp3";
exerciseDescription = "Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris. Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non mauris vitae erat consequat auctor eu in elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris in erat justo. Nullam ac urna eu felis dapibus condimentum sit amet a augue. Sed non neque elit. Sed ut imperdiet nisi. Proin condimentum fermentum nunc. Etiam pharetra, erat sed fermentum feugiat, velit mauris egestas quam, ut aliquam massa nisl quis neque. Suspendisse in orci enim.";
exerciseType = Stamina;
imageThumbNail = "firemancarry_thumbnail.png";
longVideoName = long;
shortVideoName = small;
}
If you want to find elements where any equipmentName in the equipArray contains the
given string, use:
[NSPredicate predicateWithFormat:#"ANY %K CONTAINS[c] %#", #"equipArray.equipmentName", textField.text];
("CONTAINS" is for string comparison, not to check for containment in an array.)
Use this predicate this:
[NSPredicate predicateWithFormat:#"equipArray.equipmentName =[cd] %#", textField.text];
try like this,
NSPredicate* searchPredicate = [NSPredicate predicateWithFormat:#"(equipArray.equipmentName CONTAINS[c] %#)",textField.text];
NSPredicate *searchPredicate=[NSPredicate predicateWithFormat:#"ANY %K == [cd] %#", #"equipArray.equipmentName", #"steps"];

Resources