Vala List Folder & Subfolder content - vala

I use this code, to list my folder content as a TreeView.
try {
string directory = "/home/malte/.password-store/";
Dir dir = Dir.open (directory, 0);
string? name = null;
while ((name = dir.read_name ()) != null) {
string path = Path.build_filename (directory, name);
if (FileUtils.test (path, FileTest.IS_REGULAR)) {
list_store.append (out iter);
list_store.set (iter, 0, name);
}
}
} catch (FileError err) {
stderr.printf (err.message);
}
This really works perfectly. But I want to list my subfolder contents, too. And in the subfolders are folders too. Can somebody give me a hint how to do this?
Thanks

Just make the file listing a function that calls itself recursively.
Here is an example in C.
Pseudocode:
void list_files_recursive (string dir, List<string> filenames) {
foreach (filename in dir) {
if (file_is_dir(filename)) {
list_files_recursive (filename, filenames);
} else {
filenames.add (filename);
}
}
}
As for how to add them to a tree store instead of a list store that is a different question, but I'm sure there are examples somewhere for Vala and tree stores.

Related

Doubly linked list java remove

I have a problem when deleting many nodes.
I can delete them if I select nodes like this:
But if I do something like this, I cannot delete them:
My Code:
public boolean remove(ProductNode<E> data) {
if (isEmpty()) {
throw new NoSuchElementException();
}
for (ProductNode<E> current = this.head; current != null; current = current.next) {
ProductNode<E> pre = current.prev;
ProductNode<E> next = current.next;
if (data != null) {
if (current.data.equals(data.data)) {
if (pre == null) {
head = next;
current.next = null;
} else {
if (next != null) {
next.prev = pre;
}
}
if (next == null) {
pre.next = null;
current.prev = null;
tail = pre;
} else {
if (pre != null) {
pre.next = next;
}
}
}
}
}
size--;
return false;
}
Search node
public ProductNode<E> search(E data) {
for (ProductNode<E> current = this.head; current != null; current = current.next) {
if (current.data.equals(data)) {
return current;
}
}
return null;
}
Remove
public void remove(E e) {
remove(search(e));
}
Delete:
for(Tab_Product p : remove_list){
List_Products.list_products.remove(p);
}
Your remove function (ProductNode data), is a bit complicated and may be affecting your code's ability to delete multiple nodes. In the case of this remove function you do not need traverse the whole data set. If you already have a reference to the node you can just directly modify the list with it.
public boolean remove(ProductNode<E> data) {
if (isEmpty()) {
throw new NoSuchElementException();
}
ProductNode<E> pre = data.prev;
ProductNode<E> next = data.next;
//First remove the nodes references to its neighbors.
data.prev = null;
data.next = null;
// Now check the neighbors and update their references
// to remove all references to the deleted node.
if (pre != null) pre.next = next;
if (next != null) next.prev = pre;
if (data == head) { //This checks the actual memory address.
head = next;
}
size--;
}
Since you already have the ProductNode, you do not need to search the list. your search() function is already doing that for you. since you already have the node you just need to make its references to its neighbors null then you just have to access the neighbors (if there are any) and make their old references skip over the deleted node.
I noticed a few reference errors where a deleted node was not getting completely removed from the list but i will not mention them because this delete function is rather complicated. Try simplifying the delete function and then see what your results are.
It also might be helpful if you show us the structure of the List_Products object.
Additionally you should verify that the data you select in the UI is getting passed correctly. This could be a UI bug.

Relevant url in file Upload

