2014年04月

C++ Changing from singly linked list to doubly linked list

I wrote this code using singly linked list. Now I want to change it to doubly linked list. I have tried few different things but everything messed up.
There are few useless lines in my code, but it is basically a singly linked list. What is the proper way to change it to a doubly linked list?



#pragma once

#include "Exhibit.h"

struct Node
{
Exhibit exhibit;
Node *next;
};

class Museum
{
private:
Node *p;
Node *d;
Exhibit *Ex;
int n;
int nmax;
public:
Museum();
~Museum();

void Start() { d = p; }
bool HasNext() { if (d == NULL) return false; return true; }
void Next() { d = d->next; }
Exhibit GetExhibit() const { return d->exhibit; }
int GetN() { return n; }

void Sort();
void AddExhibit(Exhibit e);
void RemoveExpensive(int p); //Removes elements more expensive than int p
};

Museum::Museum()
{
p = NULL;
d = NULL;

}

Museum::~Museum()
{
Node * element;
while (p)
{
element = p;
p = p->next;
delete element;
}
p = NULL;
d = NULL;

}

void Museum::AddExhibit(Exhibit e)
{
Node *element = new Node;

element->exhibit = e;
element->next = p;
p = element;
}

int CountExhibits(string CDfv)
{
string line;
int count = 0;
ifstream fd(CDfv.c_str());
while (!fd.eof())
{
getline(fd, line);
count++;
}
fd.close();
return count;
}

void Museum::Sort()
{
// traverse the entire list
for (Node *list = p; list->next != NULL; list = list->next)
{
// compare to the list ahead
for (Node *pass = list->next; pass != NULL; pass = pass->next)
{
// compare and swap
if (list->exhibit.Date() > pass->exhibit.Date())
{
// swap
Exhibit temp = list->exhibit;
list->exhibit = pass->exhibit;
pass->exhibit = temp;
}
}
}
}

void Museum::RemoveExpensive(int pr)
{
Node *pPre = NULL, *pDel = NULL;


pPre = p;
pDel = p->next;

/* traverse the list and check the value of each node */
while (pDel != NULL) {
if (pDel->exhibit.Price() > pr) {
/* Update the list */
pPre->next = pDel->next;
/* If it is the last node, update the tail */
if (pDel == d) {
d = pPre;
}
delete pDel; /* Here only remove the first node with the given value */
pDel = pPre;
/* break and return */
}
pPre = pDel;
pDel = pDel->next;
}


/* Check whether it is the head node?
if it is, delete and update the head node */
if (p->exhibit.Price() > pr) {
/* point to the node to be deleted */
pDel = p;
/* update */
p = pDel->next;
delete pDel;

}
}


Edit: My new AddExhibit() method:



void Museum::AddExhibit(Exhibit e)
{
Node *element = new Node;

element->exhibit = e;

if (p == NULL)
p = d = element;
else
{
p->prev = element;
element->next = p;
p = element;

}
//element->next = p;
//p = element;
}


Answers

I solved my problem with this AddExhibit() method:



void Museum::AddExhibit(Exhibit e)
{
Node *element = new Node;

element->exhibit = e;

element->next = p;
element->prev = NULL;
if (p == NULL)
d = element;
else
p->prev = element;
p = element;
}


I don't know if it is totally correct or not but it works fine for my case.





Getting an invalid object from a call to LyncClient.GetClient()

I'm having some trouble with an application that uses the Lync 2013 SDK. Here is the behavior that I am seeing:




If Lync is already running when I start my application, then a call to LyncClient.GetClient() will return a valid client object.
If Lync is not running when I start my application, then a call to LyncClient.GetClient() will throw ClientNotFoundException. I can handle the exception and start a timer to ping for the client to appear. Later, when I start Lync, LyncClient.GetClient() will return a valid client object.
If Lync exits while my application is running, then I can detect this situation in multiple ways and start a timer to ping for the client to come back.


So far so good, but here's where the problems come in:




If Lync goes away while my application is running, then subsequent calls to LyncClient.GetClient() seem to return a valid client object (even though Lync is not running), but attempts to call into this object throw InvalidCastException.
Even after Lync is restarted, subsequent calls to LyncClient.GetClient() still return an object that throws InvalidCastException when I try to access it.


The details of the exception are:




Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Uc.IClient'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{EE9F3E74-AC61-469E-80D6-E22BF4EEFF5C}' failed due to the following error: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA).




I tried the recommendation here: Troubleshooting Lync 2013 SDK development issues. It doesn't seem to make any difference. I continue to get an invalid client object for many minutes after Lync is running and signed-in again.



This doesn't happen every time. The problem seems to pretty consistently occur if Lync is already running when my application starts (i.e. the very first call to LyncClient.GetClient() succeeds.) On the other hand, everything seems to work fine across multiple restarts of Lync if I start Lync after my application is already running (i.e. the first attempt to GetClient() fails.)



Has anyone else seen this before? Any suggestions?





Update with an attempt at unloading the AppDomain

I tried to get the client object with this code, but the behavior is exactly the same:



public class LyncClientProvider
{
private AppDomain _domain = CreateDomain();

public LyncClient GetLyncClient()
{
if (_domain == null) CreateDomain();
var client = GetClient();
if (client != null && client.Capabilities != LyncClientCapabilityTypes.Invalid) return client;

// Reload AppDomain
if (_domain != null) AppDomain.Unload(_domain);
_domain = CreateDomain();
return GetClient();
}

private LyncClient GetClient()
{
if (_domain == null) return null;
return ((InternalProvider)
_domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName,
typeof (InternalProvider).FullName)).GetLyncClient();
}

