text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Kind of an ajax slider Imagine you click on Categories and go to a page like "news.php?category=2". In that page it'll show the news of the category and it has two buttons, "Previous category" and "Next category", the href for these buttons are "news.php?category=1" and "news.php?category=3", respectively.
I've used jQuery .load() to load from Categories to the News page and it worked perfectly.
$('.newstrigger').click(function() {
var toLoad = $(this).attr('href')+' #container';
$('#wrapper').append('<div id="lastcontainer"></div>');
$('#lastcontainer').load(toLoad);
return false;
});
The problem is I can't seem to load the same page again with different parameters.
Can you guys help me?
After the load, I want to animate the content to the left (or right, depending which button the user has clicked) and make the loaded content appear from the right. That's why the title of this question has slider on it. No problems with this part of the code, I suppose.
UPDATE:
I'm currently working on it here:
Link
This version doesn't have PHP, but you can see what I'm after. Click on "Projectos" and than on "Categoria 1".
A: It would really help to see the rest of your code.
it seems to me if you click twice you will have 2 divs with id=lastcontainer
also, i don't understand -- does this work once but not twice or not at all?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deploying an N-Layered ASP.NET Webforms Application In A Shared Hosting I Have a solution that containts 4 layers (3 Class Libraries and 1 Web Application). I Need to deploy this solution to my shared hosting account. I've read a little about deployment and I hope I could perform a 'Precompiled Deployment' because as far as I know, It gives a better experience for the first time users as it's already compliled.
I don't see the "Publish Application" or whatever under the 'Build' menu, I setuped Microsoft Website Copy Tool. and I have on my shared account the Deployment Tool. I'm using Visual Studio 2010 Pro.
..Any one can help with details to deploy my first website on the internet !? :)
A: Right click on your web application the solution explorer. Select 'publish' from there or is it disabled?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: django one-to-one relationship defaulting to existing object - is this what is supposed to happen? I have three models, related with one-to-one relationships. So far as relevant, the code for them is:
class Member(models.Model):
deferred_on = models.OneToOneField('PendingAuthorisation',
related_name = 'defers_member',
on_delete=models.SET_NULL,
null=True,
blank=True,
default = None)
class Director(models.Model):
deferred_on = models.OneToOneField('PendingAuthorisation',
related_name = 'defers_director',
on_delete=models.SET_NULL,
null=True,
blank=True,
default = None)
class PendingAuthorisation(models.Model):
...
My issue is that when I create a new PendingAuthorisation, it's defers_member and defers_director properties default to an existing Member or Director even if those objects do not have a deferred_on property set.
Is this supposed to happen? Is there any way to stop this happening? Is this a bug in django?
edit: I'm using django 1.3 (not 1.3.1).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apache benchmark: what does the total mean milliseconds represent? I am benchmarking php application with apache benchmark. I have the server on my local machine. I run the following:
ab -n 100 -c 10 http://my-domain.local/
And get this:
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 3 3.7 2 8
Processing: 311 734 276.1 756 1333
Waiting: 310 722 273.6 750 1330
Total: 311 737 278.9 764 1341
However, if I refresh my browser on the page http://my-domain.local/ I find out it takes a lot longer than 737 ms (the mean that ab reports) to load the page (around 3000-4000 ms). I can repeat this many times and the loading of the page in the browser always takes at least 3000 ms.
I tested another, heavier page (page load in browser takes 8-10 seconds). I used a concurrency of 1 to simulate one user loading the page:
ab -n 100 -c 1 http://my-domain.local/heavy-page/
And the results are here:
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.1 0 1
Processing: 17 20 4.7 18 46
Waiting: 16 20 4.6 18 46
Total: 17 20 4.7 18 46
So what does the total line on the ab results actually tell? Clearly it's not the number of milliseconds the browser is loading the web page. Is the number of milliseconds that it takes from browser to load the page (X) linearly dependent of number of the total mean milliseconds ab reports (Y)? So if I'm able to reduce half of Y, have I also reduced half of X?
(Also Im not really sure what Processing, Waiting and Total mean).
I'll reopen this question since I'm facing the problem again.
Recently I installed Varnish.
I run ab like this:
ab -n 100 http://my-domain.local/
Apache bench reports very fast response times:
Requests per second: 462.92 [#/sec] (mean)
Time per request: 2.160 [ms] (mean)
Time per request: 2.160 [ms] (mean, across all concurrent requests)
Transfer rate: 6131.37 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.0 0 0
Processing: 1 2 2.3 1 13
Waiting: 0 1 2.0 1 12
Total: 1 2 2.3 1 13
So the time per request is about 2.2 ms. When I browse the site (as an anonymous user) the page load time is about 1.5 seconds.
Here is a picture from Firebug net tab. As you can see my browser is waiting 1.68 seconds for my site to response. Why is this number so much bigger than the request times ab reports?
A: Are you running ab on the server? Don't forget that your browser is local to you, on a remote network link. An ab run on the webserver itself will have almost zero network overhead and report basically the time it takes for Apache to serve up the page. Your home browser link will have however many milliseconds of network transit time added in, on top of the basic page-serving overhead.
A: Ok.. I think I know what's the problem. While I have been measuring the page load time in browser I have been logged in.. So none of the heavy stuff is happening. The page load times in browser with anonymous user are closer to the ones ab is reporting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: With sendmailR, how can I specify a recipient/sender name along with the address? I am using sendmailR to send emails but I cannot get it to work with a name associated with the email addresses, like "Sender name" <sender@domain.com>
With Postfix as the SMTP server, it throws SMTP Error: 5.5.4 Unsupported option: <sender@domain.com>.
Which syntax or parameter should be used? Your advice is welcome!
Following the example:
from <- "\"Sender name\" <sender@domain.com>"
to <- "<olafm@datensplitter.net>"
subject <- "Hello from R"
body <- list("It works!", mime_part(iris))
sendmail(from, to, subject, body,
control=list(smtpServer="ASPMX.L.GOOGLE.COM"))
A: From one side, one e-mail address can't contain any whitespace non-quoted, it should have a form "\"Sender name Or Any name with any whitespace you want\"<sender@domain.com>".
And from the other side, e-mail addresses used in to and from fields format depends on the server.
For example, when using Google's ASPMX.L.GOOGLE.COM SMTP I was only able to write the addresses in the following form:
from <- "<sender@domain.com>"
Options like
*
*"\"Sender name\"<sender@domain.com>";
*"\"Sender name\" <sender@domain.com>";
*"Sender name<sender@domain.com>";
*or "Sender name <sender@domain.com>"
were not accepted and generated either
SMTP Error: 5.5.2 Syntax error.
(for the 1st option) or
SMTP Error: 5.5.4 Unsupported option
(for options 2-4, I suppose, because of whitespace).
But when I tried custom SMTP server, I was able to use both from <- "<sender@domain.com>" and "\"Sender name\"<sender@domain.com>" - the second one gave exactly what I expected to get.
A: You must not include any space between the quoted name and the email address enclosed in <>. Here is the correct code:
from <- "\"Sender name\"<sender@domain.com>"
to <- "\"Recipient name\"<olafm@datensplitter.net>"
subject <- "Hello from R"
body <- list("It works!", mime_part(iris))
sendmail(from, to, subject, body,
control=list(smtpServer="ASPMX.L.GOOGLE.COM"))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How Do ncurses et. al. Work? There are several libraries like ncurses that assist in making command-line GUIs.
Simply put, how do they work?
My first thought was that ncurses intercepts all keyboard input, and draws each "frame" by outputting it line-by-line normally. Closer inspection, however, reveals that each new frame overwrites the previous one. How does it modify lines that have already been outputted? Furthermore, how does it handle color?
EDIT: The same question applies to anything with a "fancy" interface, like vim and emacs.
A: curses (and ncurses, too, I think) works by moving the cursor around on the screen. There are control sequences to do such things. Take a look at the code again and you'll see them. These sequences are not ASCII control characters, they are strings starting with (umm...) ESC, maybe. Have a look here for a higher-level explanation.
A: Text terminals have command sequences that do things like move the cursor to a particular position on the screen, insert characters, delete lines etc.
Each terminal type is different and has its own set of command sequences. ncurses has a databse (see terminfo for details)
Internally ncurses maintains 2 views of the screen: the current contents and what the screen should look like after the current pending changes are applied. Once the program requests a screen redraw, ncurses calculates an efficient way to update the screen to look like the desired view. The exact characters/command sequences output depend on what terminal type is in use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Socket with timeout set sometimes stalls on reading I have a Java client (1.6b17 on windows XP, launched via Java webstart) that uses a TCP socket to query a Java based server over an ADSL connetion. The client socket has a timeout set (3000ms).
Occasionally (and so far, not reproducibly), the client stalls while reading responses from the server. There are a few hundred installations and most users don't encounter the issue most of the time.
The client creates a new socket for each request following the steps below:
*
*Create a new socket setting the timeout to be 3000ms
*Submit request (a single line of text)
*Read multiple lines of response, closing the socket when a special "end of message" sequence is received (or a null)
Here's some (simplified) code to illustrate:
socket = new Socket(host, port);
socket.setSoTimeout(socketTimeout);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
socket.write(cmd);
while (true) {
line = in.readLine();
if (line == null) break;
if (line.equals("EOL")) break;
// Store line of text in an ArrayList
}
socket.close();
The problem is that occasionally, in the middle of receiving, the client will pause for up to 5 minutes and then resume without any intervention. Following this, the application resumes with no noticable performance issues.
Logging on the server side indicates that the operation takes approx 150ms although the timestamp in question is taken prior to closing the socket (something I will try to address).
One of my working assumptions is that this is not due to network issues as otherwise, the readLine would timeout, is this a valid assumption?
It also doesn't seem likely that this would be garbage collection related. The app has 512MB allocated to the heap while the data being retrieved consists of approx 1600 lines of 100 characters. My expectation is if the problem related to GC or memory leaks that there would be a general degradation in performance rather than the sort of "sticky" behaviour that I am seeing, is this correct?
Any suggested strategies for troubleshooting this would be greatly appreciated.
Thanks,
Phil
A: I didn't see you get up to 5 minute "pauses". I can only imagine you are getting lots of retries on packets. You should be able to see something like this with wireshark. It can give you a clue if its something else as well.
Your full GC pause time on a 512 MB heap should be around 0.5 seconds (very approximately)
If you have an unreliable connection I wouldn't suggest using PrintWriter. If it gets an IOException, it sets a flag rather than throwing an exception. If you continue to use it, it does nothing.
A: The readLine() should timeout. Never seen that not work, on any platform. Maybe you are only receiving one character at a time, at intervals less than 3s. Wireshark will tell you.
Or as you are reading lines, maybe the server isn't sending a newline in the correct places?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Finding the phone company of a cell phone number? I have an application where people can give a phone number and it will send SMS texts to the phone number through EMail-SMS gateways. For this to work however, I need the phone company of the given number so that I send the email to the proper SMS gateway. I've seen some services that allow you to look up this information, but none of them in the form of a web service or database.
For instance, http://tnid.us provides such a service. Example output from my phone number:
Where do they get the "Current Telephone Company" information for each number. Is this freely available information? Is there a database or some sort of web service I can use to get that information for a given cell phone number?
A: What you need is called a HLR (Home Location Register) number lookup.
In their basic forms such APIs will expect a phone number in international format (example, +15121234567) and will return back their IMSI, which includes their MCC (gives you the country) and MNC (gives you the phone's carrier). The may even include the phone's current carrier (eg to tell if the phone is roaming). It may not work if the phone is currently out of range or turned off. In those cases, depending on the API provider, they may give you a cached result.
The site you mentioned seems to provide such functionality. A web search for "HLR lookup API" will give you plenty more results. I have personal experience with CLX's service and would recommend it.
A: This would be pretty code intensive, but something you could do right now, on your own, without APIs as long as the tnid.us site is around:
Why not have IE open in a hidden browser window with the URL of the phone number? It looks like the URL would take the format of http://tnid.us/search.php?q=########## where # represents a number. So you need a textbox, a label, and a button. I call the textbox "txtPhoneNumber", the label "lblCarrier", and the button would call the function I have below "OnClick".
The button function creates the IE instance using MSHtml.dll and SHDocVW.dll and does a page scrape of the HTML that is in your browser "object". You then parse it down. You have to first install the Interoperability Assemblies that came with Visual Studio 2005 (C:\Program Files\Common Files\Merge Modules\vs_piaredist.exe). Then:
1> Create a new web project in Visual Studio.NET.
2> Add a reference to SHDocVw.dll and Microsoft.mshtml.
3> In default.aspx.cs, add these lines at the top:
using mshtml;
using SHDocVw;
using System.Threading;
4> Add the following function :
protected void executeMSIE(Object sender, EventArgs e)
{
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorerClass();
object o = System.Reflection.Missing.Value;
TextBox txtPhoneNumber = (TextBox)this.Page.FindControl("txtPhoneNumber");
object url = "http://tnid.us/search.php?q=" + txtPhoneNumber.Text);
StringBuilder sb = new StringBuilder();
if (ie != null) {
ie.Navigate2(ref url,ref o,ref o,ref o,ref o);
ie.Visible = false;
while(ie.Busy){Thread.Sleep(2);}
IHTMLDocument2 d = (IHTMLDocument2) ie.Document;
if (d != null) {
IHTMLElementCollection all = d.all;
string ourText = String.Empty;
foreach (object el in all)
{
//find the text by checking each (string)el.Text
if ((string)el.ToString().Contains("Current Phone Company"))
ourText = (string)el.ToString();
}
// or maybe do something like this instead of the loop above...
// HTMLInputElement searchText = (HTMLInputElement)d.all.item("p", 0);
int idx = 0;
// and do a foreach on searchText to find the right "<p>"...
foreach (string s in searchText) {
if (s.Contains("Current Phone Company") || s.Contains("Original Phone Company")) {
idx = s.IndexOf("<strong>") + 8;
ourText = s.Substring(idx);
idx = ourText.IndexOf('<');
ourText = ourText.Substring(0, idx);
}
}
// ... then decode "ourText"
string[] ourArray = ourText.Split(';');
foreach (string s in ourArray) {
char c = (char)s.Split('#')[1];
sb.Append(c.ToString());
}
// sb.ToString() is now your phone company carrier....
}
}
if (sb != null)
lblCarrier.Text = sb.ToString();
else
lblCarrier.Text = "No MSIE?";
}
For some reason I don't get the "Current Phone Company" when I just use the tnid.us site directly, though, only the Original. So you might want to have the code test what it's getting back, i.e.
bool currentCompanyFound = false;
if (s.Contains("Current Telephone Company")) { currentCompanyFound = true }
I have it checking for either one, above, so you get something back. What the code should do is to find the area of HTML between
<p class="lt">Current Telephone Company:<br /><strong>
and
</strong></p>
I have it looking for the index of
<strong>
and adding on the characters of that word to get to the starting position. I can't remember if you can use strings or only characters for .indexOf. But you get the point and you or someone else can probably find a way to get it working from there.
That text you get back is encoded with char codes, so you'd have to convert those. I gave you some code above that should assist in that... it's untested and completely from my head, but it should work or get you where you're going.
A: Did you look just slightly farther down on the tnid.us result page?
Need API access? Contact sales@tnID.us.
A: [Disclosure: I work for Twilio]
You can retrieve phone number information with Twilio Lookup.
If you are currently evaluating services and functionality for phone number lookup, I'd suggest giving Lookup a try via the quickstart.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to set spam email using EWS api? I am developing an email client using EWS api. I know for each item(email), I can use Move function to move the item into a specific folder. I noticed that in WellKnkownFolderName there is a JunkEmail. I wonder after is use Move function move that item into junkemail folder, does that mean the server will ban future emails coming from that sender?
EmailMessage current = EmailMessage.Bind(service, id);
current.Move(WellKnownFolderName.JunkEmail);//Does JunkEmail means spam? Or it is just a normal email folder as inbox, draft, sent etc
A: No, Exchange will not automatically move future emails to the junk folder based on this mail.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Search API - HTTP Query Argument Format I've created a search API for a site that I work on. For example, some of the queries it supports are:
*
*/api/search - returns popular search results
*/api/search?q=car - returns results matching the term "car"
*/api/search?start=50&limit=50 - returns 50 results starting at offset 50
*/api/search?user_id=3987 - returns results owned by the user with ID 3987
These query arguments can be mixed and matched. It's implemented under the hood using Solr's faceted search.
I'm working on adding query arguments that can filter results based on a numeric attribute. For example, I might want to only return results where the view count is greater than 100. I'm wondering what the best practice is for specifying this.
Solr uses this way:
/api/search?views:[100 TO *]
Google seems to do something like this:
/api/search?viewsisgt:100
Neither of these seem very appealing to me. Is there a best practice for specifying this kind of query term? Any suggestions?
A: Simply use ',' as separator for from/to, it reads the best and in my view is intuitive:
# fixed from/to
/search?views=4,2
# upper wildcard
/search?views=4,
# lower wildcard
/search?views=,4
I take values inclusive. In most circumstances you won't need the exclusive/inclusive additional syntax sugar.
Binding it even works very well in some frameworks out of the box (like spring mvc), which bind ',' separated values to an array of values. You could then wrap the internal array with specific accessors (getMin(), getMax()).
A: Google's approach is good, why it's not appealing?
Here comes my suggestion:
/api/search?viewsgt=100
A: I think the mathematical notation for limits are suitable.
[x the lower limit can be atleast x
x] the upper limit can be atmost x
(x the lower limit must be strictly greater than x
x) the upper limit must be strictly lesser than x
Hence,
q=cats&range=(100,200) - the results from 100 to 200, but not including 100 and 200
q=cats&range=[100,200) - the results from 100 to 200, but the lower limit can be greater than 100
q=cats&range=[100 - any number from 100 onwards
q=cats&range=(100 - any number greater than 100
q=cats&range=100,200 - default, same as [100,200]
Sure, its aesthetics are still questionable, but it seems (IMO) the most intuitive for the human eye, and the parser is still easy.
As per http://en.wikipedia.org/wiki/Percent-encoding =,&,[,],(,) are reserved
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to keep processed data with to_python when form is not valid? I have a django form which can be not valid, but I would like to keep the data processed with to_python() method on some fields to propose it to the user, so that he can changes wrong fields, but having already processed values for some 'good' fields.
f = MyForm(request.POST)
if f.is_valid():
# not my case
return render_to_response('template.html', form)
and request.POST {'price':'100 000', 'duration':'aaa'}
is processed with to_python() to {'price':'100000', 'duration':'aaa'}
and I would like to fill the form in render_to_response with this new price value (100000 and not 100 000)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: A recursion algorithm Ok, this may seem trivial to some, but I'm stuck.
Here's the algorithm I'm supposed to use:
Here’s a recursive algorithm. Suppose we have n integers in a non-increasing sequence, of which the first is the number k. Subtract one from each of the first k numbers after the first. (If there are fewer than k such number, the sequence is not graphical.) If necessary, sort the resulting sequence of n-1 numbers (ignoring the first one) into a non-increasing sequence. The original sequence is graphical if and only if the second one is. For the stopping conditions, note that a sequence of all zeroes is graphical, and a sequence containing a negative number is not. (The proof of this is not difficult, but we won’t deal with it here.)
Example:
Original sequence: 5, 4, 3, 3, 2, 1, 1
Subtract 1 five times: 3, 2, 2, 1, 0, 1
Sort: 3, 2, 2, 1, 1, 0
Subtract 1 three times: 1, 1, 0, 1, 0
Sort: 1, 1, 1, 0, 0
Subtract 1 once: 0, 1, 0, 0
Sort: 1, 0, 0, 0
Subtract 1 once: -1, 0, 0
We have a negative number, so the original sequence is not graphical.
This seems simple enough to me, but when I try to execute the algorithm I get stuck.
Here's the function I've written so far:
//main
int main ()
{
//local variables
const int MAX = 30;
ifstream in;
ofstream out;
int graph[MAX], size;
bool isGraph;
//open and test file
in.open("input3.txt");
if (!in) {
cout << "Error reading file. Exiting program." << endl;
exit(1);
}
out.open("output3.txt");
while (in >> size) {
for (int i = 0; i < size; i++) {
in >> graph[i];
}
isGraph = isGraphical(graph, 0, size);
if (isGraph) {
out << "Yes\n";
}else
out << "No\n";
}
//close all files
in.close();
out.close();
cin.get();
return 0;
}//end main
bool isGraphical(int degrees[], int start, int end){
bool isIt = false;
int ender;
inSort(degrees, end);
ender = degrees[start] + start + 1;
for(int i = 0; i < end; i++)
cout << degrees[i];
cout << endl;
if (degrees[start] == 0){
if(degrees[end-1] < 0)
return false;
else
return true;
}
else{
for(int i = start + 1; i < ender; i++) {
degrees[i]--;
}
isIt = isGraphical(degrees, start+1, end);
}
return isIt;
}
void inSort(int x[],int length)
{
for(int i = 0; i < length; ++i)
{
int current = x[i];
int j;
for(j = i-1; j >= 0 && current > x[j]; --j)
{
x[j+1] = x[j];
}
x[j+1] = current;
}
}
I seem to get what that sort function is doing, but when I debug, the values keep jumping around. Which I assume is coming from my recursive function.
Any help?
EDIT:
Code is functional. Please see the history if needed.
With help from @RMartinhoFernandes I updated my code. Includes working insertion sort.
I updated the inSort funcion boundaries
I added an additional ending condition from the comments. But the algorithm still isn't working. Which makes me thing my base statements are off. Would anyone be able to help further? What am I missing here?
A: Ok, I helped you out in chat, and I'll post a summary of the issues you had here.
*
*The insertion sort inner loop should go backwards, not forwards. Make it for(i = (j - 1); (i >= 0) && (key > x[i]); i--);
*There's an out-of-bounds access in the recursion base case: degrees[end] should be degrees[end-1];
*while (!in.eof()) will not read until the end-of-file. while(in >> size) is a superior alternative.
A: Are you sure you ender do not go beyond end? Value of ender is degrees[start] which could go beyond the value of end.
Then you are using ender in for loop
for(int i = start+1; i < ender; i++){ //i guess it should be end here
A: I think your insertion sort algorithm isn't right. Try this one (note that this sorts it in the opposite order from what you want though). Also, you want
for(int i = start + 1; i < ender + start + 1; i++) {
instead of
for(int i = start+1; i < ender; i++)
Also, as mentioned in the comments, you want to check if degrees[end - 1] < 0 instead of degrees[end].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I muddle around in subversion transactions from a hook script? I've read all the warnings. I want to see for myself what will blow up if in a pre-commit hook script, I change the files that are being committed.
It would be a good thing if the client is ignorant of this for my particular purposes. People are checking in system passwords that we want to keep out of the repository. I've got a perl script that regexes through changed files, and if it sees a password it vomits up a warning along with filename and line number.
So now they have to dig back into the file (it's probably not even open), delete the password, save it, and re-commit. Trouble is, then they have to re-open the file, put the password back in to continue working. It's annoying. If Subversion intercepted the file, scrubbed the password, and secretly committed that... it seems like that's the ideal circumstance. No one works around the pre-commit script, svn doesn't save sensitive passwords, and people aren't constantly removing passwords that they'll just have to put back in after committing (which would probably discourage commits, the last thing we want to do).
I'm language agnostic here. If you know how to do it in php or C or m68k assembler, I'd like to see an example. Doesn't have to be perl. If the Subversion police show up to question you, you're welcome to pin it all on me.
A: Not really an answer to your question, but I would keep the approach you already have - to deny the commit. On the client side though, if the person working with the code wants to easy her life, she can use some scripts on the client side. Maybe applying some previously generated diffs/patches before and after a commit. Some other options are given in with this SO question: client side pre-commit hooks in subversion
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Grep for specific sentence that contains [] I have a python script that reports how many times an error shows up in catalina.out within a 17 minute time period. Some errors contain more information, displayed in the next three lines beneath the error. Unfortunately the sentence I'm grepping for contains []. I don't want to do a search using regular expressions. Is there a way to turn off the regular expression function and only do an exact search?
Here is an example of a sentence im searching for:
bob: [2012-08-30 02:58:57.326] ERROR: web.errors.GrailsExceptionResolver Exception occurred when processing request: [GET] /bob/event
Thanks
A: If you're using bash and regular grep, you have to escape the [] chars, i.e. \[ ... \],
grep 'bob: \[2012-08-30 02:58:57.326\] ERROR: web.errors.GrailsExceptionResolver Exception occurred when processing request: \[GET\] /bob/event' catalina.out
Not sure if you're really asking how to search for a '17 minute time period' and/or how to 'displayed in the next three lines beneath the error.'
It will help the answers supplied if you show sample input and sample output.
I hope this helps.
A: (assuming you are using the standard grep command)
Is there a way to turn off the regular expression function and only do an exact search?
Sure, you can pass the -F flag to grep, like so:
grep -F "[GET]" catalina.out
Remember to put the search term in quotes, or else bash will interpret the brackets in a special way.
A: What are you searching for? If you need more than a specific exact search, you will probably need to use regular expressions.
There is no need to worry about the brackets. Regex can still search for them. You just need to escape the characters in your regex:
pattern = r'\[\d+-\d+-\d+ \d+:\d+:\d+\.\d+] ERROR:' # or whatever
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to load data to make them visible in an ActivityList? I'm relatively new to Android and have the following question. I have a local DB on the device from which I want to display the content in an ActivityList. Let's say there is a table "person" on the DB containing general information like "name, surname etc."
Every row in the table should be displayed as an item within the ActivityList.
I know that there exists a sort of Adapter with which I can directly fill the ActivityList with my table data, but is this the way to do it?
Isn't it better to load all the data at startup and then hold them for the entire session and pass the data from one activity to another(or make them static..) if necessary, instead of loading the data every time I change to another Activity?
If I would have a normal Java application I would load the Data at startup and then just work with the loaded objects (at least for reasonable data sets).
Doesn't it make sense for an Android App too?
I will up-rate every answer that makes sense to me.
Thanks!
Slash
A: I would have a look at the ContentProvider.
You can use it to query your database and then show the content in the ListView using a CursorAdapter.
A: You need to use an Adapter if you want to work with ListView. So, that is a must. And you can set the Adapter data from your Activity.
As for the "sense" question, it probably makes sense. But as always it depends on a few things:
Will this data be used through out the application? Then it absolutely makes sense to load it once and use it everywhere. How you do that is up to your needs, static access or passing the data, all should work.
And DB access is always expensive. And if you have lots of rows, the loading process from the database can be extremely slow. So, again, load it once and use it everywhere is a good plan.
But be careful about blocking the UI thread when you load this data. You should never access DB from your UI thread. Instead use a worker thread or AsyncTask.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: 10g Package Construction - Restricting References I am constructing a rather large Oracle 10g package full of functions etc.
The problem is some of these functions are pulling information from materilized view's or tables that other functions are creating.
Is there a way to successfully compile a package even though some of the functions cannot find the information they are looking for (But these functions will work once the views have been created?).
Attempts:
I have looked into PRAGMA RESTRICT_REFERENCES but have had no success so far. Am I even on the right track or is this not even possible?
A: You cannot refer using static SQL to objects that do not exist when the code is compiled. There is nothing you can do about that.
You would need to modify your code to use dynamic SQL to refer to any object that is created at runtime. You can probably use EXECUTE IMMEDIATE, i.e.
EXECUTE IMMEDIATE
'SELECT COUNT(*) FROM new_mv_name'
INTO l_cnt;
rather than
SELECT COUNT(*)
INTO l_cnt
FROM new_mv_name;
That being said, however, I would be extremely dubious about a PL/SQL implementation that involved creating any new tables and materialized views at runtime. That is almost always a mistake in Oracle. Why do you need to create new objects at runtime?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create an instance of any type (id) in Objective-c I've an NSArray instance containing some objects of some type (NSDictionary)..
I need to copy this Array into an NSArray of some runtime-known type.
So I need to create instances of the runtime-known type and copy the contents of the NSDictionary into.
I've actually created these instances of type NSObject, but when querying it after-head, I got unrecognized selector error!
NSUInteger count = [value count];
NSMutableArray* arr = [[NSMutableArray alloc]initWithCapacity:count];
if (count > 0)
{
for (int i=0; i < [value count]; i++)
{
id newObj = [[NSObject alloc] init];
id currentValue = [value objectAtIndex:i];
[self objectFromDictionary:currentValue object:newObj];
[arr addObject:newObj];
}
}
[arr release];
EDIT:
objectFromDictionary forget about it, what it do is to inspect the properties of newObj and set it by the values from the dictionary. it is doing its work good.
EDIT 2:
Please see why I am trying to do this:
Type of objects inside non-parameterized arrays in JSON
A: Change:
id newObj = [[NSObject alloc] init];
to:
id newObj = [[NSMutableArray alloc] init];
or:
id newObj = [[NSClassFromString(@"NSMutableArray") alloc] init];
or, if you want to derive the class from an existing object:
id newObj = [[[existingObj class] alloc] init];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I force my application to launch the default Camera rather than offering the 'Complete action using' list? I'm using the intent new Intent(MediaStore.ACTION_IMAGE_CAPTURE); to capture an image for use in my application. I have two applications installed on my device that can perform this function but would like my app to only use the default camera.
Is there a way of doing this?
A: As Dr_sulli suggested, i am just converting it into a code and it works for me well, If case to access direct camera application and else part is allow the user to choose other camera applications along with system camera.
protected static final int CAMERA_ACTIVITY = 100;
Intent mIntent = null;
if(isPackageExists("com.google.android.camera")){
mIntent= new Intent();
mIntent.setPackage("com.google.android.camera");
mIntent.setAction(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mIntent.putExtra("output", Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "/myImage" + ".jpg")));
}else{
mIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mIntent.putExtra("output", Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "/myImage" + ".jpg")));
Log.i("in onMenuItemSelected",
"Result code = "
+ Environment.getExternalStorageDirectory());
}
startActivityForResult(mIntent, CAMERA_ACTIVITY);
inside onActivityResult do your stuff
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Log.i("in onActivityResult", "Result code = " + resultCode);
if (resultCode == -1) {
switch (requestCode) {
case CAMERA_ACTIVITY:
//do your stuff here, i am just calling the path of stored image
String filePath = Environment.getExternalStorageDirectory()
+ "/myImage" + ".jpg";
}
}
}
isPackageExists will confirm the package exist or not.
public boolean isPackageExists(String targetPackage){
List<ApplicationInfo> packages;
PackageManager pm;
pm = getPackageManager();
packages = pm.getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
if(packageInfo.packageName.equals(targetPackage)) return true;
}
return false;
}
OR you can do it in my way its much easier, this will filter the all system application and then later you compare the name hence it work on all phone but the above technique due to hard coding will not work on every phone. Later you can use this package name to start the camera activity as i described above.
PackageManager pm = this.getPackageManager();
List<ApplicationInfo> list = getPackageManager().getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
for (int n=0;n<list.size();n++) {
if((list.get(n).flags & ApplicationInfo.FLAG_SYSTEM)==1)
{
Log.d("Installed Applications", list.get(n).loadLabel(pm).toString());
Log.d("package name", list.get(n).packageName);
if(list.get(n).loadLabel(pm).toString().equalsIgnoreCase("Camera"))
break;
}
}
A: List<ApplicationInfo> list = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
for (int n=0;n<list.size();n++) {
if((list.get(n).flags & ApplicationInfo.FLAG_SYSTEM)==1)
{
Log.d("TAG", "Installed Applications : " + list.get(n).loadLabel(packageManager).toString());
Log.d("TAG", "package name : " + list.get(n).packageName);
if(list.get(n).loadLabel(packageManager).toString().equalsIgnoreCase("Camera")) {
defaultCameraPackage = list.get(n).packageName;
break;
}
}
}
I find following solution and its working perfectly.
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.setPackage(defaultCameraPackage);
startActivityForResult(takePictureIntent, actionCode);
you can filter default camera by setting package in above intent. I've tested it by installing two application Line Camera and Paper Camera both apps were showing chooser but filtering by package above code open only default camera.
A: I have prepared a solution which works in almost all solution:
private void openCamera() {
String systemCamera;
if (isPackageExists("com.google.android.camera")) {
systemCamera = "com.google.android.camera";
} else {
systemCamera = findSystemCamera();
}
if (systemCamera != null) {
Log.d(TAG, "System Camera: " + systemCamera);
Intent mIntent = new Intent();
mIntent.setPackage(systemCamera);
File f = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), ("IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg"));
mIntent.setAction(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(mIntent, IMAGE_CODE_PICKER);
} else {
//Unable to find default camera app
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_CODE_PICKER && resultCode == RESULT_OK) {
}
}
private boolean isPackageExists(String targetPackage) {
List<ApplicationInfo> packages;
PackageManager pm;
pm = getPackageManager();
packages = pm.getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
if (packageInfo.packageName.equals(targetPackage)) {
return true;
}
}
return false;
}
private String findSystemCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = this.getPackageManager();
List<ResolveInfo> listCam = packageManager.queryIntentActivities(intent, 0);
for (ResolveInfo info :
listCam) {
if (isSystemApp(info.activityInfo.packageName)) {
return info.activityInfo.packageName;
}
}
return null;
}
boolean isSystemApp(String packageName) {
ApplicationInfo ai;
try {
ai = this.getPackageManager().getApplicationInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
int mask = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
return (ai.flags & mask) != 0;
}
You may need to put following code in onCreate method:
StrictMode.VmPolicy.Builder newbuilder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(newbuilder.build());
A: I'm not sure what you are trying to accomplish is portable across all devices. One goal of Android is to allow the easy replacement of activities that service requests such as image capture. That being said, if you only wish to do this for your device, you could simply set the component name in the intent to the media capture activity's name.
A: the default camera app is the first app was installed. So, the first element in camlist is the default app
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = MapsActivity.this.getPackageManager();
List<ResolveInfo> listCam = packageManager.queryIntentActivities(intent, 0);
intent.setPackage(listCam.get(0).activityInfo.packageName);
startActivityForResult(intent,INTENT_REQUESTCODE1);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Deforming an image so that curved lines become straight lines I have an image with free-form curved lines (actually lists of small line-segments) overlayed onto it, and I want to generate some kind of image-warp that will deform the image in such a way that these curves are deformed into horizontal straight lines.
I already have the coordinates of all the line-segment points stored separately so they don't have to be extracted from the image. What I'm looking for is an appropriate method of warping the image such that these lines are warped into straight ones.
thanks
A: You can use methods similar to those developed here:
http://www-ui.is.s.u-tokyo.ac.jp/~takeo/research/rigid/
What you do, is you define an MxN grid of control points which covers your source image.
You then need to determine how to modify each of your control points so that the final image will minimize some energy function (minimum curvature or something of this sort).
The final image is a linear warp determined by your control points (think of it as a 2D mesh whose texture is your source image and whose vertices' positions you're about to modify).
As long as your energy function can be expressed using linear equations, you can globally solve your problem (figuring out where to send each control point) using linear equations solver.
You express each of your source points (those which lie on your curved lines) using bi-linear interpolation weights of their surrounding grid points, then you express your restriction on the target by writing equations for these points.
After solving these linear equations you end up with destination grid points, then you just render your 2D mesh with the new vertices' positions.
A: You need to start out with a mapping formula that given an output coordinate will provide the corresponding coordinate from the input image. Depending on the distortion you're trying to correct for, this can get exceedingly complex; your question doesn't specify the problem in enough detail. For example, are the curves at the top of the image the same as the curves on the bottom and the same as those in the middle? Do horizontal distances compress based on the angle of the line? Let's assume the simplest case where the horizontal coordinate doesn't need any correction at all, and the vertical simply needs a constant correction based on the horizontal. Here x,y are the coordinates on the input image, x',y' are the coordinates on the output image, and f() is the difference between the drawn line segment and your ideal straight line.
x = x'
y = y' + f(x')
Now you simply go through all the pixels of your output image, calculate the corresponding point in the input image, and copy the pixel. The wrinkle here is that your formula is likely to give you points that lie between input pixels, such as y=4.37. In that case you'll need to interpolate to get an intermediate value from the input; there are many interpolation methods for images and I won't try to get into that here. The simplest would be "nearest neighbor", where you simply round the coordinate to the nearest integer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CUFFT output not aligned the same as FFTW output I am doing a 1D FFT. I have the same input data as would go in FFTW, however, the return from CUFFT does not seem to be "aligned" the same was FFTW is. That is, In my FFTW code, I could calculate the center of the zero padding, then do some shifting to "left-align" all my data, and have trailing zeros.
In CUFFT, the result from the FFT is data that looks like it is the same, however, the zeros are not "centered" in the output, so the rest of my algorithm breaks. (The shifting to left-align the data still has a "gap" in it after the bad shift).
Can anyone give me any insight? I thought it had something to do with those compatibility flags, but even with cufftSetCompatibilityMode(plan, CUFFT_COMPATIBILITY_FFTW_ALL); I am still getting a bad result.
Below is a plot of the magnitude of the data from the first row. The data on the left is the output of the inverse CUFFT, and the output on the right is the output of the inverse FFTW.
Thanks!
Here is the setup code for the FFTW and CUFFT plans
ifft = fftwf_plan_dft_1d(freqCols, reinterpret_cast<fftwf_complex*>(indata),
reinterpret_cast<fftwf_complex*>(outdata),
FFTW_BACKWARD, FFTW_ESTIMATE);
CUFFT:
cufftSetCompatibilityMode(plan, CUFFT_COMPATIBILITY_FFTW_ALL);
cufftPlan1d(&plan, width, CUFFT_C2C, height);
and executing code:
fftwf_execute(ifft);
CUFFT:
cufftExecC2C(plan, d_image, d_image, CUFFT_INVERSE); //in place inverse
Completed some test code:
complex<float> *input = (complex<float>*)fftwf_malloc(sizeof(fftwf_complex) * 100);
complex<float> *output = (complex<float>*)fftwf_malloc(sizeof(fftwf_complex) * 100);
fftwf_plan ifft;
ifft = fftwf_plan_dft_1d(100, reinterpret_cast<fftwf_complex*>(input),
reinterpret_cast<fftwf_complex*>(output),
FFTW_BACKWARD, FFTW_ESTIMATE);
cufftComplex *inplace = (cufftComplex *)malloc(100*sizeof(cufftComplex));
cufftComplex *d_inplace;
cudaMalloc((void **)&d_inplace,100*sizeof(cufftComplex));
for(int i = 0; i < 100; i++)
{
inplace[i] = make_cuComplex(cos(.5*M_PI*i),sin(.5*M_PI*i));
input[i] = complex<float>(cos(.5*M_PI*i),sin(.5*M_PI*i));
}
cutilSafeCall(cudaMemcpy(d_inplace, inplace, 100*sizeof(cufftComplex), cudaMemcpyHostToDevice));
cufftHandle plan;
cufftPlan1d(&plan, 100, CUFFT_C2C, 1);
cufftExecC2C(plan, d_inplace, d_inplace, CUFFT_INVERSE);
cutilSafeCall(cudaMemcpy(inplace, d_inplace, 100*sizeof(cufftComplex), cudaMemcpyDeviceToHost));
fftwf_execute(ifft);
When I dumped the output from both of these FFT calls, it did look the same. I am not exactly sure what I was looking at though. The data had a value of 100 in the 75th row. Is that correct?
A: It looks like you may have swapped the real and imaginary components of your complex data in the input to one of the IFFTs. This swap will change an even function to an odd function in the time domain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I serialize a Java object such that it can be deserialized by pickle (Python)? I'm using a Python service that uses pickled messages as part of its protocol. I'd like to query this service from Java, but to do so, I need to pickle my message on the client (Java). Are there any implementations of pickle that run on the JVM (ideally with minimal dependencies)?
Clarification: Modifying the server side is not an option, so while alternate serializations would be convenient, they won't solve the problem here.
A: Some additional investigation yielded pyrolite, an MIT-licensed library that allows Java and .NET programs to interface with the Python world. In addition to remote object functionality, it (more importantly) includes a pickle serializer and de-serializer.
A: You can use a Java JSON serializer like GSON or Jackson to serilaise quite easily and use a python json pickle to deserialize
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How would I best construct a recursive tree visual with unknown child nodes in PHP? I'm having trouble getting started with the following:
*
*I have a database of questions and multiple answers per question.
*Each answer belongs to one question.
*Each answer points to one (different) question.
I'm trying to create a multi-level tree visualization of the entire relationship path without knowing the number of levels. How would I best do this?
Here is an example of the data array (simplififed):
array(
1 => array( //this key is the answer id
question_id = 1,
answers = array(
0 => answer_opens_question__id = 2,
1 => answer_opens_question__id = 3,
2 => answer_opens_question__id = 5
)
),
2 => array(
question_id = 2,
answers = array(
0 => answer_opens_question__id = 1,
1 => answer_opens_question__id = 5
)
),
5 => array(
question_id = 3,
answers = array(
0 => answer_opens_question__id = 2
)
)
)
In theory, this could go on forever and end up in an infinite loop - it's highly unlikely that this will ever happen though, since this data is user generated and not dynamically created.
I'm only looking for a way to recursively display a path like question > answer>>question > answer>>question > answer>>question> ... - the output will be in HTML with nested ul-li.
Any ideas on how I could do this? Thanks a lot for input of any kind.
EDIT/Solution:
Thanks to DaveRandom, I got it: write a function that loops through each answer and calls itself for each.
function recursiveTree($id) {
global $data; //an array like the one above
if(array_key_exists($id, $data)) {
echo '<ul><li>';
echo $data[$id]['question_name']; //question
if(is_array($data[$id]['answers']) && !empty($data[$id]['answers'])) {
foreach($data[$id]['answers'] as $answer) {
echo '<ul><li class="answer"><div>'.$answer['text'].' opens </div>';
recursiveTree($answer['answer_opens_question__id']); //call this very function for this answer's question - that's the trick
echo '</li></ul>';
}
}
echo '<li></ul>';
}
}//recursiveTree()
recursiveTree(1); //where 1 is the first question's id
I'm not keeping track of questions yet like Dave is in this code (please check out the accepted answer below) - that will be added. It works like this already though (because I don't have any loops in my test data), but I agree with everybody that it's advisable to take care of possible infinite loops.
With some padding and some borders around li.answer, the above output is even readable :)
Thanks again DaveRandom.
A: You do have a loop in that data. Question #1 has an answer pointing at question #2, and question #2 has an answer pointing at question #1. Ditto for #5 and #2.
If you want to prevent an infinite loop, you'll just have to build up a parallel breadcrumb array as you recurse down the tree. if you come to question #2 and see that it's pointing at question #1 - well, the breadcrumb array indicates that #1's been output already, so you skip recursing down that particular branch, and no loop occurs.
A: Maybe this will give you a prod in the right direction? (Slightly fixed)
function recursive_tree ($startQuestionId, $alreadyDisplayed = array()) {
// Make sure we only display each question once
$alreadyDisplayed[] = $startQuestionId;
// Replace this with a sensible query to get the answers for question id $startQuestionId
$answers = $db->query("SELECT answers.answerId, answers.opensQuestionId FROM questions, answers WHERE questions.questionId = '$startQuestionId' AND answers.questionId = questions.questionId");
// Echo a header for the question
echo "<div id='question$startQuestionId'>Question $startQuestionId\n<ul>\n";
while ($row = $db->fetch()) {
// Loop through the answers to this question
echo "<li>\nAnswer id {$row['answerId']} opens question id {$row['opensQuestionId']}\n";
if (!in_array($row['opensQuestionId'],$alreadyDisplayed)) {
// The linked question hasn't been displayed, show it here
$alreadyDisplayed = array_merge($alreadyDisplayed,recursive_tree($row['opensQuestionId'],$alreadyDisplayed));
} else {
// The linked question has already been displayed
echo "(<a href='#question{$row['opensQuestionId']}'>Already displayed</a>)\n";
}
echo "</li>\n";
}
// Close everything off
echo "</ul>\n</div>\n";
return $alreadyDisplayed;
}
// And call it like this
$questionToStartAt = 1;
recursive_tree($questionToStartAt);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cron job in Ubuntu This should be pretty straight forward but I can't seem to get getting it working despite reading several tutorials via Google, Stackoverflow and the man page.
I created a cron to run every 1 min (for testing) and all it basically does is spit out the date.
crontab -l
* * * * * /var/test/cron-test.sh
The cron-test file is:
echo "$(date): cron job run" >> test.log
Waiting many minutes and I never see a test.log file.
I can call the "test.sh" manually and get it to output & append.
I'm wondering what I'm missing? I'm also doing this as root. I wonder if I'm miss-understanding something about root's location? Is my path messed up because it's appending some kind of home directory to it?
Thanks!
UPDATE -----------------
It does appear that I'm not following something with the directory path. If I change directory to root's home directory:
# cd
I see my output file "test.log" with all the dates printed out every minute.
So, I will update my question to be, what am I miss-understanding about the /path? Is there a term I need to use to have it start from the root directory?
Cheers!
UPDATE 2 -----------------
Ok, so I got what I was missing.
The script to setup crontab was working right. It was finding the file relative to the root directory. ie:
* * * * * /var/test/cron-test.sh
But the "cron-test.sh" file was not set relative to the root directory. Thus, when "root" ran the script, it dumped it back into "root's" home directory. My thinking was that since the script was being run in "/var/test/" that the file would also be dumped in "/var/test/".
Instead, I need to set the location in the script file to dump it out correctly.
echo "$(date): cron job run" >> /var/test/test.log
And that works.
A: You have not provided any path for test.log so it will be created in the current path(which is the home directory of the user by default).
You should update your script and provide the full path, e.g:
echo "$(date): cron job run" >> /var/log/test.log
A: To restate the answer you gave yourself more explicitely: cronjobs are started in the home directory of the executing user, in your case root. That's why a relative file ended up in ~root.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Change windows default playback device How can I change the default playback device in windows 7, .net 4/4.5. I change the default device frequently and I want to make a little C# application to switch faster.
Is it even possible? Please help me.
A: Yes it is. However microsoft somehow did not want us to tamper with this. You can follow this project : http://www.codeproject.com/Articles/31836/Changing-your-Windows-audio-device-programmaticall
and adapt it to use with C#.
I have done something similar so it's not so hard to do!
A: I think you'll be able to do this by editing the registry. You get many programs to take snapshots of your registry. In doing this you'll be able to see where the changes are being made. It will take some time but is worth it. Also note that if this is Windows 7 you'll have to jump through hoops to be able to make some changes.
Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: NuGet and nUnit automation I have a VS project and in the project properties under the Debug tab I set:
Start External Program: D:\SolutionName\packages\NUnit.2.5.10.11092\tools\nunit.exe
Command Arguments: projectname.dll
This lets me start nUnit and run the nunits tests dll and when I start debugging the project.
Is there a better way? We use TFS and not everyone installs the solution to d: and the version number in the path where NuGet installs it changes periodically.
Was hoping to some how grab the text of the nunit.exe path from the path in the VS: Project : References section that was placed there by NuGet. This way I wouldn't have to change it for nUnit version changes and other TFS users wouldn't have to change it either.
Any ideas?
A: You might want to take a look at this:
http://lostechies.com/joshuaflanagan/2011/06/24/how-to-use-a-tool-installed-by-nuget-in-your-build-scripts/
A: If you're using NUnit in NuGet, then the runner will be in packages\NUnit(version)\, so you could probably use $(SolutionDir)packages\NUnit(blah) in the External Program command to run the version pulled from the NuGet package.
A: As Danny mentioned, install it to a relative (to your source code) tools folder via NuGet, ie
./tools/nuget.exe install Nunit.Runners -o ./tools
Then in your project configuration, just use the relative path.
A: I ran into the same issue. After a great deal of searching I found this question: Get NuGet package folder in MSBuild
Basically, you can create a project item containing a sort-of "wildcard" in the path name in place of the specific version number and then tell MSBuild to retrieve the relative path directory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: EF Table per Hierarchy (TPH) not saving because can't insert value null in Discriminator column I have a table used for multiply type of category and it contains a Discriminator column named 'ClassName' to specify the type of object to load. The ClassName column is non nullable with a default value of 'Category'
My problem is when saving a new item , I get the error :
'Cannot insert the value null into column ClassName' table Category.
I tought that ef would set the ClassName value base on the new object class.
How can I save my object with the right 'ClassName' value ?
A: I changed my db Structure to accept null. EF will set null if the object name match the table name and will set the discreminator name for the derived classes.
A: It's old question but I just met it today. In .net 4.0 code first I don't meet "disclaimer column" but when downgrade to net 3.5, it make me tired for a day.
This is my solution
Change the column in the database to ALLOW NULL (using alter table)
and update the edmx file to make it update the change(allow null)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting values from XML type field using in SQL server I have MS SQL table which contains a XML type field. This field has data in the format below:
<doc>
<quote>
<code>AA</code>
</quote>
<quote>
<code>BB</code>
</quote>
<quote>
<code>CC</code>
</quote>
</doc>
The quotes can be in different orders. I need to see the data in the below format which shows which quote came first second and third for each document.
Code 1 Code 2 Code 3
--------------------------------
AA BB CC
BB AA CC
A: Try this:
DECLARE @test TABLE(ID INT, XmlCol XML)
INSERT INTO @test VALUES(1, '<doc>
<quote>
<code>AA</code>
</quote>
<quote>
<code>BB</code>
</quote>
<quote>
<code>CC</code>
</quote>
</doc>')
INSERT INTO @test VALUES(2, '<doc>
<quote>
<code>BB</code>
</quote>
<quote>
<code>AA</code>
</quote>
<quote>
<code>CC</code>
</quote>
</doc>')
SELECT
ID,
X.Doc.value('(quote/code)[1]', 'varchar(20)') AS 'Code1',
X.Doc.value('(quote/code)[2]', 'varchar(20)') AS 'Code2',
X.Doc.value('(quote/code)[3]', 'varchar(20)') AS 'Code3'
FROM @test
CROSS APPLY xmlcol.nodes('doc') AS X(Doc)
Gives you an output of:
ID Code1 Code2 Code3
1 AA BB CC
2 BB AA CC
A: declare @x xml = '<doc>
<quote>
<code>AA</code>
</quote>
<quote>
<code>BB</code>
</quote>
<quote>
<code>CC</code>
</quote>
</doc>';
select @x.value('(doc/quote/code)[1]', 'varchar(max)')
, @x.value('(doc/quote/code)[2]', 'varchar(max)')
, @x.value('(doc/quote/code)[3]', 'varchar(max)')
For @marc_s,
DECLARE @test TABLE(ID INT, XmlCol XML)
INSERT INTO @test VALUES(1, '<doc>
<quote>
<code>AA</code>
</quote>
<quote>
<code>BB</code>
</quote>
<quote>
<code>CC</code>
</quote>
</doc>')
INSERT INTO @test VALUES(2, '<doc>
<quote>
<code>BB</code>
</quote>
<quote>
<code>AA</code>
</quote>
<quote>
<code>CC</code>
</quote>
</doc>')
SELECT
ID,
XmlCol.value('(doc/quote/code)[1]', 'varchar(20)') AS 'Code1',
XmlCol.value('(doc/quote/code)[2]', 'varchar(20)') AS 'Code2',
XmlCol.value('(doc/quote/code)[3]', 'varchar(20)') AS 'Code3'
FROM @test
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to represent a binary tree with tables (html)? Here is a brain-teaser for the brave. I've been at it for days and just can't come with the solution.
I wanted to come out with something like this:
Using html, CSS and PHP only.
I got near, but not quite what I expected. Here is the code in PHP and here is the output.
<table border="0">
<thead>
<tr>
<th>Cientoveintiochavos</th>
<th>Seseintaicuatravos</th>
<th>Treintaidosavos</th>
<th>Dieciseisavos</th>
<th>Octavos</th>
<th>Cuartos</th>
<th>Semifinales</th>
<th>Final</th>
</tr>
</thead>
<tbody>
<?php for($i=0;$i<256;$i++): ?>
<tr>
<?php for($n=0,$c=2;$n<8;$n++,$c*=2): ?>
<?php
/*
if(false){//$i == 0) {
$rwspn = $c/2+1;
$iter = 0;
} else {
$rwspn = $c;
$iter = $c;//-$c/2+1;
}
*/
$class = ($i%($c*2))?'par':'impar winner';
if($i%$c==0):?>
<td rowspan="<?=$c;?>" class="<?=$class;?>"><span><?php echo genRandomString();?></span></td>
<?php endif; ?>
<?php endfor; ?>
</tr>
<?php endfor; ?>
</tbody>
</table>
If someone knows how to represent a binary tree or a dendrogram or comes up with a smarter code please let me know!
A: I've done something like this, using divs kinda like @HugoDelsing. The way I handled the lines was to divide each pair into 4 vertically-stacked divs:
*
*The first player (border-bottom)
*A spacer between 1st and 2nd players (border-right)
*The second player (border-bottom and border-right)
*A spacer before the next pair (no borders)
Each of these gets 1/4 the height of the pair*, and the total height of a pair gets doubled as you move to the right. If you don't have a power of two, fill slots with placeholders to push everything down the right amount.
*The bottom borders will throw the heights off by 1, so take that into account when styling your rows.
Other Notes
The spacer divs may not be necessary, but for me they easily handled the spacing and getting the different columns to line up correctly.
I used inline styles filled-in by PHP for the heights, so I didn't have an arbitrary depth limit or calculations hard-coded into CSS.
Here's an example.
EDIT
OK, here is teh codez:
<style type="text/css">
.round{
float:left;
width:200px;
}
.firstTeam, .secondTeam{
border-bottom:1px solid #ccc;
position:relative;
}
.firstSpacer, .secondTeam{
border-right:1px solid #ccc;
}
.team{
position:absolute;
bottom: 4px;
left: 8px;
}
</style>
<div class="round">
<div class="matchup">
<div class="firstTeam" style="height:29px;"><div class="team">Team One</div></div>
<div class="firstSpacer" style="height:30px;"> </div>
<div class="secondTeam" style="height:29px;"><div class="team">Team Two</div></div>
<div class="secondSpacer" style="height:30px;"> </div>
</div>
<div class="matchup">
<div class="firstTeam" style="height:29px;"><div class="team">Team Three</div></div>
<div class="firstSpacer" style="height:30px;"> </div>
<div class="secondTeam" style="height:29px;"><div class="team">Team Four</div></div>
<div class="secondSpacer" style="height:30px;"> </div>
</div>
<div class="matchup">
<div class="firstTeam" style="height:29px;"><div class="team">Team Five</div></div>
<div class="firstSpacer" style="height:30px;"> </div>
<div class="secondTeam" style="height:29px;"><div class="team">Team Six</div></div>
<div class="secondSpacer" style="height:30px;"> </div>
</div>
<div class="matchup">
<div class="firstTeam" style="height:29px;"><div class="team">Team Seven</div></div>
<div class="firstSpacer" style="height:30px;"> </div>
<div class="secondTeam" style="height:29px;"><div class="team">Team Eight</div></div>
<div class="secondSpacer" style="height:30px;"> </div>
</div>
</div>
<div class="round">
<div class="matchup">
<div class="firstTeam" style="height:59px;"><div class="team">Team One</div></div>
<div class="firstSpacer" style="height:60px;"> </div>
<div class="secondTeam" style="height:59px;"><div class="team">Team Three</div></div>
<div class="secondSpacer" style="height:60px;"> </div>
</div>
<div class="matchup">
<div class="firstTeam" style="height:59px;"><div class="team">Team Five</div></div>
<div class="firstSpacer" style="height:60px;"> </div>
<div class="secondTeam" style="height:59px;"><div class="team">Team Eight</div></div>
<div class="secondSpacer" style="height:60px;"> </div>
</div>
</div>
<div class="round">
<div class="matchup">
<div class="firstTeam" style="height:119px;"> </div>
<div class="firstSpacer" style="height:120px;"> </div>
<div class="secondTeam" style="height:119px;"> </div>
<div class="secondSpacer" style="height:120px;"> </div>
</div>
</div>
<div class="round">
<div class="matchup">
<div class="firstTeam" style="height:239px;"> </div>
</div>
</div>
A: I wouldnt use a table but divs.
*
*create a column container div with relative/absolute position with a fixed width (eg: 200px) for each col.
*Each column container has inner divs with a height and lineheight of double the previous column container
*create a long black vertical line image (length atleast the half the size of the largest height of inner divs in any column. Start the line with a horizontal line of 200px wide to the left (so rotate an L with 180degrees). Leave about half the text height of free space above the horizontal line in the image, so the line will be under the text.
*set this image as background to the inner div of each column container and position it at left center; repeat = none;
Some sample code (without images)
<style type="text/css">
div.col { position:absolute;border:1px solid #f00;width:200px;top:0px; }
div.col1 { left:0px; }
div.col1 div { height:20px; line-height:20px; }
div.col2 { left:200px; }
div.col2 div { height:40px; line-height:40px; }
div.col3 { left:400px; }
div.col3 div { height:80px; line-height:80px; }
div.col4 { left:600px; }
div.col4 div { height:160px; line-height:160px; }
div.col5 { left:800px; }
div.col5 div { height:320px; line-height:320px; }
</style>
<div class='col1 col'>
<div>player1</div>
<div>player2</div>
<div>player3</div>
<div>player4</div>
<div>player5</div>
<div>player6</div>
<div>player7</div>
<div>player8</div>
<div>player9</div>
<div>player10</div>
<div>player11</div>
<div>player12</div>
<div>player13</div>
<div>player14</div>
<div>player15</div>
<div>player16</div>
</div>
<div class='col2 col'>
<div>player1</div>
<div>player3</div>
<div>player5</div>
<div>player7</div>
<div>player9</div>
<div>player11</div>
<div>player13</div>
<div>player15</div>
</div>
<div class='col3 col'>
<div>player1</div>
<div>player5</div>
<div>player9</div>
<div>player13</div>
</div>
<div class='col4 col'>
<div>player1</div>
<div>player9</div>
</div>
<div class='col5 col'>
<div>player1</div>
</div>
A: Looks like you're almost there. Nice work! I think the center alignment you want is in CSS
td {
vertical-align: middle;
}
I don't think you can get the lines to work using borders. You might try a background image for them instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: JPL for java\prolog I'm interested in using JPL with java, but an error message is prompting like 'package jpl does not exist' while trying to compile the java program. How do i import jpl to java?
A: You need to do sudo apt-get install swi-prolog and then sudo apt-get install swi-prolog-java
A: You need to download the JPL package/s , then make it accessible to your class(I'm not exactly sure where to put it, but probably in the /lib of your java directory) . See here : http://www.swi-prolog.org/download/stable
More info: How to use JPL (bidirectional Java/Prolog interface) on windows?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SoftPhone and linux We are thinking about writing a softphone app. It would basically be a component of a system that has calls queued up from a database. It would interface with a LINUX server which has Asterisk installed.
My first question is
Whether we should write the softphone at all or just buy one?
Secondly, if we do,
what base libraries should be use?
I see SIP Sorcery on CodePlex. More than anything, I am looking for a sense of direction here. Any comments or recommendations would be appreciated.
A: The answer would depend on the capabilities you have in your team and the place you see your core value and the essence of the service you provide.
In most cases, I'd guess that you don't really care about SIP or doing anything fancy with it that require access to its low level. In such a case, I'd recommend getting a ready-made softphone - either a commercial one or an open source one. I'd go for a commercial one, as it will give you the peace of mind as to its stability and assistance with bug fixing and stuff.
A: To directly answer your question, one of the many open source softphones are likely to fit your needs, and allow slight modifications as needed. Under most open source licenses there is no obligation to distribute your code as long as you only use it internally (do not distribute the binary.)
Trying to guess what you are trying to do, it sounds like a call center like scenario, so one of the many call queue implementations out there might fit your needs.
A: I had to write an own softphone and I found a great guide how to achieve it. In the guide there are 10 steps provided for having an own softphone (voip-sip-sdk.com on page 272)
I found it useful and maybe you will find it as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to pass a parameter in my method to return using a stateless session? minimize code duplication I want to pass a parameter in my method call, if set (its a boolean), then return a Stateless session.
I don't want to duplicate the QueryOver code, is there a way to have it like:
public virtual IList<User> GetAllUsers(bool isStateless)
{
var query = QueryOver<User>().Where(x => x.UserType == 1).ToList();
if(isStateless)
return NHibernateHelper.Session(query);
else
return NHibernateHelper.StatelessSession(query);
}
I know the above won't work, but I hope it is clear what I am after.
The only way I know is to basically duplicate the entire queryover code, and the only different between the code blocks will be that one will use .Session and the other will use .StatelessSession.
Hoping there is a cleaner way.
A: var query = QueryOver.Of<User>().Where(x => x.UserType == 1);
IQueryOver<User, User> executableQuery;
if(isStateless)
executableQuery = query.GetExecutableQueryOver(NHibernateHelper.Session);
else
executableQuery = query.GetExecutableQueryOver(NHibernateHelper.StatelessSession);
return executableQuery.ToList();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I have a cache of dropdown data instead of getting it from DB on every request? I am populating three dropdown menus using database stored procs. Each time the page is called it executes the store procedure and populates the dropdowns. Doing so it takes much amount of time. Is there any other way that I can have a cache of the data and can use it rather than executing the stored procedure?
A: Store it in the application or session scope. Assuming that those dropdowns represent application wide constants, then you could use a ServletContextListener for this. It get executed only one on webapp's startup.
E.g.
@WebListener
public class ApplicationDataConfigurator implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = populateAndGetItSomehow();
event.getServletContext().setAttribute("countries", countries);
// ...
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP.
}
}
ServletContext attributes are also available in JSP EL the usual way:
<select name="countries">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
If you'd rather like to store it in the session instead, then use a preprocessing servlet instead which checks in doGet() if they aren't already present in the current session and then populate it. You only need to realize that this may impact the total memory usage when it concerns large data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Site dies after so long? I have a website doing some things that I've never seen before. My server is Win 2003 w/ IIS6 I'm using C# and .Net 4.0.
The site is a real-estate website that stores the data directly in my db. The site will run great for a little while and then just die. What I mean is you'll try to view a property's details and it will take the site 2-3 minutes to load, if it loads at all. If I simply resave the web.config file and reupload it to restart the app, it runs just fine for a little while and then will die again. This continues over and over. I've gone to the local copy while the live site has "died" and the local copy will run just fine and then it will die after so long as well. The time frame that it takes varies from 5 minutes to 30 minutes, i believe it has something to do with the number of requests.
Anyone have any clue as to what might be happening? The only the data query on the page is to pull the main data which is the LINQ query below:
public Listing GetListingByMLNumber(string MLNumber)
{
try
{
DatabaseDataContext db = new DatabaseDataContext();
var item = (from a in db.Listings
where a.ML_.ToLower() == MLNumber.ToLower()
select a).FirstOrDefault();
return item;
}
catch (Exception ex)
{
Message = ex.Message;
return null;
}
}
A: Not closing the database context stands out as the obvious error in the code you provided. Wrap it in a using statement to be sure it gets disposed correctly.
As long as the context lives, you will hold on to a sql connection, which is a limited resource. You will also waste memory by change-tracking the entities you returned. Given your code the context should be garbage collected at some point, but it might still be the problem (And, whether or not this is the problem, you should dispose your database contexts).
Try load testing locally to see if you can reproduce the problem. If you can, then use the debugger to figure out the problem. If not, you probably need to add logging to narrow down the problem.
You could also look at the IIS process to see if it uses absurd amounts of memory, handles, etc. Also check IIS settings for performance and application pool recyling as suggested in another answer here.
A: I would take a look at the application pool settings to see how the worker processes are being recycled, and I would also look under the Performance tab in IIS to see if there's a bandwidth threshold specified.
A: If you ever hit this type of problem again then your should add DebugDiag/ADPlus and WinDBG to your diagnostic toolbelt.
When your application hangs again or is taking an exceedingly long time to respond to requests then grab a dump of the worker process using DebugDiag or ADPlus. Load this up into WinDBG, load up SOS (Son of Strike) which is a WinDBG extension for managed code debugging and start digging around.
Tess Ferrandez has a great set of tutorials and labs on how to use these tools effectively:
.NET Debugging Demos - Information and setup instructions
They've gotten me out of a few pickles several times and it's well worth spending the time familiarising yourself with them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to read all child nodes of an XML file I've got this file:
<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:app='http://purl.org/atom/app#' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:gml='http://www.opengis.net/gml' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:georss='http://www.georss.org/georss'>
<id>http://gdata.youtube.com/feeds/api/users/snifyy/favorites</id>
<updated>2011-09-26T16:21:40.933Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/>
<title type='text'>Favorites of snifyy</title>
<logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
<author>
<name>snifyy</name>
<uri>http://gdata.youtube.com/feeds/api/users/snifyy</uri>
</author>
<generator version='2.1' uri='http://gdata.youtube.com'>YouTube data API</generator>
<openSearch:totalResults>631</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://gdata.youtube.com/feeds/api/videos/LXO-jKksQkM</id>
<published>2011-09-23T16:15:27.000Z</published>
<updated>2011-09-26T16:21:15.000Z</updated>
<title type='text'>PUMPED UP KICKS|DUBSTEP</title>
<content type='text'>DUBSTEPPIN!!! to a beast track remixed by "butch clancy"</content>
<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=LXO-jKksQkM&feature=youtube_gdata'/>
<link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/LXO-jKksQkM/responses'/>
<link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/LXO-jKksQkM/related'/>
<link rel='http://gdata.youtube.com/schemas/2007#mobile' type='text/html' href='http://m.youtube.com/details?v=LXO-jKksQkM'/>
<link rel='related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/LXO-jKksQkM'/>
<link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/snifyy/favorites/LXO-jKksQkM'/>
<author>
<name>WHZGUD2</name>
<uri>http://gdata.youtube.com/feeds/api/users/whzgud2</uri>
</author>
<gd:comments>
<gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/LXO-jKksQkM/comments' countHint='3738'/>
</gd:comments>
<media:group>
<media:category label='Entertainment' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Entertainment</media:category>
<media:content url='http://www.youtube.com/v/LXO-jKksQkM?f=user_favorites&app=youtube_gdata' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='327' yt:format='5'/>
<media:content url='rtsp://v3.cache5.c.youtube.com/CioLENy73wIaIQlDQiypjL5zLRMYDSANFEgGUg51c2VyX2Zhdm9yaXRlcww=/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='327' yt:format='1'/>
<media:content url='rtsp://v1.cache2.c.youtube.com/CioLENy73wIaIQlDQiypjL5zLRMYESARFEgGUg51c2VyX2Zhdm9yaXRlcww=/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='327' yt:format='6'/>
<media:description type='plain'>DUBSTEPPIN!!! to a beast track remixed by "butch clancy"</media:description>
<media:keywords>DUBSTEP, butch, clancy, bass</media:keywords>
<media:player url='http://www.youtube.com/watch?v=LXO-jKksQkM&feature=youtube_gdata_player'/>
<media:thumbnail url='http://i.ytimg.com/vi/LXO-jKksQkM/0.jpg' height='360' width='480' time='00:02:43.500'/>
<media:thumbnail url='http://i.ytimg.com/vi/LXO-jKksQkM/1.jpg' height='90' width='120' time='00:01:21.750'/>
<media:thumbnail url='http://i.ytimg.com/vi/LXO-jKksQkM/2.jpg' height='90' width='120' time='00:02:43.500'/>
<media:thumbnail url='http://i.ytimg.com/vi/LXO-jKksQkM/3.jpg' height='90' width='120' time='00:04:05.250'/>
<media:title type='plain'>PUMPED UP KICKS|DUBSTEP</media:title>
<yt:duration seconds='327'/>
</media:group>
<gd:rating average='4.96415' max='5' min='1' numRaters='24435' rel='http://schemas.google.com/g/2005#overall'/>
<yt:statistics favoriteCount='16660' viewCount='924793'/>
</entry>
</feed>
And I want to load all entries and then their title, content and thumbnail. But I have problems even loading the entries. That's my code (data is this xml):
XmlDocument xml = new XmlDocument();
xml.LoadXml(data);
XmlNodeList xnList = xml.SelectNodes("feed/entry");
foreach (XmlNode xn in xnList) {
Debug.WriteLine(xn.LocalName.ToString());
}
A: The problem is that your XPath doesn't specify the namespaces (so you're actually searching for names with null namespace URIs). Given that feed is the top level element, it's a pretty trivial query - I don't think using XPath is actually helping you here. Try this instead, using XmlElement.GetElementsByTagName:
XmlElement root = doc.DocumentElement;
String atomUri = "http://www.w3.org/2005/Atom";
foreach (XmlElement element in root.GetElementsByTagName("entry", atomUri))
{
// Use element here
}
(If you get the chance to use .NET 3.5, I suggest you start using LINQ to XML - it's much nicer :)
EDIT: Here's a short but complete program printing out the url attribute of each content element:
using System;
using System.Xml;
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
XmlElement root = doc.DocumentElement;
String atomUri = "http://www.w3.org/2005/Atom";
String mediaUri = "http://search.yahoo.com/mrss/";
foreach (XmlElement entry in root.GetElementsByTagName("entry", atomUri))
{
foreach (XmlElement group in
entry.GetElementsByTagName("group", mediaUri))
{
foreach (XmlElement content in
entry.GetElementsByTagName("content", mediaUri))
{
Console.WriteLine(content.Attributes["url"].Value);
}
}
}
}
}
A: You can use XmlNamespaceManager to specify namspace from your feed:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(data);
XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
manager.AddNamespace("atom", "http://www.w3.org/2005/Atom");
XmlNodeList xnList = xDoc.SelectNodes("atom:feed/atom:entry", manager);
foreach (XmlNode xn in xnList)
{
Debug.WriteLine(xn.LocalName.ToString());
}
And any type when you trying to select nodes use prefix of the namespace, eg: atom:feed/atom:entry
Adding another namespace to work with multiple ones:
XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
manager.AddNamespace("atom", "http://www.w3.org/2005/Atom");
manager.AddNamespace("media", "http://search.yahoo.com/mrss/");
XmlNodeList mediaNodes = xDoc.SelectNodes("atom:feed/atom:entry/media:group", manager);
A: You need to use the Atom namespace when you select the feed/entry elements.
Create a namespace manager, add a namespace prefix for the Atom namespace, and then use it in your XPath expression.
For example code, see the accepted answer to this question.
A: Here's some help - http://www.kirupa.com/forum/showthread.php?292473-Reading-Child-nodes-from-XML-file-C
And How to read/write nodes and child nodes from xml file in c# maybe using xpath?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cannot Access Applet Containing JFileChooser From JSP I have written the following simple Applet that presents a File Uploader:
import java.io.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FileChooserDemo extends Applet implements ActionListener {
static private final String newline = "\n";
JButton openButton;
JTextArea log;
JFileChooser fc;
public void init() {
// Create the log first, because the action listeners
// need to refer to it.
log = new JTextArea(5, 20);
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);
// Create a file chooser
fc = new JFileChooser();
// Uncomment one of the following lines to try a different
// file selection mode. The first allows just directories
// to be selected (and, at least in the Java look and feel,
// shown). The second allows both files and directories
// to be selected. If you leave these lines commented out,
// then the default mode (FILES_ONLY) will be used.
//
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
// Create the open button. We use the image from the JLF
// Graphics Repository (but we extracted it from the jar).
openButton = new JButton("Open a File...");
openButton.addActionListener(this);
// For layout purposes, put the buttons in a separate panel
JPanel buttonPanel = new JPanel(); // use FlowLayout
buttonPanel.add(openButton);
// Add the buttons and the log to this panel.
add(buttonPanel, BorderLayout.PAGE_START);
add(logScrollPane, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
// Handle open button action.
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
// This is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline);
} else {
log.append("Open command cancelled by user." + newline);
}
log.setCaretPosition(log.getDocument().getLength());
// Handle save button action.
}
}
}
It runs fine except when I try to include it within a Web Application. I compiled it into a JAR and signed the JAR. Below is the JSP File referencing the Applet:
<%@ page language="java" %>
<html>
<head>
<title>Welcome JSP-Applet Page</title>
</head>
<body>
<jsp:plugin type="applet" code="FileChooserDemo" codebase="./applet" archive="Applet.jar"
width="400" height="400">
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>
</jsp:plugin>
</body>
</html>
When I try to open from my browser. I get the following error from the Java console Window:
java.security.AccessControlException: access denied (java.io.FilePermission C:\Users\jatoui\Documents read)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkRead(Unknown Source)
at java.io.File.exists(Unknown Source)
at java.io.Win32FileSystem.canonicalize(Unknown Source)
at java.io.File.getCanonicalPath(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2.createShellFolder(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2.getPersonal(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2.get(Unknown Source)
at sun.awt.shell.ShellFolder.get(Unknown Source)
at javax.swing.filechooser.FileSystemView.getDefaultDirectory(Unknown Source)
at javax.swing.JFileChooser.setCurrentDirectory(Unknown Source)
at javax.swing.JFileChooser.<init>(Unknown Source)
at javax.swing.JFileChooser.<init>(Unknown Source)
at com.blackducksoftware.proserv.applets.FileChooserDemo.init(FileChooserDemo.java:26)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.security.AccessControlException: access denied (java.io.FilePermission C:\Users\jatoui\Documents read)
Is there any way to overcome this???
A: java.security.AccessControlException: access denied
(java.io.FilePermission C:\Users\jatoui\Documents read)
An applet needs to be digitally signed by the developer, and trusted by the end user, before it can read or write files on the end-user's machine. (Unless it is deployed in a plug-in 2 JRE and used the JNLP API Services for accessing the local file system.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: UIToolbar custom background image in loadView method I set
self.navigationController.toolbarHidden = NO;
That will display a toolbar at the bottom of every view.
Now I want to have a custom background for every toolbar. So in app delegate I have following code:
@implementation UIToolbar(CustomImage)
-(void)drawRect:(CGRect)rect{
UIImage *image = [UIImage imageNamed:@"toolbar.png"];
[image drawInRect:self.bounds];
}
@end
but this has no effect. The color has still this standard blue color. How can I have a custom background?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Refresh Databinding when Using Entity Model I have a list box that is databound to a collection from the entity frame work.
I need to find a way to update this listbox in the main window when a new object is added using another window. I see in the entity model, there is
protected override sealed void ReportPropertyChanging(string property);
but i don't know how to use this, or even if this is what it is for.
Here is my Main Window C#
public partial class MainWindow : Window
{
List<Game> _GameColletion = new List<Game>();
GameDBEntities _entity = new GameDBEntities();
public MainWindow()
{
InitializeComponent();
_GameColletion = _entity.Games.ToList<Game>();
DataContext = _GameColletion;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var newWindow = new AddGame();
newWindow.Show();
}
}
here is the list box xaml
<ListBox ItemsSource="{Binding}" Name="GameList"></ListBox>
And Finally Here is the code from another window that inserts a new Game into the Entity.
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
_newGame.Date = date.SelectedDate.Value;
_newGame.Time = time.Text;
MainWindow w = new MainWindow();
w._entity.AddToGames(_newGame);
w._entity.SaveChanges();
this.Close();
}
catch (Exception ex) { }
}
I just need that listBox to refresh when ever anything is added to or changed in the entity.
Thanks!
UPDATE: Here is what I have based on the posts, it still is not working
ObservableCollection<Game> _GameColletion;
GameDBEntities _entity = new GameDBEntities();
public MainWindow()
{
InitializeComponent();
DataContext = GameCollection;
}
public ObservableCollection<Game> GameCollection
{
get
{
if (_GameColletion == null)
{
_GameColletion = new ObservableCollection<Game>(_entity.Games.ToList<Game>());
}
return _GameColletion;
}
}
A: looks like you are using a List<Game> as your backing collection. In WPF, if you want notifications when the collection has items added or removed, use ObservableCollection<Game> instead (MSDN documentation here). Now, that said, it should be noted that only add/remove events are watched. There is NO notification on the individual objects that are being held in the collection. so, for example, if a property changes on your Game object that is held in the collection (say, a Score) property, your UI will NOT be notified. If you want this behavior, you can sub-class the ObservableCollection to add this behavior.
the ObservableCollection uses INotifyCollectionChanged(MSDN documentation here) interface, which the ListBox, ItemsControl, etc. respond to.
EDIT
ok, i see what is going on now... in addition to the changes above, and the changes to your getter, when you make a new game on the other window, it is getting added to the entity collection, but NOT to the observable collection. you need to add it to your observable collection. what you need to do to pass the OC to the child window is set ITS DataContext to your observable collection...
private void Button_Click(object sender, RoutedEventArgs e)
{
var newWindow = new AddGame();
newWindow.DataContext = this.DataContext; // ----> new code to set the DC
newWindow.Show();
}
// in the other window...
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
_newGame.Date = date.SelectedDate.Value;
_newGame.Time = time.Text;
((ObservableCollection<Game>)DataContext).Add( _newGame ); // ----> new code
entity.AddToGames(_newGame);
entity.SaveChanges();
this.Close();
}
catch (Exception ex) { }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linux app sends UDP without socket fellow coders.
I'm monitoring my outgoing traffic using libnetfilter_queue module and an iptables rule
ipatbles -I OUTPUT 1 -p all -j NFQUEUE --queue-num 11220
A certain app, called Jitsi (which runs on Java) is exhibiting such a strange behaviour a haven't encountered before:
My monitoring program which process NFQUEUE packets clearly shows that UDP packets are being sent out,
yet when I look into:
"/proc/net/udp" and "/proc/net/udp6" they are empty, moreover "/proc/net/protocols" has a column "sockets" for UDP and it is 0.
But the UDP packets keep getting sent.
Then after a minute or so, "/proc/net/udp" and "/proc/net/protocols" begin to show the correct information about UDP packets.
And again after a while there is no information in them while the UDP packets are being sent.
My only conclusion is that somehow it is possible for an application to send UDP packets without creating a socket and/or it is possible create a socket, then delete it (so that kernel thinks there are none) and still use some obscure method to send packets outside.
Could somebody with ideas about such behaviour land a hand, please?
A: Two ideas:
Try running the app through strace and take a look at that output.
You could also try to run it through systemtap with a filter for the socket operations.
From that link:
probe kernel.function("*@net/socket.c").call {
printf ("%s -> %s\n", thread_indent(1), probefunc())
}
probe kernel.function("*@net/socket.c").return {
printf ("%s <- %s\n", thread_indent(-1), probefunc())
}
A: Thank you Paul Rubel for giving me a hint in the right direction. strace showed that Java app was using IPv6 sockets. I had a closer look at /proc/net/udp6 and there those sockets were. I probably had too cursory a view the first time around chiefly because I didn't even expect to find them there. This is the first time I stumbled upon IPv4 packets over IPv6 sockets. But that is what Java does.
Cheers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to show something when an image displays? I want to check if an application is running on another server and the only way I can do this is by displaying an image that it provides.
If it doesn't provide the image, I use the alt attribute to inform that the app is down.
I cannot modify what's in the image, so I need a way to show something else that says that the app is up instead of saying "if you see this image it means that the app is up".
I'd like a CSS/HTML solution, if not, a JS or PHP one.
I'm thinking of hiding the image itself with the "the app is up" message but I don't know how. It doesn't work like image replacement usually do.
A: You can choose a custom message to display when the image is down using pure HTML and CSS, but for the image loading successfully, I think you're out of luck. Use a JavaScript Ajax request and check the returned status header, and you won't even have to create an image.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Less stylesheet file 406 on IIS7/discountaspnet I have a site, http://www.allampersandall.com that i'm trying to post up to discountasp.net. It runs great locally in VS2010 debug, but when i post it up all my .less files HTTP 406.
When i looked up HTTP 406, it says its the browser not accepting it-- but why would it run locally but not up on live?
Any ideas?
Thanks,
A: I fixed this in the end....
The 406 error is basically telling you that there was a mismatch between what the browser was expecting and what the server sent it.
In my case it was the fact that my web.config was telling the browser that any files with an extension of .less were to be served as the mime type "text/css".
<staticContent>
<mimeMap fileExtension=".less" mimeType="text/css" />
</staticContent>
Where as, in my site, the file was being declared as "text/less"
<link href="@Url.Content("~/Content/style.less")" rel="stylesheet/less" type="text/less" />
To fix it I changed the "mimeType" setting in the web.config to match the declaration in the page so the web.config section is now:
<staticContent>
<mimeMap fileExtension=".less" mimeType="text/less" />
</staticContent>
I hope that helps!
Cheers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: What is the standard for testing in Java? What apps would you use? Are there auto testing suites like autotest for ruby? What do you use and why? To be honest, I don't even know how to write tests, when, or why. I'd like to learn though, I know that it will make me a better developer.
Our team uses Netbeans, not eclipse, although I'm going to still google eclipse responses to see if they are implemented as a Netbeans solution as well.
A: There are 2 most popular frameworks for unit tests: JUnit and TestNG. Both are annotation based. To create test you have to create class and mark each method that performs test using annotation @Test.
JUnit is older and have more extensions (DBUnit, Cactus etc). TestNG has much more annotations. Very important feature of TestNG is ability to create test groups using annotations.
Yet another group of tools you will probably need is mocking tools (EasyMock, EasyMock etc.)
A: There are a bunch of testing frameworks that are popular. JUnit is pretty good and comes by default with Eclipse. It provides an API for defining tests and doing assertions, as well as a Testrunner to execute the tests. EasyMock and Mockito work well with JUnit to provide mocking functionality so you can test components in isolation.
For continuous integration, there is Jenkins, which is free.
There are others as well.
A: I would use junit and possibly a mocking library like jmock.
Most of the automatic "tests" which can be done use the compiler or a code analysis tool like FindBugs.
A: Don't forget TestNG. It's the "next generation" beyond JUnit. It handles threaded tests better.
SOAP UI is the right tool for testing SOAP web services.
JMeter or Grinder for load testing.
A: In addition to what has already been said (JUnit, EasyMock, ...) you may also have a look at Fitnesse: it may be a good tool for full integration and acceptance tests!
A: As JUnit and Mockito was already mentioned, You can look into Infinitest or JUnit Max for autotesting.
http://infinitest.github.com/
http://junitmax.com/
A: If you are looking for something that implements continuous testing I can recommend two free products:
For a developer during work in Eclipse/IntelliJ IDE:
http://infinitest.github.com/
Infinitest is an Eclipse/IntelliJ plugin that runs your test continuously in the background while you are developing your code.
For a team:
http://hudson-ci.org/
or
http://jenkins-ci.org/
are great continuous integration servers that can do builds and run tests continuously.
A: Been writing junits for over 7 years now and I highly recommend spock for all your testing needs: unit and integration testing, mocking, end-to-end testing, data driven testing etc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Info Window With Marker Manager Google Maps V3 I have many map markers with the exact same lat/long cords so no matter how far in I zoom my map still shows the marker cluster and the number of results.
Is there a way to have some onclick or onhover event so that it shows an info box with all of the markers in that cluster in a list? Then clicking a link within that info box opens up that individual marker info box?
I've read solutions to change the lat, long by a small amount so that they aren't the same location. I think that is very messy and not that good anyways if there ends up being multiple markers 10+ anyways at the same locationg. I think it'd be much easier for a user to just click the cluster and bring up the info window with all of those markers in there with links.
Or if someone knows another plugin that does what I am seeking I could work with that too. I just haven't found much info on it.
A: There might be a plug in out there to do what you want, but it's also possible to do without one. I did something like that in one of my projects.
*
*Add event listener to each marker; clicking opens marker list info window
*The content of the marker list info window contains onclick attributes that will open the marker info window.
My code was tucked away into functions, but it was basically just this:
//1) while creating marker, create click listener that opens the marker list
google.maps.event.addListener(marker, 'click', function() {
markerWindow.close();
markerList.open(map, marker);
});
//2) store the content required by the marker's info windows
var markers = [
[marker1Reference, "The Stadium"],
[maerker2Reference, "The Supermarket"]
];
//3) the function that is called each time a marker is chosen from the marker list
function openMarkerInfo(markerIndex) {
markerList.close();
markerWindow.setContent(markers[markerIndex][1]);
markerWindow.open(map, markers[markerIndex][0]);
}
//4) info window for the marker list - the content includes JS onclick events that will open each marker info window
markerList = new google.maps.InfoWindow({
content: "Choose:<br><br><div href='' class='markerLink' onclick='openMarkerInfo(0)'>The Stadium</div><br><div href='' class='markerLink' onclick='openMarkerInfo(1)'>My House</div>"
});
//5) the marker window that will get set each time a marker is clicked in the list
markerWindow = new google.maps.InfoWindow();
Hope that helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sqlite with multiple NHibernate Session Factories I have a problem in that I have switched my (working) multiple-database nhibernate solution to DI its session factory so that I can use SqlLite from within my integration test suite.
Whereas using a physical file where i can use multiple file names, one for each db works (see code below), I am not sure how to do that with it in memory. Maybe its just a limitation inflicted by sqlite when in memory? What happens is that each subsequent call to InMemory() overwrites the existing one even though each factory gets its own key on the current thread.
public override Configuration BuildSessionFactoryFor(string databaseName, bool showSql, IsolationLevel level)
{
Configuration cfg = null;
var filename = @"c:\temp\{0}-test.db".Substitute(databaseName);
if (File.Exists(filename)) File.Delete(filename);
var sqlConfig =
SQLiteConfiguration.Standard.ShowSql().UsingFile(filename); //.InMemory()
var sessionFactory = Fluently.Configure()
.Database(sqlConfig)
.ProxyFactoryFactory(typeof (ProxyFactoryFactory))
.Mappings(m =>
m.AutoMappings.Add(
new AutoPersistenceModelGenerator().GenerateSchema(databaseName)
)
)
.ExposeConfiguration(c =>
{
new SchemaExport(c).Execute(false, true, false);
cfg = c;
})
.BuildSessionFactory();
NHibernateSession.AddConfiguration(FactoryKeyFor(databaseName), sessionFactory, cfg, null);
return cfg;
}
A: You probably close or dispose NHIbernate session. The scope of the in-memory database is not ISessionFactory. It is ISession, so every time you close it explicitly or in a 'using' statement the database will be gone.
From In-Memory Databases:
The database ceases to exist as soon as the
database connection is closed. Every :memory: database is distinct
from every other. So, opening two database connections each with the
filename ":memory:" will create two independent in-memory databases.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MyISAM or InnoDB to use for my Large project, to do multiple work at a time As I have no more knowledge then usual about MyISAM, InnoDB engines, So I'm in confusion what engine to use for my large project, where
1) minimum 3000 users will log their account at a time (within hour)
2) and do some work like Update, delete data from their Account etc.
I'm on shared host. May anyone give me specific answer that what engine should I use for faster processing for above condition.
which database engine will speed up above works ? any help plz ?
A: Does your application use Foreign keys? If so, then you'll need to use the InnoDB engine. If it doesn't you can go ahead with MyISAM engine.
If there are many modifications of the data, it's said that InnoDB works faster because it uses row locking instead of table locking, like MyISAM. However, if there are mainly SELECT statements, a MyISAM table might be faster.
However, it's always important what the needs of a specific table are - so I would choose the storage engine that best fits the requirements for the given table. If you need foreign key constraints or transactions, you can only use InnoDB, wheras if you need fulltext indexes, you can only use MyISAM tables at the moment.
With replication it's even possible to take advantage of both storage engines on one table. For example, the master could store a table as InnoDB which makes it fast for INSERTs, UPDATEs and DELETEs while the slave(s) could store the same table as MyISAM and offer the best performance for SELECTs.
Source
A: both engines have advantages and disadvantages
*
*MYISAM
*
*myisam is very simple to use, thus it is easy to write third-party tools to interact with it.
*myisam have been around for a while so it's highly optimized
*myisam uses less memory than InnoDb and the actual data files are often quite a bit larger for Innodb
*InnoDb
*
*performance : u can read this blog about innodb's performance against myisam and falcon http://www.mysqlperformanceblog.com/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/
*InnoDB is a largely ACID (Atomicity, Consistency, Isolation, Durability) engine, it supports transactions
*InnoDB can run a backup job in a single transaction and pull consistent, database-wide backups with only a short lock at the beginning of the job. on the other hand myisam consistent back up requires database locks and this is totally unacceptable for a large websites.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Oracle - break dates into quarters Given 2 dates (StartDate and EndDate), how to do i generate quarterly periods in Pl/SQL.
Example:
Start Date: 01-JAN-2009
End Date: 31-DEC-2009
Expected Output:
StartDate EndDate
01-JAN-2009 31-MAR-2009
01-APR-2009 30-JUN-2009
01-JUL-2009 30-SEP-2009
01-OCT-2009 31-DEC-2009
A: SELECT ADD_MONTHS( TRUNC(PARAM.start_date, 'Q'), 3*(LEVEL-1) ) AS qstart
, ADD_MONTHS( TRUNC(PARAM.start_date, 'Q'), 3*(LEVEL) ) -1 AS qend
FROM ( SELECT TO_DATE('&start_date') AS start_date
, TO_DATE('&end_date') AS end_date
FROM DUAL
) PARAM
CONNECT BY ADD_MONTHS( TRUNC(PARAM.start_date, 'Q'), 3*(LEVEL) ) -1
<= PARAM.end_date
Rules for params, you may need to adjust the query to suit your purposes:
*
*If start_date is not exact quarter start it effectively uses the quarter contain start date.
*If end_date is not exact quarter end then we end on the quarter that ended BEFORE end_date (not the one containing end date).
A: Here's one way that you can do it with PL/SQL
declare
startDate Date := '01-JAN-2009';
endDate Date := '31-DEC-2009';
totalQuarters number := 0;
begin
totalQuarters := round(months_between(endDate, startDate),0)/3;
dbms_output.put_line ('total quarters: ' || totalQuarters);
for i in 1..totalQuarters loop
dbms_output.put_line('start date: '|| startDate || ' end date:' || add_months(startDate -1,3));
startDate := add_months(startDate,3) ;
end loop;
end;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: java to matlab conversion I am a newbie at matlab . As a part of a larger problem, I need to find maximum number of occurrences of a string in an array of Strings.
Since I have some experience in java I have written the partial code in java ( only until the number of occurences of the string within the string array can be computed I can sort the hashmap depending on the values and extract this)
int incr = 0;
String[] c = { "c1", "c2", "c3", "c1", "c2", "c2", "c2","c1","c2" };
Map<String, Integer> classRegistry = new HashMap<String, Integer>();
for (int i = 0; i < c.length; i++) {
String classes = c[i];
if (!(classRegistry.containsKey(classes))) {
for (int j = i + 1; j < c.length; j++) {
if (classes.equals(c[j])) {
incr++;
}
}
classRegistry.put(classes, incr+1);
incr = 0;
}
}
Any idea how i can use something like a hashMap in MATLAB to calculate the number of occurrences of all the strings in an array
Thanks,
Bhavya
A: MATLAB has a function TABULATE available in the Statistics Toolbox:
c = {'c1' 'c2' 'c3' 'c1' 'c2' 'c2' 'c2' 'c1' 'c2'};
t = tabulate(c)
t = t(:,1:2)
The result:
t =
'c1' [3]
'c2' [5]
'c3' [1]
Alternatively, you can do the same using the UNIQUE and ACCUMARRAY functions:
c = {'c1' 'c2' 'c3' 'c1' 'c2' 'c2' 'c2' 'c1' 'c2'};
[classes,~,subs] = unique(c);
counts = accumarray(subs(:),1);
Again the result as before:
>> t = [classes(:) num2cell(counts)]
t =
'c1' [3]
'c2' [5]
'c3' [1]
Then to find the string that occurred the most, use:
>> [~,idx] = max(counts);
>> classes(idx)
ans =
'c2'
A: You didn't specify exaclty how you would want your input and output data types to be, but I wrote this quick script you might find usefull.
c = {'c1' 'c2' 'c3' 'c1' 'c2' 'c2' 'c2' 'c1' 'c2'};
count = struct();
for ic=1:length(c)
field = c{ic};
if isfield(count, field)
count = setfield(count, field, getfield(count, field) + 1);
else
count = setfield(count, field, 1);
end
end
The output for this specific c would be
count =
c1: 3
c2: 5
c3: 1
A: Since you have experience with Java, you could just write your code in Java and call it from MATLAB. This techdoc article should help you get started if you decide to go this route. But it would probably be more useful to learn how to do it in m-script (see jomb87's answer)
Incidentally, you could improve the performance of your Java algorithm if you take further advantage of the hash map:
for (int i = 0; i < c.length; i++) {
String classes = c[i];
if (classRegistry.containsKey(classes)) {
classRegistry.put(classes, classRegistry.get(classes) + 1);
} else {
classRegistry.put(classes, 1);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: IntelliJ - Delete list of previously opened projects? Is there a way in IntelliJ IDEA to delete previously used projects? I am referring to a list on the main page when the application starts. Please look at the image.
A: In IntelliJ15, you can remove them from welcome screen, works ctrl+a and then remove all of them.
A: File -> Open Recent -> Clear List
Edit: For versions of 2016+ this is no longer available. Use This solution: File -> Open Recent -> Manage Recent Projects / Startup Dialog, ctrl+a (select multiple with ctrl+click) -> del
A: File -> Open Recent -> Manage Projects .... CTRL-A then Delete to remove all, or hit the X to remove individual.
IntelliJ IDEA 2016.2.5
A: In MAC, ~/Library/Preferences/IdeaIC14/options/recentProjects.xml is the file to easily edit the list when you do not want to lose everything. (It is for IdeaIC14).
A: Locate config\options\other.xml file and manually edit the list of recent projects inside the XML under <component name="RecentProjectsManager"> node.
There is no way to remove individual projects from the UI. See Dan's reply otherwise.
A: In idea 2022 for MAC it is located under ~/Library/Application Support/JetBrains/IntelliJIdea2022.3/options
A: In Idea 2019 it is located in Idea Colder\config\options\recentProjects.xml
A: Just figured, I am using Idea Community edition 13.1.1 and the cleanest and easiest way is to go to File > Reopen project > Clear List. I just stumbled upon this menu today. I always thought that is just to clear the latest projects from the view inside the IDE and just realized it is clearing the projects from the main Dialog too.
-VRS
A: Close all projects till you reach the welcome screen. Right click on the project and choose Remove Selected from Welcome Screen. Or click on the cross arrow on the upper right corner of the selected project.
A: idea22 on windows10 system, recent projects on the path C:\Users\****\AppData\Roaming\JetBrains\IntelliJIdea2022.3\options\recentProjects.xml, I delete all the <entry><\entry> labels
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: JSF convertNumber throws java.lang.IllegalArgumentException: argument type mismatch Error I'm using JSF 1.2. My IDE is RAD.
In my xhtml page Iam using a convertNumber tag to format an Integer variable. Integers need to be left padded with 0's if they are not 4 digits long (If the Integer value is 21, it should be displayed as 0021)
I have used a convertNumber to acheive this.
<f:convertNumber pattern="0000"/>
It looks fine when the values are being displayed, but when i try to input an integer value into the textbox, and try to save it, it throws the following error:
ava.lang.IllegalArgumentException: argument type mismatch
Am I doing something wrong ? Is custom validators the only way to acheive this ?
A: You can achieve that using <f:convertNumber minIntegerDigits="4"/>.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to divide a string into multiple parts and reconstruct it backwards? I have important data in a string and I want to randomly divide it into multiple parts(x) and then store it into multiple location(y).
If (locations > parts) how should I go about collecting data pseudo-randomly from x location (may be predefined groups), and able to reconstruct the data i had initially.
Please someone suggest me how to do this?
[EDIT]: I have divided data into 3 equals parts and hide it at multiple locations (6), i.e, every part at 2 locations. Then I pick from any of the two locations to rebuild it.
But I want it to be more efficient and random, therefore I would like to get suggestions on how to do that.
A: http://en.wikipedia.org/wiki/Erasure_code seems to talking about this sort of problem, and contains pointers to implementations.
http://www.usenix.org/event/fast09/tech/full_papers/plank/plank_html/ describes this sort of thing in the context of RAID.
These are for cases where the object is to reduce the odds of data loss. If the object is to make the data more secure, "secret splitting" might be a good first search term.
A: If you are going to be storing multiple strings at multiple locations you need a unique ID for each one so you can retrieve it later.
void Store(String, UID);
String Restore(UID);
If the locations and order are random then your string pieces need to be marked in the correct order.
LOCATION 1: String UID 1: String Piece 3
LOCATION 2: String UID 1: String Piece 1
LOCATION 3: String UID 1: String Peice 2
LOCATION 4: empty
When you retrieve you need to check every location for String UID collect all the string piece and rebuild in the correct order.
Here's an example using files:
Your 4 random locations are
c:\Folder1
c:\Folder2
c:\Folder3
c:\Folder4
Store("abcdefghij", 1);
c:\folder1\1.str
3
hij
c:\Folder2\1.str
1
abcd
c:\Folder3\1.str
2
efg
Store("1234567890", 2);
c:\folder1\2.str
2
567
c:\Folder3\2.str
3
890
c:\Folder4\2.str
1
1234
Restore(2)
Read c:\Folder1\2.str - Piece 2
Read c:\Folder2\2.str - Doesn't Exist
Read c:\Folder3\2.str - Piece 3
Read c:\Folder4\2.str - Piece 1
Sort Pieces
Concatenate Pieces
Return String
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Updating several records for same object Ok I'm really feeling I'm missing the rails way on this one.
Following my last question rails parameters in form_for, I can correctly update the message contents but am struggling with updating the recipients
My Draft model
class Draft < ActiveRecord::Base
belongs_to :message
belongs_to :draft_recipient, :class_name => "User"
delegate :created_at, :subject, :user, :body, :draft_recipients, :to => :message
...
My Message Model
class Message < ActiveRecord::Base
belongs_to :user
has_many :recipients, :through => :message_copies
has_many :draft_recipients, :through => :drafts
has_many :message_copies
has_many :drafts, :class_name => "Draft", :foreign_key => :message_id
attr_accessor :to #array of people to send to
attr_accessible :subject, :body, :to, :recipients, :author, :user
...
In my controller I want to do something like
new_draft_recipients = params[:draft][:draft_recipients].split(",")
@draft.update_attributes(:draft_recipients => new_draft_recipients)
which obviously doesn't work. When I try update each record comparing old (from the database )and new recipients (passed through the form), the algorithm gets ridiculously complicated. I feel what is missing is proper associations, but I don't manage to understand which. I know this is really simple. Thanks for your help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to set up a button to invert two textFields I'm an absolute beginner, and I need to have a button to invert two text fields:
text1 <—> text2
- (IBAction)swapText {
name.text = surname.text;
surname.text = name.text;
}
I know that I have to retain the values and then release them, but I'm not sure how to write it.
A: This is quite simple: the only text / NSString you have to retain is the one that will stop being hold by the UITextField itself, namely the name.text that you will replace by surname.text.
- (IBAction)swapText {
NSString* temp = [name.text retain];
name.text = surname.text;
surname.text = temp;
[temp release];
}
A: The only objects you need to take care of would be alloc/deallocating the UITextFields. Assuming your UITextfields are ivars (declared in your header file) you can use the following code:
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect b = [[self view] bounds];
_txt1 = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMidX(b)-100, 50, 200, 29)];
[_txt1 setBorderStyle:UITextBorderStyleRoundedRect];
[[self view] addSubview:_txt1];
_txt2 = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMidX(b)-100, 100, 200, 29)];
[_txt2 setBorderStyle:UITextBorderStyleRoundedRect];
[[self view] addSubview:_txt2];
UIButton* btnSwap = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnSwap setFrame:CGRectMake(CGRectGetMidX(b)-75, 150, 150, 44)];
[btnSwap setTitle:@"Swap Text" forState:UIControlStateNormal];
[btnSwap addTarget:self action:@selector(tappedSwapButton) forControlEvents:UIControlEventTouchUpInside];
[[self view] addSubview:btnSwap];
}
- (void)tappedSwapButton
{
NSString* text1 = [_txt1 text];
NSString* text2 = [_txt2 text];
[_txt2 setText:text1];
[_txt1 setText:text2];
}
- (void)dealloc
{
[_txt1 release];
[_txt2 release];
[super dealloc];
}
A: Based on your code given, your text in the first textfield will be lost. The easiest way to fix that is to declare a temp NSString object that will hold the string that is contained in name.text:
- (IBAction)swapText{
// create a temp string to hold the contents of name.text
NSString *tempString = [NSString stringWithString: name.text];
name.text = surname.text;
surname.text = tempString;
}
Since you are using dot notation, it is assumed that "name" and "surname" are properties for the IBOutlet references to both textfields that you want to swap. If this is the case, as long as you have "retain" for both of these properties, that will take care of the memory management (as long as you release these in the dealloc method in the .m file).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Will setuptools work with python 3.2.x Will the setuptools for windows python 2.7 http://pypi.python.org/pypi/setuptools#files be compatible with a python 3.2.x runtime. The installer fails to detect the python settings during an install. Should I wait for a new release?
A: NOTE: Answer obsolete, Setuptools now works for Python 3. Distribute is deprecated.
Setuptools itself doesn't work on Python 3. But you can use Distribute, a fork and a drop in replacement for setuptools:
http://packages.python.org/distribute/
http://pypi.python.org/pypi/distribute
From the bottom of the page to install distribute:
curl -O http://python-distribute.org/distribute_setup.py
python distribute_setup.py
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Why doesn't this user script work in Opera? This is my userscript:
// ==UserScript==
// @name wykopSpamBlock
// @namespace wykopSpamBlock
// @description Skrypt ukrywający sponsorowane i polecane wykopy w serwisie wykop.pl 3.0
// @include http://www.*wykop.pl/
// @include http://www.*wykop.pl/strona/*
// @include http://www.*wykop.pl/wykopalisko*
// @include http://www.*wykop.pl/hity*
// ==/UserScript==
(function() {
function block(element) {
element.style.display = 'none';
console.log('It works');
}
//////////////////////////////////////////////////////////////////////
var Filter = new RegExp('^http://www.wykop.pl/link/partnerredirect/');
var Entries = document.getElementById('body-con').getElementsByClassName('entry');
var Links;
//////////////////////////////////////////////////////////////////////
for (i = 0; i < Entries.length; i++) {
Links = Entries.item(i).getElementsByTagName('div').item(0).getElementsByClassName('content').item(0).getElementsByTagName('header').item(0).getElementsByTagName('p').item(0).getElementsByTagName('a');
if (Filter.test(Links.item(1).href) || Filter.test(Links.item(2).href)) {
block(Entries.item(i));
}
}
})();
It works fine in Chrome and Firefox (GreaseMonkey), but it doesn't in Opera. I get this error:
User Javascript thread
Uncaught exception: TypeError: Cannot convert 'Entries.item(i).getElementsByTagName('div').item(0).getElementsByClassName('content').item(0)' to object
Error thrown at line 30, column 4 in <anonymous function>():
Links = Entries.item(i).getElementsByTagName('div').item(0).getElementsByClassName('content').item(0).getElementsByTagName('header').item(0).getElementsByTagName('p').item(0).getElementsByTagName('a');
called from line 11, column 0 in program code:
(function() {
And the question is, what's wrong?
//edit
For people who can't read that:
// ==UserScript==
// @name wykopSpamBlock
// @namespace wykopSpamBlock
// @description Skrypt ukrywający sponsorowane i polecane wykopy w serwisie wykop.pl 3.0
// @include http://www.*wykop.pl/
// @include http://www.*wykop.pl/strona/*
// @include http://www.*wykop.pl/wykopalisko*
// @include http://www.*wykop.pl/hity*
// ==/UserScript==
(function() {
function block(element) {
element.style.display = 'none';
console.log('It works');
}
//////////////////////////////////////////////////////////////////////
var Filter = new RegExp('^http://www.wykop.pl/link/partnerredirect/');
var Entries = document.getElementById('body-con').getElementsByClassName('entry');
//////////////////////////////////////////////////////////////////////
for (i = 0; i < Entries.length; i++) {
var EntriesItem = Entries.item(i);
var Div = EntriesItem.getElementsByTagName('div');
var DivItem = Div.item(0);
var Content = DivItem.getElementsByClassName('content');
var ContentItem = Content.item(0);
var Header = ContentItem.getElementsByTagName('header');
var HeaderItem = Header.item(0);
var Paragraph = HeaderItem.getElementsByTagName('p');
var ParagraphItem = Paragraph.item(0);
var Links = ParagraphItem.getElementsByTagName('a');
if (Filter.test(Links.item(1).href) || Filter.test(Links.item(2).href)) {
block(Entries.item(i));
}
}
})();
and error:
[26.09.2011 20:35:07] JavaScript - http://www.wykop.pl/
User Javascript thread
Uncaught exception: TypeError: Cannot convert 'ContentItem' to object
Error thrown at line 35, column 4 in <anonymous function>():
var Header = ContentItem.getElementsByTagName('header');
called from line 11, column 0 in program code:
(function() {
//edit 2
Here is full html of entry. Content starts in 21 line.
<article class="entry brbotte8 pding15_0 {id:891309}">
<div class="clr rel">
<div class="fleft diggbox">
<a href="http://www.wykop.pl/link/dig/%7E2/891309/55a55552de3fac6ececb6a8933938e71-1317062985/log_ref_0,index,log_ref_m_0,index,log_ref_n_0," class="block tcenter tdnone diggit ">
<span class="icon inlblk diggcount cff5917 large fbold vtop animated ">
22
</span>
<span class="block action small br3 bre3">
wykop
</span>
</a>
</div>
<a href="http://www.wykop.pl/ramka/891309/policjant-strzelil-nastolatkowi-w-twarz-taserem-wideo/" class="image rel fright">
<div class="lazy">
<!--<img src="http://c0692282.3.cdn.imgwykop.pl/hi_34VehOZEwdnDXdwlMEBOWbkmNGIzrPM0.jpg" alt="Policjant strzelił nastolatkowi w twarz taserem [wideo" class="fright border marginleft15" width="104" height="74" />-->
</div>
</a>
<div class="content">
<header>
<h2 class="xx-large lheight20">
<a href="http://www.wykop.pl/ramka/891309/policjant-strzelil-nastolatkowi-w-twarz-taserem-wideo/" class="link">
<span class="fbold">Policjant strzelił nastolatkowi w twarz taserem [wideo</span>
</a>
</h2>
<p class="small cc6">
<a href="http://www.wykop.pl/reklama/" class="link gray" title="Przejdź do Reklama Wykop.pl">
<span>
Wykop Poleca
</span>
</a>
dodany
<time title="2011-09-26 19:37:24" datetime="2011-09-26T19:37:24+02:00" pubdate>
1 godz. temu
</time>
przez
<a href="http://www.wykop.pl/ludzie/Saper86/" class="link gray color color-1">
<span>
Saper86
</span>
</a>
z
<a href="http://www.wykop.pl/link/partnerredirect/891309/policjant-strzelil-nastolatkowi-w-twarz-taserem-wideo/" rel="nofollow" class="link gray" title="Przejdź do Policjant strzelił nastolatkowi w twarz taserem [wideo">
<span>
gadzetomania.pl
</span>
</a>
do
<a href="http://ciekawostki.wykop.pl/" title="Ciekawostki" class="link gray" rel="nofollow">
<span>
Ciekawostki
</span>
</a>
<a href="http://www.wykop.pl/link/891309/policjant-strzelil-nastolatkowi-w-twarz-taserem-wideo/" class="marginleft10 caf small tdnone">
<span class="icon inlblk comments mini vtop margintop5 "> </span>
<span class="hvline link gray">13 komentarzy</span>
</a>
</p>
</header>
<p class="lheight18">
<a href="http://www.wykop.pl/link/891309/policjant-strzelil-nastolatkowi-w-twarz-taserem-wideo/" class="block ce1">
<span class="c22">Oceńcie sami czy postąpił właściwie</span>
</a>
</p>
</div>
</div>
</article>
A: I'd suggest breaking each piece of this long line into individual steps and find out which of the 8 steps is failing and that should give you a clue:
Links = Entries.item(i).getElementsByTagName('div').item(0).getElementsByClassName('content').item(0).getElementsByTagName('header').item(0).getElementsByTagName('p').item(0).getElementsByTagName('a');
I really have no idea what's causing the problem. It works for both of us in jsFiddle, just not in the greasemonkey environment. Do you have any other greasemonkey scripts that are modifying the page and changing the DOM on you?
Other than that, the only other thing I can think of is to switch to using document.querySelectorAll() when it's present. Since that is supported in recent versions of Opera, that may avoid whatever issues your code is having. You can see a sample implementation in this jsFiddle: http://jsfiddle.net/jfriend00/5hJLn/. This selector doesn't generate exactly the same result as your code with any HTML, but I think it works for the HTML you have. You can consider tweaking the selector if you want. This selector is a little less brittle because it doesn't rely on the exact position of various tags as much as your code.
The general idea (implemented in that jsFiddle) is like this:
if (document.querySelectorAll) {
var Links = document.querySelectorAll("#body-con .content header p a");
// turn the links we found green just to show that the code executed properly
for (var j = 0; j < Links.length; j++) {
Links[j].className = "target2";
}
} else {
var Entries = document.getElementById('body-con').getElementsByClassName('entry');
for (var i = 0; i < Entries.length; i++) {
var EntriesItem = Entries.item(i);
var Div = EntriesItem.getElementsByTagName('div');
var DivItem = Div.item(0);
var Content = DivItem.getElementsByClassName('content');
var ContentItem = Content.item(0);
var Header = ContentItem.getElementsByTagName('header');
var HeaderItem = Header.item(0);
var Paragraph = HeaderItem.getElementsByTagName('p');
var ParagraphItem = Paragraph.item(0);
var Links = ParagraphItem.getElementsByTagName('a');
// turn the links we found red just to show that the code executed properly
for (var j = 0; j < Links.length; j++) {
Links[j].className = "target";
}
}
}
A: I used getElementsByTagName('div').item(1) instead of getElementsByClassName('content').item(0). It works. I think there must be a bug in Opera's implemetation of getElementsByClassName.
//edit
Ehh... now I get the same error for getElementsByTagName('header').item(0)..
A: Change the way you implement it. Try another approaching to anonymous function and use Opera dragonfly to test it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How do I run a command in a list of directories using bash? I need to run some commands in OS X User directories, apart from "Shared" and our local admin account.
So far, I have:
#!/bin/bash
userFolders=$(find /Users/ -type d -depth 1 | sed -e 's/\/\//\//g' | egrep -v "support|Shared")
for PERSON in "$userFolders"; do
mkdir $PERSON/Desktop/flagFolderForLoop
done
Running the above as root, I get
mkdir: /Users/mactest1: File exists
Where might I be going wrong?
A: You should remove the quotes around "$userFolders" so that your loop iterates over each person correctly.
The following example illustrates the difference between quoting and not quoting:
With quotes:
for i in "a b c"
do
echo "Param: $i"
done
prints only one parameter:
Param: a b c
Without quotes:
for i in a b c
do
echo "Param: $i"
done
prints each parameter:
Param: a
Param: b
Param: c
Also, you can tell find to exclude certain directories, like this:
for PERSON in $(find /Users/ -type d -depth 1 ! -name support ! -name Shared)
do
mkdir "$PERSON"/Desktop/flagFolderForLoop
done
A: Instead of find you can use dscl to list (regular, standard) /Users on Mac OS X.
dscl . -list /Users NFSHomeDirectory
# list name of users
dscl . -list /Users NFSHomeDirectory |
awk '/^[^[:space:]]+[[:space:]]+\/Users\//{print $1}'
# list home directories of users
dscl . -list /Users NFSHomeDirectory |
awk '/^[^[:space:]]+[[:space:]]+\/Users\//{$1=""; sub(/^ */,""); print $0}'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Are there any essential reasons to use isset() over @ in php So I'm working on cleanup of a horrible codebase, and I'm slowly moving to full error reporting.
It's an arduous process, with hundreds of notices along the lines of:
Notice: Undefined index: incoming in /path/to/code/somescript.php on line 18
due to uses of variables assuming undefined variables will just process as false, like:
if($_SESSION['incoming']){
// do something
}
The goal is to be able to know when a incorrectly undefined variable introduced, the ability to use strict error/notice checking, as the first stage in a refactoring process that -will- eventually include rewriting of the spots of code that rely on standard input arrays in this way. There are two ways that I know of to replace a variable that may or may not be defined
in a way that suppresses notices if it isn't yet defined.
It is rather clean to just replace instances of a variable like $_REQUEST['incoming'] that are only looking for truthy values with
@$_REQUEST['incoming'].
It is quite dirty to replace instances of a variable like $_REQUEST['incoming'] with the "standard" test, which is
(isset($_REQUEST['incoming'])? $_REQUEST['incoming'] : null)
And you're adding a ternary/inline if, which is problematic because you can actually nest parens differently in complex code and totaly change the behavior.
So.... ...is there any unacceptable aspect to use of the @ error suppression symbol compared to using (isset($something)? $something : null) ?
Edit: To be as clear as possible, I'm not comparing "rewriting the code to be good" to "@", that's a stage later in this process due to the added complexity of real refactoring. I'm only comparing the two ways (there may be others) that I know of to replace $undefined_variable with a non-notice-throwing version, for now.
A: Another option, which seems to work well with lame code that uses "superglobals" all over the place, is to wrap the globals in dedicated array objects, with more or less sensible [] behaviour:
class _myArray implements ArrayAccess, Countable, IteratorAggregate
{
function __construct($a) {
$this->a = $a;
}
// do your SPL homework here: offsetExists, offsetSet etc
function offsetGet($k) {
return isset($this->a[$k]) ? $this->a[$k] : null;
// and maybe log it or whatever
}
}
and then
$_REQUEST = new _myArray($_REQUEST);
This way you get back control over "$REQUEST" and friends, and can watch how the rest of code uses them.
A: You need to decide on your own if you rate the @ usage acceptable or not. This is hard to rate from a third party, as one needs to know the code for that.
However, it already looks like that you don't want any error suppression to have the code more accessible for you as the programmer who needs to work with it.
You can create a specification of it in the re-factoring of the code-base you're referring to and then apply it to the code-base.
It's your decision, use the language as a tool.
You can disable the error suppression operator as well by using an own callback function for errors and warnings or by using the scream extension or via xdebug's xdebug.scream setting.
A: You answered you question yourself. It suppress error, does not debug it.
A: In my opinion you should be using the isset() method to check your variables properly.
Suppressing the error does not make it go away, it just stops it from being displayed because it essentially says "set error_reporting(0) for this line", and if I remember correctly it would be slower than checking isset() too.
And if you don't like the ternary operator then you should use the full if else statement.
It might make your code longer but it is more readable.
A: I would never suppress errors on a development server, but I would naturally suppress errors on a live server. If you're developing on a live server, well, you shouldn't. That means to me that the @ symbol is always unacceptable. There is no reason to suppress an error in development. You should see all errors including notices.
@ also slows things down a bit, but I'm not sure if isset() is faster or slower.
If it is a pain to you to write isset() so many times, I'd just write a function like
function request($arg, $default = null) {
return isset($_REQUEST[$arg]) ? trim($_REQUEST[$arg]) : $default;
}
And just use request('var') instead.
A: I've actually discovered another caveat of the @ beyond the ones mentioned here that I'll have to consider, which is that when dealing with functions, or object method calls, the @ could prevent an error even through the error kills the script, as per here:
http://us3.php.net/manual/en/language.operators.errorcontrol.php
Which is a pretty powerful argument of a thing to avoid in the rare situation where an attempt to suppress a variable notice suppressed a function undefined error instead (and perhaps that potential to spill over into more serious errors is another unvoiced reason that people dislike @?).
A: Most so-called "PHP programmers" do not understand the whole idea of assigning variables at all.
Just because of lack of any programming education or background.
Well, it isn't going a big deal with usual php script, coded with considerable efforts and consists of some HTML/Mysql spaghetti and very few variables.
Another matter is somewhat bigger code, when writing going to be relatively easy but debugging turns up a nightmare. And you are learn to value EVERY bloody error message as you come to understanding that error messages are your FRIENDS, not some irritating and disturbing things, which better to be gagged off.
So, upon this understanding you're learn to leave no intentional errors in your code.
And define all your variables as well.
And thus make error messages your friends, telling you that something gone wrong, lelping to hunt down some hard-spotting error which caused by uninitialized variable.
Another funny consequence of lack of education is that 9 out of 10 "PHP programmers" cannot distinguish error suppression from turning displaying errors off and use former in place of latter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there a Feedburner plugin for Wordpress that will change the RSS tags on the pages I'm looking for a Feedburner plugin for Wordpress that redirects feeds to Feedburner, but also changes the RSS links that are embedded on the Wordpress pages to point to Feedburner. The plugins I've tried will redirect the RSS feed, but none of them change the embedded RSS tags. So in Safari, for instance, when you click the RSS button, it pulls from the Wordpress feed (instead of Feedburner).
A: As I recall Wordpress does not offer an api that allows you to modify the RSS links. However, you can remove them completely and then add back in your own. This WP support post is where I got the following info.
Add the following to your functions.php in your theme directory
//remove the feeds for pages
remove_action( 'wp_head', 'feed_links_extra', 3 ); // extra feeds such as category
remove_action( 'wp_head', 'feed_links', 2 ); // general, post and comment feeds
//explicitly add feedburner link back into head
add_action('wp_head', 'addFeedburnerLink');
function addFeedburnerLink() {
echo '<link rel="alternate" type="application/rss+xml" title="RSS 2.0 Feed" href="http://feedburner.com/myfeedburnerurl" />';
}
Hope that helps! You should also checkout http://wordpress.stackexchange.com . They tend to do a much better job with Wordpress codex/plugin related questions over there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Routes in Rails 3 I'm new to Rails 3 and I need some help regarding the routes.
This is my old route
map.connect '/admin/login/:language/:brand',
:controller => 'adm/auth', :action => 'login',
:defaults => {:brand => 'brand', :language => 'en'}
as I change it to
match '/admin/login/:language/:brand', :to => 'adm/auth#login' ,
:defaults => {:brand => 'brand', :language => 'en'}
and also
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
to
match "/:controller(/:action(/:id))"
match "/:controller(/:action(/:id))(.:format)"
but still I'm getting No route matches [GET] "/cmm" ,error.
I'm using Jruby 1.6.4 and rails 3.1.1
Somebody please help me!
A: Could you post the complete url you are trying to access (maybe redact the domain, if that's a secret).
Basically I'm interested in if /cmm is in the start of the url, therein lies your problem. As I read you routes, you have nothing matching example.com/cmm/...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WPF webBrowser: how to display to an image after rendering has finished I have a webBrowser on my UI. I ask if it is possible that it is not displayed directly but instead through an image, and I want that the image is updated only when the LoadCompleted event is received.
How to do?
A: I'm not sure if I understood your question, but if I did, you basically want to show the loaded web page only when its rendering has finished.
If so, this code should do the trick (I'm assuming you hooked the "LoadCompleted" event up to the "webBrowser1_LoadCompleted" method). This code uses a Button ("button1") to trigger the navigation, but you can use it in any other place.
//here is the code that triggers the navigation: when the button is clicked, I hide the
//webBrowser and then navigate to the page (here I used Google as an example)
private void button1_Click(object sender, RoutedEventArgs e)
{
webBrowser1.Visibility = Visibility.Hidden;
webBrowser1.Navigate(new Uri("http://www.google.it"));
}
private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
{
webBrowser1.Visibility = Visibility.Visible;
}
Keep in mind, though, that not showing anything to the user for a long period of time (as with a heavy page) is not always a good idea, depending on the kind of application you're writing. This is up to you, though.
A: (I decided to leave the previous answer if someone needs it)
If you want to leave the previous page visible until the new one appears, then I think you need a Windows DLL. This is how I would do it.
At the top of the code file, insert these two import statements:
using System.Runtime.InteropServices;
using System.Windows.Interop;
Then you need to declare your DLL function like this (in the Window class):
[DllImport("user32")]
private static extern int LockWindowUpdate (IntPtr hWnd);
Then, let's modify the code in the previous answer a little bit:
private void button1_Click(object sender, RoutedEventArgs e)
{
IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
LockWindowUpdate(handle);
webBrowser1.Navigate(new Uri("http://www.google.it"));
}
private void webBrowser1_DocumentCompleted(object sender, NavigationEventArgs e)
{
LockWindowUpdate(new IntPtr(0));
}
This should keep the last loaded page on screen until the new page has completed its rendering; as you may imagine, the DLL function simply locks the update of the Window by passing its handle. The handle 0 unlocks it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to simulate SQL Server under an unworkable load? Our company are currently beta testing an application which uses our SQL Server 2008 box as a backend..
One day our server was under some serious strain to the point where the only way to recover it was to reboot.
During this time of heavy load the we found an interesting bug in the application which manifests itself when the backend database times out.
Now to be able to send the company some decent stack trace data and screenshots I need to replicate the error..
How can I put the SQL server under an unworkable amount of strain / make all queries timeout?
A: I wanted to simulate Sql server deadlock and timeout. Deadlock is hard to replicate, but sql client timeout is relatively easy to reproduce.
BEGIN TRANSACTION
SELECT TOP 1 * FROM MyTable WITH (TABLOCKX, HOLDLOCK)
ROLLBACK TRANSACTION
This will lock the table and any select query will timeout. The timeout value depends on your client's library settings.
If you want to lock the table for a certain time, you can use waitfor delay (https://stackoverflow.com/a/798234/437961)
BEGIN TRANSACTION
SELECT TOP 1 * FROM MyTable WITH (TABLOCKX, HOLDLOCK) WAITFOR DELAY '00:05'
ROLLBACK TRANSACTION
A: There are a couple of tools to simulate heavy usage, these were for sql 2005 but they probably work in 2008 too.
Actually, this has been asked before on S/O so I'll just paste that question:
How to simulate heavy database usage with SQL server 2005
A: If all you want is for the app to timeout, you can just start transactions on your tables to block other processes. For instance, this will lock MyTable until you COMMIT:
BEGIN TRANSACTION
SELECT top 1 * FROM MyTable
--COMMIT
Unless you have finagled concurrency settings this should do the trick without any other scripting gymnastics.
A: If you want to simiulate a long running query, you can use this WAITFOR DELAY '00:00:35'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Access an object in an NSArray using a key path I've read through the KVC docs on Apple and it talks in depth about making your indexed collections accessible through key value coding, but I can't find any examples of a key path being used to access an arbitrary element within the array.
If my Blob class has an NSArray *widgets, I'd like to be able to get the widget at index 4 by doing something like:
[myBlob valueForKeyPath:@"widgets[4]"]
Is there anything like this?
A: myBlob answers to 'valueForKey:' and widgets being an NSArray answers to 'objectAtIndex:'.
So '[[myBlob valueForKey:@"widgets"] objectAtIndex:4]' should do the trick.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Finding X the lowest cost trees in graph I have Graph with N nodes and edges with cost. (graph may be Complete but also can contain zero edges).
I want to find K trees in the graph (K < N) to ensure every node is visited and cost is the lowest possible.
Any recommendations what the best approach could be?
I tried to modify the problem to finding just single minimal spanning tree, but didn't succeeded.
Thank you for any hint!
EDIT
little detail, which can be significant. To cost is not related to crossing the edge. The cost is the price to BUILD such edge. Once edge is built, you can traverse it forward and backwards with no cost. The problem is not to "ride along all nodes", the problem is about "creating a net among all nodes". I am sorry for previous explanation
The story
Here is the story i have heard and trying to solve.
There is a city, without connection to electricity. Electrical company is able to connect just K houses with electricity. The other houses can be connected by dropping cables from already connected houses. But dropping this cable cost something. The goal is to choose which K houses will be connected directly to power plant and which houses will be connected with separate cables to ensure minimal cable cost and all houses coverage :)
A: As others have mentioned, this is NP hard. However, if you're willing to accept a good solution, you could use simulated annealing. For example, the traveling salesman problem is NP hard, yet near-optimal solutions can be found using simulated annealing, e.g. http://www.codeproject.com/Articles/26758/Simulated-Annealing-Solving-the-Travelling-Salesma
A: Assume you can find a minimum spanning tree in O(V^2) using prim's algorithm.
For each vertex, find the minimum spanning tree with that vertex as the root.
This will be O(V^3) as you run the algorithm V times.
Sort these by total mass (sum of weights of their vertices) of the graph. This is O(V^2 lg V) which is consumed by the O(V^3) so essentially free in terms of order complexity.
Take the X least massive graphs - the roots of these are your "anchors" that are connected directly to the grid, as they are mostly likely to have the shortest paths. To determine which route it takes, you simply follow the path to root in each node in each tree and wire up whatever is the shortest. (This may be further optimized by sorting all paths to root and using only the shortest ones first. This will allow for optimizations on the next iterations. Finding path to root is O(V). Finding it for all V X times is O(V^2 * X). Because you would be doing this for every V, you're looking at O(V^3 * X). This is more than your biggest complexity, but I think the average case on these will be small, even if their worst case is large).
I cannot prove that this is the optimal solution. In fact, I am certain it is not. But when you consider an electrical grid of 100,000 homes, you can not consider (with any practical application) an NP hard solution. This gives you a very good solution in O(V^3 * X), which I imagine is going to give you a solution very close to optimal.
A: You are describing something like a cardinality constrained path cover. It's in the Traveling Salesman/ Vehicle routing family of problems and is NP-Hard. To create an algorithm you should ask
*
*Are you only going to run it on small graphs.
*Are you only going to run it on special cases of graphs which do have exact algorithms.
*Can you live with a heuristic that solves the problem approximately.
A: Looking at your story, I think that what you call a path can be a tree, which means that we don't have to worry about Hamiltonian circuits.
Looking at the proof of correctness of Prim's algorithm at http://en.wikipedia.org/wiki/Prim%27s_algorithm, consider taking a minimum spanning tree and removing the most expensive X-1 links. I think the proof there shows that the result has the same cost as the best possible answer to your problem: the only difference is that when you compare edges, you may find that the new edge join two separated components, but in this case you can maintain the number of separated components by removing an edge with cost at most that of the new edge.
So I think an answer for your problem is to take a minimum spanning tree and remove the X-1 most expensive links. This is certainly the case for X=1!
A: Here is attempt at solving this...
For X=1 I can calculate minimal spanning tree (MST) with Prim's algorithm from each node (this node is the only one connected to the grid) and select the one with the lowest overall cost
For X=2 I create extra node (Power plant node) beside my graph. I connect it with random node (eg. N0) by edge with cost of 0. I am now sure I have one power plant plug right (the random node will definitely be in one of the tree, so whole tree will be connected). Now the iterative part. I take other node (eg. N1) and again connected with PP with 0 cost edge. Now I calculate MST. Then repeat this process with replacing N1 with N2, N3 ...
So I will test every pair [N0, NX]. The lowest cost MST wins.
For X>2 is it really the same as for X=2, but I have to test connect to PP every (x-1)-tuple and calculate MST
with x^2 for MST I have complexity about (N over X-1) * x^2... Pretty complex, but I think it will give me THE OPTIMAL solution
what do you think?
edit by random node I mean random but FIXED node
attempt to visualize for x=2 (each description belongs to image above it)
Let this be our city, nodes A - F are houses, edges are candidates to future cables (each has some cost to build)
Just for image, this could be the solution
Let the green one be the power plant, this is how can look connection to one tree
But this different connection is really the same (connection to power plant(pp) cost the same, cables remains untouched). That is why we can set one of the nodes as fixed point of contact to the pp. We can be sure, that the node will be in one of the trees, and it does not matter where in the tree is.
So let this be our fixed situation with G as PP. Edge (B,G) with zero cost is added.
Now I am trying to connect second connection with PP (A,G, cost 0)
Now I calculate MST from the PP. Because red edges are the cheapest (the can actually have even negative cost), is it sure, that both of them will be in MST.
So when running MST I get something like this. Imagine detaching PP and two MINIMAL COST trees left. This is the best solution for A and B are the connections to PP. I store the cost and move on.
Now I do the same for B and C connections
I could get something like this, so compare cost to previous one and choose the better one.
This way I have to try all the connection pairs (B,A) (B,C) (B,D) (B,E) (B,F) and the cheapest one is the winner.
For X=3 I would just test other tuples with one fixed again. (A,B,C) (A,B,D) ... (A,C,D) ... (A,E,F)
A: I just came up with the easy solution as follows:
N - node count
C - direct connections to the grid
E - available edges
1, Sort all edges by cost
2, Repeat (N-C) times:
*
*Take the cheapest edge available
*Check if adding this edge will not caused circles in already added edge
*If not, add this edge
3, That is all... You will end up with C disjoint sets of edges, connect every set to the grid
A: Sounds like the famous Traveling Salesman problem. The problem known to be NP-hard. Take a look at the Wikipedia as your starting point: http://en.wikipedia.org/wiki/Travelling_salesman_problem
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Show tooltips with delay Is it possible to create a style that applies to all my controls in the application for the tooltip service that sets a delay for showing tooltips? And how?
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android HTTP Library to handle sessions, cookies, post/get, keep-alive and async What HTTP library should I use as a core of my application ?
Need to handle these:
*
*Cookies
*POST / GET
*Keep-Alive capability
*HTTP Sessions
*Asynchronous requests
*Stream compression (Gzip)
in API from Level 7 (So AndroidHttpClient can't be used)
A: It's quite an old question, but I should provide up to date correct answer.
The final and best choice was probably Android Async Http Client from James Smith (aka LoopJ)
Github: https://github.com/loopj/android-async-http
Website: http://loopj.com/android-async-http/
+ Feature HttpClient in version 4.2.3
+ Compatibility since API 1
It's not very hard to use library httpclientandroidlib and build more up to date version of loopj async http client
For those who just want to use library, I provide my custom updated version (with latest 4.2.3 HttpClient)
https://github.com/smarek/Android-Async-Http-Client-Updated
A: Android includes the apache HTTP library. See
*
*http://developer.android.com/reference/org/apache/http/package-summary.html
for more. That should provide you with everything you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: django - how can I clean variable data passed by an url? When I'm using a form I clean field data using Django forms but how do you clean variable data that's passed by an URL?
For example I have an URL like this: http://mywebsite.com/tags/my-tag/ where my-tag is the variable that I'm passing to a function on my views.py.
I tried to use a Django form to clean the data but I'm getting en error saying "'TagForm' object has no attribute 'cleaned_data'".
I know my-form variable is reaching the tags function in the views.py since I'm able to show its content on a template so the problem is probably with the way I'm using the form.
views.py
def tags(request, my-tag):
tagform = TagForm(request.GET)
cleaned_dt = tagform.cleaned_data
form_tag = cleaned_dt['tag']
forms.py
class TagForm(forms.Form):
tag = forms.CharField()
Any ideas?
A: You are creating a TagForm with a request object, but you're not giving the TagForm the value of my-tag anywhere that I can see.
The /my-tag/ section of the URL isn't a request parameter. It's part of the url, and presumably passed to the view function as my-tag (you might want to rename it my_tag to be more Pythonic).
Edit
You can simple create a dict object to initialize to Form object instead of request.GET. An example is here.
data = {'tag': my_tag,
'anotherIfNecessary': 'Hi there'}
tagform = TagForm(data)
Basically, the dictionary used to populate a form object must contain a mapping of form field names to the value you wish to set it at.
In this case, you have a form field name of "tag" and want to set it to my-tag (are you sure you don't get a syntax error with the dash in the variable name? I do...). I've corrected my example.
A: The cleaned_data dictionary attribute appears after you call is_valid method on your form.
def tags(request, my-tag):
tagform = TagForm(request.GET)
if tagform.is_valid():
cleaned_dt = tagform.cleaned_data
form_tag = cleaned_dt['tag']
return render(request, "may_template.html", {"form":tagform})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Strange shader corruption I'm working with shaders just now and I'm observing some very strange behavior. I've loaded this vertex shader:
#version 150
uniform float r;
uniform float g;
uniform float b;
varying float retVal;
attribute float dummyAttrib;
void main(){
retVal = dummyAttrib+r+g+b; //deleting dummyAttrib = corruption
gl_Position = gl_ModelViewProjectionMatrix*vec4(100,100,0,1);
}
First of all I render with glDrawArrays(GL_POINTS,0,1000) with this shader without nothing special, just using shader program. If you run this shader and set point size to something visible, you should see white square in middle of screen (I'm using glOrtho2d(0,200,0,200)). DummyAttrib is just some attrib - my shaders won't run if there's none. Also I need to actually use that attribute so normally I do something like float c = dummyAttrib.That is also first question I would like to ask why it is that way.
However this would be fine but when you change the line with comment (retval=...) to retVal = r+g+b; and add that mentioned line to use attrib (float c = dummyAttrib), strange things happen. First of all you won't see that square anymore, so I had to set up transform feedback to watch what's happening.
I've set the dummyAttrib to 5 in each element of field and r=g=b=1. With current code the result of transform feedback is 8 - exactly what you'd expect. However changing it like above gives strange values like 250.128 and every time I modify the code somehow (just reorder calls), this value changes. As soon as I return that dummyAttrib to calculation of retVal everything is magically fixed.
This is why I think there's some sort of shader corruption. I'm using the same loading interface for shaders as I did in projects before and these were flawless, however they were using attributes in normal way, not just dummy for actually running shader.
These 2 problems can have connecion. To sum up - shader won't run without any attribute and shader is corrupted if that attribute isn't used for setting varying that is used either in fragment shader or for transform feedback.
PS: It came to my mind when I was writing this that it looks like every variable that isn't used for passing into next stage is opt out. This could opt out attribute as well and then this shader would be without attribute and wouldn't work properly. Could this be a driver fault? I have Radeon 3870HD with current catalyst version 2010.1105.19.41785.
A: In case of your artificial usage (float c = dummyAttrib) the attribute will be optimized out. The question is what your mesh preparing logic does in this case. If it queries used attributes from GL it will get nothing. And with no vertex attributes passed the primitive will not be drawn (behavior of my Radeon 2400HD on any Catalyst).
So, basically, you should pass an artificial non-used attribute (something like 1 byte per vertex on some un-initialized buffer) if GL reports attributes are not at all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TEXT values in sqlite databases Do sqlite databases use anything like a flyweight pattern for TEXT values. If I'm repeatedly using only a few different, short TEXT values in a column, would it be better to replace them with integers?
A: SQLite stores each copy of the text column individually:
$ sqlite3 pancakes.sqlt
sqlite> create table pancakes (s text);
sqlite> insert into pancakes (s) values ('where is pancakes house?');
sqlite> insert into pancakes (s) values ('where is pancakes house?');
sqlite> insert into pancakes (s) values ('where is pancakes house?');
sqlite> insert into pancakes (s) values ('where is pancakes house?');
sqlite> insert into pancakes (s) values ('where is pancakes house?');
sqlite> insert into pancakes (s) values ('where is pancakes house?');
sqlite> insert into pancakes (s) values ('where is pancakes house?');
sqlite> insert into pancakes (s) values ('where is pancakes house?');
$ strings pancakes.sqlt
SQLite format 3
Itablepancakespancakes
CREATE TABLE pancakes (s text)
=where is pancakes house?
=where is pancakes house?
=where is pancakes house?
=where is pancakes house?
=where is pancakes house?
=where is pancakes house?
=where is pancakes house?
=where is pancakes house?
So if you want to avoid duplicating your strings you should use integers, set up a separate table to map your integers to strings, and then add a foreign key to this new table so that you can ensure referential integrity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to remove tabs from blank lines using sed? I'd like to use sed to remove tabs from otherwise blank lines. For example a line containing only \t\n should change to \n. What's the syntax for this?
A: sed does not know about escape sequences like \t. So you will have to literally type a tab on your console:
sed 's/^ *$//g' <filename>
If you are on bash, then you can't type tab on the console. You will have to do ^V and then press tab. (Ctrl-V and then tab) to print a literal tab.
A: The other posted solution will work when there is 1 (and only 1) tab in the line. Note that Raze2dust points out that sed requires you to type a literal tab. An alternative is:
sed '/[^ ]/!s/ //g' file-name.txt
Which substitues away tabs from lines that only have tabs. The inverted class matches lines that contain anything bug a tab - the following '!' causes it to not match those lines - meaning only lines that have only tabs. The substitution then only runs on those lines, removing all tabs.
A: To replace arbitrary whitespace lines with an empty line, use
sed -r 's/^\s+$//'
The -r flag says to use extended regular expressions, and the ^\s+$ pattern matches all lines with some whitespace but no other characters.
A: What worked for me was:
sed -r '/^\s+$/d' my_file.txt > output.txt
A: grep -o ".*" file > a; mv a file;
A: I've noticed \t is not recognized by UNIX. Being said, use the actual key. In the code below, TAB represents pressing the tab key.
$ sed 's/TAB//g' oldfile > newfile
Friendly tip: to ensure you have tabs in the file you are trying to remove tabs from use the following code to see if \t appears
$ od -c filename
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: How to add another app (option 1, 2, 3 etc) from current app (main app)? Is it possible to have multiple options of the app (separate FB app instances) and be able to add them from the main app? If yes where I can find some info how to do that?
I'm trying to install an app to the page multiple times, but what I know it is not possible so what I'm looking for is to create a main app with options as separate FB apps aka "Install Another Tab". I saw few apps which utilize that way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Execute html at a certain time I am wondering how you execute html on a certain time. I have a small marquee html code that I want to be executed at the time I want, instead of just immediately once the page loads.
A: Html does not execute, but it renders.
For execution, you need a script or program. For client side, you should use javascipt. Many people use a library that generally improves their code, and makes programming easier. I would recommend jQuery, but there are others.
To do what you are asking in jQuery is trivial, you would use setTimeout to calculate the time you want it to execute, and then insert or display the html code in the timeout callback function.
A: The easiest way is to use jquery's marquee plugin to access your marquee in an easy way.
Then, the HTML is not executable! You should create a client-side script to achieve your purpose. For example: after adding a reference to jquery.js and marquee.jquery.js in your page, try:
HTML:
<marquee id="myMarq">Content here...</marquee>
JS:
$(document).ready(function(){
$("#myMarq").marquee().trigger('stop');
setTimeout(function(){
$("#myMarq").marquee().trigger('start');
},10000 /* or any time-out you want, in milisecond */);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jstl invalid prefix error I am using similar piece of code in a jspx file
<html
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:uikit="http://www.abc.net/ld/uikit" >
<head>
<link type="text/css" rel="stylesheet" href="${uikit:cpp('abc')}"/>
but its throws the error
jsp.error.attribute.invalidPrefix uikit
The cpp function is defined in the uikit.tld file.
The above code works perfectly fine on tomcat, but gives error on Websphere 7.0.0.19.
Any idea what might be going wrong ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: javascript function date I have this form in Drupal that contains two datepickers and two textfields. I need to write a function that updates the values in the two textfields. So in the textfield first_result I need to add 35 days and in the textfield second_result i need to add 3 months and to set these values in the two textfields, and in the datepicker due_date I need to update this field to add one year and 45 days:
My code:
<?php
drupal_add_js(drupal_get_path('module', 'Date') .'/script.js');
function Pregnancy_menu() {
$items['form/Date'] = array(
'title' => 'Date Calculator',
'page callback' => 'drupal_get_form',
'page arguments' => array('Date_form'),
'access callback' => TRUE,
);
return $items;
}
function Date_form($form_type) {
drupal_add_js(drupal_get_path('module', 'Date') .'/script.js');
$form['First_Period'] = array(
'#type' => 'date_popup',
'#title' => 'Date of your last menstrual period',
'#date_format' => 'Y-m-d',
'#date_text_parts' => array('year'),
'#date_increment' => 30,
'#date_year_range' => '-1:0',
'#default_value' => date(Y) . date(M) . date(D),
);
$form['Calculate_Forward'] = array(
'#type' => 'button',
'#value' => t('Calculate Forward'),
'#attributes' => array('onclick' => "testing()"),
);
$form['Reset_form'] = array(
'#name' => 'clear',
'#type' => 'button',
'#value' => t('Reset this Form'),
'#attributes' => array('onclick' => 'this.form.reset(); return false;'),
);
$form['First_result'] = array(
'#type' => 'textfield',
'#title' => t('first result'),
'#prefix' => '<div style="float:left;">',
'#suffix' => '</div>',
'#default_value' => 'Hello',
);
$form['Second_result'] = array(
'#type' => 'textfield',
'#title' => t('second result'),
'#prefix' => '<div style="float:left;">',
'#suffix' => '</div>',
);
$form['Due_Date'] = array(
'#type' => 'date_popup',
'#title' => 'Estimated Due Date',
'#date_format' => 'Y-m-d',
'#date_text_parts' => array('year'),
'#date_increment' => 30,
'#date_year_range' => '+1:+1',
'#default_value' => date(Y) . date(M) . date(D),
);
return $form;
}
//the javascript function script.js
var testing()=function()
{
//how to do the calculation here
}
A: This depends on what you mean by month? and what you mean by year?
If it is Jan 31 and you add 3 months is that adding 3 sets of 30 days (avg month), or incrementing the month value 3 times so it becomes Apr 31 (which doesn't exist).
And by year do you mean add 365 days or Feb 29 2004 -> Feb 29 2005 (again the second doesn't exist).
Date manipulation has a ridiculous number of boundary cases, so you really need to define what you are intending to do. The simplest solution would be to only use days and then convert that to milliseconds then add it to your current dates valueOf() then convert back to date:
function addDays( fromDate, numDays ) {
var millisecondsInDay = 1000 * 60 * 60 * 24;
return new Date( fromDate.valueOf() + (millisecondsInDay * numDays) );
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Warning: passing incompatible type to setRootViewController: I am doing a calculator for the iPhone, where on rotation of the device, a new view is displayed, and I am getting the following three errors:
CalculatorAppDelegate.m:21: warning: incompatible Objective-C types 'struct CalculatorViewController *', expected 'struct UIViewController *' when passing argument 1 of 'setRootViewController:' from distinct Objective-C type`
this error (and below) is from code:
self.window.rootViewController = self.viewController;
CalculatorAppDelegate.m: warning: Semantic Issue: Incompatible pointer types assigning to 'UIViewController *' from 'CalculatorViewController *'
the below error is from:
UIInterfaceOrientation interfaceOrientation = [[object object] orientation];`
CalculatorViewController.m: warning: Semantic Issue: Implicit conversion from enumeration type 'UIDeviceOrientation' to different enumeration type 'UIInterfaceOrientation'
A: For your first 2 errors:
*
*Either CalculatorViewController is not declared as a subclass of UIViewController in your .h file
*Or the compiler doesn't know about it, because you forgot the #import "CalculatorViewController.h" in your code to let the compiler know about its definition
For your last issue, this is because you misuse UIDeviceOrientation and UIInterfaceOrientation, which are not the same type (even quite related).
*
*UIInterfaceOrientation define the orientation of the user interface. It only has 4 values: Portrait, Landscape Left, Landscape Right or UpsideDown.
*UIDeviceOrientation define the orientation of the device. It has 6 values, defining that your device is straight up, turns 90° left or right, upsidedown, or faceing down ou up.
If you setup your interface so that it does not rotate (shouldAutorotateToInterfaceOrientation: returns YES only for one of the 4 UIInterfaceOrientation), your UIDeviceOrientation can still change (nothing prevent the user to turn his/her iPhone into any position), but your UIInterfaceOrientation won't change.
If you setup your interface so this it does rotate (shouldAutorotateToInterfaceOrientation: always returns YES), when the user turns his/her iPhone to the right, UIDeviceOrientation will be UIDeviceOrientationLandscapeRight because the iPhone will be turned right... and UIInterfaceOrientation will be UIInterfaceOrientationLandscapeLeft, because the interface orientation will be rotated 90° to the left, so that because the device is turned to the right, the interface will still be displayed horizontally to the user.
You can notice that UIInterfaceOrientation and UIDeviceOrientation have opposed values (for enums that are common to both; of course for UIDeviceOrientationFaceUp and UIDeviceOrientationFaceDown there is no corresponding UIInterfaceOrientation)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTTP Request does not set Content Length I'm trying to use Google Data API to upload a CSV file with some places.
I've this piece of code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:direccion]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:direccion]];
NSData *postData = [creacionCSV dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"2.0" forHTTPHeaderField:@"GData-Version"];
[request setValue:@"application/vnd.google-earth.kml+xml" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"Mapa de prueba" forHTTPHeaderField:@"Slug"];
[request setHTTPBody:postData];
[request setHTTPMethod:@"POST"];
NSData *datosRecibidos;
datosRecibidos = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *token = [[NSString alloc] initWithData:datosRecibidos encoding:NSASCIIStringEncoding];
NSLog(@"%@",token);
Where creacionCSV is an NSString with all the KML code.
Once executed, I've obtained this answe from server:
<html lang=en>
<meta charset=utf-8>
<title>Error 411 (Length Required)!!1</title>
<style> [...] </style>
<a href=//www.google.com/ id=g><img src=//www.google.com/images/logo_sm.gif alt=Google></a>
<p><b>411.</b> <ins>That’s an error.</ins>
<p>POST requests require a <code>Content-length</code> header.
<ins>That’s all we know.</ins>
So I'm getting that 411 Error. I've checked the header and it's not nil nor empty. Why is not taking that header my POST?
Many thanks!
A: How do you build tokenAutorizacion, the base64 encoding? See this page: http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Which CMS is right for me? I am looking to help out a non-profit get a website up and running.
Only, they don't just want a website with content, they also want to maintain a database of members, and allow those members to register and pay for classes/events/seminars held by the club.
It seems to me, that if all they wanted was to post content, nearly any of the available CMS's out there would fit the bill.
But the registration portion would require some customization.
I have considered just installing a basic CMS for them, and then creating separate web application for the registration section. And this would still work...
But if I wanted to hook into the users/roles from the CMS and use them in the registration side, I think I would have to have some way of either extending the CMS or easily using it's data in the sub-application.
I have been reading about the following CMS's:
*
*Orchard
*Umbraco
*C1 Composite
All of them seem to have the ability to be extended, but I'm not certain how much "work" is involved to extend each. Given that my requirements are rather simple and the fact that I don't want to spend a ton of time doing this (it is free work, after all), does anyone have a recommendation?
A: I'd pass on Umbraco and C1 Composite, as they generally aren't user-friendly. I think Orchard is best, as it has the best feedback of them all. Umbraco is aimed more at developers who want to tweak a lot of things.
Orchard - https://stackoverflow.com/questions/1978360/anybody-using-orchard-cms
Link - Reviews/Comparison of Open Source ASP.NET MVC CMS
A: Umbraco would be a very good choice because it:
*
*is mature and has a proven track record.
*is very easy to use for most use cases.
*has a built-in member system which could (and should) be used for the member registration.
*has a Big and friendly community always glad to help out.
*has lots of plugins and extensions covering some special use cases.
A: If you will go outside of .NET and IIS, Joomla is another popular CMS in LAMP. This can be hosted in either Unix or Win environments. There's a large community, lots of implementations and robust API for plugins. I run it on MAMP on my Mac, and it also runs on WAMPServer, for development.
Last year I created a membership style site in Joomla using Mighty Extensions for a bed and breakfast listing service (http://uurehome.com). Mighty User and Membership was enough, this adds custom user fields and subscription plans. You do have to pay for Mighty Extensions. Payment for the B&B listings is done thru Paypal, Mighty Membership enables this.
The subscription plan feature is Mighty Membership is very good. You can have length of time, cost renewals, renewal nag messages. Could have written myself, but why at this cost :-)
Joomla can certainly handle the community side of a non-profit site, there's the usual assortment of content, discussions, news feeds and so on. It's also ok for mere mortals to administer.
Not so sure about comparing to Orchard, as I haven't kicked the tires on Orchard. I have done enterprise web CMS for a living in the past, so I am used to evaluating these sorts of products. Orchard looks similar to Joomla in how it works, based on the screenshots I see in the docs. One thing I will say with confidence is that it's easier to standup Joomla (or something LAMP/WAMP/MAMP) than on the MS Webmatrix. However, if you already have a Webmatrix provider, then it's similar. Said by someone that has done a bunch of IIS and pretty much all the web technologies going back to the beginning of time (that's 1993).
Another aspect of using Joomla for me in this project, which is for a small business, was knowing that there's a bunch of Joomla knowledgable web design shops this owner could use if I stop helping her. While I am not going to say there isn't a base of folks doing web design that are doing Orchard, my sense is that its much smaller than Joomla. This is a factor for me in helping non-profits, churches and so on, not leaving them in a place where I am the "only" person that could keep whatever it is running. Still, if there's even a couple of local web design shops that do Orchard, I'd say that's enough to feel comfortable.
A: We built http://aclj.org on Orchard with a custom membership implementation within to support millions of members. We do form processing through Kimbia for donations and petition signatures. We're very happy with the implementation and feel that Orchard worked out well for us as a platform. It is VERY extensible and we developed 32 custom modules in-house.
A: For a non profit organization it is unlikely to maintain a costly server where LAMP stack has both low cost server and some decent CMS which meets your requirements perfectly. Some of them are :
*
*Drupal
*Joomla
*WordPress
Any of them are highly extensible, got a great community support , plenty of themes and modules readily available and you can get awesome things for free though there are some paid once too.
And if you want my recommendation i would go for Drupal as it provides :
*
*Build in role management service.
*Very matured and friendly community.
*Great scalabilty.
*Secured out of the box
*And some more .......
Hope that adds a new dimension to your search :)
Best of luck
A: I would recommend wordpress for your requirement.
Advantages:
1. More forum support.
2. Easy to learn.
3. Very less server cost to host the site.
4. You will have N number of plugins and widgets etc...
Hope It gives some sense :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How to set pixel on mouse click in C++ using WinApi (GDI) in GUI window? I'm trying to set pixel by mouse click, but nothing happens when I click. Here is part of my code.
First, I control window size changing in WM_SIZE.
Than, at first time when I want to set pixel by mouse I get window's width and height, then copy window's content to memory HDC and HBITMAP (in Store Window) (HBITMAP size equal to (width,height)). In fact, I copy to memory only clear window.
And than in any case I set pixel to memory DC. In next WM_PAINT message handling I'm drawing memory DC to screen.
.....
case WM_SIZE:
{
CheckWidthHeight();
break;
}
case WM_MBUTTONDOWN:
{
if (firstTimeDraw)
{
CheckWidthHeight();
StoreWindow();
firstTimeDraw = false;
}
SetPixel(memoryDC, LOWORD(lParam), HIWORD(lParam), RGB(0,0,0));
break;
}
case WM_PAINT:
{
RestoreWindow();
break;
}
.....
where my functions and variables is:
HDC memoryDC;
HBITMAP memoryBitmap;
int width = 0, height = 0;
bool firstTimeDraw = true;
void CheckWidthHeight()
{
RECT clientRect;
GetClientRect(hwnd, &clientRect);
width = clientRect.right - clientRect.left;
height = clientRect.bottom - clientRect.top;
}
//Copy real window content to memory window
void StoreWindow()
{
HDC hDC = GetDC(hwnd);
memoryDC = CreateCompatibleDC(hDC);
memoryBitmap = CreateCompatibleBitmap(hDC, width, height);
SelectObject(memoryDC, memoryBitmap);
BitBlt(memoryDC, 0, 0, width, height, hDC, 0, 0, SRCCOPY);
ReleaseDC(hwnd, hDC);
}
//Copy memory windows content to real window at the screen
void RestoreWindow()
{
PAINTSTRUCT ps;
HDC hDC = BeginPaint(hwnd, &ps);
memoryDC = CreateCompatibleDC(hDC);
SelectObject(memoryDC, memoryBitmap);
BitBlt(hDC, 0, 0, width, height, memoryDC, 0, 0, SRCCOPY);
EndPaint(hwnd, &ps);
}
What I'm doing wrong?
UPD:
A shot in the dark: You're handling the middle button click. Are you by any chance clicking on the left or right mouse buttons? :)
Ok. Now I use WM_LBUTTONUP or WM_LBUTTONDOWN. Nothing happens again.
UPD2:
*
*When you change the memory DC, you'll also want to invalidate the part of the window that is affected so that Windows will generate a WM_PAINT message for it. InvalidateRect would be a good place to start.
I placed this code
RECT rect;
GetClientRect(hwnd, &rect);
InvalidateRect(hwnd, &rect, true);
before EndPaint. Nothing. Than I move it after EndPaint. Nothing.
*
*In the WM_PAINT handler, you need to use a DC provided by BeginPaint and call EndPaint when you're done with it.
I do it in RestoreWindow().
I don't know yet what's the problem...
UPD3:
InvalidateRect() needs to happen in the WM_?BUTTONDOWN handler after the SetPixel (not in RestoreWindow())- it's what tells windows that you want to get a WM_PAINT in the first place.
Ok. I've done it before you wrote this message. Still don't work.
UPD4:
Thank you a lot, Remy! Thank you to all the rest. Now all right!!
A: Two things.
*
*When you change the memory DC, you'll also want to invalidate the part of the window that is affected so that Windows will generate a WM_PAINT message for it. InvalidateRect would be a good place to start.
*In the WM_PAINT handler, you need to use a DC provided by BeginPaint and call EndPaint when you're done with it.
A: When you call RestoreWindow() to draw the bitmap onscreen, you are wiping out your memoryDC variable that you used to draw the pixels with. The bitmap is still selected into the original HDC that you have now lost, and a bitmap cannot be selected into multiple HDCs at the same time (the MSDN documentation for SelectObject() says as much). So you are not actually drawing the bitmap onscreen at all.
There is no need to call CreateCompatibleDC() or SelectObject() inside of RestoreWindow() because you already have the bitmap and memory HDC set up inside of StoreWindow(), so they use them as-is instead.
Try this:
HDC memoryDC = NULL;
HBITMAP memoryBitmap = NULL;
int width = 0, height = 0;
void CheckWidthHeight()
{
RECT clientRect;
GetClientRect(hwnd, &clientRect);
width = clientRect.right - clientRect.left;
height = clientRect.bottom - clientRect.top;
}
void StoreWindow()
{
HDC hDC = GetDC(hwnd);
memoryDC = CreateCompatibleDC(hDC);
memoryBitmap = CreateCompatibleBitmap(hDC, width, height);
SelectObject(memoryDC, memoryBitmap);
BitBlt(memoryDC, 0, 0, width, height, hDC, 0, 0, SRCCOPY);
ReleaseDC(hwnd, hDC);
}
void RestoreWindow()
{
PAINTSTRUCT ps;
HDC hDC = BeginPaint(hwnd, &ps);
if (memoryDC)
BitBlt(hDC, 0, 0, width, height, memoryDC, 0, 0, SRCCOPY);
EndPaint(hwnd, &ps);
}
...
case WM_SIZE:
{
CheckWidthHeight();
break;
}
case WM_LBUTTONDOWN:
{
if (!memoryDC)
StoreWindow();
if (memoryDC)
{
SetPixel(memoryDC, LOWORD(lParam), HIWORD(lParam), RGB(0,0,0));
RECT rect;
rect.left = LOWORD(lParam);
rect.top = HIWORD(lParam);
rect.right = rect.left + 1;
rect.bottom = rect.top + 1;
InvalidateRect(hwnd, &rect, TRUE);
}
break;
}
case WM_PAINT:
{
RestoreWindow();
break;
}
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Rails 3 link or button that executes action in controller In RoR 3, I just want to have a link/button that activates some action/method in the controller. Specifically, if I click on a 'update_specs' link on a page, it should go to 'update_specs' method in my products controller. I've found suggestions to do this on this site:
link_to "Update Specs", :controller => :products, :action => :update_specs
However, I get the following routing error when I click on this link:
Routing Error No route matches {:action=>"update_specs",
:controller=>"products"}
I've read up on routing but I don't understand why I should have to route this method if all other methods are accessible via resources:products.
A: You need to create a route for it.
For instance:
resources :products do
put :update_specs, :on => :collection
end
Also by default link_to will look for a GET method in your routes. If you want to handle a POST or PUT method you need to specify it by adding {:method => :post } or {:method => :put } as a parameter, like:
link_to "Update Specs", {:controller => :products, :action => :update_specs}, {:method => :put }
Or you can use button_to instead of link_to which handles the POST method by default.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How do I get mongoid's eager loading to work? I get the following error:
NoMethodError (undefined method `eager_load' for nil:NilClass)
when I run the following command in Mongoid 2.2.1
Person.includes(:game).all.each do
user.game.dosomething
end
a Person has_one Game
A: Just turn on Identity Map: http://mongoid.org/en/mongoid/docs/identity_map.html
A: Try add this to your Gemfile
# gem "mongoid-eager-loading"
But note that it's deprecated in newer mongoid versions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: IE9 - acceptable frameset replacement I have a site that I'm working on that has a lot of framesets in it. However, since IE9 (HTML5), framesets have been deprecated and it throws me into quirks mode which slows down the loading of my page. Basically, I'm looking for an acceptable alternative to framesets that is HTML5 compatible. Thanks for any responses.
A: You can simply replace frameset with iframes. Use CSS and maybe some JavaScript to recreate the same layout.
A: Were you using frames in order to provide distinction between different sections of your page, i.e. a frame for a left nav column, a frame for a header, and a frame for the content? If so, you can accomplish the same effect by using div elements and css styling.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Quick while stopping i have this code:
private STOP = false;
public void Start()
{
while(!STOP)
{
//do some work
Thread.Sleep(15000);
}
}
public void Stop()
{
STOP = true;
}
But using this code sometimes need to wait a 15 secs, how to quickly stop this cycle or maybe need to use other code?
Thanks!
A: Something along the lines of:
private System.Threading.ManualResetEvent STOP = new System.Threading.ManualResetEvent(false);
public void Start()
{
while(true)
{
//do some work
if(STOP.WaitOne(15000))
break;
}
}
public void Stop()
{
STOP.Set();
}
A: Whenever you find yourself writing a loop that does something, then waits a relatively long period of time (even one second is a long time!) to do it again, you should eliminate the loop and use a timer. For example, your code above can be re-written:
System.Threading.Timer MyTimer;
public void Start()
{
MyTimer = new Timer((s) =>
{
DoSomeWork();
}, null, 15000, 15000);
}
The timer will be triggered every 15 seconds to do the work. When it's time to shut down the program, just dispose of the timer.
public void Stop()
{
MyTimer.Dispose();
}
This will be more efficient than using a separate thread that spends most of its time sleeping, but still consuming system resources.
A: Use ManualResetEvent.WaitOne with timeout.
manualResetEvent.WaitOne(timeout)
Set the event to wake it up, or it will wake up when timed out.
See this related question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to write a GROUP BY SQL query I have a "Revenue" table which stores the revenue for a Company State combination.
Company int
State char(2)
IsBiggestState bit
TotalRevenue numeric (10,2)
I need to set the IsBiggestState bit to 1 if the TotalRevenue Amount is the largest amount of all the States within a Company.
How can I write the SQL? Since I am dealing with millions of records, efficiency is of concern.
We are on SQL2008 R2.
A: UPDATE A
SET A.IsBiggestState = 1
FROM YourTable A
INNER JOIN (SELECT Company, MAX(TotalRevenue) MaxRevenue FROM YourTable
GROUP BY Company) B
ON A.Company = B.Company AND A.TotalRevenue = B.MaxRevenue
A: This would address the problem of 2 states having the same TotalRevenue (if that is indeed a problem). It would mark only one of them as the IsBiggestState. I am not entirely sure how the performance compares to other solutions.
UPDATE A
SET A.IsBiggestState = 1
FROM Revenue A
INNER JOIN
(
SELECT
Company
,[State]
,ROW_NUMBER() OVER (PARTITION BY Company ORDER BY TotalRevenue desc) as rownum
FROM Revenue
) B
ON A.Company = B.Company AND A.[State] = B.[State] AND B.rownum = 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there an R package that will handle POSIX objects and return the nth N-day of the week? I have written a function which, when provided a range of dates, the name of a particular day of the week and the occurrence of that day in a given month (for instance, the second Friday of each month) will return the corresponding date. However, it isn't very fast and I'm not 100% convinced of its robustness. Is there a package or set of functions in R which can do these kinds of operations on POSIX objects? Thanks in advance!
A: Using the function nextfri whose one line source is shown in the zoo Quick Reference vignette in the zoo package the following gives the second Friday of d where d is the "Date" of the first of the month:
library(zoo)
d <- as.Date(c("2011-09-01", "2011-10-01"))
nextfri(d) + 7
## [1] "2011-09-09" "2011-10-14"
(nextfri is not part of the zoo package -- you need to enter it yourself -- but its only one line)
The following gives the day of the week where 0 is Sunday, 1 is Monday, etc.
as.POSIXlt(d)$wday
## [1] 4 6
If you really are dealing exclusively with dates rather than date-times then you ought to be using "Date" class rather than "POSIXt" classes in order to avoid time zone errors. See the article in R News 4/1.
A: The timeDate package has some of that functionality; I based this little snippet of code on some code that package. This is for Dates, timeDate has underlying POSIX types.
nthNdayInMonth <- function(date,nday = 1, nth = 1){
wday <- (as.integer(date) - 3) %% 7
r <- (as.integer(date) + (nth -1) * 7 + (nday - wday)%%7)
as.Date(r,"1970-01-01")
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Apply a pattern against a calendar Say I have a pattern of letters that simply repeats itself forever - is there an easy way to apply this pattern to a calendar?
For example, the actual pattern itself is E1, E, E, E, O, O, N1, N1, N, O, O, O, L, L1, L1, L, O, O, E, E, E1, O, O, N, N, N, N, O, O, O, L, L, L, O, O, E1, E, E, E, O, O
I would like to then take this pattern and apply it for the rest of the year (and if possible, a year or two after that aswell) starting from a given date, in my case, the 25th February 2012.
I've been thinking about how to solve this using PHP without having to resort to doing it manually but I can't think of the steps to take, all I can think is that it will make extensive use of the date() function!
All joking aside, I think putting these values into an array might be a good first step and use that structure as the basis of the loop?
Ideal output would simply be:
dd/mm/yyyy : one of E1/E/O/N1/N
A: Not sure why this was deleted, it was almost correct. All I added is the while loop from the previous answer. All credit to original poster.
<?php
$str = "E1, E, E, E, O, O, N1, N1, N, O, O, O, L, L1, L1, L, O, O, E, E, E1, O, O, N, N, N, N, O, O, O, L, L, L, O, O";
$now = strtotime('25th Feb 2012'); // Now in unix-timestamp (seconds since epoch)
$end = strtotime('2013-02-25');
while ($now <= $end)
{
foreach (explode(', ', $str) as $val) { // Loop through each value
print date("d/m/Y", $now) . " : {$val}<br />\n"; // Format output
$now += 86400; // Add 1 day to $now (86400 seconds)
if ($now >= $end) break; // Close after $end date
}
}
?>
A: In php it's very easy using a Julian Daten
$str = explode(', ',"E1, E, E, E, O, O, N1, N1, N, O, O, O, L, L1, L1, L, O, O, E, E, E1, O, O, N, N, N, N, O, O, O, L, L, L, O, O");
$now = GregorianToJD(date('m'),date('j'),date('Y'));
$start = GregorianToJD(1,13,1993); // Start January 13th 1993
$days = $now-$start; //get total days
$tod = $str[($days % count($str)) - 1]; //Total days mod amount of options -1 gets you the key to the currect code.
echo "today is $tod";
A: You can use a function like this:
<?php
function valueFor($check_date){
//the data reference
$data = "E1, E, E, E, O, O, N1, N1, N, O, O, O, L, L1, L1, L, O, O, E, E, E1, O, O, N, N, N, N, O, O, O, L, L, L, O, O";
$data_ary = explode(',',str_replace(' ','',$data));
$start_stamp = strtotime("2012-02-25");
$check_stamp = strtotime($check_date);
//get difference of days for both dates
$days_diff = floor( ($check_stamp - $start_stamp) / (60*60*24) );
if($days_diff > count($data_ary)) $days_diff = ( $days_diff % count($data_ary) ) - 1;
return $data_ary[$days_diff];
}
//=> this will output 'E1'
echo valueFor('2012-04-01');
?>
So you simply call the function passing the date.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Publish into facebook wall from flex mobile I'm building a mobile app using flex 4.5 that should be able to post/share a message to the facebook wall.
I've find examples for desktop app, but I am not getting any examples for mobile app. Can someone help me?
A: You can use the new FacebookMobile class for posting to the wall etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS Help: floating an image inside a list item hides icon I have an image in a list item I need floated. Everything looks fine in FF/6+. Webkit and IE, however, show the list icon on top of the image. When I try floating the list item itself, the icon simply vanishes. Is there a CSS way around this issue? I tried wrapping the content in a span, and still no solution. I've removed some of the text in order to lighten the code here.
<ul class="leftList">
<ul>
<li>Pillow menu to customize your night's sleep</li>
<li>Complimentary bathroom amenities</li>
<li><span class="special_needs_list_item"><a rel="tooltip nofollow" title="Tooltip - Lorem ipsum"><img src="http://teamsite-prod.rccl.com:8030/DOT/img/global/special_needs.png" alt=""></a> Some srooms in this category are wheelchair-accessible.</span></li>
</ul>
</ul>
#ccStateroomFeatures ul {
float: left;
width: 320px;
margin-left: 15px;
font-size: 12px;
}
#ccStateroomFeatures ul li {
margin-bottom: 5px;
}
#ccStateroomFeatures .leftList {
width: 490px;
float: left;
}
#ccStateroomFeatures .leftList ul,
#ccStateroomFeatures .rightList ul {
float: none;
margin-left: 15px;
width: auto;
}
#ccStateroomFeatures .leftList ul .special_needs_list_item {
margin:0 0 20px -15px;
padding-left:15px;
}
#ccStateroomFeatures .leftList ul .special_needs_list_item img {
float:left;
margin:3px 5px 0 15px;
overflow:hidden;
width:13px;
}
A: I'm not sure I understand what you're trying to do. Are you trying to have the image supplied be used instead of the list icon?
If so, you'll want to use list-style-type:none to deal with that. Then play around with the margins to get it to line up like you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Doctrine 2 - Access level problems when using Class Table Inheritance I'm trying to implent the Class Table Inheritance Doctrine 2 offers in my Symfony 2 project.
Let's say a have a Pizza class, Burito class and a MacAndCheese class which all inherit from a Food class.
The Food class has the following settings:
<?php
namespace Kitchen;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="food")
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="dish", type="string")
* @ORM\DiscriminatorMap({"pizza" = "Pizza", "burito" = "Burito", "mac" => "MacAndCheese"})
*/
class Food {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
And the inherited classes have these settings (Pizza for example):
<?php
namespace Kitchen;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="food_pizza")
*/
class Pizza extends Food {
When running doctrine:schema:update --force from the Symfony 2 app/console I get an error about the access level of $id in the children of Food (Pizza for example), stating it must be protected or weaker. I haven't declared $id anywhere in the Pizza, since I reckoned it would be inherited from Food.
So I tried to declare $id, but that gives me an error, cause I can't redeclare $id.
I figure I need some kind of reference to $id from Food in Pizza, but the Doctrine 2 documentation didn't really give me a clear answer on what this would look like.
Hopefully you understand what I mean and can help me.
A: Apparently I should have investigated the code generated by doctrine:generate:entities a bit more. When I started my IDE this morning and seeing the code again, I noticed that it had 'copied' all of the inherited fields (like $id in Food, in the example above) to the children (Pizza, in the example above).
For some reason it decided to make these fields private. I manually changed the access level to protected in all of the classes and I tried to run doctrine:schema:update --force again: it worked!
So, as in many cases, the solution was a good night's rest! ;)
If someone comes up with a better solution and / or explanation for this problem, please do post it. I'd be more than happy to change the accepted answer.
A: Something to keep in mind:
Every Entity must have an identifier/primary key. You cannot generate
entities in an inheritance hierachy currently (beta) As a workaround
while generating methods for new entities, I moved away from project
inheritated entities and after generating I moved them back.
source
A: May be you should define the @ORM\DiscriminatorMap in a such way:
/**
*
..
* @ORM\DiscriminatorMap({"food" = "Food", "pizza" = "Pizza", "burito" = "Burito", "mac" => "MacAndCheese"})
*/
If you compare your code with the example from Doctrine site, you will see that they added parent entity to the DiscriminatorMap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What's the effect on a second request of calling Thread.currentThread().sleep(2000) in a Spring MVC request handler? I need to wait for a condition in a Spring MVC request handler while I call a third party service to update some entities for a user.
The wait averages about 2 seconds.
I'm calling Thread.sleep to allow the remote call to complete and for the entities to be updated in the database:
Thread.currentThread().sleep(2000);
After this, I retrieve the updated models from the database and display the view.
However, what will be the effect on parallel requests that arrive for processing at this controller/request handler?
Will parallel requests also experience a wait?
Or will they be spawned off into separate threads and so not be affected by the delay experienced by the current request?
A: What are doing may work sometimes, but it is not a reliable solution.
The Java Future interface, along with a configured ExecutorService allows you to begin some operation and have one or more threads wait until the result is ready (or optionally until a certain amount of time has passed).
You can find documentation for it here:
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What exactly does Delegate.EndInvoke do? Is it necessary to call?
Possible Duplicate:
Why does asynchronous delegate method require calling EndInvoke?
Is Delegate.EndInvoke() really necessary?
Working on a multi-threaded application at the moment and when raising an event instead of doing the normal handler.Invoke(); I am experimenting with handler.BeginInvoke();. Both work fine. However, for BeginInvoke I am using null for the last two arguments because there needs not be a callback and since there is no callback, there is definitely no need for data to be passed to a non-existent callback.
Because of this, I am not calling EndInvoke at all. But the application seems to.. work perfectly? I read and people said there would be leaks which may be occurring but I am just not noticing.
I'm curious though, what exactly does EndInvoke do? Do I really need to make a callback just to call EndInvoke and that's it? Also, why does EndInvoke take an IAsyncResult argument? I can just pass null for that right because there is no extra data being passed to the callback, correct? But still, I'm wondering, why, if there was extra data, would it need to be passed to EndInvoke? What is it doing with that parameter? I want to know how it works.
I checked the .NET Reflector but I couldn't find where EndInvoke was actually defined. In EventHandler (which is what I'm using) all it showed was the method header.
Thanks.
A: The main practical concerns are deterministically cleaning up a wait handle resource (if you chose to create the handle by referencing it) and making sure that Exceptions are propagated properly.
That said, what I would recommend is to move away from the slightly schizophrenic asynchronous pattern in the earlier .NET framework and use TPL, which has a much cleaner continuation model. The TPL even has some nice wrapping functionality to help deal with the older Begin/End style of calling:
http://msdn.microsoft.com/en-us/library/dd997423.aspx
A: As was mentioned in one of the referenced articles, if you're invoking a delegate in a fire-and-forget fashion, you probably should use ThreadPool.QueueUserWorkItem instead. Then you won't have to worry about cleaning up with EndInvoke.
A: According to MSDN, you ought to always call EndInvoke no matter what:
No matter which technique you use, always call EndInvoke to complete your asynchronous call.
So take that for what it's worth. I assume it's futureproofing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iOS: is Core Graphics implemented on top of OpenGL? I have found one diagram that shows Core Graphics implemented above OpenGL, and another that puts it alongside OpenGL. I would think that Apple would be smart to give each equal access to the graphics hardware but then again, I don't know much about the graphics chip they are using... maybe it is 3D all the way?
Does anybody here know the specifics?
A: Core Graphics and OpenGL are two completely separate systems. Look at the image below (source), which shows both listed at the same level. The description of Core Graphics lower on the same page also indicates that it is the lowest-level native drawing system.
Also see the About OpenGL ES page. It shows that the OpenGL code runs directly on the GPU, and if you scroll down you will see that there are some things which cannot be done with an application that uses OpenGL. Obviously, if CG was based on OpenGL, you wouldn't be able to do those things ever.
Finally, look at the Drawing Model page for iOS. At the top, it compares OpenGL to native drawing, indicating that they work separately from each other.
A: Core Graphics and OpenGL are separate technologies. UIKit and AppKit are built on top of both, as well as Core Animation. You can see the graphics technology stack inside Apple's documentation (Core Animation Programming Guide)
A: Yes, on iOS Core Graphics (Quartz) appears to be layered on top of OpenGL ES for drawing that targets the screen, although not in an explicit way that we have access to.
Core Graphics takes vector elements (lines, arcs, etc.) and some raster ones (images) and processes them for display to the screen or for other forms of output (PDF files, printing, etc.). If the target is the screen on iOS, those vector elements will be hosted in a CALayer, either directly or through the backing layer of a UIView.
These Core Animation layers are effectively wrappers around rectangular textures on the GPU, which is how Core Animation can provide the smooth translation, scaling, and rotation of layers on even the original iPhone hardware. I can't find a reference for it right now, but at least one WWDC presentation states that OpenGL ES is used by Core Animation to communicate with the GPU to perform this hardware acceleration. Something similar can be observed on the new dual-GPU MacBook Pros, where the more powerful GPU kicks in when interacting with an application using Core Animation.
Because Core Graphics rasterizes the vector and raster elements into a CALayer when drawing to the screen, and a CALayer effectively wraps around an OpenGL ES texture, I would place OpenGL ES below Core Graphics on iOS, but only for the case where Core Graphics is rendering to the screen. The reason for the side-by-side placement in the hierarchy you saw may be due to three factors: on the Mac, not all views are layer-backed, so they may not be hardware accelerated in the same way; we can't really interact with the OpenGL ES backing of standard UI elements, so from a developer's point of view they are distinct concepts; and Core Graphics can be used to render to offscreen contexts, like PDF files or images.
A: As of iOS 9 Core Graphics on iOS are based on Apple's Metal framework, not OpenGL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: left:50% element not appearing in middle of page I have an absolute positioned popup (hover over "ice white" image to see popup) which has css left:50%. Now this should appear in the middle of page but doesn't. Any suggestions please? Thanks in advance.
A: position: absolute;
left: 50%;
transform: translate(-50%,0)
A: You're also supposed to add margin-left with the negative of a half of visible width of the element. So, for example:
width: 400px;
padding: 10px;
border-width: 2px;
/* -(400 + 10 + 2)/2 = -206 */
margin-left: -206px;
left: 50%;
Note that margin: auto suggested by others won't work because you've positioned the element absolutely.
A: Lol, no. The left side of the image appears at 50% of the page width. Hence; left: 50%.
In order to center your image, set margin: auto instead.
A: Your code is working correctly. The popup is being positioned with left of 50% ... of the TD tag it's nested inside.
Try either taking the popup out of the table, or setting it to 50% of the document width instead. (Your javascript is minified and unreadable to me, or I'd help further.)
A: u can try to change CSS Style like this
#displayDiv {
background-color: white;
font-weight: bold;
height: 460px;
left: 50%;
margin: auto auto auto -475px;/* change done here */
overflow: hidden;
position: absolute;
text-align: center;
top: 80px;
width: 950px;
z-index: 1;
}
A: Looks to me like there's a containing element somewhere in between the "Ice White" image and the body (specifically, Firebug reveals that it's the <a class="popup1" ... >) that is relatively positioned, so your 50% is relative to that rather than the whole page.
I know this seems a bit counterintuitive: Why should it be relative to a parent element if the poput uses absolute positioning? It's basically because relative positioning is relative to where the element is in the normal flow of the document, whereas absolute positioning yanks the element out of that flow. See sections 9.4.3 and 9.6 of the W3C's explanation of the visual formatting model for more info.
Check out a tutorial or two if this is giving you trouble. I like Learn CSS Positioning in Ten Steps and css-tricks.com's "Absolute Positioning Inside Relative Positioning" (to which I'd provide a link if not for the spam filter; first-time answerer here ;) ).
As for what to do about it, you might be able to move the popups out of the relatively positioned parent, as mblaze75 suggests, but it looks (and I'm guessing here) like that <a> is what's triggering your JavaScript event, so you probably can't do that. Instead, I'd try removing the relative positioning and using margins instead.
Also, bear in mind what Greg Agnew said: Even with that problem solved, you're still centering the left edge rather than the center of your popup. I think duri's answer will take care of that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Wicket application throws exception on start up when starting with jetty:run-exploded I'm currently developing a Wicket Spring Hibernate application. For development I'm using Jetty as web server.
When starting the application with mvn jetty:run everything works as expected. But when I try to start the application with mvn jetty:run-exploded some exceptions are thrown telling that the sessionFactory bean couldn't be created.
I already search a lot about this issue but couldn't find any hints on what triggers this error. Also the stack trace doesn't provide very much information where exactly to start. I hope someone can point me in the right direction how to solve this issue.
As the exception stack trace is too long to post it here I pasted it on PasteBin. This happens if I start my application with mvn jetty:run-exploded. Exception Stack Trace
Here is my applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- Configurer that replaces ${...} placeholders with values from properties files -->
<!-- (in this case, JDBC related properties) -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:application.properties</value>
<value>file:///${user.home}/storefinder.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
<!-- a bean for storing configuration properties. -->
<bean id="runtimeConfig" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:application.properties</value>
<value>file:///${user.home}/storefinder.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
<!-- bean id="wicketApplication" class="com.mycompany.storefinder.backend.core.web.StoreFinderApplication" /-->
<!-- Services -->
<bean id="authenticationService" class="com.mycompany.storefinder.backend.core.service.AuthenticationServiceImpl">
<constructor-arg ref="userDao"/>
<constructor-arg ref="runtimeConfig" />
</bean>
<bean id="imageService" class="com.mycompany.storefinder.backend.core.infrastructure.filesystem.ImageFileServiceImpl">
<constructor-arg ref="imageDao"/>
<constructor-arg ref="runtimeConfig" />
</bean>
<!-- DAOs -->
<bean id="offerDao" class="com.mycompany.storefinder.backend.core.infrastructure.hibernate.OfferDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userDao" class="com.mycompany.storefinder.backend.core.infrastructure.hibernate.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="roleDao" class="com.mycompany.storefinder.backend.core.infrastructure.hibernate.RoleDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="imageDao" class="com.mycompany.storefinder.backend.core.infrastructure.hibernate.ImageDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="storeDao" class="com.mycompany.storefinder.backend.core.infrastructure.hibernate.StoreDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Database Beans -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:file:target/db/storefinder"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="use_outer_join">true</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
<prop key="hibernate.connection.pool_size">10</prop>
<prop key="hibernate.jdbc.batch_size">1000</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.mycompany.storefinder.backend.core.domain.offer.Offer</value>
<value>com.mycompany.storefinder.backend.core.domain.image.Image</value>
<value>com.mycompany.storefinder.backend.core.domain.store.Store</value>
<value>com.mycompany.storefinder.backend.core.domain.store.OpeningPeriod</value>
<value>com.mycompany.storefinder.backend.core.domain.store.CommunicationData</value>
<value>com.mycompany.storefinder.backend.core.domain.user.Role</value>
<value>com.mycompany.storefinder.backend.core.domain.user.User</value>
<value>com.mycompany.storefinder.backend.core.domain.base.BusinessObject</value>
</list>
</property>
<!-- TODO Check -->
<property name="schemaUpdate" value="true"/>
</bean>
<!-- Tell Spring it should use @Transactional annotations -->
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Here is my pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.storefinder</groupId>
<artifactId>backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>StoreFinder Backend</name>
<dependencies>
<!-- LOGGING DEPENDENCIES -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- SPRING -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>2.5.5</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>spring-core</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-context</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-beans</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- HIBERNATE & DB -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.158</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.15.0-GA</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<!-- COMMONS LIBS -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- JODA TIME -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time-hibernate</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.6.2</version>
</dependency>
<!-- WICKET -->
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-auth-roles</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-extensions</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-spring</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-devutils</artifactId>
<version>${wicket.version}</version>
</dependency>
<!-- TESTING DEPENDENCIES -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils</artifactId>
<version>${unitils.version}</version>
<type>pom</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-spring</artifactId>
<version>${unitils.version}</version>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-test</artifactId>
<version>${unitils.version}</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-management</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.1</version>
</dependency>
<!-- >dependency>
<groupId>org.codehaus.enunciate</groupId>
<artifactId>enunciate-spring3-app-rt</artifactId>
<version>1.24</version>
</dependency-->
</dependencies>
<build>
<plugins>
<!-- plugin>
<groupId>org.codehaus.enunciate</groupId>
<artifactId>maven-enunciate-spring-plugin</artifactId>
<version>1.24</version>
<configuration>
<configFile>src/main/webapp/WEB-INF/enunciate.xml</configFile>
</configuration>
<executions>
<execution>
<goals>
<goal>assemble</goal>
</goals>
</execution>
</executions>
</plugin-->
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<encoding>UTF-8</encoding>
<source>1.5</source>
<target>1.5</target>
<optimize>true</optimize>
<debug>true</debug>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.8</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>${cobertura.version}</version>
<configuration>
<instrumentation>
<excludes>
<exclude>src/test/**/*.class</exclude>
</excludes>
</instrumentation>
</configuration>
<executions>
<execution>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>${jetty.version}</version>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Add code coverage report to site -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>${cobertura.version}</version>
</plugin>
</plugins>
</reporting>
<properties>
<wicket.version>1.5-RC5.1</wicket.version>
<jetty.version>6.1.4</jetty.version>
<cobertura.version>2.5.1</cobertura.version>
<slf4j.version>1.6.1</slf4j.version>
<springframework.version>3.0.5.RELEASE</springframework.version>
<junit.version>4.8.1</junit.version>
<unitils.version>3.1</unitils.version>
</properties>
</project>
UPDATE
As adding the Maven dependency graph of my project here would exceed the maximum allowed character count I pasted it to PasteBin.
UPDATE 2
Output of the maven-duplicate-finder plugin.
UPDATE 3
*
*Updated dependency graph.
*Updated conflicts.
A: java.lang.IncompatibleClassChangeError: Implementing class means that some class used to implement an interface, but that interface turned into a class. Usually it's an evidence of some version conflict.
I believe you have conflicting versions of Hibernate artifacts in the classpath. If so, the problem can manifest itself only in particular configurations (such as run-exploded) due to different ordering of classpath items.
Try to run mvn dependency:tree -Dverbose to identify conflicts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: adblock and jquery It seems like adblock for Chrome is preventing jquery's $.load() command from being executed. I looked around the web a little and couldn't find anything about this. It doesn't seem to block other jquery, such as $.ajax. I threw a little message on the main page of my site to warn users, but I'd rather find a fix or workaround. Anyone heard of this problem before?
A: Maybe what you're retreiving with .load() is injected in a div named publicity, advertising or something similar that get blocked by adblock.
A: jQuery .load() is just shorthand for an Ajax load, so if Ajax is worknig but not .load(), it's probably something you did wrong.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How To Check If A User's iOS Device Supports Bluetooth Peer-To-Peer Connections What is the best way of programatically checking if the current device supports Bluetooth peer-to-peer GameKit connectivity? I am aware of how to check for Game Center support, but want to support devices on iOS 3 that have Bluetooth (I know all devices with bluetooth can be upgraded to iOS 4).
Edit: The app functions perfectly fine without Bluetooth, so I don't want peer-peer to be in UIRequiredDeviceCapabilities.
Many thanks in advance,
jrtc27
A: Since we know which device supports what, if you can detect device you can make it work. I found this method and it works for me. You can find device capabilities here.
//Return TRUE if Device Support X.
-(BOOL)platformSupported_X
{
NSString *platform = [self platform];
if ([platform isEqualToString:@"iPhone1,1"]) return FALSE;
if ([platform isEqualToString:@"iPhone1,2"]) return FALSE;
if ([platform isEqualToString:@"iPhone2,1"]) return TRUE;
if ([platform isEqualToString:@"iPhone3,1"]) return TRUE;
if ([platform isEqualToString:@"iPod1,1"]) return FALSE;
if ([platform isEqualToString:@"iPod2,1"]) return TRUE;
if ([platform isEqualToString:@"iPod3,1"]) return TRUE;
if ([platform isEqualToString:@"iPod4,1"]) return TRUE;
if ([platform isEqualToString:@"iPad1,1"]) return TRUE;
if ([platform isEqualToString:@"i386"]) return TRUE;
return TRUE;
}
// Check Device Model
-(NSString *)platform
{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithUTF8String:machine];
free(machine);
return platform;
}
A: There doesn't seem to be an elegant way to detect bluetooth peer-to-peer support based on the device type. You might want to consider basing the detection on the OS version instead (iOS 3.1 is the minimum for peer-to-peer):
NSString *reqSysVer = @"3.1";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
BOOL osSupportsBluetoothPeerToPeer = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);
In case the OS is 3.1 or later, but the device does not support bluetooth peer-to-peer, the system will inform the user about the lack of support. This seems to be what Apple prefers: http://support.apple.com/kb/HT3621
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Javascript, add string if true I need to modify this function:
function checkPermissions(fid, obj) {
$("#permissions_"+fid+"_canview").attr("checked", obj.checked);
}
if the param "n" is "true" then instead of #permissions it'll output #permissionsSet.
is that possible?
A: OP clarified the question to be change this whether or not a 3rd parameter was provided. Here you go.
function checkPermissions(fid, obj, n) {
var id = n !== undefined ? '#permissionsSet' : '#permissions';
$(id + fid + "_canview").attr("checked", obj.checked);
}
Note: This function can be freely used with passing 2 or 3 parameters (or really any number).
checkPermissions(1, this); // Ok n === undefined
checkPermissions(1, this, true); // Ok n === true
checkPermissions(1); // Okish n and obj === undefined
A: function checkPermissions(fid, obj, n) {
$("#permissions" + ((n) ? "Set" : "") + "_"+fid+"_canview").attr("checked", obj.checked);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Redirecting a page using Javascript, like PHP's Header->Location I have some code like so:
$('.entry a:first').click(function()
{
<?php header("Location:" . "http://www.google.com"); ?>
});
I would like to know how I can achieve this using Javascript.
A: You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)
You can use window.location to change your current page.
$('.entry a:first').click(function() {
window.location = "http://google.ca";
});
A: You application of js and php in totally invalid.
You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.
However you can do something like this
var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;
You see, by the time the script is loaded, the above code renders into different form, something like this
var newLocation = "your/redirecting/page.php";
window.location = newLocation;
Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.
A: The PHP code is executed on the server, so your redirect is executed before the browser even sees the JavaScript.
You need to do the redirect in JavaScript too
$('.entry a:first').click(function()
{
window.location.replace("http://www.google.com");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: How to set volume for text-to-speech "speak" method? I'm at a lost. I want to be able to adjust the speak volume. Whatever I do, I can't increase its volume. How do I make it as loud as that found in the Android settings (as below)?
System Settings -> Voice input and output -> Text-to-Speech settings -> Listen to an example
My code at this moment is:
AudioManager mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setSpeakerphoneOn(true);
int loudmax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
mAudioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION,loudmax, AudioManager.FLAG_PLAY_SOUND);
mTts.speak(name,TextToSpeech.QUEUE_FLUSH, null);
A: In your code you are changing the volume of notifications. Is the volume of TTS played at the same volume level as notifications? I suspect it isn't and it probably played at either STREAM_SYSTEM or STREAM_MUSIC Try changing the stream type to one of these:
STREAM_VOICE_CALL, STREAM_SYSTEM, STREAM_RING, STREAM_MUSIC or STREAM_ALARM
A: Try using AudioManager.STREAM_MUSIC when calling the setStreamVolume(...) method. The example speech is affected by the media volume if I adjust the volume of music playback on my phone so I guess STREAM_MUSIC is what you need.
EDIT: This code works perfectly for me...
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int amStreamMusicMaxVol = am.getStreamMaxVolume(am.STREAM_MUSIC);
am.setStreamVolume(am.STREAM_MUSIC, amStreamMusicMaxVol, 0);
tts.speak("Hello", TextToSpeech.QUEUE_FLUSH, null);
The max volume for STREAM_MUSIC on my phone is 15 and I've even tested this by replacing amStreamMusicMaxVol in my call to am.setStreamVolume(...) above with the values 3, 6, 9, 12, 15 and the volume of the speech is correctly set.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: logout the main form and show the login form i know this problem may sound stupid, but sad case, i've been searched online to get solution but still cannot get it correct. My problem now is = Logout button so to exit the main form, then show up the login form again.
The code below will NOT show the login form after i click the logout button, it straight away exit the whole application.
void logoutbtn_Click(object sender, EventArgs e)
{
CloseSockets();
this.Close();
serverlogin login = new serverlogin();
login.Show();
}
So, i try to replace this.Hide() instead of this.Close();. But, something even dumb happen. Yes, the login page show after i click the logout button, but when i click the Cancel button at my login form, it didnt exit the whole application where it suppose to exit the whole application. i guess is because the main form is just hiding and not yet close??? Plus, when i try to login again, the login button is also, NOT functioning, cannot login to main page.
i apologize upon my explanation and please tell me if it is very unclear.
Please kindly help me. Thank you so much.
A: You need to define 2 event in your form which will be fired on butttons click and handle it in the main form:
MainForm.cs
void logoutbtn_Click(object sender, EventArgs e)
{
CloseSockets();
this.Hide();
serverlogin login = new serverlogin();
login.Login += new EventHandler(serverlogin_Login);
login.Cancel += new EventHandler(serverlogin_Cancel);
login.Show();
}
private void serverlogin_Login(object sender, EventArgs args)
{
this.Show();
// do login
}
private void serverlogin_Cancel(object sender, EventArgs args)
{
Application.Exit();
// do exit
}
LoginForm.cs
public event EventHandler Login;
public event EventHandler Cancel;
private void OnLogin()
{
if (Login != null)
Login(this, EventArgs.Empty);
}
private void OnCancel()
{
if (Login != null)
Login(this, EventArgs.Empty);
}
private void btnLogin_Click(object sender, EventArgs e)
{
this.OnLogin();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.OnCancel();
}
A: You might just want to start a new instance of your application, then exit the old one, when "logout" is selected. This cleans up any resources still in use, and makes it much more difficult to leak data from one user session to the next.
The disadvantage, of course, is that it will be slower, but there's ngen.exe to reduce the cost of restarting the app.
A: I reviewed the first answer, and I found out that there is something wrong. In the code, he closes the form after creating the new thread. I tested it, but it always closed my form. So I switched the this.Close(); with t.Start(); and it worked. Below you have the explanation of the code.
You create a new thread then you close the form you are in (for exemple the menu), and finally you start your new thread. You create a new method where you run your new form. I commented it line by line.
private void btnLogout_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OpenLoginForm)); //you create a new thread
this.Close(); //you close your current form (for example a menu)
t.Start(); //you start the thread
}
public static void OpenLoginForm()
{
Application.Run(new LoginForm()); //run your new form
}
A: private void btnLogout_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OpenLoginForm));
t.Start();
this.Close();
}
public static void OpenLoginForm()
{
Application.Run(new LoginForm());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Faster Parameter Passing in Delphi/C i have 2 parts application, Delphi and C, and i have 2 questions
1. what is the fastest way to pass parameters to Delphi?
procedure name(Data: string); // Data is Copied to another location before passing so its slow
procedure name(var Data: string); // Data is Passed by pointer, Faster
procedure name(const Data: string); // unknown
*
*i wanna pass parameters by pointers in c, i have a char array and a function, i don't wanna pass the whole array, cut a first part of it and pass the rest
void testfunction(char **Data)
{
printf("Data = %d\n", *Data);
return;
}
int main()
{
char Data[] = "TEST FUNCTION";
testfunction(&&Data[4]); // Error
return 0;
}
thanks
A: Delphi strings reside on the heap and are always passed by pointer. Your first example of pass by value is incorrect. Strings passed by value are not copied. Only the reference is copied. This is possible for strings because they have magic copy-on-write behaviour. A dynamic array passed by value is copied.
Using const when passing a string has the best performance because the compiler can optimise out reference counting code.
Your C code is somewhat confused. You don't want char**, rather you want char*. Remember that a C string, a char*, is just a pointer to a null-terminated block of memory. You don't need to take a pointer to a C string since it is already a pointer.
And you mean %s rather than %d surely. To pass a C string starting at the 5th character write Data+4.
void testfunction(char *Data) {
printf("Data = %s\n", Data);
}
int main() {
char Data[] = "TEST FUNCTION";
testfunction(Data+4);
return 0;
}
A: No one did emphasize on the well-known fact that since Delphi 2009, string = UnicodeString so will be exported as PWideChar / LPCWSTR and not PChar / LPCSTR. Worth noting IMHO, because it may be confusing if it is not clear enough in your mind, and expect your code to work with all version of Delphi.
If you want to modify the string content from C library, you should perhaps use a WideString Delphi type instead of a string. WideString is allocated and handled by Windows (this is the COM / Ole string), so you have all the corresponding C API at hand to handle those OLESTR pointers. And this WideString do not suffer from the Delphi 2009 Unicode break (it has always been Unicode).
Of course, WideString is slower than string (for several reasons, the main one is the much slower heap allocation for WideString - getting better since Vista), but it's IMHO a safe a cross-language way of exporting some TEXT data to and from a Delphi application and library (in the Windows world). For instance, the .Net world will like marshaling those OLESTR kind of variable.
A: The code is a bit misleading I guess. Does it intend to print just " FUNCTION"? If so:
void testfunction(const char *Data)
{
printf("Data = %s\n", Data);
return;
}
int main()
{
char Data[] = "TEST FUNCTION";
testfunction(Data+4);
return 0;
}
That will pass the string to that function from index 4 (including) in the array to the rest of it.
By passing char* you are not copying the string in that function's local stack. Just the pointer to the beginning of that memory.
A: I can only answer the delphi part (my C is a little rusty just now and C pointer/array references make my head hurt when I am current and up to date)
Strings are pointer and are ALWAYS passed by reference, so the data is not copied on passing -EVER.
However, in the case of the
procedure test(s:String);
The pointer S is passed, and if you modify S inside the procedure test, a unique string is generated, and new pointer assigned to S, but not the original passed variable. You can pass string litterals and string expressions/modified on the fly (s+'bla bla bla')
procedure test(var s: String);
the address to the pointer S is passed,
The pointer S is passed, and if you modify S inside the procedure test, a unique string is generated (if required), and new pointer assigned to S, AND the original passed variable. You can NEVER pass string litterals and string expressions/modified on the fly (s+'bla bla bla')
procedure test(const s: string);
The pointer S is passed, and you can not modify S inside the procedure test period. (ok, you can screw around and fool the compiler but it is ugly and hard to do and usually requires a lot of type casting)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Memory exhaustion while running NDSolve I run into the "No more memory available" error message in Mathematica. I understand that "Parallelize[]" isn't (obviously) going to help me. Neither has "ClearSystemCache[]".
What gives? Do I just need more RAM?
My Code
Needs["VectorAnalysis`"]
Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];
Clear[Eq4, EvapThickFilm, h, S, G, E1, K1, D1, VR, M, R]
Eq4[h_, {S_, G_, E1_, K1_, D1_, VR_, M_, R_}] := \!\(
\*SubscriptBox[\(\[PartialD]\), \(t\)]h\) +
Div[-h^3 G Grad[h] +
h^3 S Grad[Laplacian[h]] + (VR E1^2 h^3)/(D1 (h + K1)^3)
Grad[h] + M (h/(1 + h))^2 Grad[h]] + E1/(
h + K1) + (R/6) D[D[(h^2/(1 + h)), x] h^3, x] == 0;
SetCoordinates[Cartesian[x, y, z]];
EvapThickFilm[S_, G_, E1_, K1_, D1_, VR_, M_, R_] :=
Eq4[h[x, y, t], {S, G, E1, K1, D1, VR, M, R}];
TraditionalForm[EvapThickFilm[S, G, E1, K1, D1, VR, M, R]];
L = 318; TMax = 10;
Off[NDSolve::mxsst];
Clear[Kvar];
Kvar[t_] := Piecewise[{{1, t <= 1}, {2, t > 1}}]
(*Ktemp = Array[0.001+0.001#^2&,13]*)
hSol = h /. NDSolve[{
(*S,G,E,K,D,VR,M*)
EvapThickFilm[1, 3, 0.1, 7, 0.01, 0.1, 0, 160],
h[0, y, t] == h[L, y, t],
h[x, 0, t] == h[x, L, t],
(*h[x,y,0] == 1.1+Cos[x] Sin[2y] *)
h[x, y, 0] ==
1 + (-0.25 Cos[2 \[Pi] x/L] - 0.25 Sin[2 \[Pi] x/L]) Cos[
2 \[Pi] y/L]
},
h,
{x, 0, L},
{y, 0, L},
{t, 0, TMax},
MaxStepSize -> 0.1
][[1]]
hGrid = InterpolatingFunctionGrid[hSol];
Error message
No more memory available.
Mathematica kernel has shut down.
Try quitting other applications and then retry.
My OS specs
Intel Core 2 Duo with 4.00 GB ram, 64 bit OS (Windows 7)
A: Here you may get a taste of what is happening:
Replace
MaxStepSize -> 0.1
by
MaxStepFraction -> 1/30
And run your code.
Then:
p = Join[#,Reverse@#]&@
Table[Plot3D[hSol[x, y, i], {x, 0, L}, {y, 0, L},
PlotRange -> {All, All, {0, 4}}],
{i, 7, 8, .1}]
Export["c:\\plot.gif", p]
So, Mma is trying to refine the solution at those peaks, to no avail.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Java timing accuracy on Windows XP vs. Windows 7 I have a bizarre problem - I'm hoping someone can explain to me what is happening and a possible workaround. I am implementing a Z80 core in Java, and attempting to slow it down, by using a java.util.Timer object in a separate thread.
The basic setup is that I have one thread running an execute loop, 50 times per second. Within this execute loop, however many cycles are executed, and then wait() is invoked. The external Timer thread will invoke notifyAll() on the Z80 object every 20ms, simulating a PAL Sega Master System clock frequency of 3.54 MHz (ish).
The method I have described above works perfectly on Windows 7 (tried two machines) but I have also tried two Windows XP machines and on both of them, the Timer object seems to be oversleeping by around 50% or so. This means that one second of emulation time is actually taking around 1.5 seconds or so on a Windows XP machine.
I have tried using Thread.sleep() instead of a Timer object, but this has exactly the same effect. I realise granularity of time in most OSes isn't better than 1ms, but I can put up with 999ms or 1001ms instead of 1000ms. What I can't put up with is 1562ms - I just don't understand why my method works OK on newer version of Windows, but not the older one - I've investigated interrupt periods and so on, but don't seem to have developed a workaround.
Could anyone please tell me the cause of this problem and a suggested workaround? Many thanks.
Update: Here is the full code for a smaller app I built to show the same issue:
import java.util.Timer;
import java.util.TimerTask;
public class WorkThread extends Thread
{
private Timer timerThread;
private WakeUpTask timerTask;
public WorkThread()
{
timerThread = new Timer();
timerTask = new WakeUpTask(this);
}
public void run()
{
timerThread.schedule(timerTask, 0, 20);
while (true)
{
long startTime = System.nanoTime();
for (int i = 0; i < 50; i++)
{
int a = 1 + 1;
goToSleep();
}
long timeTaken = (System.nanoTime() - startTime) / 1000000;
System.out.println("Time taken this loop: " + timeTaken + " milliseconds");
}
}
synchronized public void goToSleep()
{
try
{
wait();
}
catch (InterruptedException e)
{
System.exit(0);
}
}
synchronized public void wakeUp()
{
notifyAll();
}
private class WakeUpTask extends TimerTask
{
private WorkThread w;
public WakeUpTask(WorkThread t)
{
w = t;
}
public void run()
{
w.wakeUp();
}
}
}
All the main class does is create and start one of these worker threads. On Windows 7, this code produces a time of around 999ms - 1000ms, which is totally fine. Running the same jar on Windows XP however produces a time of around 1562ms - 1566ms, and this is on two separate XP machines that I have tested this. They are all running Java 6 update 27.
I find this problem is happening because the Timer is sleeping for 20ms (quite a small value) - if I bung all the execute loops for a single second into wait wait() - notifyAll() cycle, this produces the correct result - I'm sure people who see what I'm trying to do (emulate a Sega Master System at 50fps) will see how this is not a solution though - it won't give an interactive response time, skipping 49 of every 50. As I say, Win7 copes fine with this. Sorry if my code is too large :-(
A:
Could anyone please tell me the cause of this problem and a suggested workaround?
The problem you are seeing probably has to do with clock resolution. Some Operating Systems (Windows XP and earlier) are notorious for oversleeping and being slow with wait/notify/sleep (interrupts in general). Meanwhile other Operating Systems (every Linux I've seen) are excellent at returning control at quite nearly the moment specified.
The workaround? For short durations, use a live wait (busy loop). For long durations, sleep for less time than you really want and then live wait the remainder.
A: I'd forgo the TimerTask and just use a busy loop:
long sleepUntil = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(20);
while (System.nanoTime() < sleepUntil) {
Thread.sleep(2); // catch of InterruptedException left out for brevity
}
The two millisecond delay gives the host OS plenty of time to work on other stuff (and you're likely to be on a multicore anyway). The remaining program code is a lot simpler.
If the hard-coded two milliseconds are too much of a blunt instrument, you can calculate the required sleep time and use the Thread.sleep(long, int) overload.
A: You can set the timer resolution on Windows XP.
http://msdn.microsoft.com/en-us/library/windows/desktop/dd757624%28v=vs.85%29.aspx
Since this is a system-wide setting, you can use a tool to set the resolution so you can verify whether this is your problem.
Try this out and see if it helps: http://www.lucashale.com/timer-resolution/
You might see better timings on newer versions of Windows because, by default, newer version might have tighter timings. Also, if you are running an application such as Windows Media Player, it improves the timer resolution. So if you happen to be listening to some music while running your emulator, you might get great timings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Ignore file with CSS manifest? I was wondering if there was a way to ignore a css file from being added to the manifest application.css file.
The reason why I want to do this is that I have two versions of the site, a mobile version, an an web version. The mobile version's css is currently being added to the manifest, and messing with the style of the main page.
Is there anyway to configure the manifest file to exclude a certain css file?
A: Remove the require_tree directive and add just the files you want, in the order you want them to application.css. Leave out the mobile CSS file.
To access the mobile CSS file you need to add it to the precompile list in
production.rb:
config.assets.precompile += ['mobile.css']
This will allow you to use the standard rails helper to access the mobile css:
<%= stylesheet_link_tag "mobile" %>
as distinct from the application.css file.
One tip for these situations is that you can share CSS files between manifests. For example, if you have a CSS reset in a separate file this can be added to both manifests (assuming you make the mobile css a manifest too).
A: What I ended up doing was creating subdirectories under app/assets/stylesheets called app/assets/stylesheets/web and app/assets/stylesheets/mobile
Then place an application.css with the standard:
/* ...
*= require_self
*= require_tree .
*/
inside each of your new web and mobile folders. Then to access them:
# just use this
<%= stylesheet_link_tag "web/application", :media => "all" %>
# or this as needed
<%= stylesheet_link_tag "mobile/application", :media => "all" %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7558670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.