I'm uploading an image to my site using the following code,
The Image uploading just fine but, how ever
I need to fix the following things :
-I'm getting this kind of Url
C:\Users\Me\Documents\Visual Studio 2013\Projects\Wow\WowMvc5\WowMvc5\images\gallery\Picture 022.jpg,
Instead of relevant folder Url
-I thing in order to avoid an error of 2 images this the same name it would be better to create a folder under images for each image (or any better idea )
Thank you for your time
public async Task<ActionResult> Create([Bind(Include = "TakeAwayId,TakeAwayName,description,Price,DishUrl,quantity,DishesAmount,GenreId")] TakeAway takeaway)
{
var path = Server.MapPath("~/Images/gallery/");
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item];
if (file.ContentLength == 0)
{
continue;
}
string SavedFileName = System.IO.Path.GetFileName(file.FileName);
SavedFileName = Server.MapPath
("~" + "/images/gallery/" + SavedFileName);
file.SaveAs(SavedFileName);
takeaway.DishUrl = SavedFileName;
}
if (ModelState.IsValid)
{
db.takeaway.Add(takeaway);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.GenreId = new SelectList(db.genre, "GenreId", "GenreName", takeaway.GenreId);
return View(takeaway);
}
What I would do is name and save each picture using a HashCode.
By definition, It's very improbable that 2 different strings, when transformed using a hash algorithm, will have the same output. Just to be sure, add a random string to the original name of the image.
string newName = (oldName + random).GetHashCode().ToString()
filename_1.jpg
where cnt is incremental count
if(file.exists()
{
string cnt = file.split("");
String newFileName = filename+""+(cnt+1)+".jpg";
}

How to compare two JSONArray and find differencer when JSONArrays itself contain JSONObject which in turn contain JSONArray

I am new to this forum.I am trying to compare two directory structure one that is on remote and another one that is on local.
Currently what I am doing is based on certain things I am making a JSONArray of directury structure from server side(remote) . Same way I am making a JSONArray of directory structure of client side. Now I want to compare those two JSONArray and get the difference between them.
Also I want to maintain the level of directory structure also . Meaning that in the resulting JSONArray the difference should be at proper level which I can may directly with directory.
Please guide me If I make any mistake here as I am new to the forum.
I have tried below code.
public static boolean jsonObjsAreEqual (JSONObject js1, JSONObject js2) throws JSONException {
if (js1 == null || js2 == null) {
System.out.println(METHOD+"js1 or js2 null");
return (js1 == js2);
}
List<String> l1 = Arrays.asList(JSONObject.getNames(js1));
Collections.sort(l1);
Collections.reverse(l1);
List<String> l2 = Arrays.asList(JSONObject.getNames(js2));
Collections.sort(l2);
Collections.reverse(l2);
if (!l1.equals(l2)) {
return false;
}
for (String key : l1) {
Object val1 = js1.get(key);
Object val2 = js2.get(key);
if (val1 instanceof JSONObject) {
if (!(val2 instanceof JSONObject)) {
return false;
}
if (jsonObjsAreEqual((JSONObject)val1, (JSONObject)val2)) {
return true;
}else{
return false;
}
}
if (val1 instanceof JSONArray) {
if (!(val2 instanceof JSONArray)) {
return false;
}
JSONArray arr1=JsonSorter.sortJsonByKey((JSONArray) val1, "name");
JSONArray arr2=JsonSorter.sortJsonByKey((JSONArray) val2, "name");
int flag=0;
int count=0;
int []arr=new int[100];
for(int k=0;k<arr1.length();k++){
flag=0;
for(int l=0;l<arr2.length();l++){
boolean returnval=jsonObjsAreEqual((JSONObject)arr1.get(k), (JSONObject)arr2.get(l));
if (returnval) {
flag=1;
break;
}
}
if(flag==0){
return false;
}
}
}else{
if (val1 == null) {
if (val2 != null) {
return false;
}
} else if (!val1.equals(val2)) {
return false;
}
}
}
return true;
}
For example I am using below JSONs as arguments;
js1={"JSArray":[{"folder":1,"name":"My Music","innerJSON":[]},{"folder":1,"name":"My Videos","innerJSON":[]},{"folder":1,"name":"RW-By-10-No-New-Folder","innerJSON":[]},{"folder":1,"name":"RW-By-11-plus-New-Folder","innerJSON":[{"folder":1,"name":"ab25249asset.001829.PNG","innerJSON":[]}]},{"folder":1,"name":"My Documents","innerJSON":[]},{"folder":1,"name":"My Tunes","innerJSON":[]},{"folder":1,"name":"Music","innerJSON":[{"folder":1,"name":"ROnly-SubFolder-to-user10","innerJSON":[]}]},{"folder":1,"name":"kamal","innerJSON":[]},{"folder":1,"name":"zxcvb","innerJSON":[]},{"folder":1,"name":"My Pictures","innerJSON":[]},{"folder":1,"name":"abc","innerJSON":[]}]}
js2={"JSArray":[{"folder":1,"name":"Music","innerJSON":[{"folder":0,"name":"Track_12_[1].mp3"},{"folder":1,"name":"ROnly-SubFolder-to-user10","innerJSON":[]},{"folder":0,"name":"08_Track_8.wma"}]},{"folder":1,"name":"My Documents","innerJSON":[{"folder":0,"name":"temp.ico"},{"folder":0,"name":"logo-mdpi.png"}]},{"folder":1,"name":"My Music","innerJSON":[]},{"folder":1,"name":"My Pictures","innerJSON":[{"folder":0,"name":"ab16807asset.JPG"}]},{"folder":1,"name":"My Tunes","innerJSON":[{"folder":0,"name":"dharamshala.jpg"},{"folder":0,"name":"Logo.gif"}]},{"folder":1,"name":"My Videos","innerJSON":[]},{"folder":1,"name":"RW-By-10-No-New-Folder","innerJSON":[]},{"folder":1,"name":"RW-By-11-plus-New-Folder","innerJSON":[{"folder":1,"name":"ab25249asset.001829.PNG","innerJSON":[]}]}]}
Tell me if anything more is needed. I want diff of this type of JSONs. They represent directory structure and file inside them so there can be n level of folder.so need to keep that thing in mind.
In a JSON an "innerJSON" key represents a folder inside a folder upto n level from that folder.
Thanks

Load an XML string into a Vaadin Tree

I am doing a project in Vaadin and need to do the following. I make a server request and get an XML string in response. And, I know nothing about how this XML file will look at run time. I need to convert this XML string into a vaadin tree.
I have seen some answers where they say to load into a HierarchicalContainer and all but I'm unable to make sense of it.
Please help me!
If you don't want to use HierarchicalContainer (I have no experience with that), you can just parse the XML document recursively like that: Recursive XML-parser
Then just add the items and set the parent. Something like this:
#Override
protected void init(VaadinRequest request) {
Tree tree = new Tree();
setContent(tree);
try {
File fXmlFile = new File("C:\\temp\\sample.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
Element root = doc.getDocumentElement();
Object rootItem = root.getNodeName();
tree.addItem(rootItem);
addChildrenToTree(tree, root.getChildNodes(), rootItem);
} catch (Exception e) { }
}
private void addChildrenToTree(Tree tree, NodeList children, Object parent) {
if (children.getLength() > 0) {
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
Object child = node.getNodeName();
tree.addItem(child);
tree.setParent(child, parent);
addChildrenToTree(tree, node.getChildNodes(), child);
}
}
}

OpenXml and HttpResponse.OutputStream

I have an Asp.Net Mvc application. In this application i have a functionality to download data from Database to Excel file (with OpenXml Sdk). It works now. But when data is large, time from user request to response with download window becomes 10+ minutes. This is because of two long process:
Taking data from MSSQL server.
Generating Excel document in memory on server. (Downloading begins only when Excel document completed)
First problem was solved through using of DataReader. Now generating of excel file begins just after user request becomes to webserver.
For solving second problem we need to generate Excel document on HttpResponse.OutputStream, but this stream is not Seekable and generation fails before begining.
Does anyone knows any workaround that can help to work with this problem?
Sample of my generating function:
public void GenerateSpreadSheetToStream(IDataReader dataReader, Stream outputStream)
{
var columnCaptions = FillColumnCaptionsFromDataReader(dataReader.GetSchemaTable());
//fails on next line with exception "Cannot open package because FileMode or FileAccess value is not valid for the stream."
using (var spreadsheetDocument = SpreadsheetDocument.Create(outputStream, SpreadsheetDocumentType.Workbook))
{
spreadsheetDocument.AddWorkbookPart();
var workSheetPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
OpenXmlWriter writer;
using (writer = OpenXmlWriter.Create(workSheetPart))
{
using (writer.Write(new Worksheet()))
{
using (writer.Write(new SheetData()))
{
using (writer.Write(w =>
w.WriteStartElement(new Row(), new[] {new OpenXmlAttribute("r", null, 1.ToString(CultureInfo.InvariantCulture))})))
{
var cells =
columnCaptions.Select(caption => new Cell()
{
CellValue = new CellValue(caption.Item2),
DataType = CellValues.String
});
foreach (var cell in cells)
{
writer.WriteElement(cell);
}
}
var i = 2;
while (dataReader.Read())
{
var oxa = new[] { new OpenXmlAttribute("r", null, i.ToString(CultureInfo.InvariantCulture)) };
using (writer.Write(w => w.WriteStartElement(new Row(), oxa)))
{
var cells =
columnCaptions.Select(
(c, j) =>
new Cell
{
CellValue = new CellValue(dataReader[c.Item1].ToString()),
DataType = CellValues.String,
CellReference = new StringValue(GetSymbolByCellNumber(j))
});
foreach (var cell in cells)
{
writer.WriteElement(cell);
}
}
i++;
}
}
}
}
using (writer = OpenXmlWriter.Create(spreadsheetDocument.WorkbookPart))
{
using (writer.Write(new Workbook()))
{
using (writer.Write(new Sheets()))
{
var sheet = new Sheet
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(workSheetPart),
SheetId = 1,
Name = SheetName
};
writer.WriteElement(sheet);
}
}
}
}
}
private static string GetSymbolByCellNumber(int number)
{
var r = number/26;
var s = (char) ((number%26) + 65);
return new string(s, r);
}
My FileStreamResultWithTransformation (for working with HttpResponse.OutputStream):
public class FileStreamResultWithTransformation : FileResult
{
private readonly Action<Stream> _action;
public FileStreamResultWithTransformation(Action<Stream> action, string contentType, string fileName) : base(contentType)
{
_action = action;
FileDownloadName = fileName;
}
protected override void WriteFile(HttpResponseBase response)
{
response.BufferOutput = false;
_action(response.OutputStream); ->> it fails there
}
}
StackTrace:
[IOException: Cannot open package because FileMode or FileAccess value
is not valid for the stream.]
System.IO.Packaging.Package.ValidateModeAndAccess(Stream s, FileMode
mode, FileAccess access) +784533
System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode,
FileAccess packageAccess, Boolean streaming) +89
System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode,
FileAccess packageAccess) +10
DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream
stream) +192
DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Create(Stream
stream, SpreadsheetDocumentType type, Boolean autoSave) +215
DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Create(Stream
stream, SpreadsheetDocumentType type) +44
-------.GenerateSpreadSheetToStream(IDataReader dataReader, Stream outputStream) in
d:\Work\Epsilon\development\Web\trunk\Sources\Epsilon.DocumentGenerator\XlsXGenerator.cs:119
It seems to me, that this problem cannot be solved. On finalization of writing, OpenXmlWriter seeks, read and write in different positions of stream and without this actions xlsx file is broken.
I think, there is something wrong in design of OpenXml library.
The problem is a little deeper. Xlsx file is zip archive and OpenXml internally uses the ZipArchive class. Each file in archive has a header, it is placed before the data. ZipArchive writes data to the stream, then returns to the beginning of the file and writes file's header. It uses the Stream.Seek method and HttpResponse.OutputStream cannot work this way.

Resources