private static AppDomain CreateDomain()
{
return AppDomain.CreateDomain("LyncClientCreator", null, new AppDomainSetup
{
ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
});
}

[Serializable]
private class InternalProvider
{
public LyncClient GetLyncClient()
{
try
{
return LyncClient.GetClient();
}
catch (Exception)
{
return null;
}
}
}
}


Answers

I am assuming you are being disconnected from the Lync server. The LyncClient.GetClient() method may still work because you have some lingering variables, but you won't be able to preform any Lync actions with it.



I think looking at the UI suppression stuff would help.
https://msdn.microsoft.com/en-us/library/office/hh345230%28v=office.14%29.aspx



Answers

"•If Lync goes away while my application is running, then subsequent calls to LyncClient.GetClient() seem to return a valid client object (even though Lync is not running), but attempts to call into this object throw InvalidCastException."



Can you elaborate what you mean by "If Lync goes away". Do you mean you have signed out of Lync or you have exited the Lync (i.e. no Lync process running)? If you have just signed out of the Lync LyncClient will not throw exception. You can listen to LyncClient.StateChanged event and check for clientStateChangedEventArgs.NewState event.



private void LyncClient_StateChanged(object sender, ClientStateChangedEventArgs e) {
switch (e.NewState) {
case ClientState.Invalid:
case ClientState.ShuttingDown:
this.IsLyncStarted = false;
this.IsLyncSignedIn = false;
break;
case ClientState.SignedOut:
case ClientState.SigningIn:
case ClientState.SigningOut
this.IsLyncStarted = true;
this.IsLyncSignedIn = false;
break;
case ClientState.SignedIn:
this.IsLyncStarted = true;
this.IsLyncSignedIn = true;
break;
}
if (!this.IsLyncStarted || !this.IsLyncSignedIn) {
// Do relevant operation
// Show error message to user - Lync is not present
}
}


When the user exits the Lync - I start the timer similar to your approach and try to Initialize Lync like below:



private void InitializeLync() {
try {
if (this.LyncClient == null || this.LyncClient.State == ClientState.Invalid) {
this.LyncClient = LyncClient.GetClient();

if (this.LyncClient != null) {
this.LyncClient.StateChanged += this.LyncClient_StateChanged;
}
}

} catch (Exception ex) {
// Show message to user that Lync is not started
}
}


This works for me. May be it is machine specific issue.





How to set Created pdf's location after generating PDF in html2pdf?

I have used html2pdf for generating pdf.
It works well.
But it creates files to root folder. I want to save all the pdf's to desired location.



So how to save create pdf to desired location?



Answers

You can use path in outout parameter like



$html2pdf->Output('/absolut/directory/path/to/file_xxxx.pdf', 'F');


EDIT:

be sure: the path is writeable by your service!





Run time errors in fortran program with LAPACK on Windows

I want to run a fortran program (GNU GCC fortran compiler) with LAPACK library on Windows platform. I followed the instructions outlined in on the webpage http://icl.cs.utk.edu/lapack-for-windows/lapack/ Build Instructions to create LAPACK and LAPACKE 3.5.0 dlls for Windows with MinGW I tried using method Configuring LAPACK in Eclipse-Photran for fortran compiler on Windows.



Compiling a program test1.f90 with cygwin goes fine, here is command:



gfortran test1.f90 -o test1 -L "C:\MinGW\lapack-3.5.0\bin" -llapack



I have lapack installed at "C:\MinGW\lapack-3.5.0", under lapack-3.5.0\, libs are in lib folder, dlls are in bin folder
"C:\MinGW\bin" is added to PATH variable


But I got errors,




Running with cygwin gives error error while loading shared libraries: ?: cannot open shared object file: No such file or directory
Running with Windows terminal gives error The program cannot start because liblapack.dll is missing from your computer. Try reinstalling the program to fix this problem,


When I checked "C:\MinGW\lapack-3.5.0\bin", liblapack.dll is there. Any idea what is happening here? Do I need to add the directory of library to the PATH variable? Thanks.





how can I see inside of the dictionary calling request.data using flask

I'm trying to get file and directory name by using javascript, flask and ajax. I use dictionary and put file and directory name(which is obtained from the user) in that dictionary. However, I cannot see them when I print in my python code.



my related js part is:



    var directory_name = $('#userInput').val();
directory_dict["directory"] = directory_name;

var form_data = new FormData($('#uploadform')[0]);
file_dict["file"] = form_data;

request_data["file"] = {};
request_data["directory"] = {};

request_data["file"] = file_dict;
request_data["directory"] = directory_dict;

var url = "http://" + location.host + "/uploadajax"
console.log('before file upload request');

var file_request = $.ajax({
type: 'POST',
url: url,
data: request_data,
processData: false,
contentType: false,
async: true,
dataType: 'json',
accepts: JSON,
});


I just want to see inside of the dictionary first. In order to do that, I use



     print request.data


However it prints:



     [object Object]


python part is:



    @app.route('/uploadajax', methods=['POST'])
def upldfile():
print request.data


I have used all of these



     request.POST.getlist
request.values.getlist
request.args
request.form
request.values
request.data["file"]


however, I got errors or ImmutableMultiDict([]) result. I know that I have got the file and directory name separately but I cannot see them in my dictionary in python code. Am I missing something?





↑このページのトップヘ