PostId
int64 4
11.8M
| PostCreationDate
stringlengths 19
19
| OwnerUserId
int64 1
1.57M
| OwnerCreationDate
stringlengths 10
19
| ReputationAtPostCreation
int64 -55
461k
| OwnerUndeletedAnswerCountAtPostTime
int64 0
21.5k
| Title
stringlengths 3
250
| BodyMarkdown
stringlengths 5
30k
⌀ | Tag1
stringlengths 1
25
⌀ | Tag2
stringlengths 1
25
⌀ | Tag3
stringlengths 1
25
⌀ | Tag4
stringlengths 1
25
⌀ | Tag5
stringlengths 1
25
⌀ | PostClosedDate
stringlengths 19
19
⌀ | OpenStatus
stringclasses 5
values | unified_texts
stringlengths 32
30.1k
| OpenStatus_id
int64 0
4
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,349,792 | 07/05/2012 17:51:58 | 1,504,797 | 07/05/2012 17:47:27 | 1 | 0 | How to extract title's webpage from a url using gwt? | How to take metadata like title of a webpage from a url?
I need also to create a preview of the webpage, how to do?
Thanks | java | url | gwt | null | null | null | open | How to extract title's webpage from a url using gwt?
===
How to take metadata like title of a webpage from a url?
I need also to create a preview of the webpage, how to do?
Thanks | 0 |
11,349,967 | 07/05/2012 18:02:13 | 688,953 | 04/02/2011 13:49:58 | 1,089 | 66 | Sorting Core Data by date typed as NSString | I get a bunch of dates from a server in YYYY-MM-DD NSString format which we immediately stick into core data for accessing. However, I need to do a sorted fetch request with a greater than date predicate. How can I say "date greater than X" when date is a string instead of a date object? | iphone | core-data | nsstring | nsdate | null | null | open | Sorting Core Data by date typed as NSString
===
I get a bunch of dates from a server in YYYY-MM-DD NSString format which we immediately stick into core data for accessing. However, I need to do a sorted fetch request with a greater than date predicate. How can I say "date greater than X" when date is a string instead of a date object? | 0 |
11,349,976 | 07/05/2012 18:02:32 | 1,481,274 | 06/25/2012 23:03:33 | 13 | 1 | Extracting the value of a hidden variable from a website using PHP cURL | I want to extract the variable of a hidden variable from a website like facebook.com.
How can i do this using cURL.
Thanks | php | curl | null | null | null | null | open | Extracting the value of a hidden variable from a website using PHP cURL
===
I want to extract the variable of a hidden variable from a website like facebook.com.
How can i do this using cURL.
Thanks | 0 |
11,401,394 | 07/09/2012 19:02:28 | 1,512,825 | 07/09/2012 18:32:09 | 1 | 0 | Omit the sub menus in url[Joomla 2.5 .htaccess SEF] | I'm creating a website with joomla 2.5.x, In that I'm using SEF. So that the url seems pretty OK... but the issue i have is,
i have menus with sub menus [up to two level Ex: Main menu item--> Sub Menu (A)-->Sub Menu(Sub Menu of menu A)], but the first, second level menu Items are just Text Separators.
Eg: http://my-domain.com/(Alias)Main-menu-item/(Alias)Sub-Menu-(A)/(Alias)Sub-Menu(Sub-of-menu-A)
the question is,
How to omit [(Alias)Main-menu-item/(Alias)Sub-Menu-(A)/] parts in the Url without effecting the other urls in .htaccess.
ultimately url must look like
http://my-domain.com/(Alias)Sub-Menu(Sub-of-menu-A)
Note: I have tried the SEF Components. | .htaccess | joomla | url-rewriting | null | null | null | open | Omit the sub menus in url[Joomla 2.5 .htaccess SEF]
===
I'm creating a website with joomla 2.5.x, In that I'm using SEF. So that the url seems pretty OK... but the issue i have is,
i have menus with sub menus [up to two level Ex: Main menu item--> Sub Menu (A)-->Sub Menu(Sub Menu of menu A)], but the first, second level menu Items are just Text Separators.
Eg: http://my-domain.com/(Alias)Main-menu-item/(Alias)Sub-Menu-(A)/(Alias)Sub-Menu(Sub-of-menu-A)
the question is,
How to omit [(Alias)Main-menu-item/(Alias)Sub-Menu-(A)/] parts in the Url without effecting the other urls in .htaccess.
ultimately url must look like
http://my-domain.com/(Alias)Sub-Menu(Sub-of-menu-A)
Note: I have tried the SEF Components. | 0 |
11,401,395 | 07/09/2012 19:02:37 | 772,922 | 05/27/2011 10:44:32 | 42 | 0 | LinkedBlockingQueue Issue with put operation | I will try to describe the issue I'm facing and back it up with some code samples.
I'm using LinkedBlockingQueue declared as follows:
private BlockingQueue<OutgoingMessage> outgoingMessageQueue = new LinkedBlockingQueue<OutgoingMessage>();
OutgoingMessage represents text message to be sent to the customer. It gets in the queue by web service call that prepares it, saves it to database and puts it the queue. Application is deployed on tomcat so this thread a thread from HTTP pool.
I created different thread to process the queue and to do the actual message sending. It runs indefinitely and calls take() method on queue like this:
public void processOutgoingMessageQueue() {
try {
OutgoingMessage outgoingMessage = outgoingMessageQueue.take();
logger.debug(MessageFormat.format("Took outgoing message with id = [{0}] from queue", outgoingMessage.getId()));
this.forwardToCommunicator(outgoingMessage);
}
catch (InterruptedException e) {
logger.fatal("Interupted while waiting to process outgoing messages ", e); }
catch (Exception e) {
exceptionHandler.handle(e);
}
}
Method processOutgoingMessageQueue() is called from thread.
This is functional in a way that messages are put in the queue and later sent regularly but the client side (side that invoked web service method) doesn't get the response immediately after the outgoing message is put in the queue but rather when the thread that takes it from queue finishes it processing. It looks like the thread from the tomcat's HTTP pool is waiting for other thread to finish message processing and then returns web service response to the client.
This results in bad user experience as user has to wait for complete process to finish before he can enqueue another message.
Here is a log that shows that message was put in the queue successfully:
[DEBUG] 2012-07-08 23:09:51,707 [http-8080-8] SimpleServiceCommunicatorImpl: Received sendMessage request from serviceId = [3], charginId = [3], text [some text]
[DEBUG] 2012-07-08 23:09:51,721 [http-8080-8] SimpleServiceCommunicatorImpl: Request verification succeeded, creating outgoing message.
[INFO ] 2012-07-08 23:09:51,738 [http-8080-8] SimpleMessageCreatorImpl: Created outgoing message with id = [1,366] and payment invoice with id = [1,323]
[INFO ] 2012-07-08 23:09:51,738 [http-8080-8] Core: Enqueued outgoing message with id = [1,366]
This is client side log that shows send message request being performed:
DEBUG 2012-07-08 23:09:51,702 CoreAdapter: Sending message with serviceId = [3], chargingId = [3], text = [some text]
INFO 2012-07-08 23:10:06,477 SimpleMessageSenderImpl: Created answer with core id = [1,366]
INFO 2012-07-08 23:10:06,477 SMSChatServiceImpl: Response message with result = 1366 sent to the customer
It shows that request returned after aprox 15 seconds from outgoing message was put in the queue, although there was no more work for the thread HTTP 8080-8 to perform.
Could this be a known tomcat or a LinkedBlockingQueue issue?
Does anyone have an idea? It more details are needed, I'll be glad to provide it.
| java | multithreading | tomcat | queue | blocking | null | open | LinkedBlockingQueue Issue with put operation
===
I will try to describe the issue I'm facing and back it up with some code samples.
I'm using LinkedBlockingQueue declared as follows:
private BlockingQueue<OutgoingMessage> outgoingMessageQueue = new LinkedBlockingQueue<OutgoingMessage>();
OutgoingMessage represents text message to be sent to the customer. It gets in the queue by web service call that prepares it, saves it to database and puts it the queue. Application is deployed on tomcat so this thread a thread from HTTP pool.
I created different thread to process the queue and to do the actual message sending. It runs indefinitely and calls take() method on queue like this:
public void processOutgoingMessageQueue() {
try {
OutgoingMessage outgoingMessage = outgoingMessageQueue.take();
logger.debug(MessageFormat.format("Took outgoing message with id = [{0}] from queue", outgoingMessage.getId()));
this.forwardToCommunicator(outgoingMessage);
}
catch (InterruptedException e) {
logger.fatal("Interupted while waiting to process outgoing messages ", e); }
catch (Exception e) {
exceptionHandler.handle(e);
}
}
Method processOutgoingMessageQueue() is called from thread.
This is functional in a way that messages are put in the queue and later sent regularly but the client side (side that invoked web service method) doesn't get the response immediately after the outgoing message is put in the queue but rather when the thread that takes it from queue finishes it processing. It looks like the thread from the tomcat's HTTP pool is waiting for other thread to finish message processing and then returns web service response to the client.
This results in bad user experience as user has to wait for complete process to finish before he can enqueue another message.
Here is a log that shows that message was put in the queue successfully:
[DEBUG] 2012-07-08 23:09:51,707 [http-8080-8] SimpleServiceCommunicatorImpl: Received sendMessage request from serviceId = [3], charginId = [3], text [some text]
[DEBUG] 2012-07-08 23:09:51,721 [http-8080-8] SimpleServiceCommunicatorImpl: Request verification succeeded, creating outgoing message.
[INFO ] 2012-07-08 23:09:51,738 [http-8080-8] SimpleMessageCreatorImpl: Created outgoing message with id = [1,366] and payment invoice with id = [1,323]
[INFO ] 2012-07-08 23:09:51,738 [http-8080-8] Core: Enqueued outgoing message with id = [1,366]
This is client side log that shows send message request being performed:
DEBUG 2012-07-08 23:09:51,702 CoreAdapter: Sending message with serviceId = [3], chargingId = [3], text = [some text]
INFO 2012-07-08 23:10:06,477 SimpleMessageSenderImpl: Created answer with core id = [1,366]
INFO 2012-07-08 23:10:06,477 SMSChatServiceImpl: Response message with result = 1366 sent to the customer
It shows that request returned after aprox 15 seconds from outgoing message was put in the queue, although there was no more work for the thread HTTP 8080-8 to perform.
Could this be a known tomcat or a LinkedBlockingQueue issue?
Does anyone have an idea? It more details are needed, I'll be glad to provide it.
| 0 |
11,401,398 | 07/09/2012 19:02:54 | 1,512,885 | 07/09/2012 18:56:06 | 1 | 0 | Javascript Process Kill with pass in name | I am looking to make a short javascript code that Kills a process running on my windows machine (i am developing the program on 7 but it must be run when in production on server 2003). I have started with the following code:
w = new ActiveXObject("WScript.Shell");
w.run("taskkill.exe /im iexpore.exe");
return true;
I need to make the process that is killed something that i pass in though. There are many different things to kill and i have another program that determines what one is killed. | javascript | windows | process | kill-process | null | null | open | Javascript Process Kill with pass in name
===
I am looking to make a short javascript code that Kills a process running on my windows machine (i am developing the program on 7 but it must be run when in production on server 2003). I have started with the following code:
w = new ActiveXObject("WScript.Shell");
w.run("taskkill.exe /im iexpore.exe");
return true;
I need to make the process that is killed something that i pass in though. There are many different things to kill and i have another program that determines what one is killed. | 0 |
11,401,143 | 07/09/2012 18:45:27 | 805,501 | 06/19/2011 16:00:07 | 36 | 0 | Python socket error - recv() function | I've been trying to code a simple chat server in Python, my code is as follows:
import socket
import select
port = 11222
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1024)
serverSocket.bind(('',port))
serverSocket.listen(5)
sockets=[serverSocket]
print 'Server is started on port' , port,'\n'
def acceptConn():
newsock, addr = serverSocket.accept()
sockets.append(newsock)
newsock.send('You are now connected to the chat server\n')
msg = 'Client joined',addr.__str__(),
broadcast(msg, newsock)
def broadcast(msg, sourceSocket):
for s in sockets:
if (s != serverSocket and s != sourceSocket):
s.send(msg)
print msg,
while True:
(sread, swrite, sexec)=select.select(sockets,[],[])
for s in sread:
if s == serverSocket:
acceptConn()
else:
msg=s.recv(100)
if msg.rstrip() == "quit":
host,port=socket.getpeername()
msg = 'Client left' , (host,port)
broadcast(msg,s)
s.close()
sockets.remove(s)
del s
else:
host,port=s.getpeername()
msg = s.recv(1024)
broadcast(msg,s)
continue
After running the server and connecting via telnet, the server reads single character and skips the next one. Example if I type Hello in telnet, server reads H l o.
Any help please ?! :) | python | sockets | python-2.7 | recv | python-sockets | null | open | Python socket error - recv() function
===
I've been trying to code a simple chat server in Python, my code is as follows:
import socket
import select
port = 11222
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1024)
serverSocket.bind(('',port))
serverSocket.listen(5)
sockets=[serverSocket]
print 'Server is started on port' , port,'\n'
def acceptConn():
newsock, addr = serverSocket.accept()
sockets.append(newsock)
newsock.send('You are now connected to the chat server\n')
msg = 'Client joined',addr.__str__(),
broadcast(msg, newsock)
def broadcast(msg, sourceSocket):
for s in sockets:
if (s != serverSocket and s != sourceSocket):
s.send(msg)
print msg,
while True:
(sread, swrite, sexec)=select.select(sockets,[],[])
for s in sread:
if s == serverSocket:
acceptConn()
else:
msg=s.recv(100)
if msg.rstrip() == "quit":
host,port=socket.getpeername()
msg = 'Client left' , (host,port)
broadcast(msg,s)
s.close()
sockets.remove(s)
del s
else:
host,port=s.getpeername()
msg = s.recv(1024)
broadcast(msg,s)
continue
After running the server and connecting via telnet, the server reads single character and skips the next one. Example if I type Hello in telnet, server reads H l o.
Any help please ?! :) | 0 |
11,401,401 | 07/09/2012 19:03:41 | 1,437,307 | 06/05/2012 12:04:17 | 1 | 1 | Restlet GAE Router Template matching | I'm using Restlet (2.1 rc4) on GAE and Android. On GAE, I'm using the following Router, which isn't working regarding the PatientServerResource:
public class Server extends Application {
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
//routes should be matched by uri_starts_with
router.setRoutingMode(Router.MODE_FIRST_MATCH);
router.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
//router.setDefaultMatchingQuery(false);
router.attach("/save", WrapperServerResource.class);
TemplateRoute route = router.attach("/query/{name}?{gdat}?{svnr}", PatientServerResource.class);
Map<String, Variable> routeVariables = route.getTemplate().getVariables();
routeVariables.put("name", new Variable(Variable.TYPE_URI_QUERY_PARAM));
routeVariables.put("gdat", new Variable(Variable.TYPE_URI_QUERY_PARAM));
routeVariables.put("svnr", new Variable(Variable.TYPE_URI_QUERY_PARAM));
router.attachDefault(StandardResource.class);
return router;
}
}
Client Code:
public class PatientFetcher {
private String name, gdat, svnr;
public PatientFetcher(String name, String gdat, String svnr) {
this.name = name;
this.gdat = gdat;
this.svnr = svnr;
}
public List<Patient> fetch(Context ctx) {
Engine.getInstance().getRegisteredConverters().add(new JacksonConverter());
Engine.getInstance().getRegisteredClients().clear();
Engine.getInstance().getRegisteredClients().add(new HttpClientHelper(null));
if(name == null && gdat == null && svnr == null) return null;
ClientResource cr = new ClientResource(DataUtil.getUriFetcher(ctx));
cr.setRequestEntityBuffering(true);
cr.addQueryParameter("name", name);
cr.addQueryParameter("gdat", gdat);
cr.addQueryParameter("svnr", svnr);
PatientResource resource = cr.wrap(PatientResource.class);
try {
JacksonRepresentation<PatientList> repPList = new JacksonRepresentation<PatientList>(resource.search(), PatientList.class);
StringWriter writer = new StringWriter();
repPList.write(writer);
writer.flush();
Log.i("PatientFetcher", "jackson json: "+writer.toString());
return repPList.getObject();
} catch (IOException e) {
Log.e("PatientFetcher", e.getMessage());
e.printStackTrace();
return null;
}
}
}
According to the GAE Log, the called URI (in this example svnr=1234, other fields are blank - but even if all fields are non-null, it isn't working) is `/query/?name=&gdat=&svnr=1234` which seems to be correct, but the Server's response (in `writer.toString()`) is the Default Route's `StandardResource.represent()` String, so I guess the issue is that Router does not match the calling URI to the PatientResource - what am I doing wrong?
There are no errors/warnings in the GAE log/android logcat except for a EOFException resulting from jackson not being able to deserialize the result string. The other route ("/save") is working fine.
(The `router.setDefaultMatchingQuery(false);` line does not seem to have any effect on the result, therefore it's commented out) | google-app-engine | restlet | router | null | null | null | open | Restlet GAE Router Template matching
===
I'm using Restlet (2.1 rc4) on GAE and Android. On GAE, I'm using the following Router, which isn't working regarding the PatientServerResource:
public class Server extends Application {
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
//routes should be matched by uri_starts_with
router.setRoutingMode(Router.MODE_FIRST_MATCH);
router.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
//router.setDefaultMatchingQuery(false);
router.attach("/save", WrapperServerResource.class);
TemplateRoute route = router.attach("/query/{name}?{gdat}?{svnr}", PatientServerResource.class);
Map<String, Variable> routeVariables = route.getTemplate().getVariables();
routeVariables.put("name", new Variable(Variable.TYPE_URI_QUERY_PARAM));
routeVariables.put("gdat", new Variable(Variable.TYPE_URI_QUERY_PARAM));
routeVariables.put("svnr", new Variable(Variable.TYPE_URI_QUERY_PARAM));
router.attachDefault(StandardResource.class);
return router;
}
}
Client Code:
public class PatientFetcher {
private String name, gdat, svnr;
public PatientFetcher(String name, String gdat, String svnr) {
this.name = name;
this.gdat = gdat;
this.svnr = svnr;
}
public List<Patient> fetch(Context ctx) {
Engine.getInstance().getRegisteredConverters().add(new JacksonConverter());
Engine.getInstance().getRegisteredClients().clear();
Engine.getInstance().getRegisteredClients().add(new HttpClientHelper(null));
if(name == null && gdat == null && svnr == null) return null;
ClientResource cr = new ClientResource(DataUtil.getUriFetcher(ctx));
cr.setRequestEntityBuffering(true);
cr.addQueryParameter("name", name);
cr.addQueryParameter("gdat", gdat);
cr.addQueryParameter("svnr", svnr);
PatientResource resource = cr.wrap(PatientResource.class);
try {
JacksonRepresentation<PatientList> repPList = new JacksonRepresentation<PatientList>(resource.search(), PatientList.class);
StringWriter writer = new StringWriter();
repPList.write(writer);
writer.flush();
Log.i("PatientFetcher", "jackson json: "+writer.toString());
return repPList.getObject();
} catch (IOException e) {
Log.e("PatientFetcher", e.getMessage());
e.printStackTrace();
return null;
}
}
}
According to the GAE Log, the called URI (in this example svnr=1234, other fields are blank - but even if all fields are non-null, it isn't working) is `/query/?name=&gdat=&svnr=1234` which seems to be correct, but the Server's response (in `writer.toString()`) is the Default Route's `StandardResource.represent()` String, so I guess the issue is that Router does not match the calling URI to the PatientResource - what am I doing wrong?
There are no errors/warnings in the GAE log/android logcat except for a EOFException resulting from jackson not being able to deserialize the result string. The other route ("/save") is working fine.
(The `router.setDefaultMatchingQuery(false);` line does not seem to have any effect on the result, therefore it's commented out) | 0 |
11,401,405 | 07/09/2012 19:04:03 | 1,512,882 | 07/09/2012 18:55:32 | 1 | 0 | not sending information with mail form? | i'm currently working on a site...
and i have encountered a error...
i'm using this mail form:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
// on submit...
$("#contactForm #submit").click(function() {
$("#error").hide();
//required:
//name
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
// email
var email = $("input#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
// web
var web = $("input#web").val();
if(web == ""){
$("#error").fadeIn().text("Web required");
$("input#web").focus();
return false;
}
// comments
var comments = $("#comments").val();
// send mail php
var sendMailUrl = $("#sendMailUrl").val();
//to, from & subject
var to = $("#to").val();
var from = $("#from").val();
var subject = $("#subject").val();
// data string
var dataString = 'name='+ name
+ '&email=' + email
+ '&web=' + web
+ '&comments=' + comments
+ '&to=' + to
+ '&from=' + from
+ '&subject=' + subject;
// ajax
$.ajax({
type:"POST",
url: sendMailUrl,
data: dataString,
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
return false;
});
and i have this on my page: to gather the information and forward it to ma email adress.
<!-- form -->
<form id="contactForm" action="#" method="post" />
<fieldset>
<p>
<label for="name">Naam</label>
<input name="name" id="name" type="text" class="form-poshytip" title="Enter your full name" />
</p>
<p>
<label for="email">Email</label>
<input name="email" id="email" type="text" class="form-poshytip" title="Enter your email address" />
</p>
<p>
<label for="comments">Bericht</label>
<textarea name="comments" id="comments" rows="5" cols="20" class="form-poshytip" title="Enter your comments"></textarea>
</p>
<!-- send mail configuration -->
<input type="hidden" value="[email protected]" name="to" id="to" />
<input type="hidden" value="Jebike EmailForm mail" name="subject" id="subject" />
<input type="hidden" value="send-mail.php" name="sendMailUrl" id="sendMailUrl" />
<!-- ENDS send mail configuration -->
<p><input type="button" value="Send" name="submit" id="submit" /> <span id="error" class="warning">Oeps, er is iets fout gegaan, probeer opnieuw.</span></p>
</fieldset>
</form>
<p id="sent-form-msg" class="success">Uw email is verzonden.</p>
<!-- ENDS form -->
But it isn't sending any emails. Can anybody help?
| jquery | html | forms | email | null | null | open | not sending information with mail form?
===
i'm currently working on a site...
and i have encountered a error...
i'm using this mail form:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
// on submit...
$("#contactForm #submit").click(function() {
$("#error").hide();
//required:
//name
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
// email
var email = $("input#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
// web
var web = $("input#web").val();
if(web == ""){
$("#error").fadeIn().text("Web required");
$("input#web").focus();
return false;
}
// comments
var comments = $("#comments").val();
// send mail php
var sendMailUrl = $("#sendMailUrl").val();
//to, from & subject
var to = $("#to").val();
var from = $("#from").val();
var subject = $("#subject").val();
// data string
var dataString = 'name='+ name
+ '&email=' + email
+ '&web=' + web
+ '&comments=' + comments
+ '&to=' + to
+ '&from=' + from
+ '&subject=' + subject;
// ajax
$.ajax({
type:"POST",
url: sendMailUrl,
data: dataString,
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
return false;
});
and i have this on my page: to gather the information and forward it to ma email adress.
<!-- form -->
<form id="contactForm" action="#" method="post" />
<fieldset>
<p>
<label for="name">Naam</label>
<input name="name" id="name" type="text" class="form-poshytip" title="Enter your full name" />
</p>
<p>
<label for="email">Email</label>
<input name="email" id="email" type="text" class="form-poshytip" title="Enter your email address" />
</p>
<p>
<label for="comments">Bericht</label>
<textarea name="comments" id="comments" rows="5" cols="20" class="form-poshytip" title="Enter your comments"></textarea>
</p>
<!-- send mail configuration -->
<input type="hidden" value="[email protected]" name="to" id="to" />
<input type="hidden" value="Jebike EmailForm mail" name="subject" id="subject" />
<input type="hidden" value="send-mail.php" name="sendMailUrl" id="sendMailUrl" />
<!-- ENDS send mail configuration -->
<p><input type="button" value="Send" name="submit" id="submit" /> <span id="error" class="warning">Oeps, er is iets fout gegaan, probeer opnieuw.</span></p>
</fieldset>
</form>
<p id="sent-form-msg" class="success">Uw email is verzonden.</p>
<!-- ENDS form -->
But it isn't sending any emails. Can anybody help?
| 0 |
11,401,407 | 07/09/2012 19:04:07 | 1,183,283 | 02/01/2012 17:09:07 | 33 | 0 | Joining multiple tables (Following/Activity) | I have 2 tables
**Following**
>id
>User_ID
>Following_user_ID
The User_ID is following the Following_user_ID
**Activity**
>A_ID
>User_ID
>Shared
(The User_ID column is the user that inserted the data into the tables.)
How would I build the query to select all of the activity rows where the currently logged in user is following the user in the User_ID column of Activity.
*EXAMPLE*
**Following**
>id = 1
>User_ID = 1
>Following_user_ID = 2
User 1 is following user 2
**Activity**
>A_ID = 1
>User_ID = 2
>Shared = Blah Blah
How can I make it so that user 1 (currently logged in) can see the activity of User 2 as user 1 is following user 2?
From the example above, user 1 should be able to see along the lines of "User 2 shared Blah Blah".
I have tried to explain this the best I can, have been trying to figure out the query but can't wrap my head around it.
| php | mysql | null | null | null | null | open | Joining multiple tables (Following/Activity)
===
I have 2 tables
**Following**
>id
>User_ID
>Following_user_ID
The User_ID is following the Following_user_ID
**Activity**
>A_ID
>User_ID
>Shared
(The User_ID column is the user that inserted the data into the tables.)
How would I build the query to select all of the activity rows where the currently logged in user is following the user in the User_ID column of Activity.
*EXAMPLE*
**Following**
>id = 1
>User_ID = 1
>Following_user_ID = 2
User 1 is following user 2
**Activity**
>A_ID = 1
>User_ID = 2
>Shared = Blah Blah
How can I make it so that user 1 (currently logged in) can see the activity of User 2 as user 1 is following user 2?
From the example above, user 1 should be able to see along the lines of "User 2 shared Blah Blah".
I have tried to explain this the best I can, have been trying to figure out the query but can't wrap my head around it.
| 0 |
11,401,409 | 07/09/2012 19:04:15 | 762,721 | 05/20/2011 12:25:51 | 182 | 7 | How to make text on a website appear handwritten, but unreadable | I have a 'guestbook' image on my webpage that I use as the login box. Keeping true to the theme, I display the names of each person who has logged in to read that particular article and list their names before the login boxes (trying to create the feel of an actual guestbook). Of course, some users may want to log in but not have their real name displayed, so I added a checkbox allowing them to mark their name for obfuscation.
I thought the smoothest way to integrate this, since there is some value to having the correct number of 'signatures' on the 'guestbook', would be to have normal names appear in a standard script font (such as Brush Script), then have the lines for the 'hidden' names have what looks like handwriting, but that isn't actually readable.
The only way I could think to do this would be to find an unreadable font, define it in the css for the browser to download, then apply it to the hidden names. For good measure I can replace the real names with a random selection of "John Doe", "Jane Doe", "Jayne Doe", etc in case anyone views the source. However, after an hour of searching I've been unable to locate a font that meets my criteria, and I'm wondering if there's some better way to handle this problem.
So I was hoping someone could either suggest a font that might work for my needs, or suggest a better solution. Thank you. | html | css | fonts | webfonts | null | null | open | How to make text on a website appear handwritten, but unreadable
===
I have a 'guestbook' image on my webpage that I use as the login box. Keeping true to the theme, I display the names of each person who has logged in to read that particular article and list their names before the login boxes (trying to create the feel of an actual guestbook). Of course, some users may want to log in but not have their real name displayed, so I added a checkbox allowing them to mark their name for obfuscation.
I thought the smoothest way to integrate this, since there is some value to having the correct number of 'signatures' on the 'guestbook', would be to have normal names appear in a standard script font (such as Brush Script), then have the lines for the 'hidden' names have what looks like handwriting, but that isn't actually readable.
The only way I could think to do this would be to find an unreadable font, define it in the css for the browser to download, then apply it to the hidden names. For good measure I can replace the real names with a random selection of "John Doe", "Jane Doe", "Jayne Doe", etc in case anyone views the source. However, after an hour of searching I've been unable to locate a font that meets my criteria, and I'm wondering if there's some better way to handle this problem.
So I was hoping someone could either suggest a font that might work for my needs, or suggest a better solution. Thank you. | 0 |
11,650,359 | 07/25/2012 13:03:49 | 1,275,092 | 03/16/2012 22:56:09 | 175 | 0 | PSN API Tutorial? | I have found a [Java API for the PlayStation Network](http://code.google.com/p/playstation-network/). I know the basics, but the website does not explain a lot about it. Has anyone used this before? Do you know of a good tutorial or starting place for it?
Thanks in advance :) | java | networking | playstation | playstation3 | null | 07/26/2012 01:15:40 | not constructive | PSN API Tutorial?
===
I have found a [Java API for the PlayStation Network](http://code.google.com/p/playstation-network/). I know the basics, but the website does not explain a lot about it. Has anyone used this before? Do you know of a good tutorial or starting place for it?
Thanks in advance :) | 4 |
11,650,577 | 07/25/2012 13:16:17 | 377,909 | 06/28/2010 09:40:26 | 217 | 17 | Block type drives me nuts | I have this code:
typedef void (^OutputBlockType) (void (^) (NSString*));
static OutputBlockType outputBlock;
+(void) logMessage:(NSString*) msg {
NSString* bla = @"bla";
outputBlock(bla);
}
Granted, that the original code is a bit more complex. Still.. Xcode (4.3) is not happy with this code and throws me an
> Passing 'NSString *__strong' to parameter of incompatible type 'void
> (^__strong)(NSString *__strong)';
message which, basically, tells me nothing at all. Does anyone have a clue as to what I'm doing wrong here? | objective-c | blocks | null | null | null | null | open | Block type drives me nuts
===
I have this code:
typedef void (^OutputBlockType) (void (^) (NSString*));
static OutputBlockType outputBlock;
+(void) logMessage:(NSString*) msg {
NSString* bla = @"bla";
outputBlock(bla);
}
Granted, that the original code is a bit more complex. Still.. Xcode (4.3) is not happy with this code and throws me an
> Passing 'NSString *__strong' to parameter of incompatible type 'void
> (^__strong)(NSString *__strong)';
message which, basically, tells me nothing at all. Does anyone have a clue as to what I'm doing wrong here? | 0 |
11,650,579 | 07/25/2012 13:16:19 | 379,264 | 06/29/2010 17:19:25 | 61 | 8 | Paypal API TransactionSearch Object Reference Not Set asp.net | Ok Paypal drives me nuts. I've taken their "sample code" directly from the latest area of xcom (or whatever they are calling it these days) and installed the DLL's just fine. I'm doing a simple TransactionSearch as follows:
protected void btnSearch_Click(object sender, EventArgs e)
{
GenerateCodeSOAP.TransactionSearch t = new GenerateCodeSOAP.TransactionSearch();
String mysearch = t.TransactionSearchnCode(Convert.ToDateTime(dtStart.Text), Convert.ToDateTime(dtEnd.Text), "05S08011830926906");
Response.Write("Results:<br/>" + mysearch);
lblStatus.Text = "Finished";
}
And here is the sample code I altered just slightly with my own API stuff in it:
public class TransactionSearch
{
public TransactionSearch()
{
}
public string TransactionSearchnCode(DateTime startDate, DateTime endDate,string transactionId)
{
CallerServices caller = new CallerServices();
IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
// Set up your API credentials, PayPal end point, and API version.
profile.APIUsername = "[removed for security]";
profile.APIPassword = "[removed for security]";
profile.APISignature = "[removed for security]";
profile.Subject = "[removed for security]";
profile.Environment = "live";
// Create the request object.
TransactionSearchRequestType concreteRequest = new TransactionSearchRequestType();
concreteRequest.Version="92.0";
// Add request-specific fields to the request.
concreteRequest.StartDate = startDate;
concreteRequest.EndDate = endDate.AddHours(23).AddMinutes(59).AddSeconds(59);
concreteRequest.EndDateSpecified = true;
//concreteRequest.TransactionID=transactionId;
// Execute the API operation and obtain the response.
TransactionSearchResponseType pp_response=new TransactionSearchResponseType();
pp_response= (TransactionSearchResponseType) caller.Call("TransactionSearch", concreteRequest);
return pp_response.Ack.ToString();
}
}
No matter what I try (you'll see I commented out the transactionid just to give me back something) I get a Object Reference Not Set error on this line:
pp_response= (TransactionSearchResponseType) caller.Call("TransactionSearch", concreteRequest);
I know it's just "sample code" but this seems like this should be pretty straight forward. I tried it via the sandbox and that clearly didn't work, so I have transactions in my own paypal account, so I setup the API credentials and it still doesn't work. | asp.net | api | paypal | null | null | null | open | Paypal API TransactionSearch Object Reference Not Set asp.net
===
Ok Paypal drives me nuts. I've taken their "sample code" directly from the latest area of xcom (or whatever they are calling it these days) and installed the DLL's just fine. I'm doing a simple TransactionSearch as follows:
protected void btnSearch_Click(object sender, EventArgs e)
{
GenerateCodeSOAP.TransactionSearch t = new GenerateCodeSOAP.TransactionSearch();
String mysearch = t.TransactionSearchnCode(Convert.ToDateTime(dtStart.Text), Convert.ToDateTime(dtEnd.Text), "05S08011830926906");
Response.Write("Results:<br/>" + mysearch);
lblStatus.Text = "Finished";
}
And here is the sample code I altered just slightly with my own API stuff in it:
public class TransactionSearch
{
public TransactionSearch()
{
}
public string TransactionSearchnCode(DateTime startDate, DateTime endDate,string transactionId)
{
CallerServices caller = new CallerServices();
IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
// Set up your API credentials, PayPal end point, and API version.
profile.APIUsername = "[removed for security]";
profile.APIPassword = "[removed for security]";
profile.APISignature = "[removed for security]";
profile.Subject = "[removed for security]";
profile.Environment = "live";
// Create the request object.
TransactionSearchRequestType concreteRequest = new TransactionSearchRequestType();
concreteRequest.Version="92.0";
// Add request-specific fields to the request.
concreteRequest.StartDate = startDate;
concreteRequest.EndDate = endDate.AddHours(23).AddMinutes(59).AddSeconds(59);
concreteRequest.EndDateSpecified = true;
//concreteRequest.TransactionID=transactionId;
// Execute the API operation and obtain the response.
TransactionSearchResponseType pp_response=new TransactionSearchResponseType();
pp_response= (TransactionSearchResponseType) caller.Call("TransactionSearch", concreteRequest);
return pp_response.Ack.ToString();
}
}
No matter what I try (you'll see I commented out the transactionid just to give me back something) I get a Object Reference Not Set error on this line:
pp_response= (TransactionSearchResponseType) caller.Call("TransactionSearch", concreteRequest);
I know it's just "sample code" but this seems like this should be pretty straight forward. I tried it via the sandbox and that clearly didn't work, so I have transactions in my own paypal account, so I setup the API credentials and it still doesn't work. | 0 |
11,650,580 | 07/25/2012 13:16:20 | 1,551,709 | 07/25/2012 13:06:51 | 1 | 0 | Oracle:Delete duplicate records in bulk | I have a table where there are 1220200 duplicate records present.
I'm using below query to delete duplicate records.
DELETE /*+ NO_CPU_COSTING */
FROM FCST f1
WHERE
ROWID >
(SELECT MIN (ROWID)
FROM FCST f2
WHERE
f1.DMDUNIT = f2.DMDUNIT
AND f1.DMDGROUP = f2.DMDGROUP
AND f1.LOC = f2.LOC
AND f1.STARTDATE = f2.STARTDATE
AND f1.TYPE = f2.TYPE
AND UPPER (f1.FCSTID) = UPPER (f2.FCSTID));
It's taking almost 2 minutes to delete these records. I tried bulk delete approach as well by loading duplicate data into cursor and deleting it in bulk but it is taking more time.
What is better approach to optimize this code? | oracle11g | null | null | null | null | null | open | Oracle:Delete duplicate records in bulk
===
I have a table where there are 1220200 duplicate records present.
I'm using below query to delete duplicate records.
DELETE /*+ NO_CPU_COSTING */
FROM FCST f1
WHERE
ROWID >
(SELECT MIN (ROWID)
FROM FCST f2
WHERE
f1.DMDUNIT = f2.DMDUNIT
AND f1.DMDGROUP = f2.DMDGROUP
AND f1.LOC = f2.LOC
AND f1.STARTDATE = f2.STARTDATE
AND f1.TYPE = f2.TYPE
AND UPPER (f1.FCSTID) = UPPER (f2.FCSTID));
It's taking almost 2 minutes to delete these records. I tried bulk delete approach as well by loading duplicate data into cursor and deleting it in bulk but it is taking more time.
What is better approach to optimize this code? | 0 |
11,650,581 | 07/25/2012 13:16:28 | 1,551,620 | 07/25/2012 12:38:15 | 1 | 0 | Python Twitter Not Registering in Eclipse | I am trying to import python-twitter on Eclipse with Python 2.7.3 and PyDev 2.5
I downloaded it as follows.
pip install twitter
Eclipse doesn't recognize it, instead saying:
Traceback (most recent call last):
File "/Users/Jen/Documents/workspace/drugs/src/marijuana.py", line 1, in <module>
import twitter as twitter
ImportError: No module named twitter
I have the same error when trying to import Matplotlib, Scipy, SimpleJSON and NLTK. In fact, the only module I can import is NumPy. So, I think the PyDev plugin for Eclipse might not know that these files were added to PYTHONPATH?
Any advice on how to proceed? | eclipse | python-2.7 | python-twitter | null | null | null | open | Python Twitter Not Registering in Eclipse
===
I am trying to import python-twitter on Eclipse with Python 2.7.3 and PyDev 2.5
I downloaded it as follows.
pip install twitter
Eclipse doesn't recognize it, instead saying:
Traceback (most recent call last):
File "/Users/Jen/Documents/workspace/drugs/src/marijuana.py", line 1, in <module>
import twitter as twitter
ImportError: No module named twitter
I have the same error when trying to import Matplotlib, Scipy, SimpleJSON and NLTK. In fact, the only module I can import is NumPy. So, I think the PyDev plugin for Eclipse might not know that these files were added to PYTHONPATH?
Any advice on how to proceed? | 0 |
11,650,583 | 07/25/2012 13:16:33 | 890,387 | 08/11/2011 17:04:33 | 35 | 2 | Casting Error when using function in PowerShell defined in C# DLL | I'm working on a project to integrate a custom made c# .DLL into powershell. However, I'm having problems
with casting the C# Objects into a form that PowerShell can understand which it cannot. I've searched google
like a million times and tried a few different things but none of them were succesfull.
The following error occurs when I'm calling SNC-getVlan with an array of objects:
**"Exception calling "printObject" with "1" argument(s): "Unable to cast object of type 'System.Management.Automation.PSObject' to type 'Objects.blablazzz.DC_Object'"**
I'm posting some small subsets of my code hoping you guys can see what I'm doing wrong.
Classes I'm using:
public class DC_Object
{
public string name = "undefined";
}
public class Cmdb_Host : DC_Object
{
//Lots of properties
}
public class Cmdb_Vlan : DC_Object
{
//Lots of properties
}
Function that prints the objects:
public static void printObject(Object[] objects)
{
foreach (Object o in objects)
{
string name = ((DC_Object)o).name; //I'm assuimg things go wrong in here.
The fromJSON function is the function that actually returns the object that is sent into printObject, not sure
if it matters but I'll post it anyways.
static public Object[] fromJSON(string input)
{
//Check the string to see to what object it should convert to
switch (input.Substring(0, 16))
{
//Reuest for a host (Host Table)
case "{\"u_cmdb_ci_host":
if (input[18] == '[') // We have an array
{
Container_Host c_host = JsonConvert.DeserializeObject<Container_Host>(input);
return c_host.u_cmdb_ci_host;
}
else // We have a single object
{
Container_Host_Single c_host = JsonConvert.DeserializeObject<Container_Host_Single>(input);
Container_Host h = new Container_Host();
h.u_cmdb_ci_host = new Cmdb_Host[1];
h.u_cmdb_ci_host[0] = c_host.u_cmdb_ci_host;
return h.u_cmdb_ci_host;
}
//Request for a VLAN (Network Table)
case "{\"cmdb_ci_ip_net":
Container_Vlan c_vlan = JsonConvert.DeserializeObject<Container_Vlan>(input);
return c_vlan.cmdb_ci_ip_network;
}
return null;
}
Powershell Module/Script:
#Loads in the custom DLL created for this specific project.
[Reflection.Assembly]::LoadFrom(“C:\Users\Joey\Documents\PSScripts\DataCollector\DataCollect.dll”)
# Creates a new Client object that handles all communication between the PowerShell module and the
# sncdb-worker at server side.
$client = new-object blablazzz.Sender;
[blablazzz.Config]::Configure("C:\Users\Joey\Documents\PSScripts\DataCollector\asp4all.ini")
$client.Connect();
# This functions returns a Host Machine (Virtual or Physical) in object notation to for easy post-processing
# in PowerShell.
Function SNC-GetHost($hostz = "blabla")
{
return $client.sendMessage([blablazzz.Parser]::getHost($hostz));
}
# This function returns VLAN information in object notation. This is a collection most of the time.
function SNC-GetVLAN($vlan = "TLS-TL2-CPH-TEST")
{
return $client.sendMessage([blablazzz.Parser]::getVlan($vlan));
}
Function printObject($hostz)
{
[blablazzz.Formatter]::printObject($hostz)
}
PowerShell commands (dll is already loaded):
PS C:\$variable = SNC-Get-VLAN
PS C:\printObject($variable)
I'll have to note that my printDebug function works fine when used on SNC-getHost but doesn't work on
SNC-getVlan, SNC-Get-Vlan returns an array of values while SNC-getHost only returns one value (it's still
in an array though but it doesn't look like PowerShell kept it in an array). | c# | dll | powershell | casting | null | null | open | Casting Error when using function in PowerShell defined in C# DLL
===
I'm working on a project to integrate a custom made c# .DLL into powershell. However, I'm having problems
with casting the C# Objects into a form that PowerShell can understand which it cannot. I've searched google
like a million times and tried a few different things but none of them were succesfull.
The following error occurs when I'm calling SNC-getVlan with an array of objects:
**"Exception calling "printObject" with "1" argument(s): "Unable to cast object of type 'System.Management.Automation.PSObject' to type 'Objects.blablazzz.DC_Object'"**
I'm posting some small subsets of my code hoping you guys can see what I'm doing wrong.
Classes I'm using:
public class DC_Object
{
public string name = "undefined";
}
public class Cmdb_Host : DC_Object
{
//Lots of properties
}
public class Cmdb_Vlan : DC_Object
{
//Lots of properties
}
Function that prints the objects:
public static void printObject(Object[] objects)
{
foreach (Object o in objects)
{
string name = ((DC_Object)o).name; //I'm assuimg things go wrong in here.
The fromJSON function is the function that actually returns the object that is sent into printObject, not sure
if it matters but I'll post it anyways.
static public Object[] fromJSON(string input)
{
//Check the string to see to what object it should convert to
switch (input.Substring(0, 16))
{
//Reuest for a host (Host Table)
case "{\"u_cmdb_ci_host":
if (input[18] == '[') // We have an array
{
Container_Host c_host = JsonConvert.DeserializeObject<Container_Host>(input);
return c_host.u_cmdb_ci_host;
}
else // We have a single object
{
Container_Host_Single c_host = JsonConvert.DeserializeObject<Container_Host_Single>(input);
Container_Host h = new Container_Host();
h.u_cmdb_ci_host = new Cmdb_Host[1];
h.u_cmdb_ci_host[0] = c_host.u_cmdb_ci_host;
return h.u_cmdb_ci_host;
}
//Request for a VLAN (Network Table)
case "{\"cmdb_ci_ip_net":
Container_Vlan c_vlan = JsonConvert.DeserializeObject<Container_Vlan>(input);
return c_vlan.cmdb_ci_ip_network;
}
return null;
}
Powershell Module/Script:
#Loads in the custom DLL created for this specific project.
[Reflection.Assembly]::LoadFrom(“C:\Users\Joey\Documents\PSScripts\DataCollector\DataCollect.dll”)
# Creates a new Client object that handles all communication between the PowerShell module and the
# sncdb-worker at server side.
$client = new-object blablazzz.Sender;
[blablazzz.Config]::Configure("C:\Users\Joey\Documents\PSScripts\DataCollector\asp4all.ini")
$client.Connect();
# This functions returns a Host Machine (Virtual or Physical) in object notation to for easy post-processing
# in PowerShell.
Function SNC-GetHost($hostz = "blabla")
{
return $client.sendMessage([blablazzz.Parser]::getHost($hostz));
}
# This function returns VLAN information in object notation. This is a collection most of the time.
function SNC-GetVLAN($vlan = "TLS-TL2-CPH-TEST")
{
return $client.sendMessage([blablazzz.Parser]::getVlan($vlan));
}
Function printObject($hostz)
{
[blablazzz.Formatter]::printObject($hostz)
}
PowerShell commands (dll is already loaded):
PS C:\$variable = SNC-Get-VLAN
PS C:\printObject($variable)
I'll have to note that my printDebug function works fine when used on SNC-getHost but doesn't work on
SNC-getVlan, SNC-Get-Vlan returns an array of values while SNC-getHost only returns one value (it's still
in an array though but it doesn't look like PowerShell kept it in an array). | 0 |
11,650,584 | 07/25/2012 13:16:40 | 1,530,898 | 07/17/2012 07:00:13 | 1 | 0 | export the xcode project to put another mac machine | Am doing iphone Apple Applcation. Am using Xcode 4.2. but my iphone is ios 5.1 version so i need to use xcode 4.3.3.Already i have developed the application in xcode 4.2. but now i need to run that application in xcode 4.3.3 so how to export the project from xcode 4.2?
Please guide me for this otherwise i need to develop application again. | ios | xcode | null | null | null | null | open | export the xcode project to put another mac machine
===
Am doing iphone Apple Applcation. Am using Xcode 4.2. but my iphone is ios 5.1 version so i need to use xcode 4.3.3.Already i have developed the application in xcode 4.2. but now i need to run that application in xcode 4.3.3 so how to export the project from xcode 4.2?
Please guide me for this otherwise i need to develop application again. | 0 |
11,650,362 | 07/25/2012 13:04:00 | 13,913 | 09/16/2008 21:17:03 | 32,937 | 628 | DateTime supported language for formatting? | DateTime let you format depending of the current culture. What are the culture supported by default?
The scenario I have in mind use `this.Date.Value.ToString("MMMM")` which will print "January" if the culture is set to english-us but will print "Janvier" if the culture is in french-ca. This formatting documentation can be found at [MSDN website][1] but doesn't give the scope of culture this one can translate.
I would like to know what languages are supported and if a language is not, what are my options?
[1]: http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx | c# | .net | .net-4.0 | globalization | culture | null | open | DateTime supported language for formatting?
===
DateTime let you format depending of the current culture. What are the culture supported by default?
The scenario I have in mind use `this.Date.Value.ToString("MMMM")` which will print "January" if the culture is set to english-us but will print "Janvier" if the culture is in french-ca. This formatting documentation can be found at [MSDN website][1] but doesn't give the scope of culture this one can translate.
I would like to know what languages are supported and if a language is not, what are my options?
[1]: http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx | 0 |
11,650,364 | 07/25/2012 13:04:02 | 1,551,675 | 07/25/2012 12:55:28 | 1 | 0 | Tool (similar to e.g. Firepath) for matching XPaths in multiple frames | I currently use Firepath to test my XPaths. Firepath gives matches from the currently focused frame only. Is there a similar tool that can give me all matches in all frames on the page? | xpath | firebug | frames | null | null | null | open | Tool (similar to e.g. Firepath) for matching XPaths in multiple frames
===
I currently use Firepath to test my XPaths. Firepath gives matches from the currently focused frame only. Is there a similar tool that can give me all matches in all frames on the page? | 0 |
11,650,365 | 07/25/2012 13:04:07 | 1,551,655 | 07/25/2012 12:51:42 | 1 | 0 | JQUERY:Popup should always visible on scroll of page | Issue : I have a web page, whic contain one normal div popup(popup #1) on this popup i have one button, onclick of this button i am opening one jquery dialog(popup #2).
Now the scenario is i am opening the popup #2 on top of popup #1(for popup#1 i am using table-layout:fixed property to ensure it will be visible on scroll of the web page).For popup #2 i tried position : fixed and absolute property to maintain this visible on scroll of the web page, but it is not working.
Please help me in resolving the issue | jquery | .net | null | null | null | null | open | JQUERY:Popup should always visible on scroll of page
===
Issue : I have a web page, whic contain one normal div popup(popup #1) on this popup i have one button, onclick of this button i am opening one jquery dialog(popup #2).
Now the scenario is i am opening the popup #2 on top of popup #1(for popup#1 i am using table-layout:fixed property to ensure it will be visible on scroll of the web page).For popup #2 i tried position : fixed and absolute property to maintain this visible on scroll of the web page, but it is not working.
Please help me in resolving the issue | 0 |
11,650,587 | 07/25/2012 13:16:41 | 1,551,706 | 07/25/2012 13:04:50 | 1 | 0 | Fetching rougly 7Mb of data from SQL server 2008 R2 to a client takes around 5 seconds. Why is it so slow, is it normal? | Fetching rougly 7Mb of data from SQL server 2008 R2 to a client takes around 5 seconds. The machine is relatively powerful AMD 12 Core, 64Gb RAM, Windows Server 2008, 2 10Gbit cards.
Running the select on the server is even slower, then from client.
Here is a small reproducer:
--create test table for reproducer
CREATE TABLE [dbo].[Test_Speed](
[ED] [datetime] NULL
) ON [PRIMARY]
--fill test table with data, insert took 3:51 mins
declare @r int
set @r = 1
while (@r < 830000)
begin
insert into [CDB_ODS].[dbo].[Test_Speed] select getdate()
set @r = @r+1
end
--select all records, roughly 7Mb. 4 secs if run on the client, 5 secs on the server (1.4Mb sec)
select ed from [dbo].[Test_Speed]
/*
SELECT on CLIENT
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
Table 'Test_Speed'. Scan count 1, logical reads 1833, physical reads 0, read-ahead reads 0,
lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
SQL Server Execution Times:
CPU time = 281 ms, elapsed time = 4020 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
--- SELECT on SERVER
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
(829999 row(s) affected)
Table 'Test_Speed'. Scan count 1, logical reads 1833, physical reads 0, read-ahead reads 0,
lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
SQL Server Execution Times:
CPU time = 328 ms, elapsed time = 5369 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
*/ | sql | performance | select | null | null | null | open | Fetching rougly 7Mb of data from SQL server 2008 R2 to a client takes around 5 seconds. Why is it so slow, is it normal?
===
Fetching rougly 7Mb of data from SQL server 2008 R2 to a client takes around 5 seconds. The machine is relatively powerful AMD 12 Core, 64Gb RAM, Windows Server 2008, 2 10Gbit cards.
Running the select on the server is even slower, then from client.
Here is a small reproducer:
--create test table for reproducer
CREATE TABLE [dbo].[Test_Speed](
[ED] [datetime] NULL
) ON [PRIMARY]
--fill test table with data, insert took 3:51 mins
declare @r int
set @r = 1
while (@r < 830000)
begin
insert into [CDB_ODS].[dbo].[Test_Speed] select getdate()
set @r = @r+1
end
--select all records, roughly 7Mb. 4 secs if run on the client, 5 secs on the server (1.4Mb sec)
select ed from [dbo].[Test_Speed]
/*
SELECT on CLIENT
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
Table 'Test_Speed'. Scan count 1, logical reads 1833, physical reads 0, read-ahead reads 0,
lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
SQL Server Execution Times:
CPU time = 281 ms, elapsed time = 4020 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
--- SELECT on SERVER
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
(829999 row(s) affected)
Table 'Test_Speed'. Scan count 1, logical reads 1833, physical reads 0, read-ahead reads 0,
lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
SQL Server Execution Times:
CPU time = 328 ms, elapsed time = 5369 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
*/ | 0 |
11,650,588 | 07/25/2012 13:16:44 | 516,146 | 11/22/2010 13:23:08 | 622 | 18 | Tracking phone position with Android | I am working on an app that uses the phone's position. But, not just the position, but how far it is from a certain starting point. Since I'm working with small distances(not more than a meter), I cannot use GPS. Basically, what I want to do is very similar to a wireless mouse using an android phone, but I have no idea what data to use from the phone's sensors for this, and how to adapt it to any screen resolution in order to move the cursor accordingly. I thought about calibrating both the cursor and the phone at the middle of the screen, but I'm not sure how to go from there.
Thanks for reading. | android | cursor-position | motion-detection | null | null | null | open | Tracking phone position with Android
===
I am working on an app that uses the phone's position. But, not just the position, but how far it is from a certain starting point. Since I'm working with small distances(not more than a meter), I cannot use GPS. Basically, what I want to do is very similar to a wireless mouse using an android phone, but I have no idea what data to use from the phone's sensors for this, and how to adapt it to any screen resolution in order to move the cursor accordingly. I thought about calibrating both the cursor and the phone at the middle of the screen, but I'm not sure how to go from there.
Thanks for reading. | 0 |
11,650,592 | 07/25/2012 13:16:58 | 1,078,982 | 12/03/2011 12:52:19 | 81 | 5 | how to use production database on local? | I have downloaded Magento database from the production environment to use on local. Now while installation when I try to use that database . i get caught into an indefinate loop. what change do I have to make in the database to make it work fine on local, so that I can use the content. I am using wamp on local.
Production environment has multiple websites. so every region has it's own website. there are 5 websites. Please suggest something I really need to use the content like cms pages blocks customer groups etc. Thanks in advance. | magento | null | null | null | null | null | open | how to use production database on local?
===
I have downloaded Magento database from the production environment to use on local. Now while installation when I try to use that database . i get caught into an indefinate loop. what change do I have to make in the database to make it work fine on local, so that I can use the content. I am using wamp on local.
Production environment has multiple websites. so every region has it's own website. there are 5 websites. Please suggest something I really need to use the content like cms pages blocks customer groups etc. Thanks in advance. | 0 |
11,471,922 | 07/13/2012 13:54:47 | 1,399,459 | 05/16/2012 19:12:17 | 18 | 1 | Php Xpath - How to get two information in a child node | How can I get the following information in xpath?
Text 01 - link_1.com
Text 02 - link_2.com
$page = '
<div class="news">
<div class="content">
<div>
<span class="title">Text 01</span>
<span class="link">link_1.com</span>
</div>
</div>
<div class="content">
<div>
<span class="title">Text 02</span>
<span class="link">link_2.com</span>
</div>
</div>
</div>';
@$this->dom->loadHTML($page);
$xpath = new DOMXPath($this->dom);
// perform step #1
$childElements = $xpath->query("//*[@class='content']");
$lista = '';
foreach ($childElements as $child) {
// perform step #2
$textChildren = $xpath->query("//*[@class='title']", $child);
foreach ($textChildren as $n) {
echo $n->nodeValue.'<br>';
}
$linkChildren = $xpath->query("//*[@class='link']", $child);
foreach ($linkChildren as $n) {
echo $n->nodeValue.'<br>';
}
}
My result is returning
Text 01
Text 02
link_1.com
link_2.com
Text 01
Text 02
link_1.com
link_2.com
| php | xpath | null | null | null | null | open | Php Xpath - How to get two information in a child node
===
How can I get the following information in xpath?
Text 01 - link_1.com
Text 02 - link_2.com
$page = '
<div class="news">
<div class="content">
<div>
<span class="title">Text 01</span>
<span class="link">link_1.com</span>
</div>
</div>
<div class="content">
<div>
<span class="title">Text 02</span>
<span class="link">link_2.com</span>
</div>
</div>
</div>';
@$this->dom->loadHTML($page);
$xpath = new DOMXPath($this->dom);
// perform step #1
$childElements = $xpath->query("//*[@class='content']");
$lista = '';
foreach ($childElements as $child) {
// perform step #2
$textChildren = $xpath->query("//*[@class='title']", $child);
foreach ($textChildren as $n) {
echo $n->nodeValue.'<br>';
}
$linkChildren = $xpath->query("//*[@class='link']", $child);
foreach ($linkChildren as $n) {
echo $n->nodeValue.'<br>';
}
}
My result is returning
Text 01
Text 02
link_1.com
link_2.com
Text 01
Text 02
link_1.com
link_2.com
| 0 |
11,471,925 | 07/13/2012 13:55:06 | 536,212 | 04/21/2010 13:05:18 | 26 | 0 | Add more devices to iOS Developer account | In our office we are using developer account to register devices, As you all know using developer account we can add only 100 devices per year, we have already used 90 of it. we just have 10 devices more and we have 6 more months for renewal date. can you anyone guide me, whether i should buy a new developer account or is there any possible to add more devices into my current account? Any help much appreciated.
Thanks!
With Regards,
P. Arun Ganesh | iphone | ios | null | null | null | null | open | Add more devices to iOS Developer account
===
In our office we are using developer account to register devices, As you all know using developer account we can add only 100 devices per year, we have already used 90 of it. we just have 10 devices more and we have 6 more months for renewal date. can you anyone guide me, whether i should buy a new developer account or is there any possible to add more devices into my current account? Any help much appreciated.
Thanks!
With Regards,
P. Arun Ganesh | 0 |
11,471,640 | 07/13/2012 13:39:58 | 847,575 | 07/16/2011 07:38:21 | 280 | 55 | set custom font through xml | how can i set a font, whose ttf resides in my `assets` folder through xml?
I know [how to do that programmatically][1] but how can you do that via xml? Thanks in advance.
[1]: http://stackoverflow.com/questions/5694163/custom-font-on-android | android | xml | fonts | null | null | null | open | set custom font through xml
===
how can i set a font, whose ttf resides in my `assets` folder through xml?
I know [how to do that programmatically][1] but how can you do that via xml? Thanks in advance.
[1]: http://stackoverflow.com/questions/5694163/custom-font-on-android | 0 |
11,471,641 | 07/13/2012 13:40:00 | 1,177,811 | 01/30/2012 10:15:37 | 8 | 1 | MySQL / PHP Joining tables without always having common column | I can't find any answers on my question and probably it's because I don't know what I should be looking for.
The problem I have is that I want to join 2 tables **with** a common indicator but include records where the common indicator also doesnt exist..
Maybe I'm making no sense, but I'll try to explain in code below
Table1
id | name
1 | John
2 | Michael
3 | Anna
4 | Sue
Table2
id | surname
1 | Doe
2 | Anderson
So I would like a query that outputs/binds the tables like so:
table1.id | table1.name | table2.id | table2.surname
1 | John | 1 | Doe
2 | Michael | 2 | Anderson
3 | Anna | NULL | NULL
4 | Sue | NULL | NULL
So, merge where there is data, and dont merge where this is no data (or add NULL value).
The table2 will always have less data than table1, so table1 could be used as a bone.
vlookup does this perfectly in excel, returns N/A where the value is not found
I know how to achieve this with PHP but I'm trying to speed up my code, when working with records well above the 50k I don't want to single query every row for another table column.
I've tried the WHERE table1.id=table2.id, but it only joins them if table2.id exists, I've also tried the JOIN ON function, but it does the same.
Please help | mysql | table | join | multiple | null | null | open | MySQL / PHP Joining tables without always having common column
===
I can't find any answers on my question and probably it's because I don't know what I should be looking for.
The problem I have is that I want to join 2 tables **with** a common indicator but include records where the common indicator also doesnt exist..
Maybe I'm making no sense, but I'll try to explain in code below
Table1
id | name
1 | John
2 | Michael
3 | Anna
4 | Sue
Table2
id | surname
1 | Doe
2 | Anderson
So I would like a query that outputs/binds the tables like so:
table1.id | table1.name | table2.id | table2.surname
1 | John | 1 | Doe
2 | Michael | 2 | Anderson
3 | Anna | NULL | NULL
4 | Sue | NULL | NULL
So, merge where there is data, and dont merge where this is no data (or add NULL value).
The table2 will always have less data than table1, so table1 could be used as a bone.
vlookup does this perfectly in excel, returns N/A where the value is not found
I know how to achieve this with PHP but I'm trying to speed up my code, when working with records well above the 50k I don't want to single query every row for another table column.
I've tried the WHERE table1.id=table2.id, but it only joins them if table2.id exists, I've also tried the JOIN ON function, but it does the same.
Please help | 0 |
6,755,485 | 07/19/2011 23:50:09 | 478,478 | 10/17/2010 11:23:21 | 683 | 23 | WPF ContextMenu CommandParamater binding? | I am trying to bind the command paramater of my context menu item to another element on the form, however no matter what I try the command paramater is always null.
Can someone please show me how to correctly bind the command paramater of my context menu item?
What I have:
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Files}">
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Rename Folder" Command="{Binding Path=ToggleControlVisability}" CommandTarget="{Binding ElementName=FolderEditor}" CommandParameter="{Binding ElementName=FolderEditor}"></MenuItem>
</ContextMenu>
</Grid.ContextMenu>
<Label Content="{Binding Path=FolderName}"></Label>
<StackPanel Name="FolderEditor" Orientation="Horizontal" Visibility="Hidden">
<TextBox Text="{Binding Path=FolderName}"></TextBox>
</StackPanel>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
Thanks,
Alex. | .net | wpf | xaml | .net-4.0 | binding | null | open | WPF ContextMenu CommandParamater binding?
===
I am trying to bind the command paramater of my context menu item to another element on the form, however no matter what I try the command paramater is always null.
Can someone please show me how to correctly bind the command paramater of my context menu item?
What I have:
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Files}">
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Rename Folder" Command="{Binding Path=ToggleControlVisability}" CommandTarget="{Binding ElementName=FolderEditor}" CommandParameter="{Binding ElementName=FolderEditor}"></MenuItem>
</ContextMenu>
</Grid.ContextMenu>
<Label Content="{Binding Path=FolderName}"></Label>
<StackPanel Name="FolderEditor" Orientation="Horizontal" Visibility="Hidden">
<TextBox Text="{Binding Path=FolderName}"></TextBox>
</StackPanel>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
Thanks,
Alex. | 0 |
11,471,932 | 07/13/2012 13:55:28 | 273,767 | 02/15/2010 19:40:33 | 15,934 | 342 | transform_primary() and collate_byname() | To give context of what I'm talking about, the following program correctly prints `true` when compiled with clang++/libc++
#include <iostream>
#include <regex>
int main()
{
std::locale::global(std::locale("en_US.UTF-8"));
std::wstring str = L"AÀÁÂÃÄÅaàáâãäå";
std::wregex re(L"[[=a=]]*", std::regex::basic);
std::cout << std::boolalpha << std::regex_match(str, re) << '\n';
}
however, I can't quite understand the description of `std::regex_traits::transform_primary()` in the standard (through which `[=a=]` is handled). To quote 28.7[re.traits]/7:
>if `typeid(use_facet<collate<charT> >) == typeid(collate_byname<charT>)` and the
form of the sort key returned by `collate_byname<charT>::transform(first, last)` is known and can be converted into a primary sort key then returns that key, otherwise returns an empty string.
The [original proposal][1] explains that the standard `regex_traits::transform_primary()` can only work if the `collate` facet in the imbued locale was not replaced by the user (that's the only way it can know how to convert the result of `collate::transform()` to the equivalence key).
My question is, how is the `typeid` comparison in the standard supposed to ensure that? Does it imply that all system-supplied facets pulled out of locales with `use_facet` have `_byname` as their true dynamic types?
[1]: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1429.htm | c++ | c++11 | locale | regex-traits | null | null | open | transform_primary() and collate_byname()
===
To give context of what I'm talking about, the following program correctly prints `true` when compiled with clang++/libc++
#include <iostream>
#include <regex>
int main()
{
std::locale::global(std::locale("en_US.UTF-8"));
std::wstring str = L"AÀÁÂÃÄÅaàáâãäå";
std::wregex re(L"[[=a=]]*", std::regex::basic);
std::cout << std::boolalpha << std::regex_match(str, re) << '\n';
}
however, I can't quite understand the description of `std::regex_traits::transform_primary()` in the standard (through which `[=a=]` is handled). To quote 28.7[re.traits]/7:
>if `typeid(use_facet<collate<charT> >) == typeid(collate_byname<charT>)` and the
form of the sort key returned by `collate_byname<charT>::transform(first, last)` is known and can be converted into a primary sort key then returns that key, otherwise returns an empty string.
The [original proposal][1] explains that the standard `regex_traits::transform_primary()` can only work if the `collate` facet in the imbued locale was not replaced by the user (that's the only way it can know how to convert the result of `collate::transform()` to the equivalence key).
My question is, how is the `typeid` comparison in the standard supposed to ensure that? Does it imply that all system-supplied facets pulled out of locales with `use_facet` have `_byname` as their true dynamic types?
[1]: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1429.htm | 0 |
11,471,937 | 07/13/2012 13:55:44 | 149,358 | 08/02/2009 18:42:46 | 1,588 | 87 | Portable Library Service Reference | I created a WCF service and a portable class library. I added a service reference to the service from the library. I noticed that it only generated async methods. After further inspection, some options are disabled in the create service reference dialog advanced options. Options such as the access level( defaults to public ), and "Allow generation of asynchronous operations"
Is this a limitation in a portable class library? | wcf | portable-class-library | null | null | null | null | open | Portable Library Service Reference
===
I created a WCF service and a portable class library. I added a service reference to the service from the library. I noticed that it only generated async methods. After further inspection, some options are disabled in the create service reference dialog advanced options. Options such as the access level( defaults to public ), and "Allow generation of asynchronous operations"
Is this a limitation in a portable class library? | 0 |
11,471,938 | 07/13/2012 13:55:46 | 1,027,207 | 11/03/2011 08:16:14 | 9 | 0 | Access denide while getting process time | List<string> ul = new List<string>();
List<Int32> ul2 = new List<Int32>();
List<DateTime> ul3 = new List<DateTime>();
Process[] procs = Process.GetProcesses();
foreach (Process proc in procs)
{
ul.Add(proc.ProcessName);
ul2.Add(proc.Id);
ul3.Add(proc.StartTime);//Error line
}
Can any one explain what's wrong with the above lines? when i try to get process start time, i can't get it also pop up a message "Access Denide" while program running. | c# | null | null | null | null | null | open | Access denide while getting process time
===
List<string> ul = new List<string>();
List<Int32> ul2 = new List<Int32>();
List<DateTime> ul3 = new List<DateTime>();
Process[] procs = Process.GetProcesses();
foreach (Process proc in procs)
{
ul.Add(proc.ProcessName);
ul2.Add(proc.Id);
ul3.Add(proc.StartTime);//Error line
}
Can any one explain what's wrong with the above lines? when i try to get process start time, i can't get it also pop up a message "Access Denide" while program running. | 0 |
11,567,721 | 07/19/2012 19:12:40 | 1,484,391 | 06/27/2012 02:40:07 | 10 | 0 | Change background color of jtable column heads | I have a table with four columns, and I would like each column head to be a different color. I only want the column head to have color, not the rest of the cells in the column. I tried using the DefaultTableCellRenderer, but it made every cell red except for the column heads. What could I change in my code(below) to indivdually assign a color to each column head?
class CustomRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, 3, 3);
c.setBackground(new java.awt.Color(255,72,72));
return c;
}
}
table.setDefaultRenderer(Object.class, new CustomRenderer());
| java | table | colors | columns | jtable | null | open | Change background color of jtable column heads
===
I have a table with four columns, and I would like each column head to be a different color. I only want the column head to have color, not the rest of the cells in the column. I tried using the DefaultTableCellRenderer, but it made every cell red except for the column heads. What could I change in my code(below) to indivdually assign a color to each column head?
class CustomRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, 3, 3);
c.setBackground(new java.awt.Color(255,72,72));
return c;
}
}
table.setDefaultRenderer(Object.class, new CustomRenderer());
| 0 |
11,567,723 | 07/19/2012 19:12:46 | 379,008 | 06/29/2010 12:49:08 | 3,000 | 61 | How to add a list to a View Model MVC | I'm using MVC 3 wiht View Model, in my case I have a View Model that should display a list of items and also a form for inserting some input.
I have problem in my View because I'n not able to associate the Form for inserting the data with the view model, could you tell me what I'm doing wrong? thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using TestGuestBook.Models;
namespace TestGuestBook.ViewModel
{
public class ListAddCommentsViewModel
{
public int CommentId { get; set; }
[Required]
public string Nominative { get; set; }
[Email]
public string Email { get; set; }
[Required]
public string Content { get; set; }
public List<Comment> CommentItems { get; set; }
}
}
View
@model IEnumerable<TestGuestBook.ViewModel.ListAddCommentsViewModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>ListAddCommentsViewModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CommentId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CommentId)
@Html.ValidationMessageFor(model => model.CommentId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Nominative)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Nominative)
@Html.ValidationMessageFor(model => model.Nominative)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Content)
@Html.ValidationMessageFor(model => model.Content)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
CommentId
</th>
<th>
Nominative
</th>
<th>
Email
</th>
<th>
Content
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.CommentId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Nominative)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.Content)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
| asp.net-mvc | c#-4.0 | viewmodel | null | null | null | open | How to add a list to a View Model MVC
===
I'm using MVC 3 wiht View Model, in my case I have a View Model that should display a list of items and also a form for inserting some input.
I have problem in my View because I'n not able to associate the Form for inserting the data with the view model, could you tell me what I'm doing wrong? thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using TestGuestBook.Models;
namespace TestGuestBook.ViewModel
{
public class ListAddCommentsViewModel
{
public int CommentId { get; set; }
[Required]
public string Nominative { get; set; }
[Email]
public string Email { get; set; }
[Required]
public string Content { get; set; }
public List<Comment> CommentItems { get; set; }
}
}
View
@model IEnumerable<TestGuestBook.ViewModel.ListAddCommentsViewModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>ListAddCommentsViewModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CommentId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CommentId)
@Html.ValidationMessageFor(model => model.CommentId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Nominative)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Nominative)
@Html.ValidationMessageFor(model => model.Nominative)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Content)
@Html.ValidationMessageFor(model => model.Content)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
CommentId
</th>
<th>
Nominative
</th>
<th>
Email
</th>
<th>
Content
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.CommentId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Nominative)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.Content)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
| 0 |
11,567,725 | 07/19/2012 19:12:47 | 1,534,311 | 07/18/2012 09:33:21 | 16 | 0 | Php singup form validation | I have this simple form on submit it will be redirected to submit.php, if there are errors it shows error messages on submit.php .Now what I want that the error messages will be shown back to form page.
<html>
<head>
<? require_once('lib.php'); ?>
</head>
<body>
<form name="my-form" id="my-form" method="post" action="submit.php">
Your name:
<input name="name" value="" size="30" maxlength="255" />
Your email:
<input name="email" value="" size="30" maxlength="255" />
Your favourite color:
<select name="fav_color">
<option value="">-select please-</option>
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Blue">Blue</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
Your comment:
<textarea name="comment" rows="6" cols="35"></textarea>
<input type="submit" value="Submit" />
</form>
</body>
</html>
<?php
require_once('lib.php');
function getErrors($postData,$rules){
$errors = array();
// validate each existing input
foreach($postData as $name => $value){
//if rule not found, skip loop iteration
if(!isset($rules[$name])){
continue;
}
//convert special characters to HTML entities
$fieldName = htmlspecialchars($name);
$rule = $rules[$name];
//check required values
if(isset($rule['required']) && $rule['required'] && !$value){
$errors[] = 'Field '.$fieldName.' is required.';
}
//check field's minimum length
if(isset($rule['minlength']) && strlen($value) < $rule['minlength']){
$errors[] = $fieldName.' should be at least '.$rule['minlength'].' characters length.';
}
//verify email address
if(isset($rule['email']) && $rule['email'] && !filter_var($value,FILTER_VALIDATE_EMAIL)){
$errors[] = $fieldName.' must be valid email address.';
}
$rules[$name]['found'] = true;
}
//check for missing inputs
foreach($rules as $name => $values){
if(!isset($values['found']) && isset($values['required']) && $values['required']){
$errors[] = 'Field '.htmlspecialchars($name).' is required.';
}
}
return $errors;
}
$errors = getErrors($_POST,$validation_rules);
if(!count($errors)){
echo 'Your form has no errors.';
}
else{
echo '<strong>Errors found in form:</strong><ul><li>';
echo join('</li><li>',$errors);
echo '</li></ul><p>Correct your errors and try again.</p>';
}
?>
As this php code display the error messages on same page. I want to display that error messages back on the form.php page. Does anyone help me to do so.. | php | form-validation | php-form-processing | null | null | null | open | Php singup form validation
===
I have this simple form on submit it will be redirected to submit.php, if there are errors it shows error messages on submit.php .Now what I want that the error messages will be shown back to form page.
<html>
<head>
<? require_once('lib.php'); ?>
</head>
<body>
<form name="my-form" id="my-form" method="post" action="submit.php">
Your name:
<input name="name" value="" size="30" maxlength="255" />
Your email:
<input name="email" value="" size="30" maxlength="255" />
Your favourite color:
<select name="fav_color">
<option value="">-select please-</option>
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Blue">Blue</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
Your comment:
<textarea name="comment" rows="6" cols="35"></textarea>
<input type="submit" value="Submit" />
</form>
</body>
</html>
<?php
require_once('lib.php');
function getErrors($postData,$rules){
$errors = array();
// validate each existing input
foreach($postData as $name => $value){
//if rule not found, skip loop iteration
if(!isset($rules[$name])){
continue;
}
//convert special characters to HTML entities
$fieldName = htmlspecialchars($name);
$rule = $rules[$name];
//check required values
if(isset($rule['required']) && $rule['required'] && !$value){
$errors[] = 'Field '.$fieldName.' is required.';
}
//check field's minimum length
if(isset($rule['minlength']) && strlen($value) < $rule['minlength']){
$errors[] = $fieldName.' should be at least '.$rule['minlength'].' characters length.';
}
//verify email address
if(isset($rule['email']) && $rule['email'] && !filter_var($value,FILTER_VALIDATE_EMAIL)){
$errors[] = $fieldName.' must be valid email address.';
}
$rules[$name]['found'] = true;
}
//check for missing inputs
foreach($rules as $name => $values){
if(!isset($values['found']) && isset($values['required']) && $values['required']){
$errors[] = 'Field '.htmlspecialchars($name).' is required.';
}
}
return $errors;
}
$errors = getErrors($_POST,$validation_rules);
if(!count($errors)){
echo 'Your form has no errors.';
}
else{
echo '<strong>Errors found in form:</strong><ul><li>';
echo join('</li><li>',$errors);
echo '</li></ul><p>Correct your errors and try again.</p>';
}
?>
As this php code display the error messages on same page. I want to display that error messages back on the form.php page. Does anyone help me to do so.. | 0 |
11,567,732 | 07/19/2012 19:13:47 | 223,367 | 12/02/2009 23:52:01 | 4,681 | 24 | Devise is logging out users after a password change | I am using devise and when a user changes a password the site logs them out. I read online that adding the sign_in will do the trick but not working and the user gets logged out when a password change. Here is my code
if @user.errors[:base].empty? and @user.update_attributes(params[:user])
sign_in(current_user, :bypass => true)
flash[:success] = "User account has been successfully updated"
redirect_to edit_user_path(params[:site_id], @user)
else
render :action => :edit, :status => :unprocessable_entity
end
I was assuming that this would work but regardless of what i do i still get logged out....anything missing or maybe one devise setting is off...any help would be appreciated | ruby-on-rails | ruby | ruby-on-rails-3 | devise | null | null | open | Devise is logging out users after a password change
===
I am using devise and when a user changes a password the site logs them out. I read online that adding the sign_in will do the trick but not working and the user gets logged out when a password change. Here is my code
if @user.errors[:base].empty? and @user.update_attributes(params[:user])
sign_in(current_user, :bypass => true)
flash[:success] = "User account has been successfully updated"
redirect_to edit_user_path(params[:site_id], @user)
else
render :action => :edit, :status => :unprocessable_entity
end
I was assuming that this would work but regardless of what i do i still get logged out....anything missing or maybe one devise setting is off...any help would be appreciated | 0 |
11,514,038 | 07/16/2012 23:25:48 | 1,437,824 | 06/05/2012 16:07:00 | 17 | 2 | HttpHostConnectException: Connection refused Android | I am trying to connect via HttpPost and send a username and password to a website and then receive a string from that website. I have tried various methods that have worked for me in the past but now when I send the username and password identifiers the app times out for as long as 4 minutes and then spits out the following exception:
07-16 16:32:32.897: W/System.err(632): Unable to connect to the server
07-16 16:32:32.907: W/System.err(632): org.apache.http.conn.HttpHostConnectException: Connection to http://devdashboard.company refused
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-16 16:32:32.927: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-16 16:32:32.927: W/System.err(632): at callisto.fm.android.dashboard.app.HttpHelperAndroid.sendToHttp(HttpHelperAndroid.java:66)
07-16 16:32:32.927: W/System.err(632): at callisto.fm.android.dashboard.app.DashboardAppActivity.goToDashboard(DashboardAppActivity.java:62)
07-16 16:32:32.927: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 16:32:32.937: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 16:32:32.937: W/System.err(632): at android.view.View$1.onClick(View.java:3039)
07-16 16:32:32.947: W/System.err(632): at android.view.View.performClick(View.java:3511)
07-16 16:32:32.947: W/System.err(632): at android.view.View$PerformClick.run(View.java:14105)
07-16 16:32:32.947: W/System.err(632): at android.os.Handler.handleCallback(Handler.java:605)
07-16 16:32:32.957: W/System.err(632): at android.os.Handler.dispatchMessage(Handler.java:92)
07-16 16:32:32.957: W/System.err(632): at android.os.Looper.loop(Looper.java:137)
07-16 16:32:32.967: W/System.err(632): at android.app.ActivityThread.main(ActivityThread.java:4424)
07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 16:32:32.977: W/System.err(632): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-16 16:32:32.987: W/System.err(632): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-16 16:32:32.987: W/System.err(632): at dalvik.system.NativeStart.main(Native Method)
07-16 16:32:32.987: W/System.err(632): Caused by: java.net.ConnectException: failed to connect to /50.19.240.232 (port 80): connect failed: ETIMEDOUT (Connection timed out)
07-16 16:32:32.997: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:114)
07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
07-16 16:32:33.007: W/System.err(632): at java.net.Socket.connect(Socket.java:842)
07-16 16:32:33.007: W/System.err(632): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
07-16 16:32:33.017: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
07-16 16:32:33.017: W/System.err(632): ... 22 more
07-16 16:32:33.027: W/System.err(632): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
07-16 16:32:33.047: W/System.err(632): at libcore.io.Posix.connect(Native Method)
07-16 16:32:33.047: W/System.err(632): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
07-16 16:32:33.047: W/System.err(632): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
07-16 16:32:33.057: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:112)
07-1
6 16:32:33.057: W/System.err(632): ... 27 more
Internet permission IS enabled in my XML manifest file
My current implementation goes like this:
String LOGIN = "[email protected]";
String PASSWORD ="password1";
//JSONObject to send the username and pw
JSONObject json = new JSONObject();
//put the path in the JSONArray object
JSONArray vect = new JSONArray();
vect.put("Callisto Android Library");
vect.put("Rocket Ship");
int duration = 50;
try {
json.put("email", LOGIN);
json.put("password", PASSWORD);
json.put("json", "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "ABOUT TO SEND:" + json.toString());
JSONObject inJson = HttpHelperAndroid.sendToHttp(json, "http://devdashboard.company/login");
if(inJson != null)
{
Log.d(TAG, "RECIEVED the JSON:" + inJson.toString());
}
else
Log.d(TAG, "THE RESPONSE WAS NULL");
}
And the HttpHelperAndroid class looks like so:
public class HttpHelperAndroid
{
private static final String TAG = "HttpHelperAndroid";//TAG for the LogCat(debugging)
private static boolean responseSuccessful = true;
/**
* sends the JSONObject parameter to the desired URL parameter and gets the response
*
* @param url the URL to which the JSONObject should be sent
* @param jsonObjOut the JSONObject that is to be sent
* @return the response from the server as a JSONObject
*/
public static JSONObject sendToHttp(JSONObject jsonObjOut, String url) {
responseSuccessful = true;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(url);
//convert the JSONObject to a string
StringEntity se;
//set our StringEntity to the JSONObject as a string
se = new StringEntity(jsonObjOut.toString());
// Set HTTP params
httpRequest.setEntity(se);
httpRequest.setHeader("Accept", "application/json");
httpRequest.setHeader("Content-type", "application/json");
httpRequest.setHeader("Accept-Encoding", "gzip"); //for gzip compression
//get the current time
long oldTime = System.currentTimeMillis();
HttpResponse response = null;
try
{
//execute the http request and get the response
response = (HttpResponse) httpClient.execute(httpRequest);
}
catch(HttpHostConnectException e)
{
System.err.println("Unable to connect to the server");
e.printStackTrace();
responseSuccessful = false;
}
//only continue executing if we got a response from the server
if(responseSuccessful)
{
//print how long the response took to the LogCat if it's on
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-oldTime) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream in = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}
// convert content stream to a String
String resultString= streamToString(in);
//close the stream
in.close();
// convert the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
//take a peak at the JSONObject we got back if the LogCat is on
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
//return the JSONObject we got back from the server
return jsonObjRecv;
}
}
}
//catch any exception that was thrown
catch (Exception e)
{
//Print the exception
e.printStackTrace();
}
return null;
}
private static String streamToString(InputStream is)
{
//create a new BufferedReader for the input stream
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//create a new StringBuilder to append the lines
StringBuilder sb = new StringBuilder();
//initialize an empty string
String line = null;
try
{
//iterate as long as there is still lines to be read
while ((line = reader.readLine()) != null)
{
//append the line and a newline character to our StringBuilder
sb.append(line + "\n");
}
}
//catch an IOException and print it
catch (IOException e) {
e.printStackTrace();
}
//close the stream when we're done
finally
{
try
{
is.close();
}
//catch and print an exception if it's thrown
catch (IOException e)
{
e.printStackTrace();
}
}
//return the stream converted to a string
return sb.toString();
}
}
And here is my XML just for kicks:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="callisto.fm.android.dashboard.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="@drawable/company_android_ico"
android:label="@string/app_name" >
<activity
android:name=".DashboardAppActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I have used the HttpHelper class in past projects and it has worked for me, in addition I tried to implement this using nameValuePairs:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", "[email protected]"));
nameValuePairs.add(new BasicNameValuePair("password", "password1"));
nameValuePairs.add(new BasicNameValuePair("json", "true"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
And this yielded the same result.
Could this somehow be a certificate thing? or perhaps something to do with a corrupt XML file( I tried remaking the project and the xml file) http://stackoverflow.com/q/9469060/1437824
Or maybe some sort of Android hosts file issue?
I'm open to any suggestions!
I have examined this from a lot of angles and I'm happy to provide any other information that would be helpful! I really appreciate your time!
| android | json | https | http-post | null | null | open | HttpHostConnectException: Connection refused Android
===
I am trying to connect via HttpPost and send a username and password to a website and then receive a string from that website. I have tried various methods that have worked for me in the past but now when I send the username and password identifiers the app times out for as long as 4 minutes and then spits out the following exception:
07-16 16:32:32.897: W/System.err(632): Unable to connect to the server
07-16 16:32:32.907: W/System.err(632): org.apache.http.conn.HttpHostConnectException: Connection to http://devdashboard.company refused
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-16 16:32:32.927: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-16 16:32:32.927: W/System.err(632): at callisto.fm.android.dashboard.app.HttpHelperAndroid.sendToHttp(HttpHelperAndroid.java:66)
07-16 16:32:32.927: W/System.err(632): at callisto.fm.android.dashboard.app.DashboardAppActivity.goToDashboard(DashboardAppActivity.java:62)
07-16 16:32:32.927: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 16:32:32.937: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 16:32:32.937: W/System.err(632): at android.view.View$1.onClick(View.java:3039)
07-16 16:32:32.947: W/System.err(632): at android.view.View.performClick(View.java:3511)
07-16 16:32:32.947: W/System.err(632): at android.view.View$PerformClick.run(View.java:14105)
07-16 16:32:32.947: W/System.err(632): at android.os.Handler.handleCallback(Handler.java:605)
07-16 16:32:32.957: W/System.err(632): at android.os.Handler.dispatchMessage(Handler.java:92)
07-16 16:32:32.957: W/System.err(632): at android.os.Looper.loop(Looper.java:137)
07-16 16:32:32.967: W/System.err(632): at android.app.ActivityThread.main(ActivityThread.java:4424)
07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 16:32:32.977: W/System.err(632): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-16 16:32:32.987: W/System.err(632): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-16 16:32:32.987: W/System.err(632): at dalvik.system.NativeStart.main(Native Method)
07-16 16:32:32.987: W/System.err(632): Caused by: java.net.ConnectException: failed to connect to /50.19.240.232 (port 80): connect failed: ETIMEDOUT (Connection timed out)
07-16 16:32:32.997: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:114)
07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
07-16 16:32:33.007: W/System.err(632): at java.net.Socket.connect(Socket.java:842)
07-16 16:32:33.007: W/System.err(632): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
07-16 16:32:33.017: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
07-16 16:32:33.017: W/System.err(632): ... 22 more
07-16 16:32:33.027: W/System.err(632): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
07-16 16:32:33.047: W/System.err(632): at libcore.io.Posix.connect(Native Method)
07-16 16:32:33.047: W/System.err(632): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
07-16 16:32:33.047: W/System.err(632): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
07-16 16:32:33.057: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:112)
07-1
6 16:32:33.057: W/System.err(632): ... 27 more
Internet permission IS enabled in my XML manifest file
My current implementation goes like this:
String LOGIN = "[email protected]";
String PASSWORD ="password1";
//JSONObject to send the username and pw
JSONObject json = new JSONObject();
//put the path in the JSONArray object
JSONArray vect = new JSONArray();
vect.put("Callisto Android Library");
vect.put("Rocket Ship");
int duration = 50;
try {
json.put("email", LOGIN);
json.put("password", PASSWORD);
json.put("json", "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "ABOUT TO SEND:" + json.toString());
JSONObject inJson = HttpHelperAndroid.sendToHttp(json, "http://devdashboard.company/login");
if(inJson != null)
{
Log.d(TAG, "RECIEVED the JSON:" + inJson.toString());
}
else
Log.d(TAG, "THE RESPONSE WAS NULL");
}
And the HttpHelperAndroid class looks like so:
public class HttpHelperAndroid
{
private static final String TAG = "HttpHelperAndroid";//TAG for the LogCat(debugging)
private static boolean responseSuccessful = true;
/**
* sends the JSONObject parameter to the desired URL parameter and gets the response
*
* @param url the URL to which the JSONObject should be sent
* @param jsonObjOut the JSONObject that is to be sent
* @return the response from the server as a JSONObject
*/
public static JSONObject sendToHttp(JSONObject jsonObjOut, String url) {
responseSuccessful = true;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(url);
//convert the JSONObject to a string
StringEntity se;
//set our StringEntity to the JSONObject as a string
se = new StringEntity(jsonObjOut.toString());
// Set HTTP params
httpRequest.setEntity(se);
httpRequest.setHeader("Accept", "application/json");
httpRequest.setHeader("Content-type", "application/json");
httpRequest.setHeader("Accept-Encoding", "gzip"); //for gzip compression
//get the current time
long oldTime = System.currentTimeMillis();
HttpResponse response = null;
try
{
//execute the http request and get the response
response = (HttpResponse) httpClient.execute(httpRequest);
}
catch(HttpHostConnectException e)
{
System.err.println("Unable to connect to the server");
e.printStackTrace();
responseSuccessful = false;
}
//only continue executing if we got a response from the server
if(responseSuccessful)
{
//print how long the response took to the LogCat if it's on
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-oldTime) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream in = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}
// convert content stream to a String
String resultString= streamToString(in);
//close the stream
in.close();
// convert the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
//take a peak at the JSONObject we got back if the LogCat is on
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
//return the JSONObject we got back from the server
return jsonObjRecv;
}
}
}
//catch any exception that was thrown
catch (Exception e)
{
//Print the exception
e.printStackTrace();
}
return null;
}
private static String streamToString(InputStream is)
{
//create a new BufferedReader for the input stream
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//create a new StringBuilder to append the lines
StringBuilder sb = new StringBuilder();
//initialize an empty string
String line = null;
try
{
//iterate as long as there is still lines to be read
while ((line = reader.readLine()) != null)
{
//append the line and a newline character to our StringBuilder
sb.append(line + "\n");
}
}
//catch an IOException and print it
catch (IOException e) {
e.printStackTrace();
}
//close the stream when we're done
finally
{
try
{
is.close();
}
//catch and print an exception if it's thrown
catch (IOException e)
{
e.printStackTrace();
}
}
//return the stream converted to a string
return sb.toString();
}
}
And here is my XML just for kicks:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="callisto.fm.android.dashboard.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="@drawable/company_android_ico"
android:label="@string/app_name" >
<activity
android:name=".DashboardAppActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I have used the HttpHelper class in past projects and it has worked for me, in addition I tried to implement this using nameValuePairs:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", "[email protected]"));
nameValuePairs.add(new BasicNameValuePair("password", "password1"));
nameValuePairs.add(new BasicNameValuePair("json", "true"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
And this yielded the same result.
Could this somehow be a certificate thing? or perhaps something to do with a corrupt XML file( I tried remaking the project and the xml file) http://stackoverflow.com/q/9469060/1437824
Or maybe some sort of Android hosts file issue?
I'm open to any suggestions!
I have examined this from a lot of angles and I'm happy to provide any other information that would be helpful! I really appreciate your time!
| 0 |
11,514,045 | 07/16/2012 23:26:38 | 74,134 | 03/05/2009 08:26:47 | 381 | 15 | Windows Phone 7 ListPicker InvalidCastException | I have a problem building a simple crud form in WP7. I have spent a lot of time to display an Enum into a listpicker an now I see InvalidCastException when trying to bind to the (IsolatedStorage) object.
public class Bath {
public string Colour { get; set; }
public WaterType WaterType { get; set; }
}
public enum WaterType {
Hot,
Cold
}
The enum is bound to a ListPicker, but as there is not enum.GetValues() in WP7 this is not a simple task.
I have a simple type class...
public class TypeList
{
public string Name { get; set; }
}
And in my viewmodel, I have ObservableCollection and mock the values from the enum...
private ObservableCollection<TypeList> _WaterTypeList;
public ObservableCollection<TypeList> WaterTypeList
{
get { return _WaterTypeList; }
set
{
_WaterTypeList= value;
NotifyPropertyChanged("WaterTypeList");
}
}
public void LoadCollectionsFromDatabase()
{
ObservableCollection<TypeList> wTypeList = new ObservableCollection<WaterTypeList>();
wTypeList.Add(new TypeList{ Name = WaterType.Hot.ToString() });
wTypeList.Add(new TypeList{ Name = WaterType.Income.ToString() });
WaterTypeList = new ObservableCollection<TypeList>(wTypeList);
}
Finally, my xaml contains the listbox...
<toolkit:ListPicker
x:Name="BathTypeListPicker"
ItemsSource="{Binding WaterTypeList}"
DisplayMemberPath="Name">
</toolkit:ListPicker>
Im not sure if the above is best practise and indeed if the above is part of the problem but the above does give me a populated ListPicker.
Finally, when the form is submitted the cast causes a InvalidCastException.
private void SaveAppBarButton_Click(object sender, EventArgs e)
{
var xyz = WaterTypeList.SelectedItem; // type AppName.Model.typeList
Bath b = new Bath
{
Colour = ColourTextBox.Text ?? "Black",
WaterType = (WaterType)WaterTypeListPicker.SelectedItem
};
App.ViewModel.EditBath(b);
NavigationService.Navigate(new Uri("/Somewhere.xaml", UriKind.Relative));
}
}
Has anyone faced a simlar problem and can offer advice. I see that my opions are to concentrate on casting something meaningful from the ListPicker or should I rethink the way that the ListPicker is populated?
| c# | silverlight | windows-phone-7 | data-binding | null | null | open | Windows Phone 7 ListPicker InvalidCastException
===
I have a problem building a simple crud form in WP7. I have spent a lot of time to display an Enum into a listpicker an now I see InvalidCastException when trying to bind to the (IsolatedStorage) object.
public class Bath {
public string Colour { get; set; }
public WaterType WaterType { get; set; }
}
public enum WaterType {
Hot,
Cold
}
The enum is bound to a ListPicker, but as there is not enum.GetValues() in WP7 this is not a simple task.
I have a simple type class...
public class TypeList
{
public string Name { get; set; }
}
And in my viewmodel, I have ObservableCollection and mock the values from the enum...
private ObservableCollection<TypeList> _WaterTypeList;
public ObservableCollection<TypeList> WaterTypeList
{
get { return _WaterTypeList; }
set
{
_WaterTypeList= value;
NotifyPropertyChanged("WaterTypeList");
}
}
public void LoadCollectionsFromDatabase()
{
ObservableCollection<TypeList> wTypeList = new ObservableCollection<WaterTypeList>();
wTypeList.Add(new TypeList{ Name = WaterType.Hot.ToString() });
wTypeList.Add(new TypeList{ Name = WaterType.Income.ToString() });
WaterTypeList = new ObservableCollection<TypeList>(wTypeList);
}
Finally, my xaml contains the listbox...
<toolkit:ListPicker
x:Name="BathTypeListPicker"
ItemsSource="{Binding WaterTypeList}"
DisplayMemberPath="Name">
</toolkit:ListPicker>
Im not sure if the above is best practise and indeed if the above is part of the problem but the above does give me a populated ListPicker.
Finally, when the form is submitted the cast causes a InvalidCastException.
private void SaveAppBarButton_Click(object sender, EventArgs e)
{
var xyz = WaterTypeList.SelectedItem; // type AppName.Model.typeList
Bath b = new Bath
{
Colour = ColourTextBox.Text ?? "Black",
WaterType = (WaterType)WaterTypeListPicker.SelectedItem
};
App.ViewModel.EditBath(b);
NavigationService.Navigate(new Uri("/Somewhere.xaml", UriKind.Relative));
}
}
Has anyone faced a simlar problem and can offer advice. I see that my opions are to concentrate on casting something meaningful from the ListPicker or should I rethink the way that the ListPicker is populated?
| 0 |
11,514,059 | 07/16/2012 23:28:32 | 1,530,187 | 07/16/2012 22:11:27 | 1 | 0 | Brainstorm: Disable Vendor Web Application Functionality on Public PC | The **question/problem**: *From a single installation of a web site, what's the "best" (good, reasonable) "backdoor" way to flex functionality for a specific PC*?
We have a vendor-supplied web application that, among other things, allows online payments--intended for use by "the public" over the intERnet, from outside our building and network. We have PC's that are intentionally accessible to the public throughout our organization. We would like to make this vendor application available from these public PC's; however, to protect ourselves from users inadvertently exposing their personal, financial information to subsequent users, we would like to disable the payment functionality of the application--using the same installation of the site as is used for external access (if that's not too crazy).
My first stab at accomplishing this has been to create a cookie on these public PC's. I have added javascript to the vendor .aspx that hides the "Pay" button if the cookie exists.
This works and feels relatively reliable, assuming we control the browser installation and prohibit public users from deleting cookies. However, since there are many other ways cookies could get inadvertently deleted (i.e., maintenance, upgrades, etc.), I am not entirely comfortable with this approach.
I am struggling to come up with another, more reasonable and reliable solution, so I am just sort of throwing this out here for suggestions, brainstorming. The solution will likely have to be a sort-of backdoor something similar to the above since the vendor has not been forthcoming with a solution.
I have considered evaluating IP addresses; however, I am not certain how to tell if the PC is from inside or outside our network. (Although, I did see a post for pinging an internal destination as one means; this in conjuction with a fixed IP check may be a possibility.)
I realize (and am embarrassed that) this is kind of out there--there is probably a whole lot wrong with what we're trying to accomplish. Regardless, any [not too cruel] direction or suggestions will be greatly appreciated.
Here goes nothing . . . \*Post\*
| javascript | asp.net | cookies | web | ip-address | null | open | Brainstorm: Disable Vendor Web Application Functionality on Public PC
===
The **question/problem**: *From a single installation of a web site, what's the "best" (good, reasonable) "backdoor" way to flex functionality for a specific PC*?
We have a vendor-supplied web application that, among other things, allows online payments--intended for use by "the public" over the intERnet, from outside our building and network. We have PC's that are intentionally accessible to the public throughout our organization. We would like to make this vendor application available from these public PC's; however, to protect ourselves from users inadvertently exposing their personal, financial information to subsequent users, we would like to disable the payment functionality of the application--using the same installation of the site as is used for external access (if that's not too crazy).
My first stab at accomplishing this has been to create a cookie on these public PC's. I have added javascript to the vendor .aspx that hides the "Pay" button if the cookie exists.
This works and feels relatively reliable, assuming we control the browser installation and prohibit public users from deleting cookies. However, since there are many other ways cookies could get inadvertently deleted (i.e., maintenance, upgrades, etc.), I am not entirely comfortable with this approach.
I am struggling to come up with another, more reasonable and reliable solution, so I am just sort of throwing this out here for suggestions, brainstorming. The solution will likely have to be a sort-of backdoor something similar to the above since the vendor has not been forthcoming with a solution.
I have considered evaluating IP addresses; however, I am not certain how to tell if the PC is from inside or outside our network. (Although, I did see a post for pinging an internal destination as one means; this in conjuction with a fixed IP check may be a possibility.)
I realize (and am embarrassed that) this is kind of out there--there is probably a whole lot wrong with what we're trying to accomplish. Regardless, any [not too cruel] direction or suggestions will be greatly appreciated.
Here goes nothing . . . \*Post\*
| 0 |
11,514,060 | 07/16/2012 23:28:40 | 1,380,918 | 05/08/2012 00:33:23 | 115 | 0 | Javacscript: Calculating the time required to retrieve data | I use jQuery to POST data to a page, and to get data back. How would I calculate the time it took from POSTing to the page, and receiving the data?
I use jQuery.post, and here is an code example:
$.post("test.php", function(data) {
//do something with data
}); | javascript | jquery | null | null | null | null | open | Javacscript: Calculating the time required to retrieve data
===
I use jQuery to POST data to a page, and to get data back. How would I calculate the time it took from POSTing to the page, and receiving the data?
I use jQuery.post, and here is an code example:
$.post("test.php", function(data) {
//do something with data
}); | 0 |
11,349,969 | 07/05/2012 18:02:22 | 1,484,365 | 06/27/2012 02:19:53 | 8 | 1 | Adding and editing rows using Modal Form in jqGrid using ASP.NET MVC | I have Add, Edit and Delete icons displaying in the navigation bar. I want to have a modal form displayed when clicking on the icons to add or edit the rows. Can someone point me to any good article or in the right direction to implement modal forms in javascript and how the controller actions should be implmented on the server side. I have researched a lot and couldn't find a good article or answer to use modal forms, most of them look complicated. Any help is greatly appreciated! | asp.net-mvc-3 | jqgrid | modal-dialog | jqgrid-asp.net | null | null | open | Adding and editing rows using Modal Form in jqGrid using ASP.NET MVC
===
I have Add, Edit and Delete icons displaying in the navigation bar. I want to have a modal form displayed when clicking on the icons to add or edit the rows. Can someone point me to any good article or in the right direction to implement modal forms in javascript and how the controller actions should be implmented on the server side. I have researched a lot and couldn't find a good article or answer to use modal forms, most of them look complicated. Any help is greatly appreciated! | 0 |
11,349,971 | 07/05/2012 18:02:26 | 598,511 | 02/01/2011 14:16:14 | 2,166 | 117 | Converting Canvas to Drawable | int x = 10;
int y = 10;
int r = 4;
Paint mPaint = new Paint();
mPaint.setColor(0xFF0000);
Canvas mCanvas = new Canvas();
mCanvas.drawCircle(x,y,r,mPaint);
Is there any way to convert `mCanvas` to a Drawable? My goal is to generate drawables with a certain shape and color.
Thanks
| android | null | null | null | null | null | open | Converting Canvas to Drawable
===
int x = 10;
int y = 10;
int r = 4;
Paint mPaint = new Paint();
mPaint.setColor(0xFF0000);
Canvas mCanvas = new Canvas();
mCanvas.drawCircle(x,y,r,mPaint);
Is there any way to convert `mCanvas` to a Drawable? My goal is to generate drawables with a certain shape and color.
Thanks
| 0 |
11,349,987 | 07/05/2012 18:03:29 | 1,496,850 | 07/02/2012 18:21:20 | 8 | 0 | I have an error in my PHP code set up to view my images | <?php
$con=mysql_connect ("localhost","","");
mysql_select_db("dbhappps",$con);
@$sql="select * from tbl_image where id='4' and status='0'";
@$query=mysql_query($sql);
while(@$row=mysql_fetch_array($query))
{
@$image=$row ['photo'];
echo $image
?>
<img src="/image/<?php echo $image; ?>" width="320" height="480">
<?php
}
?>
**The echo $image is giving me the correct file name so I am either not referencing the /image (the image folder is in my root directory) folder correctly or could it be a browser issue? I am testing it in google chrome. any tips would be great.** | php | image | null | null | null | null | open | I have an error in my PHP code set up to view my images
===
<?php
$con=mysql_connect ("localhost","","");
mysql_select_db("dbhappps",$con);
@$sql="select * from tbl_image where id='4' and status='0'";
@$query=mysql_query($sql);
while(@$row=mysql_fetch_array($query))
{
@$image=$row ['photo'];
echo $image
?>
<img src="/image/<?php echo $image; ?>" width="320" height="480">
<?php
}
?>
**The echo $image is giving me the correct file name so I am either not referencing the /image (the image folder is in my root directory) folder correctly or could it be a browser issue? I am testing it in google chrome. any tips would be great.** | 0 |
11,349,988 | 07/05/2012 18:03:33 | 1,047,912 | 11/15/2011 15:36:44 | 50 | 0 | Delete all S3 buckets with Fog | Folks, I want to figure out how to delete all the S3 buckets with Fog without doing a list. I wont be knowing the list of buckets and objects in S3 for an account, and doing a list and then deleting sounds too expensive, isnt there a way to delete all the objects and buckets for an amazon account.
Thanks a lot. | amazon-s3 | fog | null | null | null | null | open | Delete all S3 buckets with Fog
===
Folks, I want to figure out how to delete all the S3 buckets with Fog without doing a list. I wont be knowing the list of buckets and objects in S3 for an account, and doing a list and then deleting sounds too expensive, isnt there a way to delete all the objects and buckets for an amazon account.
Thanks a lot. | 0 |
11,349,990 | 07/05/2012 18:03:37 | 1,443,707 | 06/08/2012 04:47:52 | 1 | 0 | Jython: Set coordinates of image? | I am placing two pictures into an empty picture. I can place both pictures into the empty picture. How do I set the coordinates of one of the pictures?
#wall and mona are image names
#frame
for x in range (0, wW):
for y in range (0, wH):
wPixel = getPixel(wall, x, y)
wColor = getColor(wPixel)
newWPixel = getPixel(pic, x, y)
setColor(newWPixel, wColor)
#mona
for y in range (0, mH):
for x in range (0, mW):
mPixel = getPixel(mona, x, y)
mColor = getColor(mPixel)
newMPixel = getPixel(pic, x, y)
setColor(newMPixel, mColor) | jython | jython-2.5 | null | null | null | null | open | Jython: Set coordinates of image?
===
I am placing two pictures into an empty picture. I can place both pictures into the empty picture. How do I set the coordinates of one of the pictures?
#wall and mona are image names
#frame
for x in range (0, wW):
for y in range (0, wH):
wPixel = getPixel(wall, x, y)
wColor = getColor(wPixel)
newWPixel = getPixel(pic, x, y)
setColor(newWPixel, wColor)
#mona
for y in range (0, mH):
for x in range (0, mW):
mPixel = getPixel(mona, x, y)
mColor = getColor(mPixel)
newMPixel = getPixel(pic, x, y)
setColor(newMPixel, mColor) | 0 |
11,349,991 | 07/05/2012 18:03:38 | 1,377,568 | 05/06/2012 03:29:11 | 1 | 3 | LESS CSS access element NESTED CSS CLASSES | I am trying to access only the ELEMENT for toc-chapter number (1 in this case). The element is in nested classes. I've used this approach on toc-section and was able to produce the wanted result.
Css:
.book .toc {
& > .title{
font-size: x-large;
font-weight: bold;
padding-bottom: .25em;
margin-bottom:.50em;
border-bottom: 1px solid @tuscany;
}
& a.target-chapter{
.cnx-gentext-n{
&:before{content: "testing";}
}
color:red ;
}
}
HTML:
<div class="toc">
<div class="title">
Table of Contents
</div>
<ul>
<li xmlns:d="http://docbook.org/ns/docbook" xmlns:db=
"http://docbook.org/ns/docbook" xmlns:pmml2svg=
"https://sourceforge.net/projects/pmml2svg/" xmlns:c="http://cnx.rice.edu/cnxml"
xmlns:ext="http://cnx.org/ns/docbook+" xmlns:svg="http://www.w3.org/2000/svg"
xmlns:mml="http://www.w3.org/1998/Math/MathML" class="toc-chapter">
<a href="#idm3792312" class="target-chapter"><span class=
"cnx-gentext-chapter cnx-gentext-autogenerated">Chapter</span> <span class=
"cnx-gentext-chapter cnx-gentext-n">1</span><span class=
"cnx-gentext-chapter cnx-gentext-autogenerated">.</span> <span class=
"cnx-gentext-chapter cnx-gentext-t">Aging and the Elderly</span></a>
| css | class | nested | less | null | null | open | LESS CSS access element NESTED CSS CLASSES
===
I am trying to access only the ELEMENT for toc-chapter number (1 in this case). The element is in nested classes. I've used this approach on toc-section and was able to produce the wanted result.
Css:
.book .toc {
& > .title{
font-size: x-large;
font-weight: bold;
padding-bottom: .25em;
margin-bottom:.50em;
border-bottom: 1px solid @tuscany;
}
& a.target-chapter{
.cnx-gentext-n{
&:before{content: "testing";}
}
color:red ;
}
}
HTML:
<div class="toc">
<div class="title">
Table of Contents
</div>
<ul>
<li xmlns:d="http://docbook.org/ns/docbook" xmlns:db=
"http://docbook.org/ns/docbook" xmlns:pmml2svg=
"https://sourceforge.net/projects/pmml2svg/" xmlns:c="http://cnx.rice.edu/cnxml"
xmlns:ext="http://cnx.org/ns/docbook+" xmlns:svg="http://www.w3.org/2000/svg"
xmlns:mml="http://www.w3.org/1998/Math/MathML" class="toc-chapter">
<a href="#idm3792312" class="target-chapter"><span class=
"cnx-gentext-chapter cnx-gentext-autogenerated">Chapter</span> <span class=
"cnx-gentext-chapter cnx-gentext-n">1</span><span class=
"cnx-gentext-chapter cnx-gentext-autogenerated">.</span> <span class=
"cnx-gentext-chapter cnx-gentext-t">Aging and the Elderly</span></a>
| 0 |
11,349,994 | 07/05/2012 18:03:45 | 545,295 | 12/16/2010 20:20:37 | 697 | 16 | Objective C - Override setter to accept objects of a different type | I'm trying to override the setter of an `NSManagedObject` so that I can pass in an object of a different type, do a transformation and then set the property. Something like this:
- (void)setContentData:(NSData *)contentData
{
NSString *base64String;
// do some stuff to convert data to base64-encoded string
// ...
[self willChangeValueForKey:@"contentData"];
[self setPrimitiveValue:base64String forKey:@"contentData"];
[self didChangeValueForKey:@"contentData"];
}
So, in this case the `contentData` field of my `NSManagedObject` is an `NSString *`, and I want to allow the setter to accept an `NSData *` which I would then convert to an `NSString *` and save it to the model. However, if I try to do this I get warnings from the compiler about trying to assign an `NSData *` to an `NSString *`:
myObject.contentData = someNSData;
-> Incompatible pointer types assigning to 'NSString *' from 'NSData *__strong'
Is there a better way to go about this, or perhaps I should avoid the setters altogether and create custom "setters" that allow me to pass in the `NSData *` and set the `NSString *` field without a compiler warning? | objective-c | ios | null | null | null | null | open | Objective C - Override setter to accept objects of a different type
===
I'm trying to override the setter of an `NSManagedObject` so that I can pass in an object of a different type, do a transformation and then set the property. Something like this:
- (void)setContentData:(NSData *)contentData
{
NSString *base64String;
// do some stuff to convert data to base64-encoded string
// ...
[self willChangeValueForKey:@"contentData"];
[self setPrimitiveValue:base64String forKey:@"contentData"];
[self didChangeValueForKey:@"contentData"];
}
So, in this case the `contentData` field of my `NSManagedObject` is an `NSString *`, and I want to allow the setter to accept an `NSData *` which I would then convert to an `NSString *` and save it to the model. However, if I try to do this I get warnings from the compiler about trying to assign an `NSData *` to an `NSString *`:
myObject.contentData = someNSData;
-> Incompatible pointer types assigning to 'NSString *' from 'NSData *__strong'
Is there a better way to go about this, or perhaps I should avoid the setters altogether and create custom "setters" that allow me to pass in the `NSData *` and set the `NSString *` field without a compiler warning? | 0 |
11,350,000 | 07/05/2012 18:04:06 | 197,860 | 10/28/2009 06:22:02 | 3,305 | 104 | Mapping corners to arbitrary positions using Direct2D | I'm using WIC and Direct2D (via SharpDX) to composite photos into video frames. For each frame I have the exact coordinates where each corner will be found. While the photos themselves are a standard aspect ratio (e.g. 4:3 or 16:9) the insertion points are not -- they may be rotated, scaled, and skewed.
![enter image description here][1]
[1]: http://i.stack.imgur.com/YUsjN.png
Now I know in Direct2D I can apply matrix transformations to accomplish this... but I'm not exactly sure how. The examples I've seen are more about applying specific transformations (e.g. rotate 30 degrees) than trying to match an exact destination.
Given that I know the exact coordinates (A,B,C,D) above, is there an easy way to map the source image onto the target? Alternately how would I generate the matrix given the source and destination coordinates? | matrix | directx | direct2d | sharpdx | srt | null | open | Mapping corners to arbitrary positions using Direct2D
===
I'm using WIC and Direct2D (via SharpDX) to composite photos into video frames. For each frame I have the exact coordinates where each corner will be found. While the photos themselves are a standard aspect ratio (e.g. 4:3 or 16:9) the insertion points are not -- they may be rotated, scaled, and skewed.
![enter image description here][1]
[1]: http://i.stack.imgur.com/YUsjN.png
Now I know in Direct2D I can apply matrix transformations to accomplish this... but I'm not exactly sure how. The examples I've seen are more about applying specific transformations (e.g. rotate 30 degrees) than trying to match an exact destination.
Given that I know the exact coordinates (A,B,C,D) above, is there an easy way to map the source image onto the target? Alternately how would I generate the matrix given the source and destination coordinates? | 0 |
11,350,004 | 07/05/2012 18:04:22 | 152,949 | 08/08/2009 11:22:21 | 1,240 | 83 | Override method in multiple threads | I have implemented my own memory manager and I override the new and delete operators like this:
/** Override the Standard C++ new operator */
void* operator new (size_t size);
/** Override the Standard C++ delete operator */
void operator delete (void *p);
This works ok, but now I'm developing in a multi-threaded environment with lots of heap allocation. To avoid heap contention, I want that each thread has its own memory manager instance. How can I make the operator overrides point to the memory manager instance for that thread? | c++ | multithreading | null | null | null | null | open | Override method in multiple threads
===
I have implemented my own memory manager and I override the new and delete operators like this:
/** Override the Standard C++ new operator */
void* operator new (size_t size);
/** Override the Standard C++ delete operator */
void operator delete (void *p);
This works ok, but now I'm developing in a multi-threaded environment with lots of heap allocation. To avoid heap contention, I want that each thread has its own memory manager instance. How can I make the operator overrides point to the memory manager instance for that thread? | 0 |
11,350,005 | 07/05/2012 18:04:22 | 1,076,582 | 12/02/2011 01:27:47 | 6 | 0 | DOJO, how to get slice index in pie chart and connect slice with dotted line to another pie chart? | I am new to DOJO and need help.
I am able to create Pie chart's using DOJOX charting widget and get all action2d api's working...moving, highlight, tooltip and...etc but I need following things
1. Get current slice (selected by user) index or object or value
2. To draw dotted line with arrow pointing to another Pie chart in the same layout for each slice.
Goal is to get something like below
(my example pie chart is rectangular instead of circular :-))
------- ---------
|slice1|...........>|s1 | s2|
|------| ---------
|slice2|............>
-------- ---------
| s1|s2 |
---------
Any pointers...or suggestions or thoughts ....are welcome
Thanks in Advance | dojo | pie | null | null | null | null | open | DOJO, how to get slice index in pie chart and connect slice with dotted line to another pie chart?
===
I am new to DOJO and need help.
I am able to create Pie chart's using DOJOX charting widget and get all action2d api's working...moving, highlight, tooltip and...etc but I need following things
1. Get current slice (selected by user) index or object or value
2. To draw dotted line with arrow pointing to another Pie chart in the same layout for each slice.
Goal is to get something like below
(my example pie chart is rectangular instead of circular :-))
------- ---------
|slice1|...........>|s1 | s2|
|------| ---------
|slice2|............>
-------- ---------
| s1|s2 |
---------
Any pointers...or suggestions or thoughts ....are welcome
Thanks in Advance | 0 |
11,350,007 | 07/05/2012 18:04:25 | 1,247,387 | 03/03/2012 21:51:35 | 21 | 6 | How to do a foreach loop in a LinkedHashMap in JSP? | I do not have much experience with jsp.
In java I can do, but it is not good to open a block <% %> | java | jsp | foreach | linkedhashmap | null | null | open | How to do a foreach loop in a LinkedHashMap in JSP?
===
I do not have much experience with jsp.
In java I can do, but it is not good to open a block <% %> | 0 |
11,350,008 | 07/05/2012 18:04:35 | 1,058,646 | 11/21/2011 21:34:49 | 298 | 4 | How to get .exe file version number from file path | I am trying to get a version number of an exe file on my c: drive. For example path is:
c:\Program\demo.exe , if the version number of demo.exe is 1.0 how can i use this path to grab version number. I am using .Net 3.5/4.0 with code in C#.
| c#-4.0 | null | null | null | null | null | open | How to get .exe file version number from file path
===
I am trying to get a version number of an exe file on my c: drive. For example path is:
c:\Program\demo.exe , if the version number of demo.exe is 1.0 how can i use this path to grab version number. I am using .Net 3.5/4.0 with code in C#.
| 0 |
11,373,035 | 07/07/2012 07:08:02 | 1,330,984 | 04/13/2012 07:40:05 | 215 | 3 | MVC3 areas and routing structure | I am making Areas for User, Admin, Shop, Forum... etc
In each area, it has its own Controllers, Models, Views folders. At the root Models, root Controllers and root Views I have shared components in them.
Structure A:
Root/ -> Models/, Controllers/, Views/
Root/User/ -> Models/, Controllers/, Views/
Root/Admin/ -> Models/, Controllers/, Views/
Root/Shop/ -> Models/, Controllers/, Views/
Root/Forum/ -> Models/, Controllers/, Views/
I maybe wrong, but they really don't look DRY to me to repeat M V and C folders in each of the business logic groups. I was thinking a better structure would be using M V and C as the main folders and layout my business logic groups in them:
Structure B:
Root/Views/ -> User/, Admin/, Shop/, Forum/ ...etc
Root/Models/ -> User/, Admin/, Shop/, Forum/ ...etc
Root/Controllers/ -> User/, Admin/, Shop/, Forum/ ...etc
But if I do structure the folders this way, I lost the area (or from users point of view, the sub folder path) ability to divde logical functionalities of the website.
e.g.
with structure A, I can do:
www.mywebsite.com/Users(area)/Account(controller)/LogOn(action)
www.mywebsite.com/Admin(area)/Account(controller)/LogOn(action)
Notice I can have same controller and action names with different areas.
With structure B, best I can do is:
www.mywebsite.com/AdminAccount(controller)/LogOn(action)
www.mywebsite.com/UserAccount(controller)/LogOn(action)
It can not achieve the single-word sub-folder result without area. If not only that, the controller names here can get longer and more messy very soon. Not to mention you have a large group of actions stacking in same controller.cs file.
So, anyway, my point is, if I find Structure B making more sense to me, how do I go about configuring routing to achieve that?
| asp.net | mvc | routing | null | null | null | open | MVC3 areas and routing structure
===
I am making Areas for User, Admin, Shop, Forum... etc
In each area, it has its own Controllers, Models, Views folders. At the root Models, root Controllers and root Views I have shared components in them.
Structure A:
Root/ -> Models/, Controllers/, Views/
Root/User/ -> Models/, Controllers/, Views/
Root/Admin/ -> Models/, Controllers/, Views/
Root/Shop/ -> Models/, Controllers/, Views/
Root/Forum/ -> Models/, Controllers/, Views/
I maybe wrong, but they really don't look DRY to me to repeat M V and C folders in each of the business logic groups. I was thinking a better structure would be using M V and C as the main folders and layout my business logic groups in them:
Structure B:
Root/Views/ -> User/, Admin/, Shop/, Forum/ ...etc
Root/Models/ -> User/, Admin/, Shop/, Forum/ ...etc
Root/Controllers/ -> User/, Admin/, Shop/, Forum/ ...etc
But if I do structure the folders this way, I lost the area (or from users point of view, the sub folder path) ability to divde logical functionalities of the website.
e.g.
with structure A, I can do:
www.mywebsite.com/Users(area)/Account(controller)/LogOn(action)
www.mywebsite.com/Admin(area)/Account(controller)/LogOn(action)
Notice I can have same controller and action names with different areas.
With structure B, best I can do is:
www.mywebsite.com/AdminAccount(controller)/LogOn(action)
www.mywebsite.com/UserAccount(controller)/LogOn(action)
It can not achieve the single-word sub-folder result without area. If not only that, the controller names here can get longer and more messy very soon. Not to mention you have a large group of actions stacking in same controller.cs file.
So, anyway, my point is, if I find Structure B making more sense to me, how do I go about configuring routing to achieve that?
| 0 |
11,373,057 | 07/07/2012 07:12:25 | 1,150,527 | 01/15/2012 15:39:19 | 40 | 7 | How to set default controller in Yii | Is there a way to specify a default controller in Yii? Instead of using the SiteController? Thank you in advance. | php | mvc | yii | null | null | null | open | How to set default controller in Yii
===
Is there a way to specify a default controller in Yii? Instead of using the SiteController? Thank you in advance. | 0 |
11,373,062 | 07/07/2012 07:12:58 | 1,490,066 | 06/29/2012 01:22:59 | 12 | 0 | counting the number of nodes is not working | I have an xml file :
<?xml version="1.0" encoding="ISO-8859-1"?>
<food>
<cuisine type="Chinese">
<restaurant name = "Panda Express">
<location id= "0"></location>
<phone id = "1"></phone>
<city id="2"></phone>
</restaurant>
<restaurant name = "Mr. Chau's">
</restaurant>
</cuisine>
<cuisine type="Indian">
<restaurant name = "Shan">
</restaurant>
</cuisine>
</food>
and I am trying to count the number of cuisine nodes this is the code I have, I know its mostly right but when I try to print out the length of the nodelist it says it's 0
//starts talking to the xml document
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","data.xml", false);
xmlhttp.send();
xmlData = xmlhttp.responseXML;
//fills the first comboBox
var sel = document.getElementById('CuisineList');
cuisineList = xmlData.getElementsByTagName('cuisine');
document.getElementById("test").innerHTML = cuisineList.length; | javascript | xml | xml-parsing | null | null | null | open | counting the number of nodes is not working
===
I have an xml file :
<?xml version="1.0" encoding="ISO-8859-1"?>
<food>
<cuisine type="Chinese">
<restaurant name = "Panda Express">
<location id= "0"></location>
<phone id = "1"></phone>
<city id="2"></phone>
</restaurant>
<restaurant name = "Mr. Chau's">
</restaurant>
</cuisine>
<cuisine type="Indian">
<restaurant name = "Shan">
</restaurant>
</cuisine>
</food>
and I am trying to count the number of cuisine nodes this is the code I have, I know its mostly right but when I try to print out the length of the nodelist it says it's 0
//starts talking to the xml document
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","data.xml", false);
xmlhttp.send();
xmlData = xmlhttp.responseXML;
//fills the first comboBox
var sel = document.getElementById('CuisineList');
cuisineList = xmlData.getElementsByTagName('cuisine');
document.getElementById("test").innerHTML = cuisineList.length; | 0 |
11,373,067 | 07/07/2012 07:13:52 | 868,908 | 07/29/2011 07:38:34 | 235 | 5 | Merging one-by-many CSV files in Python | I have the output of a series of stochastic simulations in the form of a .csv file that look something like this:
Run, ID, Var
1, 1, 7
1, 2, 9
1, 3, 4
2, 1, 3
2, 2, 4
2, 3, 8
etc.
Along with that, I have another data file, also a .csv, formatted like so:
ID, Var2, Var3
1, 0.89, 0.10
2, 0.45, 0.98
3, 0.27, 0.05
What I'd like to do is write a script that takes each value <code>ID</code> from the first .csv file, and finds Var2 and Var3 and puts it together, to end up with something like:
Run, ID, Var, Var2, Var3
1, 1, 7, 0.89, 0.10
1, 2, 9, 0.45, 0.98
1, 3, 4, 0.27, 0.05
2, 1, 3, 0.89, 0.10
2, 2, 4, 0.45, 0.98
2, 3, 8, 0.27, 0.05
Any suggestions on a way to do this? I confess this is at the limits of my understanding for data handling in Python. I'd got a fair sense of how to do it in SAS, but I'd prefer to keep this a one-language task so that they can be processed as a single script.
| python | data | csv | null | null | null | open | Merging one-by-many CSV files in Python
===
I have the output of a series of stochastic simulations in the form of a .csv file that look something like this:
Run, ID, Var
1, 1, 7
1, 2, 9
1, 3, 4
2, 1, 3
2, 2, 4
2, 3, 8
etc.
Along with that, I have another data file, also a .csv, formatted like so:
ID, Var2, Var3
1, 0.89, 0.10
2, 0.45, 0.98
3, 0.27, 0.05
What I'd like to do is write a script that takes each value <code>ID</code> from the first .csv file, and finds Var2 and Var3 and puts it together, to end up with something like:
Run, ID, Var, Var2, Var3
1, 1, 7, 0.89, 0.10
1, 2, 9, 0.45, 0.98
1, 3, 4, 0.27, 0.05
2, 1, 3, 0.89, 0.10
2, 2, 4, 0.45, 0.98
2, 3, 8, 0.27, 0.05
Any suggestions on a way to do this? I confess this is at the limits of my understanding for data handling in Python. I'd got a fair sense of how to do it in SAS, but I'd prefer to keep this a one-language task so that they can be processed as a single script.
| 0 |
11,372,843 | 07/07/2012 06:31:28 | 108,176 | 05/16/2009 15:03:41 | 494 | 1 | Strange shell behaviour | Here is a simple bash script:
a="asd"
b="qf"
echo "$a.$b"
echo "$a_$b"
It's output is:
asd.qf
qf
Why the second line is not "`asd_qf`" but "`qf`"? | shell | null | null | null | null | null | open | Strange shell behaviour
===
Here is a simple bash script:
a="asd"
b="qf"
echo "$a.$b"
echo "$a_$b"
It's output is:
asd.qf
qf
Why the second line is not "`asd_qf`" but "`qf`"? | 0 |
11,373,069 | 07/07/2012 07:14:36 | 1,293,317 | 03/26/2012 14:55:34 | 37 | 3 | Physical memory usage approaching 100%(96%) | Context:
- Windows Server 2008 R2;
- 32GB RAM;
- Application: SQL Server 2008 R2, several Connectors to Write Data into SQL Server(Write Frequency: 0.5HZ);
- The Server has not been restart for more than half a year;
- About 15G Data per month;
- Support Several Applications hosted on other Server(Web Applicaion, Socket Application);
- Problem(From the Task Manager): The Memory Usage is **approaching 100%**(96%), while by checking all the running processes, the total usage of memory should be **less than 10%**, the situation has been like this for a long time, causing no big problems temporarily...
is there some kind of memory-leak problems here?
any related information is appreciated,
Dean | windows | sql-server-2008 | memory-leaks | null | null | 07/08/2012 01:01:55 | off topic | Physical memory usage approaching 100%(96%)
===
Context:
- Windows Server 2008 R2;
- 32GB RAM;
- Application: SQL Server 2008 R2, several Connectors to Write Data into SQL Server(Write Frequency: 0.5HZ);
- The Server has not been restart for more than half a year;
- About 15G Data per month;
- Support Several Applications hosted on other Server(Web Applicaion, Socket Application);
- Problem(From the Task Manager): The Memory Usage is **approaching 100%**(96%), while by checking all the running processes, the total usage of memory should be **less than 10%**, the situation has been like this for a long time, causing no big problems temporarily...
is there some kind of memory-leak problems here?
any related information is appreciated,
Dean | 2 |
11,373,046 | 07/07/2012 07:09:11 | 1,150,071 | 01/15/2012 05:17:19 | 14 | 0 | Fill Gaps in a c# graph using Drawline method in c# | ![enter image description here][1]
[1]: http://i.stack.imgur.com/MrovS.jpg
i have a preprocessed graph image..So i want to fill the gaps in some parts of the line.
I think i can use drawline method in c# to do that.
my logic is we have to read each column and check where is the black pixel and check rightmost pixel is also a black pixel.if rightmost pixel is a white pixel we have to draw a line between nearest right most black pixel.
can anyone give me a idea.i posted here template of the source code.
public void fillGaps(bitmap bmp)
{
Color col;
Color col1;
Color col2;
Color col3;
int val;
int x,y;
Graphics g;
for (int i = 0; i < bmp.Height; ++i)
{
for (int j = 0; j < bmp.Width; ++j)
{
col = bmp.GetPixel(j, i);
if((col.R==0) && (val==0))
{
if((i<height-1) && (j<width-1))
{
col1=bmp.GetPixel(j+1,i-1);
col2=bmp.GetPixel(j+1,i);
col3=bmp.GetPixel(j+1,i+1);
if((col1.R !=0) && (col2.R !=0) && (col3.R !=0))
{
x = j;
y = i;
}
g.DrawLine(myPen, x, y, x1, y2);
//i need a logic to find these x1,y2 pixels(nearest right most black pixel)
}
}
}
}
}
}
i need a logic to find these x1,y2 pixels(nearest right most black pixel | c# | drawing | null | null | null | null | open | Fill Gaps in a c# graph using Drawline method in c#
===
![enter image description here][1]
[1]: http://i.stack.imgur.com/MrovS.jpg
i have a preprocessed graph image..So i want to fill the gaps in some parts of the line.
I think i can use drawline method in c# to do that.
my logic is we have to read each column and check where is the black pixel and check rightmost pixel is also a black pixel.if rightmost pixel is a white pixel we have to draw a line between nearest right most black pixel.
can anyone give me a idea.i posted here template of the source code.
public void fillGaps(bitmap bmp)
{
Color col;
Color col1;
Color col2;
Color col3;
int val;
int x,y;
Graphics g;
for (int i = 0; i < bmp.Height; ++i)
{
for (int j = 0; j < bmp.Width; ++j)
{
col = bmp.GetPixel(j, i);
if((col.R==0) && (val==0))
{
if((i<height-1) && (j<width-1))
{
col1=bmp.GetPixel(j+1,i-1);
col2=bmp.GetPixel(j+1,i);
col3=bmp.GetPixel(j+1,i+1);
if((col1.R !=0) && (col2.R !=0) && (col3.R !=0))
{
x = j;
y = i;
}
g.DrawLine(myPen, x, y, x1, y2);
//i need a logic to find these x1,y2 pixels(nearest right most black pixel)
}
}
}
}
}
}
i need a logic to find these x1,y2 pixels(nearest right most black pixel | 0 |
11,541,831 | 07/18/2012 12:51:38 | 1,070,258 | 11/28/2011 22:24:32 | 61 | 5 | Select element from collection with probability proportional to element value | I have a list of vertices, from which I have to pick a random vertex with probability proportional to deg(v), where deg(v) is a vertex degree. The pseudo code for this operation look like that:
Select u ∈ L with probability deg(u) / Sigma ∀v∈L deg(v)
Where u is the randomly selected vertex, L is the list of vertices and v is a vertex in L. The problem is that I don't understand how to do it. Can someone explain to me, how to get this random vertex. I would greatly appreciate if someone can explain this to me. Pseudo-code will be even more appreciate ;). | algorithm | graph | selection | probability | random-sample | null | open | Select element from collection with probability proportional to element value
===
I have a list of vertices, from which I have to pick a random vertex with probability proportional to deg(v), where deg(v) is a vertex degree. The pseudo code for this operation look like that:
Select u ∈ L with probability deg(u) / Sigma ∀v∈L deg(v)
Where u is the randomly selected vertex, L is the list of vertices and v is a vertex in L. The problem is that I don't understand how to do it. Can someone explain to me, how to get this random vertex. I would greatly appreciate if someone can explain this to me. Pseudo-code will be even more appreciate ;). | 0 |
11,541,840 | 07/18/2012 12:51:59 | 811,401 | 06/23/2011 01:31:26 | 6 | 2 | Creating asynchronous thread for REST API processing using Spring Servet | I want to create fire-and-forget model for couple of my REST API calls where server will accept requests on end point, send object for async processing to internal services while releasing client connection. I am using Spring 3 MVC and Tomcat 6. I think introducing full messaging system like ActiveMQ or RabbitMQ would be overkill for my project at this stage.
Is there any other safe way for creating async processing (threads) for my services inside tomcat and Spring? I am afraid that doing thread programming inside tomcat will violate it integrity.
Thanks | spring | rest | tomcat | asynchronous | fire-and-forget | null | open | Creating asynchronous thread for REST API processing using Spring Servet
===
I want to create fire-and-forget model for couple of my REST API calls where server will accept requests on end point, send object for async processing to internal services while releasing client connection. I am using Spring 3 MVC and Tomcat 6. I think introducing full messaging system like ActiveMQ or RabbitMQ would be overkill for my project at this stage.
Is there any other safe way for creating async processing (threads) for my services inside tomcat and Spring? I am afraid that doing thread programming inside tomcat will violate it integrity.
Thanks | 0 |
11,541,847 | 07/18/2012 12:52:30 | 1,065,129 | 11/25/2011 06:59:48 | 30 | 1 | Java SipServlet to build VOIP phone calls (between Computer and analog phone/mobile) | I'm interested in building VOIP that actually can be used to call to analog phone using SIP or H.323. But my question is that, is it even possible to build Computer to Phone & Phone to Computer VOIP phone calls with SIP or H.323? Else what is the most common way of achieving this task? I've successfully built an application that i can transfer voices between two computers by using socket, and my guess is that building SIP to communicate with analog phone is quite complicated (even though i read some docs, i still haven't fully understood it) and has a quite different architecture than ordinary socket communication applications. So is it possible to achieve my goal using SIP servlet or H.323? And if you have experienced building it, could u plz share some of references or docs that you have used with me? I would appreciate it so much and I'm pretty sure it will be helpful for all the others who are looking forward to building similar app as mine.
=====================================
According to http://stackoverflow.com/questions/2321582/begin-with-java-voip
a dude recommended using APIs like http://public.ifbyphone.com/ or https://www.tropo.com/home.jsp but i have strong feeling that these people will ask me to pay money to use their API, and all i want to do is just build it by myself and try-out only purpose without commercializing it at all. I've found a quite decent VOIP related thingy called VoiceXML, but is it the same kind of API or library as the ones I've mentioned already? What exactly is VoiceXML? | java | android | servlets | sip | voip | null | open | Java SipServlet to build VOIP phone calls (between Computer and analog phone/mobile)
===
I'm interested in building VOIP that actually can be used to call to analog phone using SIP or H.323. But my question is that, is it even possible to build Computer to Phone & Phone to Computer VOIP phone calls with SIP or H.323? Else what is the most common way of achieving this task? I've successfully built an application that i can transfer voices between two computers by using socket, and my guess is that building SIP to communicate with analog phone is quite complicated (even though i read some docs, i still haven't fully understood it) and has a quite different architecture than ordinary socket communication applications. So is it possible to achieve my goal using SIP servlet or H.323? And if you have experienced building it, could u plz share some of references or docs that you have used with me? I would appreciate it so much and I'm pretty sure it will be helpful for all the others who are looking forward to building similar app as mine.
=====================================
According to http://stackoverflow.com/questions/2321582/begin-with-java-voip
a dude recommended using APIs like http://public.ifbyphone.com/ or https://www.tropo.com/home.jsp but i have strong feeling that these people will ask me to pay money to use their API, and all i want to do is just build it by myself and try-out only purpose without commercializing it at all. I've found a quite decent VOIP related thingy called VoiceXML, but is it the same kind of API or library as the ones I've mentioned already? What exactly is VoiceXML? | 0 |
11,541,849 | 07/18/2012 12:52:34 | 258,863 | 01/25/2010 23:16:58 | 973 | 6 | iOS upload files over wifi to app | I am developing an App that needs to support transfer files over a local wifi network like goodread app does.
The idea is that iPhone app creates an HTTP server accessible through a web browser displaying a form to upload files to the app.
1. Press in my app the wifi transfer option
2. Visit an ip address like: 192.168.0.12:port
3. Upload files to my app using that page
any idea?
Thanks | ios | file-upload | null | null | null | null | open | iOS upload files over wifi to app
===
I am developing an App that needs to support transfer files over a local wifi network like goodread app does.
The idea is that iPhone app creates an HTTP server accessible through a web browser displaying a form to upload files to the app.
1. Press in my app the wifi transfer option
2. Visit an ip address like: 192.168.0.12:port
3. Upload files to my app using that page
any idea?
Thanks | 0 |
11,541,851 | 07/18/2012 12:52:37 | 1,500,633 | 07/04/2012 05:50:10 | 27 | 0 | window.print not working with pdf file?Is there a solution? | I need to display print dialogue window while opening a pop up window which contains PDF file,I tried with java script window.print,but it opens print window for the web page not for the PDF file opened.Is there any other solution to open the print window for pdf in javascript asp.net c#? | javascript | null | null | null | null | null | open | window.print not working with pdf file?Is there a solution?
===
I need to display print dialogue window while opening a pop up window which contains PDF file,I tried with java script window.print,but it opens print window for the web page not for the PDF file opened.Is there any other solution to open the print window for pdf in javascript asp.net c#? | 0 |
11,523,053 | 07/17/2012 13:01:38 | 1,335,614 | 04/16/2012 06:04:31 | 1 | 0 | change joomla orientation of things | I wanted to figure out how to do some visual changes in joomla 1.5
for example I want to change the place of menu in admin menus, or some changes in buttons that are in different parts of admin menu(somewhere like add/remove components).
or in the pages like adding and removing components, I want to do some changes in the tables that show data, for example I want to delete a column or do some changes in column contents.
and I don't wanna make these changes in an specific theme or sth;I want that my changes affect all themes.
thanks | javascript | css | joomla | null | null | null | open | change joomla orientation of things
===
I wanted to figure out how to do some visual changes in joomla 1.5
for example I want to change the place of menu in admin menus, or some changes in buttons that are in different parts of admin menu(somewhere like add/remove components).
or in the pages like adding and removing components, I want to do some changes in the tables that show data, for example I want to delete a column or do some changes in column contents.
and I don't wanna make these changes in an specific theme or sth;I want that my changes affect all themes.
thanks | 0 |
11,541,750 | 07/18/2012 12:46:50 | 1,213,897 | 02/16/2012 13:13:31 | 1 | 0 | Google Maps route playback | I'm looking for a jquery plugin or any solution to playback (with animation) a route in a kml layer. such as.: http://ridewithgps.com/trips/337442 | php | jquery | google-maps | null | null | null | open | Google Maps route playback
===
I'm looking for a jquery plugin or any solution to playback (with animation) a route in a kml layer. such as.: http://ridewithgps.com/trips/337442 | 0 |
11,541,753 | 07/18/2012 12:47:01 | 192,384 | 10/19/2009 11:26:32 | 330 | 7 | Parsing csv file with unknown delimiter symbol | I have to write (or use existing) csv parsing library.
The problem is that files are uploaded in different formats with different delimiter symbols for example:
File1:
field1; field2; field3; field4;
File2:
feld1, field2, field3, field4,
File3:
"field1", "field2", "field3", "field4"
What is the best way to programmaticaly understand which symbol is actual delimiter for columns?
I'm thinking about writing my own method with symbols statistical analysis, but maybe there are existing solutions? | .net | parsing | csv | delimiter | null | null | open | Parsing csv file with unknown delimiter symbol
===
I have to write (or use existing) csv parsing library.
The problem is that files are uploaded in different formats with different delimiter symbols for example:
File1:
field1; field2; field3; field4;
File2:
feld1, field2, field3, field4,
File3:
"field1", "field2", "field3", "field4"
What is the best way to programmaticaly understand which symbol is actual delimiter for columns?
I'm thinking about writing my own method with symbols statistical analysis, but maybe there are existing solutions? | 0 |
11,387,310 | 07/08/2012 22:43:00 | 313,827 | 04/11/2010 09:10:22 | 666 | 17 | Accessing Twitter with Django and Javascript | This is a follow up to a previous question I had posted [here][1].
Basically I've been trying to implement a way to send request to twitter oauth resources via javascript. I have a server running a Django application which uses Django-social-auth to register users to Tiwtter. After I've obtained authorisation I get a users access_token and oauth_token_secret.
On the client side I have a javascript application which calls my server to compute the appropriate headers, which I do by using [python oauth2][2]. The piece of code doing this is as follows:
url = request.POST['url']
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time()),
}
at = social.extra_data['access_token'].split('&oauth_token=')[1]
ats = social.extra_data['access_token'].split('&oauth_token=')[0].split('oauth_token_secret=')[1]
token = oauth.Token(key=at, secret=ats)
consumer = oauth.Consumer(key=settings.TWITTER_CONSUMER_KEY, secret=settings.TWITTER_CONSUMER_SECRET)
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
req = oauth.Request(method="GET", url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
This request parameters are then sent to the client which does the call to Twitter using these parameters:
$.ajax({
url: "https://api.twitter.com/1/statuses/home_timeline.json",
data: parameters,
dataType: 'jsonp',
success: function(twitter_data) {
console.log('twitter_data = ', twdata);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('err = ', textStatus);
console.log('err = ', errorThrown);
}
});
which generates a request for a resource like:
https://api.twitter.com/1/statuses/home_timeline.json?callback=jQuery17107030615725088865_1341786299930&oauth_nonce=15094349&oauth_timestamp=1341785696&oauth_consumer_key=[OAUTH_CONSUMER_KEY HERE]&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=[OAUTH_TOKEN HERE]0&oauth_signature=pQwHlKmepgtym%2Ffj%2BupCGP8mv3s%3D&page=2&include_entities=true&_=1341786306712
Still I get a 401 Unauthorized error. I checked the code three times so am wondering if I missing something???
Thanks.
[1]: http://stackoverflow.com/questions/11379398/accessing-twitter-through-javascript
[2]: https://github.com/simplegeo/python-oauth2/ | javascript | ajax | twitter | twitter-api | django-socialauth | null | open | Accessing Twitter with Django and Javascript
===
This is a follow up to a previous question I had posted [here][1].
Basically I've been trying to implement a way to send request to twitter oauth resources via javascript. I have a server running a Django application which uses Django-social-auth to register users to Tiwtter. After I've obtained authorisation I get a users access_token and oauth_token_secret.
On the client side I have a javascript application which calls my server to compute the appropriate headers, which I do by using [python oauth2][2]. The piece of code doing this is as follows:
url = request.POST['url']
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time()),
}
at = social.extra_data['access_token'].split('&oauth_token=')[1]
ats = social.extra_data['access_token'].split('&oauth_token=')[0].split('oauth_token_secret=')[1]
token = oauth.Token(key=at, secret=ats)
consumer = oauth.Consumer(key=settings.TWITTER_CONSUMER_KEY, secret=settings.TWITTER_CONSUMER_SECRET)
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
req = oauth.Request(method="GET", url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
This request parameters are then sent to the client which does the call to Twitter using these parameters:
$.ajax({
url: "https://api.twitter.com/1/statuses/home_timeline.json",
data: parameters,
dataType: 'jsonp',
success: function(twitter_data) {
console.log('twitter_data = ', twdata);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('err = ', textStatus);
console.log('err = ', errorThrown);
}
});
which generates a request for a resource like:
https://api.twitter.com/1/statuses/home_timeline.json?callback=jQuery17107030615725088865_1341786299930&oauth_nonce=15094349&oauth_timestamp=1341785696&oauth_consumer_key=[OAUTH_CONSUMER_KEY HERE]&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=[OAUTH_TOKEN HERE]0&oauth_signature=pQwHlKmepgtym%2Ffj%2BupCGP8mv3s%3D&page=2&include_entities=true&_=1341786306712
Still I get a 401 Unauthorized error. I checked the code three times so am wondering if I missing something???
Thanks.
[1]: http://stackoverflow.com/questions/11379398/accessing-twitter-through-javascript
[2]: https://github.com/simplegeo/python-oauth2/ | 0 |
11,387,311 | 07/08/2012 22:43:11 | 1,413,151 | 05/23/2012 16:28:36 | 29 | 7 | iOS navigationItem title with custom font loses vertical centering | Is there any text attribute like line-height or any other feature that would help with vertical centering of a `UINavigationItem` title? After setting custom font it is higher than standard one. | ios | text | attributes | navigationitem | null | null | open | iOS navigationItem title with custom font loses vertical centering
===
Is there any text attribute like line-height or any other feature that would help with vertical centering of a `UINavigationItem` title? After setting custom font it is higher than standard one. | 0 |
11,386,870 | 07/08/2012 21:30:54 | 1,462,022 | 06/17/2012 15:48:09 | 1 | 0 | How to implement an UISlider sliderValueChanged && MouseButton released | I am using Xcode 4.3.2 and a project with storyboards. A page based application.
I am using an UISlider in a view. When the slider is pushed and moved, sliverValueChanged is triggered. This works fine. However i want more...
How would you implement a feature that only triggers an event, when the slider is changed AND the mouse button is released ?
My first idea was:
- (IBAction) sliderValueChanged:(UISlider *)sender {
if(sender.something){
// DO stuff
}
}
Thank you for reading this. | objective-c | xcode | null | null | null | null | open | How to implement an UISlider sliderValueChanged && MouseButton released
===
I am using Xcode 4.3.2 and a project with storyboards. A page based application.
I am using an UISlider in a view. When the slider is pushed and moved, sliverValueChanged is triggered. This works fine. However i want more...
How would you implement a feature that only triggers an event, when the slider is changed AND the mouse button is released ?
My first idea was:
- (IBAction) sliderValueChanged:(UISlider *)sender {
if(sender.something){
// DO stuff
}
}
Thank you for reading this. | 0 |
11,386,871 | 07/08/2012 21:31:00 | 1,181,506 | 01/31/2012 22:24:19 | 104 | 0 | how to save every listbox item into a xml file | i have listbox that reads a xml file and gives the user the ability to add items from one list box to the other. I want to somehow save all item names into a xml file when a user clicks on a specific button. But instead of printing the name it prints this `"System.Windows.Forms.ListBox+ObjectCollection"`
I thought i could do this.
XmlDocument doc = new XmlDocument();
doc.Load("info.xml");
XmlNode test = doc.CreateElement("Name");
test.InnerText = listBox2.Items.ToString();
doc.DocumentElement.AppendChild(test);
doc.Save("info.xml"); | c# | winforms | null | null | null | null | open | how to save every listbox item into a xml file
===
i have listbox that reads a xml file and gives the user the ability to add items from one list box to the other. I want to somehow save all item names into a xml file when a user clicks on a specific button. But instead of printing the name it prints this `"System.Windows.Forms.ListBox+ObjectCollection"`
I thought i could do this.
XmlDocument doc = new XmlDocument();
doc.Load("info.xml");
XmlNode test = doc.CreateElement("Name");
test.InnerText = listBox2.Items.ToString();
doc.DocumentElement.AppendChild(test);
doc.Save("info.xml"); | 0 |
11,387,322 | 07/08/2012 22:45:04 | 903,585 | 08/20/2011 09:24:21 | 406 | 35 | MemoryError while using Python's xml.dom.minidom with a relatively small input | I am trying to create a system for our college DC Hub to keep track of files shared by users, so that it is possible to pinpoint the source of any "objectionable" content. I have already built a command line DC client using python that I am using to download the file-lists of all users connected to the Official DC Hub of our college. This cycle is supposed to repeat every couple of hours, which means that the file-lists of the same user may be downloaded multiple over the course of time. Instead of storing each copy separately, I am trying to maintain one single master copy of the file-list, which is updated as necessary. As this data is in XML format, I have introduced additional tags to store information about when a particular item was created/updated or in case, the values of its other attributes change, the time at which it was detected and the previous value(s). The exact details for the process can be found here: http://pastebin.com/8FUbFEF3. For the purpose I am using xml.dom.minidom, loading the main and the latest versions of the file-list, and then calling a recursive function that performs the updates on the main one. The exact code can be found here: http://pastebin.com/VMMbX6Xj.
While this procedure works perfectly for smaller file-lists, whenever I process a file greater than 40MB in size, python gives me a MemoryError. I am using Python 2.7 on a Windows 7 Ultimate 32-bit with 4GB of RAM, of which it says (under Basic System Info) 2.99GB is usable. Aside from WAMP, Explorer & Notepad++, I am running no other programs as I perform this process. However, it makes no sense that a 40MB file is able to cause this. The only reason I can think of is that xml.dom stores the data structures in an extremely space inefficient way, which again doesnt make sense. Could someone please help me figure out why I am facing this program? | memory | python-2.7 | xml-dom | null | null | null | open | MemoryError while using Python's xml.dom.minidom with a relatively small input
===
I am trying to create a system for our college DC Hub to keep track of files shared by users, so that it is possible to pinpoint the source of any "objectionable" content. I have already built a command line DC client using python that I am using to download the file-lists of all users connected to the Official DC Hub of our college. This cycle is supposed to repeat every couple of hours, which means that the file-lists of the same user may be downloaded multiple over the course of time. Instead of storing each copy separately, I am trying to maintain one single master copy of the file-list, which is updated as necessary. As this data is in XML format, I have introduced additional tags to store information about when a particular item was created/updated or in case, the values of its other attributes change, the time at which it was detected and the previous value(s). The exact details for the process can be found here: http://pastebin.com/8FUbFEF3. For the purpose I am using xml.dom.minidom, loading the main and the latest versions of the file-list, and then calling a recursive function that performs the updates on the main one. The exact code can be found here: http://pastebin.com/VMMbX6Xj.
While this procedure works perfectly for smaller file-lists, whenever I process a file greater than 40MB in size, python gives me a MemoryError. I am using Python 2.7 on a Windows 7 Ultimate 32-bit with 4GB of RAM, of which it says (under Basic System Info) 2.99GB is usable. Aside from WAMP, Explorer & Notepad++, I am running no other programs as I perform this process. However, it makes no sense that a 40MB file is able to cause this. The only reason I can think of is that xml.dom stores the data structures in an extremely space inefficient way, which again doesnt make sense. Could someone please help me figure out why I am facing this program? | 0 |
11,387,324 | 07/08/2012 22:45:34 | 1,147,795 | 01/13/2012 13:50:14 | 40 | 5 | PHP JSON GCM request from PHP | For days I tried to implement a number of solutions from the [gcm & php thread here][1] to get my server to send a message to the GCM server and then to my Android device. My call to curl_exec($ch) kept returning false. After a few days of racking my brain, reading and searching the web it seems I finally figured it out. I had to use GET instead of POST, I found that [here][2], and I had to NOT verify the SSL. (I can't remember where I found that...)
I hope this helps someone who's having the same problem. And please, if anyone can improve upon this their corrections are more then welcome.
This is what was suggested by the thread linked to above:
$ch = curl_init();
// WRITE MESSAGE TO SEND TO JSON OBJECT
$message = '{"data":{"message":"here is the message","title":"message title"},"registration_ids":["'. $reg . '","'. $reg2 . '"]}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_URL, $gcmurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
$result = curl_exec($ch);
if(!$result > 0){
echo "<p>An error has occurred.<p>";
echo "<p>ERROR: $curl_error</p>";
}
else{
$json_return = json_decode($result);
echo var_dump($json_return);
$info = curl_getinfo($ch);;
echo "<p>httpcode: " . $info['http_code'] . "</p>";
}
curl_close($ch);
For me to get this working I have to implement the following.
$ch = curl_init();
$message = '{"data":{"message":"here is the message","title":"message title"},"registration_ids":["'. $reg . '","'. $reg2 . '"]}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_URL, $gcmurl);
/*
* COMMENT OUT THE FOLLOWING LINE
*/
*//curl_setopt($ch, CURLOPT_POST, true);*
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
/*
* ADD THESE 2 LINES
*/
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
if(!$result > 0){
echo "<p>An error has occurred.<p>";
echo "<p>ERROR: $curl_error";
}
else{
$json_return = json_decode($result);
echo var_dump($json_return);
$info = curl_getinfo($ch);;
}
curl_close($ch);
[1]: http://stackoverflow.com/questions/11242743/gcm-with-php-google-cloud-messaging
[2]: http://stackoverflow.com/questions/3018378/php-curl-error-empty-reply-from-server | php | json | android-gcm | null | null | null | open | PHP JSON GCM request from PHP
===
For days I tried to implement a number of solutions from the [gcm & php thread here][1] to get my server to send a message to the GCM server and then to my Android device. My call to curl_exec($ch) kept returning false. After a few days of racking my brain, reading and searching the web it seems I finally figured it out. I had to use GET instead of POST, I found that [here][2], and I had to NOT verify the SSL. (I can't remember where I found that...)
I hope this helps someone who's having the same problem. And please, if anyone can improve upon this their corrections are more then welcome.
This is what was suggested by the thread linked to above:
$ch = curl_init();
// WRITE MESSAGE TO SEND TO JSON OBJECT
$message = '{"data":{"message":"here is the message","title":"message title"},"registration_ids":["'. $reg . '","'. $reg2 . '"]}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_URL, $gcmurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
$result = curl_exec($ch);
if(!$result > 0){
echo "<p>An error has occurred.<p>";
echo "<p>ERROR: $curl_error</p>";
}
else{
$json_return = json_decode($result);
echo var_dump($json_return);
$info = curl_getinfo($ch);;
echo "<p>httpcode: " . $info['http_code'] . "</p>";
}
curl_close($ch);
For me to get this working I have to implement the following.
$ch = curl_init();
$message = '{"data":{"message":"here is the message","title":"message title"},"registration_ids":["'. $reg . '","'. $reg2 . '"]}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_URL, $gcmurl);
/*
* COMMENT OUT THE FOLLOWING LINE
*/
*//curl_setopt($ch, CURLOPT_POST, true);*
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
/*
* ADD THESE 2 LINES
*/
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
if(!$result > 0){
echo "<p>An error has occurred.<p>";
echo "<p>ERROR: $curl_error";
}
else{
$json_return = json_decode($result);
echo var_dump($json_return);
$info = curl_getinfo($ch);;
}
curl_close($ch);
[1]: http://stackoverflow.com/questions/11242743/gcm-with-php-google-cloud-messaging
[2]: http://stackoverflow.com/questions/3018378/php-curl-error-empty-reply-from-server | 0 |
11,387,325 | 07/08/2012 22:45:37 | 880,837 | 08/05/2011 15:10:30 | 40 | 0 | Using NSTableView for logging? | I've been trying to work out how to use table views and I'm a little stuck if I'm honest. I wanted to use a tableview with a limited number of rows (say 50 max). It starts of empty, with 0 rows. Then I wanted to do something along the lines of:
[self logMessage:@"Waiting for response"];
Which inserts a new row at the bottom with the above text. If I do another call to this pseudo function:
[self logMessage:@"Server response received"];
It should insert yet another new row below the previous row, and ensure it is visible. Once the above limit of 50 is reached, and a new message is inserted, I wanted the oldest message to be removed. All of this would be scrollable, with the latest being visible by default.
Am I looking at the right thing to do this? Eventually, I was hoping to have this in a nice little drawer below the main window, which I can then toggle from the main menu if needed. But as I said, I can't work out how to use a table view properly, it doesn't seem to be as straight forward as other objects are.
Any example code would be greatly appreciated!
| objective-c | xcode | osx | nstableview | null | null | open | Using NSTableView for logging?
===
I've been trying to work out how to use table views and I'm a little stuck if I'm honest. I wanted to use a tableview with a limited number of rows (say 50 max). It starts of empty, with 0 rows. Then I wanted to do something along the lines of:
[self logMessage:@"Waiting for response"];
Which inserts a new row at the bottom with the above text. If I do another call to this pseudo function:
[self logMessage:@"Server response received"];
It should insert yet another new row below the previous row, and ensure it is visible. Once the above limit of 50 is reached, and a new message is inserted, I wanted the oldest message to be removed. All of this would be scrollable, with the latest being visible by default.
Am I looking at the right thing to do this? Eventually, I was hoping to have this in a nice little drawer below the main window, which I can then toggle from the main menu if needed. But as I said, I can't work out how to use a table view properly, it doesn't seem to be as straight forward as other objects are.
Any example code would be greatly appreciated!
| 0 |
11,387,326 | 07/08/2012 22:45:54 | 1,126,880 | 01/02/2012 22:19:40 | 28 | 3 | Reskit not calling callbacks |
I am trying to use restkit with cocoapods and rubymotion, and just cant get a simple get request to work. I can see on my rails app logs that the simulator request is getting there, but restkit never calls its callback. Worse is, I dont get any error messages most of the time, and if I am lucky all I get is this one;
Command failed with status (1): [DYLD_FRAMEWORK_PATH="/Applications/Xcode.a...]
Which in the end tells me nothing. Here is the code I am performing:
class GameManager
attr_accessor :games, :delegate
def load_games
RKClient.sharedClient.get("/games.json", delegate:self)
end
def objectLoader(objectLoader, didLoadObjects:objects)
puts "Objects: #{objects}"
end
def objectLoader(objectLoader, didFailWithError:failError)
puts "Error: #{failError}"
end
def request(request, didLoadResponse:response)
if request.isGET
if response.isOK
puts response.bodyAsString
else
puts response.inspect
end
end
end
end
Any help would be great with this | ios | xcode | restkit | rubymotion | null | null | open | Reskit not calling callbacks
===
I am trying to use restkit with cocoapods and rubymotion, and just cant get a simple get request to work. I can see on my rails app logs that the simulator request is getting there, but restkit never calls its callback. Worse is, I dont get any error messages most of the time, and if I am lucky all I get is this one;
Command failed with status (1): [DYLD_FRAMEWORK_PATH="/Applications/Xcode.a...]
Which in the end tells me nothing. Here is the code I am performing:
class GameManager
attr_accessor :games, :delegate
def load_games
RKClient.sharedClient.get("/games.json", delegate:self)
end
def objectLoader(objectLoader, didLoadObjects:objects)
puts "Objects: #{objects}"
end
def objectLoader(objectLoader, didFailWithError:failError)
puts "Error: #{failError}"
end
def request(request, didLoadResponse:response)
if request.isGET
if response.isOK
puts response.bodyAsString
else
puts response.inspect
end
end
end
end
Any help would be great with this | 0 |
11,387,329 | 07/08/2012 22:46:25 | 401,450 | 07/25/2010 09:27:49 | 346 | 7 | nested data in mustache template | I'm totaly new in mustache and this is my first project i'm trying it out.
I have a collection of sport tournaments and each of it has many events and each event has 3 entities that i call "outcome". My task is to show all of them in one table. Following template show how i need this table to be show.
{{#tournaments}}
<h2>{{name}}</h2>
<table class="event_list">
{{#events.find_all}}
<tr>
<td>{{day}}</td>
{{#outcomes.find_all}}
<td class="outcome">{{name}}</td>
{{/outcomes.find_all}}
</tr>
{{/events.find_all}}
</table>
{{/tournaments}}
And now goes my problem and thus question. While showing "outcomes" i need to attach additional different classes to each <td>. So i mean i have 3 "outcomes" for each event and thus i have 3 different CSS classes for each of them. But inside {{#outcomes.find_all}} loop i have no clue is it first entity or second or third. What can i do about this?
Trying to solve this I was thinking about using functions. I thought of adding function to this view's class that would render all events "outcomes" and this may look like this:
{{#tournaments}}
<h2>{{name}}</h2>
<table class="event_list">
{{#events.find_all}}
<tr>
<td>{{day}}</td>
{{print_outcomes}}
</tr>
{{/events.find_all}}
</table>
{{/tournaments}}
But obviously i will need to pass collection of "outcomes" in that function and then i realized that i can't pass anything in that function. So how such problems solved in mustache? | mustache | kohana-3.2 | null | null | null | null | open | nested data in mustache template
===
I'm totaly new in mustache and this is my first project i'm trying it out.
I have a collection of sport tournaments and each of it has many events and each event has 3 entities that i call "outcome". My task is to show all of them in one table. Following template show how i need this table to be show.
{{#tournaments}}
<h2>{{name}}</h2>
<table class="event_list">
{{#events.find_all}}
<tr>
<td>{{day}}</td>
{{#outcomes.find_all}}
<td class="outcome">{{name}}</td>
{{/outcomes.find_all}}
</tr>
{{/events.find_all}}
</table>
{{/tournaments}}
And now goes my problem and thus question. While showing "outcomes" i need to attach additional different classes to each <td>. So i mean i have 3 "outcomes" for each event and thus i have 3 different CSS classes for each of them. But inside {{#outcomes.find_all}} loop i have no clue is it first entity or second or third. What can i do about this?
Trying to solve this I was thinking about using functions. I thought of adding function to this view's class that would render all events "outcomes" and this may look like this:
{{#tournaments}}
<h2>{{name}}</h2>
<table class="event_list">
{{#events.find_all}}
<tr>
<td>{{day}}</td>
{{print_outcomes}}
</tr>
{{/events.find_all}}
</table>
{{/tournaments}}
But obviously i will need to pass collection of "outcomes" in that function and then i realized that i can't pass anything in that function. So how such problems solved in mustache? | 0 |
11,410,550 | 07/10/2012 09:41:07 | 1,080,661 | 12/04/2011 23:48:47 | 1 | 0 | How to calculate cosine similarity of 2 vectors when the element of each vectors has different range | How do I find the cosine similarity between two vectors and each element of the vector has different range?
For example, each vector has two elements, V = {v[0], v[1]}, such as {age, height},where age ranges from 30 to 70, and height ranges from 100cm - 200 cm, two example vectors, v1 = {20, 175}, v2 = {35,192} are given.
I know that cosine similarity (sim) is defined as sim = (v1 dot v2 ) / (|v1| * |v2|), where dot is the dot product between v1 and v2, |v| is the magnitude of a vector. But this is based on the assumption of the each element in vector V has same range of data and it is not applied when each element has different range, such as the case I used here.
One thing I can think of is to apply a weights vector W = {w[0],w[1]} to each vector v1, and v2 here to normalize each element in vector.
That is
weighted_sim = ( sum (w[i] * v1[i] * v2[i]) ) / sqrt ( (sum (w[i] *v1[i]^2 ) ) * ( sum (w[i] *v2[i]^2 ) ) )
But I have difficult to figure out the weights vector W here.
Could someone help me here? Thanks a lot.
| java | algorithm | math | null | null | null | open | How to calculate cosine similarity of 2 vectors when the element of each vectors has different range
===
How do I find the cosine similarity between two vectors and each element of the vector has different range?
For example, each vector has two elements, V = {v[0], v[1]}, such as {age, height},where age ranges from 30 to 70, and height ranges from 100cm - 200 cm, two example vectors, v1 = {20, 175}, v2 = {35,192} are given.
I know that cosine similarity (sim) is defined as sim = (v1 dot v2 ) / (|v1| * |v2|), where dot is the dot product between v1 and v2, |v| is the magnitude of a vector. But this is based on the assumption of the each element in vector V has same range of data and it is not applied when each element has different range, such as the case I used here.
One thing I can think of is to apply a weights vector W = {w[0],w[1]} to each vector v1, and v2 here to normalize each element in vector.
That is
weighted_sim = ( sum (w[i] * v1[i] * v2[i]) ) / sqrt ( (sum (w[i] *v1[i]^2 ) ) * ( sum (w[i] *v2[i]^2 ) ) )
But I have difficult to figure out the weights vector W here.
Could someone help me here? Thanks a lot.
| 0 |
11,410,359 | 07/10/2012 09:29:05 | 397,645 | 07/21/2010 07:38:26 | 135 | 2 | Codeigniter - MySQL DATE_FORMAT | When I try to select formatted date using active record
$this->db->select( "date_format(created, '%d.%m.%Y') as created_date", FALSE );
$res = $this->db->get( 'ticket' );
the month gets prefixed with the table prefix I set in database configuration file (sl), like so:
[created_date] => 05.sl_07.2012
Any idea why?
Thanks in advance. | codeigniter | table | prefix | date-format | null | null | open | Codeigniter - MySQL DATE_FORMAT
===
When I try to select formatted date using active record
$this->db->select( "date_format(created, '%d.%m.%Y') as created_date", FALSE );
$res = $this->db->get( 'ticket' );
the month gets prefixed with the table prefix I set in database configuration file (sl), like so:
[created_date] => 05.sl_07.2012
Any idea why?
Thanks in advance. | 0 |
11,410,557 | 07/10/2012 09:41:38 | 1,029,825 | 11/04/2011 14:05:27 | 450 | 20 | Insert comment into expression language | Is anything like this possible?
${ long_boolean_expression_a <comment here>
|| long_boolean_expression_b <comment here>
|| long_boolean_expression_c <comment here>}
? | jsp | el | null | null | null | null | open | Insert comment into expression language
===
Is anything like this possible?
${ long_boolean_expression_a <comment here>
|| long_boolean_expression_b <comment here>
|| long_boolean_expression_c <comment here>}
? | 0 |
11,410,560 | 07/10/2012 09:41:46 | 1,514,062 | 03/15/2010 12:09:01 | 34 | 18 | Android + JQM+ jsonp not work on 3g | I am crunntly working on Hybrid Android App using JQM + PhoneGap
I am doing a JSONP request with AJAX
It works well on all Chrome PC browser, also works well on my android application when WiFi is connected,
but when changing network connection to 3G the AJAX request is not responding.
I found @BruceHill related post that wrote the following :
"mobile operators do content modification before delivering it to the phone and this modification breaks jQuery"
http://stackoverflow.com/questions/7930179/jquery-mobile-page-not-loading-correctly-on-netherlands-3g-connections
Although I am not living in Holland, I tried doing what he suggests by locating all the JS files on a remote server and called it via CDN, but unfortunately it didn't help.
I will be happy to get some help on this one...
this is my AJAX request:
$.mobile.allowCrossDomainPages = true;
$('#expertsListPage').live('pageshow', function (event) {
$.mobile.showPageLoadingMsg();
getExpertsList();
});
var catId;
var catName
function getExpertsList() {
$('#expertsList li').remove();
catId = getUrlVars()["id"];
catName = getUrlVars()["cat"] ;
$('h1').text( unescape(catName) );
var url = 'http://apis.mydomain.com/mydata.svc/jsonp
$.ajax({
cache: true,
type: 'GET',
url: url,
dataType: 'jsonp' ,
jsonp: 'callback',
success:api_do
});
}
var expertss;
function api_do(obj) {
$('#expertsList li').remove();
expertss = obj.experts;
$.each(expertss, function (index, expert) {
$('#expertsList').append('<li><a href="ExpertDetails.html?id=' + expert.id + '&catid=' + catId +'&catName=' + catName + '">' +
'<img style="width:160px;height:160px;" src="' + expert.thumbnail + '"/>' +
'<h4>' + expert.name + '</h4>' +
'<p>' + expert.description + '</p>' +
'</a></li>');
});
$('#expertsList').listview('refresh');
$.mobile.hidePageLoadingMsg();
}
function getUrlVars() {
var varsExperts = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
varsExperts.push(hash[0]);
varsExperts[hash[0]] = hash[1];
}
return varsExperts;
}
| android | jquery | ajax | phonegap | null | null | open | Android + JQM+ jsonp not work on 3g
===
I am crunntly working on Hybrid Android App using JQM + PhoneGap
I am doing a JSONP request with AJAX
It works well on all Chrome PC browser, also works well on my android application when WiFi is connected,
but when changing network connection to 3G the AJAX request is not responding.
I found @BruceHill related post that wrote the following :
"mobile operators do content modification before delivering it to the phone and this modification breaks jQuery"
http://stackoverflow.com/questions/7930179/jquery-mobile-page-not-loading-correctly-on-netherlands-3g-connections
Although I am not living in Holland, I tried doing what he suggests by locating all the JS files on a remote server and called it via CDN, but unfortunately it didn't help.
I will be happy to get some help on this one...
this is my AJAX request:
$.mobile.allowCrossDomainPages = true;
$('#expertsListPage').live('pageshow', function (event) {
$.mobile.showPageLoadingMsg();
getExpertsList();
});
var catId;
var catName
function getExpertsList() {
$('#expertsList li').remove();
catId = getUrlVars()["id"];
catName = getUrlVars()["cat"] ;
$('h1').text( unescape(catName) );
var url = 'http://apis.mydomain.com/mydata.svc/jsonp
$.ajax({
cache: true,
type: 'GET',
url: url,
dataType: 'jsonp' ,
jsonp: 'callback',
success:api_do
});
}
var expertss;
function api_do(obj) {
$('#expertsList li').remove();
expertss = obj.experts;
$.each(expertss, function (index, expert) {
$('#expertsList').append('<li><a href="ExpertDetails.html?id=' + expert.id + '&catid=' + catId +'&catName=' + catName + '">' +
'<img style="width:160px;height:160px;" src="' + expert.thumbnail + '"/>' +
'<h4>' + expert.name + '</h4>' +
'<p>' + expert.description + '</p>' +
'</a></li>');
});
$('#expertsList').listview('refresh');
$.mobile.hidePageLoadingMsg();
}
function getUrlVars() {
var varsExperts = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
varsExperts.push(hash[0]);
varsExperts[hash[0]] = hash[1];
}
return varsExperts;
}
| 0 |
11,410,562 | 07/10/2012 09:41:53 | 1,514,298 | 07/10/2012 09:14:46 | 1 | 0 | How to control wrong pagebreaks of longtable in latex() from Hmisc package? | I'm using Sweave and latex() from the Hmisc package to insert a longtable in my PDF.
When I do it the first time, the table is spread nicely, filling up the pages with the table.
If I do it again, some pages are only half full (like page 4 of PDF), which looks weird and somehow wrong because it seems to be unnecessary space.
Is there a way to control this? Or what could I do to improve the look?
Especially, if I'm adding some text and graphs, it won't look good with the empty space on page 4.
\documentclass{article}
\usepackage{Sweave}
\usepackage{longtable}
\usepackage{booktabs}
\begin{document}
\SweaveOpts{concordance=TRUE}
I want to insert this longtable
<<tab.R,echo=FALSE,results=tex>>=
library(Hmisc)
#library(xtable)
x <- matrix(rnorm(1000), ncol = 10)
x.big <- data.frame(x)
latex(x.big,"",file="",longtable=TRUE, dec=2,caption='First longtable spanning several pages')
@
then write some text. Maybe add a graph...
And then another table
<<tab.R,echo=FALSE,results=tex>>=
latex(x.big,"",file="",longtable=TRUE, dec=2,caption='Second longtable spanning wrongly')
@
\end{document} | r | latex | sweave | pagebreak | longtable | null | open | How to control wrong pagebreaks of longtable in latex() from Hmisc package?
===
I'm using Sweave and latex() from the Hmisc package to insert a longtable in my PDF.
When I do it the first time, the table is spread nicely, filling up the pages with the table.
If I do it again, some pages are only half full (like page 4 of PDF), which looks weird and somehow wrong because it seems to be unnecessary space.
Is there a way to control this? Or what could I do to improve the look?
Especially, if I'm adding some text and graphs, it won't look good with the empty space on page 4.
\documentclass{article}
\usepackage{Sweave}
\usepackage{longtable}
\usepackage{booktabs}
\begin{document}
\SweaveOpts{concordance=TRUE}
I want to insert this longtable
<<tab.R,echo=FALSE,results=tex>>=
library(Hmisc)
#library(xtable)
x <- matrix(rnorm(1000), ncol = 10)
x.big <- data.frame(x)
latex(x.big,"",file="",longtable=TRUE, dec=2,caption='First longtable spanning several pages')
@
then write some text. Maybe add a graph...
And then another table
<<tab.R,echo=FALSE,results=tex>>=
latex(x.big,"",file="",longtable=TRUE, dec=2,caption='Second longtable spanning wrongly')
@
\end{document} | 0 |
11,410,566 | 07/10/2012 09:42:10 | 552,279 | 12/23/2010 10:41:58 | 417 | 1 | Cannot upload cron.xml file to app engine | After creating a new cron.xml file in my java project, when I upload my app to GAE, some errors occur:
<br/>Detail:
<br/>Verifying availability:
<br/> Will check again in 1 seconds.
<br/> Will check again in 2 seconds.
<br/> Will check again in 4 seconds.
<br/> Will check again in 8 seconds.
<br/> Closing update: new version is ready to start serving.
<br/>Updating datastore:
<br/> Uploading index definitions.
<br/> Uploading cron jobs.com.google.appengine.tools.admin.HttpIoException: Error posting to URL: https://appengine.google.com/api/datastore/cron/update?app_id=aptosin&version=1&
<br/>500 Internal Server Error
<br/>Server Error (500)
<br/>A server error has occurred.
<br/>Can somebody tell me what is going wrong here?
<br/>Thank you. | google-app-engine | gae-datastore | null | null | null | null | open | Cannot upload cron.xml file to app engine
===
After creating a new cron.xml file in my java project, when I upload my app to GAE, some errors occur:
<br/>Detail:
<br/>Verifying availability:
<br/> Will check again in 1 seconds.
<br/> Will check again in 2 seconds.
<br/> Will check again in 4 seconds.
<br/> Will check again in 8 seconds.
<br/> Closing update: new version is ready to start serving.
<br/>Updating datastore:
<br/> Uploading index definitions.
<br/> Uploading cron jobs.com.google.appengine.tools.admin.HttpIoException: Error posting to URL: https://appengine.google.com/api/datastore/cron/update?app_id=aptosin&version=1&
<br/>500 Internal Server Error
<br/>Server Error (500)
<br/>A server error has occurred.
<br/>Can somebody tell me what is going wrong here?
<br/>Thank you. | 0 |
11,410,541 | 07/10/2012 09:40:37 | 374,402 | 06/23/2010 15:54:09 | 693 | 24 | Tab Control not working properly in shared dll written using MFC? | I am writing a DLL written in MFC to be used by other application.
project settings:
1. Use MFC in static library
2. preprocessor : AFXDLL
3. MD Build
I have also used AFX_MANAGE_STATE (AfxGetStaticModuleState()) before calling
CWinApp which internally calls InitInstance and DLL main.
This Dialog has tab in it and I am able to see only the first tab all other tab are coming as blank. When I am running the same DLL as exe (with required changes) its working fine.
Also DLL is crashing when i am calling AfxGetApp() ?
I suppose major problem is due to DOMODAL(). Can anyone tell what might be the issue of tab control not working?
I am new to MFC so let me know if you need any more info | c++ | windows | dll | mfc | null | null | open | Tab Control not working properly in shared dll written using MFC?
===
I am writing a DLL written in MFC to be used by other application.
project settings:
1. Use MFC in static library
2. preprocessor : AFXDLL
3. MD Build
I have also used AFX_MANAGE_STATE (AfxGetStaticModuleState()) before calling
CWinApp which internally calls InitInstance and DLL main.
This Dialog has tab in it and I am able to see only the first tab all other tab are coming as blank. When I am running the same DLL as exe (with required changes) its working fine.
Also DLL is crashing when i am calling AfxGetApp() ?
I suppose major problem is due to DOMODAL(). Can anyone tell what might be the issue of tab control not working?
I am new to MFC so let me know if you need any more info | 0 |
11,410,542 | 07/10/2012 09:40:37 | 1,501,667 | 07/04/2012 13:07:12 | 1 | 0 | Password generator | I need to generate some passwords(password generator), I want to avoid characters that can be confused each other.
for exempel: Chair2bok.
| dictionary | passwords | null | null | null | null | open | Password generator
===
I need to generate some passwords(password generator), I want to avoid characters that can be confused each other.
for exempel: Chair2bok.
| 0 |
11,660,364 | 07/25/2012 23:46:59 | 1,390,487 | 05/12/2012 00:18:59 | 319 | 12 | PHP Using a string in arithmetic | I have situation where I have a variable being used in some arithmetic (mostly just multiplication/division) in a PHP function. The variable is actually passed to the function from another. What gets passed, though, may be either a numerical value, or a string value.
So basically I have:
$inverse = 1/$number;
Where `$number` may be either a valid number, or a string.
My question is what happens when `$number` is a string? How does php handle that situation?
Ultimately the answer isn't too important; I can think of a couple of different ways of working around the situation. It's just that it came up, I got curious, and a quick google search couldn't answer my question. Even if I don't need to know the answer, I'd like to know the answer, because understanding how PHP works will help me in the future.
Thanks. | php | string | math | null | null | null | open | PHP Using a string in arithmetic
===
I have situation where I have a variable being used in some arithmetic (mostly just multiplication/division) in a PHP function. The variable is actually passed to the function from another. What gets passed, though, may be either a numerical value, or a string value.
So basically I have:
$inverse = 1/$number;
Where `$number` may be either a valid number, or a string.
My question is what happens when `$number` is a string? How does php handle that situation?
Ultimately the answer isn't too important; I can think of a couple of different ways of working around the situation. It's just that it came up, I got curious, and a quick google search couldn't answer my question. Even if I don't need to know the answer, I'd like to know the answer, because understanding how PHP works will help me in the future.
Thanks. | 0 |
11,660,366 | 07/25/2012 23:47:05 | 863,980 | 07/21/2011 06:35:51 | 928 | 18 | movl multi-data instruction and assembly optimization comparison | Consider a simple loop in :
for(int i=0;i<32;i++)
a[i] = i;
The LLVM disassembler shows the following assembly:
.LBB0_1: # =>This Inner Loop Header: Depth=1
movl %eax, (%esp,%eax,4)
addl $1, %eax
adcl $0, %ecx
cmpl $32, %eax
jne .LBB0_1
# BB#2:
xorl %eax, %eax
addl $140, %esp
ret
**Question 1:** Can anyone explain `movl %eax, (%esp,%eax,4)` instruction?
Moreover, Visual Studio disassembler outputs the following assembly:
;for(int i=0;i<32;i++)
00F290B5 mov dword ptr [ebp-94h],0
00F290BF jmp main+60h (0F290D0h)
00F290C1 mov eax,dword ptr [ebp-94h]
00F290C7 add eax,1
00F290CA mov dword ptr [ebp-94h],eax
00F290D0 cmp dword ptr [ebp-94h],20h
00F290D7 jge main+7Eh (0F290EEh)
;a[i] = i;
00F290D9 mov eax,dword ptr [ebp-94h]
00F290DF mov ecx,dword ptr [ebp-94h]
00F290E5 mov dword ptr a[eax*4],ecx
00F290EC jmp main+51h (0F290C1h)
;return 0;
00F290EE xor eax,eax
Obvoiusly the LLVM's output is more optimized.
**Question 2:** Is there an option in Visual Studio to optimize the code like LLVM does? | c++ | assembly | simd | disassembly | null | null | open | movl multi-data instruction and assembly optimization comparison
===
Consider a simple loop in :
for(int i=0;i<32;i++)
a[i] = i;
The LLVM disassembler shows the following assembly:
.LBB0_1: # =>This Inner Loop Header: Depth=1
movl %eax, (%esp,%eax,4)
addl $1, %eax
adcl $0, %ecx
cmpl $32, %eax
jne .LBB0_1
# BB#2:
xorl %eax, %eax
addl $140, %esp
ret
**Question 1:** Can anyone explain `movl %eax, (%esp,%eax,4)` instruction?
Moreover, Visual Studio disassembler outputs the following assembly:
;for(int i=0;i<32;i++)
00F290B5 mov dword ptr [ebp-94h],0
00F290BF jmp main+60h (0F290D0h)
00F290C1 mov eax,dword ptr [ebp-94h]
00F290C7 add eax,1
00F290CA mov dword ptr [ebp-94h],eax
00F290D0 cmp dword ptr [ebp-94h],20h
00F290D7 jge main+7Eh (0F290EEh)
;a[i] = i;
00F290D9 mov eax,dword ptr [ebp-94h]
00F290DF mov ecx,dword ptr [ebp-94h]
00F290E5 mov dword ptr a[eax*4],ecx
00F290EC jmp main+51h (0F290C1h)
;return 0;
00F290EE xor eax,eax
Obvoiusly the LLVM's output is more optimized.
**Question 2:** Is there an option in Visual Studio to optimize the code like LLVM does? | 0 |
11,660,367 | 07/25/2012 23:47:09 | 856,275 | 07/21/2011 15:19:49 | 444 | 15 | Extending NSMutableArray to act like a Java Array | I am working on an rpg type game for the iphone. What I want to do is have an inventory that will only allow you to hold a specific amount of only a specific type of items. I think to do this I'm just going to extend the NSMutableArray (since it is a slut and will take any amount of anything) and add limits to it. I can't figure out the best way to do this though. Here's the idea I have in my head...
**Backpack.h**
@interface Backpack : NSMutableArray {
Class * arrayClass;
NSMutableArray * array;
int limit;
}
-(id) initWithClass:(Class) type andLimit:(int) num;
@end
**Backpack.m**
@implementation Backpack
-(id)initWithClass:(Class) type andLimit:(int) num {
arrayClass = type;
limit = num;
array = [NSMutableArray new];
return self;
}
-(void)insertObject:(id) object atIndex:(int) index {
if([object isKindOfClass:arrayClass] && index < limit) {
// Insert it
} else {
// Throw Exception
}
}
@end | java | objective-c | arrays | nsmutablearray | null | null | open | Extending NSMutableArray to act like a Java Array
===
I am working on an rpg type game for the iphone. What I want to do is have an inventory that will only allow you to hold a specific amount of only a specific type of items. I think to do this I'm just going to extend the NSMutableArray (since it is a slut and will take any amount of anything) and add limits to it. I can't figure out the best way to do this though. Here's the idea I have in my head...
**Backpack.h**
@interface Backpack : NSMutableArray {
Class * arrayClass;
NSMutableArray * array;
int limit;
}
-(id) initWithClass:(Class) type andLimit:(int) num;
@end
**Backpack.m**
@implementation Backpack
-(id)initWithClass:(Class) type andLimit:(int) num {
arrayClass = type;
limit = num;
array = [NSMutableArray new];
return self;
}
-(void)insertObject:(id) object atIndex:(int) index {
if([object isKindOfClass:arrayClass] && index < limit) {
// Insert it
} else {
// Throw Exception
}
}
@end | 0 |
11,660,368 | 07/25/2012 23:47:19 | 670,017 | 03/21/2011 19:13:20 | 1,330 | 14 | Conditional INSERT following a CTE clause in t-SQL | I was curious why I can't seem to get a conditional statement to follow a common table expression in t-SQL statement?
Stuff like this:
WITH ctx AS(...)
IF ctx.v BEGIN
INSERT INTO ...
END
I made a [sample fiddle here][1].
[1]: http://sqlfiddle.com/#!3/8f656/28 | sql | sql-server | tsql | insert | common-table-expression | null | open | Conditional INSERT following a CTE clause in t-SQL
===
I was curious why I can't seem to get a conditional statement to follow a common table expression in t-SQL statement?
Stuff like this:
WITH ctx AS(...)
IF ctx.v BEGIN
INSERT INTO ...
END
I made a [sample fiddle here][1].
[1]: http://sqlfiddle.com/#!3/8f656/28 | 0 |
11,660,370 | 07/25/2012 23:47:23 | 193,892 | 10/21/2009 15:11:03 | 5,461 | 287 | Canonical way to check file size in Windows API? | Is there a canonical way to check the size of a file in Windows? Googling brings me both [FindFirstFile][1] and GetFileSizeEx but no clear winner.
[1]: http://blogs.msdn.com/b/oldnewthing/archive/2011/12/26/10251026.aspx | c++ | c | windows | null | null | null | open | Canonical way to check file size in Windows API?
===
Is there a canonical way to check the size of a file in Windows? Googling brings me both [FindFirstFile][1] and GetFileSizeEx but no clear winner.
[1]: http://blogs.msdn.com/b/oldnewthing/archive/2011/12/26/10251026.aspx | 0 |
11,660,373 | 07/25/2012 23:47:33 | 899,804 | 08/18/2011 02:58:53 | 1 | 2 | Monotouch "Swipe To Delete" CommitEditingStyle Not Firing | I am trying to implement "swipe to delete" functionality in a uitableview. I have followed other tutorials/forums and extended UITableViewSource. Within that class I have overridden the following methods:
public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
{
if (editingStyle == UITableViewCellEditingStyle.Delete)
{
tableItems.RemoveAt(indexPath.Row);
tableView.DeleteRows(new [] { indexPath }, UITableViewRowAnimation.Fade);
}
}
public override UITableViewCellEditingStyle EditingStyleForRow(UITableView tableView, NSIndexPath indexPath)
{
return UITableViewCellEditingStyle.Delete;
}
public override bool CanEditRow(UITableView tableView, NSIndexPath indexPath)
{
return true;
}
I believe these are the only methods I should need. However when I perform a swipe gesture, the CanEditRow and EditingStyleForRow methods are called but CommitEditingStyle is never called. Any help would be much appreciated. Thanks. | monotouch | null | null | null | null | null | open | Monotouch "Swipe To Delete" CommitEditingStyle Not Firing
===
I am trying to implement "swipe to delete" functionality in a uitableview. I have followed other tutorials/forums and extended UITableViewSource. Within that class I have overridden the following methods:
public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
{
if (editingStyle == UITableViewCellEditingStyle.Delete)
{
tableItems.RemoveAt(indexPath.Row);
tableView.DeleteRows(new [] { indexPath }, UITableViewRowAnimation.Fade);
}
}
public override UITableViewCellEditingStyle EditingStyleForRow(UITableView tableView, NSIndexPath indexPath)
{
return UITableViewCellEditingStyle.Delete;
}
public override bool CanEditRow(UITableView tableView, NSIndexPath indexPath)
{
return true;
}
I believe these are the only methods I should need. However when I perform a swipe gesture, the CanEditRow and EditingStyleForRow methods are called but CommitEditingStyle is never called. Any help would be much appreciated. Thanks. | 0 |
11,660,383 | 07/25/2012 23:48:44 | 882,445 | 08/07/2011 05:30:34 | 386 | 15 | Multiple Highlights/Selects in C# with different colors | I am looking for a way to highlight a word and a sentence at the same time in C#. An example of what I am trying to accomplish is shown below.
![Created from MS Word][1]
I am working with windows forms, but I would be able to port over to WPF if nessassary.
I have been trying to accomplish this with a rich text box, but I cant seem to find a method to do what I want. Is there anything out there that could accomplish this?
[1]: http://i.stack.imgur.com/AwV3k.png | c# | visual-studio-2012 | null | null | null | null | open | Multiple Highlights/Selects in C# with different colors
===
I am looking for a way to highlight a word and a sentence at the same time in C#. An example of what I am trying to accomplish is shown below.
![Created from MS Word][1]
I am working with windows forms, but I would be able to port over to WPF if nessassary.
I have been trying to accomplish this with a rich text box, but I cant seem to find a method to do what I want. Is there anything out there that could accomplish this?
[1]: http://i.stack.imgur.com/AwV3k.png | 0 |
11,660,386 | 07/25/2012 23:49:12 | 1,553,087 | 07/25/2012 23:28:45 | 1 | 0 | Create dynamic radiobuttonlist from object properties | I have a list of objects of multiple choice questions. I need to create a RadioButtonList with the object properties: Choice_A, Choice_B,... Choice_D.
var qs = (from questions in dc.Survey_Questions
where questions.Survey_ID == surveyid
select new SQuestions
{
QuestionID = questions.Question_ID,
SurveyID = questions.Survey_ID,
Description = questions.Description,
Choice_A = questions.Choice_A,
Choice_B = questions.Choice_B,
Choice_C = questions.Choice_C,
Choice_D = questions.Choice_D,
}).ToList();
DataList dtQuestion.DataSource = qs;
HTML Structure:
` <asp:DataList ID="dtQuestion" runat="server" RepeatDirection="Vertical" >`
` <ItemTemplate>
` `<%# Eval("Description") %> `
` <ItemTemplate>
`<RadioButtonList></RadiobuttonList>
`</ItemTemplate>
` </ItemTemplate>
`</asp:DataList> | c# | dynamic | properties | radiobuttonlist | null | null | open | Create dynamic radiobuttonlist from object properties
===
I have a list of objects of multiple choice questions. I need to create a RadioButtonList with the object properties: Choice_A, Choice_B,... Choice_D.
var qs = (from questions in dc.Survey_Questions
where questions.Survey_ID == surveyid
select new SQuestions
{
QuestionID = questions.Question_ID,
SurveyID = questions.Survey_ID,
Description = questions.Description,
Choice_A = questions.Choice_A,
Choice_B = questions.Choice_B,
Choice_C = questions.Choice_C,
Choice_D = questions.Choice_D,
}).ToList();
DataList dtQuestion.DataSource = qs;
HTML Structure:
` <asp:DataList ID="dtQuestion" runat="server" RepeatDirection="Vertical" >`
` <ItemTemplate>
` `<%# Eval("Description") %> `
` <ItemTemplate>
`<RadioButtonList></RadiobuttonList>
`</ItemTemplate>
` </ItemTemplate>
`</asp:DataList> | 0 |
11,628,098 | 07/24/2012 09:38:29 | 921,244 | 08/31/2011 09:01:54 | 368 | 31 | Does GWT support inclusion of stylesheet during GWTTestCase? | I have some simple GWT client code that I would like to test using `GWTTestCase` and GWTTestSuite.
However, those tests require the use of some `CSS stylesheet` (only needed for the tests).
My first attempt was :
1. Define a `ClientBundle` that provide the CSS file used for tests.
2. in my `gwtSetUp()`, call the `ensureInjected() method to add the CSS file before my tests get called
3. Test if the CSS style was applied to a particular element in the DOM, for example
code:
<!-- language: lang-java -->
assertEquals("blue", element.getStyle().getBorderColor());
**I got no errors, but this not seems to work.**
Looking throught the logs of the Console (during the Junit test) I found this :
> Initializing ResourceGenerator <br>
> Finding operable CssResource subtypes<br>
> Computing CSS class replacements<br>
> Preparing method css<br>
> Finding resources<br>
> Parsing CSS stylesheet file:/D:/Workspace/libraries/gwt-text/gwt-text/src/test/java/com/t/i/client/CSSDecorationTest.css<br>
> Scanning CSS for requirements<br>
> Creating fields<br>
> Creating assignment for css()<br>
> Creating image sprite classes<br>
> Replacing property-based @if blocks<br>
> Replacing CSS class names<br>
> Performing substitution in node border-color : ..... ;<br>
My css file simple contains :
<!-- language: lang-css -->
.d {
border-color: blue;
}
**Is GWT doing some guru things on my CSS file ? Is this a wrong approach ?** | gwt | junit | gwttestcase | null | null | null | open | Does GWT support inclusion of stylesheet during GWTTestCase?
===
I have some simple GWT client code that I would like to test using `GWTTestCase` and GWTTestSuite.
However, those tests require the use of some `CSS stylesheet` (only needed for the tests).
My first attempt was :
1. Define a `ClientBundle` that provide the CSS file used for tests.
2. in my `gwtSetUp()`, call the `ensureInjected() method to add the CSS file before my tests get called
3. Test if the CSS style was applied to a particular element in the DOM, for example
code:
<!-- language: lang-java -->
assertEquals("blue", element.getStyle().getBorderColor());
**I got no errors, but this not seems to work.**
Looking throught the logs of the Console (during the Junit test) I found this :
> Initializing ResourceGenerator <br>
> Finding operable CssResource subtypes<br>
> Computing CSS class replacements<br>
> Preparing method css<br>
> Finding resources<br>
> Parsing CSS stylesheet file:/D:/Workspace/libraries/gwt-text/gwt-text/src/test/java/com/t/i/client/CSSDecorationTest.css<br>
> Scanning CSS for requirements<br>
> Creating fields<br>
> Creating assignment for css()<br>
> Creating image sprite classes<br>
> Replacing property-based @if blocks<br>
> Replacing CSS class names<br>
> Performing substitution in node border-color : ..... ;<br>
My css file simple contains :
<!-- language: lang-css -->
.d {
border-color: blue;
}
**Is GWT doing some guru things on my CSS file ? Is this a wrong approach ?** | 0 |
11,628,099 | 07/24/2012 09:38:29 | 637,424 | 02/28/2011 09:28:30 | 3 | 0 | Reusable Client Side/Ajax enabled Table Design ( Don't use default Asp.Net Grid ) | I am looking for code to have below features with HTML table.
Design a reusable grid which has the below default features
1. Ajax enabled Table ( No Post backs)
2. Paging through Ajax Calls
3. Sorting through Ajax calls
4. Filtering through Ajax calls
Thanks you very much
G. Raj | ajax | table | null | null | null | null | open | Reusable Client Side/Ajax enabled Table Design ( Don't use default Asp.Net Grid )
===
I am looking for code to have below features with HTML table.
Design a reusable grid which has the below default features
1. Ajax enabled Table ( No Post backs)
2. Paging through Ajax Calls
3. Sorting through Ajax calls
4. Filtering through Ajax calls
Thanks you very much
G. Raj | 0 |
11,628,101 | 07/24/2012 09:38:34 | 1,206,976 | 02/13/2012 14:09:17 | 1 | 0 | hide a div when click on body and show it when click on a button | i have apply click event on a button and show a div.Also i have apply onclick event on body tag to hide that div.But when i click on button which is also in body then on click function of button call and div show. Same time onclick event of body call and div goes hide.
I want to show div on click on button and hide it when click any other place.
Can anyone help me
Thanks in Advance | jquery | events | click | null | null | null | open | hide a div when click on body and show it when click on a button
===
i have apply click event on a button and show a div.Also i have apply onclick event on body tag to hide that div.But when i click on button which is also in body then on click function of button call and div show. Same time onclick event of body call and div goes hide.
I want to show div on click on button and hide it when click any other place.
Can anyone help me
Thanks in Advance | 0 |
11,628,102 | 07/24/2012 09:38:34 | 1,548,185 | 07/24/2012 09:25:00 | 1 | 0 | Howto setup Apache Web Server for clustering a Web Service on two Tomcats | I'm trying to setup an Apache Web Server, so that it balances requests of a client on two Tomcat servers. For the Web Service I uses Axis2. It is deployed on two Tomcats. When I invoke the Web Service, there is always only one Server answering, although the cluster is established. I used [this][1] tutorial, Axis2 1.6.1, Tomcat 7, Apache Web Server 2.2 and I am running it on a Windows 32 bit system.
How is it possible to balance the client requests on both Tomcats?
It might have something to do with the proxy configuration of the Web Server, but its just a thought.
If you need screenshots or else, please let me know. And sorry for my german accent :)
[1]: http://jee-bpel-soa.blogspot.de/2009/07/apache-tomcat-clustering-load-balancing.html
| web-services | apache | axis2 | tomcat7 | null | null | open | Howto setup Apache Web Server for clustering a Web Service on two Tomcats
===
I'm trying to setup an Apache Web Server, so that it balances requests of a client on two Tomcat servers. For the Web Service I uses Axis2. It is deployed on two Tomcats. When I invoke the Web Service, there is always only one Server answering, although the cluster is established. I used [this][1] tutorial, Axis2 1.6.1, Tomcat 7, Apache Web Server 2.2 and I am running it on a Windows 32 bit system.
How is it possible to balance the client requests on both Tomcats?
It might have something to do with the proxy configuration of the Web Server, but its just a thought.
If you need screenshots or else, please let me know. And sorry for my german accent :)
[1]: http://jee-bpel-soa.blogspot.de/2009/07/apache-tomcat-clustering-load-balancing.html
| 0 |
11,628,078 | 07/24/2012 09:37:16 | 438,932 | 09/03/2010 12:14:57 | 46 | 0 | nHibernate Dynamic Query With OR | We have a form which allows users to specify criteria to query a database.
Our form builds "criterion" objects which are then used to build the nHibernate criteria.
Our current code to do this is:
<pre>
public virtual ICriteria BuildCriteria(ICriteria criteria)
{
foreach (SheCriterion criterion in this.SheCriterions)
{
if (criterion.OperatorKey == "OR")
{
//// code required here to process ORs
}
criteria.Add(criterion.BuildCriterion());
}
return criteria;
}
</pre>
Unfortunately, this is where I'm stuck - if we AND each criterion there is no problem but I'm having difficulties in working out how to add ORs - by the time we know that an OR is involved, the previous criterion has already been processed.
Can anyone help? | nhibernate | dynamic | hibernate-criteria | null | null | null | open | nHibernate Dynamic Query With OR
===
We have a form which allows users to specify criteria to query a database.
Our form builds "criterion" objects which are then used to build the nHibernate criteria.
Our current code to do this is:
<pre>
public virtual ICriteria BuildCriteria(ICriteria criteria)
{
foreach (SheCriterion criterion in this.SheCriterions)
{
if (criterion.OperatorKey == "OR")
{
//// code required here to process ORs
}
criteria.Add(criterion.BuildCriterion());
}
return criteria;
}
</pre>
Unfortunately, this is where I'm stuck - if we AND each criterion there is no problem but I'm having difficulties in working out how to add ORs - by the time we know that an OR is involved, the previous criterion has already been processed.
Can anyone help? | 0 |
11,628,081 | 07/24/2012 09:37:31 | 1,338,399 | 04/17/2012 09:47:21 | 14 | 0 | Different states in D3/Coffee Bubble chart | I want to use this ([http://vallandingham.me/vis/gates/][1]) Bubble Chart (made in D3) to walk through some different scenarios. In short, I want to visualize election data. How many votes did parties get, and what scenario's are possible to form a government?
At the data level, it's quite obvious: Name, number of seats in parliament, state1, state2, state3, etc. State1 is a 1 or 2. 1 is a place in government, 2 is opposition. Pretty straightforward.
But the example only shows two states: All Grants and Grants By year. What I want, is more states like Grants By Year. But me being not a very good programmer can't figure out how to make this work. The visualisation doesn't work when I add a new state.
Here's the code (Coffee) which controls states.
class BubbleChart
constructor: (data) ->
@data = data
@width = 940
@height = 600
@tooltip = CustomTooltip("gates_tooltip", 240)
# locations the nodes will move towards
# depending on which view is currently being
# used
@center = {x: @width / 2, y: @height / 2}
@year_centers = {
"2008": {x: @width / 3, y: @height / 2},
"2009": {x: @width / 2, y: @height / 2},
"2010": {x: 2 * @width / 3, y: @height / 2}
}
# used when setting up force and
# moving around nodes
@layout_gravity = -0.01
@damper = 0.1
# these will be set in create_nodes and create_vis
@vis = null
@nodes = []
@force = null
@circles = null
# nice looking colors - no reason to buck the trend
@fill_color = d3.scale.ordinal()
.domain(["low", "medium", "high"])
.range(["#d84b2a", "#beccae", "#7aa25c"])
# use the max total_amount in the data as the max in the scale's domain
max_amount = d3.max(@data, (d) -> parseInt(d.total_amount))
@radius_scale = d3.scale.pow().exponent(0.5).domain([0, max_amount]).range([2, 85])
this.create_nodes()
this.create_vis()
# create node objects from original data
# that will serve as the data behind each
# bubble in the vis, then add each node
# to @nodes to be used later
create_nodes: () =>
@data.forEach (d) =>
node = {
id: d.id
radius: @radius_scale(parseInt(d.total_amount))
value: d.total_amount
name: d.grant_title
org: d.organization
group: d.group
year: d.start_year
x: Math.random() * 900
y: Math.random() * 800
}
@nodes.push node
@nodes.sort (a,b) -> b.value - a.value
# create svg at #vis and then
# create circle representation for each node
create_vis: () =>
@vis = d3.select("#vis").append("svg")
.attr("width", @width)
.attr("height", @height)
.attr("id", "svg_vis")
@circles = @vis.selectAll("circle")
.data(@nodes, (d) -> d.id)
# used because we need 'this' in the
# mouse callbacks
that = this
# radius will be set to 0 initially.
# see transition below
@circles.enter().append("circle")
.attr("r", 0)
.attr("fill", (d) => @fill_color(d.group))
.attr("stroke-width", 2)
.attr("stroke", (d) => d3.rgb(@fill_color(d.group)).darker())
.attr("id", (d) -> "bubble_#{d.id}")
.on("mouseover", (d,i) -> that.show_details(d,i,this))
.on("mouseout", (d,i) -> that.hide_details(d,i,this))
# Fancy transition to make bubbles appear, ending with the
# correct radius
@circles.transition().duration(2000).attr("r", (d) -> d.radius)
# Charge function that is called for each node.
# Charge is proportional to the diameter of the
# circle (which is stored in the radius attribute
# of the circle's associated data.
# This is done to allow for accurate collision
# detection with nodes of different sizes.
# Charge is negative because we want nodes to
# repel.
# Dividing by 8 scales down the charge to be
# appropriate for the visualization dimensions.
charge: (d) ->
-Math.pow(d.radius, 2.0) / 8
# Starts up the force layout with
# the default values
start: () =>
@force = d3.layout.force()
.nodes(@nodes)
.size([@width, @height])
# Sets up force layout to display
# all nodes in one circle.
display_group_all: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_center(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
# Moves all circles towards the @center
# of the visualization
move_towards_center: (alpha) =>
(d) =>
d.x = d.x + (@center.x - d.x) * (@damper + 0.02) * alpha
d.y = d.y + (@center.y - d.y) * (@damper + 0.02) * alpha
# sets the display of bubbles to be separated
# into each year. Does this by calling move_towards_year
display_by_year: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_year(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.display_years()
# move all circles to their associated @year_centers
move_towards_year: (alpha) =>
(d) =>
target = @year_centers[d.year]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
# Method to display year titles
display_years: () =>
years_x = {"2008": 160, "2009": @width / 2, "2010": @width - 160}
years_data = d3.keys(years_x)
years = @vis.selectAll(".years")
.data(years_data)
years.enter().append("text")
.attr("class", "years")
.attr("x", (d) => years_x[d] )
.attr("y", 40)
.attr("text-anchor", "middle")
.text((d) -> d)
# Method to hide year titiles
hide_years: () =>
years = @vis.selectAll(".years").remove()
show_details: (data, i, element) =>
d3.select(element).attr("stroke", "black")
content = "<span class=\"name\">Title:</span><span class=\"value\"> #{data.name}</span><br/>"
content +="<span class=\"name\">Amount:</span><span class=\"value\"> $#{addCommas(data.value)}</span><br/>"
content +="<span class=\"name\">Year:</span><span class=\"value\"> #{data.year}</span>"
@tooltip.showTooltip(content,d3.event)
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", (d) => d3.rgb(@fill_color(d.group)).darker())
@tooltip.hideTooltip()
root = exports ? this
$ ->
chart = null
render_vis = (csv) ->
chart = new BubbleChart csv
chart.start()
root.display_all()
root.display_all = () =>
chart.display_group_all()
root.display_year = () =>
chart.display_by_year()
root.toggle_view = (view_type) =>
if view_type == 'year'
root.display_year()
else
root.display_all()
d3.csv "data/gates_money.csv", render_vis
[1]: http://vallandingham.me/vis/gates/ "Bubble Chart" | coffeescript | d3.js | bubble-chart | null | null | null | open | Different states in D3/Coffee Bubble chart
===
I want to use this ([http://vallandingham.me/vis/gates/][1]) Bubble Chart (made in D3) to walk through some different scenarios. In short, I want to visualize election data. How many votes did parties get, and what scenario's are possible to form a government?
At the data level, it's quite obvious: Name, number of seats in parliament, state1, state2, state3, etc. State1 is a 1 or 2. 1 is a place in government, 2 is opposition. Pretty straightforward.
But the example only shows two states: All Grants and Grants By year. What I want, is more states like Grants By Year. But me being not a very good programmer can't figure out how to make this work. The visualisation doesn't work when I add a new state.
Here's the code (Coffee) which controls states.
class BubbleChart
constructor: (data) ->
@data = data
@width = 940
@height = 600
@tooltip = CustomTooltip("gates_tooltip", 240)
# locations the nodes will move towards
# depending on which view is currently being
# used
@center = {x: @width / 2, y: @height / 2}
@year_centers = {
"2008": {x: @width / 3, y: @height / 2},
"2009": {x: @width / 2, y: @height / 2},
"2010": {x: 2 * @width / 3, y: @height / 2}
}
# used when setting up force and
# moving around nodes
@layout_gravity = -0.01
@damper = 0.1
# these will be set in create_nodes and create_vis
@vis = null
@nodes = []
@force = null
@circles = null
# nice looking colors - no reason to buck the trend
@fill_color = d3.scale.ordinal()
.domain(["low", "medium", "high"])
.range(["#d84b2a", "#beccae", "#7aa25c"])
# use the max total_amount in the data as the max in the scale's domain
max_amount = d3.max(@data, (d) -> parseInt(d.total_amount))
@radius_scale = d3.scale.pow().exponent(0.5).domain([0, max_amount]).range([2, 85])
this.create_nodes()
this.create_vis()
# create node objects from original data
# that will serve as the data behind each
# bubble in the vis, then add each node
# to @nodes to be used later
create_nodes: () =>
@data.forEach (d) =>
node = {
id: d.id
radius: @radius_scale(parseInt(d.total_amount))
value: d.total_amount
name: d.grant_title
org: d.organization
group: d.group
year: d.start_year
x: Math.random() * 900
y: Math.random() * 800
}
@nodes.push node
@nodes.sort (a,b) -> b.value - a.value
# create svg at #vis and then
# create circle representation for each node
create_vis: () =>
@vis = d3.select("#vis").append("svg")
.attr("width", @width)
.attr("height", @height)
.attr("id", "svg_vis")
@circles = @vis.selectAll("circle")
.data(@nodes, (d) -> d.id)
# used because we need 'this' in the
# mouse callbacks
that = this
# radius will be set to 0 initially.
# see transition below
@circles.enter().append("circle")
.attr("r", 0)
.attr("fill", (d) => @fill_color(d.group))
.attr("stroke-width", 2)
.attr("stroke", (d) => d3.rgb(@fill_color(d.group)).darker())
.attr("id", (d) -> "bubble_#{d.id}")
.on("mouseover", (d,i) -> that.show_details(d,i,this))
.on("mouseout", (d,i) -> that.hide_details(d,i,this))
# Fancy transition to make bubbles appear, ending with the
# correct radius
@circles.transition().duration(2000).attr("r", (d) -> d.radius)
# Charge function that is called for each node.
# Charge is proportional to the diameter of the
# circle (which is stored in the radius attribute
# of the circle's associated data.
# This is done to allow for accurate collision
# detection with nodes of different sizes.
# Charge is negative because we want nodes to
# repel.
# Dividing by 8 scales down the charge to be
# appropriate for the visualization dimensions.
charge: (d) ->
-Math.pow(d.radius, 2.0) / 8
# Starts up the force layout with
# the default values
start: () =>
@force = d3.layout.force()
.nodes(@nodes)
.size([@width, @height])
# Sets up force layout to display
# all nodes in one circle.
display_group_all: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_center(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
# Moves all circles towards the @center
# of the visualization
move_towards_center: (alpha) =>
(d) =>
d.x = d.x + (@center.x - d.x) * (@damper + 0.02) * alpha
d.y = d.y + (@center.y - d.y) * (@damper + 0.02) * alpha
# sets the display of bubbles to be separated
# into each year. Does this by calling move_towards_year
display_by_year: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_year(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.display_years()
# move all circles to their associated @year_centers
move_towards_year: (alpha) =>
(d) =>
target = @year_centers[d.year]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
# Method to display year titles
display_years: () =>
years_x = {"2008": 160, "2009": @width / 2, "2010": @width - 160}
years_data = d3.keys(years_x)
years = @vis.selectAll(".years")
.data(years_data)
years.enter().append("text")
.attr("class", "years")
.attr("x", (d) => years_x[d] )
.attr("y", 40)
.attr("text-anchor", "middle")
.text((d) -> d)
# Method to hide year titiles
hide_years: () =>
years = @vis.selectAll(".years").remove()
show_details: (data, i, element) =>
d3.select(element).attr("stroke", "black")
content = "<span class=\"name\">Title:</span><span class=\"value\"> #{data.name}</span><br/>"
content +="<span class=\"name\">Amount:</span><span class=\"value\"> $#{addCommas(data.value)}</span><br/>"
content +="<span class=\"name\">Year:</span><span class=\"value\"> #{data.year}</span>"
@tooltip.showTooltip(content,d3.event)
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", (d) => d3.rgb(@fill_color(d.group)).darker())
@tooltip.hideTooltip()
root = exports ? this
$ ->
chart = null
render_vis = (csv) ->
chart = new BubbleChart csv
chart.start()
root.display_all()
root.display_all = () =>
chart.display_group_all()
root.display_year = () =>
chart.display_by_year()
root.toggle_view = (view_type) =>
if view_type == 'year'
root.display_year()
else
root.display_all()
d3.csv "data/gates_money.csv", render_vis
[1]: http://vallandingham.me/vis/gates/ "Bubble Chart" | 0 |
11,628,066 | 07/24/2012 09:36:29 | 1,548,197 | 07/24/2012 09:29:00 | 1 | 0 | how to show all duplicate rows from 2 tables? | I hav 2 tables named-DataEntry_old & DataEntry_new
having columns doc id, mobileno, name,addr on both tables
I want to show all matching rows from both the tables where mobileno=987654321.
that is if mobileno=987654321 is in DataEntry_old then one row from this table & if also mobileno=987654321 is in DataEntry_new then another one rows from this table......plz give any sql query for it?
| sql | null | null | null | null | null | open | how to show all duplicate rows from 2 tables?
===
I hav 2 tables named-DataEntry_old & DataEntry_new
having columns doc id, mobileno, name,addr on both tables
I want to show all matching rows from both the tables where mobileno=987654321.
that is if mobileno=987654321 is in DataEntry_old then one row from this table & if also mobileno=987654321 is in DataEntry_new then another one rows from this table......plz give any sql query for it?
| 0 |
11,628,091 | 07/24/2012 09:38:02 | 1,187,135 | 02/03/2012 09:15:24 | 197 | 9 | Reg ex with . and space | I am having problem with regular expression. When ever I type 'St. Joe', the input is stored on the backend as 'St.' only. I have a space in my regular expression, but i am not sure what is wrong.
Here's the function the input goes through.
function reg_sent($i){
$reg_sent = "/[^A-Za-z0-9., '\n\r ]/";
return preg_replace($reg_sent, '', $i);
}
| php | regex | null | null | null | 07/24/2012 12:07:02 | too localized | Reg ex with . and space
===
I am having problem with regular expression. When ever I type 'St. Joe', the input is stored on the backend as 'St.' only. I have a space in my regular expression, but i am not sure what is wrong.
Here's the function the input goes through.
function reg_sent($i){
$reg_sent = "/[^A-Za-z0-9., '\n\r ]/";
return preg_replace($reg_sent, '', $i);
}
| 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.